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(Reader input) throws IOException 

Source Link

Document

Get the contents of a Reader as a list of Strings, one entry per line.

Usage

From source file:android.databinding.tool.DataBindingExcludeGeneratedTask.java

private List<String> readGeneratedClasses() {
    Preconditions.checkNotNull(generatedClassListFile,
            "Data binding exclude generated task" + " is not configured properly");
    Preconditions.checkArgument(generatedClassListFile.exists(), "Generated class list does not exist %s",
            generatedClassListFile.getAbsolutePath());
    FileInputStream fis = null;//from w w  w .jav a2s  . c o  m
    try {
        fis = new FileInputStream(generatedClassListFile);
        return IOUtils.readLines(fis);
    } catch (FileNotFoundException e) {
        L.e(e, "Unable to read generated class list from %s", generatedClassListFile.getAbsoluteFile());
    } catch (IOException e) {
        L.e(e, "Unexpected exception while reading %s", generatedClassListFile.getAbsoluteFile());
    } finally {
        IOUtils.closeQuietly(fis);
    }
    Preconditions.checkState(false, "Could not read data binding generated class list");
    return null;
}

From source file:com.nsano.uat.StatusServlet.java

/**
 *
 * @param request//from  w  w  w.  j ava2  s . c  om
 * @return
 * @throws IOException
 */
private String moneytransfer(HttpServletRequest request)
        throws IOException, JSONException, NoSuchAlgorithmException {

    // joined json string
    String join = "";
    JsonElement root = null;
    JsonElement root2 = null;
    JsonElement root3 = null;

    String responseobject = "";

    //String nickname="KENDYIPL";
    // These represent parameters received over the network
    String tag = "", apikey = "", refID = "", sender = "", sender_country = "", receiver = "",
            receiver_msisdn = "", receiver_country = "", amount = "", mno = "";

    //referenceid, customermsisdn, nickname,amount, batchref, username, password, narrative
    // Get all parameters, the keys of the parameters are specified
    List<String> lines = IOUtils.readLines(request.getReader());

    // used to format/join incoming JSon string
    join = StringUtils.join(lines.toArray(), "");

    //###############################################################################
    // instantiate the JSon
    //Note
    //The = sign is encoded to \u003d. Hence you need to use disableHtmlEscaping().
    //###############################################################################
    Gson g = new GsonBuilder().disableHtmlEscaping().create();
    //Gson g = new Gson();
    Map<String, String> expected = new HashMap<>();

    try {
        // parse the JSon string
        //referenceid, customermsisdn, nickname,amount, batchref, username, password, narrative

        root = new JsonParser().parse(join);

        tag = root.getAsJsonObject().get("tag").getAsString();

        apikey = root.getAsJsonObject().get("apikey").getAsString();
        refID = root.getAsJsonObject().get("refID").getAsString();

        sender = root.getAsJsonObject().get("sender").getAsString();
        sender_country = root.getAsJsonObject().get("sender_country").getAsString();

        receiver = root.getAsJsonObject().get("receiver").getAsString();
        receiver_msisdn = root.getAsJsonObject().get("receiver_msisdn").getAsString();

        receiver_country = root.getAsJsonObject().get("receiver_country").getAsString();
        amount = root.getAsJsonObject().get("amount").getAsString();

        mno = root.getAsJsonObject().get("mno").getAsString();

    } catch (Exception e) {

        expected.put("command_status", "COMMANDSTATUS_INVALID_PARAMETERS");
        String jsonResult = g.toJson(expected);
        System.out.println(e);

        return jsonResult;
    }

    //check for the presence of all required parameters
    if (StringUtils.isBlank(tag) || StringUtils.isBlank(apikey) || StringUtils.isBlank(refID)
            || StringUtils.isBlank(sender) || StringUtils.isBlank(sender_country)
            || StringUtils.isBlank(receiver) || StringUtils.isBlank(receiver_msisdn)
            || StringUtils.isBlank(receiver_country) || StringUtils.isBlank(amount)
            || StringUtils.isBlank(mno)) {

        //expected.put("username", username);
        expected.put("status_code", statuscode);
        expected.put("status_description", Statusdescription);
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }

    //assign the remit url from properties.config
    //String processtransaction = airtelbalance.AirtelBalance( nickname, username, password);
    String processtransaction = st.sendPOST();
    //capture the switch respoinse.

    System.out.println(processtransaction);

    //pass the returned json string
    JsonElement roots = new JsonParser().parse(processtransaction);
    //JsonElement rootsone = roots.getAsJsonObject();

    //exctract a specific json element from the object(status_code)
    //Double code = roots.getAsJsonObject().get("code").getAsDouble();
    Number code = roots.getAsJsonObject().get("code").getAsNumber();
    System.out.println("####################################################################");
    System.out.println(code);
    System.out.println("####################################################################");
    String msg = roots.getAsJsonObject().get("msg").getAsString();
    System.out.println(msg);
    System.out.println("#####################################################################");
    //String d                                                                                          ata = rootsone.getAsJsonObject().get("error_type").getAsString();

    // loop array

    //add 
    //expected.put("username", username);
    expected.put("code", code.toString());
    expected.put("msg", msg.toString());
    //expected.put("error_type", data.toString());

    String jsonResult = g.toJson(expected);

    if (code.toString() == "01") {

        System.out.println("fail");

    } else {

        System.out.println("success");

    }

    return jsonResult;

}

From source file:net.ostis.scpdev.builder.SCsFileBuilder.java

protected void applySCsErrors(IFile source, InputStream errorStream) throws IOException {
    @SuppressWarnings("unchecked")
    List<String> errorLines = IOUtils.readLines(errorStream);
    if (errorLines.isEmpty())
        return;/* ww  w . j  a  v a 2  s .  c  om*/

    if (errorLines.size() != 1) {
        errorLines.remove(errorLines.size() - 1);

        for (String errorLine : errorLines) {
            Matcher matcher = ERROR_TYPE_1_PATTERN.matcher(errorLine);
            if (matcher.matches()) {
                addMarker(matcher.group(1), Integer.parseInt(matcher.group(2)), IMarker.SEVERITY_ERROR);
            } else {
                matcher = ERROR_TYPE_2_PATTERN.matcher(errorLine);
                if (matcher.matches()) {
                    addMarker(matcher.group(1), Integer.parseInt(matcher.group(2)), IMarker.SEVERITY_ERROR);
                } else {
                    addMarker(errorLine, 1, IMarker.SEVERITY_ERROR);
                }
            }
        }
    } else {
        addMarker(errorLines.get(0), 1, IMarker.SEVERITY_ERROR);
    }
}

From source file:net.lyonlancer5.mcmp.karasu.util.VersionIdentifier.java

/**
 * Checks if the given version is compatible with the current version running
 * @param remoteVersion The version we are connecting to
 * @param remoteSide The side of the target connection
 *//*from w w w  . jav a 2s. c o m*/
public boolean isCompatibleVersion(String remoteVersion, Side remoteSide) {
    Constants.LOGGER.info("Remote version: " + remoteVersion + " @ Side." + remoteSide.name());
    Constants.LOGGER.info(
            "Local version: " + Constants.VERSION + " @ Side." + FMLCommonHandler.instance().getSide().name());

    try {
        if (!localCompatLoc.exists()
                || (System.currentTimeMillis() - localCompatLoc.lastModified()) > 604800000000L) {
            ModFileUtils.download(remoteCompatLoc, localCompatLoc);
        }

        List<String> lines = IOUtils.readLines(new FileInputStream(localCompatLoc));
        for (String s : lines) {
            String[] pars = s.split(":");
            if (pars[0].equalsIgnoreCase(Constants.VERSION)) {
                for (String oneVer : pars[1].split(",")) {
                    if (oneVer.equals(remoteVersion))
                        return true;
                    else
                        continue;
                }
            }
        }

    } catch (Exception e) {
        //NOISE
    }

    Map<String, Integer> localv = identify(Constants.VERSION), remotev = identify(remoteVersion);
    if (remotev.get("major") != localv.get("major"))
        return false;
    if (remotev.get("minor") != localv.get("minor"))
        return false;
    if (remotev.get("revision") != localv.get("revision"))
        return false;

    if (remotev.get("is-pre-release") == localv.get("is-pre-release")) {
        return true;
    } else {
        return false;
    }
}

From source file:com.boozallen.cognition.ingest.storm.bolt.starter.FlattenJsonBoltTest.java

@Test
public void testParseJson() throws IOException {
    try (InputStream sampleDataStream = TestResourceUtils.getResourceAsStream(this.getClass(), "test.json")) {
        List<String> stringList = IOUtils.readLines(sampleDataStream);
        String jsonString = StringUtils.join(stringList, "");

        LogRecord logRecord = new LogRecord();
        bolt.parseJson(jsonString, logRecord);

        Map<String, String> fields = logRecord.getFields();
        assertThat(fields.size(), is(6));
        assertThat(fields.get("boolean"), is("true"));
        assertThat(fields.get("object.a"), is("a"));
        assertThat(fields.get("number"), is("1234"));
        assertThat(fields.get("string"), is("string"));
        assertThat(fields.get("list"), is("[\"value0\",\"value1\"]"));
        assertThat(fields.get("object_list"), is("[{\"a\":\"a\"},{\"b\":\"b\"}]"));
    }/* w  w w  . j  av  a2  s.  c  o  m*/
}

From source file:com.splunk.shuttl.testutil.ShellClassRunner.java

private List<String> readInputStream(InputStream inputStream) {
    try {/*from   w  w w . j  ava  2s . c o m*/
        return IOUtils.readLines(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:com.logsniffer.model.file.RollingLogSourceTest.java

@Test
public void testRollingLogAccess() throws Exception {
    final RollingLogsSource source = new RollingLogsSource();
    source.setPattern(logDir.getPath() + "/server.log");
    source.setPastLogsSuffixPattern(".UNKNOWN");
    source.setPastLogsType(PastLogsType.NAME);

    // Test only live
    Log[] rolledLogs = source.getLogs().toArray(new Log[0]);
    Assert.assertEquals(1, rolledLogs.length);
    Assert.assertEquals(5, rolledLogs[0].getSize());
    Assert.assertEquals("live",
            IOUtils.readLines(
                    new DailyRollingLogAccess(new DirectFileLogAccessor(), (DailyRollingLog) rolledLogs[0])
                            .getInputStream(null))
                    .get(0));//from   w w w . ja  v a 2  s.  c  o  m

    // Test past ordered desc by name
    source.setPastLogsSuffixPattern(".*");
    rolledLogs = source.getLogs().toArray(new Log[0]);
    Assert.assertEquals(1, rolledLogs.length);
    BufferedReader lr = new BufferedReader(new InputStreamReader(
            new DailyRollingLogAccess(new DirectFileLogAccessor(), (DailyRollingLog) rolledLogs[0])
                    .getInputStream(null)));
    Assert.assertEquals("log from 2013-03-26", lr.readLine());
    Assert.assertEquals("log from 2013-03-27", lr.readLine());
    Assert.assertEquals("live", lr.readLine());

    // Test ordered by modification date
    source.setPastLogsType(PastLogsType.LAST_MODIFIED);
    rolledLogs = source.getLogs().toArray(new Log[0]);
    lr = new BufferedReader(new InputStreamReader(
            new DailyRollingLogAccess(new DirectFileLogAccessor(), (DailyRollingLog) rolledLogs[0])
                    .getInputStream(null)));
    Assert.assertEquals("log from 2013-03-27", lr.readLine());
    Assert.assertEquals("log from 2013-03-26", lr.readLine());
    Assert.assertEquals("live", lr.readLine());
}

From source file:brut.androlib.res.ResSmaliUpdater.java

private void tagResIdsForFile(ResTable resTable, Directory dir, String fileName)
        throws IOException, DirectoryException, AndrolibException {
    Iterator<String> it = IOUtils.readLines(dir.getFileInput(fileName)).iterator();
    PrintWriter out = new PrintWriter(dir.getFileOutput(fileName));
    while (it.hasNext()) {
        String line = it.next();//from   ww w .  j a v  a 2  s.  c  o  m
        if (RES_NAME_PATTERN.matcher(line).matches()) {
            out.println(line);
            out.println(it.next());
            continue;
        }
        Matcher m = RES_ID_PATTERN.matcher(line);
        if (m.matches()) {
            int resID = parseResID(m.group(3));
            if (resID != -1) {
                try {
                    ResResSpec spec = resTable.getResSpec(resID);
                    out.println(String.format(RES_NAME_FORMAT, spec.getFullName()));
                } catch (UndefinedResObject ex) {
                    if (!R_FILE_PATTERN.matcher(fileName).matches()) {
                        LOGGER.warning(String.format("Undefined resource spec in %s: 0x%08x", fileName, resID));
                    }
                }
            }
        }
        out.println(line);
    }
    out.close();
}

From source file:com.music.service.text.TimelineToMusicService.java

@PostConstruct
public void init() throws IOException {
    provider = new TwitterServiceProvider(appKey, appSecret);
    stopwords = new HashSet<>(
            IOUtils.readLines(TimelineToMusicService.class.getResourceAsStream("/stopwords.txt")));
}

From source file:de.rallye.test.GroupsTest.java

@Test
public void testLogin() throws IOException {

    Authenticator.setDefault(new Authenticator() {
        @Override//from  ww  w . java 2  s .  co  m
        protected PasswordAuthentication getPasswordAuthentication() {
            String realm = getRequestingPrompt();
            assertEquals("Should be right Realm", "RallyeNewUser", realm);
            return new PasswordAuthentication(String.valueOf(1), "test".toCharArray());
        }
    });
    URL url = new URL("http://127.0.0.1:10111/groups/1");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");

    conn.setDoOutput(true);
    conn.addRequestProperty("Content-Type", "application/json");
    //      conn.setFixedLengthStreamingMode(post.length);
    conn.getOutputStream().write(MockDataAdapter.validLogin.getBytes());

    int code = conn.getResponseCode();

    Authenticator.setDefault(null);

    try {
        assertEquals("Code should be 200", 200, code);
    } catch (AssertionError e) {
        System.err.println("This is the content:");
        List<String> contents = IOUtils.readLines((InputStream) conn.getContent());
        for (String line : contents)
            System.err.println(line);
        throw e;
    }

}