Example usage for org.apache.commons.io IOUtils readLines

List of usage examples for org.apache.commons.io IOUtils readLines

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils readLines.

Prototype

public static List readLines(InputStream input, String encoding) throws IOException 

Source Link

Document

Get the contents of an InputStream as a list of Strings, one entry per line, using the specified character encoding.

Usage

From source file:br.com.thiagomoreira.bancodobrasil.Main.java

/**
 * @param args//from ww  w  .  j a v  a  2  s .  c  o  m
 */
public static void main(String[] args) throws Exception {
    if (args != null) {
        NumberFormat formatter = NumberFormat.getNumberInstance(new Locale("pt", "BR"));

        formatter.setMaximumFractionDigits(2);
        formatter.setMinimumFractionDigits(2);

        double total = 0;

        for (String arg : args) {
            File input = new File(arg);
            if (input.exists()) {
                List<String> lines = IOUtils.readLines(new FileInputStream(input), "ISO-8859-1");

                Parser parser = new DefaultParser();

                List<Transaction> transactions = parser.parse(lines);

                TransactionList transactionList = new TransactionList();
                transactionList.setStart(parser.getStartDate());
                transactionList.setEnd(parser.getEndDate());
                transactionList.setTransactions(transactions);

                CreditCardAccountDetails creditCardAccountDetails = new CreditCardAccountDetails();
                creditCardAccountDetails.setAccountNumber("7616-3");
                creditCardAccountDetails.setAccountKey(parser.getAccountKey());

                CreditCardStatementResponse creditCardStatementResponse = new CreditCardStatementResponse();
                creditCardStatementResponse.setAccount(creditCardAccountDetails);
                creditCardStatementResponse.setCurrencyCode("BRL");
                creditCardStatementResponse.setTransactionList(transactionList);

                Status status = new Status();
                status.setCode(Status.KnownCode.SUCCESS);
                status.setSeverity(Status.Severity.INFO);

                CreditCardStatementResponseTransaction statementResponse = new CreditCardStatementResponseTransaction();
                statementResponse.setClientCookie(UUID.randomUUID().toString());
                statementResponse.setStatus(status);
                statementResponse.setUID(UUID.randomUUID().toString());
                statementResponse.setMessage(creditCardStatementResponse);

                CreditCardResponseMessageSet creditCardResponseMessageSet = new CreditCardResponseMessageSet();
                creditCardResponseMessageSet.setStatementResponse(statementResponse);

                SortedSet<ResponseMessageSet> messageSets = new TreeSet<ResponseMessageSet>();
                messageSets.add(creditCardResponseMessageSet);

                ResponseEnvelope envelope = new ResponseEnvelope();
                envelope.setUID(UUID.randomUUID().toString());
                envelope.setSecurity(ApplicationSecurity.NONE);
                envelope.setMessageSets(messageSets);

                double brazilianRealsamount = parser.getBrazilianRealsAmount();
                double dolarsAmount = parser.getDolarsAmount();
                double cardTotal = dolarsAmount * parser.getExchangeRate() + brazilianRealsamount;
                total += cardTotal;

                System.out.println(creditCardAccountDetails.getAccountKey());
                System.out.println("TOTAL EM RS " + formatter.format(brazilianRealsamount));
                System.out.println("TOTAL EM US " + formatter.format(dolarsAmount));
                System.out.println("TOTAL FATURA EM RS " + formatter.format(cardTotal));
                System.out.println();

                if (!transactions.isEmpty()) {
                    String parent = System.getProperty("user.home") + "/Downloads";
                    String fileName = arg.replace(".txt", ".ofx");
                    File output = new File(parent, fileName);
                    FileOutputStream fos = new FileOutputStream(output);

                    OFXV1Writer writer = new OFXV1Writer(fos);
                    writer.setWriteAttributesOnNewLine(true);

                    AggregateMarshaller marshaller = new AggregateMarshaller();
                    marshaller.setConversion(new MyFinanceStringConversion());
                    marshaller.marshal(envelope, writer);

                    writer.flush();
                    writer.close();
                }
            }
        }
        System.out.println("TOTAL FATURAS EM RS " + formatter.format(total));
    }

}

From source file:com.uksf.mf.core.utility.ClassNames.java

/**
 * Gets class names from file on uksf server
 * @return map of class names: old, new/*w  ww  . ja v  a  2 s  .c o m*/
 */
public static LinkedHashMap<String, String> getClassNames() {
    LinkedHashMap<String, String> classNames = new LinkedHashMap<>();
    try {
        URL url = new URL("http://www.uk-sf.com/mf/CLASSES.txt");
        if (checkConnection(url)) {
            throw new IOException();
        }
        InputStream stream = url.openStream();
        List<String> lines = IOUtils.readLines(stream, "UTF-8");
        for (String line : lines) {
            String parts[] = line.split(",", -1);
            if (parts[1] == null)
                parts[1] = "";
            classNames.put(parts[0], parts[1]);
        }
    } catch (IOException e) {
        LogHandler.logSeverity(WARNING, "Cannot reach 'www.uk-sf.com', class name swap will not run");
        return null;
    }
    return classNames;
}

From source file:com.athena.peacock.controller.common.util.DiffUtil.java

public static Patch<String> getDiff(File original, File revised) throws Exception {
    return getDiff(IOUtils.readLines(new FileInputStream(original), "UTF-8"),
            IOUtils.readLines(new FileInputStream(revised), "UTF-8"));
}

From source file:com.handcraftedbits.bamboo.plugin.go.parser.GoTestParser.java

@SuppressWarnings("unchecked")
public static List<PackageTestResults> parseTests(final InputStream input) throws Exception {
    final List<String> lines = IOUtils.readLines(input, "UTF-8");
    final List<PackageTestResults> packageTestResults = new LinkedList<>();
    final Stack<SingleTestResult> testResults = new Stack<>();

    for (final String line : lines) {
        // A test has finished.  Parse it out and push it on the stack until we know which package it belongs to.

        if (line.startsWith("---")) {
            final Matcher matcher = GoTestParser.patternTestFinish.matcher(line);

            if (matcher.matches()) {
                TestStatus status = null;

                switch (matcher.group(1)) {
                case "FAIL": {
                    status = TestStatus.FAILED;

                    break;
                }//from  ww  w.  j a va  2s .  c  o m

                case "PASS": {
                    status = TestStatus.PASSED;

                    break;
                }

                case "SKIP": {
                    status = TestStatus.SKIPPED;

                    break;
                }
                }

                if (status != null) {
                    testResults.push(new SingleTestResult(matcher.group(2), status,
                            Double.parseDouble(matcher.group(3))));
                }
            }
        }

        // This is either noise or a finished set of package tests.

        else {
            final Matcher matcher = GoTestParser.patternPackageFinish.matcher(line);

            // We have a finished set of package tests, so create the model for it and clear the stack of tests.

            if (matcher.matches()) {
                final PackageTestResults packageResults = new PackageTestResults(matcher.group(2));

                // In this case, either the go test run did not specify -v or there are no tests in the
                // package.  We'll create a single "AllTests" test and assign it the correct status.  In the
                // case of no tests existing for the package, the status will be "skipped".

                if (testResults.empty()) {
                    double duration = 0.0d;
                    final String durationStr = matcher.group(3);
                    TestStatus testStatus = TestStatus.SKIPPED;

                    switch (matcher.group(1)) {
                    case "FAIL": {
                        testStatus = TestStatus.FAILED;

                        break;
                    }

                    case "ok  ": {
                        testStatus = TestStatus.PASSED;

                        break;
                    }
                    }

                    // If there are tests in the package, we should be able to extract the duration.

                    if (durationStr.endsWith("s")) {
                        duration = Double.parseDouble(durationStr.substring(0, durationStr.length() - 1));
                    }

                    packageResults.addTestResult(new SingleTestResult("AllTests", testStatus, duration));
                }

                while (!testResults.empty()) {
                    packageResults.addTestResult(testResults.pop());
                }

                packageTestResults.add(packageResults);
            }
        }
    }

    IOUtils.closeQuietly(input);

    return packageTestResults;
}

From source file:com.lyricaloriginal.picturediaryapp.OssActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_oss);
    InputStream is = null;/*  w ww . j  a  va2  s. c om*/
    try {
        is = getAssets().open("apache_license.txt");
        List<String> lines = IOUtils.readLines(is, "UTF-8");
        TextView v = (TextView) findViewById(R.id.apacheLicTextView);
        for (String l : lines) {
            v.append(l + "\n");
        }
    } catch (IOException ex) {
        Log.e("DIARY", ex.getMessage(), ex);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.geewhiz.pacify.utils.FileUtils.java

public static List<String> getFileAsLines(URL fileURL, String encoding) {
    InputStream is = null;//from ww  w.  ja v a  2  s  .c  om
    try {
        is = fileURL.openStream();
        return IOUtils.readLines(is, Charsets.toCharset(encoding));
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:api.location.BaiduPlaceAPI.java

public void myDoGet() {
    try {/*from  w ww  .j a v  a2  s. c o  m*/
        url = new URL(createUrlString());
        httpURLConn = (HttpURLConnection) url.openConnection();
        httpURLConn.setDoOutput(true);
        httpURLConn.setRequestMethod("GET");
        httpURLConn.connect();
        InputStream in = httpURLConn.getInputStream();
        List<String> lines = IOUtils.readLines(in, "UTF-8");
        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            System.out.println(line);
            sb.append(line);
        }
        Response parsed = JSONObject.parseObject(sb.toString(), Response.class);
        System.out.println(parsed);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (httpURLConn != null) {
            httpURLConn.disconnect();
        }
    }
}

From source file:au.org.ala.bhl.service.WebServiceHelper.java

/**
 * Performs a GET on the specified URI, and expects that the output is well formed JSON. The output is parsed into a JsonNode for consumption
 * /*  w w  w . j  a v a2 s  .  c  o m*/
 * @param uri
 * @return
 * @throws IOException
 */
public static JsonNode getJSON(String uri) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(uri);
    httpget.setHeader("Accept", "application/json");
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        @SuppressWarnings("unchecked")
        List<String> lines = IOUtils.readLines(instream, "utf-8");
        String text = StringUtils.join(lines, "\n");
        try {
            JsonNode root = new ObjectMapper().readValue(text, JsonNode.class);
            return root;
        } catch (Exception ex) {
            log("Error parsing results for request: %s\n%s\n", uri, text);
            ex.printStackTrace();
        }

    }
    return null;
}

From source file:com.spotify.scio.extra.transforms.ProcessUtil.java

static String getStream(InputStream is) throws IOException {
    return Joiner.on('\n').join(IOUtils.readLines(is, Charsets.UTF_8));
}

From source file:edworld.pdfreader4humans.PDFReaderTest.java

@Test
public void toTextLines() throws IOException {
    InputStream input = getClass().getResourceAsStream("/testcase1/output.txt");
    try {/* w w  w  .j  a  va  2  s  .  c  om*/
        assertEquals(text(IOUtils.readLines(input, UTF_8)), text(reader.toTextLines()));
    } finally {
        input.close();
    }
}