Example usage for java.util Scanner nextLine

List of usage examples for java.util Scanner nextLine

Introduction

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

Prototype

public String nextLine() 

Source Link

Document

Advances this scanner past the current line and returns the input that was skipped.

Usage

From source file:org.arasthel.almeribus.utils.LoadFromWeb.java

private static int loadCookie() throws ClientProtocolException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new HttpGet("http://m.surbus.com/tiempo-espera");
    HttpResponse response = httpClient.execute(get);
    HttpEntity entity = response.getEntity();

    if (entity == null) {
        return ERROR_IO;
    }//w ww.java2s . c o  m

    Scanner scan = new Scanner(entity.getContent());
    StringBuilder strBuilder = new StringBuilder();
    while (scan.hasNextLine()) {
        strBuilder.append(scan.nextLine());
    }
    scan.close();
    if (!strBuilder.toString().contains("id=\"blockResult\" class=\"messageResult\"")) {
        return MANTENIMIENTO;
    }

    List<Cookie> cookies = httpClient.getCookieStore().getCookies();
    for (Cookie c : cookies) {
        if (c.getName().contains("ASP.NET_SessionId")) {
            cookie = c.getValue();
        }
    }
    return TODO_OK;
}

From source file:com.github.mavogel.ilias.utils.IOUtils.java

/**
 * Reads and parses the registration period.<br>
 * Validates the format and that the start is after the end.
 *
 * @return the {@link RegistrationPeriod}
 *//*from w w  w. ja  v a  2 s  . c om*/
public static RegistrationPeriod readAndParseRegistrationDates() {
    LOG.info("Date need to be of the format 'yyyy-MM-ddTHH:mm'. E.g.: 2016-04-15T13:00"); // TODO get from the formatter
    LocalDateTime registrationStart = null, registrationEnd = null;
    boolean validStart = false, validEnd = false;

    Scanner scanner = new Scanner(System.in);
    while (!validStart) {
        LOG.info("Registration start: ");
        String line = StringUtils.deleteWhitespace(scanner.nextLine());
        try {
            registrationStart = LocalDateTime.parse(line, Defaults.DATE_FORMAT);
            validStart = true;
        } catch (DateTimeParseException dtpe) {
            LOG.error("'" + line + "' is not a valid date");
        }
    }

    while (!validEnd) {
        LOG.info("Registration end:  ");
        String line = scanner.nextLine();
        try {
            registrationEnd = LocalDateTime.parse(line, Defaults.DATE_FORMAT);
            validEnd = registrationStart.isBefore(registrationEnd);
            if (!validEnd) {
                LOG.error("End of registration has to be after the start'" + registrationStart + "'");
            }
        } catch (DateTimeParseException dtpe) {
            LOG.error("'" + line + "' is not a valid date");
        }
    }

    return new RegistrationPeriod(registrationStart, registrationEnd);
}

From source file:org.arasthel.almeribus.utils.LoadFromWeb.java

public static String getMensajeDesarrollador() {
    String mensaje = null;// w  w  w .j  a  v  a2s  . co  m
    try {
        URL url = new URL("http://arasthel.byethost14.com/almeribus/message.html?token="
                + new Random().nextInt(Integer.MAX_VALUE));
        URLConnection connection = url.openConnection();
        connection.setUseCaches(false);
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(15000);
        Scanner scan = new Scanner(connection.getInputStream());
        StringBuilder strBuilder = new StringBuilder();
        while (scan.hasNextLine()) {
            strBuilder.append(scan.nextLine());
        }
        scan.close();
        mensaje = strBuilder.toString();
    } catch (Exception e) {

    }
    return mensaje;
}

From source file:org.arasthel.almeribus.utils.LoadFromWeb.java

public static String getUltimaVersion() {
    String mensaje = null;/*from  w  w w  . jav  a  2 s. c  o m*/
    try {
        URL url = new URL("http://arasthel.byethost14.com/almeribus/version.html?token="
                + new Random().nextInt(Integer.MAX_VALUE));
        URLConnection connection = url.openConnection();
        connection.setUseCaches(false);
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(15000);
        Scanner scan = new Scanner(connection.getInputStream());
        StringBuilder strBuilder = new StringBuilder();
        while (scan.hasNextLine()) {
            strBuilder.append(scan.nextLine());
        }
        scan.close();
        mensaje = strBuilder.toString();
    } catch (Exception e) {

    }
    return mensaje;
}

From source file:com.mirth.connect.server.util.DatabaseUtil.java

public static void executeScript(String script, boolean ignoreErrors) throws Exception {
    SqlSessionManager sqlSessionManger = SqlConfig.getSqlSessionManager();

    Connection conn = null;//w  w  w.j a  v  a 2 s.c o m
    ResultSet resultSet = null;
    Statement statement = null;

    try {
        sqlSessionManger.startManagedSession();
        conn = sqlSessionManger.getConnection();

        /*
         * Set auto commit to false or an exception will be thrown when trying to rollback
         */
        conn.setAutoCommit(false);

        statement = conn.createStatement();

        Scanner s = new Scanner(script);

        while (s.hasNextLine()) {
            StringBuilder sb = new StringBuilder();
            boolean blankLine = false;

            while (s.hasNextLine() && !blankLine) {
                String temp = s.nextLine();

                if (temp.trim().length() > 0)
                    sb.append(temp + " ");
                else
                    blankLine = true;
            }

            // Trim ending semicolons so Oracle doesn't throw
            // "java.sql.SQLException: ORA-00911: invalid character"
            String statementString = StringUtils.removeEnd(sb.toString().trim(), ";");

            if (statementString.length() > 0) {
                try {
                    statement.execute(statementString);
                    conn.commit();
                } catch (SQLException se) {
                    if (!ignoreErrors) {
                        throw se;
                    } else {
                        logger.error("Error was encountered and ignored while executing statement: "
                                + statementString, se);
                        conn.rollback();
                    }
                }
            }
        }

    } catch (Exception e) {
        throw new Exception(e);
    } finally {
        DbUtils.closeQuietly(statement);
        DbUtils.closeQuietly(resultSet);
        DbUtils.closeQuietly(conn);
        sqlSessionManger.close();
    }
}

From source file:com.ibm.iotf.sample.devicemgmt.device.RasPiFirmwareHandlerSample.java

private static String getInstallLog() throws FileNotFoundException {
    File file = new File(INSTALL_LOG_FILE);
    Scanner scanner = new Scanner(file);
    StringBuilder sb = new StringBuilder();
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        sb.append(line);/*from ww w.  j a v  a  2 s.c  om*/
        sb.append('\n');
    }
    scanner.close();
    return sb.toString();
}

From source file:com.github.mavogel.ilias.utils.IOUtils.java

/**
 * Reads and parses a positive integer.// w  ww.j  a  v a  2s . co m
 *
 * @return the positive integer.
 */
public static int readAndParsePositiveInteger() {
    boolean isCorrectInput = false;
    String line = null;
    int positiveInteger = -1;

    Scanner scanner = new Scanner(System.in);
    while (!isCorrectInput) {
        try {
            LOG.info("Enter a positive integer:");
            line = StringUtils.deleteWhitespace(scanner.nextLine());
            positiveInteger = Integer.valueOf(line);
            isCorrectInput = positiveInteger >= 0;
        } catch (NumberFormatException nfe) {
            LOG.error("'" + line + "' is not a positive integer! Try again");
        } catch (IllegalArgumentException iae) {
            LOG.error(iae.getMessage());
        }
    }

    return positiveInteger;
}

From source file:longism.com.api.APIUtils.java

/**
 * TODO Function:Upload file then Load json by type POST.<br>
 *
 * @param activity    - to get context/*from   w  w  w .ja va 2  s.c om*/
 * @param action      - need authenticate or not, define at top of class
 * @param data        - parameter String
 * @param files       - param file input <key,path of file>
 * @param url         - host of API
 * @param apiCallBack - call back to handle action when start, finish, success or fail
 * @date: July 07, 2015
 * @author: Nguyen Long
 */
public static void loadJSONWithUploadFile(final Activity activity, final int action,
        final HashMap<String, String> data, final HashMap<String, String> files, final String url,
        final String sUserName, final String sUserPassword, final APICallBack apiCallBack) {

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            apiCallBack.uiStart();
        }
    });
    new Thread(new Runnable() {
        @Override
        public synchronized void run() {
            try {
                HttpParams params = new BasicHttpParams();
                HttpConnectionParams.setSoTimeout(params, TIMEOUT_TIME);
                HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_TIME);
                Charset chars = Charset.forName("UTF-8");
                DefaultHttpClient client = new DefaultHttpClient(params);
                HttpPost post = new HttpPost(url);
                //               DLog.e("Accountant", "url  : " + url);
                MultipartEntity multipartEntity = new MultipartEntity();
                if (files != null) {
                    Set<String> set = files.keySet();
                    for (String key : set) {
                        //                     DLog.e("Accountant", "param  : " + key);
                        File file = new File(files.get(key));
                        multipartEntity.addPart(key, new FileBody(file));
                    }
                }
                if (data != null) {
                    Set<String> set = data.keySet();
                    for (String key : set) {
                        //                     DLog.e("Accountant", "param  : " + key);
                        StringBody stringBody = new StringBody(data.get(key), chars);
                        multipartEntity.addPart(key, stringBody);
                    }

                }
                post.setEntity(multipartEntity);
                /**
                 * if need authen then run this code below
                 */
                if (action == ACTION_UPLOAD_WITH_AUTH) {
                    setAuthenticate(client, post, sUserName, sUserPassword);
                }

                HttpResponse response = null;
                response = client.execute(post);
                final StringBuilder builder = new StringBuilder();
                if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                    InputStream inputStream = response.getEntity().getContent();
                    Scanner scanner = new Scanner(inputStream);
                    while (scanner.hasNext()) {
                        builder.append(scanner.nextLine());
                    }
                    inputStream.close();
                    scanner.close();
                    apiCallBack.success(builder.toString(), 0);
                } else {
                    apiCallBack.fail(response != null && response.getStatusLine() != null ? "response null"
                            : "" + response.getStatusLine().getStatusCode());
                }
            } catch (final Exception e) {
                apiCallBack.fail(e.getMessage());
            } finally {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        apiCallBack.uiEnd();
                    }
                });
            }
        }
    }).start();
}

From source file:com.github.mavogel.ilias.utils.IOUtils.java

/**
 * Reads and parses a single choice from the user.<br>
 * Handles wrong inputs and ensures the choice is in
 * the range of the possible choices.//  w  w  w  .j a  va  2  s . c o m
 *
 * @param choices the possible choices
 * @return the choice of the user.
 */
public static int readAndParseSingleChoiceFromUser(final List<?> choices) {
    boolean isCorrectInput = false;
    String line = null;
    int userChoice = -1;

    Scanner scanner = new Scanner(System.in);
    while (!isCorrectInput) {
        try {
            LOG.info("A single choice only! (E.g.: 1)");
            line = StringUtils.deleteWhitespace(scanner.nextLine());
            userChoice = Integer.valueOf(line);
            isCorrectInput = isInRange(choices, userChoice);
        } catch (NumberFormatException nfe) {
            LOG.error("'" + line + "' is not  a number! Try again");
        } catch (IllegalArgumentException iae) {
            LOG.error(iae.getMessage());
        }
    }

    return userChoice;
}

From source file:com.google.api.ads.adwords.jaxws.extensions.AwReporting.java

/**
 * Prints the sample properties file on the default output.
 *//*ww w .j  a  va 2 s .  c  om*/
private static void printSamplePropertiesFile() {

    System.out.println("\n  File: aw-report-sample.properties example");

    ClassPathResource sampleFile = new ClassPathResource("aw-report-sample.properties");
    Scanner fileScanner = null;
    try {
        fileScanner = new Scanner(sampleFile.getInputStream());
        while (fileScanner.hasNext()) {
            System.out.println(fileScanner.nextLine());
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fileScanner != null) {
            fileScanner.close();
        }
    }
}