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:com.snaplogic.snaps.lunex.RequestProcessor.java

public String execute(RequestBuilder rBuilder) throws MalformedURLException, IOException {
    try {/*from  w ww  . ja  v  a2  s.c o  m*/
        URL api_url = new URL(rBuilder.getURL());
        HttpURLConnection httpUrlConnection = (HttpURLConnection) api_url.openConnection();
        httpUrlConnection.setRequestMethod(rBuilder.getMethod().toString());
        httpUrlConnection.setDoInput(true);
        httpUrlConnection.setDoOutput(true);
        if (rBuilder.getSnapType() != LunexSnaps.Read) {
            rBuilder.getHeaders().add(Pair.of(CONTENT_LENGTH, rBuilder.getRequestBodyLenght()));
        }
        for (Pair<String, String> header : rBuilder.getHeaders()) {
            if (!StringUtils.isEmpty(header.getKey()) && !StringUtils.isEmpty(header.getValue())) {
                httpUrlConnection.setRequestProperty(header.getKey(), header.getValue());
            }
        }
        log.debug(String.format(LUNEX_HTTP_INFO, rBuilder.getSnapType(), rBuilder.getURL(),
                httpUrlConnection.getRequestProperties().toString()));
        if (rBuilder.getSnapType() != LunexSnaps.Read) {
            String paramsJson = null;
            if (!StringUtils.isEmpty(paramsJson = rBuilder.getRequestBody())) {
                DataOutputStream cgiInput = new DataOutputStream(httpUrlConnection.getOutputStream());
                log.debug(String.format(LUNEX_HTTP_REQ_INFO, paramsJson));
                cgiInput.writeBytes(paramsJson);
                cgiInput.flush();
                IOUtils.closeQuietly(cgiInput);
            }
        }

        List<String> input = null;
        StringBuilder response = new StringBuilder();
        try (InputStream iStream = httpUrlConnection.getInputStream()) {
            input = IOUtils.readLines(iStream);
        } catch (IOException ioe) {
            log.warn(String.format(INPUT_STREAM_ERROR, ioe.getMessage()));
            try (InputStream eStream = httpUrlConnection.getErrorStream()) {
                if (eStream != null) {
                    input = IOUtils.readLines(eStream);
                } else {
                    response.append(String.format(INPUT_STREAM_ERROR, ioe.getMessage()));
                }
            } catch (IOException ioe1) {
                log.warn(String.format(INPUT_STREAM_ERROR, ioe1.getMessage()));
            }
        }
        statusCode = httpUrlConnection.getResponseCode();
        log.debug(String.format(HTTP_STATUS, statusCode));
        if (input != null && !input.isEmpty()) {
            for (String line : input) {
                response.append(line);
            }
        }
        return formatResponse(response, rBuilder);
    } catch (MalformedURLException me) {
        log.error(me.getMessage(), me);
        throw me;
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
        throw ioe;
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        throw ex;
    }
}

From source file:com.impala.servlet.Balance.java

/**
 * //from  ww w .ja v  a 2  s  . co m
 * @param request
 * @return
 * @throws IOException
 */
private String moneytransfer(HttpServletRequest request) throws IOException, JSONException {

    // 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 referenceid = "", customermsisdn = "", amount = "", batchref = "", username = "", password = "",
            narrative = "";
    //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);

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

        username = root.getAsJsonObject().get("username").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(nickname) || StringUtils.isBlank(password) || StringUtils.isBlank(username)) {

        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);
    //capture the switch respoinse.

    System.out.println(processtransaction);

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

    //exctract a specific json element from the object(status_code)
    Double balance = roots.getAsJsonObject().get("CheckBalanceResult").getAsDouble();

    //add 

    expected.put("username", username);

    expected.put("balance", balance.toString());

    String jsonResult = g.toJson(expected);

    return jsonResult;

}

From source file:com.gargoylesoftware.htmlunit.gae.GAETestRunner.java

/**
 * Loads the white list./*ww w.ja  v  a2s  .  c o  m*/
 * @return the list of classes in the white list
 */
private static Set<String> loadWhiteList() {
    final InputStream is = GAETestRunner.class.getResourceAsStream("whitelist.txt");
    assertNotNull(is);
    final List<String> lines;
    try {
        lines = IOUtils.readLines(is);
    } catch (final IOException e) {
        throw new Error("Failed to load while list content", e);
    } finally {
        IOUtils.closeQuietly(is);
    }

    return new HashSet<>(lines);
}

From source file:com.sillelien.dollar.DollarOperatorsRegressionTest.java

public void regression(String symbol, String operation, String variant, @NotNull List<List<var>> result)
        throws IOException {
    String filename = operation + "." + variant + ".json";
    final JsonArray previous = new JsonArray(IOUtils.toString(getClass().getResourceAsStream("/" + filename)));
    //Use small to stop massive string creation
    final File file = new File("target", filename);
    final var current = $(result);
    FileUtils.writeStringToFile(file, current.jsonArray().encodePrettily());
    System.out.println(file.getAbsolutePath());
    SortedSet<String> typeComparison = new TreeSet<>();
    SortedSet<String> humanReadable = new TreeSet<>();
    for (List<var> res : result) {
        if (res.size() != 3) {
            throw new IllegalStateException(res.toString());
        }// ww  w .j  a v a2 s.co m

        typeComparison.add(
                res.get(0).$type() + " " + operation + " " + res.get(1).$type() + " = " + res.get(2).$type());
        humanReadable.add(res.get(0).toDollarScript() + " " + symbol + " " + res.get(1).toDollarScript()
                + " <=> " + res.get(2).toDollarScript());
    }
    final String typesFile = operation + "." + variant + ".types.txt";
    final String humanFile = operation + "." + variant + ".ds";
    FileUtils.writeLines(new File("target", typesFile), typeComparison);
    FileUtils.writeLines(new File("target", humanFile), humanReadable);
    final TreeSet previousTypeComparison = new TreeSet<String>(
            IOUtils.readLines(getClass().getResourceAsStream("/" + typesFile)));
    diff("type", previousTypeComparison.toString(), typeComparison.toString());
    diff("result", previous, current.jsonArray());
}

From source file:com.impala.servlet.Remit.java

/**
 * //  w  w w. j av a 2s.c o m
 * @param request
 * @return
 * @throws IOException
 */
private String moneytransfer(HttpServletRequest request) throws IOException, JSONException {

    // 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 referenceid = "", customermsisdn = "", amount = "", batchref = "", username = "", password = "",
            narrative = "";
    //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);

        referenceid = root.getAsJsonObject().get("transaction_id").getAsString();

        customermsisdn = root.getAsJsonObject().get("beneficiary_msisdn").getAsString();

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

        password = root.getAsJsonObject().get("password").getAsString();
        batchref = root.getAsJsonObject().get("source_msisdn").getAsString();
        username = root.getAsJsonObject().get("username").getAsString();
        narrative = root.getAsJsonObject().get("sendingIMT").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(referenceid) || StringUtils.isBlank(customermsisdn) || StringUtils.isBlank(nickname)
            || StringUtils.isBlank(amount) || StringUtils.isBlank(password) || StringUtils.isBlank(batchref)
            || StringUtils.isBlank(username) || StringUtils.isBlank(narrative)) {

        expected.put("am_referenceid", username);
        expected.put("am_timestamp", "tombwa");
        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 = remittoairtel.Airtelpayout(referenceid, customermsisdn, nickname, amount,
            batchref, username, password, narrative);
    //capture the switch respoinse.

    System.out.println(processtransaction);

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

    //exctract a specific json element from the object(status_code)
    String switchresponse = roots.getAsJsonObject().get("Status").getAsString();

    if (switchresponse.equalsIgnoreCase("success")) {
        switchresponse = "S000";
    }

    //map error
    if (switchresponse.equalsIgnoreCase("failed")) {
        switchresponse = "00029";
    }

    if (switchresponse.equalsIgnoreCase("Insufficient Funds In Source Wallet")) {
        switchresponse = "00029";
    }

    //add 

    String success = "S000";

    if (switchresponse.equalsIgnoreCase(success)) {

        //exctract a specific json element from the object(transactionID)
        String transactionID = roots.getAsJsonObject().get("Reference").getAsString();

        expected.put("am_referenceid", transactionID);
        expected.put("am_timestamp", username);
        expected.put("status_code", "S000");
        expected.put("status_description", "SUCCESSFUL");
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }

    expected.put("am_referenceid", username);
    expected.put("am_timestamp", username);
    expected.put("status_code", switchresponse);
    expected.put("status_description", "FAILED");

    String jsonResult = g.toJson(expected);

    return jsonResult;

}

From source file:ml.shifu.shifu.core.dvarsel.wrapper.WrapperWorkerConductorTest.java

public TrainingDataSet genTrainingDataSet(ModelConfig modelConfig, List<ColumnConfig> columnConfigList)
        throws IOException {
    List<Integer> columnIdList = new ArrayList<Integer>();
    boolean hasCandidates = CommonUtils.hasCandidateColumns(columnConfigList);
    for (ColumnConfig columnConfig : columnConfigList) {
        if (columnConfig.isCandidate(hasCandidates)) {
            columnIdList.add(columnConfig.getColumnNum());
        }//from ww w.  j a  v a 2s  .c  o  m
    }

    TrainingDataSet trainingDataSet = new TrainingDataSet(columnIdList);
    List<String> recordsList = IOUtils.readLines(
            new FileInputStream("src/test/resources/example/cancer-judgement/DataStore/DataSet1/part-00"));
    for (String record : recordsList) {
        addRecordIntoTrainDataSet(modelConfig, columnConfigList, trainingDataSet, record);
    }

    return trainingDataSet;
}

From source file:com.stratio.mojo.scala.crossbuild.RewriteJUnitXMLTest.java

private void assertEqualToResource(final File actual, final String expected) throws IOException {
    final List<String> actualLines = IOUtils.readLines(new FileInputStream(actual));
    final List<String> expectedLines = new ArrayList<>(actualLines.size());
    try (final BufferedReader reader = new BufferedReader(
            new InputStreamReader(getClass().getResourceAsStream(expected)))) {
        String line;//ww w. jav  a2 s .  c  om
        while ((line = reader.readLine()) != null) {
            expectedLines.add(line);
        }
    }
    assertThat(actualLines).isEqualTo(expectedLines);
}

From source file:com.thoughtworks.go.domain.materials.tfs.TfsSDKCommandBuilderTest.java

private String implementationVersionFromManifrest(URL log4jJarFromClasspath) throws IOException {
    JarInputStream in = new JarInputStream(log4jJarFromClasspath.openStream());
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    in.getManifest().write(out);//from w  w  w. j a  va  2s  .  c  om
    out.close();

    List<String> lines = IOUtils.readLines(new ByteArrayInputStream(out.toByteArray()));
    for (String line : lines) {
        if (line.startsWith("Implementation-Version")) {
            return line.split(":")[1].trim();
        }
    }
    return null;
}

From source file:com.tc.util.io.ServerURL.java

private static String readLines(HttpURLConnection urlConnection) throws IOException {
    try {// ww  w  .  j av a  2  s.  c  o  m
        List<String> lines = IOUtils.readLines(urlConnection.getInputStream());
        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            sb.append(line).append(System.getProperty("line.separator"));
        }
        return sb.toString();
    } catch (IOException e) {
        return "";
    }
}

From source file:io.kahu.hawaii.service.sql.ResourceSqlQueryService.java

private List<String> readQueryFromOverride(String resourcePath) {
    if (overridePath == null) {
        return null;
    }//from w w w. ja  va2 s .  c o  m
    List<String> result = null;
    BufferedReader reader = null;
    try {
        File query = Paths.get(overridePath, resourcePath).toFile();
        if (query.exists()) {
            reader = new BufferedReader(new FileReader(query));
            result = IOUtils.readLines(reader);
        }
    } catch (IOException e) {
        logManager.error(CoreLoggers.SERVER, e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                logManager.error(CoreLoggers.SERVER, e);
            }
        }
    }
    return result;
}