com.google.common.base.Charsets Java Examples

The following examples show how to use com.google.common.base.Charsets. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: GoPush   Author: PinkHello   File: ZkUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 创建节点
 *
 * @param path
 * @param data
 * @param mode
 * @return
 */
public boolean createNode(String path, String data, CreateMode mode) {
    if (!ObjectUtils.allNotNull(zkClient, path)) {
        return Boolean.FALSE;
    }
    try {
        Stat stat = exists(path);
        if (stat == null) {
            mode = mode == null ? CreateMode.PERSISTENT : mode;
            String opResult;
            if (ObjectUtils.allNotNull(data)) {
                opResult = zkClient.create().creatingParentContainersIfNeeded().withMode(mode).forPath(path, data.getBytes(Charsets.UTF_8));
            } else {
                opResult = zkClient.create().creatingParentContainersIfNeeded().withMode(mode).forPath(path);
            }
            return Objects.equal(opResult, path);
        }
        return Boolean.TRUE;
    } catch (Exception e) {
        log.error("create node fail! path: {}, error: {}", path, e);
    }
    return Boolean.FALSE;
}
 
Example #2
Source Project: hadoop   Author: naver   File: DistributedPentomino.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create the input file with all of the possible combinations of the 
 * given depth.
 * @param fs the filesystem to write into
 * @param dir the directory to write the input file into
 * @param pent the puzzle 
 * @param depth the depth to explore when generating prefixes
 */
private static long createInputDirectory(FileSystem fs, 
                                         Path dir,
                                         Pentomino pent,
                                         int depth
                                         ) throws IOException {
  fs.mkdirs(dir);
  List<int[]> splits = pent.getSplits(depth);
  Path input = new Path(dir, "part1");
  PrintWriter file = 
    new PrintWriter(new OutputStreamWriter(new BufferedOutputStream
                    (fs.create(input), 64*1024), Charsets.UTF_8));
  for(int[] prefix: splits) {
    for(int i=0; i < prefix.length; ++i) {
      if (i != 0) {
        file.print(',');          
      }
      file.print(prefix[i]);
    }
    file.print('\n');
  }
  file.close();
  return fs.getFileStatus(input).getLen();
}
 
Example #3
Source Project: elasticsearch-migration   Author: hubrick   File: YamlParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ChecksumedMigrationFile parse(final String path) {
    checkNotNull(StringUtils.trimToNull(path), "path must be not null");

    try {
        log.info("Checking schema for file " + path);
        checkSchema(path);
        log.info("Parsing file " + path);
        final byte[] yaml = IOUtils.toByteArray(ResourceUtils.getResourceAsStream(path, this));
        final MigrationFile migrationFile = yamlMapper.readValue(new ByteArrayInputStream(yaml), MigrationFile.class);
        final String fileSha256Checksum = HashUtils.hashSha256(new ByteArrayInputStream(yaml));

        final byte[] normalizedYaml = yamlMapper.writeValueAsBytes(migrationFile);
        final String normalizedSha256Checksum = HashUtils.hashSha256(ByteBuffer.wrap(normalizedYaml));

        if(log.isDebugEnabled()) {
            log.debug("Original yaml: \n{}", new String(yaml, Charsets.UTF_8));
            log.debug("Normalized yaml: \n{}", new String(normalizedYaml, Charsets.UTF_8));
        }

        return new ChecksumedMigrationFile(migrationFile, ImmutableSet.of(fileSha256Checksum, normalizedSha256Checksum));
    } catch (IOException e) {
        throw new InvalidSchemaException("Problem parsing yaml file " + path, e);
    }
}
 
Example #4
Source Project: mt-flume   Author: javachen   File: TestBufferedLineReader.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBatchedReadsAtFileBoundary() throws IOException {
  File f1 = new File(tmpDir.getAbsolutePath() + "/file1");
  Files.write("file1line1\nfile1line2\nfile1line3\nfile1line4\n" +
              "file1line5\nfile1line6\nfile1line7\nfile1line8\n",
              f1, Charsets.UTF_8);

  SimpleTextLineEventReader reader = new SimpleTextLineEventReader(new FileReader(f1));

  List<String> out = bodiesAsStrings(reader.readEvents(10));

  // Make sure we got exactly 8 lines
  assertEquals(8, out.size());
  assertTrue(out.contains("file1line1"));
  assertTrue(out.contains("file1line2"));
  assertTrue(out.contains("file1line3"));
  assertTrue(out.contains("file1line4"));
  assertTrue(out.contains("file1line5"));
  assertTrue(out.contains("file1line6"));
  assertTrue(out.contains("file1line7"));
  assertTrue(out.contains("file1line8"));
}
 
Example #5
Source Project: jweb-cms   Author: chifei   File: CombinedResource.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public InputStream openStream() {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    for (String resourcePath : resourcePaths) {
        Optional<Resource> resource = repository.get(resourcePath);
        if (!resource.isPresent()) {
            logger.warn("missing resource file, path={}", resourcePath);
        } else {
            try {
                outputStream.write(resource.get().toByteArray());
                outputStream.write("\n".getBytes(Charsets.UTF_8));
            } catch (IOException e) {
                throw new ResourceException(e);
            }
        }
    }
    return new ByteArrayInputStream(outputStream.toByteArray());
}
 
Example #6
Source Project: The-5zig-Mod   Author: 5zig   File: Configuration.java    License: MIT License 6 votes vote down vote up
private T loadConfig() throws IOException {
	if (!configFile.exists()) {
		return createNewConfig(configClass, configFile);
	}
	String reader = FileUtils.readFileToString(configFile, Charsets.UTF_8);
	GsonBuilder gsonBuilder = new GsonBuilder();
	if (LastServer.class.isAssignableFrom(configClass))
		gsonBuilder.registerTypeAdapter((new TypeToken<List<Server>>() {
		}).getType(), new ServerAdapter());
	try {
		T t = gsonBuilder.create().fromJson(reader, configClass);
		return t == null ? createNewConfig(configClass, configFile) : t;
	} catch (Exception e) {
		The5zigMod.logger.warn("Could not parse JSON at " + configFile.getPath(), e);
		return createNewConfig(configClass, configFile);
	}
}
 
Example #7
Source Project: tac-kbp-eal   Author: BBN-E   File: PerDocResultWriter.java    License: MIT License 6 votes vote down vote up
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());
                    }
                  })));
}
 
Example #8
Source Project: logging-java   Author: spotify   File: LoggingConfigurator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a syslog appender. The appender will use the facility local0. If host is null or an
 * empty string, default to "localhost". If port is less than 0, default to 514.
 *
 * @param context The logger context to use.
 * @param host The host running the syslog daemon.
 * @param port The port to connect to.
 * @return An appender that writes to syslog.
 */
static Appender<ILoggingEvent> getSyslogAppender(final LoggerContext context,
                                                 final String host,
                                                 final int port,
                                                 final ReplaceNewLines replaceNewLines) {
  final String h = isNullOrEmpty(host) ? "localhost" : host;
  final int p = port < 0 ? 514 : port;

  final MillisecondPrecisionSyslogAppender appender = new MillisecondPrecisionSyslogAppender();

  appender.setFacility("LOCAL0");
  appender.setSyslogHost(h);
  appender.setPort(p);
  appender.setName("syslog");
  appender.setCharset(Charsets.UTF_8);
  appender.setContext(context);
  appender.setSuffixPattern(
      "%property{ident}[%property{pid}]: " + ReplaceNewLines.getMsgPattern(replaceNewLines));
  appender.setStackTracePattern(
      "%property{ident}[%property{pid}]: " + CoreConstants.TAB);
  appender.start();

  return appender;
}
 
Example #9
Source Project: incubator-atlas   Author: apache   File: CuratorFactory.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
void enhanceBuilderWithSecurityParameters(HAConfiguration.ZookeeperProperties zookeeperProperties,
                                          CuratorFrameworkFactory.Builder builder) {

    ACLProvider aclProvider = getAclProvider(zookeeperProperties);

    AuthInfo authInfo = null;
    if (zookeeperProperties.hasAuth()) {
        authInfo = AtlasZookeeperSecurityProperties.parseAuth(zookeeperProperties.getAuth());
    }

    if (aclProvider != null) {
        LOG.info("Setting up acl provider.");
        builder.aclProvider(aclProvider);
        if (authInfo != null) {
            byte[] auth = authInfo.getAuth();
            LOG.info("Setting up auth provider with scheme: {} and id: {}", authInfo.getScheme(),
                    getIdForLogging(authInfo.getScheme(), new String(auth, Charsets.UTF_8)));
            builder.authorization(authInfo.getScheme(), auth);
        }
    }
}
 
Example #10
Source Project: spring-boot-quickstart   Author: fireshort   File: Servlets.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 设置让浏览器弹出下载对话框的Header.
 * 
 * @param fileName 下载后的文件名.
 */
public static void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
	// 中文文件名支持
	String encodedfileName = null;
	// 替换空格,否则firefox下有空格文件名会被截断,其他浏览器会将空格替换成+号
	encodedfileName = fileName.trim().replaceAll(" ", "_");
	String agent = request.getHeader("User-Agent");
	boolean isMSIE = (agent != null && agent.toUpperCase().indexOf("MSIE") != -1);
	if (isMSIE) {
		encodedfileName = Encodes.urlEncode(fileName);
	} else {
		encodedfileName = new String(fileName.getBytes(), Charsets.ISO_8859_1);
	}

	response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");

}
 
Example #11
Source Project: grpc-java   Author: grpc   File: AsyncSinkTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void flushCoalescing_shouldMergeWrites() throws IOException {
  byte[] firstData = "a string".getBytes(Charsets.UTF_8);
  byte[] secondData = "a longer string".getBytes(Charsets.UTF_8);
  Buffer buffer = new Buffer();
  sink.becomeConnected(mockedSink, socket);
  sink.write(buffer.write(firstData), buffer.size());
  sink.write(buffer.write(secondData), buffer.size());
  sink.flush();
  queueingExecutor.runAll();

  InOrder inOrder = inOrder(mockedSink);
  inOrder.verify(mockedSink)
      .write(any(Buffer.class), eq((long) firstData.length + secondData.length));
  inOrder.verify(mockedSink).flush();
}
 
Example #12
Source Project: buck   Author: facebook   File: SymlinkFileStepTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAbsoluteSymlinkFiles() throws IOException {
  ExecutionContext context = TestExecutionContext.newInstance();

  File source = tmpDir.newFile();
  Files.write("foobar", source, Charsets.UTF_8);

  File target = tmpDir.newFile();
  target.delete();

  SymlinkFileStep step =
      SymlinkFileStep.of(
          TestProjectFilesystems.createProjectFilesystem(tmpDir.getRoot().toPath()),
          Paths.get(source.getName()),
          Paths.get(target.getName()));
  step.execute(context);
  // Run twice to ensure we can overwrite an existing symlink
  step.execute(context);

  assertTrue(target.exists());
  assertEquals("foobar", Files.readFirstLine(target, Charsets.UTF_8));

  // Modify the original file and see if the linked file changes as well.
  Files.write("new", source, Charsets.UTF_8);
  assertEquals("new", Files.readFirstLine(target, Charsets.UTF_8));
}
 
Example #13
Source Project: ganttproject   Author: bardsoftware   File: GanttTXTOpen.java    License: GNU General Public License v3.0 6 votes vote down vote up
/** Load tasks list from a text file. */
public boolean load(File f) {
  try {
    // Open a stream
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), Charsets.UTF_8));
    for (String taskName = br.readLine(); taskName != null; taskName = br.readLine()) {
      // The test is used to skip the white line (with no text)
      if (!Strings.isNullOrEmpty(taskName)) {
        // Create the task
        myTaskManager.newTaskBuilder().withName(taskName).build();
      }
    }
  } catch (Exception e) {
    e.printStackTrace();
    return false;
  }
  return true;
}
 
Example #14
Source Project: hadoop   Author: naver   File: JobQueueClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Method used to display information pertaining to a Single JobQueue
 * registered with the {@link QueueManager}. Display of the Jobs is determine
 * by the boolean
 * 
 * @throws IOException, InterruptedException
 */
private void displayQueueInfo(String queue, boolean showJobs)
    throws IOException, InterruptedException {
  JobQueueInfo jobQueueInfo = jc.getQueueInfo(queue);
  
  if (jobQueueInfo == null) {
    System.out.println("Queue \"" + queue + "\" does not exist.");
    return;
  }
  printJobQueueInfo(jobQueueInfo, new PrintWriter(new OutputStreamWriter(
      System.out, Charsets.UTF_8)));
  if (showJobs && (jobQueueInfo.getChildren() == null ||
      jobQueueInfo.getChildren().size() == 0)) {
    JobStatus[] jobs = jobQueueInfo.getJobStatuses();
    if (jobs == null)
      jobs = new JobStatus[0];
    jc.displayJobList(jobs);
  }
}
 
Example #15
Source Project: flink   Author: flink-tpc-ds   File: Configuration.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get a {@link Reader} attached to the configuration resource with the
 * given <code>name</code>.
 *
 * @param name configuration resource name.
 * @return a reader attached to the resource.
 */
public Reader getConfResourceAsReader(String name) {
	try {
		URL url= getResource(name);

		if (url == null) {
			LOG.info(name + " not found");
			return null;
		} else {
			LOG.info("found resource " + name + " at " + url);
		}

		return new InputStreamReader(url.openStream(), Charsets.UTF_8);
	} catch (Exception e) {
		return null;
	}
}
 
Example #16
Source Project: karamel   Author: karamelchef   File: KaramelApiTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testBaremetal() throws KaramelException, IOException, InterruptedException {
    String ymlString = Resources.toString(Resources.getResource("se/kth/karamel/client/model/test-definitions/hopsworks_compact_baremetal.yml"), Charsets.UTF_8);
    String json = api.yamlToJson(ymlString);
//    String json
//        = "{\"name\":\"flink\",\"cookbooks\":[{\"name\":\"hadoop\",\"github\":\"hopshadoop/apache-hadoop-chef\",\"branch\":\"master\",\"attributes\":{},\"recipes\":[]},{\"name\":\"flink\",\"github\":\"hopshadoop/flink-chef\",\"branch\":\"master\",\"attributes\":{},\"recipes\":[]}],\"groups\":[{\"name\":\"namenodes\",\"provider\":\"\",\"attrs\":[],\"instances\":1,\"baremetal\":{\"ips\":[\"192.168.33.11\"]},\"cookbooks\":[{\"name\":\"hadoop\",\"github\":\"hopshadoop/apache-hadoop-chef\",\"branch\":\"master\",\"attributes\":{},\"recipes\":[{\"title\":\"hadoop::nn\"}]},{\"name\":\"flink\",\"github\":\"hopshadoop/flink-chef\",\"branch\":\"master\",\"attributes\":{},\"recipes\":[{\"title\":\"flink::wordcount\"},{\"title\":\"flink::jobmanager\"}]}]},{\"name\":\"datanodes\",\"provider\":\"\",\"attrs\":[],\"instances\":2,\"baremetal\":{\"ips\":[\"192.168.33.12\",\"192.168.33.13\"]},\"cookbooks\":[{\"name\":\"hadoop\",\"github\":\"hopshadoop/apache-hadoop-chef\",\"branch\":\"master\",\"attributes\":{},\"recipes\":[{\"title\":\"hadoop::dn\"}]},{\"name\":\"flink\",\"github\":\"hopshadoop/flink-chef\",\"branch\":\"master\",\"attributes\":{},\"recipes\":[{\"title\":\"flink::taskmanager\"}]}]}],\"ec2\":null,\"baremetal\":{\"mapKey\":\"baremetal\",\"username\":\"vagrant\",\"ips\":[]},\"sshKeyPair\":{\"mapKey\":\"ssh\",\"pubKey\":null,\"priKey\":null,\"pubKeyPath\":null,\"privKeyPath\":null,\"passphrase\":null,\"isValid\":true}}\n"
//        + "";
    SshKeyPair keyPair = new SshKeyPair();
    keyPair.setPrivateKeyPath("/Users/kamal/.vagrant.d/insecure_private_key");
    keyPair.setPublicKeyPath("/Users/kamal/.vagrant.d/id_rsa.pub");
    SshKeyPair sshKeys = api.registerSshKeys(keyPair);
    api.registerSshKeys(sshKeys);
//    Ec2Credentials credentials = api.loadEc2CredentialsIfExist();
//    api.updateEc2CredentialsIfValid(credentials);
    api.startCluster(json);
    long ms1 = System.currentTimeMillis();
    int mins = 0;
    while (ms1 + 24 * 60 * 60 * 1000 > System.currentTimeMillis()) {
      mins++;
      System.out.println(api.processCommand("status").getResult());
      Thread.currentThread().sleep(10000);
    }
  }
 
Example #17
Source Project: coming   Author: SpoonLabs   File: Closure_18_Compiler_s.java    License: MIT License 6 votes vote down vote up
/** Load a library as a resource */
@VisibleForTesting
Node loadLibraryCode(String resourceName) {
  String originalCode;
  try {
    originalCode = CharStreams.toString(new InputStreamReader(
        Compiler.class.getResourceAsStream(
            String.format("js/%s.js", resourceName)),
        Charsets.UTF_8));
  } catch (IOException e) {
    throw new RuntimeException(e);
  }

  return Normalize.parseAndNormalizeSyntheticCode(
      this, originalCode,
      String.format("jscomp_%s_", resourceName));
}
 
Example #18
@Before
public void setUp() throws IOException {
  DefaultFileSystem fileSystem = new DefaultFileSystem(tempFolder.getRoot());
  fileSystem.setEncoding(Charsets.UTF_8);
  file = tempFolder.newFile();
  inputFile = new DefaultInputFile("moduleKey", file.getName())
    .setLanguage("css")
    .setType(InputFile.Type.MAIN);
  fileSystem.add(inputFile);

  sensorContext = SensorContextTester.create(tempFolder.getRoot());
  sensorContext.setFileSystem(fileSystem);

  visitorContext = mock(TreeVisitorContext.class);
  highlighterVisitor = new CssSyntaxHighlighterVisitor(sensorContext);
  when(visitorContext.getFile()).thenReturn(file);
}
 
Example #19
Source Project: Despector   Author: Despector   File: MessageUnpacker.java    License: MIT License 6 votes vote down vote up
/**
 * Reads a string value from the input.
 */
public String readString() throws IOException {
    expectType(MessageType.STRING);
    int next = this.stream.readUnsignedByte();
    int len = -1;
    if ((next & SHORTSTRING_TYPE_MASK) == TYPE_STR5_MASK) {
        len = next & SHORTSTRING_MASK;
    } else if (next == TYPE_STR8) {
        len = this.stream.readUnsignedByte();
    } else if (next == TYPE_STR16) {
        len = this.stream.readUnsignedShort();
    } else if (next == TYPE_STR32) {
        len = this.stream.readInt();
    }
    byte[] data = new byte[len];
    this.stream.read(data);
    return new String(data, Charsets.UTF_8);
}
 
Example #20
Source Project: The-5zig-Mod   Author: 5zig   File: ILoveRadioManager.java    License: MIT License 6 votes vote down vote up
private String resolveCover(final String path) throws ExecutionException {
	return TRACK_IMAGE_LOOKUP.get(path, new Callable<String>() {
		@Override
		public String call() throws Exception {
			URL url = new URL(path);
			BufferedImage image = ImageIO.read(url);
			BufferedImage image1 = new BufferedImage(60, 60, image.getType());
			Graphics graphics = image1.getGraphics();
			try {
				graphics.drawImage(image, 0, 0, image1.getWidth(), image1.getHeight(), null);
			} finally {
				graphics.dispose();
			}
			// Converting Image byte array into Base64 String
			ByteBuf localByteBuf1 = Unpooled.buffer();
			ImageIO.write(image1, "PNG", new ByteBufOutputStream(localByteBuf1));
			ByteBuf localByteBuf2 = Base64.encode(localByteBuf1);
			return localByteBuf2.toString(Charsets.UTF_8);
		}
	});
}
 
Example #21
Source Project: Cleanstone   Author: CleanstoneMC   File: SimpleSessionServerRequester.java    License: MIT License 6 votes vote down vote up
@Async(value = "mcLoginExec")
public ListenableFuture<SessionServerResponse> request(Connection connection, LoginData loginData,
                                                       PublicKey publicKey) {
    try {
        String authHash = LoginCrypto.generateAuthHash(connection.getSharedSecret(), publicKey);
        URL url = new URL(SESSION_SERVER_URL
                + String.format("?username=%s&serverId=%s&ip=%s", loginData.getPlayerName(), authHash,
                URLEncoder.encode(connection.getAddress().getHostAddress(), "UTF-8")));
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "application/json");
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);
        try (Reader reader = new InputStreamReader(con.getInputStream(), Charsets.UTF_8)) {
            Gson gson = new Gson();
            return new AsyncResult<>(gson.fromJson(reader, SessionServerResponse.class));
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to contact session servers", e);
    }
}
 
Example #22
Source Project: coming   Author: SpoonLabs   File: Closure_18_Compiler_t.java    License: MIT License 6 votes vote down vote up
/** Load a library as a resource */
@VisibleForTesting
Node loadLibraryCode(String resourceName) {
  String originalCode;
  try {
    originalCode = CharStreams.toString(new InputStreamReader(
        Compiler.class.getResourceAsStream(
            String.format("js/%s.js", resourceName)),
        Charsets.UTF_8));
  } catch (IOException e) {
    throw new RuntimeException(e);
  }

  return Normalize.parseAndNormalizeSyntheticCode(
      this, originalCode,
      String.format("jscomp_%s_", resourceName));
}
 
Example #23
Source Project: buck   Author: facebook   File: ShellStepTest.java    License: Apache License 2.0 6 votes vote down vote up
private static ExecutionContext createContext(
    ImmutableMap<ProcessExecutorParams, FakeProcess> processes, Console console) {
  ExecutionContext context =
      TestExecutionContext.newBuilder()
          .setConsole(console)
          .setProcessExecutor(new FakeProcessExecutor(processes, console))
          .build();

  context
      .getBuckEventBus()
      .register(
          new Object() {
            @Subscribe
            public void logEvent(ConsoleEvent event) throws IOException {
              if (event.getLevel().equals(Level.WARNING)) {
                console.getStdErr().write(event.getMessage().getBytes(Charsets.UTF_8));
              }
            }
          });

  return context;
}
 
Example #24
Source Project: ipmi4j   Author: shevek   File: AsfRAKPMessage1Data.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void toWireData(ByteBuffer buffer) {
    buffer.putInt(getClientSessionId());
    buffer.put(getConsoleRandom());
    buffer.put(getConsoleUserRole().getCode());
    buffer.putShort((short) 0); // Reserved, 0

    String userName = getConsoleUserName();
    if (userName != null) {
        byte[] userNameBytes = userName.getBytes(Charsets.US_ASCII);
        buffer.put(UnsignedBytes.checkedCast(userNameBytes.length));
        buffer.put(Arrays.copyOf(userNameBytes, 16));   // XXX Wrong: It should be variable?
    } else {
        buffer.put(new byte[17]);
    }
}
 
Example #25
Source Project: big-c   Author: yncxcw   File: Util.java    License: Apache License 2.0 5 votes vote down vote up
/** Create a writer of a local file. */
public static PrintWriter createWriter(File dir, String prefix) throws IOException {
  checkDirectory(dir);
  
  SimpleDateFormat dateFormat = new SimpleDateFormat("-yyyyMMdd-HHmmssSSS");
  for(;;) {
    final File f = new File(dir,
        prefix + dateFormat.format(new Date(System.currentTimeMillis())) + ".txt");
    if (!f.exists())
      return new PrintWriter(new OutputStreamWriter(new FileOutputStream(f), Charsets.UTF_8));

    try {Thread.sleep(10);} catch (InterruptedException e) {}
  }
}
 
Example #26
Source Project: org.hl7.fhir.core   Author: hapifhir   File: ValidationTestSuite.java    License: Apache License 2.0 5 votes vote down vote up
public Resource loadResource(String filename, String contents) throws IOException, FHIRFormatError, FileNotFoundException, FHIRException, DefinitionException {
  try (InputStream inputStream = IOUtils.toInputStream(contents, Charsets.UTF_8)) {
    if (filename.contains(".json")) {
      if (Constants.VERSION.equals(version) || "5.0".equals(version))
        return new JsonParser().parse(inputStream);
      else if (org.hl7.fhir.dstu3.model.Constants.VERSION.equals(version) || "3.0".equals(version))
        return VersionConvertor_30_50.convertResource(new org.hl7.fhir.dstu3.formats.JsonParser().parse(inputStream), false);
      else if (org.hl7.fhir.dstu2016may.model.Constants.VERSION.equals(version) || "1.4".equals(version))
        return VersionConvertor_14_50.convertResource(new org.hl7.fhir.dstu2016may.formats.JsonParser().parse(inputStream));
      else if (org.hl7.fhir.dstu2.model.Constants.VERSION.equals(version) || "1.0".equals(version))
        return VersionConvertor_10_50.convertResource(new org.hl7.fhir.dstu2.formats.JsonParser().parse(inputStream));
      else if (org.hl7.fhir.r4.model.Constants.VERSION.equals(version) || "4.0".equals(version))
        return VersionConvertor_40_50.convertResource(new org.hl7.fhir.r4.formats.JsonParser().parse(inputStream));
      else
        throw new FHIRException("unknown version " + version);
    } else {
      if (Constants.VERSION.equals(version) || "5.0".equals(version))
        return new XmlParser().parse(inputStream);
      else if (org.hl7.fhir.dstu3.model.Constants.VERSION.equals(version) || "3.0".equals(version))
        return VersionConvertor_30_50.convertResource(new org.hl7.fhir.dstu3.formats.XmlParser().parse(inputStream), false);
      else if (org.hl7.fhir.dstu2016may.model.Constants.VERSION.equals(version) || "1.4".equals(version))
        return VersionConvertor_14_50.convertResource(new org.hl7.fhir.dstu2016may.formats.XmlParser().parse(inputStream));
      else if (org.hl7.fhir.dstu2.model.Constants.VERSION.equals(version) || "1.0".equals(version))
        return VersionConvertor_10_50.convertResource(new org.hl7.fhir.dstu2.formats.XmlParser().parse(inputStream));
      else if (org.hl7.fhir.r4.model.Constants.VERSION.equals(version) || "4.0".equals(version))
        return VersionConvertor_40_50.convertResource(new org.hl7.fhir.r4.formats.XmlParser().parse(inputStream));
      else
        throw new FHIRException("unknown version " + version);
    }
  }
}
 
Example #27
Source Project: qconfig   Author: qunarcorp   File: DefaultPropertiesLoader.java    License: MIT License 5 votes vote down vote up
private DefaultPropertiesLoader() {
    String defaultPropertiesName = "default.conf";

    URL fileUrl = Thread.currentThread().getContextClassLoader().getResource(defaultPropertiesName);
    if (fileUrl == null) return;
    try (InputStream inputStream = fileUrl.openStream();
         InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charsets.UTF_8)) {
        propertiesMap.load(inputStreamReader);
    } catch (Throwable e) {
        logger.error("init default properties failed", e);
    }
}
 
Example #28
Source Project: tutorials   Author: eugenp   File: JavaReaderToXUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException {
    String initialString = "With Commons IO";
    final Reader initialReader = new StringReader(initialString);
    final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8);

    String finalString = IOUtils.toString(targetStream, Charsets.UTF_8);
    assertThat(finalString, equalTo(initialString));

    initialReader.close();
    targetStream.close();
}
 
Example #29
Source Project: kafkameter   Author: BrightTag   File: LoadGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private static @Nullable String readFile(String filename) {
  try {
    return Files.toString(new File(filename), Charsets.UTF_8);
  } catch (IOException e) {
    log.warn("Unable to retrieve config from " + filename, e);
    return null;
  }
}
 
Example #30
Source Project: kite   Author: kite-sdk   File: TestInputFormatImportCommandCluster.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void readFields(DataInput in) throws IOException {
  int length = in.readInt();
  byte[] nameBytes = new byte[length];
  in.readFully(nameBytes);
  this.name = Charsets.UTF_8.decode(ByteBuffer.wrap(nameBytes)).toString();
  this.value = in.readDouble();
}