Java Code Examples for com.google.common.base.Charsets

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project airlift, under directory /dbpool/src/test/java/io/airlift/dbpool/.

Source file: H2EmbeddedDataSourceTest.java

  19 
vote

@Test public void testInitFromFile() throws Exception {
  File initScript=File.createTempFile("initscript",".ddl");
  Connection connection=null;
  Statement statement=null;
  ResultSet resultSet=null;
  try {
    URL url=Resources.getResource("io/airlift/dbpool/h2.ddl");
    Files.copy(Resources.newReaderSupplier(url,Charsets.UTF_8),initScript,Charsets.UTF_8);
    H2EmbeddedDataSourceConfig config=new H2EmbeddedDataSourceConfig().setFilename(file.getAbsolutePath()).setInitScript(initScript.getAbsolutePath()).setCipher(Cipher.AES).setFilePassword("filePassword");
    H2EmbeddedDataSource dataSource=new H2EmbeddedDataSource(config);
    connection=dataSource.getConnection();
    statement=connection.createStatement();
    resultSet=statement.executeQuery("select * from message");
  }
  finally {
    initScript.delete();
    closeQuietly(resultSet);
    closeQuietly(statement);
    closeQuietly(connection);
  }
}
 

Example 2

From project android_packages_apps_Tag, under directory /src/com/android/apps/tag/provider/.

Source file: TagProvider.java

  19 
vote

@Override public String getType(Uri uri){
  int match=MATCHER.match(uri);
switch (match) {
case NDEF_MESSAGES_ID:
{
      return NdefMessages.CONTENT_ITEM_TYPE;
    }
case NDEF_MESSAGES:
{
    return NdefMessages.CONTENT_TYPE;
  }
case NDEF_MESSAGES_ID_MIME:
{
  NdefRecord record=getRecord(uri);
  if (record != null) {
    return new String(record.getType(),Charsets.US_ASCII).toLowerCase();
  }
  return null;
}
default :
{
throw new IllegalArgumentException("unknown uri " + uri);
}
}
}
 

Example 3

From project annotare2, under directory /app/magetab/src/main/java/uk/ac/ebi/fg/annotare2/magetab/base/.

Source file: TsvParser.java

  19 
vote

public Table parse(InputStream in) throws IOException {
  init();
  BufferedReader br=null;
  try {
    br=new BufferedReader(new InputStreamReader(in,Charsets.UTF_8));
    String line;
    while ((line=br.readLine()) != null) {
      processLine(line);
    }
  }
  finally {
    closeQuietly(br);
  }
  if (!stats.isReadable()) {
    throw new IOException("The file content doesn't look like a text");
  }
  return table;
}
 

Example 4

From project Arecibo, under directory /dashboard/src/main/java/com/ning/arecibo/dashboard/config/.

Source file: LegendConfigurationsManager.java

  19 
vote

@Inject public LegendConfigurationsManager(final DashboardConfig config) throws Exception {
  if (config.getLegendGroupsFile() != null) {
    final File legendGroupsFile=new File(config.getLegendGroupsFile());
    final LegendConfiguration legendConfiguration=mapper.readValue(legendGroupsFile,new TypeReference<LegendConfiguration>(){
    }
);
    this.legendConfiguration.putAll(legendConfiguration);
  }
  if (config.getLegendFixturesFile() != null) {
    final File legendFixturesFile=new File(config.getLegendFixturesFile());
    legendFixtures=Joiner.on("\n").join(Files.readLines(legendFixturesFile,Charsets.UTF_8));
  }
 else {
    legendFixtures="";
  }
}
 

Example 5

From project artifactory-plugin, under directory /src/main/java/org/jfrog/hudson/gradle/.

Source file: GradleInitScriptWriter.java

  19 
vote

/** 
 * Generate the init script from the Artifactory URL.
 * @return The generated script.
 */
public String generateInitScript() throws URISyntaxException, IOException, InterruptedException {
  StringBuilder initScript=new StringBuilder();
  InputStream templateStream=getClass().getResourceAsStream("/initscripttemplate.gradle");
  String templateAsString=IOUtils.toString(templateStream,Charsets.UTF_8.name());
  File localGradleExtractorJar=Which.jarFile(getClass().getResource("/initscripttemplate.gradle"));
  FilePath dependencyDir=PluginDependencyHelper.getActualDependencyDirectory(build,localGradleExtractorJar);
  String absoluteDependencyDirPath=dependencyDir.getRemote();
  absoluteDependencyDirPath=absoluteDependencyDirPath.replace("\\","/");
  String str=templateAsString.replace("${pluginLibDir}",absoluteDependencyDirPath);
  initScript.append(str);
  return initScript.toString();
}
 

Example 6

From project artimate, under directory /artimate-core/src/main/java/fr/loria/parole/artimate/data/io/.

Source file: XWavesSegmentation.java

  19 
vote

public void load(String fileName) throws Exception {
  URL url=getClass().getResource("/" + fileName);
  List<String> lines=Resources.readLines(url,Charsets.UTF_8);
  boolean header=true;
  float lastEndTime=0;
  Matcher matcher=LINE_PATTERN.matcher();
  int index=0;
  for (  String line : lines) {
    if (line.trim().equals("#")) {
      header=false;
      continue;
    }
    if (header) {
      continue;
    }
    if (!matcher.matches(line)) {
      throw new Exception("Could not parse line: " + line);
    }
    String label=matcher.group("label");
    String end=matcher.group("end");
    float endTime=0;
    try {
      endTime=Float.parseFloat(end);
    }
 catch (    NumberFormatException e) {
      throw new Exception("File not well-formed, could not parse end time: " + end);
    }
    if (endTime < lastEndTime) {
      throw new Exception("Unit end times are not in ascending order!");
    }
    Unit segment=new Unit(lastEndTime,endTime,label);
    segment.setIndex(index++);
    units.add(segment);
    lastEndTime=endTime;
  }
  logger.info("Loaded Xwaves lab file " + fileName);
}
 

Example 7

From project atlas, under directory /src/test/java/com/ning/atlas/config/.

Source file: TestConfiguration.java

  19 
vote

@Test public void testAtlasOverridesRecorded() throws Exception {
  Files.write("name=Brian",atlas,Charsets.UTF_8);
  Files.write("name=Eric",recorded,Charsets.UTF_8);
  AtlasConfiguration config=new AtlasConfiguration(atlas,recorded);
  assertThat(config.lookup("name"),equalTo(Optional.of("Brian")));
}
 

Example 8

From project b1-pack, under directory /standard/src/main/java/org/b1/pack/standard/common/.

Source file: Volumes.java

  19 
vote

public static String encodeBase64(byte[] buffer){
  try {
    return new String(Base64.encode(buffer),Charsets.US_ASCII.name());
  }
 catch (  UnsupportedEncodingException e) {
    throw new RuntimeException(e);
  }
}
 

Example 9

From project build-info, under directory /build-info-extractor/src/main/java/org/jfrog/build/extractor/.

Source file: BuildInfoExtractorUtils.java

  19 
vote

public static void saveBuildInfoToFile(Build build,File toFile) throws IOException {
  String buildInfoJson=buildInfoToJsonString(build);
  if (!toFile.getParentFile().exists()) {
    toFile.getParentFile().mkdirs();
  }
  if (!toFile.exists()) {
    toFile.createNewFile();
  }
  Files.write(buildInfoJson,toFile,Charsets.UTF_8);
}
 

Example 10

From project cascading-avro, under directory /cascading-avro-maven-plugin/src/test/java/com/maxpoint/cascading/avro/.

Source file: CascadingFieldsGeneratorTest.java

  19 
vote

@Test public void testGenerate() throws Exception {
  final CascadingFieldsGenerator gen=new CascadingFieldsGenerator();
  final Schema schema=getSchema();
  final Writer writer=new StringWriter();
  gen.generate(schema,writer);
  writer.close();
  final String actual=writer.toString();
  final String expected=Resources.toString(getClass().getResource("expected.txt"),Charsets.UTF_8);
  assertEquals(expected,actual);
}
 

Example 11

From project closure-templates, under directory /java/src/com/google/template/soy/jssrc/internal/.

Source file: JsSrcMain.java

  19 
vote

/** 
 * Generates JS source files given a Soy parse tree, an options object, an optional bundle of translated messages, and information on where to put the output files.
 * @param soyTree The Soy parse tree to generate JS source code for.
 * @param jsSrcOptions The compilation options relevant to this backend.
 * @param locale The current locale that we're generating JS for, or null if not applicable.
 * @param msgBundle The bundle of translated messages, or null to use the messages from the Soysource.
 * @param outputPathFormat The format string defining how to build the output file pathcorresponding to an input file path.
 * @param inputPathsPrefix The input path prefix, or empty string if none.
 * @throws SoySyntaxException If a syntax error is found.
 * @throws IOException If there is an error in opening/writing an output JS file.
 */
public void genJsFiles(SoyFileSetNode soyTree,SoyJsSrcOptions jsSrcOptions,@Nullable String locale,@Nullable SoyMsgBundle msgBundle,String outputPathFormat,String inputPathsPrefix) throws SoySyntaxException, IOException {
  List<String> jsFileContents=genJsSrc(soyTree,jsSrcOptions,msgBundle);
  int numFiles=soyTree.numChildren();
  if (numFiles != jsFileContents.size()) {
    throw new AssertionError();
  }
  Multimap<String,Integer> outputs=Multimaps.newListMultimap(Maps.<String,Collection<Integer>>newLinkedHashMap(),new Supplier<List<Integer>>(){
    @Override public List<Integer> get(){
      return Lists.newArrayList();
    }
  }
);
  for (int i=0; i < numFiles; ++i) {
    SoyFileNode inputFile=soyTree.getChild(i);
    String inputFilePath=inputFile.getFilePath();
    String outputFilePath=JsSrcUtils.buildFilePath(outputPathFormat,locale,inputFilePath,inputPathsPrefix);
    BaseUtils.ensureDirsExistInPath(outputFilePath);
    outputs.put(outputFilePath,i);
  }
  for (  String outputFilePath : outputs.keySet()) {
    Writer out=Files.newWriter(new File(outputFilePath),Charsets.UTF_8);
    try {
      boolean isFirst=true;
      for (      int inputFileIndex : outputs.get(outputFilePath)) {
        if (isFirst) {
          isFirst=false;
        }
 else {
          out.write("\n;\n");
        }
        out.write(jsFileContents.get(inputFileIndex));
      }
    }
  finally {
      out.close();
    }
  }
}
 

Example 12

From project Cloud9, under directory /src/dist/edu/umd/cloud9/collection/clue/.

Source file: ClueWarcDocnoMappingBuilder.java

  19 
vote

/** 
 * Runs this tool.
 */
public int run(String[] args) throws IOException {
  DocnoMapping.DefaultBuilderOptions options=DocnoMapping.BuilderUtils.parseDefaultOptions(args);
  if (options == null) {
    return -1;
  }
  LOG.info("Tool name: " + ClueWarcDocnoMappingBuilder.class.getCanonicalName());
  LOG.info(" - input path: " + options.collection);
  LOG.info(" - output file: " + options.docnoMapping);
  FileSystem fs=FileSystem.get(getConf());
  FSDataOutputStream out=fs.create(new Path(options.docnoMapping),true);
  final InputStream in=ClueWarcDocnoMapping.class.getResourceAsStream("docno.mapping");
  List<String> lines=CharStreams.readLines(CharStreams.newReaderSupplier(new InputSupplier<InputStream>(){
    @Override public InputStream getInput() throws IOException {
      return in;
    }
  }
,Charsets.UTF_8));
  out.write((Joiner.on("\n").join(lines) + "\n").getBytes());
  out.close();
  return 0;
}
 

Example 13

From project clustermeister, under directory /api/src/main/java/com/github/nethad/clustermeister/api/impl/.

Source file: KeyPairCredentials.java

  19 
vote

/** 
 * Creates Credentials with private key, public key and user name.
 * @param name A name for these credentials.
 * @param user  The user name.
 * @param privateKeySource A source for the private key. This source is read when  {@link #getPrivateKey()} is called. The source is expected to be encoded in UTF-8. This can be changed with  {@link #setKeySourceCharset(java.nio.charset.Charset)}. The private key must not have a pass phrase.
 * @param publicKeySource (optional) A source for the public key. This source is read when  {@link #getPublicKey()} is called. The source is expected to be encoded in UTF-8. This can be changed with  {@link #setKeySourceCharset(java.nio.charset.Charset)}.
 */
protected KeyPairCredentials(String name,String user,File privateKeySource,Optional<File> publicKeySource){
  super(name,user);
  this.privatekeySource=privateKeySource;
  this.publicKeySource=publicKeySource;
  this.charset=Charsets.UTF_8;
}
 

Example 14

From project commons-j, under directory /src/main/java/nerds/antelax/commons/net/pubsub/.

Source file: ApplicationMessage.java

  19 
vote

ApplicationMessage(final ChannelBuffer body,final String topic){
  super(Type.Application);
  Preconditions.checkNotNull(body,"Message body cannot be null");
  Preconditions.checkNotNull(topic,"Topic cannot be null");
  this.topic=topic;
  final byte[] topicBytes=topic.getBytes(Charsets.UTF_8);
  this.body=ChannelBuffers.buffer(4 + topicBytes.length + body.readableBytes());
  this.body.writeInt(topicBytes.length);
  this.body.writeBytes(topicBytes);
  this.body.writeBytes(body);
}
 

Example 15

From project community-plugins, under directory /deployit-udm-plugins/middleware-plugins/apache-weblogic-plugin/src/test/java/ext/deployit/community/plugin/apacheweblogic/.

Source file: ApacheWeblogicTest.java

  19 
vote

@Test public void testTest() throws Exception {
  Deployable apacheWlsSettingSpec=newInstance("www.ApacheWeblogicSettingSpec");
  apacheWlsSettingSpec.setId("App/1.0/wlsApache");
  final Set<String> matchExpressions=Sets.newHashSet("*.jsp"," *.do");
  apacheWlsSettingSpec.setProperty("matchExpressions",matchExpressions);
  final File docroot=folder.newFolder("docroot");
  final File configurationFragmentDirectory=folder.newFolder("conf");
  apacheWebServer.setProperty("configurationFragmentDirectory",configurationFragmentDirectory.getAbsolutePath());
  final Deployed deployed=tester.generateDeployed(apacheWlsSettingSpec,apacheWebServer,Type.valueOf("www.ApacheWeblogicSetting"));
  deployed.setProperty("port","80");
  deployed.setProperty("host","myremote.com");
  deployed.setProperty("targets",this.servers);
  deployed.setProperty("documentRoot",docroot.getAbsolutePath());
  final DeploymentPackage deploymentPackageOne=TestUtils.createDeploymentPackage("1.0",apacheWlsSettingSpec);
  final DeployedApplication deployedApplication=TestUtils.createDeployedApplication(deploymentPackageOne,environment);
  DeltaSpecification spec=new DeltaSpecificationBuilder().initial(deployedApplication).create(deployed).build();
  Plan resolvedPlan=tester.resolvePlan(spec);
  List<DeploymentStep> resolvedSteps=resolvedPlan.getSteps();
  assertThat(resolvedSteps.size(),is(3));
  Step.Result result=tester.executePlan(resolvedPlan,context);
  assertThat(result,is(Step.Result.Success));
  final List<String> generatedFile=readLines(new File(configurationFragmentDirectory,deployed.getName() + ".conf"),Charsets.UTF_8);
  assertThat(filter(generatedFile,new Predicate<String>(){
    public boolean apply(    String input){
      return input.contains(generatedServers);
    }
  }
).size(),is(1));
  assertThat(filter(generatedFile,new Predicate<String>(){
    public boolean apply(    String input){
      return input.contains("MatchExpression");
    }
  }
).size(),is(matchExpressions.size()));
}
 

Example 16

From project components-ness-hbase, under directory /src/main/java/com/nesscomputing/hbase/.

Source file: HBaseEncoder.java

  19 
vote

/** 
 * Encode  {@link String} as <code>byte[]</code>.  Just uses UTF8 encoding. 
 */
public static byte[] bytesForString(String string){
  if (string == null) {
    return new byte[0];
  }
  return string.getBytes(Charsets.UTF_8);
}
 

Example 17

From project components-ness-httpclient, under directory /client/src/main/java/com/nesscomputing/httpclient/response/.

Source file: HttpResponse.java

  19 
vote

/** 
 * @return the body interpreted as a string. If a charset was returned in the http response, it will be used. Ifnot, the body will be interpreted as UTF-8.
 * @throws UnsupportedEncodingException if the encoding is unsupported
 */
@Nonnull public String getBodyAsString() throws UnsupportedEncodingException {
  if (charset == null) {
    return new String(body,Charsets.UTF_8);
  }
  return new String(body,charset);
}
 

Example 18

From project components-ness-httpserver_1, under directory /src/main/java/com/nesscomputing/httpserver/log/file/.

Source file: FileRequestLog.java

  19 
vote

@Override public void doStart(){
  if (requestLogFile.exists() && !requestLogFile.isFile()) {
    LOG.warn("Log file \"%s\" exists, but is not a file!",requestLogFile.getAbsolutePath());
    return;
  }
  final File logPath=requestLogFile.getParentFile();
  if (!logPath.mkdirs() && !logPath.exists()) {
    LOG.warn("Cannot create \"%s\" and path does not already exist!",logPath.getAbsolutePath());
  }
  LOG.info("Opening request log at \"%s\"",requestLogFile.getAbsolutePath());
  try {
    setWriter(new PrintWriter(new OutputStreamWriter(new FileOutputStream(requestLogFile,true),Charsets.UTF_8),true));
  }
 catch (  FileNotFoundException e) {
    LOG.error(e,"Could not open request log \"%s\"",requestLogFile.getAbsolutePath());
  }
}
 

Example 19

From project cp-openrdf-utils, under directory /test/src/com/clarkparsia/openrdf/.

Source file: TestGraphs.java

  19 
vote

@Test public void testOf() throws Exception {
  Graph aInput=TestUtils.createRandomGraph(20);
  File aFile=File.createTempFile("foo",".ttl");
  try {
    Files.write(OpenRdfIO.toString(aInput,RDFFormat.TURTLE),aFile,Charsets.UTF_8);
    assertTrue(ModelUtil.equals(aInput,Graphs.of(aFile)));
  }
  finally {
    if (!aFile.delete()) {
      aFile.deleteOnExit();
    }
  }
}
 

Example 20

From project crunch, under directory /crunch/src/test/java/org/apache/crunch/impl/mem/.

Source file: MemPipelineFileWritingTest.java

  19 
vote

@Test public void testMemPipelineFileWriter() throws Exception {
  File tmpDir=Files.createTempDir();
  tmpDir.delete();
  Pipeline p=MemPipeline.getInstance();
  PCollection<String> lines=MemPipeline.collectionOf("hello","world");
  p.writeTextFile(lines,tmpDir.getAbsolutePath());
  p.done();
  assertTrue(tmpDir.exists());
  File[] files=tmpDir.listFiles();
  assertTrue(files != null && files.length > 0);
  for (  File f : files) {
    if (!f.getName().startsWith(".")) {
      List<String> txt=Files.readLines(f,Charsets.UTF_8);
      assertEquals(ImmutableList.of("hello","world"),txt);
    }
  }
}
 

Example 21

From project Empire, under directory /jena/src/com/clarkparsia/empire/jena/.

Source file: DefaultJenaDataSourceFactory.java

  19 
vote

/** 
 * Return the unknown object as a Reader.  Supported conversions are provided for  {@link Reader},  {@link InputStream}, {@link java.io.File},  {@link java.net.URI}, and  {@link java.net.URL}.
 * @param theObj the object try to create as a Reader
 * @return the object as a Reader
 * @throws DataSourceException if there is an error while opening the Reader or it cannot be turned into a Reader
 */
private Reader asReader(Object theObj) throws DataSourceException {
  try {
    if (theObj instanceof Reader) {
      return (Reader)theObj;
    }
 else     if (theObj instanceof InputStream) {
      return new InputStreamReader((InputStream)theObj,Charsets.UTF_8);
    }
 else     if (theObj instanceof File) {
      return new InputStreamReader(new FileInputStream((File)theObj),Charsets.UTF_8);
    }
 else     if (theObj instanceof URI) {
      return new InputStreamReader(((URI)theObj).toURL().openStream(),Charsets.UTF_8);
    }
 else     if (theObj instanceof URL) {
      return new InputStreamReader(((URL)theObj).openStream(),Charsets.UTF_8);
    }
 else {
      throw new DataSourceException("Cannot read from the specified stream objects, it is not a Reader or an InputStream: " + theObj);
    }
  }
 catch (  IOException e) {
    throw new DataSourceException("There was an error opening the reader/inputstream",e);
  }
}
 

Example 22

From project event-collector, under directory /event-combiner/src/main/java/com/proofpoint/event/combiner/.

Source file: S3CombineObjectMetadataStore.java

  19 
vote

private boolean writeMetadataFile(EventPartition eventPartition,CombinedGroup combinedGroup,String sizeName){
  byte[] json=jsonCodec.toJson(combinedGroup).getBytes(Charsets.UTF_8);
  URI metadataFile=toMetadataLocation(eventPartition,sizeName);
  try {
    ObjectMetadata metadata=new ObjectMetadata();
    metadata.setContentLength(json.length);
    metadata.setContentMD5(Base64.encodeBase64String(DigestUtils.md5(json)));
    metadata.setContentType(MediaType.APPLICATION_JSON);
    InputStream input=new ByteArrayInputStream(json);
    s3Service.putObject(getS3Bucket(metadataFile),getS3ObjectKey(metadataFile),input,metadata);
    return true;
  }
 catch (  AmazonClientException e) {
    log.warn(e,"error writing metadata file: %s",metadataFile);
    return false;
  }
}
 

Example 23

From project fasthat, under directory /src/com/sun/tools/hat/internal/lang/jruby/.

Source file: JRubyString.java

  19 
vote

private static String getRubyStringValue(JavaObject obj){
  JavaObject value=Models.getFieldObject(obj,"value");
  if (value != null) {
    JavaValueArray bytes=Models.safeCast(value.getField("bytes"),JavaValueArray.class);
    JavaInt begin=Models.safeCast(value.getField("begin"),JavaInt.class);
    JavaInt realSize=Models.safeCast(value.getField("realSize"),JavaInt.class);
    if (bytes != null && begin != null && realSize != null) {
      return new String((byte[])bytes.getElements(),begin.value,realSize.value,Charsets.UTF_8);
    }
  }
  return null;
}
 

Example 24

From project flume, under directory /flume-ng-channels/flume-file-channel/src/main/java/org/apache/flume/channel/file/encryption/.

Source file: JCEFileKeyProvider.java

  19 
vote

public JCEFileKeyProvider(File keyStoreFile,File keyStorePasswordFile,Map<String,File> aliasPasswordFileMap){
  super();
  this.aliasPasswordFileMap=aliasPasswordFileMap;
  this.keyStorePasswordFile=keyStorePasswordFile;
  try {
    ks=KeyStore.getInstance("jceks");
    keyStorePassword=Files.toString(keyStorePasswordFile,Charsets.UTF_8).trim().toCharArray();
    ks.load(new FileInputStream(keyStoreFile),keyStorePassword);
  }
 catch (  Exception ex) {
    throw Throwables.propagate(ex);
  }
}
 

Example 25

From project FML, under directory /common/cpw/mods/fml/common/asm/transformers/.

Source file: MarkerTransformer.java

  19 
vote

private void readMapFile(String rulesFile) throws IOException {
  File file=new File(rulesFile);
  URL rulesResource;
  if (file.exists()) {
    rulesResource=file.toURI().toURL();
  }
 else {
    rulesResource=Resources.getResource(rulesFile);
  }
  Resources.readLines(rulesResource,Charsets.UTF_8,new LineProcessor<Void>(){
    @Override public Void getResult(){
      return null;
    }
    @Override public boolean processLine(    String input) throws IOException {
      String line=Iterables.getFirst(Splitter.on('#').limit(2).split(input),"").trim();
      if (line.length() == 0) {
        return true;
      }
      List<String> parts=Lists.newArrayList(Splitter.on(" ").trimResults().split(line));
      if (parts.size() != 2) {
        throw new RuntimeException("Invalid config file line " + input);
      }
      List<String> markerInterfaces=Lists.newArrayList(Splitter.on(",").trimResults().split(parts.get(1)));
      for (      String marker : markerInterfaces) {
        markers.put(parts.get(0),marker);
      }
      return true;
    }
  }
);
}
 

Example 26

From project galaxy, under directory /src/co/paralleluniverse/galaxy/core/.

Source file: AbstractCluster.java

  19 
vote

public void writeToTree(){
  assertDuringInitialization();
  if (attached)   throw new IllegalStateException("Node is attached to tree -> cannot be written!");
  if (name == null || nodeId < 0)   throw new AssertionError("Incomplete node data");
  LOG.info("Publishing node info: name = {}, id = {}",name,nodeId);
  controlTree.create(treeNodePath,true);
  controlTree.create(treeNodePath + '/' + "id",true);
  controlTree.set(treeNodePath + '/' + "id",Short.toString(nodeId).getBytes(Charsets.UTF_8));
  for (  Map.Entry<String,Object> property : properties.entrySet()) {
    LOG.info("Publishing node info: {} = {}",property.getKey(),property.getValue());
    controlTree.create(treeNodePath + '/' + property.getKey(),true);
    controlTree.set(treeNodePath + '/' + property.getKey(),writeProperty(property.getKey(),property.getValue()));
  }
  controlTree.flush();
}
 

Example 27

From project Game_3, under directory /java/src/playn/java/.

Source file: JavaAssets.java

  19 
vote

@Override protected void doGetText(final String path,final ResourceCallback<String> callback){
  doResourceAction(new Runnable(){
    public void run(){
      try {
        callback.done(Resources.toString(requireResource(pathPrefix + path),Charsets.UTF_8));
      }
 catch (      Exception e) {
        callback.error(e);
      }
    }
  }
);
}
 

Example 28

From project giraph, under directory /src/main/java/org/apache/giraph/graph/.

Source file: TextAggregatorWriter.java

  19 
vote

@Override public void writeAggregator(Iterable<Entry<String,Writable>> aggregatorMap,long superstep) throws IOException {
  if (shouldWrite(superstep)) {
    for (    Entry<String,Writable> entry : aggregatorMap) {
      byte[] bytes=aggregatorToString(entry.getKey(),entry.getValue(),superstep).getBytes(Charsets.UTF_8);
      output.write(bytes,0,bytes.length);
    }
    output.flush();
  }
}
 

Example 29

From project hackergarten-moreunit, under directory /org.moreunit.test.dependencies/src/org/moreunit/test/workspace/.

Source file: Source.java

  19 
vote

private String loadSource(Class<?> loadingClass,String sourceLocation){
  try {
    URL definitionUrl=loadingClass.getResource(sourceLocation.trim());
    if (definitionUrl == null) {
      throw new RuntimeException(String.format("Resource not found: '%s'",sourceLocation));
    }
    return Resources.toString(definitionUrl,Charsets.UTF_8);
  }
 catch (  IOException e) {
    throw new RuntimeException(String.format("Could not load class definition '%s'",sourceLocation),e);
  }
}
 

Example 30

From project hdfs-nfs-proxy, under directory /src/main/java/com/cloudera/hadoop/hdfs/nfs/nfs4/state/.

Source file: HDFSState.java

  19 
vote

/** 
 * Return a FileHandle if it exists or create a new one.
 * @param path
 * @return a FileHandle
 * @throws IOException
 */
public synchronized FileHandle createFileHandle(Path path) throws IOException {
  String realPath=realPath(path);
  HDFSFile file=mPathMap.get(realPath);
  if (file != null) {
    return file.getFileHandle();
  }
  String s=UUID.randomUUID().toString().replace("-","");
  byte[] bytes=s.getBytes(Charsets.UTF_8);
  FileHandle fileHandle=new FileHandle(bytes);
  HDFSFile holder=new HDFSFile(fileHandle,realPath,getNextFileID());
  FileHandleStoreEntry storeEntry=new FileHandleStoreEntry(bytes,realPath,holder.getFileID());
  mFileHandleStore.storeFileHandle(storeEntry);
  putFileHandle(fileHandle,realPath,holder);
  return fileHandle;
}
 

Example 31

From project heritrix3, under directory /commons/src/main/java/org/apache/commons/httpclient/util/.

Source file: EncodingUtil.java

  19 
vote

/** 
 * Converts the specified string to byte array of ASCII characters.
 * @param data the string to be encoded
 * @return The string as a byte array.
 * @since 3.0
 */
public static byte[] getAsciiBytes(final String data){
  if (data == null) {
    throw new IllegalArgumentException("Parameter may not be null");
  }
  return data.getBytes(Charsets.US_ASCII);
}
 

Example 32

From project httpcache4j, under directory /httpcache4j-api/src/test/java/org/codehaus/httpcache4j/auth/mac/.

Source file: RequestMACTest.java

  19 
vote

@Test public void verifyMACTokenInExampleWithBodyExtensionMD5() throws Exception {
  URI uri=URI.create("http://example.com/request?b5=%3D%253D&a3=a&c%40=&a2=r%20b&c2&a3=2+q");
  DateTimeUtils.setCurrentMillisFixed(264095 * 1000L);
  Nonce n=new Nonce("7d8f3e4a");
  String ext=String.format("bodyhash=\"%s\"",Base64.encodeBytes(Hashing.md5().hashString("Hello World!",Charsets.UTF_8).asBytes()));
  RequestMAC mac=new RequestMAC("2134gfdg",n,ext);
  String calculated=mac.getMac(new HTTPRequest(uri,HTTPMethod.POST),Algorithm.HMAC_SHA_1);
  assertEquals("emuqa52lvjl2WWKD0nSDv/rgniA=",calculated);
  DateTimeUtils.setCurrentMillisSystem();
}
 

Example 33

From project incubator-s4, under directory /test-apps/twitter-counter/src/main/java/org/apache/s4/example/twitter/.

Source file: TopNTopicPE.java

  19 
vote

public void onTime(){
  TreeSet<TopNEntry> sortedTopics=Sets.newTreeSet();
  for (  Map.Entry<String,Integer> topicCount : countedTopics.entrySet()) {
    sortedTopics.add(new TopNEntry(topicCount.getKey(),topicCount.getValue()));
  }
  File f=new File("TopNTopics.txt");
  StringBuilder sb=new StringBuilder();
  int i=0;
  Iterator<TopNEntry> iterator=sortedTopics.iterator();
  sb.append("----\n" + new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss").format(new Date()) + "\n");
  while (iterator.hasNext() && i < 10) {
    TopNEntry entry=iterator.next();
    sb.append("topic [" + entry.topic + "] count ["+ entry.count+ "]\n");
    i++;
  }
  sb.append("\n");
  try {
    Files.append(sb.toString(),f,Charsets.UTF_8);
    logger.info("Wrote top 10 topics to file [{}] ",f.getAbsolutePath());
  }
 catch (  IOException e) {
    logger.error("Cannot write top 10 topics to file [{}]",f.getAbsolutePath(),e);
  }
}
 

Example 34

From project jackrabbit-oak, under directory /oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/.

Source file: PropertyIndex.java

  19 
vote

static List<String> encode(PropertyValue value){
  List<String> values=new ArrayList<String>();
  for (  String v : value.getValue(Type.STRINGS)) {
    try {
      if (v.length() > MAX_STRING_LENGTH) {
        v=v.substring(0,MAX_STRING_LENGTH);
      }
      values.add(URLEncoder.encode(v,Charsets.UTF_8.name()));
    }
 catch (    UnsupportedEncodingException e) {
      throw new IllegalStateException("UTF-8 is unsupported",e);
    }
  }
  return values;
}
 

Example 35

From project janbanery, under directory /janbanery-android/src/main/java/pl/project13/janbanery/android/rest/.

Source file: AndroidCompatibleRestClient.java

  19 
vote

private void setFormUrlEncodedBody(HttpEntityEnclosingRequestBase request,String requestBody){
  BasicHttpEntity entity=new BasicHttpEntity();
  try {
    byte[] contentBytes=requestBody.getBytes(Charsets.UTF_8.name());
    ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(contentBytes);
    System.out.println(">>>>>>>" + Strings.toString(byteArrayInputStream));
    entity.setContent(new ByteArrayInputStream(contentBytes));
    entity.setContentLength(contentBytes.length);
    entity.setContentEncoding(Charsets.UTF_8.name());
    entity.setChunked(false);
  }
 catch (  UnsupportedEncodingException e) {
    throw new RuntimeException("Unable to set request body.",e);
  }
  request.setEntity(entity);
}
 

Example 36

From project jclouds-chef, under directory /core/src/test/java/org/jclouds/chef/functions/.

Source file: GroupToBootScriptTest.java

  19 
vote

public void testOneRecipe() throws IOException {
  GroupToBootScript fn=new GroupToBootScript(Suppliers.ofInstance(URI.create("http://localhost:4000")),json,ImmutableMap.<String,List<String>>of("foo",ImmutableList.<String>of("recipe[apache2]")),installChefGems,validatorName,validatorCredential);
  PrivateKey validatorKey=validatorCredential.get();
  expect(validatorKey.getEncoded()).andReturn(PemsTest.PRIVATE_KEY.getBytes());
  replay(validatorKey);
  assertEquals(fn.apply("foo").render(OsFamily.UNIX),CharStreams.toString(Resources.newReaderSupplier(Resources.getResource("one-recipe.sh"),Charsets.UTF_8)));
  verify(validatorKey);
}
 

Example 37

From project kitten, under directory /java/client/src/test/java/com/cloudera/kitten/.

Source file: TestKittenDistributedShell.java

  19 
vote

@Test public void testKittenShell() throws Exception {
  String config="/lua/distshell.lua";
  File tmpFile=File.createTempFile("distshell",".txt");
  tmpFile.deleteOnExit();
  KittenClient client=new KittenClient(ImmutableMap.<String,Object>of("TEST_FILE",tmpFile.getAbsolutePath(),"PWD",(new File(".")).getAbsolutePath()));
  conf.set(LocalDataHelper.APP_BASE_DIR,"file:///tmp/");
  client.setConf(conf);
  assertEquals(0,client.run(new String[]{config,"distshell"}));
  assertEquals(12,Files.readLines(tmpFile,Charsets.UTF_8).size());
}
 

Example 38

From project knn, under directory /src/main/java/org/apache/mahout/knn/generate/.

Source file: IndianBuffet.java

  19 
vote

public WordConverter(){
  try {
    words=Resources.readLines(Resources.getResource("words.txt"),Charsets.UTF_8,new LineProcessor<List<String>>(){
      final List<String> words=Lists.newArrayList();
      public boolean processLine(      String line) throws IOException {
        Iterables.addAll(words,onSpace.split(line));
        return true;
      }
      public List<String> getResult(){
        return words;
      }
    }
);
  }
 catch (  IOException e) {
    throw new ImpossibleException(e);
  }
}
 

Example 39

From project koshinuke.java, under directory /src/java/org/koshinuke/jersey/auth/.

Source file: BasicAuthFilterFactory.java

  19 
vote

@Override public ContainerRequest filter(ContainerRequest request){
  try {
    String authorization=request.getRequestHeaders().getFirst(HttpHeaders.AUTHORIZATION);
    if (authorization != null) {
      int space=authorization.indexOf(' ');
      if (0 < space) {
        String type=authorization.substring(0,space);
        if ("Basic".equalsIgnoreCase(type)) {
          String cred=authorization.substring(space + 1);
          cred=new String(Base64.decode(cred.getBytes(Charsets.ISO_8859_1)),Charsets.ISO_8859_1);
          int i=cred.indexOf(':');
          if (0 < i) {
            String u=cred.substring(0,i);
            String p=cred.substring(i + 1);
            HttpServletRequest req=BasicAuthFilterFactory.this.requestInvoker.get();
            req.login(u,p);
            AuthenticationFilterFactory.setUserPrincipal(req);
            return request;
          }
        }
      }
    }
  }
 catch (  IOException|ServletException e) {
    throw new WebApplicationException(e,this.make401());
  }
  throw new WebApplicationException(this.make401());
}