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 File: MessageUnpacker.java    From Despector with 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 #2
Source File: JavaReaderToXUnitTest.java    From tutorials with MIT License 6 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 #3
Source File: YamlParser.java    From elasticsearch-migration with 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 File: TestBufferedLineReader.java    From mt-flume with 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 File: ZkUtils.java    From GoPush with 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 #6
Source File: DistributedPentomino.java    From hadoop with 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 #7
Source File: Configuration.java    From The-5zig-Mod with 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 #8
Source File: CombinedResource.java    From jweb-cms with 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 #9
Source File: ShellStepTest.java    From buck with 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 #10
Source File: PerDocResultWriter.java    From tac-kbp-eal with 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 #11
Source File: LoggingConfigurator.java    From logging-java with 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 #12
Source File: CuratorFactory.java    From incubator-atlas with 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 #13
Source File: Servlets.java    From spring-boot-quickstart with 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 #14
Source File: SymlinkFileStepTest.java    From buck with 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 #15
Source File: GanttTXTOpen.java    From ganttproject with 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 #16
Source File: JobQueueClient.java    From hadoop with 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 #17
Source File: Configuration.java    From flink with 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 #18
Source File: AsyncSinkTest.java    From grpc-java with 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 #19
Source File: Closure_18_Compiler_t.java    From coming with 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 #20
Source File: KaramelApiTest.java    From karamel with 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 #21
Source File: Closure_18_Compiler_s.java    From coming with 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 #22
Source File: SimpleSessionServerRequester.java    From Cleanstone with 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 #23
Source File: CssSyntaxHighlighterVisitorTest.java    From sonar-css-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #24
Source File: ILoveRadioManager.java    From The-5zig-Mod with 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 #25
Source File: AsfRAKPMessage1Data.java    From ipmi4j with 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 #26
Source File: GenericOAuth2ApiBinding.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public U getUserInfo(String accessToken, String openId) {
	Map<String, String> parameters = createParameters();

	hasText(config.getAppId(), "'appId' is empty, please check the configure");
	parameters.put(DEFAULT_PARAM_CLIENT_ID, config.getAppId());

	hasText(accessToken, "'accessToken' is empty, please check the configure");
	parameters.put(DEFAULT_PARAM_ACCESS_TOKEN, accessToken);

	hasText(openId, "'openId' is empty, please check the configure");
	parameters.put(DEFAULT_PARAM_OPEN_ID, openId);

	// Post process
	postGetUserInfoUrl(parameters);

	String url = parametersToUrl(getUserInfoUriEndpoint(), parameters);
	log.info("Get userInfo url: '{}'", url);

	// Send request
	ResponseEntity<String> resp = restTemplate.getForEntity(url.toString(), String.class);
	if (nonNull(resp) && resp.getStatusCode() == HttpStatus.OK) {
		String body = resp.getBody();
		hasText(body, "OAuth2 response userinfo empty");
		body = new String(body.getBytes(Charsets.ISO_8859_1), Charsets.UTF_8);
		log.info("OAuth2 response userInfo: {}", body);

		return ((Oauth2UserProfile) newResponseMessage(3)).build(body).validate();
	}

	throw new SnsApiBindingException(format("Failed to receiving OAuth2 userinfo of - %s", resp));
}
 
Example #27
Source File: StringFunctionHelpers.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private static int nfeI(int start, int end, ArrowBuf buffer, FunctionErrorContext errCtx){
  byte[] buf = new byte[end - start];
  buffer.getBytes(start, buf, 0, end - start);
  String value = new String(buf, com.google.common.base.Charsets.UTF_8);
  throw errCtx.error()
    .message("Failure while attempting to cast value '%s' to Integer.", value)
    .build();
}
 
Example #28
Source File: DefaultPropertiesLoader.java    From qconfig with 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 #29
Source File: TestInputFormatImportCommandCluster.java    From kite with 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();
}
 
Example #30
Source File: ReportingWebDriverEventListener.java    From dropwizard-experiment with MIT License 5 votes vote down vote up
private static void saveLogs(String filename, WebDriver driver) {
    StringBuffer logs = new StringBuffer();
    for (LogEntry entry : driver.manage().logs().get(LogType.BROWSER)) {
        logs.append(Instant.ofEpochMilli(entry.getTimestamp()))
                .append(": ")
                .append(entry.getMessage())
                .append("\n");
    }
    try {
        Files.write(logs, new File(filename + ".txt"), Charsets.UTF_8);
    } catch (IOException e) {
        log.error("Unable to save logs from test failure.", e);
    }
}