Java Code Examples for java.io.InputStreamReader

The following are top voted examples for showing how to use java.io.InputStreamReader. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: rapidminer   File: Tools.java   Source Code and License 12 votes vote down vote up
/**
 * This method checks if the given file is a Zip file containing one entry (in case of file
 * extension .zip). If this is the case, a reader based on a ZipInputStream for this entry is
 * returned. Otherwise, this method checks if the file has the extension .gz. If this applies, a
 * gzipped stream reader is returned. Otherwise, this method just returns a BufferedReader for
 * the given file (file was not zipped at all).
 */
public static BufferedReader getReader(File file, Charset encoding) throws IOException {
	// handle zip files if necessary
	if (file.getAbsolutePath().endsWith(".zip")) {
		try (ZipFile zipFile = new ZipFile(file)) {
			if (zipFile.size() == 0) {
				throw new IOException("Input of Zip file failed: the file archive does not contain any entries.");
			}
			if (zipFile.size() > 1) {
				throw new IOException("Input of Zip file failed: the file archive contains more than one entry.");
			}
			Enumeration<? extends ZipEntry> entries = zipFile.entries();
			InputStream zipIn = zipFile.getInputStream(entries.nextElement());
			return new BufferedReader(new InputStreamReader(zipIn, encoding));
		}
	} else if (file.getAbsolutePath().endsWith(".gz")) {
		return new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(file)), encoding));
	} else {
		return new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
	}
}
 
Example 2
Project: pokeraidbot   File: LoggingRequestInterceptor.java   Source Code and License 8 votes vote down vote up
private void traceResponse(ClientHttpResponse response) throws IOException {
    StringBuilder inputStringBuilder = new StringBuilder();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"));
    String line = bufferedReader.readLine();
    while (line != null) {
        inputStringBuilder.append(line);
        inputStringBuilder.append('\n');
        line = bufferedReader.readLine();
    }
    log.debug("============================response begin==========================================");
    log.debug("Status code  : {}", response.getStatusCode());
    log.debug("Status text  : {}", response.getStatusText());
    log.debug("Headers      : {}", response.getHeaders());
    log.debug("Response body: {}", inputStringBuilder.toString());
    log.debug("=======================response end=================================================");
}
 
Example 3
Project: geomapapp   File: FossilGlossary.java   Source Code and License 7 votes vote down vote up
static void init() {
	try {
		glossary = new Vector();
		URL url = URLFactory.url( DSDP.ROOT+"fauna/glossary.gz");
		BufferedReader in = new BufferedReader(
			new InputStreamReader( 
			new GZIPInputStream( url.openStream() )));
		String s;
		while( (s=in.readLine())!=null ) glossary.add(s.getBytes());
		glossary.trimToSize();
	} catch(IOException e) {
		e.printStackTrace();
	}
}
 
Example 4
Project: CF-rating-prediction   File: JsonReader.java   Source Code and License 7 votes vote down vote up
public static JSONObject read(final String url) throws Exception {
    Exception exception = null;
    for (int i = 0; i < 3; i++) {
        Expectant.delay((i + 1) * API_DELAY_MS);
        try (InputStream is = new URL(url).openStream()) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readWhole(reader);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } catch (Exception ex) {
            System.err.println("Failed read url: " + url
                    + " try #" + (i + 1) + "\n" + ex.getMessage());
            exception = ex;
        }
    }

    throw exception;
}
 
Example 5
Project: xtf   File: LogCheckerUtils.java   Source Code and License 7 votes vote down vote up
public static boolean[] findPatternsInLogs(DockerContainer dockerContainer, Pattern... patterns) throws IOException {
	boolean found[] = new boolean[patterns.length];
	dockerContainer.dockerLogs(istream -> {
		try (BufferedReader br = new BufferedReader(new InputStreamReader(istream, "UTF-8"))) {
			br.lines().forEach(line -> {
				for (int i = 0; i < patterns.length; ++i) {
					Pattern pattern = patterns[i];
					if (pattern.matcher(line).find()) {
						LOGGER.info("Found pattern {} on line '{}'", pattern, LogCleaner.cleanLine(line));
						found[i] = true;
					}
				}
			});
		}
	});
	return found;
}
 
Example 6
Project: openrouteservice   File: StreamUtility.java   Source Code and License 7 votes vote down vote up
/**
 * 
 * 
 * @param coordstream
 *            InputStream
 * @param bufferSize
 *            int
 * @return result String
 * @throws IOException
 */
public static String readStream(InputStream stream, int bufferSize, String encoding) throws IOException {
	StringWriter sw = new StringWriter();
	int bytesRead;

	if (!Helper.isEmpty(encoding)) {
		BufferedReader br = new BufferedReader(new InputStreamReader(stream, encoding), bufferSize);
		String str;
		while ((str = br.readLine()) != null) {
			sw.write(str);
		}
	} else {
		byte[] buffer = new byte[bufferSize];

		while ((bytesRead = stream.read(buffer)) != -1) {
			sw.write(new String(buffer, 0, bytesRead));
		}
	}

	return sw.toString();
}
 
Example 7
Project: KernelHive   File: SourceCodeEditor.java   Source Code and License 6 votes vote down vote up
@Override
public final boolean loadContent(final File file) {
	try {
		FileInputStream fis = new FileInputStream(file);
		DataInputStream dis = new DataInputStream(fis);
		BufferedReader br = new BufferedReader(new InputStreamReader(dis));
		StringBuilder sb = new StringBuilder();
		String strLine;
		while ((strLine = br.readLine()) != null) {
			sb.append(strLine);
			sb.append("\n");
		}
		if (sb.length() != 0) {
			sb.deleteCharAt(sb.length() - 1);
		}
		setText(sb.toString());
		dis.close();
		return true;
	} catch (IOException e) {
		LOG.warning("KH: could not load specified file: " + file.getPath());
		e.printStackTrace();
	}
	return false;
}
 
Example 8
Project: SmingZZick_App   File: YoutubeSmingActivity.java   Source Code and License 6 votes vote down vote up
private String loadJS() {
    StringBuilder buf = new StringBuilder();
    try {
        InputStream is = getResources().getAssets().open("youtube_inject.js");
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String str;

        while ((str = br.readLine()) != null) {
            buf.append(str);
        }

        br.close();
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }

    return buf.toString();
}
 
Example 9
Project: CSLMusicModStationCreator   File: Station.java   Source Code and License 6 votes vote down vote up
public String buildModSource() {
    String template;
    try (BufferedReader buffer = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/cslmusicmod/stationeditor/Mod.cs")))) {
        template = buffer.lines().collect(Collectors.joining("\n"));
    } catch (IOException e) {
        throw new IllegalStateException();
    }

    String namespace = "MusicPack_" + getName().trim().replaceAll("[^a-zA-Z0-9]" , "_");

    template = template.replace("__NAME__", getName())
            .replace("__DESCRIPTION__", getDescription())
            .replace("__NAMESPACE__", namespace);

    return template;
}
 
Example 10
Project: Tech-Jalsa   File: LocalWebActivity.java   Source Code and License 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_aboutus);

    Intent incoming = getIntent();
    Bundle extras = incoming.getExtras();

    String uri = "html/about.html";
    if(extras != null){
        uri = extras.getString(EXTRA_HTML_URI);
    }

    mWebView = (WebView) findViewById(R.id.webView);
    mCloseBtn = (ImageButton) findViewById(R.id.closeButton);

    mCloseBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

    InputStream is;
    String htmlData = "";
    try {
        is = this.getAssets().open(uri);
        BufferedReader r = new BufferedReader(new InputStreamReader(is));
        StringBuilder stringBuilder = new StringBuilder();

        String line;
        while( (line=r.readLine()) != null ) {
            stringBuilder.append(line);
        }
        htmlData = stringBuilder.toString();
    } catch( IOException error ) {}
    mWebView.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "utf-8", "about:blank");
}
 
Example 11
Project: spoj   File: LSORT_6_Bottom_Up_Submitted.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	String s;
	String[] parts;
	int testsNum = Integer.parseInt(br.readLine());
	for (int t = 0; t < testsNum; t++) {
		arrLength = Integer.parseInt(br.readLine());
		s = br.readLine();
		parts = s.split(" ", -1);
		for (int i = 0; i < arrLength; i++) {
			arr[i] = Integer.parseInt(parts[i]);
		}
		int result = solveProblem();
		System.out.println(result);
	}
}
 
Example 12
Project: JavaRushTasks   File: Solution.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Считать строки с консоли и объявить ArrayList list тут

    ArrayList <String> list = new ArrayList<>();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    for (int i=0; i<10; i++) {
        list.add(br.readLine());
    }

    ArrayList<String> result = doubleValues(list);

    // Вывести на экран result
    for (String s: result) {
        System.out.println(s);
    }
}
 
Example 13
Project: oreilly-reactive-architecture-student   File: CoffeeHouseApp.java   Source Code and License 6 votes vote down vote up
private void commandLoop() throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        TerminalCommand tc = Terminal.create(in.readLine());
        if (tc instanceof TerminalCommand.Guest) {
            TerminalCommand.Guest tcg = (TerminalCommand.Guest) tc;
            createGuest(tcg.count, tcg.coffee, tcg.maxCoffeeCount);
        } else if (tc == TerminalCommand.Status.Instance) {
            getStatus();
        } else if (tc == TerminalCommand.Quit.Instance) {
            system.terminate();
            break;
        } else {
            TerminalCommand.Unknown u = (TerminalCommand.Unknown) tc;
            log.warning("Unknown terminal command {}!", u.command);
        }
    }
}
 
Example 14
Project: homescreenarcade   File: FieldLayout.java   Source Code and License 6 votes vote down vote up
static Map<String, Object> readFieldLayout(int level) {
    try {
        String assetPath = "tables/table" + level + ".json";
        InputStream fin = _context.getAssets().open(assetPath);
        BufferedReader br = new BufferedReader(new InputStreamReader(fin));

        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line=br.readLine())!=null) {
            buffer.append(line);
        }
        fin.close();
        Map<String, Object> layoutMap = JSONUtils.mapFromJSONString(buffer.toString());
        return layoutMap;
    }
    catch(Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 15
Project: PeSanKita-android   File: PreKeyUtil.java   Source Code and License 6 votes vote down vote up
private static synchronized int getNextPreKeyId(Context context) {
  try {
    File nextFile = new File(getPreKeysDirectory(context), PreKeyIndex.FILE_NAME);

    if (!nextFile.exists()) {
      return Util.getSecureRandom().nextInt(Medium.MAX_VALUE);
    } else {
      InputStreamReader reader = new InputStreamReader(new FileInputStream(nextFile));
      PreKeyIndex       index  = JsonUtils.fromJson(reader, PreKeyIndex.class);
      reader.close();
      return index.nextPreKeyId;
    }
  } catch (IOException e) {
    Log.w("PreKeyUtil", e);
    return Util.getSecureRandom().nextInt(Medium.MAX_VALUE);
  }
}
 
Example 16
Project: hacker-rank   File: Repeated_String.java   Source Code and License 6 votes vote down vote up
public static void main(String ... ags)throws IOException
{
	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	String str = in.readLine();
	long n = Long.parseLong(in.readLine());
	long a =0;
	for(int i=0;i<str.length();i++)
	{	
		if(str.charAt(i)=='a')
			a++;
	}
	long c =n/(long)str.length();
	a *= c;
	c = n%(long)str.length();
	for(int i=0;i<(int)c;i++)
	{
		if(str.charAt(i)=='a')
			a++;
	}
	System.out.println(a);
}
 
Example 17
Project: ZooKeeper   File: GenerateLoad.java   Source Code and License 6 votes vote down vote up
private static String getMode(String hostPort) throws NumberFormatException, UnknownHostException, IOException {
    String parts[] = hostPort.split(":");
    Socket s = new Socket(parts[0], Integer.parseInt(parts[1]));
    s.getOutputStream().write("stat".getBytes());
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String line;
    try {
      while((line = br.readLine()) != null) {
        if (line.startsWith("Mode: ")) {
          return line.substring(6);
        }
      }
      return "unknown";
    } finally {
      s.close();
    }
}
 
Example 18
Project: mmm   File: WorkflowTask.java   Source Code and License 6 votes vote down vote up
/**
 * Writes the associated README to the specified {@link Path}.
 *
 * @param outputPath The {@link Path} to which the README should be written.
 * @throws IOException
 */
protected void writeReadme(Path outputPath) throws IOException {
    InputStream readmeResource = Thread.currentThread()
                                       .getContextClassLoader()
                                       .getResourceAsStream(getClass().getSimpleName() + "_README.md");
    Files.createDirectories(outputPath);
    String username = System.getProperty("user.name");
    LocalDateTime now = LocalDateTime.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String date = formatter.format(now);

    if (readmeResource != null) {
        String readmeContent = new BufferedReader(new InputStreamReader(readmeResource)).lines()
                                                                                        .map(line -> {
                                                                                            if (line.contains("%DATE%") && line.contains("%USER%")) {
                                                                                                return line.replace("%DATE%", date).replace("%USER%", username);
                                                                                            }
                                                                                            return line;
                                                                                        })
                                                                                        .collect(Collectors.joining("\n"));
        Files.write(outputPath.resolve("README.md"), readmeContent.getBytes());
    }
}
 
Example 19
Project: JAVA-   File: NativeUtil.java   Source Code and License 6 votes vote down vote up
/** 获取网卡序列号 */
public static final String getDUID() {
	String address = "";
	String command = "cmd.exe /c ipconfig /all";
	try {
		Process p = Runtime.getRuntime().exec(command);
		BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
		String line;
		while ((line = br.readLine()) != null) {
			if (line.indexOf("DUID") > 0) {
				int index = line.indexOf(":");
				index += 2;
				address = line.substring(index);
				break;
			}
		}
		br.close();
	} catch (IOException e) {
	}
	return address;
}
 
Example 20
Project: appinventor-extensions   File: YandexTranslate.java   Source Code and License 6 votes vote down vote up
/**
 * This method reads from a stream based on the passed connection
 * @param connection the connection to read from
 * @return the contents of the stream
 * @throws IOException if it cannot read from the http connection
 */
private static String getResponseContent(HttpURLConnection connection) throws IOException {
  // Use the content encoding to convert bytes to characters.
  String encoding = connection.getContentEncoding();
  if (encoding == null) {
    encoding = "UTF-8";
  }
  InputStreamReader reader = new InputStreamReader(connection.getInputStream(), encoding);
  try {
    int contentLength = connection.getContentLength();
    StringBuilder sb = (contentLength != -1)
        ? new StringBuilder(contentLength)
        : new StringBuilder();
    char[] buf = new char[1024];
    int read;
    while ((read = reader.read(buf)) != -1) {
      sb.append(buf, 0, read);
    }
    return sb.toString();
  } finally {
    reader.close();
  }
}
 
Example 21
Project: jpl-framework   File: JsonUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a {@link JsonObject} from the given json string.
 * 
 * @param jsonString the json string to parse
 * @return the {@link JsonObject} received while parsing the given json string
 * @throws JsonParsingFailedException if any exception occurred at runtime
 */
public static JsonObject createJsonObjectFromString(final String jsonString) throws JsonParsingFailedException {
   InputStream stream = new ByteArrayInputStream(jsonString.getBytes(StandardCharsets.UTF_8));
   Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);

   JsonObject readJsonObject = null;
   try {
      readJsonObject = new Gson().fromJson(reader, JsonObject.class);
   } catch (JsonSyntaxException jsonSyntaxException) {
      throw new JsonParsingFailedException(jsonSyntaxException);
   } catch (JsonIOException jsonIoException) {
      throw new JsonParsingFailedException(jsonIoException);
   }

   return readJsonObject;
}
 
Example 22
Project: CraftyProfessions   File: ConfigController.java   Source Code and License 6 votes vote down vote up
/**
 * This method essentially imitates the getConfig method within the JavaPlugin class
 * but is used to create or grab special config files pertaining to the Wage Tables of
 * the plugin
 *
 * @param resource The file or resource to grab the Configuration for.
 *
 * @return The configuration of the resource.
 */
public YamlConfiguration getSpecialConfig (String resource)
{
    YamlConfiguration config = mWageConfigs.get (resource);

    if (config == null)
    {
        InputStream configStream = mPlugin.getResource (resource);
        config = YamlConfiguration.loadConfiguration (mWageFiles.get (resource));

        if (configStream != null)
        {
            config.setDefaults (YamlConfiguration.loadConfiguration (new InputStreamReader (configStream, Charsets.UTF_8)));
        }

        mWageConfigs.put (resource, config);
    }

    return config;
}
 
Example 23
Project: VerveineC-Cpp   File: IncludeConfs.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {

        try {
        	/*
        	 * trying to automatically configure include path by running cpp -v
        	 */
            Process p = Runtime.getRuntime().exec("cpp -v");
            
            InputStreamReader stdInput = new //BufferedReader(new 
                 InputStreamReader(p.getInputStream()) ; //);

            // read the output from the command
            System.out.println("Here is the standard output of the command:\n");
            while (stdInput.ready() ) {
                System.out.print(stdInput.read());
            }
        }
        catch (IOException e) {
        	System.out.println("exception happened - here's what I know: ");
        	e.printStackTrace();
        	System.exit(-1);
        }
	}
 
Example 24
Project: hacker-rank   File: Java_loops_2.java   Source Code and License 6 votes vote down vote up
public static void main(String ... ags)throws Exception
{
	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	int n = Integer.parseInt(in.readLine());
	for(int i=0;i<n;i++)
	{
		StringTokenizer tk = new StringTokenizer(in.readLine());
		int a = Integer.parseInt(tk.nextToken());
		int b = Integer.parseInt(tk.nextToken());
		int c = Integer.parseInt(tk.nextToken());
		int sum=a+b;
		System.out.print(sum +" ");
		for(int j=1;j<c;j++)
		{
			sum = sum+(power(j)*b);
			System.out.print(sum + " ");
		}
		System.out.println();
	}
}
 
Example 25
Project: ExoPlayer-Offline   File: SampleChooserActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected List<SampleGroup> doInBackground(String... uris) {
  List<SampleGroup> result = new ArrayList<>();
  Context context = getApplicationContext();
  String userAgent = Util.getUserAgent(context, "ExoPlayerDemo");
  DataSource dataSource = new DefaultDataSource(context, null, userAgent, false);
  for (String uri : uris) {
    DataSpec dataSpec = new DataSpec(Uri.parse(uri));
    InputStream inputStream = new DataSourceInputStream(dataSource, dataSpec);
    try {
      readSampleGroups(new JsonReader(new InputStreamReader(inputStream, "UTF-8")), result);
    } catch (Exception e) {
      Log.e(TAG, "Error loading sample list: " + uri, e);
      sawError = true;
    } finally {
      Util.closeQuietly(dataSource);
    }
  }
  return result;
}
 
Example 26
Project: openjdk-jdk10   File: PSPrinterJob.java   Source Code and License 6 votes vote down vote up
private void handleProcessFailure(final Process failedProcess,
        final String[] execCmd, final int result) throws IOException {
    try (StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw)) {
        pw.append("error=").append(Integer.toString(result));
        pw.append(" running:");
        for (String arg: execCmd) {
            pw.append(" '").append(arg).append("'");
        }
        try (InputStream is = failedProcess.getErrorStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr)) {
            while (br.ready()) {
                pw.println();
                pw.append("\t\t").append(br.readLine());
            }
        } finally {
            pw.flush();
        }
        throw new IOException(sw.toString());
    }
}
 
Example 27
Project: leoapp-sources   File: CreateChat.java   Source Code and License 6 votes vote down vote up
private void sendChat() {
    try {
        service.send(new Chat(cid, cname, Chat.ChatType.GROUP));

        URLConnection connection = new URL(generateURL(cname))
                .openConnection();

        BufferedReader reader =
                new BufferedReader(
                        new InputStreamReader(
                                connection.getInputStream(), "UTF-8"));
        StringBuilder builder = new StringBuilder();
        String        l;
        while ((l = reader.readLine()) != null)
            builder.append(l);
        reader.close();
        Utils.logDebug(builder);

        cid = Integer.parseInt(builder.toString());

        Utils.getController().getMessengerDatabase().insertChat(new Chat(cid, cname, Chat.ChatType.GROUP));
    } catch (IOException e) {
        Utils.logError(e);
    }
}
 
Example 28
Project: jPUBG   File: HttpService.java   Source Code and License 6 votes vote down vote up
private String processResponse() throws IOException, BadResponseCodeException {
    int responseCode = connection.getResponseCode();

    if(responseCode != HttpURLConnection.HTTP_OK) {
        throw new BadResponseCodeException(MessageUtils.prepareBadCodeErrorMessage(responseCode));
    }

    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(connection.getInputStream()));
    String output;
    StringBuilder response = new StringBuilder();

    while ((output = bufferedReader.readLine()) != null) {
        response.append(output);
    }

    bufferedReader.close();

    return response.toString();
}
 
Example 29
Project: OpenJSharp   File: XmlDataContentHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Create an object from the input stream
 */
public Object getContent(DataSource ds) throws IOException {
    String ctStr = ds.getContentType();
    String charset = null;
    if (ctStr != null) {
        ContentType ct = new ContentType(ctStr);
        if (!isXml(ct)) {
            throw new IOException(
                "Cannot convert DataSource with content type \""
                        + ctStr + "\" to object in XmlDataContentHandler");
        }
        charset = ct.getParameter("charset");
    }
    return (charset != null)
            ? new StreamSource(new InputStreamReader(ds.getInputStream()), charset)
            : new StreamSource(ds.getInputStream());
}
 
Example 30
Project: ULCRS   File: SessionControllerTest.java   Source Code and License 6 votes vote down vote up
@Before
public void init() throws Exception {
    MockitoAnnotations.initMocks(this);

    sessionControllerTest = new SessionController();

    directoryTest = new File(TEST_WORKSPACE_PATH);
    fileReaderTest = new FileReader(TEST_WORKSPACE_PATH + "2.json");

    Mockito.when(requestMock.params(Mockito.eq(":name"))).thenReturn("2");

    InputStream is = SessionController.class.getClassLoader().getResourceAsStream("mockSessionSchedule.json");
    JsonReader reader = new JsonReader(new InputStreamReader(is));
    Schedule schedule = gson.fromJson(reader, new TypeToken<Schedule>() {
    }.getType());
    String scheduleStrTest = gson.toJson(schedule);
    Mockito.when(requestMock.body()).thenReturn(scheduleStrTest);

    PowerMockito.whenNew(File.class).withParameterTypes(String.class)
            .withArguments(Mockito.eq(WORKSPACE_PATH)).thenReturn(directoryTest);
    PowerMockito.whenNew(FileReader.class).withParameterTypes(String.class)
            .withArguments(Mockito.eq(WORKSPACE_PATH + "2.json")).thenReturn(fileReaderTest);
}
 
Example 31
Project: lams   File: DefaultServlet.java   Source Code and License 6 votes vote down vote up
/**
 * Get the readme file as a string.
 */
protected String getReadme(DirContext directory)
    throws IOException, ServletException {

    if (readmeFile != null) {
        try {
            Object obj = directory.lookup(readmeFile);
            if ((obj != null) && (obj instanceof Resource)) {
                StringWriter buffer = new StringWriter();
                InputStream is = ((Resource) obj).streamContent();
                copyRange(new InputStreamReader(is),
                        new PrintWriter(buffer));
                return buffer.toString();
            }
        } catch (NamingException e) {
            if (debug > 10)
                log("readme '" + readmeFile + "' not found", e);

            return null;
        }
    }

    return null;
}
 
Example 32
Project: lams   File: PEMReader.java   Source Code and License 6 votes vote down vote up
/**
 * Read the PEM file and save the DER encoded octet
 * stream and begin marker.
 * 
 * @throws IOException
 */
protected void readFile() throws IOException {

    String  line;
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(stream));
    try {
        while ((line = reader.readLine()) != null)
        {
            if (line.indexOf(BEGIN_MARKER) != -1)
            {
                beginMarker = line.trim();
                String endMarker = beginMarker.replace("BEGIN", "END");
                derBytes = readBytes(reader, endMarker);
                return;
            }
        }	        
        throw new IOException("Invalid PEM file: no begin marker");
    } finally {
        reader.close();
    }
}
 
Example 33
Project: springboot-shiro-cas-mybatis   File: LdapTestUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Reads an LDIF into a collection of LDAP entries. The components performs a simple property
 * replacement in the LDIF data where <pre>${ldapBaseDn}</pre> is replaced with the environment-specific base
 * DN.
 *
 * @param ldif LDIF resource, typically a file on filesystem or classpath.
 * @param baseDn The directory branch where the entry resides.
 *
 * @return LDAP entries contained in the LDIF.
 *
 * @throws IOException On IO errors reading LDIF.
 */
public static Collection<LdapEntry> readLdif(final InputStream ldif, final String baseDn) throws IOException {
    final StringBuilder builder = new StringBuilder();
    try (final BufferedReader reader = new BufferedReader(new InputStreamReader(ldif))) {
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.contains(BASE_DN_PLACEHOLDER)) {
                builder.append(line.replace(BASE_DN_PLACEHOLDER, baseDn));
            } else {
                builder.append(line);
            }
            builder.append(NEWLINE);
        }
    }
    return new LdifReader(new StringReader(builder.toString())).read().getEntries();
}
 
Example 34
Project: JavaRushTasks   File: Solution.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    //напишите тут ваш код
    int [] vct = new int[5];

    for (int i=0;i<vct.length;i++) {
        vct[i] = Integer.parseInt(reader.readLine());
    }

    int tmp;
    for (int i=0;i<vct.length;i++)
        for (int j=i+1; j<vct.length; j++)
            if (vct[i]>vct[j]){
                tmp = vct[i];
                vct[i] = vct[j];
                vct[j] = tmp;
            }


    for (int i=0; i<vct.length; i++) {
        System.out.println(vct[i]);
    }
}
 
Example 35
Project: oscm   File: UserValidator.java   Source Code and License 6 votes vote down vote up
private void loadUserList() throws IOException {
    String delimiter = PropertyLoader.getInstance()
            .load(COMMON_PROPERTIES_PATH).getProperty(DELIMITER);
    try (InputStream in = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("UserList");
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in));) {
        userList = new HashMap<String, String>();
        String data = null;
        while ((data = reader.readLine()) != null) {
            if (!data.trim().isEmpty()) {
                String[] userData = data.split(delimiter);
                userList.put(userData[0], userData[1]);
            }
        }
    }
}
 
Example 36
Project: incubator-netbeans   File: ProcessorGenerated.java   Source Code and License 6 votes vote down vote up
private StringBuilder readFile(final File file) {        
    StringBuilder sb = new StringBuilder();
    try {
        final Reader in = new InputStreamReader (new FileInputStream (file),"UTF-8");   //NOI18N
        try {
            char[] buffer = new char[1024];
            int len;
            while ((len=in.read(buffer))>0) {
                sb.append(buffer, 0, len);
            }
        } finally {
            in.close();
        }
    } catch (IOException ioe) {
        if (sb.length() != 0) {
            sb = new StringBuilder();
        }
    }
    return sb;
}
 
Example 37
Project: incubator-netbeans   File: Bug138973Test.java   Source Code and License 6 votes vote down vote up
@Override
public FileObject createFromTemplate(FileObject template,
                                        FileObject targetFolder,
                                        String name,
                                        Map<String, Object> parameters) throws IOException {
    String nameUniq = FileUtil.findFreeFileName(targetFolder, name, template.getExt());
    FileObject newFile = FileUtil.createData(targetFolder, nameUniq + '.' + template.getExt());

    Charset templateEnc = FileEncodingQuery.getEncoding(template);
    Charset newFileEnc = FileEncodingQuery.getEncoding(newFile);

    InputStream is = template.getInputStream();
    Reader reader = new BufferedReader(new InputStreamReader(is, templateEnc));
    OutputStream os = newFile.getOutputStream();
    Writer writer = new BufferedWriter(new OutputStreamWriter(os, newFileEnc));
    int cInt;
    while ((cInt = reader.read()) != -1) {
        writer.write(cInt);
    }
    writer.close();
    reader.close();

    return newFile;
}
 
Example 38
Project: wso2is-example   File: UserInformationService.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * @param accessToken
 * @return JSON with user info
 * @throws IOException
 */
public String getUserInformation(String accessToken) throws IOException {
    String endpoint = AuthProperties.inst().getUserInformationEndpoint();
    
    URL url = new URL(endpoint);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    
    String authorizationHeader = String.format("Bearer %s", accessToken);
    con.addRequestProperty("Authorization", authorizationHeader);
    
    con.setRequestMethod("GET");
    con.connect();
    
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    
    in.close();
    
    return response.toString();
}
 
Example 39
Project: morpheus-core   File: CsvSource.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a DataFrame parsed from the stream specified stream
 * @param stream    the stream to parse
 * @return          the DataFrame parsed from stream
 * @throws IOException      if there stream read error
 */
private DataFrame<R,String> parse(CsvSourceOptions<R> options, InputStream stream) throws IOException {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, options.getCharset().orElse(StandardCharsets.UTF_8)))) {
        final CsvRequestHandler handler = new CsvRequestHandler(options);
        final CsvParserSettings settings = new CsvParserSettings();
        settings.getFormat().setDelimiter(options.getDelimiter());
        settings.setHeaderExtractionEnabled(options.isHeader());
        settings.setLineSeparatorDetectionEnabled(true);
        settings.setRowProcessor(handler);
        settings.setIgnoreTrailingWhitespaces(true);
        settings.setIgnoreLeadingWhitespaces(true);
        settings.setMaxColumns(10000);
        settings.setReadInputOnSeparateThread(false);
        final CsvParser parser = new CsvParser(settings);
        parser.parse(reader);
        return handler.getFrame();
    }
}
 
Example 40
Project: incubator-netbeans   File: ReadOnlyAccess.java   Source Code and License 6 votes vote down vote up
@Override
public javax.swing.text.Document loadSwingDocument(InputStream in)
throws IOException, BadLocationException {
    
    javax.swing.text.Document sd = new PlainDocument();
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    try {
        String line = null;
        while ((line = br.readLine()) != null) {
            sd.insertString(sd.getLength(), line+System.getProperty("line.separator"), null); // NOI18N
        }
    } finally {
        br.close();
    }
    return sd;
}
 
Example 41
Project: nem-apps-lib   File: GzipUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Decompress.
 *
 * @param compressed the compressed
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static String decompress(final byte[] compressed) throws IOException {
	String outStr = "";
	if ((compressed == null) || (compressed.length == 0)) {
		return "";
	}
	if (isCompressed(compressed)) {
		GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressed));
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gis, "UTF-8"));

		String line;
		while ((line = bufferedReader.readLine()) != null) {
			outStr += line;
		}
	} else {
		outStr = new String(compressed);
	}
	return outStr;
}
 
Example 42
Project: Minecoprocessors   File: BookCreator.java   Source Code and License 5 votes vote down vote up
private static BufferedReader openBookReader(String name) throws FileNotFoundException {
  String path = PATH + name + ".txt";
  InputStream is = BookCreator.class.getResourceAsStream(path);
  if (is == null) {
    throw new FileNotFoundException("Book file not found [" + path + "]");
  }
  return new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
}
 
Example 43
Project: pub-service   File: SmsSenderLT.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("finally")
	public String onSend(String phone, String content) {
		String messagecode = "";
		String sql ="select * from pub_sms_platform where id=3";
		SmsPlatform platform =  (SmsPlatform) this.daoSupport.queryForObject(sql, SmsPlatform.class);
		String config=platform.getConfig();
		JSONObject jsonObject = JSONObject.fromObject(config);  
		Map configMap = (Map)jsonObject.toBean(jsonObject, Map.class);
		String url=configMap.get("url").toString();
		String uid=configMap.get("uid").toString();
		String pwd=configMap.get("pwd").toString();
//			   pwd=StringUtil.md5(uid+pwd);//加密
//			   pwd="4b3d06d1fce032d72294c93e59ef8733";
		// 创建StringBuffer对象用来操作字符串
		StringBuffer sb = new StringBuffer(url);
		// 向StringBuffer追加用户名
		sb.append("?action=sendOnce&uid=").append(uid);
		// 向StringBuffer追加密码(密码采用MD5 32位 小写)
		sb.append("&pwd=").append(pwd);
		// 向StringBuffer追加手机号码
		sb.append("&mobile=").append(phone);
		// 向StringBuffer追加消息内容转URL标准码
		sb.append("&content=").append(URLEncoder.encode(content));
		sb.append("&encode=utf8");
		System.out.println(sb.toString());
		try {
			// 创建url对象
			URL url2 = new URL(sb.toString());
			
			// 打开url连接
			HttpURLConnection connection = (HttpURLConnection) url2.openConnection();
			
			// 设置url请求方式 ‘get’ 或者 ‘post’
			connection.setRequestMethod("POST");

			// 发送
			BufferedReader in = new BufferedReader(new InputStreamReader(url2.openStream()));

			// 返回发送结果
			String result = in.readLine().toString();
			System.out.println("网关信息:"+decodeUnicode(result));
			 // 将String转换为XML文档 
			Document doc=DocumentHelper.parseText(result);
			messagecode=parseDOM4J(doc);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			String message=getResponse(messagecode);
//			Map<String,String> smsMap = new HashMap<String,String>();
//			JSONObject jsonObj = JSONObject.fromObject(message);  
//			smsMap = (Map)jsonObject.toBean(jsonObj, Map.class);
//			smsMap.put("messagecode",result);
//			smsMap.put("message", message);
			AppConfigParse appconfig=new AppConfigParse();
			System.out.println(appconfig.getAppId("similar_sms"));
			if("yes".equals(appconfig.getAppId("similar_sms"))){
				this.mockSend(message);
			}
			
			return str2json(messagecode);
		}
	}
 
Example 44
Project: spring-webflux-client   File: DataBuffers.java   Source Code and License 5 votes vote down vote up
public static String readToString(DataBuffer dataBuffer) {
    try {
        return FileCopyUtils.copyToString(new InputStreamReader(dataBuffer.asInputStream()));
    }
    catch (IOException e) {
        return e.getMessage();
    }
}
 
Example 45
Project: StackNet   File: FRGFRegressor.java   Source Code and License 5 votes vote down vote up
/**
 * 
 * @param confingname : full path and name of the config file
 * @param istrain : if this is a train task or a prediction task
 */
private void create_frgf_suprocess(String confingname, boolean istrain ) {
  
  // check if file exists
  if (new File(confingname).exists()==false){
   throw new IllegalStateException("Config file does not exist at: " + confingname);
  }
  // create the subprocess
try {
	 String operational_system=detectos.getOS();
	 if (!operational_system.equals("win") && !operational_system.equals("linux")&& !operational_system.equals("mac")){
		 throw new IllegalStateException(" The operational system is not identified as win, linux or mac which is required to run xgboost" ); 
	 }
	 String frgf_path="lib" + File.separator + operational_system + File.separator + "frgf" + File.separator + "forest_train";
	 if (istrain==false){
		 frgf_path="lib" + File.separator + operational_system + File.separator + "frgf" + File.separator + "forest_predict";
	 }
	 List<String> list = new ArrayList<String>();
	 list.add(frgf_path);			 
	 list.add("-config=" + confingname);			 

	 //start the process		 
	 ProcessBuilder p = new ProcessBuilder(list);		  
     p.redirectErrorStream(true);
     Process sp = p.start();
     BufferedReader r = new BufferedReader(new InputStreamReader(sp.getInputStream()));
     String line;
        while(true){
            line = r.readLine();
            if(line == null) { break; }
            if (this.verbose){
            	System.out.println(line);
            }
        }

} catch (IOException e) {
	throw new IllegalStateException(" failed to create fast_rgf subprocess with config name " + confingname);
}
  
}
 
Example 46
Project: spoj   File: SLIKAR_9_Submitted.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	int rows_num = Integer.parseInt(br.readLine());
	String[] rows = new String[rows_num];
	for (int i = 0; i < rows_num; i++) {
		rows[i] = br.readLine();
	}

	solve(rows);
}
 
Example 47
Project: NyaaCore   File: LanguageRepository.java   Source Code and License 5 votes vote down vote up
private static void loadResourceMap(JavaPlugin plugin, String codeName,
                                    Map<String, String> targetMap, boolean ignoreInternal, boolean ignoreNormal) {
    if (plugin == null || codeName == null || targetMap == null) throw new IllegalArgumentException();
    InputStream stream = plugin.getResource("lang/" + codeName + ".yml");
    if (stream != null) {
        YamlConfiguration section = YamlConfiguration.loadConfiguration(new InputStreamReader(stream));
        loadLanguageSection(targetMap, section, "", ignoreInternal, ignoreNormal);
    }
}
 
Example 48
Project: mapbox-assistant-example   File: StorageManager.java   Source Code and License 5 votes vote down vote up
private Position getPositionFromKey(String key) {
    try {
        S3Object object = s3.getObject(new GetObjectRequest(BUCKET_NAME, key));
        BufferedReader reader = new BufferedReader(new InputStreamReader(object.getObjectContent()));
        StringBuilder sb = new StringBuilder();
        while (true) {
            String line = reader.readLine();
            if (line == null) break;
            sb.append(line);
        }
        return new Gson().fromJson(sb.toString(), Position.class);
    } catch (Exception e) {
        return null;
    }
}
 
Example 49
Project: agendamlgr   File: Flickr.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> Map<String, T> doRequest(String method, Map<String, String> params) throws IOException {
    params = new HashMap<>(params);
    params.put("api_key", TokensUtils.flickrApiKey);
    params.put("format", "json");
    params.put("method", method);
    String url = buildUrl(params);

    cache.entrySet().stream().filter(entry -> !entry.getValue().isValid()).forEach(entry -> cache.remove(entry.getKey()));
    CachedResult result = cache.get(url);
    if(result != null) return (Map<String, T>) result.result;

    HttpClient httpClient = new DefaultHttpClient();
    HttpUriRequest request = new HttpGet(url);
    HttpResponse res = httpClient.execute(request);

    //We get a JSONP not a json, we must discard two parts from it
    StringBuilder sb = new StringBuilder(" ");
    InputStreamReader inputStreamReader = new InputStreamReader(res.getEntity().getContent());
    while(sb.charAt(sb.length() - 1) != (char) 65535) {
        sb.append((char) inputStreamReader.read());
    }
    inputStreamReader.close();

    String json = sb.deleteCharAt(sb.length() - 1).deleteCharAt(sb.length() - 1).substring(15);
    Map<String, T> jsonParsed = new Gson().fromJson(json, Map.class);
    cache.put(url, new CachedResult((Map<String, Object>) jsonParsed));
    return jsonParsed;
}
 
Example 50
Project: Mastering-Java-EE-Development-with-WildFly   File: MailJobTestCase.java   Source Code and License 5 votes vote down vote up
public String convertStreamToString(InputStream is) {
	BufferedReader reader = new BufferedReader(new InputStreamReader(is));
	StringBuilder sb = new StringBuilder();

	String line = null;
	try {
		while ((line = reader.readLine()) != null) {
			sb.append(line + "\n");
		}
	} catch (IOException e) {
		logger.log(SEVERE, "activiti diagram", e);
	}
	return sb.toString();
}
 
Example 51
Project: apache-tomcat-7.0.73-with-comment   File: SimpleHttpClient.java   Source Code and License 5 votes vote down vote up
public void connect(int connectTimeout, int soTimeout)
       throws UnknownHostException, IOException {
    final String encoding = "ISO-8859-1";
    SocketAddress addr = new InetSocketAddress("localhost", port);
    socket = new Socket();
    socket.setSoTimeout(soTimeout);
    socket.connect(addr,connectTimeout);
    OutputStream os = socket.getOutputStream();
    writer = new OutputStreamWriter(os, encoding);
    InputStream is = socket.getInputStream();
    Reader r = new InputStreamReader(is, encoding);
    reader = new BufferedReader(r);
}
 
Example 52
Project: akita   File: PropertyLoader.java   Source Code and License 5 votes vote down vote up
/**
 * Вспомогательный метод, возвращает свойства из файла /application.properties
 *
 * @return свойства из файла /application.properties
 */
@SneakyThrows(IOException.class)
private static Properties getPropertiesInstance() {
    Properties instance = new Properties();
    try (
            InputStream resourceStream = PropertyLoader.class.getResourceAsStream(PROPERTIES_FILE);
            InputStreamReader inputStream = new InputStreamReader(resourceStream, Charset.forName("UTF-8"))
    ) {
        instance.load(inputStream);
    }
    return instance;
}
 
Example 53
Project: incubator-netbeans   File: CommandlineClient.java   Source Code and License 5 votes vote down vote up
public ISVNAnnotations annotate(BlameCommand blameCmd, CatCommand catCmd) throws SVNClientException {
    exec(blameCmd);
    Annotation[] annotations = blameCmd.getAnnotation();
    exec(catCmd);
    InputStream is = catCmd.getOutput();

    Annotations ret = new Annotations();
    BufferedReader r = new BufferedReader(new InputStreamReader(is));
    try {
        for (Annotation annotation : annotations) {
            String line = null;
            try {
                line = r.readLine();
            } catch (IOException ex) {
                // try at least to return the annotations
                Subversion.LOG.log(Level.INFO, ex.getMessage(), ex);
            }
            annotation.setLine(line);
            ret.addAnnotation(annotation);
        }
    } finally {
        if (r != null) {
            try { r.close(); } catch (IOException e) {}
        }
    }
    return ret;
}
 
Example 54
Project: defense-solutions-proofs-of-concept   File: IdentServer.java   Source Code and License 5 votes vote down vote up
public void run()
{
	if (socket == null) return;
	try
	{
		Socket soc = socket.accept();
		soc.setSoTimeout(60000);

		BufferedReader reader = new BufferedReader(new InputStreamReader(soc.getInputStream()));
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(soc.getOutputStream()));

		String line = reader.readLine();
		if (line != null)
		{
			writer.write(line + " : USERID : UNIX : " + login + "\r\n");
			writer.flush();
			writer.close();
			reader.close();
		}
		socket.close();
	}
	catch (IOException e)
	{
		// log
	}

}
 
Example 55
Project: Hacktoberfest-Mathematics   File: HeronsFormula.java   Source Code and License 5 votes vote down vote up
/**
 * Interacts with the user.
 * 
 * @param args
 *            Command line argument (not used)
 * @throws IOException
 *             if there is an error in input/output
 */
public static void main(String args[]) throws IOException {
	try {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.print("Enter side1:");
		double userInput1 = Double.parseDouble(br.readLine());
		System.out.print("Enter side2:");
		double userInput2 = Double.parseDouble(br.readLine());
		System.out.print("Enter side3:");
		double userInput3 = Double.parseDouble(br.readLine());
		System.out.print("The area is " + calcArea(userInput1, userInput2, userInput3));
	} catch (IllegalArgumentException e) {
		System.out.println("Invalid input.");
	}
}
 
Example 56
Project: tablasco   File: TableTestUtils.java   Source Code and License 5 votes vote down vote up
static String getHtml(TableVerifier verifier, String tag) throws IOException
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(verifier.getOutputFile()), "UTF-8"));
    try
    {
        StringBuilder html = new StringBuilder();
        boolean foundTable = false;
        String line = reader.readLine();
        while (line != null)
        {
            //System.out.println(line);
            if (line.startsWith("</" + tag))
            {
                html.append(line);
                return html.toString();
            }
            if (line.startsWith('<' + tag))
            {
                foundTable = true;
            }
            if (foundTable)
            {
                html.append(line).append('\n');
            }
            line = reader.readLine();
        }
    }
    finally
    {
        reader.close();
    }
    return null;
}
 
Example 57
Project: CSLMusicModStationCreator   File: VanillaCollections.java   Source Code and License 5 votes vote down vote up
private VanillaCollections() {
    Gson gson = new Gson();
    Type songCollectionListType = new TypeToken<List<SongCollection>>(){}.getType();

    try(InputStreamReader r = new InputStreamReader(getClass().getResourceAsStream("/cslmusicmod/stationeditor/VanillaCollections.json"))) {
        collections = gson.fromJson(r, songCollectionListType);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }

    System.out.println("Loaded vanilla collections.");
}
 
Example 58
Project: AquamarineLake   File: DerClient.java   Source Code and License 5 votes vote down vote up
public void get()
{
    try {
        Socket s = new Socket("localhost", 4242);

        BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
        System.out.println(reader.readLine());
        reader.close();
        
    }catch(IOException e){
        e.printStackTrace();
    }
}
 
Example 59
Project: AndroidDevSamples   File: AssetsUtil.java   Source Code and License 5 votes vote down vote up
public static String getStringFromFile(Context context, String fileName) throws IOException {
    InputStream inputStream = context.getAssets().open(fileName);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        sb.append(line).append('\n');
    }
    return sb.toString();
}
 
Example 60
Project: firefox-tv   File: HostScreencapScreenshotStrategy.java   Source Code and License 5 votes vote down vote up
private static String readInput(InputStream stream) throws IOException {
    try (final BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
        final StringBuilder builder = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

        return builder.toString();
    }
}