javatips.net counter

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: PublicBroadcastingClient.java View source code
/**
   * Retrieves the list of story ID's for the programs that are currently
   * playing somewhere in the NPR affiliate stations.
   *
   * @return an array of id Integers.
   * @throws java.io.IOException if it can't load the list
   */
public static Integer[] getNowPlayingIds(Context context) throws IOException {
    InputStream data = HttpHelper.download(nowPlayingURL, context);
    if (data == null) {
        Log.d(LOG_TAG, "No programs currently on air anywhere");
        return new Integer[0];
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(data), 1024);
    String line;
    ArrayList<Integer> list = new ArrayList<Integer>();
    try {
        while ((line = reader.readLine()) != null) {
            try {
                list.add(Integer.parseInt(line));
            } catch (NumberFormatException e) {
                Log.e(LOG_TAG, "Not an integer in on-air list: " + line);
            }
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error reading on air-list.", e);
    }
    return list.toArray(new Integer[list.size()]);
}
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: DebugFlowController.java View source code
@Override
public void nextStep(TestStepContext context) {
    requestNumber++;
    System.err.println("...request #" + requestNumber);
    if (skipToRequest > 0) {
        if (skipToRequest == requestNumber) {
            DO_SKIP = false;
            skipToRequest = 0;
        }
    }
    if (!DO_SKIP) {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String s = "";
            System.err.println("Enter [n]ext to continue, [s]kip to run to end or request number to jump to:");
            while (s != null && !(s.toLowerCase().startsWith("n") || s.toLowerCase().startsWith("s") || skipToRequest != 0)) {
                s = in.readLine();
                try {
                    skipToRequest = Integer.parseInt(s);
                } catch (NumberFormatException e) {
                    skipToRequest = 0;
                }
            }
            if (s.toLowerCase().startsWith("s") || (skipToRequest > 0)) {
                DO_SKIP = true;
            }
        } catch (IOException e) {
        }
    }
}
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: SpecReader.java View source code
public Spec specify() {
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    try {
        String line;
        boolean inCharClassSection = true;
        while ((line = reader.readLine()) != null) {
            if (line.equals("")) {
                inCharClassSection = false;
                continue;
            }
            if (inCharClassSection) {
                readCharClass(line);
            } else {
                readTokenDef(line);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException();
    }
    return spec;
}
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: AddressList.java View source code
/**
	 * Test console.
	 */
public static void main(String[] args) throws Exception {
    java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
    while (true) {
        try {
            System.out.print("> ");
            String line = reader.readLine();
            if (line.length() == 0 || line.toLowerCase().equals("exit") || line.toLowerCase().equals("quit")) {
                System.out.println("Goodbye.");
                return;
            }
            AddressList list = parse(line);
            list.print();
        } catch (Exception e) {
            e.printStackTrace();
            Thread.sleep(300);
        }
    }
}
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: WindowsLoader.java View source code
public static Window[] loadWindows(Device device) {
    Socket socket = null;
    BufferedReader in = null;
    BufferedWriter out = null;
    try {
        ArrayList<Window> windows = new ArrayList<Window>();
        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("LIST");
        out.newLine();
        out.flush();
        String line;
        while ((line = in.readLine()) != null) {
            if ("DONE.".equalsIgnoreCase(line)) {
                break;
            }
            int index = line.indexOf(' ');
            if (index != -1) {
                Window w = new Window(line.substring(index + 1), Integer.parseInt(line.substring(0, index), 16));
                windows.add(w);
            }
        }
        return windows.toArray(new Window[windows.size()]);
    } 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 new Window[0];
}
Example 33
Project: GdxStudio-master  File: ClassEnumerationReader.java View source code
/**
	 * Returns the list of classes specified in the given stream.
	 *
	 * @param in The input stream to read from.  This will be closed when
	 *        this method returns.
	 * @return The list of class names read.
	 * @throws IOException If an IO error occurs.
	 */
public static List getClassNames(InputStream in) throws IOException {
    String lastPkg = null;
    String line = null;
    List classNames = new ArrayList();
    BufferedReader r = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    try {
        while ((line = r.readLine()) != null) {
            // Skip blank lines and comments
            line = line.trim();
            if (line.length() == 0 || line.charAt(0) == '#') {
                continue;
            }
            // A new fully-qualified class name
            if (line.charAt(0) == '-') {
                line = line.substring(1).trim();
                classNames.add(line);
                int lastDot = line.lastIndexOf('.');
                lastPkg = line.substring(0, lastDot + 1);
            } else // Just a class name
            {
                String className = line;
                if (lastPkg != null) {
                    className = lastPkg + className;
                }
                classNames.add(className);
            }
        }
    } finally {
        r.close();
    }
    return classNames;
}
Example 34
Project: yarn-comment-master  File: ProcessIdFileReader.java View source code
/**
   * Get the process id from specified file path.
   * Parses each line to find a valid number
   * and returns the first one found.
   * @return Process Id if obtained from path specified else null
   * @throws IOException
   */
public static String getProcessId(Path path) throws IOException {
    if (path == null) {
        throw new IOException("Trying to access process id from a null path");
    }
    LOG.debug("Accessing pid from pid file " + path);
    String processId = null;
    FileReader fileReader = null;
    BufferedReader bufReader = null;
    try {
        File file = new File(path.toString());
        if (file.exists()) {
            fileReader = new FileReader(file);
            bufReader = new BufferedReader(fileReader);
            while (true) {
                String line = bufReader.readLine();
                if (line == null) {
                    break;
                }
                String temp = line.trim();
                if (!temp.isEmpty()) {
                    try {
                        Long pid = Long.valueOf(temp);
                        if (pid > 0) {
                            processId = temp;
                            break;
                        }
                    } catch (Exception e) {
                    }
                }
            }
        }
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
        if (bufReader != null) {
            bufReader.close();
        }
    }
    LOG.debug("Got pid " + (processId != null ? processId : "null") + " from path " + path);
    return processId;
}
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;
}
Example 52
Project: iaf-master  File: StatisticsUtil.java View source code
public static String fileToString(String fileName, String timestamp, String adapterName) throws IOException {
    StringBuffer sb = new StringBuffer();
    BufferedReader in = new BufferedReader(new FileReader(fileName));
    String line;
    boolean timestampActive = false;
    boolean adapterNameActive = false;
    while ((line = in.readLine()) != null) {
        line = line.trim();
        if (line.length() > 0) {
            if (line.startsWith("<statisticsCollection")) {
                sb.append(line);
                if (timestamp != null && line.indexOf("timestamp=\"" + timestamp + "\"") > 0) {
                    timestampActive = true;
                } else {
                    timestampActive = false;
                }
            } else {
                if (line.startsWith("</statisticsCollection")) {
                    sb.append(line);
                } else {
                    if (line.startsWith("<statgroup")) {
                        sb.append(line);
                        if (adapterName != null && line.indexOf("type=\"adapter\"") > 0) {
                            if (line.indexOf("name=\"" + adapterName + "\"") > 0) {
                                adapterNameActive = true;
                            } else {
                                adapterNameActive = false;
                            }
                        }
                    } else {
                        if (line.startsWith("</statgroup")) {
                            sb.append(line);
                        } else {
                            if (timestampActive && adapterNameActive) {
                                sb.append(line);
                            }
                        }
                    }
                }
            }
        }
    }
    in.close();
    return sb.toString();
}
Example 53
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 54
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 55
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 56
Project: cdt-tests-runner-master  File: ErrorThread.java View source code
/*
	 * Sit on the error stream output, and append to the GDB console
	 */
public void run() {
    BufferedReader reader = new BufferedReader(new InputStreamReader(session.getChannelErrorStream()));
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            OutputStream console = session.getLogPipe();
            if (console != null) {
                console.write(//$NON-NLS-1$
                (line + "\n").getBytes());
                console.flush();
            }
        }
    } catch (IOException e) {
        try {
            reader.close();
        } catch (IOException e1) {
        }
    }
}
Example 57
Project: Musubi-Android-master  File: HTTPDownloadTextFileTask.java View source code
@Override
public String doInBackground(String... urls) {
    String response = "";
    for (String url : urls) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse execute = client.execute(httpGet);
            InputStream content = execute.getEntity().getContent();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
            String s = "";
            while ((s = buffer.readLine()) != null) {
                response += s;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return response;
}
Example 58
Project: dcache-master  File: ExecAuth.java View source code
@Override
public void run() {
    Runtime runtime = Runtime.getRuntime();
    try {
        _process = runtime.exec(_execPath);
        new Destroy(_process.getErrorStream());
        _input = new BufferedReader(new InputStreamReader(_process.getInputStream()));
        _output = new PrintWriter(new OutputStreamWriter(_process.getOutputStream()));
        _active = true;
    } catch (Exception eee) {
    }
    try {
        _process.waitFor();
    } catch (InterruptedException ee) {
    }
    System.out.println("Done");
    _active = false;
}
Example 59
Project: org.openscience.cdk-master  File: StandardSubstructureSets.java View source code
/**
	 * @return A set of the functional groups.
     * @throws Exception if there is an error parsing SMILES for the functional groups
	 */
@TestMethod("testGetFunctionalGroupSubstructureSet")
public static String[] getFunctionalGroupSMARTS() throws Exception {
    if (smarts != null)
        return smarts;
    String filename = "org/openscience/cdk/fingerprint/data/SMARTS_InteLigand.txt";
    InputStream ins = StandardSubstructureSets.class.getClassLoader().getResourceAsStream(filename);
    BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
    List<String> tmp = new ArrayList<String>();
    String line;
    while ((line = reader.readLine()) != null) {
        if (line.startsWith("#") || line.trim().length() == 0)
            continue;
        String[] toks = line.split(":");
        StringBuffer s = new StringBuffer();
        for (int i = 1; i < toks.length - 1; i++) s.append(toks[i] + ":");
        s.append(toks[toks.length - 1]);
        tmp.add(s.toString().trim());
    }
    smarts = tmp.toArray(new String[] {});
    return smarts;
}
Example 60
Project: android-ePub-Library-master  File: BBBEPubBookInfo.java View source code
public static BBBEPubBookInfo createFromStream(InputStream in) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder builder = new StringBuilder();
    String aux = "";
    BBBEPubBookInfo book = null;
    try {
        while ((aux = reader.readLine()) != null) {
            builder.append(aux);
        }
        String text = builder.toString();
        try {
            book = new Gson().fromJson(text, BBBEPubBookInfo.class);
        } catch (Exception e) {
            text.replace("null", "");
            book = new Gson().fromJson(text, BBBEPubBookInfo.class);
        }
    } catch (Exception e) {
    }
    ;
    return book;
}
Example 61
Project: de.htwg.se.muehle-master  File: GamefieldGraph.java View source code
private void createEdges() {
    try {
        InputStream stream = getClass().getResourceAsStream("/GamefieldEdges.txt");
        BufferedReader in = new BufferedReader(new InputStreamReader(stream));
        String zeile = null;
        while ((zeile = in.readLine()) != null) {
            String splitresult[] = zeile.split(" ");
            int temp1 = Integer.parseInt(splitresult[0]);
            int temp2 = Integer.parseInt(splitresult[1]);
            adjacencyList.get(temp1).add(temp2);
        }
        in.close();
    } catch (IOException e) {
        System.exit(1);
    }
}
Example 62
Project: eclipselink.runtime-master  File: ClassGenUnicodeCharacterTestCases.java View source code
public String getSchema(InputStream is, String fileName) {
    String xsdSchema = EMPTY_STRING;
    try {
        InputStreamReader isr = new InputStreamReader(is, Charset.forName("UTF-8"));
        BufferedReader reader = new BufferedReader(isr);
        String nextLine = reader.readLine();
        while (nextLine != null) {
            xsdSchema += nextLine;
            nextLine = reader.readLine();
        }
        log(xsdSchema);
        return xsdSchema;
    } catch (Exception e) {
        log(getClass().toString() + ": Reading error for : " + fileName + " message: " + e.getClass() + " " + e.getMessage());
    } finally {
        try {
            if (null != is) {
                is.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }
    return xsdSchema;
}
Example 63
Project: schemacrawler-master  File: GraphGenerator.java View source code
private static void run(final String... args) throws IOException {
    final List<String> command = new ArrayList<String>(Arrays.asList(args));
    command.add(0, getGraphGenerator());
    LOGGER.log(Level.INFO, "Executing: " + command);
    final ProcessBuilder pb = new ProcessBuilder(command);
    pb.redirectErrorStream(true);
    final Process process = pb.start();
    final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuilder buffer = new StringBuilder();
    String line;
    try {
        try {
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (final EOFException e) {
        }
        reader.close();
    } catch (final IOException e) {
        LOGGER.log(Level.WARNING, "Could not read diagram generator output" + e.getMessage());
    }
    int exitCode = 0;
    try {
        exitCode = process.waitFor();
    } catch (final InterruptedException e) {
    }
    process.getInputStream().close();
    process.getOutputStream().close();
    process.getErrorStream().close();
    if (exitCode != 0) {
        throw new IOException(buffer.toString());
    } else if (buffer.length() > 0) {
        LOGGER.log(Level.INFO, buffer.toString());
    }
}
Example 64
Project: openwayback-master  File: ZiplinedMultiBlock.java View source code
@Override
public BufferedReader readBlock() throws IOException {
    byte bytes[] = attemptBlockLoad(super.loader);
    if (bytes == null) {
        throw new IOException("Unable to load block(s)!");
    }
    int count = 0;
    InputStream currChain = null;
    for (int blockSize : blockSizes) {
        InputStream nextStream = new ByteArrayInputStream(bytes, count, blockSize);
        nextStream = new OpenJDK7GZIPInputStream(nextStream);
        if (currChain == null) {
            currChain = nextStream;
        } else {
            currChain = new SequenceInputStream(currChain, nextStream);
        }
        count += blockSize;
    }
    return new BufferedReader(new InputStreamReader(currChain));
}
Example 65
Project: thundernetwork-master  File: PaymentProtocolServerSocket.java View source code
@Override
public void run() {
    int portNumber = 15462;
    try {
        ServerSocket serverSocket = null;
        serverSocket = new ServerSocket(portNumber);
        while (true) {
            try {
                Socket clientSocket = serverSocket.accept();
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                String request = in.readLine();
                System.out.println("Payment Request received: " + request);
                request = request.substring(8);
                List<NameValuePair> params = URLEncodedUtils.parse(request, Charset.defaultCharset());
                HashMap<String, String> list = new HashMap<String, String>();
                for (NameValuePair param : params) {
                    System.out.println(param.getName() + "  " + param.getValue());
                    list.put(param.getName(), param.getValue());
                }
                try {
                //                                ThunderContext.instance.makePayment(Long.valueOf(list.get("amount")), list.get("address"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 66
Project: polly-master  File: WikiReader.java View source code
public String readFirstParagraph(String article, String lang) throws IOException {
    URL url = new URL(this.getWikiLink(article, lang));
    URLConnection connection = url.openConnection();
    BufferedReader r = null;
    try {
        r = new BufferedReader(new InputStreamReader(connection.getInputStream(), //$NON-NLS-1$
        Charset.forName("UTF-8")));
        String line = null;
        StringBuilder b = new StringBuilder();
        while ((line = r.readLine()) != null) {
            b.append(line);
            //$NON-NLS-1$
            b.append("\n");
            if (b.indexOf("</p>") != -1) {
                // we read everything we needed
                break;
            }
        }
        String wikiText = b.toString();
        Matcher m = PARAGRAPH.matcher(wikiText);
        if (!m.find()) {
            //$NON-NLS-1$
            throw new IOException("Error while reading the first paragraph");
        }
        String result = wikiText.substring(m.start(), m.end());
        return this.removeHtml(result);
    } finally {
        if (r != null) {
            try {
                r.close();
            } catch (IOException e) {
            }
            ;
        }
    }
}
Example 67
Project: CeaselessAndroid-master  File: ImageURLServiceImpl.java View source code
@Override
public String getImageURL() {
    InputStream in = null;
    // HTTP Get
    try {
        URL url = new URL(HTTP_API_IMAGE);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        in = new BufferedInputStream(urlConnection.getInputStream());
    } catch (Exception e) {
        Log.e(TAG, "ERROR", e);
        Log.e(TAG, e.getStackTrace().toString());
        return null;
    }
    String json = null;
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        json = sb.toString();
    } catch (IOException e) {
        Log.e(TAG, "ERROR", e);
        Log.e(TAG, e.getStackTrace().toString());
        return null;
    }
    String imageUrl = null;
    // parse JSON response
    try {
        JSONObject obj = new JSONObject(json);
        imageUrl = obj.getString("imageUrl");
    } catch (JSONException e) {
        Log.e(TAG, "ERROR", e);
        Log.e(TAG, e.getStackTrace().toString());
        return null;
    }
    return imageUrl;
}
Example 68
Project: syncthing-android-master  File: GetTask.java View source code
/**
     * @param params Keys and values for the query string.
     */
@Override
protected String doInBackground(String... params) {
    try {
        HttpsURLConnection connection = openConnection(params);
        Log.v(TAG, "Calling Rest API at " + connection.getURL());
        connection.connect();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String line;
        String result = "";
        while ((line = br.readLine()) != null) {
            result += line;
        }
        br.close();
        Log.v(TAG, "API call result: " + result);
        return result;
    } catch (IOException e) {
        Log.w(TAG, "Failed to call rest api", e);
        return null;
    }
}
Example 69
Project: uberpay-wallet-master  File: CheckUpdateTask.java View source code
@Override
protected Integer doInBackground(Void... params) {
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) new URL(Constants.VERSION_URL).openConnection();
        connection.setInstanceFollowRedirects(true);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setRequestProperty("Accept-Charset", "utf-8");
        connection.connect();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8), 64);
            String line = reader.readLine().trim();
            reader.close();
            return Integer.valueOf(line);
        }
    } catch (final Exception e) {
        log.info("Could not check for update", e);
    } finally {
        if (connection != null)
            connection.disconnect();
    }
    return null;
}
Example 70
Project: ProjectModel-master  File: ManifestBean.java View source code
private static void initManifest() {
    if (manifest == null) {
        try {
            FacesContext facesContext = FacesContext.getCurrentInstance();
            ExternalContext externalContext = facesContext.getExternalContext();
            ServletContext context = (ServletContext) externalContext.getContext();
            String manifestPath = context.getRealPath("/META-INF/MANIFEST.MF");
            File manifestFile = new File(manifestPath);
            BufferedReader in = new BufferedReader(new FileReader(manifestFile));
            manifest = new HashMap<String, String>();
            String text = null;
            while ((text = in.readLine()) != null) {
                String key, value;
                int colonIndex = text.indexOf(':');
                if (colonIndex > 0) {
                    key = text.substring(0, colonIndex);
                    int valueIndex = colonIndex + 2;
                    if (valueIndex < text.length())
                        value = text.substring(colonIndex + 2);
                    else
                        value = null;
                    System.out.println("key='" + key + "', value='" + value + "'");
                    manifest.put(key, value);
                }
            }
            in.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
Example 71
Project: R5A-master  File: GetData.java View source code
/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("doGet : session=> " + request.getSession(true).getId());
    response.setHeader("pragma", "no-cache,no-store");
    response.setHeader("cache-control", "no-cache,no-store,max-age=0,max-stale=0");
    response.setHeader("Accept-Charset", "utf-8");
    response.setContentType("text/event-stream;charset=utf-8;");
    response.setCharacterEncoding("UTF-8");
    clients.add(response.getWriter());
    if (first) {
        first = false;
        String clientSentence;
        System.out.println("GetData : Creation de la socket sur le port 9990");
        ServerSocket welcomeSocket = new ServerSocket(NetworkServiceImpl.PORTSEND);
        while (true) {
            System.out.println("GetData : Acceptation de la socket");
            Socket connectionSocket = welcomeSocket.accept();
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            char[] buffer = new char[4096];
            inFromClient.read(buffer);
            clientSentence = (new String(buffer).trim().replaceAll("\n", "<br>"));
            for (PrintWriter out : clients) {
                out.print("data: " + clientSentence + "\n\n");
                out.flush();
            }
        }
    } else {
        while (true) {
            try {
                Thread.sleep(100000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
Example 72
Project: pentaho-kettle-master  File: StreamLogger.java View source code
@Override
public void run() {
    try {
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ((line = br.readLine()) != null) {
            lastLine = line;
            if (errorStream) {
                log.logError(type + " " + line);
            } else {
                log.logBasic(type + " " + line);
            }
        }
    } catch (IOException ioe) {
        log.logError(type + " " + Const.getStackTracker(ioe));
    }
}
Example 73
Project: ArubaSyslog-master  File: StartProcessing.java View source code
/**
     * @param args
     * @throws ParseException
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
public static void main(String[] args) throws ParseException, IOException, NoSuchAlgorithmException {
    File inFile, outFile;
    FileWriter fileWriter;
    StartProcessing sp = new StartProcessing();
    sp.ReadCmd(args);
    inFile = new File(sp.inFile);
    outFile = new File(sp.outFile);
    BufferedReader in = new BufferedReader(new FileReader(inFile));
    if (!outFile.exists())
        outFile.createNewFile();
    fileWriter = new FileWriter(outFile);
    String input;
    ArrayList<String> apName = new ArrayList<String>();
    while ((input = in.readLine()) != null) {
        String output = SyslogPreprocess.Filter(input);
        output = SyslogPreprocess.APIPDeletion(output);
        output = SyslogPreprocess.APNameAnonymous(output, apName);
        output = SyslogPreprocess.IPAnonymous(output);
        output = SyslogPreprocess.MacAnonymous(output);
        output = SyslogPreprocess.UserNameAnonymous(output);
        if (output != null)
            fileWriter.write(output + "\n");
    }
    fileWriter.close();
}
Example 74
Project: dltk.ruby-master  File: AbstractRubyParserTests.java View source code
public ModuleDeclaration processScript(String name) throws Exception {
    ModuleDeclaration module = null;
    try (InputStream input = Activator.openResource(name)) {
        InputStreamReader reader = new InputStreamReader(input);
        BufferedReader br = new BufferedReader(reader);
        StringBuffer buffer = new StringBuffer();
        while (br.ready()) {
            String l = br.readLine();
            if (l != null) {
                buffer.append(l);
                buffer.append('\n');
            }
        }
        module = (ModuleDeclaration) DLTKLanguageManager.getSourceParser(RubyNature.NATURE_ID).parse(new ModuleSource(name, buffer.toString()), null);
        assertNotNull(module);
        assertFalse(module.isEmpty());
    }
    return module;
}
Example 75
Project: TerasologyLauncher-master  File: GameRunner.java View source code
@Override
public void run() {
    try {
        try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.defaultCharset()))) {
            String line;
            do {
                line = r.readLine();
                logger.trace("Game output: {}", line);
            } while (!Thread.currentThread().isInterrupted() && (line != null));
        }
        if (Thread.currentThread().isInterrupted()) {
            logger.debug("Game thread interrupted.");
            return;
        }
        int exitValue = -1;
        try {
            exitValue = p.waitFor();
        } catch (InterruptedException e) {
            logger.error("The game thread was interrupted!", e);
        }
        logger.debug("Game closed with the exit value '{}'.", exitValue);
    } catch (IOException e) {
        logger.error("Could not read game output!", e);
    }
}
Example 76
Project: xmind-master  File: VectorGraphicsIO.java View source code
public static void copyResourceTo(Object object, String fileName, PrintWriter os) {
    InputStream is = null;
    BufferedReader br = null;
    try {
        is = object.getClass().getResourceAsStream(fileName);
        br = new BufferedReader(new InputStreamReader(is));
        String s;
        while ((s = br.readLine()) != null) {
            os.println(s);
        }
        os.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)
                br.close();
            if (is != null)
                is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Example 77
Project: NewsSpeakServer-master  File: USATodayParser.java View source code
@Override
protected String getContent(String link, String type) throws ParserException {
    String content = "";
    TagNameFilter paraFilter = new TagNameFilter("p");
    StringBuilder builder = new StringBuilder();
    URL url;
    try {
        url = new URL(link);
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()));
        String oneLine;
        while ((oneLine = reader.readLine()) != null) {
            builder.append(oneLine);
        }
        reader.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    parser.setInputHTML(builder.toString());
    NodeList list = parser.parse(paraFilter);
    if (type.equalsIgnoreCase("html")) {
        for (int i = 0; i < list.size(); ++i) {
            content += list.elementAt(i).toHtml();
        }
    } else {
        for (int i = 0; i < list.size(); ++i) {
            content += list.elementAt(i).toPlainTextString();
        }
    }
    // Remove special characters, such as  
    Pattern regex = Pattern.compile("&.*?;");
    Matcher matcher = regex.matcher(content);
    while (matcher.find()) content = matcher.replaceAll("");
    // Remove extra whitespaces
    content = content.replaceAll("(\\t|\\n)", "");
    return content;
}
Example 78
Project: dk-master  File: HttpClientUtils.java View source code
public static IResult<?> post(String url, Map<String, String> params) {
    IResult<String> result = new ResultSupport<String>();
    HttpClient client = new DefaultHttpClient();
    InputStream inputStream = null;
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        for (String key : params.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
        }
        HttpPost post = new HttpPost(url);
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
        HttpResponse response = client.execute(post);
        inputStream = response.getEntity().getContent();
        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        StringBuffer resultString = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            resultString.append(line);
        }
        result.setSuccess(true);
        result.setModel(resultString.toString());
    } catch (Exception e) {
        result.setSuccess(false);
        result.setModel("发送请求错误:" + e.getMessage());
        logger.error(e.getMessage(), e);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (Exception ignore) {
        }
        client.getConnectionManager().shutdown();
    }
    return result;
}
Example 79
Project: Java8Examples-master  File: CustomerDetails.java View source code
public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    String name;
    String email;
    String phone;
    System.out.print("enter your desired number of records:");
    //Scanner sc =new Scanner(System.in);
    //int i,j;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String s = br.readLine();
    int k = Integer.parseInt(s);
    Customer[] customers = new Customer[k];
    for (int j = 0; j < k; j++) {
        System.out.print("Are you creating a record:");
        String reply = br.readLine();
        if ("Y".equalsIgnoreCase(reply)) {
            System.out.print("enter your name");
            name = br.readLine();
            System.out.print("enter your email");
            email = br.readLine();
            System.out.print("enter your phone");
            phone = br.readLine();
            customers[j] = new Customer();
            customers[j].name = name;
            customers[j].email = email;
            customers[j].phone = phone;
        } else {
            System.out.println("Printing details");
        }
    }
    System.out.println("DETAILS ENTERED ARE:");
    for (int i = 0; i < customers.length; i++) {
        System.out.println("Customer" + (i + 1) + "name:" + customers[i].name);
        System.out.println(" Emial:" + customers[i].email);
        System.out.println("Phone:" + customers[i].phone);
        System.out.println("==============================");
    }
}
Example 80
Project: sosies-generator-master  File: TestAndBranchSelection.java View source code
protected void parse(String coverageInfo) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(coverageInfo));
    String line = br.readLine();
    while ((line = br.readLine()) != null) {
        String[] split = line.split(";");
        String branch = split[0];
        branchNbTest.put(branch, Integer.parseInt(split[1]));
        branchDeepMax.put(branch, Integer.parseInt(split[2]));
        branchDeepMean.put(branch, Double.parseDouble(split[3]));
        if (!classPositionToBranch.containsKey(split[4])) {
            classPositionToBranch.put(split[4], new HashSet<>());
        }
        classPositionToBranch.get(split[4]).add(branch);
        lineBegin.put(branch, Integer.parseInt(split[5]));
        lineEnd.put(branch, Integer.parseInt(split[6]));
    }
}
Example 81
Project: ndogen_stalled-master  File: SubstanceUtils.java View source code
public static boolean push(String content) {
    try {
        URL url = new URL("http://beta.substance.io/writedocument");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setReadTimeout(10 * 1000);
        connection.connect();
        BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
        bos.write(content.getBytes());
        bos.flush();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line + "\n");
        }
        System.out.println(stringBuilder.toString());
        connection.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}
Example 82
Project: OrderNowAndroid-master  File: AsyncNetwork.java View source code
@Override
protected String doInBackground(String... params) {
    String response = "";
    try {
        URL url = new URL(params[0]);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        String line = null;
        while ((line = br.readLine()) != null) {
            response += line;
        }
    } catch (Exception e) {
        e.printStackTrace();
        exceptionToBeThrown = e;
    }
    return response;
}
Example 83
Project: mini-git-server-master  File: Version.java View source code
private static String loadVersion() {
    InputStream in = Version.class.getResourceAsStream("Version");
    if (in == null) {
        return null;
    }
    try {
        BufferedReader r = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        try {
            String vs = r.readLine();
            if (vs != null && vs.startsWith("v")) {
                vs = vs.substring(1);
            }
            if (vs != null && vs.isEmpty()) {
                vs = null;
            }
            return vs;
        } finally {
            r.close();
        }
    } catch (IOException e) {
        return null;
    }
}
Example 84
Project: AcDisplay-master  File: Logcat.java View source code
/**
     * Captures the application logcat.
     */
@Nullable
public static String capture() {
    final String[] command;
    if (RootTools.isAccessGiven()) {
        command = new String[] { "su", "logcat", "-v", "threadtime", "-d" };
    } else
        command = new String[] { "logcat", "-v", "threadtime", "-d" };
    BufferedReader br = null;
    try {
        Process process = Runtime.getRuntime().exec(command);
        br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        return IOUtils.readTextFromBufferedReader(br);
    } catch (IOException e) {
        return null;
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
            }
        }
    }
}
Example 85
Project: dragome-sdk-master  File: JavaScriptCompressor.java View source code
public String compress(InputStream input) throws FileNotFoundException, IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    StringBuilder builder = new StringBuilder();
    int state = DEFAULT_CODE;
    char c;
    char lastC = 0;
    int i;
    while ((i = reader.read()) != -1) {
        c = (char) i;
        if (state == LINECOMMENT) {
            if (c == '\n') {
                state = DEFAULT_CODE;
                builder.append(c);
            }
        } else if (state == MULTILINECOMMENT) {
            if (c == '/' && lastC == '*') {
                state = DEFAULT_CODE;
            }
        } else if (state == STRING) {
            if (c == '"') {
                state = DEFAULT_CODE;
            }
            builder.append(c);
        } else if (c == '/' && lastC == c) {
            state = LINECOMMENT;
            builder.deleteCharAt(builder.length() - 1);
        } else if (c == '*' && lastC == '/') {
            state = MULTILINECOMMENT;
            builder.deleteCharAt(builder.length() - 1);
        } else if (c == '"') {
            state = STRING;
            builder.append(c);
        } else {
            int length = builder.length();
            if (length > 0 && Character.isWhitespace(c) && Character.isWhitespace(builder.charAt(length - 1))) {
            } else {
                builder.append(c);
            }
        }
        lastC = c;
    }
    reader.close();
    builder.trimToSize();
    return builder.toString();
}
Example 86
Project: AirPlayer-master  File: DownloadURLTask.java View source code
@Override
protected ArrayList<Picture> doInBackground(String... params) {
    HttpURLConnection connection = null;
    try {
        String urlParam = params[0];
        if (params[1] != null)
            urlParam = urlParam + params[1];
        URL url = new URL(getUrl() + urlParam);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(8000);
        connection.setReadTimeout(8000);
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            response.append(line);
        }
        return decodeJson(response.toString());
    } catch (IOException e) {
        onError(e);
        isError = true;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}
Example 87
Project: kanqiu_letv-master  File: LetvLogTool.java View source code
@Override
public void run() {
    synchronized (file) {
        BufferedReader stringReader = null;
        FileWriter fileWriter = null;
        try {
            stringReader = new BufferedReader(new StringReader(data));
            fileWriter = new FileWriter(file, true);
            String line = null;
            while ((line = stringReader.readLine()) != null) {
                fileWriter.write(line);
                fileWriter.write("\r\n");
            }
            stringReader.close();
            fileWriter.flush();
            fileWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                stringReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Example 88
Project: airlift-master  File: LoggingWriter.java View source code
@Override
public void flush() {
    BufferedReader in = new BufferedReader(new StringReader(getBuffer().toString()));
    while (true) {
        try {
            String line = in.readLine();
            if (line == null) {
                break;
            }
            switch(type) {
                default:
                case DEBUG:
                    {
                        if (logger.isDebugEnabled()) {
                            logger.debug(line);
                        }
                        break;
                    }
                case INFO:
                    {
                        if (logger.isInfoEnabled()) {
                            logger.info(line);
                        }
                        break;
                    }
            }
        } catch (IOException e) {
            throw new Error(e);
        }
    }
    getBuffer().setLength(0);
}
Example 89
Project: aipo-master  File: PopulateSampleIndices.java View source code
public static void main(String args[]) {
    try {
        TurbineConfig config = null;
        config = new TurbineConfig("./webapp", "/WEB-INF/conf/TurbineResources.properties");
        config.init();
        FileReader reader = new FileReader(SAMPLE_URLS);
        BufferedReader breader = new BufferedReader(reader);
        String line = null;
        System.out.println("================= Populate Sample Indices =================");
        System.out.println("... creates Search sample portlet test data from URLs provided in file: " + SAMPLE_URLS);
        System.out.println("...");
        while (null != (line = breader.readLine())) {
            System.out.println("Creating index for: " + line);
            URL url = new URL(line);
            Search.add(url);
        }
        System.out.println("===========================================================");
        reader.close();
    } catch (Exception e) {
        System.out.println("Exception reading URLS" + e);
    }
}
Example 90
Project: android_packages_apps_AeroControl-master  File: RAMModule.java View source code
@Override
protected void operate() {
    super.operate();
    long temp = System.currentTimeMillis();
    Integer freeRAM;
    String totalMemory;
    String totalFreeMemory = "0";
    try {
        /* /proc/meminfo entries follow this format:
             * MemTotal:         362096 kB
             * MemFree:           29144 kB
             * Buffers:            5236 kB
             * Cached:            81652 kB
             */
        final BufferedReader reader = new BufferedReader(new FileReader(mPROC_MEMINFO), 1024);
        totalMemory = reader.readLine();
        totalFreeMemory = reader.readLine();
        if (totalFreeMemory != null) {
            String parts[] = totalMemory.split("\\s+");
            parts = totalFreeMemory.split("\\s+");
            if (parts.length == 3) {
                totalFreeMemory = Long.parseLong(parts[1]) + "";
            }
        }
    } catch (IOException e) {
    }
    freeRAM = Integer.parseInt(totalFreeMemory);
    freeRAM = freeRAM / 1000;
    addValues(freeRAM);
    AppLogger.print(mClassName, "RAMModule.operate() time: " + (System.currentTimeMillis() - temp), 1);
}
Example 91
Project: FireflowEngine20-master  File: SocketAtom.java View source code
public void run() {
    if (this.context.getBoolean("stop")) {
        if (log.isInfoEnabled())
            //线程池里面可能还有有尚未启动的任务
            log.info("stop=true, so, exit ....");
        //所以,这里还需要判断一下
        Sockets.safeClose(socket);
        return;
    }
    if (log.isDebugEnabled())
        log.debugf("connect with '%s'", socket.getRemoteSocketAddress().toString());
    try {
        br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        ops = socket.getOutputStream();
    } catch (IOException e1) {
        return;
    }
    // 开始交互
    try {
        doRun();
    } catch (SocketException e) {
    }// 要关闭 socket 监听 ...
     catch (CloseSocketException e) {
        if (log.isInfoEnabled())
            log.info("Catch CloseSocketException , set lock stop");
        context.set("stop", true);
    } catch (IOException e) {
        log.error("Error!! ", e);
    } finally // 最后保证关闭
    {
        if (log.isDebugEnabled())
            log.debug("Close socket");
        Sockets.safeClose(socket);
    }
}
Example 92
Project: AIDR-master  File: CollectionScheduler.java View source code
// 10 minutes - in milliseconds
@Scheduled(fixedDelay = 60 * 60 * 1000)
private void scheduledTaskUpdateAidrData() {
    HttpURLConnection con = null;
    StringBuffer response = new StringBuffer();
    try {
        URL connectionURL = new URL(Configurations.getCollectionDataAPI());
        con = (HttpURLConnection) connectionURL.openConnection();
        if (HttpStatus.OK.value() != con.getResponseCode()) {
            throw new RuntimeException("Failed : HTTP error code : " + con.getResponseCode());
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        ObjectMapper mapper = new ObjectMapper();
        CollectionSummaryInfo[] summaryInfos = mapper.readValue(response.toString(), CollectionSummaryInfo[].class);
        if (summaryInfos.length > 0) {
            logger.info(summaryInfos.length + " collections will be sync.");
            collectionSummaryService.saveUpdateCollectionSummary(Arrays.asList(summaryInfos));
        } else {
            logger.info("No collection to update/insert");
        }
    } catch (IOException e) {
        logger.warn("Error in fetching data from aidr server.", e);
    } catch (Exception e) {
        logger.warn("Error in fetching data from aidr server.", e);
    }
}
Example 93
Project: openjdk8-jdk-master  File: DefaultLocaleTest.java View source code
public static void main(String[] args) throws IOException {
    if (args != null && args.length > 1) {
        File f = new File(args[1]);
        switch(args[0]) {
            case "-r":
                System.out.println("reading file: " + args[1]);
                String str = null;
                try (BufferedReader in = newBufferedReader(f.toPath(), Charset.defaultCharset())) {
                    str = in.readLine().trim();
                }
                if (setting.equals(str)) {
                    System.out.println("Compared ok");
                } else {
                    System.out.println("Compare fails");
                    System.out.println("EXPECTED: " + setting);
                    System.out.println("OBTAINED: " + str);
                    throw new RuntimeException("Test fails: compare failed");
                }
                break;
            case "-w":
                System.out.println("writing file: " + args[1]);
                try (BufferedWriter out = newBufferedWriter(f.toPath(), Charset.defaultCharset(), CREATE_NEW)) {
                    out.write(setting);
                }
                break;
            default:
                throw new RuntimeException("ERROR: invalid arguments");
        }
    } else {
        throw new RuntimeException("ERROR: invalid arguments");
    }
}
Example 94
Project: MinecraftSecondScreenMod-master  File: DataStorageDriver.java View source code
/**
	 * Reads lines from given file
	 * @param file
	 * @return lines, null if exception
	 */
private static ArrayList<String> readFromFile(File file) {
    if (!file.exists()) {
        Logger.i(TAG, "File: " + file.getPath() + " does not exist");
        return null;
    }
    ArrayList<String> lines = new ArrayList<String>();
    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = reader.readLine();
        while (line != null) {
            lines.add(line);
            line = reader.readLine();
        }
        reader.close();
        return lines;
    } catch (FileNotFoundException e) {
        Logger.w(TAG, "File: " + file.getAbsolutePath() + " not found");
        return null;
    } catch (IOException e) {
        Logger.e(TAG, "Failed to read from file: " + file.getAbsolutePath(), e);
        return null;
    }
}
Example 95
Project: lucene-solr-master  File: SpatialTestData.java View source code
/** Reads the stream, consuming a format that is a tab-separated values of 3 columns:
   * an "id", a "name" and the "shape".  Empty lines and lines starting with a '#' are skipped.
   * The stream is closed.
   */
public static Iterator<SpatialTestData> getTestData(InputStream in, SpatialContext ctx) throws IOException {
    List<SpatialTestData> results = new ArrayList<>();
    BufferedReader bufInput = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
    try {
        String line;
        while ((line = bufInput.readLine()) != null) {
            if (line.length() == 0 || line.charAt(0) == '#')
                continue;
            SpatialTestData data = new SpatialTestData();
            String[] vals = line.split("\t");
            if (vals.length != 3)
                throw new RuntimeException("bad format; expecting 3 tab-separated values for line: " + line);
            data.id = vals[0];
            data.name = vals[1];
            try {
                data.shape = ctx.readShapeFromWkt(vals[2]);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            results.add(data);
        }
    } finally {
        bufInput.close();
    }
    return results.iterator();
}
Example 96
Project: SRE-RoboCode-master  File: SittingDuck.java View source code
public void run() {
    setBodyColor(Color.yellow);
    setGunColor(Color.yellow);
    int roundCount, battleCount;
    // a round count, and a battle count
    try {
        BufferedReader r = new BufferedReader(new FileReader(getDataFile("count.dat")));
        // Try to get the counts
        roundCount = Integer.parseInt(r.readLine());
        battleCount = Integer.parseInt(r.readLine());
    } catch (IOException e) {
        roundCount = 0;
        battleCount = 0;
    } catch (NumberFormatException e) {
        roundCount = 0;
        battleCount = 0;
    }
    // Increment the # of rounds
    roundCount++;
    // member variables remain valid throughout it.
    if (!incrementedBattles) {
        // Increment # of battles
        battleCount++;
        incrementedBattles = true;
    }
    PrintStream w = null;
    try {
        w = new PrintStream(new RobocodeFileOutputStream(getDataFile("count.dat")));
        w.println(roundCount);
        w.println(battleCount);
        // they simply set a flag.... so check it here.
        if (w.checkError()) {
            out.println("I could not write the count!");
        }
    } catch (IOException e) {
        out.println("IOException trying to write: ");
        e.printStackTrace(out);
    } finally {
        if (w != null) {
            w.close();
        }
    }
    out.println("I have been a sitting duck for " + roundCount + " rounds, in " + battleCount + " battles.");
}
Example 97
Project: molgenis-master  File: PubMedTermFrequencyService.java View source code
public String httpGet(String targetURL) {
    HttpURLConnection connection = null;
    try {
        URL url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setConnectTimeout(TIME_OUT);
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.close();
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();
    } catch (Exception e) {
        LOG.error(e.getMessage());
        return StringUtils.EMPTY;
    }
}
Example 98
Project: dimple-master  File: DoubleSpaceCSV.java View source code
/**
	 * Constructs a 2-dimensional DoubleSpace populated with data read from a
	 * CSV input stream.
	 * 
	 * @param is
	 *            The input stream from which CSV data is read.
	 * @return The constructed 2-dimensional DoubleSpace.
	 * @throws IOException
	 */
@Nullable
public static DoubleSpace loadCSV(InputStream is) throws IOException {
    final BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line;
    final ArrayList<String> lines = new ArrayList<String>();
    while ((line = br.readLine()) != null) {
        lines.add(line);
    }
    final int rows = lines.size();
    int columns = -1;
    DoubleSpace result = null;
    if (rows > 0) {
        int row = 0;
        for (final String line2 : lines) {
            final String[] tokens = line2.split(",");
            if (columns == -1) {
                columns = tokens.length;
                result = DoubleSpaceFactory.create(rows, columns);
            } else if (columns != tokens.length) {
                throw new IllegalArgumentException("All rows of csv text must have same quantity of columns.");
            }
            requireNonNull(result);
            for (int column = 0; column < columns; column++) {
                final double value = Double.parseDouble(tokens[column]);
                result.put(value, row, column);
            }
            row += 1;
        }
    }
    return result;
}
Example 99
Project: yarep-master  File: SVNRepoTest.java View source code
public void testWriteRead() throws Exception {
    // if this path does not exist yet, it will be created automatically.
    Path path = new Path("/test/foo/bar.txt");
    // Write content to repository
    System.out.println("\nWriting content to repository " + repo.getName());
    Writer writer = repo.getWriter(path);
    String testContent = "Hello World! " + System.currentTimeMillis();
    writer.write(testContent);
    writer.close();
    assertTrue("Path does not exist, although it should have been created: " + path, repo.exists(path));
    // Read content from repository
    System.out.println("\nReading content from repository " + repo.getName());
    Reader reader = repo.getReader(path);
    BufferedReader br = new BufferedReader(reader);
    String line = br.readLine();
    br.close();
    reader.close();
    assertEquals(line, testContent);
}
Example 100
Project: openjdk-master  File: bug8059739.java View source code
private static void runTest() throws Exception {
    String testString = "my string";
    JTextField tf = new JTextField(testString);
    tf.selectAll();
    Clipboard clipboard = new Clipboard("clip");
    tf.getTransferHandler().exportToClipboard(tf, clipboard, TransferHandler.COPY);
    DataFlavor[] dfs = clipboard.getAvailableDataFlavors();
    for (DataFlavor df : dfs) {
        String charset = df.getParameter("charset");
        if (InputStream.class.isAssignableFrom(df.getRepresentationClass()) && charset != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) clipboard.getData(df), charset));
            String s = br.readLine();
            System.out.println("Content: '" + s + "'");
            passed &= s.contains(testString);
        }
    }
}
Example 101
Project: magnificent-mileage-master  File: EntityReplacementStrategyFactory.java View source code
public EntityReplacementStrategy create() throws IOException {
    EntityReplacementStrategyImpl impl = new EntityReplacementStrategyImpl();
    for (Map.Entry<Class<?>, File> entry : _mappings.entrySet()) {
        Class<?> entityClass = entry.getKey();
        File file = entry.getValue();
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = null;
        while ((line = reader.readLine()) != null) {
            String[] tokens = line.split("\\s+");
            List<AgencyAndId> ids = new ArrayList<AgencyAndId>();
            for (String token : tokens) ids.add(GtfsLibrary.convertIdFromString(token));
            for (int i = 1; i < ids.size(); i++) impl.addEntityReplacement(entityClass, ids.get(i), ids.get(0));
        }
        reader.close();
    }
    return impl;
}