Java Examples for java.io.BufferedReader

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

Example 1
Project: schach-master  File: ListReader.java View source code
public static ArrayList<String> loadStrings(File aFile) {
    ArrayList<String> pVec = new ArrayList<String>();
    if (!aFile.exists())
        return pVec;
    try {
        BufferedReader pReader = new BufferedReader(new FileReader(aFile));
        String pLine;
        while ((pLine = pReader.readLine()) != null) {
            pLine = pLine.trim();
            if (pLine.startsWith("#") || pLine.equals(""))
                continue;
            pVec.add(pLine);
        }
        pReader.close();
    } catch (IOException aE) {
        aE.printStackTrace();
    }
    return pVec;
}
Example 2
Project: android-libcore64-master  File: BufferedReaderTest.java View source code
/**
	 * @tests java.io.BufferedReader#mark(int)
	 */
public void test_markI() throws IOException {
    // Test for method void java.io.BufferedReader.mark(int)
    char[] buf = null;
    br = new BufferedReader(new Support_StringReader(testString));
    br.skip(500);
    br.mark(1000);
    br.skip(250);
    br.reset();
    buf = new char[testString.length()];
    br.read(buf, 0, 500);
    assertTrue("Failed to set mark properly", testString.substring(500, 1000).equals(new String(buf, 0, 500)));
    try {
        br = new BufferedReader(new Support_StringReader(testString), 800);
        br.skip(500);
        br.mark(250);
        br.read(buf, 0, 1000);
        br.reset();
        fail("Failed to invalidate mark properly");
    } catch (IOException x) {
    }
    char[] chars = new char[256];
    for (int i = 0; i < 256; i++) chars[i] = (char) i;
    Reader in = new BufferedReader(new Support_StringReader(new String(chars)), 12);
    in.skip(6);
    in.mark(14);
    in.read(new char[14], 0, 14);
    in.reset();
    assertTrue("Wrong chars", in.read() == (char) 6 && in.read() == (char) 7);
    in = new BufferedReader(new Support_StringReader(new String(chars)), 12);
    in.skip(6);
    in.mark(8);
    in.skip(7);
    in.reset();
    assertTrue("Wrong chars 2", in.read() == (char) 6 && in.read() == (char) 7);
    BufferedReader br = new BufferedReader(new StringReader("01234"), 2);
    br.mark(3);
    char[] carray = new char[3];
    int result = br.read(carray);
    assertEquals(3, result);
    assertEquals("Assert 0:", '0', carray[0]);
    assertEquals("Assert 1:", '1', carray[1]);
    assertEquals("Assert 2:", '2', carray[2]);
    assertEquals("Assert 3:", '3', br.read());
    br = new BufferedReader(new StringReader("01234"), 2);
    br.mark(3);
    carray = new char[4];
    result = br.read(carray);
    assertEquals("Assert 4:", 4, result);
    assertEquals("Assert 5:", '0', carray[0]);
    assertEquals("Assert 6:", '1', carray[1]);
    assertEquals("Assert 7:", '2', carray[2]);
    assertEquals("Assert 8:", '3', carray[3]);
    assertEquals("Assert 9:", '4', br.read());
    assertEquals("Assert 10:", -1, br.read());
    BufferedReader reader = new BufferedReader(new StringReader("01234"));
    reader.mark(Integer.MAX_VALUE);
    reader.read();
    reader.close();
}
Example 3
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 4
Project: sonar-java-master  File: TryWithResourcesCheck.java View source code
void foo(String fileName) {
    FileReader fr = null;
    BufferedReader br = null;
    try {
        // Noncompliant [[sc=5;ec=8;secondary=9,10]] {{Change this "try" to a try-with-resources.}}
        fr = new FileReader(fileName);
        br = new BufferedReader(fr);
        return br.readLine();
    } catch (Exception e) {
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
            }
        }
        if (fr != null) {
            try {
                br.close();
            } catch (IOException e) {
            }
        }
    }
    try {
        // compliant, no finally block so let's rely on unclosed resource rule
        fr = new FileReader(fileName);
    } catch (Exception e) {
    }
    try (FileReader fr = new FileReader(fileName);
        BufferedReader br = new BufferedReader(fr)) {
        // compliant
        return br.readLine();
    } catch (Exception e) {
    }
}
Example 5
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 6
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 7
Project: jeboorker-master  File: TextUtils.java View source code
public static StringBuilder removePageNumbers(String text) {
    StringBuilder result = new StringBuilder();
    try (BufferedReader textReader = new BufferedReader(new StringReader(text))) {
        String line;
        for (int i = 1; (line = trim(textReader.readLine())) != null; ) {
            int num = NumberUtils.toInt(line, -1);
            if (num == i) {
                i++;
                continue;
            }
            result.append(line).append(StringUtil.NEW_LINE);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return result;
}
Example 8
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 9
Project: extFM-Tooling-master  File: MtextDebugCommunicationHelper.java View source code
/**
	 * Sends a message using the given stream and waits for an answer.
	 * 
	 * @param messageType the type of message to send
	 * @param stream the stream to send the message to
	 * @param reader the reader to obtain the answer from
	 * @param parameters additional parameter to send
	 * 
	 * @return the answer that is received
	 */
public org.feature.multi.perspective.mapping.viewmapping.resource.mtext.debug.MtextDebugMessage sendAndReceive(org.feature.multi.perspective.mapping.viewmapping.resource.mtext.debug.MtextDebugMessage message, java.io.PrintStream stream, java.io.BufferedReader reader) {
    synchronized (stream) {
        sendEvent(message, stream);
        org.feature.multi.perspective.mapping.viewmapping.resource.mtext.debug.MtextDebugMessage response = receive(reader);
        return response;
    }
}
Example 10
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 11
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 12
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 13
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 14
Project: JPaxos-master  File: averageFromRanges.java View source code
public static void main(String[] args) throws Throwable {
    Locale.setDefault(Locale.ENGLISH);
    for (String arg : args) {
        BufferedReader br = new BufferedReader(new FileReader(arg));
        while (true) {
            String line = br.readLine();
            if (line == null)
                break;
            String[] tokens = line.split(", *");
            if (!tokens[0].matches("^[0-9][0-9]*$"))
                continue;
            Long time = Long.parseLong(tokens[0]);
            ArrayList<DataPoint> list = new ArrayList<DataPoint>();
            for (int i = 1; i < tokens.length; ++i) list.add(new DataPoint());
            times.put(time, list);
        }
        br.close();
    }
    for (String arg : args) {
        Long prev = 0L;
        BufferedReader br = new BufferedReader(new FileReader(arg));
        while (true) {
            String line = br.readLine();
            if (line == null)
                break;
            line = line.trim();
            String[] tokens = line.split(",");
            if (!tokens[0].trim().matches("^[0-9][0-9]*$")) {
                continue;
            }
            Long time = Long.parseLong(tokens[0].trim());
            SortedMap<Long, List<DataPoint>> affected = times.subMap(prev + 1, time + 1);
            for (List<DataPoint> points : affected.values()) {
                for (int i = 1; i < tokens.length; ++i) {
                    points.get(i - 1).add(Double.parseDouble(tokens[i].trim()));
                }
            }
            prev = time;
        }
        br.close();
    }
    for (Entry<Long, List<DataPoint>> entry : times.entrySet()) {
        System.out.printf("%d", entry.getKey());
        for (DataPoint point : entry.getValue()) {
            System.out.printf(",%f", point.mean());
        }
        System.out.println();
    }
}
Example 15
Project: traffic-balance-master  File: JSONRPCSkeleton.java View source code
void processRequest(BufferedReader in, PrintWriter out) {
    JSONObject jsonResponse = new JSONObject();
    try {
        JSONObject jsonRequest = new JSONObject(in.readLine());
        String methodName = jsonRequest.getString(JSONRPCConstants.METHOD_KEY);
        JSONArray params = jsonRequest.getJSONArray(JSONRPCConstants.PARAMS_KEY);
        JSONObject result = invoke(methodName, params);
        jsonResponse.put(JSONRPCConstants.RESULT_KEY, result);
    } catch (Exception ex) {
        try {
            jsonResponse.put(JSONRPCConstants.ERROR_KEY, ex.getMessage());
        } catch (JSONException e) {
            throw new RuntimeException("Error while creating response", e);
        }
    }
    out.println(jsonResponse.toString());
}
Example 16
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 17
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 18
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 19
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 20
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 21
Project: Tank-master  File: CustomInputStream.java View source code
public static File getNewFile(File file) throws IOException {
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    List<String> contents = new ArrayList<String>();
    String s;
    int i = 0;
    while ((s = br.readLine()) != null) {
        contents.add(s);
        if (s.endsWith(">")) {
            if (i == 0) {
                contents.add(startTag);
            }
            i++;
        }
    }
    contents.add(endTag);
    br.close();
    fr.close();
    File tmpFile = File.createTempFile("temporary", ".xml");
    FileWriter fw = new FileWriter(tmpFile);
    BufferedWriter bw = new BufferedWriter(fw);
    for (String string : contents) {
        bw.write(string);
        System.out.println(string);
    }
    bw.close();
    fw.close();
    return tmpFile;
}
Example 22
Project: Desktop-master  File: ZoteroAnnoteFieldRemoverAction.java View source code
@Override
public void performAction(File file) {
    StringBuffer sb = new StringBuffer();
    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        while ((line = br.readLine()) != null) {
            if (line.trim().startsWith("annote = {")) {
                while (!line.endsWith("},") && !line.endsWith("}")) {
                    line = br.readLine();
                }
            } else {
                sb.append(line);
                sb.append("\r\n");
            }
        }
        br.close();
        FileWriter fw = new FileWriter(file);
        fw.write(sb.toString());
        fw.close();
    } catch (IOException e) {
        DocearLogger.error(e);
    }
}
Example 23
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 24
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 25
Project: GATECH-master  File: CSVDataSetReader.java View source code
@Override
public DataSet read() throws Exception {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    List<Instance> data = new ArrayList<Instance>();
    Pattern pattern = Pattern.compile("[ ,]+");
    while ((line = br.readLine()) != null) {
        String[] split = pattern.split(line.trim());
        double[] input = new double[split.length];
        for (int i = 0; i < input.length; i++) {
            input[i] = Double.parseDouble(split[i]);
        }
        Instance instance = new Instance(input);
        data.add(instance);
    }
    br.close();
    Instance[] instances = (Instance[]) data.toArray(new Instance[0]);
    DataSet set = new DataSet(instances);
    set.setDescription(new DataSetDescription(set));
    return set;
}
Example 26
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 27
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 28
Project: clinic-softacad-master  File: SingleLineSqlCommandExtractor.java View source code
@Override
public String[] extractCommands(Reader reader) {
    BufferedReader bufferedReader = new BufferedReader(reader);
    List<String> statementList = new LinkedList<String>();
    try {
        for (String sql = bufferedReader.readLine(); sql != null; sql = bufferedReader.readLine()) {
            String trimmedSql = sql.trim();
            if (StringHelper.isEmpty(trimmedSql) || isComment(trimmedSql)) {
                continue;
            }
            if (trimmedSql.endsWith(";")) {
                trimmedSql = trimmedSql.substring(0, trimmedSql.length() - 1);
            }
            statementList.add(trimmedSql);
        }
        return statementList.toArray(new String[statementList.size()]);
    } catch (IOException e) {
        throw new ImportScriptException("Error during import script parsing.", e);
    }
}
Example 29
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 30
Project: open-mika-master  File: Chris.java View source code
public static void main(String[] args) {
    int count = 0;
    Runtime rt = Runtime.getRuntime();
    try {
        java.net.URL u = new java.net.URL("http://www.adhoco.com/time.php");
        while (true) {
            java.net.HttpURLConnection c = (java.net.HttpURLConnection) u.openConnection();
            int rc = c.getResponseCode();
            if (rc == 200) {
                System.out.println("Connected, response code is 200");
                java.io.InputStream is = c.getInputStream();
                java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(is));
                String s = br.readLine();
                while (s != null) {
                    System.out.println(s);
                    s = br.readLine();
                }
                System.out.println("=============================================");
            } else {
                System.out.println("Connection failed, response code is " + rc);
            }
            Thread.sleep(1000);
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
/*
    java.io.File f = new java.io.File("{}/data/foo/");
    System.out.println("Test 1 returned " + f.mkdirs());
    f = new java.io.File("{}/data/sir/john");
    System.out.println("Test 2 returned " + f.mkdirs());
    rt.gc();
    rt.runFinalization();

    
    System.out.println("Version 1: read first, then get exit code");
    try {
      Process p = rt.exec("fsroot/script");
      java.io.InputStream is = p.getInputStream();
      java.io.BufferedReader br = new BufferedReader(new InputStreamReader(is));
      System.out.println("============================================");
      String line = br.readLine();
      while (line != null) {
        System.out.println(line);
        line = br.readLine();
      }
      System.out.println("============================================");
      System.out.println("subprocess returned " + p.waitFor());
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println("Version 2: get exit code first, then read");
    try {
      Process p = rt.exec("fsroot/script");
      java.io.InputStream is = p.getInputStream();
      java.io.BufferedReader br = new BufferedReader(new InputStreamReader(is));
      System.out.println("subprocess returned " + p.waitFor());
      System.out.println("============================================");
      String line = br.readLine();
      while (line != null) {
        System.out.println(line);
        line = br.readLine();
      }
      System.out.println("============================================");
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    System.exit(0);

    System.out.println("java.vm.version = "+System.getProperty("java.vm.version"));
    System.out.println("Heap size: "+rt.totalMemory());
    System.out.println("Memory available: "+rt.freeMemory());
    rt.gc();
    System.out.println("Memory available: "+rt.freeMemory());

    long j = 0;
    long t0 = System.currentTimeMillis();
    for (int i = 0; i < 100000; ++i) {
      ++j;
      ++j;
      ++j;
      ++j;
      ++j;
      ++j;
      ++j;
      ++j;
      ++j;
      ++j;
    }
    long t1 = System.currentTimeMillis();
    System.out.println("t0 = " + t0 + ", t1 = " + t1);
    System.out.println("Performed "+j+" increments in "+(t1-t0)+" milliseconds");
    */
/*
    j = 0;
    t0 = System.currentTimeMillis();
    for (int i = 0; i < 1000; ++i) {
      System.out.println("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
      ++j;
    }
    t1 = System.currentTimeMillis();
    System.out.println("Printed "+j+" lines ("+(j*64)+" bytes) in "+(t1-t0)+" milliseconds");
    */
/*
    System.out.println("java.vm.vendor = "+System.getProperty("java.vm.vendor"));
    System.out.println("java.vm.name = "+System.getProperty("java.vm.name"));
    System.out.println("java.class.version = "+System.getProperty("java.class.version"));
    System.out.println("java.class.path = "+System.getProperty("java.class.path"));
    System.out.println("java.ext.dirs.path = "+System.getProperty("java.ext.dirs"));
    System.out.println("os.name = "+System.getProperty("os.name"));
    System.out.println("os.arch = "+System.getProperty("os.arch"));
    System.out.println("os.version = "+System.getProperty("os.version"));
    System.out.println("os.name = "+System.getProperty("user.name"));
    System.out.println("user.home = "+System.getProperty("user.home"));
    System.out.println("user.dir = "+System.getProperty("user.dir"));

    int jj = 0;
    t0 = System.currentTimeMillis();
    for (int i = 0; i < 1000000; ++i) {
      synchronized(rt) {
        ++jj;
      }
    }
    t1 = System.currentTimeMillis();
    System.out.println("Performed "+jj+" synchronized blocks in "+(t1-t0)+" milliseconds");

    try {
      Thread.sleep(1000000);
    }
    catch (InterruptedException ie) {}

    for (int i = 0; i < 10; ++i) {
    byte[][] blob = new byte[10][1000000];
    System.out.println("Memory available: "+rt.freeMemory());
    long t2 = System.currentTimeMillis();
    blob = null;
    rt.gc();
    long t3 = System.currentTimeMillis();
    System.out.println("gc() took "+(t3-t2)+" milliseconds");
    System.out.println("Memory available: "+rt.freeMemory());
    }

    if (args.length > 0) {
      StringBuffer sentence = new StringBuffer();
      for (int i = 0; i < args.length - 1; ++i) {
        sentence.append(args[i]);
        sentence.append(' ');
      }
      sentence.append(args[args.length - 1]);
      Carillon.getInstance(sentence.toString()).setDaemon(true);
    }
    else {
      Carillon.getInstance("Multithreaded programming is difficult and error prone. It is easy to make a mistake in synchronization that produces a data race, yet it can be extremely hard to locate this mistake during debugging.").setDaemon(true);
    }
    Runtime.getRuntime().addShutdownHook(new Thread(new Chris()));
    */
}
Example 31
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 32
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 33
Project: GdxStudio-master  File: DirSourceLocation.java View source code
/**
	 * [email protected]}
	 */
public CompilationUnit getCompilationUnit(ClassFile cf) throws IOException {
    CompilationUnit cu = null;
    String entryName = cf.getClassName(true);
    entryName = entryName.replace('.', '/');
    entryName += ".java";
    //System.out.println("DEBUG: entry name: " + entryName);
    File file = new File(dir, entryName);
    if (!file.isFile()) {
        // Be nice and check for "src/" subdirectory
        file = new File(dir, "src/" + entryName);
    }
    if (file.isFile()) {
        BufferedReader r = new BufferedReader(new FileReader(file));
        try {
            Scanner s = new Scanner(r);
            cu = new ASTFactory().getCompilationUnit(entryName, s);
        //System.out.println("DEBUG: cu: " + cu);
        } finally {
            r.close();
        }
    }
    return cu;
}
Example 34
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 35
Project: flink-master  File: TransitiveClosureData.java View source code
public static void checkOddEvenResult(BufferedReader result) throws IOException {
    Pattern split = Pattern.compile(" ");
    String line;
    while ((line = result.readLine()) != null) {
        String[] res = split.split(line);
        Assert.assertEquals("Malformed result: Wrong number of tokens in line.", 2, res.length);
        try {
            int from = Integer.parseInt(res[0]);
            int to = Integer.parseInt(res[1]);
            Assert.assertEquals("Vertex should not be reachable.", from % 2, to % 2);
        } catch (NumberFormatException e) {
            Assert.fail("Malformed result.");
        }
    }
}
Example 36
Project: wpcleaner-master  File: PageUtilitiesTest.java View source code
@Before
public void beforeTest() {
    Reader reader = null;
    File testFile = new File("test/org/wikipediacleaner/api/data/PageUtilitiesTest_1.txt");
    try {
        reader = new BufferedReader(new FileReader(testFile));
        StringBuilder buffer = new StringBuilder((int) (testFile.exists() ? testFile.length() : 1000));
        int caracter;
        while ((caracter = reader.read()) != -1) {
            buffer.append(Character.toChars(caracter));
        }
        pageText = buffer.toString();
    } catch (FileNotFoundException e) {
        fail("Unable to open test file: " + testFile.getAbsolutePath());
    } catch (IOException e) {
        fail("Error reading file: " + testFile + "\n" + e.getMessage());
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
            }
            reader = null;
        }
    }
}
Example 37
Project: rascal-master  File: CharStreamFiller.java View source code
@Override
public IValue[] refill(int pageSize) {
    try {
        if (is == null) {
            is = URIResolverRegistry.getInstance().getCharacterReader(source);
            br = new BufferedReader(is);
        }
        ArrayList<String> al = new ArrayList<String>();
        int readChars = 0;
        while (readChars < pageSize) {
            int n = br.read();
            if (n != -1) {
                al.add(new String(Character.toString((char) n)));
                ++readChars;
            } else {
                break;
            }
        }
        IValue res[] = new IValue[al.size()];
        for (int idx = 0; idx < al.size(); ++idx) res[idx] = ValueFactoryFactory.getValueFactory().string(al.get(idx));
        return res;
    } catch (IOException ioe) {
    }
    return new IValue[0];
}
Example 38
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 39
Project: teiid-designer-master  File: WorkspaceUUIDService.java View source code
/**
     * Get the Workspace's UUID
     * 
     * @return UUID
     */
public UUID getUUID() {
    UUID workspaceUuid = null;
    if (restoreFile != null && restoreFile.exists()) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(restoreFile));
            workspaceUuid = UUID.fromString(reader.readLine());
        } catch (final IOException error) {
        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (final IOException ignored) {
            }
        }
    }
    if (workspaceUuid == null)
        workspaceUuid = UUID.randomUUID();
    writeUUID(workspaceUuid);
    return workspaceUuid;
}
Example 40
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 41
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 42
Project: speechalyzer-master  File: HTTPConnection.java View source code
public static String getJSonFromURL(String urlS, LoggerInterface logger, int urlConnectTimeout) {
    try {
        StringBuilder ret = new StringBuilder(2000);
        if (logger != null && logger.isDebugEnabled())
            logger.debug("asking url: " + urlS);
        URL url = new URL(urlS);
        URLConnection connection = url.openConnection();
        //			connection.setRequestProperty("Accept-Charset", "UTF-8");
        //			connection.setRequestProperty("Content-Type",
        //					"application/x-www-form-urlencoded;charset=utf-8");
        connection.setConnectTimeout(urlConnectTimeout);
        connection.addRequestProperty("Accept", "application/json");
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            ret.append(line).append("\n");
        }
        return ret.toString();
    } catch (Exception e) {
        if (logger != null)
            logger.error(e.getMessage());
        e.printStackTrace();
    }
    return "";
}
Example 43
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 44
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 45
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 46
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 47
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 48
Project: google-web-toolkit-svnmirror-master  File: FormPanelTestServlet.java View source code
protected void doPost(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
    rsp.setContentType("text/html");
    String query = req.getQueryString();
    if (query != null) {
        if (query.equals("sendHappyHtml")) {
            rsp.getWriter().write("<html><body><div id=':)'></div></body></html>");
            return;
        }
    }
    // Read the request content.
    BufferedReader reader = req.getReader();
    char[] buf = new char[req.getContentLength()];
    reader.read(buf, 0, req.getContentLength());
    // Echo the request content.
    rsp.getWriter().write(buf);
}
Example 49
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 50
Project: jnlp-master  File: Seg.java View source code
/**
	 * 训练文件
	 * @param fileName
	 */
public void train(String fileName) {
    List<List<WordTag>> wordTags = new ArrayList<List<WordTag>>();
    BufferedReader br = MemFile.readFile(fileName, this);
    if (br != null) {
        wordTags = MemFile.segFile(br, wordTags);
    }
    // 加载自定义的训练文件
    File extendFiles = new File("extend");
    if (extendFiles.isDirectory() && extendFiles.listFiles().length > 0) {
        for (File file : extendFiles.listFiles()) {
            br = MemFile.readFile(file.getName(), this);
            if (br != null) {
                wordTags = MemFile.segFile(br, wordTags);
            }
        }
    }
    this.segger.train(wordTags);
}
Example 51
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;
}