Example usage for java.util Scanner hasNextLine

List of usage examples for java.util Scanner hasNextLine

Introduction

In this page you can find the example usage for java.util Scanner hasNextLine.

Prototype

public boolean hasNextLine() 

Source Link

Document

Returns true if there is another line in the input of this scanner.

Usage

From source file:org.sasabus.export2Freegis.network.DataRequestManager.java

public String datarequest() throws IOException {
    Scanner sc = new Scanner(new File(DATAREQUEST));
    String subscriptionstring = "";
    while (sc.hasNextLine()) {
        subscriptionstring += sc.nextLine();
    }//from  w w  w .j  a  v  a  2s  . com
    sc.close();
    SimpleDateFormat date_date = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat date_time = new SimpleDateFormat("HH:mm:ssZ");

    Date d = new Date();
    String timestamp = date_date.format(d) + "T" + date_time.format(d);
    timestamp = timestamp.substring(0, timestamp.length() - 2) + ":"
            + timestamp.substring(timestamp.length() - 2);

    subscriptionstring = subscriptionstring.replaceAll(":timestamp", timestamp);

    String requestString = "http://" + this.address + ":" + this.portnumber_sender
            + "/TmEvNotificationService/gms/polldata.xml";

    HttpPost subrequest = new HttpPost(requestString);

    StringEntity requestEntity = new StringEntity(subscriptionstring,
            ContentType.create("text/xml", "ISO-8859-1"));

    CloseableHttpClient httpClient = HttpClients.createDefault();

    subrequest.setEntity(requestEntity);

    CloseableHttpResponse response = httpClient.execute(subrequest);
    //System.out.println("Stauts Response: " + response.getStatusLine().getStatusCode());
    //System.out.println("Status Phrase: " + response.getStatusLine().getReasonPhrase());
    HttpEntity responseEntity = response.getEntity();
    String responsebody = "";
    if (responseEntity != null) {
        responsebody = EntityUtils.toString(responseEntity);
    }
    return responsebody;
}

From source file:com.btobits.automator.fix.utils.FileMessageFactory.java

public void load() throws Exception {
    try {/*  w w w .  ja va2s  .  co  m*/
        Scanner scanner = new Scanner(new FileInputStream(file));

        while (scanner.hasNextLine()) {
            final String line = scanner.nextLine();

            if (StringUtils.isBlank(line)) {
                continue;
            }

            int i = line.indexOf("8=FIX");
            if (i != -1) {
                String s = line.substring(i);
                final String type = MessageUtils.getStringField(s, FixUtils.MSGTYPE);
                if (!isSkip(type)) {
                    messages.add(s);
                }
            }
        }
    } catch (Exception ex) {
        throw new Exception("Error load from file", ex);
    }
}

From source file:io.github.binout.wordpress2html.writer.PostWriter.java

private String getFullHtml() {

    String content = post.getHtmlContent();
    boolean pre = false;
    StringBuilder builder = new StringBuilder();

    Scanner scanner = new Scanner(content);
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        // String line;
        // process the line
        line = line.replaceAll("</?pre>", " ");
        if (line.contains("[code") || line.contains("[sourcecode")) {
            pre = true;/*from   w w  w .  ja  v  a2 s . c  om*/
        }

        if (pre) {
            if (line.contains("[/code") || line.contains("[/sourcecode")) {
                pre = false;
            }
            line = line.replaceAll("<", "&lt;");
            line = line.replaceAll(">", "&gt;");
            line = line.replaceAll("&", "&amp;");
            line = line.replaceAll("(\\[.*code .*\\])", "$1<pre>");
            line = line.replaceAll("(\\[\\/.*code\\])", "</pre>");
            builder.append(line).append("\n");

        } else {
            builder.append(line).append("</p><p>");

        }

    }
    scanner.close();

    if (post.getTitle().startsWith("XML")) {
        System.out.println(builder.toString());
    }

    return "<html><head>" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />"
            + "</head>" + "<body>" + builder.toString() + "</body></html>";
}

From source file:org.apache.accumulo.core.util.shell.commands.AddSplitsCommand.java

public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws Exception {
    final String tableName = OptUtil.getTableOpt(cl, shellState);
    final boolean decode = cl.hasOption(base64Opt.getOpt());

    final TreeSet<Text> splits = new TreeSet<Text>();

    if (cl.hasOption(optSplitsFile.getOpt())) {
        final String f = cl.getOptionValue(optSplitsFile.getOpt());

        String line;//from w  ww  . ja v  a2s . c  o m
        java.util.Scanner file = new java.util.Scanner(new File(f), Constants.UTF8.name());
        while (file.hasNextLine()) {
            line = file.nextLine();
            if (!line.isEmpty()) {
                splits.add(
                        decode ? new Text(Base64.decodeBase64(line.getBytes(Constants.UTF8))) : new Text(line));
            }
        }
    } else {
        if (cl.getArgList().isEmpty()) {
            throw new MissingArgumentException("No split points specified");
        }
        for (String s : cl.getArgs()) {
            splits.add(new Text(s.getBytes(Shell.CHARSET)));
        }
    }

    if (!shellState.getConnector().tableOperations().exists(tableName)) {
        throw new TableNotFoundException(null, tableName, null);
    }
    shellState.getConnector().tableOperations().addSplits(tableName, splits);

    return 0;
}

From source file:com.hortonworks.registries.storage.tool.shell.ShellMigrationExecutor.java

@Override
public void execute(Connection connection) throws SQLException {
    String scriptLocation = this.shellScriptResource.getLocationOnDisk();
    try {/*from w w w . j  av  a2s.  c o m*/
        List<String> args = new ArrayList<String>();
        args.add(scriptLocation);
        ProcessBuilder builder = new ProcessBuilder(args);
        builder.redirectErrorStream(true);
        Process process = builder.start();
        Scanner in = new Scanner(process.getInputStream());
        System.out.println(StringUtils.repeat("+", 200));
        while (in.hasNextLine()) {
            System.out.println(in.nextLine());
        }
        int returnCode = process.waitFor();
        System.out.println(StringUtils.repeat("+", 200));
        if (returnCode != 0) {
            throw new FlywayException("script exited with value : " + returnCode);
        }
    } catch (Exception e) {
        LOG.error(e.toString());
        // Only if SQLException or FlywaySqlScriptException is thrown flyway will mark the migration as failed in the metadata table
        throw new SQLException(String.format("Failed to run script \"%s\", %s", scriptLocation, e.getMessage()),
                e);
    }
}

From source file:br.com.intelidev.dao.userDao.java

/**
  * Run the web service request/*  w  w  w.  ja  v  a  2s.  c o  m*/
  * @param username
  * @param password
  * @return 
  */
public boolean login_acess(String username, String password) {
    HttpsURLConnection conn = null;
    boolean bo_return = false;

    try {
        // Create url to the Device Cloud server for a given web service request
        URL url = new URL("https://devicecloud.digi.com/ws/sci");
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("GET");

        // Build authentication string
        String userpassword = username + ":" + password;

        // can change this to use a different base64 encoder
        String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim();

        // set request headers
        conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
        // Get input stream from response and convert to String
        InputStream is = conn.getInputStream();

        Scanner isScanner = new Scanner(is);
        StringBuffer buf = new StringBuffer();
        while (isScanner.hasNextLine()) {
            buf.append(isScanner.nextLine() + "\n");
        }
        //String responseContent = buf.toString();

        // add line returns between tags to make it a bit more readable
        //responseContent = responseContent.replaceAll("><", ">\n<");

        // Output response to standard out
        //System.out.println(responseContent);
        bo_return = true;
    } catch (Exception e) {
        // Print any exceptions that occur
        System.out.println("br.com.intelidev.dao.userDao.login_acess() Error: " + e);
        bo_return = false;
        //e.printStackTrace();
    } finally {
        if (conn != null)
            conn.disconnect();
        if (bo_return) {
            System.out.println("Conectou ");
        } else {
            System.out.println("No conectou ");
        }

    }
    return bo_return;
}

From source file:com.joliciel.csvLearner.features.NormalisationLimitReader.java

private void readCSVFile(InputStream csvInputStream, Map<String, Float> featureToMaxMap) {
    Scanner scanner = new Scanner(csvInputStream, "UTF-8");
    try {//from  w w  w  .  j a  v a  2s .  co  m
        boolean firstLine = true;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (!firstLine) {
                List<String> cells = CSVFormatter.getCSVCells(line);
                String featureName = cells.get(0);
                float maxValue = Float.parseFloat(cells.get(1));
                featureToMaxMap.put(featureName, maxValue);
            }
            firstLine = false;
        }
    } finally {
        scanner.close();
    }
}

From source file:com.mgmtp.perfload.perfalyzer.binning.PerfMonBinningStrategy.java

@Override
public void binData(final Scanner scanner, final WritableByteChannel destChannel) throws IOException {
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        tokenizer.reset(line);/*w ww.  j a v a2  s. c  o  m*/
        List<String> tokenList = tokenizer.getTokenList();

        if (typeConfig == null) {
            String type = tokenList.get(1);
            typeConfig = PerfMonTypeConfig.fromString(type);
        }

        try {
            long timestampMillis = Long.parseLong(tokenList.get(0));
            Double value = Double.valueOf(tokenList.get(2));
            binManager.addValue(timestampMillis, value);
        } catch (NumberFormatException ex) {
            log.error("Could not parse value {}. Line in perfMon file might be incomplete. Ignoring it.", ex);
        }
    }

    binManager.toCsv(destChannel, "seconds", typeConfig.getHeader(), intNumberFormat,
            typeConfig.getAggregationType());
}

From source file:org.apache.streams.datasift.serializer.DatasiftActivitySerializerTest.java

@Test
public void testConversion() throws Exception {

    Scanner scanner = StreamsScannerUtil.getInstance("/rand_sample_datasift_json.txt");

    String line = null;
    while (scanner.hasNextLine()) {
        try {//  w ww.  j  a  v  a 2  s  .  c  om
            line = scanner.nextLine();
            Datasift item = MAPPER.readValue(line, Datasift.class);
            testConversion(item);
            String json = MAPPER.writeValueAsString(item);
            testDeserNoNull(json);
            testDeserNoAddProps(json);
        } catch (Exception e) {
            System.err.println(line);
            throw e;
        }
    }
}

From source file:debrepo.teamcity.archive.DebFileReader.java

protected Map<String, String> getDebItemsFromControl(File debFile, String controlFileContents) {
    Pattern p = Pattern.compile("^(\\S+):(.+)$");

    Map<String, String> map = new LinkedHashMap<String, String>();
    Scanner scanner = new Scanner(controlFileContents);

    while (scanner.hasNextLine()) {
        Matcher m = p.matcher(scanner.nextLine());
        if (m.find()) {
            map.put(m.group(1), m.group(2).trim());
        }//from  ww w.j a  v a 2  s. c o m
    }
    scanner.close();

    map.putAll(getExtraPackageItemsFromDeb(debFile));

    return map;
}