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   View source code 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: CF-rating-prediction   File: JsonReader.java   View source code 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 3
Project: xtf   File: LogCheckerUtils.java   View source code 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 4
Project: openrouteservice   File: StreamUtility.java   View source code 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 5
Project: KernelHive   File: SourceCodeEditor.java   View source code 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 6
Project: SmingZZick_App   File: YoutubeSmingActivity.java   View source code 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 7
Project: CSLMusicModStationCreator   File: Station.java   View source code 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 8
Project: Tech-Jalsa   File: LocalWebActivity.java   View source code 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 9
Project: spoj   File: LSORT_6_Bottom_Up_Submitted.java   View source code 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 10
Project: JavaRushTasks   File: Solution.java   View source code 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 11
Project: oreilly-reactive-architecture-student   File: CoffeeHouseApp.java   View source code 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 12
Project: homescreenarcade   File: FieldLayout.java   View source code 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 13
Project: PeSanKita-android   File: PreKeyUtil.java   View source code 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 14
Project: hacker-rank   File: Repeated_String.java   View source code 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 15
Project: ZooKeeper   File: GenerateLoad.java   View source code 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 16
Project: mmm   File: WorkflowTask.java   View source code 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 17
Project: JAVA-   File: NativeUtil.java   View source code 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 18
Project: appinventor-extensions   File: YandexTranslate.java   View source code 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 19
Project: jpl-framework   File: JsonUtils.java   View source code 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 20
Project: pokeraidbot   File: LoggingRequestInterceptor.java   View source code 6 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 21
Project: CraftyProfessions   File: ConfigController.java   View source code 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 22
Project: VerveineC-Cpp   File: IncludeConfs.java   View source code 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 23
Project: hacker-rank   File: Java_loops_2.java   View source code 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 24
Project: ExoPlayer-Offline   File: SampleChooserActivity.java   View source code 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 25
Project: geomapapp   File: FossilGlossary.java   View source code 6 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 26
Project: openjdk-jdk10   File: PSPrinterJob.java   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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;
}