Example usage for java.util Scanner hasNext

List of usage examples for java.util Scanner hasNext

Introduction

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

Prototype

public boolean hasNext() 

Source Link

Document

Returns true if this scanner has another token in its input.

Usage

From source file:codeu.chat.client.commandline.Chat.java

private void doOneCommand(Scanner lineScanner) {

    final Scanner tokenScanner = new Scanner(lineScanner.nextLine());
    if (!tokenScanner.hasNext()) {
        return;// www .j a  v a2s  . c  o m
    }
    final String token = tokenScanner.next();

    if (token.equals("exit")) {

        alive = false;

    } else if (token.equals("help")) {

        help();

    } else if (token.equals("sign-in")) {

        if (!tokenScanner.hasNext()) {
            System.out.println("ERROR: No user name supplied.");
        } else {
            signInUser(tokenScanner.nextLine().trim());

            // Check whether the bot/convo already exist
            if (clientContext.user.lookup(BOT_NAME) == null) {
                addUser(BOT_NAME);
                clientContext.conversation.startConversation(BOT_CONVO, clientContext.user.getCurrent().id);
            }
        }

    } else if (token.equals("sign-out")) {

        if (!clientContext.user.hasCurrent()) {
            System.out.println("ERROR: Not signed in.");
        } else {
            signOutUser();
        }

    } else if (token.equals("current")) {

        showCurrent();

    } else if (token.equals("u-add")) {

        if (!tokenScanner.hasNext()) {
            System.out.println("ERROR: Username not supplied.");
        } else {
            addUser(tokenScanner.nextLine().trim());
        }

    } else if (token.equals("u-list-all")) {

        showAllUsers();

    } else if (token.equals("c-add")) {

        if (!clientContext.user.hasCurrent()) {
            System.out.println("ERROR: Not signed in.");
        } else {
            if (!tokenScanner.hasNext()) {
                System.out.println("ERROR: Conversation title not supplied.");
            } else {
                final String title = tokenScanner.nextLine().trim();
                clientContext.conversation.startConversation(title, clientContext.user.getCurrent().id);
            }
        }

    } else if (token.equals("c-list-all")) {

        clientContext.conversation.showAllConversations();

    } else if (token.equals("c-select")) {

        selectConversation(lineScanner);

    } else if (token.equals("c-search-title")) {

        if (!tokenScanner.hasNext()) {
            System.out.println("ERROR: Conversation title not supplied.");
        } else {
            final String title = tokenScanner.nextLine().trim();
            clientContext.conversation.searchTitle(title);
        }

    } else if (token.equals("m-add")) {

        if (!clientContext.user.hasCurrent()) {
            System.out.println("ERROR: Not signed in.");
        } else if (!clientContext.conversation.hasCurrent()) {
            System.out.println("ERROR: No conversation selected.");
        } else {
            if (!tokenScanner.hasNext()) {
                System.out.println("ERROR: Message body not supplied.");
            } else {
                final String body = tokenScanner.nextLine().trim();
                clientContext.message.addMessage(clientContext.user.getCurrent().id,
                        clientContext.conversation.getCurrentId(), body);

                respondAsBot(body, true);
            }
        }

    } else if (token.equals("m-list-all")) {

        if (!clientContext.conversation.hasCurrent()) {
            System.out.println("ERROR: No conversation selected.");
        } else {
            clientContext.message.showAllMessages();
        }

    } else if (token.equals("m-next")) {

        if (!clientContext.conversation.hasCurrent()) {
            System.out.println("ERROR: No conversation selected.");
        } else if (!tokenScanner.hasNextInt()) {
            System.out.println("Command requires an integer message index.");
        } else {
            clientContext.message.selectMessage(tokenScanner.nextInt());
        }

    } else if (token.equals("m-show")) {

        if (!clientContext.conversation.hasCurrent()) {
            System.out.println("ERROR: No conversation selected.");
        } else {
            final int count = (tokenScanner.hasNextInt()) ? tokenScanner.nextInt() : 1;
            clientContext.message.showMessages(count);
        }

    } else if (token.equals("m-search-string")) {

        if (!clientContext.conversation.hasCurrent()) {
            System.out.println("ERROR: No conversation selected.");
        } else if (!tokenScanner.hasNext()) {
            System.out.println("ERROR: String not supplied.");
        } else {
            final String keyword = tokenScanner.nextLine().trim();
            clientContext.message.searchString(keyword);
        }

    } else if (token.equals("m-search-author")) {

        if (!clientContext.conversation.hasCurrent()) {
            System.out.println("ERROR: No conversation selected.");
        } else if (!tokenScanner.hasNext()) {
            System.out.println("ERROR: author body not supplied.");
        } else {
            final String author = tokenScanner.nextLine().trim();
            clientContext.message.searchAuthor(author);
        }

    } else if (token.equals("t-add")) {

        if (!clientContext.user.hasCurrent()) {
            System.out.println("ERROR: Not signed in.");
        } else {
            if (!tokenScanner.hasNext()) {
                System.out.println("ERROR: tag name not supplied.");
            } else {
                final String name = tokenScanner.nextLine().trim();
                clientContext.tag.addTag(clientContext.user.getCurrent().id, name);
            }
        }

    } else if (token.equals("t-list")) {
        if (!clientContext.user.hasCurrent()) {
            System.out.println("ERROR: Not signed in.");
        } else {
            if (!tokenScanner.hasNext()) {
                System.out.println("ERROR: tag name not supplied.");
            } else {
                final String name = tokenScanner.nextLine().trim();
                clientContext.tag.listTag(clientContext.user.getCurrent().id, name);
            }
        }

    } else if (token.equals("t-list-all")) {
        showAllTags();

    } else if (token.equals("t-list-user")) {
        if (!clientContext.user.hasCurrent()) {
            System.out.println("ERROR: Not signed in.");
        } else {
            clientContext.tag.showUserTags(clientContext.user.getCurrent().id);
        }
    } else {
        System.out.format("Command not recognized: %s\n", token);
        System.out.format("Command line rejected: %s%s\n", token,
                (tokenScanner.hasNext()) ? tokenScanner.nextLine() : "");
        System.out.println("Type \"help\" for help.");
    }
    tokenScanner.close();
}

From source file:com.tesora.dve.tools.DVEConfigCLI.java

public void cmd_connect(Scanner scanner) throws PEException {
    cmd_disconnect();/*w ww. j ava2  s .co  m*/

    String url = PEConstants.MYSQL_URL;
    String user = PEConstants.ROOT;
    String password = PEConstants.PASSWORD;

    if (scanner.hasNext()) {
        url = scan(scanner, "url");
        user = scan(scanner, "user");
        password = scan(scanner, "password");
    }

    url = PEUrl.fromUrlString(url).getURL();

    dbHelper = new DBHelper(url, user, password).connect();

    printlnDots("You are now connected to the DVE server at '" + url + "'");
}

From source file:ml.shifu.shifu.core.processor.VarSelectModelProcessor.java

private void postProcess4SEVarSelect(SourceType source, String varSelectMSEOutputPath) throws IOException {
    String outputFilePattern = varSelectMSEOutputPath + Path.SEPARATOR + "part-r-*";
    if (!ShifuFileUtils.isFileExists(outputFilePattern, source)) {
        throw new RuntimeException("Var select MSE stats output file not exist.");
    }//from  w w  w. java  2s . co  m

    int selectCnt = 0;
    for (ColumnConfig config : super.columnConfigList) {
        if (config.isFinalSelect()) {
            config.setFinalSelect(false);
        }

        // enable ForceSelect
        if (config.isForceSelect()) {
            config.setFinalSelect(true);
            selectCnt++;
            log.info("Variable {} is selected, since it is in ForceSelect list.", config.getColumnName());
        }
    }

    Set<NSColumn> userCandidateColumns = CommonUtils.loadCandidateColumns(modelConfig);

    List<Scanner> scanners = null;
    try {
        // here only works for 1 reducer
        FileStatus[] globStatus = ShifuFileUtils.getFileSystemBySourceType(source)
                .globStatus(new Path(outputFilePattern));
        if (globStatus == null || globStatus.length == 0) {
            throw new RuntimeException("Var select MSE stats output file not exist.");
        }
        scanners = ShifuFileUtils.getDataScanners(globStatus[0].getPath().toString(), source);
        String str = null;
        int targetCnt = 0; // total variable count that user want to select
        List<Integer> candidateColumnIdList = new ArrayList<Integer>();
        Scanner scanner = scanners.get(0);
        while (scanner.hasNext()) {
            ++targetCnt;
            str = scanner.nextLine().trim();
            candidateColumnIdList.add(Integer.parseInt(str));
        }

        int i = 0;
        int candidateCount = candidateColumnIdList.size();
        // try to select another (targetCnt - selectCnt) variables, but we need to exclude those
        // force-selected variables
        while (selectCnt < targetCnt && i < targetCnt) {
            if (i >= candidateCount) {
                log.warn("Var select finish due candidate column {} is less than target var count {}",
                        candidateCount, targetCnt);
                break;
            }
            Integer columnId = candidateColumnIdList.get(i++);
            // after supporting segments, the columns will expansion. the columnId may not the position
            // in columnConfigList. It's safe to columnId to search (make sure columnNum == columnId)
            ColumnConfig columnConfig = CommonUtils.getColumnConfig(this.columnConfigList, columnId);
            if (CollectionUtils.isNotEmpty(userCandidateColumns)
                    && !userCandidateColumns.contains(new NSColumn(columnConfig.getColumnName()))) {
                log.info("Variable {} is not in user's candidate list. Skip it.", columnConfig.getColumnName());
            } else if (!columnConfig.isForceSelect() && !columnConfig.isForceRemove()) {
                columnConfig.setFinalSelect(true);
                selectCnt++;
                log.info("Variable {} is selected.", columnConfig.getColumnName());
            }
        }

        log.info("{} variables are selected.", selectCnt);
        log.info(
                "Sensitivity analysis report is in {}/{}-* file(s) with format 'column_index\tcolumn_name\tmean\trms\tvariance'.",
                varSelectMSEOutputPath, Constants.SHIFU_VARSELECT_SE_OUTPUT_NAME);
        this.seStatsMap = readSEValuesToMap(
                varSelectMSEOutputPath + Path.SEPARATOR + Constants.SHIFU_VARSELECT_SE_OUTPUT_NAME + "-*",
                source);
    } finally {
        if (scanners != null) {
            for (Scanner scanner : scanners) {
                if (scanner != null) {
                    scanner.close();
                }
            }
        }
    }
}

From source file:com.amazon.sqs.javamessaging.AmazonSQSExtendedClient.java

private String getTextFromS3(String s3BucketName, String s3Key) {
    GetObjectRequest getObjectRequest = new GetObjectRequest(s3BucketName, s3Key);
    String embeddedText = null;/*from w ww .  jav  a 2s .  com*/
    S3Object obj = null;
    try {
        obj = clientConfiguration.getAmazonS3Client().getObject(getObjectRequest);
    } catch (AmazonServiceException e) {
        String errorMessage = "Failed to get the S3 object which contains the message payload. Message was not received.";
        LOG.error(errorMessage, e);
        throw new AmazonServiceException(errorMessage, e);
    } catch (AmazonClientException e) {
        String errorMessage = "Failed to get the S3 object which contains the message payload. Message was not received.";
        LOG.error(errorMessage, e);
        throw new AmazonClientException(errorMessage, e);
    }
    try {
        InputStream objContent = obj.getObjectContent();
        java.util.Scanner objContentScanner = new java.util.Scanner(objContent, "UTF-8");
        objContentScanner.useDelimiter("\\A");
        embeddedText = objContentScanner.hasNext() ? objContentScanner.next() : "";
        objContentScanner.close();
        objContent.close();
    } catch (IOException e) {
        String errorMessage = "Failure when handling the message which was read from S3 object. Message was not received.";
        LOG.error(errorMessage, e);
        throw new AmazonClientException(errorMessage, e);
    }
    return embeddedText;
}

From source file:org.fao.geonet.kernel.search.LuceneQueryBuilder.java

/**
 * Build a Lucene query for the {@link LuceneQueryInput}.
 *
 * A AND clause is used for each search criteria and a OR clause if the content of a criteria is "this or that".
 *
 * A Boolean OR between parameters is used if the parameter has the form A_OR_B with content "this", this will
 * produce a query for documents having "this" in field A, B or both.
 *
 * Some search criteria does not support multi-occurences like spatial, temporal criteria or range fields.
 * //w  ww  .  j av a 2  s  .co m
 * @param luceneQueryInput user and system input
 * @return Lucene query
 */
public Query build(LuceneQueryInput luceneQueryInput) {
    if (Log.isDebugEnabled(Geonet.SEARCH_ENGINE))
        Log.debug(Geonet.SEARCH_ENGINE,
                "LuceneQueryBuilder: luceneQueryInput is: \n" + luceneQueryInput.toString());

    // Remember which range fields have been processed
    Set<String> processedRangeFields = new HashSet<String>();

    // top query to hold all sub-queries for each search parameter
    BooleanQuery query = new BooleanQuery();

    // Filter according to user session
    addPrivilegeQuery(luceneQueryInput, query);

    // similarity is passed to textfield-query-creating methods
    String similarity = luceneQueryInput.getSimilarity();

    Map<String, Set<String>> searchCriteria = luceneQueryInput.getSearchCriteria();

    //
    // search criteria fields may contain zero or more _OR_ in their name, in which case the search will be a
    // disjunction of searches for fieldnames separated by that.
    //
    // here such _OR_ fields are parsed, an OR searchCriteria map is created, and theyre removed from vanilla
    // searchCriteria map.
    //
    Map<String, Set<String>> searchCriteriaOR = new HashMap<String, Set<String>>();

    for (Iterator<Entry<String, Set<String>>> i = searchCriteria.entrySet().iterator(); i.hasNext();) {
        Entry<String, Set<String>> entry = i.next();
        String fieldName = entry.getKey();
        Set<String> fieldValues = entry.getValue();
        if (fieldName.contains(FIELD_OR_SEPARATOR)) {
            i.remove();
            if (fieldName.contains(LuceneIndexField.NORTH) || fieldName.contains(LuceneIndexField.SOUTH)
                    || fieldName.contains(LuceneIndexField.EAST) || fieldName.contains(LuceneIndexField.WEST)
                    || fieldName.contains(SearchParameter.RELATION)

                    || fieldName.contains("without") || fieldName.contains("phrase")

                    || fieldName.contains(SearchParameter.EXTTO) || fieldName.contains(SearchParameter.EXTFROM)

                    || fieldName.contains(SearchParameter.FEATURED)
                    || fieldName.contains(SearchParameter.TEMPLATE)

                    || UserQueryInput.RANGE_QUERY_FIELDS.contains(fieldName)

            ) {
                // not supported in field disjunction
                continue;
            }

            Scanner scanner = new Scanner(fieldName).useDelimiter(FIELD_OR_SEPARATOR);
            while (scanner.hasNext()) {
                String field = scanner.next();

                if (field.equals("or")) {
                    // handle as 'any', add ' or ' for space-separated values
                    for (String fieldValue : fieldValues) {
                        field = "any";
                        Scanner whitespaceScan = new Scanner(fieldValue).useDelimiter("\\w");
                        while (whitespaceScan.hasNext()) {
                            fieldValue += " or " + whitespaceScan.next();
                        }
                        fieldValue = fieldValue.substring(" or ".length());
                        Set<String> values = searchCriteriaOR.get(field);
                        if (values == null)
                            values = new HashSet<String>();
                        values.addAll(fieldValues);
                        searchCriteriaOR.put(field, values);
                    }
                } else {
                    Set<String> values = searchCriteriaOR.get(field);
                    if (values == null)
                        values = new HashSet<String>();
                    values.addAll(fieldValues);
                    searchCriteriaOR.put(field, values);
                }
            }
        }
    }
    query = buildORQuery(searchCriteriaOR, query, similarity);
    query = buildANDQuery(searchCriteria, query, similarity, processedRangeFields);
    if (StringUtils.isNotEmpty(_language)) {
        if (Log.isDebugEnabled(Geonet.LUCENE))
            Log.debug(Geonet.LUCENE, "adding locale query for language " + _language);
        return addLocaleTerm(query, _language, luceneQueryInput.isRequestedLanguageOnly());
    } else {
        if (Log.isDebugEnabled(Geonet.LUCENE))
            Log.debug(Geonet.LUCENE, "no language set, not adding locale query");
        return query;
    }
}

From source file:org.orekit.files.ccsds.OEMParser.java

/**
 * Parse an ephemeris data line and add its content to the ephemerides
 * block.// w w  w  . j a v  a2 s  .co  m
 *
 * @param reader the reader
 * @param pi the parser info
 * @exception IOException if an error occurs while reading from the stream
 * @exception OrekitException if a date cannot be parsed
 */
private void parseEphemeridesDataLines(final BufferedReader reader, final ParseInfo pi)
        throws OrekitException, IOException {

    for (String line = reader.readLine(); line != null; line = reader.readLine()) {

        ++pi.lineNumber;
        if (line.trim().length() > 0) {
            pi.keyValue = new KeyValue(line, pi.lineNumber, pi.fileName);
            if (pi.keyValue.getKeyword() == null) {
                Scanner sc = null;
                try {
                    sc = new Scanner(line);
                    final AbsoluteDate date = parseDate(sc.next(),
                            pi.lastEphemeridesBlock.getMetaData().getTimeSystem());
                    final Vector3D position = new Vector3D(Double.parseDouble(sc.next()) * 1000,
                            Double.parseDouble(sc.next()) * 1000, Double.parseDouble(sc.next()) * 1000);
                    final Vector3D velocity = new Vector3D(Double.parseDouble(sc.next()) * 1000,
                            Double.parseDouble(sc.next()) * 1000, Double.parseDouble(sc.next()) * 1000);
                    final CartesianOrbit orbit = new CartesianOrbit(new PVCoordinates(position, velocity),
                            pi.lastEphemeridesBlock.getMetaData().getFrame(), date, pi.file.getMuUsed());
                    Vector3D acceleration = null;
                    if (sc.hasNext()) {
                        acceleration = new Vector3D(Double.parseDouble(sc.next()) * 1000,
                                Double.parseDouble(sc.next()) * 1000, Double.parseDouble(sc.next()) * 1000);
                    }
                    final OEMFile.EphemeridesDataLine epDataLine = new OEMFile.EphemeridesDataLine(orbit,
                            acceleration);
                    pi.lastEphemeridesBlock.getEphemeridesDataLines().add(epDataLine);
                } catch (NumberFormatException nfe) {
                    throw new OrekitException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE, pi.lineNumber,
                            pi.fileName, line);
                } finally {
                    if (sc != null) {
                        sc.close();
                    }
                }
            } else {
                switch (pi.keyValue.getKeyword()) {
                case META_START:
                    pi.lastEphemeridesBlock.setEphemeridesDataLinesComment(pi.commentTmp);
                    pi.commentTmp.clear();
                    pi.lineNumber--;
                    reader.reset();
                    return;
                case COVARIANCE_START:
                    pi.lastEphemeridesBlock.setEphemeridesDataLinesComment(pi.commentTmp);
                    pi.commentTmp.clear();
                    pi.lineNumber--;
                    reader.reset();
                    return;
                case COMMENT:
                    pi.commentTmp.add(pi.keyValue.getValue());
                    break;
                default:
                    throw new OrekitException(OrekitMessages.CCSDS_UNEXPECTED_KEYWORD, pi.lineNumber,
                            pi.fileName, line);
                }
            }
        }
        reader.mark(300);

    }
}

From source file:com.tesora.dve.tools.DVEAnalyzerCLI.java

/**
 * Specify the connection information to use when connecting to a database.
 * This information is used when the 'static' command is executed.
 * Note: this information is persisted to and read back from the report file
 * //from   www  .j  a v  a2s. c o m
 * @param scanner
 * @throws PEException
 */
public void cmd_connect(Scanner scanner) throws PEException {
    if (scanner.hasNext()) {
        url = scan(scanner, "jdbcURL");
        user = scan(scanner, "user");
        password = scan(scanner, "password");
    }

    url = PEUrl.fromUrlString(url).getURL();

    println("... Connection set to '" + url.toString() + "'");
}

From source file:com.aurel.track.dbase.InitDatabase.java

private static void insertNullObjectsAndSampleData() {
    ResultSet rs = null;//from w  w w . j av  a 2 s. c om
    Connection coni = null;
    Connection cono = null;
    try {
        coni = getConnection();
        cono = getConnection();
        Statement istmt = coni.createStatement();
        Statement ostmt = cono.createStatement();
        LOGGER.info("Testing for NULL objects...");
        // --------------- T S I T E ----------------------
        rs = istmt.executeQuery("SELECT * FROM TSITE");
        if (rs == null || !rs.next()) {
            try {
                ostmt.execute("INSERT INTO TSITE " + "(OBJECTID) " + "VALUES (1)");
                LOGGER.info("Inserted TSITE");
            } catch (Exception exc) {
                LOGGER.error("Problem inserting TSITE object: " + exc.getMessage());
                LOGGER.debug(STACKTRACE, exc);
            }
        }

        // --------------- T P R O J E C T T Y P E ----------------------
        rs = istmt.executeQuery("SELECT * FROM TPROJECTTYPE WHERE OBJECTID = 0");
        if (rs == null || !rs.next()) {
            try {
                ostmt.execute(
                        "INSERT INTO TPROJECTTYPE " + "(OBJECTID, LABEL, NOTIFYOWNERLEVEL, NOTIFYMANAGERLEVEL) "
                                + "VALUES (0, 'Generic Space', 0, 1)");
                LOGGER.info("Inserted NULL project (PKEY = 0) into TPROJECTTYPE");
            } catch (Exception exc) {
                LOGGER.error("Problem inserting NULL object for TPROJECTTYPE: " + exc.getMessage());
                LOGGER.debug(STACKTRACE, exc);
            }
        }

        rs = istmt.executeQuery("SELECT * FROM TPROJECTTYPE WHERE OBJECTID = -1");
        if (rs == null || !rs.next()) {
            try {
                ostmt.execute("INSERT INTO TPROJECTTYPE " + "(OBJECTID, LABEL, DEFAULTFORPRIVATE) "
                        + "VALUES (-1, 'Private Project', 'Y')");
                LOGGER.info("Inserted Private project (PKEY = -1) into TPROJECTTYPE");
            } catch (Exception exc) {
                LOGGER.error("Problem inserting private space in TPROJECTTYPE: " + exc.getMessage());
                LOGGER.debug(STACKTRACE, exc);
            }
        }

        rs = istmt.executeQuery("SELECT * FROM TPROJECT WHERE PKEY = 0");
        // ------------------- T P R O J E C T  -----------------------
        if (rs == null || !rs.next()) {
            try {
                ostmt.execute("INSERT INTO TPROJECT " + "(PKEY, LABEL, DEFOWNER, DEFMANAGER, PROJECTTYPE) "
                        + "VALUES (0, 'Generic Space', 1, 1, 0)");
                LOGGER.info("Inserted NULL project (PKEY = 0) into TPROJECT");
            } catch (Exception exc) {
                LOGGER.error("Problem inserting NULL object for TPROJECT: " + exc.getMessage());
            }
        }

        // ----------------------- T R O L E ------------------------------
        rs = istmt.executeQuery("SELECT * FROM TROLE WHERE PKEY = -1");
        if (rs == null || !rs.next()) {
            try {
                ostmt.execute("INSERT INTO TROLE " + "(PKEY, LABEL, ACCESSKEY, EXTENDEDACCESSKEY, PROJECTTYPE) "
                        + "VALUES (-1, 'PrivateRole', 0, '111111111111', 0)");
                LOGGER.info("Inserted private role (PKEY = -1) into TROLE");
            } catch (Exception exc) {
                LOGGER.error("Problem inserting NULL object for TROLE: " + exc.getMessage());
                LOGGER.debug(STACKTRACE, exc);
            }
        }

        LOGGER.info("NULL objects are okay.");

        if (isFirstStartEver) {
            LOGGER.info("Filling some sample data...");
            try {

                URL populateURL = ApplicationBean.getInstance().getServletContext().getResource(populateSql);
                if (populateURL == null) {
                    ClassLoader cl = InitDatabase.class.getClassLoader();
                    populateURL = cl.getResource(populateSql);
                }
                InputStream in = populateURL.openStream();
                java.util.Scanner s = new java.util.Scanner(in, "UTF-8");
                s.useDelimiter(";");
                String st = null;
                StringBuffer stb = new StringBuffer();
                int line = 0;

                ApplicationStarter.getInstance().actualizePercentComplete(
                        ApplicationStarter.getInstance().INIT_DB_DATA_STEP,
                        ApplicationStarter.INIT_DB_DATA_TEXT);

                while (s.hasNext()) {
                    stb.append(s.nextLine().trim());
                    st = stb.toString();
                    ++line;
                    if (!st.isEmpty() && !st.startsWith("--") && !st.startsWith("/*")) {
                        if (st.endsWith(";")) {
                            stb = new StringBuffer(); // clear buffer
                            st = st.substring(0, st.length() - 1); // remove the semicolon
                            try {
                                ostmt.executeUpdate(st);
                            } catch (Exception exc) {
                                LOGGER.error("Problem inserting sample data: " + exc.getMessage());
                                LOGGER.error("Line " + line + ": " + st);
                            }
                        } else {
                            stb.append(" ");
                        }
                    } else {
                        stb = new StringBuffer();
                    }
                }
                s.close();
                in.close();

            } catch (Exception e) {
                LOGGER.error(ExceptionUtils.getStackTrace(e));
            }
            LOGGER.info("Sample data is okay.");

            ApplicationStarter.getInstance().actualizePercentComplete(
                    ApplicationStarter.getInstance().INIT_DB_DATA_STEP, ApplicationStarter.INIT_DB_DATA_TEXT);
        }
    } catch (Exception e) {
        LOGGER.error("Problem inserting null objects: " + e.getMessage());
        LOGGER.debug(STACKTRACE, e);
    } finally {
        if (coni != null) {
            try {
                coni.close();
            } catch (SQLException e) {
                LOGGER.info("Closing connection failed with " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
        if (cono != null) {
            try {
                cono.close();
            } catch (SQLException e) {
                LOGGER.info("Closing connection failed with " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    }
}

From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java

public String convertStream(HttpsURLConnection connection) throws IOException {
    InputStream input = connection.getInputStream();
    if (input == null) {
        return "";
    }// w  w w.  j  a  v a2s . c o  m

    InputStream readerStream;
    if (StringUtils.equalsIgnoreCase(connection.getContentEncoding(), "gzip")) {
        readerStream = new GZIPInputStream(connection.getInputStream());
    } else {
        readerStream = input;
    }
    String contentType = connection.getContentType();
    String charSet = null;
    if (contentType != null) {
        Matcher m = charsetPattern.matcher(contentType);
        if (m.find()) {
            charSet = m.group(1).trim().toUpperCase();
        }
    }

    Scanner inputScanner = StringUtils.isEmpty(charSet)
            ? new Scanner(readerStream, StandardCharsets.UTF_8.name())
            : new Scanner(readerStream, charSet);
    Scanner scannerWithoutDelimiter = inputScanner.useDelimiter("\\A");
    String result = scannerWithoutDelimiter.hasNext() ? scannerWithoutDelimiter.next() : null;
    inputScanner.close();
    scannerWithoutDelimiter.close();
    input.close();
    if (result == null) {
        result = "";
    }
    return result;
}

From source file:com.nuvolect.deepdive.probe.DecompileApk.java

/**
 * Build a new DEX file excluding classes in the OPTIMIZED_CLASS_EXCLUSION file
 * @return// w ww .j a va  2 s .co  m
 */
private JSONObject optimizeDex() {

    final Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {

            LogUtil.log(LogUtil.LogType.DECOMPILE, "Uncaught exception: " + e.toString());
            m_progressStream.putStream("Uncaught exception: " + t.getName());
            m_progressStream.putStream("Uncaught exception: " + e.toString());
        }
    };

    m_optimize_dex_time = System.currentTimeMillis(); // Save start time for tracking

    m_optimizeDexThread = new Thread(m_threadGroup, new Runnable() {
        @Override
        public void run() {

            m_progressStream = new ProgressStream(
                    new OmniFile(m_volumeId, m_appFolderPath + DEX_OPTIMIZATION_LOG_FILE));

            m_progressStream
                    .putStream("Optimizing classes, reference: " + OPTIMIZED_CLASSES_EXCLUSION_FILENAME);

            Scanner s = null;
            try {
                OmniFile omniFile = new OmniFile(m_volumeId,
                        m_appFolderPath + OPTIMIZED_CLASSES_EXCLUSION_FILENAME);
                s = new Scanner(omniFile.getStdFile());
                while (s.hasNext()) {
                    String excludeClass = s.next();
                    ignoredLibs.add(excludeClass);
                    m_progressStream.putStream("Exclude class: " + excludeClass);
                }
            } catch (Exception e) {
                LogUtil.logException(LogUtil.LogType.DECOMPILE, e);
            }
            if (s != null)
                s.close();

            ArrayList<OmniFile> dexFiles = new ArrayList<>();

            for (String fileName : m_dexFileNames) {

                OmniFile dexFile = new OmniFile(m_volumeId, m_appFolderPath + fileName + ".dex");

                if (dexFile.exists() && dexFile.isFile()) {

                    dexFiles.add(dexFile);// Keep track for summary

                    List<ClassDef> classes = new ArrayList<>();
                    m_progressStream.putStream("Processing: " + fileName + ".dex");
                    org.jf.dexlib2.iface.DexFile memoryDexFile = null;
                    try {
                        memoryDexFile = DexFileFactory.loadDexFile(dexFile.getStdFile(), Opcodes.forApi(19));
                    } catch (Exception e) {
                        m_progressStream.putStream("The app DEX file cannot be decompiled.");
                        LogUtil.logException(LogUtil.LogType.DECOMPILE, e);
                        continue;
                    }

                    int excludedClassCount = 0;
                    Set<? extends ClassDef> origClassSet = memoryDexFile.getClasses();
                    memoryDexFile = null; // Release memory

                    for (org.jf.dexlib2.iface.ClassDef classDef : origClassSet) {

                        final String currentClass = classDef.getType();

                        if (isIgnored(currentClass)) {
                            ++excludedClassCount;
                            m_progressStream.putStream("Excluded class: " + currentClass);
                        } else {
                            m_progressStream.putStream("Included class: " + currentClass);
                            classes.add(classDef);
                        }
                    }
                    origClassSet = null; // Release memory

                    m_progressStream.putStream("Excluded classes #" + excludedClassCount);
                    m_progressStream.putStream("Included classes #" + classes.size());
                    m_progressStream.putStream("Rebuilding immutable dex: " + fileName + ".dex");

                    if (classes.size() > 0) {

                        DexFile optDexFile = new ImmutableDexFile(Opcodes.forApi(19), classes);
                        classes = null; // Release memory

                        try {
                            if (dexFile.delete())
                                m_progressStream.putStream("Fat DEX file delete success: " + dexFile.getName());
                            else
                                m_progressStream.putStream("Fat DEX file delete FAILED: " + dexFile.getName());

                            DexPool.writeTo(dexFile.getStdFile().getAbsolutePath(), optDexFile);
                            String size = NumberFormat.getNumberInstance(Locale.US).format(dexFile.length());

                            m_progressStream.putStream(
                                    "Optimized DEX file created: " + dexFile.getName() + ", size: " + size);
                        } catch (IOException e) {
                            m_progressStream.putStream("DEX IOException, write error: " + dexFile.getName());
                            LogUtil.logException(LogUtil.LogType.DECOMPILE, e);
                        } catch (Exception e) {
                            m_progressStream.putStream("DEX Exception, write error: " + dexFile.getName());
                            LogUtil.logException(LogUtil.LogType.DECOMPILE, e);
                        }
                        optDexFile = null; // release memory
                    } else {

                        m_progressStream
                                .putStream("All classes excluded, DEX file not needed: " + dexFile.getName());
                        m_progressStream.putStream("Deleting: " + dexFile.getName());
                        dexFile.delete();
                    }
                }
            }
            for (OmniFile f : dexFiles) {

                if (f.exists()) {

                    String formatted_count = String.format(Locale.US, "%,d", f.length()) + " bytes";
                    m_progressStream.putStream("DEX optimized: " + f.getName() + ": " + formatted_count);
                } else {
                    m_progressStream.putStream("DEX deleted: " + f.getName() + ", all classes excluded");
                }
            }
            dexFiles = new ArrayList<>();// Release memory

            m_progressStream
                    .putStream("Optimize DEX complete: " + TimeUtil.deltaTimeHrMinSec(m_optimize_dex_time));
            m_progressStream.close();
            m_optimize_dex_time = 0;

        }
    }, UNZIP_APK_THREAD, STACK_SIZE);

    m_optimizeDexThread.setPriority(Thread.MAX_PRIORITY);
    m_optimizeDexThread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
    m_optimizeDexThread.start();

    return new JSONObject();
}