Java Code Examples for com.google.common.io.CharStreams#toString()

The following examples show how to use com.google.common.io.CharStreams#toString() . 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: KmsService.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: MetricParameters.java    From nomulus with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 3
Source File: ResourceStorageLoadable.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
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()));
}
 
Example 4
Source File: ApiDefinitionCommand.java    From apiman-cli with Apache License 2.0 6 votes vote down vote up
@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)));
}
 
Example 5
Source File: EMFGeneratorFragment.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
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();
	}
}
 
Example 6
Source File: SQLDeriver.java    From envelope with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 7
Source File: UrlUtils.java    From app-maven-plugin with Apache License 2.0 5 votes vote down vote up
/** 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;
}
 
Example 8
Source File: InfluxdbV1_Write.java    From StatsAgg with Apache License 2.0 5 votes vote down vote up
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();
        }
    }
}
 
Example 9
Source File: CommandScriptLoader.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
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));
    }
}
 
Example 10
Source File: DynamicDatabaseMockUtils.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
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);
        }
    }
}
 
Example 11
Source File: RequestModule.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Provides
@Payload
static String providePayloadAsString(HttpServletRequest req) {
  try {
    return CharStreams.toString(req.getReader());
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 12
Source File: ComposerJsonProcessorTest.java    From nexus-repository-composer with Eclipse Public License 1.0 5 votes vote down vote up
private String readStreamToString(final InputStream in) throws IOException {
  try {
    return CharStreams.toString(new InputStreamReader(in, UTF_8));
  }
  finally {
    in.close();
  }
}
 
Example 13
Source File: AlumniCerimonyDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 14
Source File: HostInfoReporter.java    From helios with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 15
Source File: KeycloakServiceClient.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
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();
  }
}
 
Example 16
Source File: GoogleFormatterMojo.java    From googleformatter-maven-plugin with Apache License 2.0 4 votes vote down vote up
@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);
  }
}
 
Example 17
Source File: FullTraversalConnectorTest.java    From connector-sdk with Apache License 2.0 4 votes vote down vote up
@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());
  }
}
 
Example 18
Source File: ValidationUtils.java    From google-cloud-eclipse with Apache License 2.0 4 votes vote down vote up
static String convertStreamToString(InputStream stream, String charset) throws IOException {
  String result = CharStreams.toString(new InputStreamReader(stream, charset));
  return result;
}
 
Example 19
Source File: JsonHandler.java    From ja-micro with Apache License 2.0 4 votes vote down vote up
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);
    }
}
 
Example 20
Source File: GithubWebhook.java    From DotCi with MIT License 4 votes vote down vote up
protected String getRequestPayload(final StaplerRequest req) throws IOException {
    return CharStreams.toString(req.getReader());
}