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:io.cloudslang.lang.compiler.modeller.model.Metadata.java

private static void appendString(StringBuilder stringBuilder, String fieldValue, String spacing)
        throws IOException {
    List<String> lines = IOUtils.readLines(new StringReader(fieldValue));
    if (lines.size() > 1) {
        stringBuilder.append(System.lineSeparator());
        for (String line : lines) {
            stringBuilder.append(spacing).append(line).append(System.lineSeparator());
        }//from   w  w  w  . j a  v  a2s  .c  om
    } else {
        stringBuilder.append(fieldValue).append(System.lineSeparator());
    }
}

From source file:com.impala.paga.all.QueryBalance.java

/**
 * //  w  ww . j a v a  2 s.  c o  m
 * @param request
 * @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;
    // These represent parameters received over the network
    String username = "", password = "", receiverqueryurl = "", sourcemsisdn = "";

    String responseobject = "";
    Properties prop = new Properties();
    String hashkey = prop.getProperty("hashkey");
    String principal = prop.getProperty("principal");
    String credentials = prop.getProperty("credentials");

    // String hashkey ="372e9b1c62ef47db83c566cf2db033cb4e1b847e12ec435997971ebd7ab8121cbd8458176374480eae7d4cb55f722f4ab328207b461f423a85a9bbad8850ce66";
    //String principal="02A10715-0E53-4A8C-982E-2B7BFC7CF550";
    //String credentials ="QE3@u=jd*2b+";

    // These represent parameters received over the network
    String referenceNumber = "";

    // 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

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

        referenceNumber = root.getAsJsonObject().get("referenceNumber").getAsString();
        username = root.getAsJsonObject().get("username").getAsString();
        password = root.getAsJsonObject().get("password").getAsString();
        receiverqueryurl = root.getAsJsonObject().get("receiverqueryurl").getAsString();
        sourcemsisdn = root.getAsJsonObject().get("sourceaccount").getAsString();

    } catch (Exception e) {

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

        return jsonResult;
    }
    /*String referenceNumber = "",  amount = "",currency="",destinationBankUUID="",
      destinationBankAccountNumber= "", recipientPhoneNumber = ""
     ,  credentials = "";*/
    // check for the presence of all required parameters
    if (StringUtils.isBlank(referenceNumber)) {

        expected.put("am_referenceid", referenceNumber);
        expected.put("am_timestamp", "tombwa");
        expected.put("status_code", statuscode);
        expected.put("status_description", Statusdescription);
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }
    MessageDigest md = null;
    String saltedToken = referenceNumber + hashkey;
    System.out.println("saltedToken:" + saltedToken);
    md = MessageDigest.getInstance("SHA-512");
    md.update(saltedToken.getBytes());
    byte byteData[] = md.digest();

    //convert the byte to hex format method 1
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < byteData.length; i++) {
        sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
    }

    System.out.println("Hex format : " + sb.toString());
    String hash = sb.toString();

    /*{ referenceNumber": "", "amount": "", "currency": "",
    "destinationBankUUID": "","destinationBankAccountNumber": "", 
    "recipientPhoneNumber": ""}
    */

    toPaga.put("referenceNumber", "");

    //toVitesse.put("source","IMPALAPAY");

    System.out.println(toPaga.toString());

    //assign the remit url from properties.config
    CLIENT_URL = receiverqueryurl;
    //principal = "" , credentials = "", hash = ""
    PostWithIgnoreSSLPaga = new PostWithIgnoreSSLPaga(CLIENT_URL, toPaga.toString(), principal, credentials,
            hash);

    //capture the switch respoinse.
    responseobject = PostWithIgnoreSSLPaga.doPost();

    System.out.println(responseobject);

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

    int responseCode = roots.getAsJsonObject().get("responseCode").getAsInt();

    String switchresponse = Integer.toString(responseCode);

    //add 

    String success = "S001";

    if (responseCode == 0) {

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

        expected.put("am_referenceid", referenceNumber);
        expected.put("am_timestamp", success);
        expected.put("status_code", "S001");
        expected.put("status_description", statusdescription);
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }

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

    String jsonResult = g.toJson(expected);

    return jsonResult;

}

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

private List<String> readQuery(String resourcePath) throws ServerException {
    InputStream resource = getClass().getResourceAsStream(resourcePath);
    if (resource == null) {
        throw new ServerException(ServerError.IO, "error reading SQL query from file");
    }/*w w  w .  j a  v a  2 s. c  o m*/
    try {
        return IOUtils.readLines(resource);
    } catch (IOException e) {
        throw new ServerException(ServerError.IO, "error reading SQL query from file");
    }
}

From source file:de.tudarmstadt.ukp.dkpro.tc.svmhmm.writer.SVMHMMDataWriterTest.java

@Test
public void testWriteMultiLineComment() throws Exception {
    featureStore = new SparseFeatureStore();
    featureStore.addInstance(new Instance(Arrays
            .asList(new Feature(OriginalTextHolderFeatureExtractor.ORIGINAL_TEXT, "multi line \n text"))));

    SVMHMMDataWriter svmhmmDataWriter = new SVMHMMDataWriter();
    System.out.println(featureStore.getNumberOfInstances());
    svmhmmDataWriter.write(temporaryFolder.getRoot(), featureStore, false, null, false);

    List<String> lines = IOUtils
            .readLines(new FileInputStream(new File(temporaryFolder.getRoot(), "feature-vectors.txt")));
    System.out.println(lines);/*w w  w . j  ava2  s.  c o  m*/

    // each instance must be on one line!
    assertEquals(1, lines.size());
}

From source file:au.com.permeance.liferay.portlet.patchingtoolinfo.cli.PatchingToolCommandRunner.java

public void runCommand() throws Exception {

    if (LOG.isDebugEnabled()) {
        LOG.debug("running patching tool command ...");
    }//from  w  w  w.jav a2  s  .c om

    try {

        ProcessBuilder processBuilder = configureProcessBuilder();

        // NOTE: ProcessBuilder#environent is initialised with System.getenv()
        // @see http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html#environment%28%29

        if (LOG.isDebugEnabled()) {
            LOG.debug("processBuilder : " + processBuilder);
            List<String> commandList = processBuilder.command();
            LOG.debug("command environment : " + processBuilder.environment());
            LOG.debug("command list : " + commandList);
            LOG.debug("command directory : " + processBuilder.directory());
        }

        if (LOG.isDebugEnabled()) {
            List<String> commandList = processBuilder.command();
            String processCommandStr = StringHelper.flattenStringList(commandList);
            LOG.debug("running patching tool command : " + processCommandStr);
        }

        Process process = processBuilder.start();

        if (LOG.isDebugEnabled()) {
            LOG.debug("process : " + process);
        }

        // NOTE: Java 1.8 supports Process#waitFor with a timeout
        // eg. boolean finished = iostat.waitFor(100, TimeUnit.MILLISECONDS);

        int processExitValue = process.waitFor();

        List<String> processOutputLines = IOUtils.readLines(process.getInputStream());

        List<String> processErrorLines = IOUtils.readLines(process.getErrorStream());

        this.patchingToolResults = new PatchingToolResults(processExitValue, processOutputLines,
                processErrorLines);

        if (LOG.isDebugEnabled()) {
            LOG.debug("patchingToolResults: " + patchingToolResults);
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("patching tool returned exit code " + this.patchingToolResults.getExitValue());
            LOG.debug("patching tool returned " + this.patchingToolResults.getOutputLines().size()
                    + " output lines");
            LOG.debug("--- COMMAND OUTPUT ---");
            LOG.debug(processOutputLines);
            LOG.debug("patching tool returned " + this.patchingToolResults.getErrorLines().size()
                    + " error lines");
            LOG.debug("--- COMMAND ERROR ---");
            LOG.debug(processErrorLines);
        }

        // NOTE: Command shell may return lines in the error stream that are warning messages, not errors.
        // Hence, we cannot rely upon content in the error stream as a valid error.

        if (this.patchingToolResults.getExitValue() != 0) {
            StringBuilder sb = new StringBuilder();
            String errorLine1 = null;
            if (this.patchingToolResults.hasErrorLines()) {
                errorLine1 = this.patchingToolResults.getErrorLines().get(0);
            }
            if (errorLine1 == null) {
                sb.append("Error running patching tool command.");
                sb.append(" See portal logs for more details.");
            } else {
                sb.append("Error running patching tool command : ");
                sb.append(errorLine1);
            }
            String errMsg = sb.toString();
            throw new Exception(errMsg);
        }

    } catch (Exception e) {

        String msg = "Error executing patching tool command : " + e.getMessage();
        LOG.error(msg, e);
        throw new Exception(msg, e);
    }
}

From source file:de.griffel.confluence.plugins.plantuml.type.UmlSourceBuilder.java

@SuppressWarnings("unchecked")
public UmlSourceBuilder append(InputStream stream) throws IOException {
    return append(IOUtils.readLines(stream));
}

From source file:com.shaobo.MyMojo.java

public void init() throws Exception {
    properties = new Properties();
    FileInputStream fis = null;//w w  w .jav  a 2  s.  c  om
    try {
        fis = new FileInputStream(basedir + System.getProperty("file.separator") + ANTX);
        properties.load(fis);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
    List<String> lines = null;
    fileLines = new ArrayList<List<String>>();
    allFiles = populate(includes);
    for (String include : allFiles) {
        fis = new FileInputStream(include);
        lines = IOUtils.readLines(fis);
        fileLines.add(lines);
        IOUtils.closeQuietly(fis);
    }
}

From source file:com.impala.paga.all.BankRouteRemit.java

/**
 * /*from www .jav a  2 s .co  m*/
 * @param request
 * @return
 * @throws IOException
 */
private String SendRequest(HttpServletRequest request) throws IOException, NoSuchAlgorithmException {
    // joined json string
    Account account = null;
    Properties prop = new Properties();
    String hashkey = prop.getProperty("hashkey");
    String principal = prop.getProperty("principal");
    String credentials = prop.getProperty("credentials");
    // String hashkey ="372e9b1c62ef47db83c566cf2db033cb4e1b847e12ec435997971ebd7ab8121cbd8458176374480eae7d4cb55f722f4ab328207b461f423a85a9bbad8850ce66";
    // String principal="02A10715-0E53-4A8C-982E-2B7BFC7CF550";
    // String credentials ="QE3@u=jd*2b+";

    String join = "";
    JsonElement root = null, roots = null;
    JsonObject root2 = null, creditrequest = null;
    JSONObject toPaga = new JSONObject();

    String apiusername = "", apipassword = "", username = "", transactioinid = "", sourcecountrycode = "",
            recipientcurrencycode = "", recipientcountrycode = "", sourcemsisdn = "", recipientmobile = "",
            sendername = "", amountstring = "", remiturlss = "", responseobject = "", statuscode = "",
            statusdescription = "", referencenumber = "", senderaddress = "", sendercity = "",
            accountnumber = "", bankcode = "", recipientname = "";

    // 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
        root = new JsonParser().parse(join);

        apiusername = root.getAsJsonObject().get("username").getAsString();

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

        username = root.getAsJsonObject().get("sendingIMT").getAsString();

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

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

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

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

        sendername = root.getAsJsonObject().get("Sender_Name").getAsString();

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

        remiturlss = root.getAsJsonObject().get("url").getAsString();

        sourcemsisdn = root.getAsJsonObject().get("source_msisdn").getAsString();

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

        senderaddress = root.getAsJsonObject().get("sender_address").getAsString();

        sendercity = root.getAsJsonObject().get("sender_city").getAsString();

        bankcode = root.getAsJsonObject().get("bank_code").getAsString();

        accountnumber = root.getAsJsonObject().get("account_number").getAsString();

        recipientname = root.getAsJsonObject().get("recipient_name").getAsString();

        root2 = root.getAsJsonObject();

    } catch (Exception e) {

        expected.put("command_status", APIConstants.COMMANDSTATUS_INVALID_PARAMETERS);
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }

    // check for the presence of all required parameters
    if (StringUtils.isBlank(apiusername) || StringUtils.isBlank(apipassword) || StringUtils.isBlank(username)
            || StringUtils.isBlank(transactioinid) || StringUtils.isBlank(sourcecountrycode)
            || StringUtils.isBlank(recipientcurrencycode) || StringUtils.isBlank(sendername)
            || StringUtils.isBlank(amountstring) || StringUtils.isBlank(remiturlss)
            || StringUtils.isBlank(senderaddress) || StringUtils.isBlank(recipientmobile)
            || StringUtils.isBlank(sourcemsisdn) || StringUtils.isBlank(sendercity)
            || StringUtils.isBlank(bankcode) || StringUtils.isBlank(accountnumber)
            || StringUtils.isBlank(recipientcountrycode) || StringUtils.isBlank(recipientname)) {

        expected.put("status_code", "server error");
        expected.put("status_description", "missing parameters");
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }

    if (root2.has("vendor_uniquefields")) {

    }

    // Retrieve the account details
    Element element;
    if ((element = accountsCache.get(username)) != null) {
        account = (Account) element.getObjectValue();
    }

    // Secure against strange servers making request(future upgrade should
    // lock on IP)
    if (account == null) {
        expected.put("status_code", "server error");
        expected.put("status_description", "unauthorised user");
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }

    MessageDigest md = null;
    String saltedToken = transactioinid + amountstring + bankcode + accountnumber + hashkey;
    md = MessageDigest.getInstance("SHA-512");
    md.update(saltedToken.getBytes());
    byte byteData[] = md.digest();

    //convert the byte to hex format method 1
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < byteData.length; i++) {
        sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
    }

    System.out.println("Hex format : " + sb.toString());
    String hash = sb.toString();

    Double intamount = Double.parseDouble(amountstring);

    /*{ referenceNumber": "", "amount": "", "currency": "",
    "destinationBankUUID": "","destinationBankAccountNumber": "", 
    "recipientPhoneNumber": ""}
    */

    toPaga.put("referenceNumber", transactioinid);
    toPaga.put("amount", amountstring);
    toPaga.put("currency", recipientcurrencycode);
    toPaga.put("destinationBankUUID", bankcode);
    toPaga.put("destinationBankAccountNumber", accountnumber);
    toPaga.put("recipientPhoneNumber", recipientmobile);

    //toVitesse.put("source","IMPALAPAY");

    System.out.println(toPaga.toString());

    //assign the remit url from properties.config
    CLIENT_URL = remiturlss;
    //principal = "" , credentials = "", hash = ""
    PostWithIgnoreSSLPaga = new PostWithIgnoreSSLPaga(CLIENT_URL, toPaga.toString(), principal, credentials,
            hash);

    //capture the switch respoinse.
    responseobject = PostWithIgnoreSSLPaga.doPost();

    System.out.println(responseobject);

    //pass the returned json string
    JsonElement roots2 = new JsonParser().parse(responseobject);

    int responseCode = roots2.getAsJsonObject().get("responseCode").getAsInt();

    String switchresponse = Integer.toString(responseCode);

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

    //add 

    String success = "S001";

    if (responseCode == 0) {

        expected.put("am_referenceid", transactioinid);
        expected.put("am_timestamp", success);
        expected.put("status_code", "S001");
        expected.put("status_description", message);
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }

    expected.put("am_referenceid", "");
    expected.put("am_timestamp", responseCode + "");
    expected.put("status_code", "00029");
    expected.put("status_description", message);

    String jsonResult = g.toJson(expected);

    return jsonResult;

}

From source file:inti.ws.spring.resource.config.ResourceConfigProviderImpl.java

protected Set<String> getPaths(Enumeration<URL> urls) {
    URL url;/*from  w  w w  .j a  v  a2 s  .c  o m*/
    InputStream input;
    List<String> lines;
    Set<String> paths = new HashSet<>();
    String tmp;

    if (urls != null) {

        while (urls.hasMoreElements()) {

            try {
                url = urls.nextElement();
                LOGGER.debug("getPaths - checking url: {}", url);
                input = url.openStream();

                try {
                    lines = IOUtils.readLines(input);

                    for (String line : lines) {
                        if (line.trim().length() > 0) {
                            tmp = url.toExternalForm();
                            paths.add(tmp.substring(0, tmp.length() - 5) + line);
                        }
                    }
                    LOGGER.debug("getPaths - got paths {} from url {}", paths, url);

                } finally {
                    try {
                        input.close();
                    } catch (IOException exception) {
                        LOGGER.error("error while reading hosts config", exception);
                    }
                }

            } catch (IOException exception) {
                LOGGER.error("error while reading hosts config", exception);
            }

        }

    }

    return paths;
}

From source file:com.eclecticlogic.pedal.loader.impl.ScriptExecutor.java

@Override
public Map<String, Object> loadNamespaced(Collection<Script> scripts) {
    Map<String, Object> variables = new HashMap<>();
    // Add overall variables
    Map<String, Object> inputVariables = scriptInputs.isEmpty() ? inputs : scriptInputs.pop();

    for (Entry<String, Object> var : inputVariables.entrySet()) {
        variables.put(var.getKey(), var.getValue());
    }//from   w  ww . j  av a  2  s  .  co m

    for (Script script : scripts) {
        NamespacedBinding binding = create();
        // Bind inputs.
        for (String key : variables.keySet()) {
            binding.setVariable(key, variables.get(key));
        }
        binding.startCapture();

        String filename = scriptDirectory == null || scriptDirectory.trim().length() == 0 ? script.getName()
                : scriptDirectory + File.separator + script.getName();
        try (InputStream stream = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(filename)) {
            List<String> lines = IOUtils.readLines(stream);
            StringBuilder builder = new StringBuilder();
            for (String line : lines) {
                builder.append(line).append("\n");
            }
            execute(builder.toString(), binding);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }

        // Add output variables
        if (script.getNamespace() == null || script.getNamespace().trim().length() == 0) {
            for (String key : binding.getNamespacedVariables().keySet()) {
                variables.put(key, binding.getNamespacedVariables().get(key));
            }
        } else {
            variables.put(script.getNamespace(), binding.getNamespacedVariables());
        }
    }

    return variables;
}