javatips.net counter

Java Examples for java.io.InputStreamReader

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

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

            public void run() {
                activity.update();
                Toast.makeText(MainActivity.context, toast, Toast.LENGTH_LONG).show();
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 50
Project: geotools-old-master  File: ExecuteOnlineTest.java View source code
/*
     * Try doing an execute request from the example xsd and parse it
     */
public void testExecute() throws IOException, SAXException, ParserConfigurationException {
    URL url = new URL("http://schemas.opengis.net/wps/1.0.0/examples/51_wpsExecute_request_ResponseDocument.xml");
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        org.geotools.xml.Parser parser = new org.geotools.xml.Parser(new WPSConfiguration());
        Object obj = parser.parse(in);
        assertNotNull(obj);
    } catch (UnknownHostException notFound) {
        System.out.println("WARNING " + notFound.getClass().getName() + ":" + notFound.getMessage());
        System.out.println("the server was not found - you may be running" + "in offline mode - or behind a firewall?" + "in anycase this represents a failure of network" + "and not our software");
    }
}
Example 51
Project: astrid-master  File: SrtParser.java View source code
public static TextTrackImpl parse(InputStream is) throws IOException {
    LineNumberReader r = new LineNumberReader(new InputStreamReader(is, "UTF-8"));
    TextTrackImpl track = new TextTrackImpl();
    String numberString;
    while ((numberString = r.readLine()) != null) {
        String timeString = r.readLine();
        String lineString = "";
        String s;
        while (!((s = r.readLine()) == null || s.trim().equals(""))) {
            lineString += s + "\n";
        }
        long startTime = parse(timeString.split("-->")[0]);
        long endTime = parse(timeString.split("-->")[1]);
        track.getSubs().add(new TextTrackImpl.Line(startTime, endTime, lineString));
    }
    return track;
}
Example 52
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 53
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 54
Project: sonar-java-master  File: DefaultEncodingUsageCheck.java View source code
void myMethod(byte[] bytes, java.io.File file, OutputStream outputStream) {
    // Noncompliant {{Remove this use of constructor "String(byte[])"}}
    new String(bytes);
    // Noncompliant {{Remove this use of constructor "String(byte[],int,int)"}}
    new String(bytes, 0, 1);
    // Noncompliant {{Remove this use of "getBytes"}}
    "".getBytes();
    // Noncompliant {{Remove this use of "getBytes"}}
    "".getBytes(0, 0, bytes, 0);
    // Noncompliant
    new java.io.ByteArrayOutputStream().toString();
    // Noncompliant
    new FileReader("fileName");
    // Noncompliant [[sc=9;ec=19]]
    new FileReader(file);
    // Noncompliant
    new FileReader(new java.io.FileDescriptor());
    // Noncompliant
    new FileWriter(file);
    // Noncompliant
    new FileWriter(file, true);
    // Noncompliant
    new FileWriter(new java.io.FileDescriptor());
    // Noncompliant
    new FileWriter("fileName");
    // Noncompliant
    new FileWriter("fileName", true);
    // Noncompliant
    new InputStreamReader(new java.io.FileInputStream(""));
    // Noncompliant
    new OutputStreamWriter(outputStream);
    // Noncompliant
    new PrintStream(file);
    // Noncompliant
    new PrintStream(outputStream);
    // Noncompliant
    new PrintStream(outputStream, true);
    // Noncompliant
    new PrintStream("fileName");
    // Noncompliant
    new PrintWriter(file);
    // Noncompliant
    new PrintWriter(outputStream);
    // Noncompliant
    new PrintWriter(outputStream, true);
    // Noncompliant
    new PrintWriter("fileName");
    // Noncompliant
    new Formatter("");
    // Noncompliant
    new Formatter(file);
    // Noncompliant
    new Formatter(outputStream);
    // Noncompliant
    new Scanner(file);
    // Noncompliant
    new java.util.Scanner(new java.io.FileInputStream(""));
    // Noncompliant
    FileReader reader = null;
    // Noncompliant
    FileReader reader3 = new FileReader("");
    // Noncompliant [[sc=30;ec=40]]
    java.io.Reader reader2 = fileReader();
    // Noncompliant
    FileWriter writer = null;
    // Noncompliant
    java.io.Writer writer2 = fileWriter();
    // Compliant
    new String("");
    "".length();
    new java.io.ByteArrayOutputStream().toString("UTF-8");
    UnknownClass unknown;
}
Example 55
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 56
Project: property-db-master  File: GraphReader.java View source code
public FilterGraph readGraphResource(Context context, int resourceId) throws GraphIOException {
    InputStream inputStream = context.getResources().openRawResource(resourceId);
    InputStreamReader reader = new InputStreamReader(inputStream);
    StringWriter writer = new StringWriter();
    char[] buffer = new char[1024];
    try {
        int bytesRead;
        while ((bytesRead = reader.read(buffer, 0, 1024)) > 0) {
            writer.write(buffer, 0, bytesRead);
        }
    } catch (IOException e) {
        throw new RuntimeException("Could not read specified resource file!");
    }
    return readGraphString(writer.toString());
}
Example 57
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 58
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 59
Project: jeboorker-master  File: XslBookProcessor.java View source code
@Override
public byte[] processHtml(Resource resource, Book book, String encoding) throws IOException {
    Source htmlSource = new StreamSource(new InputStreamReader(resource.getInputStream(), resource.getInputEncoding()));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Writer writer = new OutputStreamWriter(out, encoding);
    Result streamResult = new StreamResult(writer);
    try {
        transformer.transform(htmlSource, streamResult);
    } catch (TransformerException e) {
        log.log(Level.WARNING, e.getMessage(), e);
        throw new IOException(e);
    }
    byte[] result = out.toByteArray();
    return result;
}
Example 60
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 61
Project: picard-tools-master  File: LineReaderUtil.java View source code
/**
     * Convenience factory for composing a LineReader from an InputStream.
     */
public static LineReader fromBufferedStream(final InputStream bufferedStream, final LineReaderOption option) {
    final InputStreamReader bufferedInputStreamReader = new InputStreamReader(bufferedStream);
    switch(option) {
        case ASYNCHRONOUS:
            return new AsynchronousLineReader(bufferedInputStreamReader);
        case SYNCHRONOUS:
            return new LineReader() {

                final LongLineBufferedReader reader = new LongLineBufferedReader(bufferedInputStreamReader);

                @Override
                public String readLine() {
                    try {
                        return reader.readLine();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public void close() {
                    CloserUtil.close(reader);
                }
            };
        default:
            throw new TribbleException(String.format("Unrecognized LineReaderUtil option: %s.", option));
    }
}
Example 62
Project: eclipselink.runtime-master  File: ByteArrayDataSource.java View source code
public String getContentType() {
    if (contentType.startsWith("multipart") && contentType.indexOf("boundary") == -1) {
        //parse the bytes for the header and extract the boundary. Add it into the content type.
        StringBuilder buffer = new StringBuilder();
        InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(bytes));
        while (true) {
            try {
                int next = reader.read();
                if (next == -1) {
                    break;
                } else if (((char) next) == '\n') {
                    if (!(buffer.length() == 0)) {
                        break;
                    }
                } else {
                    buffer.append((char) next);
                }
            } catch (Exception ex) {
            }
        }
        //buffer should contain the header string here.
        int index = buffer.indexOf("boundary");
        if (index != -1) {
            contentType += ";" + buffer.substring(index);
        }
    }
    return contentType;
}
Example 63
Project: levelup-java-examples-master  File: ParseCSVFile.java View source code
@Test
public void read_CSV_File_With_OpenCSV() {
    // If you are using spring, you could use a bit cleaner way Resource resource = new ClassPathResource
    InputStream in = this.getClass().getClassLoader().getResourceAsStream("planets.csv");
    try {
        CSVReader reader = new CSVReader(new InputStreamReader(in), '\t');
        List<String[]> rows = reader.readAll();
        for (int x = 0; x < rows.size(); x++) {
            String[] columns = rows.get(x);
            for (int y = 0; y < columns.length; y++) {
                logger.info(columns[y]);
            }
        }
        reader.close();
    } catch (FileNotFoundException e) {
        logger.error(e);
    } catch (IOException e) {
        logger.error(e);
    }
}
Example 64
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 65
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 66
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 67
Project: h2-bitmap-master  File: TestScriptSimple.java View source code
public void test() throws Exception {
    if (config.memory || config.big || config.networked) {
        return;
    }
    deleteDb("scriptSimple");
    reconnect();
    String inFile = "org/h2/test/testSimple.in.txt";
    InputStream is = getClass().getClassLoader().getResourceAsStream(inFile);
    LineNumberReader lineReader = new LineNumberReader(new InputStreamReader(is, "Cp1252"));
    ScriptReader reader = new ScriptReader(lineReader);
    while (true) {
        String sql = reader.readStatement();
        if (sql == null) {
            break;
        }
        sql = sql.trim();
        try {
            if ("@reconnect".equals(sql.toLowerCase())) {
                reconnect();
            } else if (sql.length() == 0) {
            // ignore
            } else if (sql.toLowerCase().startsWith("select")) {
                ResultSet rs = conn.createStatement().executeQuery(sql);
                while (rs.next()) {
                    String expected = reader.readStatement().trim();
                    String got = "> " + rs.getString(1);
                    assertEquals(sql, expected, got);
                }
            } else {
                conn.createStatement().execute(sql);
            }
        } catch (SQLException e) {
            System.out.println(sql);
            throw e;
        }
    }
    is.close();
    conn.close();
    deleteDb("scriptSimple");
}
Example 68
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 69
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 70
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 71
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 72
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 73
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 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: 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 79
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 80
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 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: AnSiAn-master  File: Parser.java View source code
public List<MorseCodeCharacter> parseDocument(String pathToDocument) {
    InputSource is = null;
    try {
        AssetManager assetManager = MainActivity.instance.getAssets();
        InputStream inputStream = assetManager.open(pathToDocument);
        Log.d("Parser", pathToDocument);
        Reader reader = new InputStreamReader(inputStream, "UTF-8");
        is = new InputSource(reader);
        is.setEncoding("UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        SAXParser sp = spf.newSAXParser();
        sp.parse(is, this);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return tempMorseCharacters;
}
Example 88
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 89
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 90
Project: Jorum-DSpace-master  File: JettyStopListener.java View source code
public void run() {
    while (_serverSocket != null) {
        Socket socket = null;
        try {
            socket = _serverSocket.accept();
            socket.setSoLinger(false, 0);
            LineNumberReader lin = new LineNumberReader(new InputStreamReader(socket.getInputStream()));
            String key = lin.readLine();
            if (!_key.equals(key))
                continue;
            String cmd = lin.readLine();
            if ("stop".equals(cmd)) {
                try {
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    _serverSocket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                _serverSocket = null;
                if (_kill) {
                    System.exit(0);
                } else {
                    try {
                        _server.stop();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            socket = null;
        }
    }
}
Example 91
Project: SealBrowser-master  File: TestFileUtil.java View source code
/**
     * @param fileName the file to read in.
     * @param sizeLimit cap on the file size: will throw an exception if exceeded
     * @return Array of chars read from the file
     * @throws FileNotFoundException file does not exceed
     * @throws IOException error encountered accessing the file
     */
public static char[] readUtf8File(String fileName, int sizeLimit) throws FileNotFoundException, IOException {
    Reader reader = null;
    try {
        File f = new File(fileName);
        if (f.length() > sizeLimit) {
            throw new IOException("File " + fileName + " length " + f.length() + " exceeds limit " + sizeLimit);
        }
        char[] buffer = new char[(int) f.length()];
        reader = new InputStreamReader(new FileInputStream(f), "UTF-8");
        int charsRead = reader.read(buffer);
        // file grew after we inspected its length).
        assert !reader.ready();
        return charsRead < buffer.length ? Arrays.copyOfRange(buffer, 0, charsRead) : buffer;
    } finally {
        if (reader != null)
            reader.close();
    }
}
Example 92
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 93
Project: netlib-java-master  File: F2jJavadocExtractor.java View source code
private String getRawJavadoc(Method method) throws IOException {
    String filename = method.getDeclaringClass().getCanonicalName().replace(".", "/") + ".html";
    @Cleanup ZipFile zip = new ZipFile(jar);
    Enumeration<? extends ZipEntry> en = zip.entries();
    while (en.hasMoreElements()) {
        ZipEntry entry = en.nextElement();
        if (entry.getName().endsWith(filename)) {
            @Cleanup InputStreamReader stream = new InputStreamReader(zip.getInputStream(entry), "UTF-8");
            return CharStreams.toString(stream);
        }
    }
    return "";
}
Example 94
Project: lucene-solr-master  File: FileDictionaryFactory.java View source code
@Override
public Dictionary create(SolrCore core, SolrIndexSearcher searcher) {
    if (params == null) {
        // should not happen; implies setParams was not called
        throw new IllegalStateException("Value of params not set");
    }
    String sourceLocation = (String) params.get(Suggester.LOCATION);
    if (sourceLocation == null) {
        throw new IllegalArgumentException(Suggester.LOCATION + " parameter is mandatory for using FileDictionary");
    }
    String fieldDelimiter = (params.get(FIELD_DELIMITER) != null) ? (String) params.get(FIELD_DELIMITER) : FileDictionary.DEFAULT_FIELD_DELIMITER;
    try {
        return new FileDictionary(new InputStreamReader(core.getResourceLoader().openResource(sourceLocation), StandardCharsets.UTF_8), fieldDelimiter);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 95
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 96
Project: openjdk-master  File: FeaturePropagationTest.java View source code
public static void main(String[] args) throws Exception {
    InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(xsd.getBytes()));
    StreamSource xsdSource = new StreamSource(reader);
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    schemaFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
    Schema schema = null;
    schema = schemaFactory.newSchema(xsdSource);
    Validator validator = schema.newValidator();
    if (validator.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)) {
        throw new RuntimeException("Feature set on the factory is not inherited!");
    }
}
Example 97
Project: kabeja-master  File: FontManager.java View source code
private void loadFontDescription() {
    fontProperties.clear();
    try {
        InputStream stream = this.getClass().getResourceAsStream(this.fontDescription);
        if (stream == null) {
            try {
                stream = new FileInputStream(this.fontDescription);
            } catch (FileNotFoundException e1) {
            }
        }
        if (stream != null) {
            BufferedReader in = new BufferedReader(new InputStreamReader(stream));
            String line = null;
            while ((line = in.readLine()) != null) {
                int index = line.indexOf("=");
                if (index >= 0) {
                    String font = line.substring(0, index).trim().toLowerCase();
                    String svgFont = line.substring(index + 1).trim();
                    fontProperties.put(font, svgFont);
                }
            }
            in.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 98
Project: oobd-master  File: AssetInstaller.java View source code
public boolean isInstallNeeded() {
    String amName = target + "/am.rev";
    File revFile = new File(amName);
    if (!revFile.exists()) {
        return true;
    }
    String line;
    try {
        InputStream fis = new FileInputStream(amName);
        InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
        inputFileReader = new BufferedReader(isr);
        line = inputFileReader.readLine();
        inputFileReader.close();
        isr.close();
        fis.close();
        return (line == null || line.trim().equalsIgnoreCase(rev));
    } catch (IOException e) {
        return true;
    }
}
Example 99
Project: gcontact-excel-sync-master  File: OAuthHttpClient.java View source code
/**
   * Makes an http request to the input URL, and returns the response body as a
   * string.
   *
   * @param url the url to make the request to
   * @param headers any headers to add to the request
   * @return the response body of the request
   * @throws OAuthException if there was an error making the request
   */
public String getResponse(URL url, Map<String, String> headers) throws OAuthException {
    try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        if (headers != null) {
            for (Entry<String, String> entry : headers.entrySet()) {
                connection.addRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        connection.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return response.toString();
    } catch (IOException e) {
        throw new OAuthException("Error getting HTTP response", e);
    }
}
Example 100
Project: erlide-master  File: LogUtil.java View source code
public static String fetchErlideLog() {
    final StringBuffer result = new StringBuffer();
    final File log = new File(ErlLogger.getInstance().getLogFile());
    try (final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(log), "UTF-8"))) {
        for (; ; ) {
            final String line = reader.readLine();
            if (line == null) {
                break;
            }
            if (line.length() == 0) {
                continue;
            }
            result.append(line).append('\n');
        }
    } catch (final Exception e) {
        ErlLogger.warn(e);
    }
    return result.toString();
}
Example 101
Project: dtangler-master  File: ConfigFileParser.java View source code
public InputStream convertBackSlashes(InputStream stream) {
    InputStreamReader reader = new InputStreamReader(stream);
    int slashCount = 0;
    try {
        StringBuilder b = new StringBuilder();
        try {
            while (true) {
                int value = reader.read();
                if (value == -1)
                    break;
                char c = (char) value;
                if (slashCount == 1)
                    if (slashCount == 1 && (!Character.isWhitespace(c) && c != '\\')) {
                        b.append('\\');
                    }
                b.append(c);
                slashCount = (c == '\\') ? slashCount + 1 : 0;
            }
            byte[] byteArray = b.toString().getBytes("ISO-8859-1");
            return new ByteArrayInputStream(byteArray);
        } catch (IOException e) {
            throw new RuntimeException("Reading stream failed", e);
        }
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
        }
    }
}