com.google.common.io.CharStreams#toString ( )源码实例Demo

下面列出了com.google.common.io.CharStreams#toString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: nomulus   文件: MetricParameters.java
private String readGceMetadata(String path) {
  String value = "";
  HttpURLConnection connection = connectionFactory.apply(path);
  try {
    connection.connect();
    int responseCode = connection.getResponseCode();
    if (responseCode < 200 || responseCode > 299) {
      logger.atWarning().log(
          "Got an error response: %d\n%s",
          responseCode,
          CharStreams.toString(new InputStreamReader(connection.getErrorStream(), UTF_8)));
    } else {
      value = CharStreams.toString(new InputStreamReader(connection.getInputStream(), UTF_8));
    }
  } catch (IOException e) {
    logger.atWarning().withCause(e).log("Cannot obtain GCE metadata from path %s", path);
  }
  return value;
}
 
源代码2 项目: apiman-cli   文件: ApiDefinitionCommand.java
@Override
public void performFinalAction(JCommander parser) throws CommandException {
    if (!definitionStdIn && null == definitionFile) {
        throw new ExitWithCodeException(1, "API definition must be provided", true);
    }

    // read definition from STDIN or file
    String definition;
    try (InputStream is = (definitionStdIn ? System.in : Files.newInputStream(definitionFile))) {
        definition = CharStreams.toString(new InputStreamReader(is));

    } catch (IOException e) {
        throw new CommandException(e);
    }

    LOGGER.debug("Adding definition to API '{}' with contents: {}", this::getModelName, () -> definition);

    ManagementApiUtil.invokeAndCheckResponse(() ->
            getManagerConfig().buildServerApiClient(VersionAgnosticApi.class, serverVersion).setDefinition(orgName, name, version, definitionType, new TypedString(definition)));
}
 
源代码3 项目: xtext-core   文件: ResourceStorageLoadable.java
protected void readNodeModel(StorageAwareResource resource, InputStream inputStream) throws IOException {
	SerializableNodeModel serializableNodeModel = new SerializableNodeModel(resource);
	// if this is a synthetic resource (i.e. tests or so, don't load the node model)
	if (!resource.getResourceSet().getURIConverter().exists(resource.getURI(),
			resource.getResourceSet().getLoadOptions())) {
		LOG.info("Skipping loading node model for synthetic resource " + resource.getURI());
		return;
	}
	String completeContent = CharStreams.toString(
			new InputStreamReader(resource.getResourceSet().getURIConverter().createInputStream(resource.getURI()),
					resource.getEncoding()));
	DeserializationConversionContext deserializationContext = new DeserializationConversionContext(resource,
			completeContent);
	serializableNodeModel.readObjectData(new DataInputStream(inputStream), deserializationContext);
	resource.setParseResult(new ParseResult(head(resource.getContents()), serializableNodeModel.root,
			deserializationContext.hasErrors()));
}
 
源代码4 项目: kurento-java   文件: KmsService.java
private int countKmsProcesses() {
  int result = 0;
  try {
    // This command counts number of process (given its PID, stored in
    // kms-pid file)

    if (isKmsRemote) {
      String kmsPid = remoteKmsSshConnection.execAndWaitCommandNoBr("cat",
          remoteKmsSshConnection.getTmpFolder() + "/kms-pid");
      result = Integer.parseInt(remoteKmsSshConnection
          .execAndWaitCommandNoBr("ps --pid " + kmsPid + " --no-headers | wc -l"));
    } else {
      String[] command = { "sh", "-c",
          "ps --pid `cat " + workspace + File.separator + "kms-pid` --no-headers | wc -l" };
      Process countKms = Runtime.getRuntime().exec(command);
      String stringFromStream =
          CharStreams.toString(new InputStreamReader(countKms.getInputStream(), "UTF-8"));
      result = Integer.parseInt(stringFromStream.trim());
    }
  } catch (IOException e) {
    log.warn("Exception counting KMS processes", e);
  }

  return result;
}
 
源代码5 项目: helios   文件: HostInfoReporter.java
private String exec(final String command) {
  try {
    final Process process = Runtime.getRuntime().exec(command);
    return CharStreams.toString(new InputStreamReader(process.getInputStream(), UTF_8));
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
源代码6 项目: xtext-extras   文件: EMFGeneratorFragment.java
void updateBuildProperties(XpandExecutionContext ctx) throws Exception {
	if (!updateBuildProperties || modelPluginID != null)
		return;
	Outlet rootOutlet = ctx.getOutput().getOutlet(org.eclipse.xtext.generator.Generator.PLUGIN_RT);
	Outlet modelOutlet = ctx.getOutput().getOutlet(org.eclipse.xtext.generator.Generator.MODEL);
	String buildPropertiesPath = rootOutlet.getPath() + "/build.properties";
	String modelPath = modelOutlet.getPath().substring(rootOutlet.getPath().length() + 1) + "/";
	Properties buildProperties = new Properties();
	Reader reader = new InputStreamReader(new FileInputStream(new File(buildPropertiesPath)), Charset.forName(rootOutlet.getFileEncoding()));
	try {
		String existingContent = CharStreams.toString(reader);
		// for encoding details, see Properties.load
		buildProperties.load(new StringInputStream(existingContent, "ISO-8859-1"));
		String binIncludes = buildProperties.getProperty("bin.includes");
		boolean changed = false;
		if (binIncludes == null) {
			existingContent += "bin.includes = " + modelPath + Strings.newLine()+ "               ";
			changed = true;
		} else if (!binIncludes.contains(modelPath)) {
			existingContent = existingContent.replace("bin.includes = ", "bin.includes = " + modelPath + ",\\" + Strings.newLine() +"               ");
			changed = true;
		}
		if (changed) {
			Writer writer = new OutputStreamWriter(new FileOutputStream(new File(buildPropertiesPath)), Charset.forName(rootOutlet.getFileEncoding()));
			writer.write(existingContent);
			writer.close();
		}
	} finally {
		reader.close();
	}
}
 
源代码7 项目: fenixedu-academic   文件: AlumniCerimonyDA.java
public ActionForward addPeople(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final CerimonyInquiry cerimonyInquiry = getDomainObject(request, "cerimonyInquiryId");
    final UsernameFileBean usernameFileBean = getRenderedObject();
    final String contents =
            CharStreams.toString(new InputStreamReader(usernameFileBean.getInputStream(), Charset.defaultCharset()));
    final Set<String> usernames = findUsernames(contents);
    cerimonyInquiry.addPeople(usernames);
    return forwardToInquiry(mapping, request, "viewAlumniCerimonyInquiry", cerimonyInquiry);
}
 
private String readStreamToString(final InputStream in) throws IOException {
  try {
    return CharStreams.toString(new InputStreamReader(in, UTF_8));
  }
  finally {
    in.close();
  }
}
 
源代码9 项目: nomulus   文件: RequestModule.java
@Provides
@Payload
static String providePayloadAsString(HttpServletRequest req) {
  try {
    return CharStreams.toString(req.getReader());
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
源代码10 项目: ipst   文件: DynamicDatabaseMockUtils.java
private void copyDtaFile(String templateName, Path destFile, Map<String, String> mapping) throws IOException {
    try (final Reader reader = new InputStreamReader(getClass().getResourceAsStream(templateName))) {
        String dtaContents = CharStreams.toString(reader);
        dtaContents = mapping.keySet().stream()
                .reduce(dtaContents, (str, key) -> str.replaceAll(key, mapping.get(key)));
        try (BufferedWriter writer = Files.newBufferedWriter(destFile)) {
            writer.write(dtaContents);
        }
    }
}
 
源代码11 项目: FastAsyncWorldedit   文件: CommandScriptLoader.java
public CommandScriptLoader() throws IOException {
    this.engine = new NashornCraftScriptEngine();

    try (InputStream inputStream = Fawe.class.getResourceAsStream("/cs_adv.js")) {
        this.loader = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
    }
}
 
源代码12 项目: StatsAgg   文件: InfluxdbV1_Write.java
protected void processPostRequest(HttpServletRequest request, HttpServletResponse response) {
    
    if ((request == null) || (response == null)) {
        return;
    }
    
    long metricsReceivedTimestampInMilliseconds = System.currentTimeMillis();
    
    PrintWriter out = null;
    
    try {
        response.setContentType("text/json"); 
        
        String username = request.getParameter("u");
        String password = request.getParameter("p");
        String timePrecision = request.getParameter("time_precision");
        String httpAuth = request.getHeader("Authorization");

        String json = CharStreams.toString(request.getReader());
        
        String requestUri = request.getRequestURI();
        String database = (requestUri == null) ? null : StringUtils.substringBetween(requestUri, "/db/", "/series");

        parseMetrics(database, json, username, password, httpAuth, timePrecision, GlobalVariables.influxdbPrefix, metricsReceivedTimestampInMilliseconds);

        out = response.getWriter();
    }
    catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
    }
    finally {            
        if (out != null) {
            out.close();
        }
    }
}
 
源代码13 项目: app-maven-plugin   文件: UrlUtils.java
/** If the response code is 200, returns the content at the URL. Otherwise, returns null. */
public static String getUrlContent(String url) {
  try {
    HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
    int responseCode = urlConnection.getResponseCode();
    if (responseCode == 200) {
      return CharStreams.toString(new InputStreamReader(urlConnection.getInputStream()));
    }
  } catch (IOException e) {
  }
  return null;
}
 
源代码14 项目: envelope   文件: SQLDeriver.java
private String sqlFileAsString(String sqlFile) throws Exception {
  String contents;

  FileSystem fs = FileSystem.get(new URI(sqlFile), new Configuration());
  InputStream stream = fs.open(new Path(sqlFile));
  InputStreamReader reader = new InputStreamReader(stream, Charsets.UTF_8);
  contents = CharStreams.toString(reader);
  reader.close();
  stream.close();

  return contents;
}
 
源代码15 项目: google-cloud-eclipse   文件: ValidationUtils.java
static String convertStreamToString(InputStream stream, String charset) throws IOException {
  String result = CharStreams.toString(new InputStreamReader(stream, charset));
  return result;
}
 
源代码16 项目: che   文件: KeycloakServiceClient.java
private String doRequest(String url, String method, List<Pair<String, ?>> parameters)
    throws IOException, ServerException, ForbiddenException, NotFoundException,
        UnauthorizedException, BadRequestException {
  final String authToken = EnvironmentContext.getCurrent().getSubject().getToken();
  final boolean hasQueryParams = parameters != null && !parameters.isEmpty();
  if (hasQueryParams) {
    final UriBuilder ub = UriBuilder.fromUri(url);
    for (Pair<String, ?> parameter : parameters) {
      ub.queryParam(parameter.first, parameter.second);
    }
    url = ub.build().toString();
  }
  final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
  conn.setConnectTimeout(60000);
  conn.setReadTimeout(60000);

  try {
    conn.setRequestMethod(method);
    // drop a hint for server side that we want to receive application/json
    conn.addRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
    if (authToken != null) {
      conn.setRequestProperty(HttpHeaders.AUTHORIZATION, "bearer " + authToken);
    }
    final int responseCode = conn.getResponseCode();
    if ((responseCode / 100) != 2) {
      InputStream in = conn.getErrorStream();
      if (in == null) {
        in = conn.getInputStream();
      }
      final String str;
      try (Reader reader = new InputStreamReader(in)) {
        str = CharStreams.toString(reader);
      }
      final String contentType = conn.getContentType();
      if (contentType != null
          && (contentType.startsWith(MediaType.APPLICATION_JSON)
              || contentType.startsWith("application/vnd.api+json"))) {
        final KeycloakErrorResponse serviceError =
            DtoFactory.getInstance().createDtoFromJson(str, KeycloakErrorResponse.class);
        if (responseCode == Response.Status.FORBIDDEN.getStatusCode()) {
          throw new ForbiddenException(serviceError.getErrorMessage());
        } else if (responseCode == Response.Status.NOT_FOUND.getStatusCode()) {
          throw new NotFoundException(serviceError.getErrorMessage());
        } else if (responseCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
          throw new UnauthorizedException(serviceError.getErrorMessage());
        } else if (responseCode == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
          throw new ServerException(serviceError.getErrorMessage());
        } else if (responseCode == Response.Status.BAD_REQUEST.getStatusCode()) {
          throw new BadRequestException(serviceError.getErrorMessage());
        }
        throw new ServerException(serviceError.getErrorMessage());
      }
      // Can't parse content as json or content has format other we expect for error.
      throw new IOException(
          String.format(
              "Failed access: %s, method: %s, response code: %d, message: %s",
              UriBuilder.fromUri(url).replaceQuery("token").build(), method, responseCode, str));
    }
    try (Reader reader = new InputStreamReader(conn.getInputStream())) {
      return CharStreams.toString(reader);
    }
  } finally {
    conn.disconnect();
  }
}
 
@Override
public void execute() throws MojoExecutionException {

  if ("pom".equals(project.getPackaging())) {
    getLog().info("Project packaging is POM, skipping...");
    return;
  }

  if (skip) {
    getLog().info("Skipping source reformatting due to plugin configuration.");
    return;
  }

  try {
    Set<File> sourceFiles = new HashSet<>();

    if (formatMain) {
      sourceFiles.addAll(findFilesToReformat(sourceDirectory, outputDirectory));
    }
    if (formatTest) {
      sourceFiles.addAll(findFilesToReformat(testSourceDirectory, testOutputDirectory));
    }

    Set<File> sourceFilesToProcess = filterModified ? filterUnchangedFiles(sourceFiles) : sourceFiles;

    JavaFormatterOptions options = getJavaFormatterOptions();

    for (File file : sourceFilesToProcess) {
      String source = CharStreams.toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));

      Formatter formatter = new Formatter(options);
      String formattedSource = fixImports ? formatter.formatSourceAndFixImports(source) : formatter.formatSource(source);

      HashCode sourceHash = Hashing.sha256().hashString(source, StandardCharsets.UTF_8);
      HashCode formattedHash = Hashing.sha256().hashString(formattedSource, StandardCharsets.UTF_8);

      if (!formattedHash.equals(sourceHash)) {
        // overwrite existing file
        Files.write(file.toPath(), formattedSource.getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);

        getLog().info(String.format("Reformatted file %s", file.getPath()));
      }
    }
  } catch (Exception e) {
    throw new MojoExecutionException(e.getMessage(), e);
  }
}
 
源代码18 项目: connector-sdk   文件: FullTraversalConnectorTest.java
@Test
public void testTraverseNotIncrementalCommonAcl() throws Exception {
  // target targetItems
  int numberOfItems = 5;
  Map<String, String> targetItems = new HashMap<>();
  List<ApiOperation> docs = new ArrayList<>();
  for (int i = 0; i < numberOfItems; i++) {
    String id = "Test" + i;
    String content = "Test content " + i;
    targetItems.put(id, content);
    Item item = new Item();
    item.setName(id);
    docs.add(
        new RepositoryDoc.Builder()
            .setItem(item)
            .setRequestMode(RequestMode.ASYNCHRONOUS)
            .setContent(ByteArrayContent.fromString("text/html", content), ContentFormat.HTML)
            .build());
  }

  // DefaultAcl
  doAnswer(
      invocation -> {
        SettableFuture<Operation> result = SettableFuture.create();
        result.set(new Operation().setDone(true));
        return result;
      })
      .when(indexingServiceMock)
      .indexItem(
          argThat(item -> item.getName().equals(DefaultAcl.DEFAULT_ACL_NAME_DEFAULT)),
          eq(RequestMode.SYNCHRONOUS));
  // Documents
  SettableFuture<Item> updateFuture = SettableFuture.create();
  doAnswer(
      invocation -> {
        updateFuture.set(new Item());
        return updateFuture;
      })
      .when(indexingServiceMock)
      .indexItemAndContent(
          any(), any(), any(), eq(ContentFormat.HTML), eq(RequestMode.ASYNCHRONOUS));
  when(repositoryMock.getAllDocs(null))
      .thenReturn(new CheckpointCloseableIterableImpl.Builder<>(docs).build());
  // Delete other queue
  SettableFuture<Operation> deleteQueueFuture = SettableFuture.create();
  deleteQueueFuture.set(new Operation().setDone(true));
  when(indexingServiceMock.deleteQueueItems(any())).thenReturn(deleteQueueFuture);

  // full traversal test
  FullTraversalConnector connector =
      new FullTraversalConnector(repositoryMock, checkpointHandlerMock);

  setConfig("0", DefaultAclChoices.COMMON);

  connector.init(connectorContextMock);
  connector.traverse();

  InOrder inOrderCheck = inOrder(indexingServiceMock);
  // one update item with content for each of five targetItems in the db
  inOrderCheck
      .verify(indexingServiceMock, times(numberOfItems))
      .indexItemAndContent(
          itemListCaptor.capture(),
          contentCaptor.capture(),
          eq(null),
          eq(ContentFormat.HTML),
          eq(RequestMode.ASYNCHRONOUS));
  List<Item> allItems = itemListCaptor.getAllValues();
  List<ByteArrayContent> allContent = contentCaptor.getAllValues();
  assertEquals(allItems.size(), numberOfItems);
  for (int i = 0; i < numberOfItems; i++) {
    assertThat(targetItems.keySet(), hasItem(allItems.get(i).getName())); // verify item
    String html =
        CharStreams.toString(
            new InputStreamReader(allContent.get(i).getInputStream(), UTF_8));
    assertEquals(html, targetItems.get(allItems.get(i).getName())); // verify content
    ItemAcl acl = allItems.get(i).getAcl();
    assertEquals(DefaultAcl.DEFAULT_ACL_NAME_DEFAULT, acl.getInheritAclFrom());
    assertEquals(InheritanceType.PARENT_OVERRIDE.name(), acl.getAclInheritanceType());
  }
}
 
源代码19 项目: ja-micro   文件: JsonHandler.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
    logger.debug("Handling json request");

    GoTimer methodTimer = null;
    String methodName = null;
    Span span = null;
    long startTime = System.nanoTime();
    Map<String, String> headers = gatherHttpHeaders(req);
    OrangeContext context = new OrangeContext(headers);
    try {

        MDC.put(CORRELATION_ID, context.getCorrelationId());

        String postedContent = CharStreams.toString(req.getReader());
        logger.debug("Request JSON: {}", postedContent);

        JsonRpcRequest rpcRequest;

        try {
            rpcRequest = parseRpcRequest(postedContent);
        } catch (IllegalArgumentException iaex) {
            logger.warn("Error parsing request: " + postedContent, iaex);
            @SuppressWarnings("ThrowableNotThrown")
            RpcCallException callException = new RpcCallException(RpcCallException.Category.BadRequest,
                    iaex.getMessage());
            JsonObject jsonResponse = new JsonObject();
            jsonResponse.add(ERROR_FIELD, callException.toJson());
            writeResponse(resp, HttpServletResponse.SC_BAD_REQUEST, jsonResponse.toString());
            incrementFailureCounter("unknown", context.getRpcOriginService(),
                    context.getRpcOriginMethod());
            return;
        }

        methodName = rpcRequest.getMethod();

        span = getSpan(methodName, headers, context);

        methodTimer = getMethodTimer(methodName, context.getRpcOriginService(),
                context.getRpcOriginMethod());
        startTime = methodTimer.start();
        context.setCorrelationId(rpcRequest.getIdAsString());
        JsonRpcResponse finalResponse = dispatchJsonRpcRequest(rpcRequest, context);

        resp.setContentType(TYPE_JSON);
        writeResponse(resp, finalResponse.getStatusCode(), finalResponse.toJson().toString());

        //TODO: should we check the response for errors (for metrics)?
        methodTimer.recordSuccess(startTime);
        incrementSuccessCounter(methodName, context.getRpcOriginService(),
                context.getRpcOriginMethod());
    } catch (IOException e) {
        if (span != null) {
            Tags.ERROR.set(span, true);
        }
        //TODO: this case doesn't return a response.  should it?
        methodTimer.recordFailure(startTime);
        logger.error("Error handling request", e);
        incrementFailureCounter(methodName, context.getRpcOriginService(),
                context.getRpcOriginMethod());
    } finally {
        if (span != null) {
            span.finish();
        }
        MDC.remove(CORRELATION_ID);
    }
}
 
源代码20 项目: DotCi   文件: GithubWebhook.java
protected String getRequestPayload(final StaplerRequest req) throws IOException {
    return CharStreams.toString(req.getReader());
}