Java Examples for java.io.InputStreamReader

The following java examples will help you to understand the usage of java.io.InputStreamReader. These source code samples are taken from different open source projects.

Example 1
Project: android-platform-tools-base-master  File: RetraceMainDexListTest.java View source code
public void testCreateDict() throws IOException {
    InputStream stream = getClass().getResourceAsStream("mapping.txt");
    assertNotNull(stream);
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
    try {
        List<String> lines = Lists.newArrayList();
        String line;
        while ((line = reader.readLine()) != null) {
            lines.add(line);
        }
        Map<String, String> map = RetraceMainDexList.createDict(lines);
        assertEquals("android/support/multidex/MultiDex.class", map.get("android/support/a/a.class"));
        assertEquals("android/support/multidex/MultiDex$V4.class", map.get("android/support/a/d.class"));
    } finally {
        reader.close();
    }
}
Example 2
Project: jeql-master  File: IOUtil.java View source code
public static String readTextFile(String srcName, boolean addEOL) throws IOException {
    InputSource inputSrc = new InputSource(srcName);
    StringBuffer buf = new StringBuffer();
    BufferedReader bufReader = null;
    try {
        InputStream inStream = inputSrc.createStream();
        bufReader = new BufferedReader(new InputStreamReader(inStream));
        String line = "";
        while ((line = bufReader.readLine()) != null) {
            buf.append(line);
            // possibly add EOL char to each line
            if (addEOL)
                buf.append('\n');
        }
    // System.out.println(buf);
    } finally {
        if (bufReader != null)
            bufReader.close();
    }
    // may be empty string if an error occurred
    return buf.toString();
}
Example 3
Project: checkstyle-master  File: InputFinalInTryWithResource.java View source code
public static void test() {
    try {
    } catch (RuntimeException e) {
    }
    try (@NotNull BufferedReader br = new BufferedReader(new InputStreamReader(null, "utf-8"))) {
    } catch (IOException e) {
    }
    try (final BufferedReader br = new BufferedReader(new InputStreamReader(null, "utf-8"))) {
    } catch (IOException e) {
    }
    try (final BufferedReader br = new BufferedReader(new InputStreamReader(null, "utf-8"));
        final BufferedReader br2 = new BufferedReader(new InputStreamReader(null, "utf-8"))) {
    } catch (IOException e) {
    }
}
Example 4
Project: TFC2-master  File: JSONReader.java View source code
public boolean read(File file) {
    try {
        Gson gson = new Gson();
        InputStream stream;
        if (file == null)
            stream = this.getClass().getResourceAsStream(path);
        else if (file.exists()) {
            stream = Files.asByteSource(file).openStream();
        } else {
            return false;
        }
        InputStreamReader sr = new InputStreamReader(stream);
        JsonReader reader = new JsonReader(sr);
        process(reader);
        reader.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return true;
}
Example 5
Project: ocr-tools-master  File: TextMerger.java View source code
@Override
public void merge(List<InputStream> inputs, OutputStream output) {
    try {
        OutputStreamWriter osw = new OutputStreamWriter(output, "UTF-8");
        // Ascii page break dec 12, hex 0c
        char pb = (char) 12;
        // Use the platform dependent separator here
        String seperator = System.getProperty("line.separator");
        int f = 0;
        while (f < inputs.size()) {
            InputStreamReader isr = new InputStreamReader(inputs.get(f), "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                osw.write(line);
                osw.write(seperator);
            }
            //osw.write(pb);
            br.close();
            isr.close();
            f++;
        }
        osw.close();
    } catch (IOException e) {
        throw new IllegalStateException("Error while merging files.", e);
    }
}
Example 6
Project: Mint-Programming-Language-master  File: GetWebsiteContents.java View source code
@Override
public Pointer apply(SmartList<Pointer> args) throws MintException {
    String url = PointerTools.dereferenceString(args.get(0));
    url = addProtocol(url);
    URL u;
    try {
        u = new URL(url);
    } catch (MalformedURLException ex) {
        throw new MintException("Badly formatted URL: " + url);
    }
    BufferedReader website;
    try {
        website = new BufferedReader(new InputStreamReader(u.openStream()));
    } catch (IOException ex) {
        throw new MintException("IO Exception while reading from URL: " + url);
    }
    String lines = "";
    String line = "";
    while (true) {
        try {
            line = website.readLine();
        } catch (IOException ex) {
            throw new MintException("IO Exception while reading from URL: " + url);
        }
        if (line == null)
            break;
        lines += line + "\n";
    }
    try {
        website.close();
    } catch (IOException ex) {
        throw new MintException("IO Exception while closing URL: " + url);
    }
    return Heap.allocateString(lines);
}
Example 7
Project: MyDownload-master  File: Utils.java View source code
public static String getRawData(String string) {
    String dataString = "";
    try {
        URL url;
        url = new URL(string);
        URLConnection conn = url.openConnection();
        // conn.connect();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        byte buffer[] = new byte[1024];
        String readerString;
        while ((readerString = reader.readLine()) != null) {
            dataString += readerString;
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
        log("IOException", "" + e);
    }
    log("getRawData", dataString);
    return dataString;
}
Example 8
Project: nptornews-master  File: FileUtils.java View source code
public static CharSequence readFile(Resources resources, int id) {
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(resources.openRawResource(id)), 8192);
        String line;
        StringBuilder buffer = new StringBuilder();
        while ((line = in.readLine()) != null) {
            buffer.append(line).append('\n');
        }
        // Chomp the last newline
        if (buffer.length() > 0) {
            buffer.deleteCharAt(buffer.length() - 1);
        }
        return buffer;
    } catch (IOException e) {
        return "";
    } finally {
        closeStream(in);
    }
}
Example 9
Project: molgenis-master  File: ScriptTest.java View source code
@Test
public void generateScript() throws IOException {
    FileStore fileStore = new FileStore(System.getProperty("java.io.tmpdir"));
    Map<String, Object> parameterValues = Collections.singletonMap("name", "Piet");
    Script script = mock(Script.class);
    when(script.getContent()).thenReturn("Hey ${name}");
    when(script.generateScript(fileStore, "txt", parameterValues)).thenCallRealMethod();
    File f = script.generateScript(fileStore, "txt", parameterValues);
    assertNotNull(f);
    assertTrue(f.exists());
    assertTrue(f.getPath().endsWith(".txt"));
    String s = FileCopyUtils.copyToString(new InputStreamReader(new FileInputStream(f)));
    assertEquals("Hey Piet", s);
    f.delete();
}
Example 10
Project: liferay-ide-master  File: CompareFileHandler.java View source code
protected File getTemplateFile(IFile currentFile) throws Exception {
    final IProject currentProject = currentFile.getProject();
    final IFile bndfile = currentProject.getFile("bnd.bnd");
    File templateFile = null;
    try (final BufferedReader reader = new BufferedReader(new InputStreamReader(bndfile.getContents()))) {
        String fragment;
        while ((fragment = reader.readLine()) != null) {
            if (fragment.startsWith("Fragment-Host:")) {
                fragment = fragment.substring(fragment.indexOf(":") + 1, fragment.indexOf(";")).trim();
                break;
            }
        }
        final String hookfolder = currentFile.getFullPath().toOSString().substring(currentFile.getFullPath().toOSString().lastIndexOf("META-INF"));
        final IPath templateLocation = GradleCore.getDefault().getStateLocation().append(fragment).append(hookfolder);
        templateFile = new File(templateLocation.toOSString());
        if (!templateFile.exists()) {
            throw new FileNotFoundException("Template not found.");
        }
    }
    return templateFile;
}
Example 11
Project: JPaxos-master  File: MapClient.java View source code
public void run() throws IOException, ReplicationException {
    client = new Client();
    client.connect();
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        String line;
        line = reader.readLine();
        if (line == null) {
            break;
        }
        String[] args = line.trim().split(" ");
        if (args[0].equals("bye")) {
            System.exit(0);
        }
        if (args.length != 2) {
            instructions();
            continue;
        }
        Long key = Long.parseLong(args[0]);
        Long value = Long.parseLong(args[1]);
        MapServiceCommand command = new MapServiceCommand(key, value);
        byte[] response = client.execute(command.toByteArray());
        ByteBuffer buffer = ByteBuffer.wrap(response);
        Long previousValue = buffer.getLong();
        System.out.println(String.format("Previous value for %d was %d", key, previousValue));
    }
}
Example 12
Project: trie4j-master  File: GenHtml.java View source code
public static void main(String[] args) throws Exception {
    String templ = null;
    InputStream temps = GenHtml.class.getResourceAsStream("template.txt");
    try {
        templ = StreamUtil.readAsString(temps, "UTF-8");
    } finally {
        temps.close();
    }
    InputStream res = GenHtml.class.getResourceAsStream("result.txt");
    try {
        BufferedReader r = new BufferedReader(new InputStreamReader(res, "UTF-8"));
        String line = null;
        while ((line = r.readLine()) != null) {
            String[] vals = line.split("[ ]+");
            String name = vals[0].substring(0, vals[0].length() - 1).replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)").trim();
            templ = templ.replaceAll("\\$\\{" + name + "\\.build\\}", String.format("%,d", Integer.valueOf(vals[1].replace(',', ' ').trim()))).replaceAll("\\$\\{" + name + "\\.contains\\}", String.format("%,d", Integer.valueOf(vals[2].replace(',', ' ').trim()))).replaceAll("\\$\\{" + name + "\\.mem\\}", String.format("%.1f", Integer.valueOf(vals[3].replace(',', ' ').trim()) / 1000000.0));
        }
        System.out.println(templ);
    } finally {
        res.close();
    }
}
Example 13
Project: vlc-android-macbuild-master  File: StreamHelper.java View source code
public static String readStreamLineByLine(InputStream inputStream) {
    InputStreamReader reader = new InputStreamReader(inputStream);
    BufferedReader buffReader = new BufferedReader(reader);
    StringBuilder text = new StringBuilder();
    String resultText = null;
    try {
        String line;
        while ((line = buffReader.readLine()) != null) {
            text.append(line);
            text.append('\n');
        }
        resultText = text.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            buffReader.close();
            reader.close();
        } catch (Exception e) {
        }
    }
    return resultText;
}
Example 14
Project: SecurePhoto-master  File: SecurePhotoBaseTests.java View source code
@Test(timeout = 10000)
public void testServerConnectivity() throws Exception {
    Socket clientSocket = null;
    PrintWriter outWriter = null;
    BufferedReader inReader = null;
    String response = null;
    try {
        clientSocket = new Socket("localhost", SPConstants.SERVER_DEFAULT_PORT);
        outWriter = new PrintWriter(clientSocket.getOutputStream(), true);
        inReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        outWriter.println("Testing connectivity");
        response = inReader.readLine();
    } catch (IOException e) {
        throw new Exception("Exception during writing to socket: " + e.getMessage());
    }
    Assert.assertEquals(SPConstants.SERVER_OK_MESSAGE, response);
}
Example 15
Project: tmdm-studio-se-master  File: TestUtil.java View source code
/**
     * Used to read test resource
     * 
     * @param fileName
     * @return
     * @throws Exception
     */
public static String readTestResource(Class cls, String fileName) throws Exception {
    InputStreamReader fr = null;
    BufferedReader br = null;
    try {
        InputStream inputStream = cls.getResourceAsStream(fileName);
        fr = new InputStreamReader(inputStream);
        br = new BufferedReader(fr);
        StringBuffer buffer = new StringBuffer();
        String tmpStr;
        while ((tmpStr = br.readLine()) != null) {
            buffer.append(tmpStr);
        }
        return buffer.toString();
    } finally {
        if (br != null) {
            br.close();
        }
        if (fr != null) {
            fr.close();
        }
    }
}
Example 16
Project: polly-master  File: UTF8Control.java View source code
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException {
    // The below is a copy of the default implementation.
    final String bundleName = toBundleName(baseName, locale);
    //$NON-NLS-1$
    final String resourceName = toResourceName(bundleName, "properties");
    ResourceBundle bundle = null;
    InputStream stream = null;
    if (reload) {
        URL url = loader.getResource(resourceName);
        if (url != null) {
            URLConnection connection = url.openConnection();
            if (connection != null) {
                connection.setUseCaches(false);
                stream = connection.getInputStream();
            }
        }
    } else {
        stream = loader.getResourceAsStream(resourceName);
    }
    if (stream != null) {
        try {
            // Only this line is changed to make it to read properties files as UTF-8.
            bundle = new PropertyResourceBundle(//$NON-NLS-1$
            new InputStreamReader(stream, "UTF-8"));
        } finally {
            stream.close();
        }
    }
    return bundle;
}
Example 17
Project: ldbc_snb_datagen-master  File: EmpiricalDistribution.java View source code
@Override
public ArrayList<Bucket> getBuckets(Configuration conf) {
    fileName = conf.get("ldbc.snb.datagen.generator.distribution.EmpiricalDistribution.fileName");
    ArrayList<Pair<Integer, Integer>> histogram = new ArrayList<Pair<Integer, Integer>>();
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(fileName), "UTF-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            String data[] = line.split(" ");
            histogram.add(new Pair<Integer, Integer>(Integer.parseInt(data[0]), Integer.parseInt(data[1])));
        }
        reader.close();
        return Bucket.bucketizeHistogram(histogram, 1000);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Example 18
Project: many-ql-master  File: CommandLine.java View source code
/**
	 * The main method, which gets executed once this class is run. Enabled the user
	 * to enter a string, which is then parsed and shown as an AST.
	 */
public static void main(String[] args) {
    ErrorEnvironment errorEnvironment = new ErrorEnvironment();
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Press 'x' to stop");
        while (true) {
            System.out.print("Enter a statement:");
            String str = br.readLine();
            if ("x".equalsIgnoreCase(str)) {
                System.out.println("Stopped.");
                break;
            } else {
                QLNode tree = Parser.parse(str);
                if (tree instanceof Statement) {
                    errorEnvironment = TypeChecker.check((Statement) tree, null);
                    PrettyPrinter.print((Statement) tree, new ConsolePrinter());
                }
                if (errorEnvironment.hasErrors()) {
                    System.out.println(errorEnvironment.getErrors());
                    continue;
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 19
Project: couchbase-lite-android-ektorp-master  File: Attachments.java View source code
public void testAttachments() throws IOException {
    HttpClient httpClient = new CBLiteHttpClient(manager);
    CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
    CouchDbConnector dbConnector = dbInstance.createConnector(DEFAULT_TEST_DB, true);
    TestObject test = new TestObject(1, false, "ektorp");
    //create a document
    dbConnector.create(test);
    //attach file to it
    byte[] attach1 = "This is the body of attach1".getBytes();
    ByteArrayInputStream b = new ByteArrayInputStream(attach1);
    AttachmentInputStream a = new AttachmentInputStream("attach", b, "text/plain");
    dbConnector.createAttachment(test.getId(), test.getRevision(), a);
    AttachmentInputStream readAttachment = dbConnector.getAttachment(test.getId(), "attach");
    Assert.assertEquals("text/plain", readAttachment.getContentType());
    Assert.assertEquals("attach", readAttachment.getId());
    BufferedReader br = new BufferedReader(new InputStreamReader(readAttachment));
    Assert.assertEquals("This is the body of attach1", br.readLine());
}
Example 20
Project: snap-desktop-master  File: ImportTrackActionTest.java View source code
@Test
public void testReadTrack() throws Exception {
    CrsGeoCoding geoCoding = new CrsGeoCoding(DefaultGeographicCRS.WGS84, new Rectangle(360, 180), new AffineTransform());
    InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream("TrackData.csv"));
    FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = ImportTrackAction.readTrack(reader, geoCoding);
    assertNotNull(featureCollection);
    assertEquals(23, featureCollection.size());
    // test ordering
    SimpleFeature[] simpleFeatures = featureCollection.toArray(new SimpleFeature[0]);
    assertEquals(23, simpleFeatures.length);
    assertEquals("ID00000000", simpleFeatures[0].getID());
    assertEquals("ID00000011", simpleFeatures[11].getID());
    assertEquals("ID00000022", simpleFeatures[22].getID());
}
Example 21
Project: andlytics-master  File: DataLoader.java View source code
/**
	 * reads the changelog file and returns its content as a String.
	 * 
	 * @param context
	 *            the context.
	 * @param ressourceName
	 *            Name of the ressource to be loaded
	 * @return content of the ressource as a String.
	 * @throws IOException
	 *             if errors occur while reading the changelog file
	 */
public static String loadData(final Context context, final String ressourceName) throws IOException {
    int resourceIdentifier = context.getApplicationContext().getResources().getIdentifier(ressourceName, "raw", context.getApplicationContext().getPackageName());
    if (resourceIdentifier != 0) {
        InputStream inputStream = context.getApplicationContext().getResources().openRawResource(resourceIdentifier);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        String line;
        StringBuffer data = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            data.append(line);
        }
        reader.close();
        return data.toString();
    }
    return null;
}
Example 22
Project: cms-ce-master  File: TranslationReaderTest.java View source code
@Test
public void testTranslate() throws Exception {
    Map<String, String> translations = new HashMap<String, String>();
    translations.put("%__example__%", "alert");
    final String xslFilename = getClass().getName().replace('.', '/') + ".xsl";
    final InputStream xslInputStream = getClass().getClassLoader().getResourceAsStream(xslFilename);
    final Reader reader = new InputStreamReader(xslInputStream, Charset.forName("UTF-8"));
    final TranslationReader translationReader = new TranslationReader(translations, reader);
    final int length = xslInputStream.available();
    final char[] xslBuffer = new char[length];
    translationReader.read(xslBuffer, 0, length);
    final String xslString = new String(xslBuffer);
    assertFalse("The XSL contains untranslated string", xslString.contains("%__example__%"));
}
Example 23
Project: cbe-master  File: FileLoader2.java View source code
public List<String> loadLines(String filename) {
    BufferedReader bufferedReader = null;
    InputStream inputStream = null;
    InputStreamReader inputStreamReader = null;
    List<String> lines = new ArrayList<String>();
    try {
        inputStream = getClass().getClassLoader().getResourceAsStream(filename);
        inputStreamReader = new InputStreamReader(inputStream);
        bufferedReader = new BufferedReader(inputStreamReader);
        String line = null;
        while ((line = bufferedReader.readLine()) != null) lines.add(line);
        inputStream.close();
        inputStreamReader.close();
        bufferedReader.close();
    } catch (IOException e) {
        System.err.println("Failed to read and/or close file:");
        e.printStackTrace();
    }
    return lines;
}
Example 24
Project: quickml-master  File: InstanceLoader.java View source code
public static List<ClassifierInstance> getAdvertisingInstances() {
    CSVToInstanceReader csvToInstanceReader = new CSVToInstanceReaderBuilder().collumnNameForLabel("outcome").buildCsvReader();
    List<ClassifierInstance> advertisingInstances;
    try {
        final BufferedReader br = new BufferedReader(new InputStreamReader((new GZIPInputStream(InstanceLoader.class.getResourceAsStream("advertisingData.csv.gz")))));
        advertisingInstances = csvToInstanceReader.readCsvFromReader(br);
    } catch (Exception e) {
        logger.error("failed to get advertising instances", e);
        throw new RuntimeException("failed to get advertising instances");
    }
    return advertisingInstances;
}
Example 25
Project: android_platform_libcore-master  File: OldInputStreamReaderTest.java View source code
public void testInputStreamReaderSuccessiveReads() throws IOException {
    byte[] data = new byte[8192 * 2];
    // 116 = ISO-8859-1 value for 't'
    Arrays.fill(data, (byte) 116);
    ByteArrayInputStream bis = new ByteArrayInputStream(data);
    InputStreamReader isr = new InputStreamReader(bis, "ISO-8859-1");
    // One less than the InputStreamReader.BUFFER_SIZE
    char[] buf = new char[8191];
    int bytesRead = isr.read(buf, 0, buf.length);
    if (bytesRead == -1) {
        throw new RuntimeException();
    }
    bytesRead = isr.read(buf, 0, buf.length);
    if (bytesRead == -1) {
        throw new RuntimeException();
    }
}
Example 26
Project: ARTPart-master  File: InputStreamReaderTest.java View source code
/**
     * java.io.InputStreamReader#close()
     */
public void test_close() throws IOException {
    is.close();
    try {
        is.read();
        fail("Should throw IOException");
    } catch (IOException e) {
    }
    reader.close();
    try {
        reader.ready();
        fail("Should throw IOException");
    } catch (IOException e) {
    }
    // Should be a no-op
    reader.close();
    // Tests after reader closed
    in = new BufferedInputStream(this.getClass().getClassLoader().getResourceAsStream("org/apache/harmony/luni/tests/java/io/testfile-utf8.txt"));
    reader = new InputStreamReader(in, "utf-8");
    in.close();
    try {
        int count = reader.read(new char[1]);
        fail("count:" + count);
    } catch (IOException e) {
    }
    try {
        reader.read();
        fail();
    } catch (IOException e) {
    }
    assertFalse(reader.ready());
    Charset cs = Charset.forName("utf-8");
    assertEquals(cs, Charset.forName(reader.getEncoding()));
}
Example 27
Project: openmap-master  File: GLOBEData.java View source code
public void readDataFromStream(InputStream istream) throws IOException {
    int lines_read = 0;
    BufferedReader buffstream = new BufferedReader(new InputStreamReader(istream), 65536);
    while (true) {
        String line = buffstream.readLine();
        if (line == null)
            break;
        line = line.trim();
        // ignore comments
        if (line.length() == 0 || line.startsWith("#")) {
            continue;
        }
        parseDataFromStream(line);
        lines_read++;
    //          if (lines_read % 1000 == 0) {
    //              System.out.println("Read " + lines_read + " lines");
    //          }
    }
//      System.out.println("Read " + lines_read + " total lines");
}
Example 28
Project: WS171-development-master  File: ProfilesLoader.java View source code
public static double[] loadProfiles(Device device, Window window, String params) {
    Socket socket = null;
    BufferedReader in = null;
    BufferedWriter out = null;
    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress("127.0.0.1", DeviceBridge.getDeviceLocalPort(device)));
        out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out.write("PROFILE " + window.encode() + " " + params);
        out.newLine();
        out.flush();
        String response = in.readLine();
        String[] data = response.split(" ");
        double[] profiles = new double[data.length];
        for (int i = 0; i < data.length; i++) {
            // convert to ms
            profiles[i] = (Long.parseLong(data[i]) / 1000.0) / 1000.0;
        }
        return profiles;
    } catch (IOException e) {
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return null;
}
Example 29
Project: Strata-master  File: JodaBeanParameterConverter.java View source code
@Override
public T convert(String fileName) {
    try {
        File f = new File(fileName);
        try (Reader reader = new InputStreamReader(new FileInputStream(f), StandardCharsets.UTF_8)) {
            return JodaBeanSer.PRETTY.xmlReader().read(reader, getExpectedType());
        }
    } catch (RuntimeExceptionIOException |  ex) {
        if (ex instanceof FileNotFoundException || ex.getCause() instanceof FileNotFoundException) {
            throw new ParameterException(Messages.format("File not found: {}", fileName));
        }
        throw new ParameterException(Messages.format("Invalid file: {}" + System.lineSeparator() + "Exception: {}", fileName, ex.getMessage()));
    }
}
Example 30
Project: yarn-comment-master  File: WhoClient.java View source code
public static void main(String[] args) {
    try {
        if (args.length != 1) {
            System.err.println("Usage: <URL>");
            System.exit(-1);
        }
        AuthenticatedURL.Token token = new AuthenticatedURL.Token();
        URL url = new URL(args[0]);
        HttpURLConnection conn = new AuthenticatedURL().openConnection(url, token);
        System.out.println();
        System.out.println("Token value: " + token);
        System.out.println("Status code: " + conn.getResponseCode() + " " + conn.getResponseMessage());
        System.out.println();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = reader.readLine();
            while (line != null) {
                System.out.println(line);
                line = reader.readLine();
            }
            reader.close();
        }
        System.out.println();
    } catch (Exception ex) {
        System.err.println("ERROR: " + ex.getMessage());
        System.exit(-1);
    }
}
Example 31
Project: SRE-RoboCode-master  File: JarJarTest.java View source code
@Test
public void run() throws IOException {
    String clas = "Hello.class";
    String inner = "Inner.jar";
    String outer = "file:src/test/resources/Outer.jar";
    final String separ = "!/";
    URL u = new URL("jar:jarjar:" + outer + JarJar.SEPARATOR + inner + separ + clas);
    final URLConnection urlConnection = URLJarCollector.openConnection(u);
    final InputStream inputStream = urlConnection.getInputStream();
    InputStreamReader isr = new InputStreamReader(inputStream);
    char[] c = new char[4];
    int len = isr.read(c);
    Assert.assertEquals(len, 4);
    Assert.assertEquals('T', c[0]);
    Assert.assertEquals('e', c[1]);
    Assert.assertEquals('s', c[2]);
    Assert.assertEquals('t', c[3]);
    Assert.assertFalse(isr.ready());
    isr.close();
    inputStream.close();
}
Example 32
Project: wpcleaner-master  File: DumpProcessor.java View source code
/**
   * Process a wiki dump.
   * 
   * @param file File containing the wiki dump.
   */
public void processDump(File file) {
    if (file == null) {
        return;
    }
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    BZip2CompressorInputStream bzis = null;
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        fis = new FileInputStream(file);
        bis = new BufferedInputStream(fis);
        bzis = new BZip2CompressorInputStream(bis);
        Reader reader = new InputStreamReader(bzis, "UTF-8");
        InputSource is = new InputSource(reader);
        DumpHandler dh = new DumpHandler();
        dh.setPageProcessor(pageProcessor);
        parser.parse(is, dh);
    } catch (Exception e) {
        log.error("Error processing dump file", e);
    } finally {
        try {
            if (bzis != null) {
                bzis.close();
            }
            if (bis != null) {
                bis.close();
            }
            if (fis != null) {
                fis.close();
            }
        } catch (Exception e) {
            log.error("Error closing dump file", e);
        }
    }
}
Example 33
Project: vibe-master  File: TrackEventsExample.java View source code
public static void main(String[] args) throws IOException {
    Vibe vibe = DefaultVibe.builder().setBackends(new LoggingBackend(), new JmxBackend()).setSampleInterval(10, TimeUnit.SECONDS).build();
    // The events object used to send the events
    Events<AccessEvent> accessEvents = vibe.events(AccessEvent.class).at("auth/events").setSeverity(EventSeverity.INFO).export();
    // Sampling the number of events sent during 10 second interval
    vibe.sample(accessEvents.getEventsProbe()).at("auth/sampled").export();
    // Probe for the total number of events received
    Probe<Long> total = vibe.probe(accessEvents.getTotalEventsProbe()).at("auth/total").export();
    System.out.println("Press enter to send an event, type quit to quit");
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String line;
    while ((line = reader.readLine()) != null) {
        if ("quit".equals(line))
            System.exit(0);
        // Send an example event
        accessEvents.register(new AccessEvent());
        // Print the total
        System.out.println("Total number of events sent: " + total.read());
    }
}
Example 34
Project: bigpetstore-master  File: BigPetStoreMahoutIT.java View source code
public static void assertOutput(Path base, Function<String, Boolean> validator) throws Exception {
    FileSystem fs = FileSystem.getLocal(new Configuration());
    FileStatus[] files = fs.listStatus(base);
    // print out all the files.
    for (FileStatus stat : files) {
        System.out.println(stat.getPath() + "  " + stat.getLen());
    }
    Path p = new Path(base, "part-r-00000");
    BufferedReader r = new BufferedReader(new InputStreamReader(fs.open(p)));
    // line:{"product":"big chew toy","count":3}
    while (r.ready()) {
        String line = r.readLine();
        log.info("line:" + line);
        System.out.println("line:" + line);
        Assert.assertTrue("validationg line : " + line, validator.apply(line));
    }
}
Example 35
Project: tcf-master  File: FSCacheCommitTest.java View source code
protected String readFileContent() throws IOException {
    //$NON-NLS-1$ //$NON-NLS-2$
    printDebugMessage("Read file " + testFile.getLocation() + "...");
    URL url = testFile.getLocationURL();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception e) {
            }
        }
    }
}
Example 36
Project: speechalyzer-master  File: EmlUtils.java View source code
public static String postAudioToEml(String filename, String emlURL) {
    String result = "";
    try {
        logger.debug("requesting: " + emlURL + " with file: " + filename);
        ClientHttpRequest chr = new ClientHttpRequest(emlURL);
        chr.setParameter("audio", new File(filename));
        InputStream is = chr.post();
        final char[] buffer = new char[0x10000];
        StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(is, FileUtil.ENCODING_ISO8859_1);
        int read;
        do {
            read = in.read(buffer, 0, buffer.length);
            if (read > 0) {
                out.append(buffer, 0, read);
            }
        } while (read >= 0);
        result = out.toString();
        logger.debug("result: " + result);
    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    }
    return result;
}
Example 37
Project: AndroidBinding-master  File: TemplateWriter.java View source code
public static String make(InputStream template, Hashtable<String, String> data) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(template));
    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        builder.append(line + "\n");
    }
    String content = builder.toString();
    for (Entry<String, String> entry : data.entrySet()) {
        String replace = "${" + entry.getKey() + "}";
        //			System.out.println("entry: " + replace + ": " + entry.getValue());
        content = content.replace(replace, entry.getValue());
    }
    return content;
}
Example 38
Project: dashboard-master  File: TwitterOAuthRetriever.java View source code
public static void main(String args[]) throws Exception {
    String oAuthConsumerKey = args[0];
    String oAuthConsumerSecret = args[1];
    // The factory instance is re-useable and thread safe.
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(oAuthConsumerKey, oAuthConsumerSecret);
    RequestToken requestToken = twitter.getOAuthRequestToken("oob");
    AccessToken accessToken = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
        System.out.println("Open the following URL and grant access to your account:");
        System.out.println(requestToken.getAuthorizationURL());
        System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
        String pin = br.readLine();
        try {
            if (pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                System.out.println("Unable to get the access token.");
            } else {
                te.printStackTrace();
            }
        }
    }
    // persist to the accessToken for future reference.
    storeAccessToken(twitter.verifyCredentials().getId(), accessToken);
    Status status = twitter.updateStatus(args[0]);
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
    System.exit(0);
}
Example 39
Project: cloudtm-data-platform-master  File: FenixCodeGeneratorReadFromRsWithConverterClassParamOneBoxPerObject.java View source code
public static String read(final InputStreamReader fileReader) throws IOException {
    try {
        char[] buffer = new char[4096];
        final StringBuilder fileContents = new StringBuilder();
        for (int n = 0; (n = fileReader.read(buffer)) != -1; fileContents.append(buffer, 0, n)) ;
        return fileContents.toString();
    } finally {
        fileReader.close();
    }
}
Example 40
Project: Curators-Workbench-master  File: StagingAreaPreferenceInitializer.java View source code
@Override
public void initializeDefaultPreferences() {
    URL cUrl = StagingPlugin.getDefault().getBundle().getResource("initialStagingAreasConfig.json");
    StringBuilder sb = new StringBuilder();
    try (BufferedReader r = new BufferedReader(new InputStreamReader(cUrl.openStream()))) {
        for (String line = r.readLine(); line != null; line = r.readLine()) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        throw new Error("Unexpected issue loading JSON file", e);
    }
    String localStagingConfig = sb.toString();
    IEclipsePreferences prefs = DefaultScope.INSTANCE.getNode(StagingPlugin.PLUGIN_ID);
    prefs.put(StagingPlugin.LOCAL_STAGING_CONFIG_JSON, localStagingConfig);
}
Example 41
Project: bus-n-train-master  File: TrainTestActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Reader reader = null;
    List<StationModel> stations = null;
    try {
        reader = new InputStreamReader(new URL(URL_RED_STATIONS_TXT).openStream());
        stations = new Gson().fromJson(reader, StationModel.TYPE);
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                reader = null;
            }
        }
    }
    if (stations != null) {
        Log.i(TAG, stations.toString());
    } else {
        Log.e(TAG, "no stations available.");
    }
//	   setContentView(view)
}
Example 42
Project: cdo-master  File: StreamWrapperTest.java View source code
@SuppressWarnings("resource")
public void testXORStreams() throws Exception {
    int[] key = { 1, 2, 3, 4 };
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    XOROutputStream xorOutputStream = new XOROutputStream(byteArrayOutputStream, key);
    PrintStream printStream = new PrintStream(xorOutputStream);
    printStream.println("Hello world!");
    printStream.println("Hello world!");
    XORInputStream xorInputStream = new XORInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), key);
    InputStreamReader inputStreamReader = new InputStreamReader(xorInputStream);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    assertEquals("Hello world!", bufferedReader.readLine());
    assertEquals("Hello world!", bufferedReader.readLine());
}
Example 43
Project: geoserver-enterprise-master  File: GetSchema.java View source code
/**
     * Fetches named schema and writes it to the response stream
     *
     * @param request
     * @param response
     */
@SuppressWarnings("unchecked")
public void run(HttpServletRequest request, HttpServletResponse response) {
    String name = null;
    // Iterate over all parameters looking case insensitively for 'identifier'
    for (Enumeration<String> a = request.getParameterNames(); a.hasMoreElements(); ) {
        String i = a.nextElement();
        if ("identifier".equalsIgnoreCase(i)) {
            name = request.getParameter(i);
            break;
        }
    }
    if (null == name) {
        throw new WPSException("NoApplicableCode", "No Identifier key and value.");
    }
    InputStream stream = org.geoserver.wps.schemas.Stub.class.getResourceAsStream(name);
    if (null == stream) {
        throw new WPSException("NoApplicableCode", "No Schema '" + name + "'.");
    }
    BufferedReader bufReader = new BufferedReader(new InputStreamReader(stream));
    StringBuilder schema = new StringBuilder();
    String line = null;
    try {
        while (null != (line = bufReader.readLine())) {
            schema.append(line + "\n");
        }
        bufReader.close();
    } catch (Exception e) {
        throw new WPSException("NoApplicableCode", "Error reading schema on server.");
    }
    response.setContentType("text/xml");
    try {
        response.getOutputStream().print(schema.toString());
    } catch (Exception e) {
        throw new WPSException("NoApplicableCode", "Could not write schema to output.");
    }
    return;
}
Example 44
Project: btpka3.github.com-master  File: MyEchoServer.java View source code
@Override
public void run() {
    try {
        Reader reader = new InputStreamReader(new BufferedInputStream(socket.getInputStream()), "UTF-8");
        Writer writer = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
        int i = 0;
        // blocking read
        while ((i = reader.read()) != -1) {
            char c = (char) i;
            System.out.println("<<< " + socket + " : '" + c + "'");
            writer.write(c);
            writer.flush();
            System.out.println(">>> " + socket + " : '" + c + "'");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 45
Project: ARKOST-master  File: jsParser.java View source code
public JSONObject AmbilJson(String url) {
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
        Log.e("UNSUPPORTED", e.getMessage());
    } catch (ClientProtocolException e) {
        Log.e("CLIENT", e.getMessage());
    } catch (IOException e) {
        Log.e("IO", e.getMessage());
    }
    try {
        Log.d("TEST", "BEFORE START");
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        Log.d("TEST", "START");
        while ((line = reader.readLine()) != null) {
            sb.append(line);
            Log.d("TEST", line);
        }
        Log.d("TEST", "END");
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("JSON Parser", "Error pasing data " + e.toString() + e.getMessage());
    }
    try {
        jobj = new JSONObject(json);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return jobj;
}
Example 46
Project: expenditures-master  File: FileUtil.java View source code
public static String[] readResource(final String resource) {
    final InputStream inputStream = FileUtil.class.getResourceAsStream(resource);
    try {
        final InputStreamReader fileReader = new InputStreamReader(inputStream, "UTF-8");
        try {
            char[] buffer = new char[4096];
            final StringBuilder fileContents = new StringBuilder();
            for (int n = 0; (n = fileReader.read(buffer)) != -1; fileContents.append(buffer, 0, n)) {
                ;
            }
            return fileContents.toString().split("\n");
        } catch (final IOException ex) {
            throw new Error(ex);
        } finally {
            try {
                fileReader.close();
            } catch (final IOException ex) {
                throw new Error(ex);
            }
        }
    } catch (final UnsupportedEncodingException ex) {
        throw new Error(ex);
    }
}
Example 47
Project: plusTimer-master  File: ChangelogDialog.java View source code
@SuppressLint("InflateParams")
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final View customView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_webview, null);
    MaterialDialog dialog = new MaterialDialog.Builder(getActivity()).title(R.string.changelog).customView(customView, false).positiveText(android.R.string.ok).build();
    final WebView webView = (WebView) customView.findViewById(R.id.webview);
    try {
        // Load from changelog.html in the assets folder
        StringBuilder buf = new StringBuilder();
        InputStream html = getResources().openRawResource(R.raw.changelog);
        BufferedReader in = new BufferedReader(new InputStreamReader(html));
        String str;
        while ((str = in.readLine()) != null) buf.append(str);
        in.close();
        // Inject color values for WebView body background and links
        webView.loadData(buf.toString(), "text/html; charset=UTF-8", null);
    } catch (Throwable e) {
        webView.loadData("<h1>Unable to load</h1><p>" + e.getLocalizedMessage() + "</p>", "text/html", "UTF-8");
    }
    return dialog;
}
Example 48
Project: cm4mm-updater-master  File: SysUtils.java View source code
/**
     * Returns a SystemProperty
     *
     * @param propName The Property to retrieve
     * @return The Property, or NULL if not found
     */
public static String getSystemProperty(String propName) {
    String line;
    BufferedReader input = null;
    try {
        Process p = Runtime.getRuntime().exec("getprop " + propName);
        input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
        line = input.readLine();
        input.close();
    } catch (IOException ex) {
        Log.e(TAG, "Unable to read sysprop " + propName, ex);
        return null;
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                Log.e(TAG, "Exception while closing InputStream", e);
            }
        }
    }
    return line;
}
Example 49
Project: javainstaller-master  File: Update.java View source code
@Override
public void run() {
    try {
        udate = false;
        URL url = new URL((Checkforfile.getArch().equals("arm")) ? "http://borcteam.bplaced.net/files/java/arm/versions" : "http://borcteam.bplaced.net/files/java/versions");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        // download the file
        InputStream input = connection.getInputStream();
        BufferedReader read = new BufferedReader(new InputStreamReader(input));
        for (int i = 0; i < 10; i++) {
            String version = read.readLine();
            String oldversion = MainActivity.checks[i].getversion();
            System.out.println(version + " old: " + oldversion);
            if (oldversion.equals(version) || !MainActivity.checks[i].installed) {
                update[i] = false;
            } else {
                udate = true;
                update[i] = true;
                updatetext[i] = "update available: " + oldversion + " to " + version;
            }
        }
        input.close();
        final String toast;
        if (udate) {
            toast = "new uptates";
        } else {
            toast = "nothing new";
        }
        activity.runOnUiThread(new Runnable() {

            public void run() {
                activity.update();
                Toast.makeText(MainActivity.context, toast, Toast.LENGTH_LONG).show();
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 50
Project: geotools-old-master  File: ExecuteOnlineTest.java View source code
/*
     * Try doing an execute request from the example xsd and parse it
     */
public void testExecute() throws IOException, SAXException, ParserConfigurationException {
    URL url = new URL("http://schemas.opengis.net/wps/1.0.0/examples/51_wpsExecute_request_ResponseDocument.xml");
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        org.geotools.xml.Parser parser = new org.geotools.xml.Parser(new WPSConfiguration());
        Object obj = parser.parse(in);
        assertNotNull(obj);
    } catch (UnknownHostException notFound) {
        System.out.println("WARNING " + notFound.getClass().getName() + ":" + notFound.getMessage());
        System.out.println("the server was not found - you may be running" + "in offline mode - or behind a firewall?" + "in anycase this represents a failure of network" + "and not our software");
    }
}
Example 51
Project: astrid-master  File: SrtParser.java View source code
public static TextTrackImpl parse(InputStream is) throws IOException {
    LineNumberReader r = new LineNumberReader(new InputStreamReader(is, "UTF-8"));
    TextTrackImpl track = new TextTrackImpl();
    String numberString;
    while ((numberString = r.readLine()) != null) {
        String timeString = r.readLine();
        String lineString = "";
        String s;
        while (!((s = r.readLine()) == null || s.trim().equals(""))) {
            lineString += s + "\n";
        }
        long startTime = parse(timeString.split("-->")[0]);
        long endTime = parse(timeString.split("-->")[1]);
        track.getSubs().add(new TextTrackImpl.Line(startTime, endTime, lineString));
    }
    return track;
}