Example usage for java.util Scanner close

List of usage examples for java.util Scanner close

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes this scanner.

Usage

From source file:com.marklogic.client.functionaltest.BasicJavaClientREST.java

/**
 * Write document using StringHandle// w  w w  . j  a v a2s.  c o m
 * @param client
 * @param filename
 * @param uri
 * @param type
 * @throws IOException
 */
public void writeDocumentUsingStringHandle(DatabaseClient client, String filename, String uri, String type)
        throws IOException {
    // acquire the content
    File file = new File("src/test/java/com/marklogic/client/functionaltest/data/" + filename);
    FileInputStream fis = new FileInputStream(file);
    Scanner scanner = new Scanner(fis).useDelimiter("\\Z");
    String readContent = scanner.next();
    fis.close();
    scanner.close();

    // create doc manager
    DocumentManager docMgr = null;
    docMgr = documentManagerSelector(client, docMgr, type);

    String docId = uri + filename;

    // create handle
    StringHandle contentHandle = new StringHandle();
    contentHandle.set(readContent);

    // write the doc
    docMgr.write(docId, contentHandle);

    System.out.println("Write " + docId + " to the database");
}

From source file:com.marklogic.client.functionaltest.BasicJavaClientREST.java

/**
 * Update document using FileHandle//from  w  w w .ja  v  a 2  s. co m
 * @param client
 * @param filename
 * @param uri
 * @param type
 * @throws IOException
 */
public void updateDocumentUsingStringHandle(DatabaseClient client, String filename, String uri, String type)
        throws IOException {
    // create doc manager
    DocumentManager docMgr = null;
    docMgr = documentManagerSelector(client, docMgr, type);

    File file = new File("src/test/java/com/marklogic/client/functionaltest/data/" + filename);
    FileInputStream fis = new FileInputStream(file);
    Scanner scanner = new Scanner(fis).useDelimiter("\\Z");
    String readContent = scanner.next();
    fis.close();
    scanner.close();

    // create an identifier for the document
    String docId = uri;

    // create a handle on the content
    // create handle
    StringHandle contentHandle = new StringHandle();
    contentHandle.set(readContent);

    // write the document content
    docMgr.write(docId, contentHandle);

    System.out.println("Update " + docId + " to database");
}

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

/**
 * Build a new DEX file excluding classes in the OPTIMIZED_CLASS_EXCLUSION file
 * @return/* w  w  w .  j  a v a 2 s . c  o  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();
}

From source file:com.joliciel.talismane.terminology.viewer.TerminologyViewerController.java

@FXML
protected void initialize() throws Exception {
    String currentDirPath = System.getProperty("user.dir");
    File confDir = new File(currentDirPath + "/conf/");
    confDir.mkdirs();/*from   w  w w  .ja v  a 2  s . co m*/
    File iniFile = new File(confDir, "talismane_terminology_viewer.ini");
    if (!iniFile.exists())
        iniFile.createNewFile();
    else {
        Scanner scanner = new Scanner(
                new BufferedReader(new InputStreamReader(new FileInputStream(iniFile), "UTF-8")));

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (!line.startsWith("#")) {
                int equalsPos = line.indexOf('=');
                String parameter = line.substring(0, equalsPos);
                String value = line.substring(equalsPos + 1);
                if (parameter.equals("editor")) {
                    editor = value;
                } else if (parameter.equals("arguments")) {
                    arguments = value;
                } else if (parameter.equals("jdbc.url")) {
                    databaseURL = value;
                } else if (parameter.equals("jdbc.username")) {
                    databaseUsername = value;
                } else if (parameter.equals("jdbc.password")) {
                    databasePassword = value;
                } else if (parameter.equals("project.code")) {
                    projectCode = value;
                } else if (parameter.equals("csvSeparator")) {
                    csvSeparator = value;
                }
            }
        }
        scanner.close();
    }
}

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

private Map<Integer, ColumnStatistics> readSEValuesToMap(String seOutputFiles, SourceType source)
        throws IOException {
    // here only works for 1 reducer
    FileStatus[] globStatus = ShifuFileUtils.getFileSystemBySourceType(source)
            .globStatus(new Path(seOutputFiles));
    if (globStatus == null || globStatus.length == 0) {
        throw new RuntimeException("Var select MSE stats output file not exist.");
    }//from  w w w.  j av a 2s.  c om
    Map<Integer, ColumnStatistics> map = new HashMap<Integer, ColumnStatistics>();
    List<Scanner> scanners = null;
    try {
        scanners = ShifuFileUtils.getDataScanners(globStatus[0].getPath().toString(), source);
        for (Scanner scanner : scanners) {
            String str = null;
            while (scanner.hasNext()) {
                str = scanner.nextLine().trim();
                String[] splits = CommonUtils.split(str, "\t");
                if (splits.length == 5) {
                    map.put(Integer.parseInt(splits[0].trim()),
                            new ColumnStatistics(Double.parseDouble(splits[2]), Double.parseDouble(splits[3]),
                                    Double.parseDouble(splits[4])));
                }
            }
        }
    } finally {
        if (scanners != null) {
            for (Scanner scanner : scanners) {
                if (scanner != null) {
                    scanner.close();
                }
            }
        }
    }
    return map; // should be a bug, if it always return null
}

From source file:de.stefanwndelmann.zy1270logger.ZY1270LoggerMain.java

private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed
    if (connectButton.getText().equals("Connect")) {
        // attempt to connect to the serial port
        chosenPort = SerialPort.getCommPort(portList.getSelectedItem().toString());
        chosenPort.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
        if (chosenPort.openPort()) {
            connectButton.setText("Disconnect");
            portList.setEnabled(false);/*  w ww. ja  va  2s  .  c o  m*/
        }

        portThread = new Thread() {
            @Override
            public void run() {
                Scanner scanner = new Scanner(chosenPort.getInputStream());
                try {
                    Thread.currentThread().setName("Port Reader");
                    while (true) {
                        while (scanner.hasNextLine()) {
                            try {
                                String line = scanner.nextLine();
                                ZY1270Data data = ZY1270Data.parseString(line, new Date());
                                ((DefaultTableModel) resultTable.getModel()).addRow(data.getRowFormat());
                                java.awt.EventQueue.invokeLater(new Runnable() {
                                    public void run() {
                                        resultTable.scrollRectToVisible(
                                                resultTable.getCellRect(resultTable.getRowCount() - 1,
                                                        resultTable.getColumnCount(), true));
                                    }
                                });
                                ampSeries.add(new Millisecond(data.getTimestamp()), data.getAmp());
                                voltageSeries.add(new Millisecond(data.getTimestamp()), data.getVoltage());
                                wattSeries.add(new Millisecond(data.getTimestamp()), data.getWatt());
                            } catch (Exception e) {
                            }
                        }
                        Thread.sleep(1);
                    }
                } catch (Exception e) {

                } finally {
                    scanner.close();
                }
            }
        };
        portThread.start();
    } else {
        // disconnect from the serial port
        new Thread() {
            @Override
            public void run() {
                while (!portThread.isInterrupted()) {
                    portThread.interrupt();
                }
                chosenPort.closePort();
                portList.setEnabled(true);
                connectButton.setText("Connect");
            }
        }.start();
    }
}

From source file:la2launcher.MainFrame.java

private int scanSumFilesCount(File sums, boolean full) throws FileNotFoundException, IOException {
    FileInputStream fis = new FileInputStream(sums);
    Scanner scn = new Scanner(fis);
    int lc = 0;//  w  ww.  j  av a2s  .  c  o m
    while (scn.hasNextLine()) {
        String line = scn.nextLine();
        if ("#-[Required from required.ini]----------------------------------".equals(line)) {
            break;
        }
        int pipe = line.indexOf('|');
        int nextPipe = line.indexOf('|', pipe + 1);
        String sum = line.substring(0, pipe);
        String name = line.substring(pipe + 1, nextPipe);
        if (!full) {
            if (name.toUpperCase().startsWith("\\SYSTEM")) {
                lc++;
            }
        } else {
            lc++;
        }
    }
    scn.close();
    fis.close();
    return lc;
}

From source file:com.axelor.studio.service.builder.FormBuilderService.java

private Iterator<ViewPanel> sortPanels(List<ViewPanel> viewPanelList) {

    Collections.sort(viewPanelList, new Comparator<ViewPanel>() {

        @Override/*from w  w w  .j  av  a2s.  co m*/
        public int compare(ViewPanel panel1, ViewPanel panel2) {
            Scanner scan1 = new Scanner(panel1.getPanelLevel());
            Scanner scan2 = new Scanner(panel2.getPanelLevel());
            scan1.useDelimiter("\\.");
            scan2.useDelimiter("\\.");
            try {
                while (scan1.hasNextInt() && scan2.hasNextInt()) {
                    int v1 = scan1.nextInt();
                    int v2 = scan2.nextInt();
                    if (v1 < v2) {
                        return -1;
                    } else if (v1 > v2) {
                        return 1;
                    }
                }

                if (scan2.hasNextInt()) {
                    return -1;
                }
                if (scan1.hasNextInt()) {
                    return 1;
                }

                return 0;
            } finally {
                scan1.close();
                scan2.close();
            }

        }
    });

    return viewPanelList.iterator();
}

From source file:com.zero_x_baadf00d.partialize.Partialize.java

/**
 * Build a JSON object from data taken from the scanner and
 * the given class type and instance./*w  ww .ja  v  a  2  s .com*/
 *
 * @param depth         The current depth
 * @param fields        The field names to requests
 * @param clazz         The class of the object to render
 * @param instance      The instance of the object to render
 * @param partialObject The partial JSON document
 * @return A JSON Object
 * @since 16.01.18
 */
private ObjectNode buildPartialObject(final int depth, String fields, final Class<?> clazz,
        final Object instance, final ObjectNode partialObject) {
    if (depth <= this.maximumDepth) {
        if (clazz.isAnnotationPresent(com.zero_x_baadf00d.partialize.annotation.Partialize.class)) {
            final List<String> closedFields = new ArrayList<>();
            List<String> allowedFields = Arrays.asList(clazz
                    .getAnnotation(com.zero_x_baadf00d.partialize.annotation.Partialize.class).allowedFields());
            List<String> defaultFields = Arrays.asList(clazz
                    .getAnnotation(com.zero_x_baadf00d.partialize.annotation.Partialize.class).defaultFields());
            if (allowedFields.isEmpty()) {
                allowedFields = new ArrayList<>();
                for (final Method m : clazz.getDeclaredMethods()) {
                    final String methodName = m.getName();
                    if (methodName.startsWith("get") || methodName.startsWith("has")) {
                        final char[] c = methodName.substring(3).toCharArray();
                        c[0] = Character.toLowerCase(c[0]);
                        allowedFields.add(new String(c));
                    } else if (methodName.startsWith("is")) {
                        final char[] c = methodName.substring(2).toCharArray();
                        c[0] = Character.toLowerCase(c[0]);
                        allowedFields.add(new String(c));
                    }
                }
            }
            if (defaultFields.isEmpty()) {
                defaultFields = allowedFields.stream().map(f -> {
                    if (this.aliases != null && this.aliases.containsValue(f)) {
                        for (Map.Entry<String, String> e : this.aliases.entrySet()) {
                            if (e.getValue().compareToIgnoreCase(f) == 0) {
                                return e.getKey();
                            }
                        }
                    }
                    return f;
                }).collect(Collectors.toList());
            }
            if (fields == null || fields.length() == 0) {
                fields = defaultFields.stream().collect(Collectors.joining(","));
            }
            Scanner scanner = new Scanner(fields);
            scanner.useDelimiter(com.zero_x_baadf00d.partialize.Partialize.SCANNER_DELIMITER);
            while (scanner.hasNext()) {
                String word = scanner.next();
                String args = null;
                if (word.compareTo("*") == 0) {
                    final StringBuilder sb = new StringBuilder();
                    if (scanner.hasNext()) {
                        scanner.useDelimiter("\n");
                        sb.append(",");
                        sb.append(scanner.next());
                    }
                    final Scanner newScanner = new Scanner(
                            allowedFields.stream().filter(f -> !closedFields.contains(f)).map(f -> {
                                if (this.aliases != null && this.aliases.containsValue(f)) {
                                    for (Map.Entry<String, String> e : this.aliases.entrySet()) {
                                        if (e.getValue().compareToIgnoreCase(f) == 0) {
                                            return e.getKey();
                                        }
                                    }
                                }
                                return f;
                            }).collect(Collectors.joining(",")) + sb.toString());
                    newScanner.useDelimiter(com.zero_x_baadf00d.partialize.Partialize.SCANNER_DELIMITER);
                    scanner.close();
                    scanner = newScanner;
                }
                if (word.contains("(")) {
                    while (scanner.hasNext()
                            && (StringUtils.countMatches(word, "(") != StringUtils.countMatches(word, ")"))) {
                        word += "," + scanner.next();
                    }
                    final Matcher m = this.fieldArgsPattern.matcher(word);
                    if (m.find()) {
                        word = m.group(1);
                        args = m.group(2);
                    }
                }
                final String aliasField = word;
                final String field = this.aliases != null && this.aliases.containsKey(aliasField)
                        ? this.aliases.get(aliasField)
                        : aliasField;
                if (allowedFields.stream().anyMatch(
                        f -> f.toLowerCase(Locale.ENGLISH).compareTo(field.toLowerCase(Locale.ENGLISH)) == 0)) {
                    if (this.accessPolicyFunction != null
                            && !this.accessPolicyFunction.apply(new AccessPolicy(clazz, instance, field))) {
                        continue;
                    }
                    closedFields.add(aliasField);
                    try {
                        final Method method = clazz.getMethod("get" + WordUtils.capitalize(field));
                        final Object object = method.invoke(instance);
                        this.internalBuild(depth, aliasField, field, args, partialObject, clazz, object);
                    } catch (IllegalAccessException | InvocationTargetException
                            | NoSuchMethodException ignore) {
                        try {
                            final Method method = clazz.getMethod(field);
                            final Object object = method.invoke(instance);
                            this.internalBuild(depth, aliasField, field, args, partialObject, clazz, object);
                        } catch (IllegalAccessException | InvocationTargetException
                                | NoSuchMethodException ex) {
                            if (this.exceptionConsumer != null) {
                                this.exceptionConsumer.accept(ex);
                            }
                        }
                    }
                }
            }
            return partialObject;
        } else if (instance instanceof Map<?, ?>) {
            if (fields == null || fields.isEmpty() || fields.compareTo("*") == 0) {
                for (Map.Entry<?, ?> e : ((Map<?, ?>) instance).entrySet()) {
                    this.internalBuild(depth, String.valueOf(e.getKey()), String.valueOf(e.getKey()), null,
                            partialObject, e.getValue() == null ? Object.class : e.getValue().getClass(),
                            e.getValue());
                }
            } else {
                final Map<?, ?> tmpMap = (Map<?, ?>) instance;
                for (final String k : fields.split(",")) {
                    if (k.compareTo("*") != 0) {
                        final Object o = tmpMap.get(k);
                        this.internalBuild(depth, k, k, null, partialObject,
                                o == null ? Object.class : o.getClass(), o);
                    } else {
                        for (Map.Entry<?, ?> e : ((Map<?, ?>) instance).entrySet()) {
                            this.internalBuild(depth, String.valueOf(e.getKey()), String.valueOf(e.getKey()),
                                    null, partialObject,
                                    e.getValue() == null ? Object.class : e.getValue().getClass(),
                                    e.getValue());
                        }
                    }
                }
            }
        } else {
            throw new RuntimeException("Can't convert " + clazz.getCanonicalName());
        }
    }
    return partialObject;
}

From source file:azkaban.viewer.reportal.ReportalServlet.java

/**
 * Returns a list of file Objects that contain a "name" property with the file name,
 * a "content" property with the lines in the file, and a "hasMore" property if the
 * file contains more than NUM_PREVIEW_ROWS lines.
 * @param fileList/*  ww w.j ava2s  .c o m*/
 * @param locationFull
 * @param streamProvider
 * @return
 */
private List<Object> getFilePreviews(String[] fileList, String locationFull, IStreamProvider streamProvider) {
    List<Object> files = new ArrayList<Object>();
    InputStream csvInputStream = null;

    try {
        for (String fileName : fileList) {
            Map<String, Object> file = new HashMap<String, Object>();
            file.put("name", fileName);

            String filePath = locationFull + "/" + fileName;
            csvInputStream = streamProvider.getFileInputStream(filePath);
            Scanner rowScanner = new Scanner(csvInputStream);

            List<Object> lines = new ArrayList<Object>();
            int lineNumber = 0;
            while (rowScanner.hasNextLine() && lineNumber < ReportalMailCreator.NUM_PREVIEW_ROWS) {
                String csvLine = rowScanner.nextLine();
                String[] data = csvLine.split("\",\"");
                List<String> line = new ArrayList<String>();
                for (String item : data) {
                    String column = StringEscapeUtils.escapeHtml(item.replace("\"", ""));
                    line.add(column);
                }
                lines.add(line);
                lineNumber++;
            }

            file.put("content", lines);

            if (rowScanner.hasNextLine()) {
                file.put("hasMore", true);
            }

            files.add(file);
            rowScanner.close();
        }
    } catch (Exception e) {
        logger.debug("Error encountered while processing files in " + locationFull, e);
    } finally {
        IOUtils.closeQuietly(csvInputStream);
    }

    return files;
}