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:uk.ac.gda.dls.client.views.ReadonlyScannableComposite.java

private void setVal(String newVal) {
    if (decimalPlaces != null) {
        Scanner sc = new Scanner(newVal.trim());
        if (sc.hasNextDouble()) {
            NumberFormat format = NumberFormat.getInstance();
            format.setMaximumFractionDigits(decimalPlaces.intValue());
            newVal = format.format(sc.nextDouble());
        }/*  ww w . j  av a2  s .c o m*/
        sc.close();
    }
    val = newVal;
    if (!isDisposed()) {
        if (minPeriodMS != null) {
            if (!textUpdateScheduled) {
                textUpdateScheduled = true;
                display.asyncExec(new Runnable() {

                    @Override
                    public void run() {
                        display.timerExec(minPeriodMS, setTextRunnable);
                    }
                });
            }
        } else {
            display.asyncExec(setTextRunnable);
        }
    }
}

From source file:ProgressMonitorInputStreamTest.java

/**
 * Prompts the user to select a file, loads the file into a text area, and sets it as the content
 * pane of the frame./* www .  j av a2s . co m*/
 */
public void openFile() throws IOException {
    int r = chooser.showOpenDialog(this);
    if (r != JFileChooser.APPROVE_OPTION)
        return;
    final File f = chooser.getSelectedFile();

    // set up stream and reader filter sequence

    FileInputStream fileIn = new FileInputStream(f);
    ProgressMonitorInputStream progressIn = new ProgressMonitorInputStream(this, "Reading " + f.getName(),
            fileIn);
    final Scanner in = new Scanner(progressIn);

    textArea.setText("");

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        protected Void doInBackground() throws Exception {
            while (in.hasNextLine()) {
                String line = in.nextLine();
                textArea.append(line);
                textArea.append("\n");
            }
            in.close();
            return null;
        }
    };
    worker.execute();
}

From source file:org.pathwaycommons.pcviz.service.PathwayCommonsGraphService.java

@Cacheable("metadataCache")
public String getMetadata(String datatype) {
    String urlStr = getPathwayCommonsUrl() + "/metadata/" + datatype;
    try {//from w  ww. j  a v a 2 s .com
        URL url = new URL(urlStr);
        URLConnection urlConnection = url.openConnection();
        StringBuilder builder = new StringBuilder();
        Scanner scanner = new Scanner(urlConnection.getInputStream());
        while (scanner.hasNextLine()) {
            builder.append(scanner.nextLine() + "\n");
        }
        scanner.close();

        return builder.toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.callimachusproject.test.TemporaryServerFactory.java

private String readRepositoryConfigFile() throws FileNotFoundException {
    Scanner scanner = new Scanner(new File("etc", "callimachus-repository.ttl"));
    try {//from  w w  w. j a  v  a 2 s .c om
        return scanner.useDelimiter("\\A").next();
    } finally {
        scanner.close();
    }
}

From source file:edu.harvard.hul.ois.fits.junit.VideoStdSchemaTestXmlUnit.java

@Test
public void testVideoXmlUnitFitsOutput_DV() throws Exception {

    Fits fits = new Fits();

    // First generate the FITS output
    File input = new File("testfiles/FITS-SAMPLE-26.mov");
    FitsOutput fitsOut = fits.examine(input);

    XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());
    String actualXmlStr = serializer.outputString(fitsOut.getFitsXml());

    // Read in the expected XML file
    Scanner scan = new Scanner(new File("testfiles/output/FITS-SAMPLE-26_mov_FITS.xml"));
    String expectedXmlStr = scan.useDelimiter("\\Z").next();
    scan.close();

    // Set up XMLUnit
    XMLUnit.setIgnoreWhitespace(true);// w  ww.ja v  a 2s.co  m
    XMLUnit.setNormalizeWhitespace(true);

    Diff diff = new Diff(expectedXmlStr, actualXmlStr);

    // Initialize attributes or elements to ignore for difference checking
    diff.overrideDifferenceListener(new IgnoreNamedElementsDifferenceListener("version", "toolversion",
            "dateModified", "fslastmodified", "startDate", "startTime", "timestamp", "fitsExecutionTime",
            "executionTime", "filepath", "location"));

    DetailedDiff detailedDiff = new DetailedDiff(diff);

    // Display any Differences
    List<Difference> diffs = detailedDiff.getAllDifferences();
    if (!diff.identical()) {
        StringBuffer differenceDescription = new StringBuffer();
        differenceDescription.append(diffs.size()).append(" differences");

        System.out.println(differenceDescription.toString());
        for (Difference difference : diffs) {
            System.out.println(difference.toString());
        }

    }

    assertTrue("Differences in XML", diff.identical());
}

From source file:ir.ac.ut.snl.mrcd.InputConverter.java

public void convert(String filename) throws FileNotFoundException, UnsupportedEncodingException {
    int paddingSize = 49; //  50-1; 1 baraye '\n'

    File file = new File(filename);
    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    Scanner scanner = new Scanner(bufferedReader);

    PrintWriter printWriter = new PrintWriter(filename + "-converted", "UTF-8");

    int n = scanner.nextInt();
    scanner.nextLine();// w ww. j a v  a2 s.com

    printWriter.write(StringUtils.leftPad(String.valueOf(n), paddingSize));
    printWriter.write('\n');

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        printWriter.write(StringUtils.leftPad(line, paddingSize));
        printWriter.write('\n');
    }

    scanner.close();
    printWriter.close();
}

From source file:org.geppetto.model.neuroml.services.NeuroMLModelInterpreterService.java

public IModel readModel(URL url, List<URL> recordings, String instancePath) throws ModelInterpreterException {
    ModelWrapper model = new ModelWrapper(instancePath);
    try {//from w ww .j a  v  a2s .c om
        Scanner scanner = new Scanner(url.openStream(), "UTF-8");
        String neuroMLString = scanner.useDelimiter("\\A").next();
        scanner.close();
        String lemsString = NeuroMLConverter.convertNeuroML2ToLems(neuroMLString);

        ILEMSDocumentReader lemsReader = new LEMSDocumentReader();
        //ILEMSDocument document = lemsReader.readModel(lemsString);

        int index = url.toString().lastIndexOf('/');
        String urlBase = url.toString().substring(0, index + 1);

        OptimizedLEMSReader reader = new OptimizedLEMSReader(urlBase);
        String lemsStringOptimized = reader.processLEMSInclusions(lemsString);
        lemsStringOptimized = reader.processLEMSInclusions(lemsStringOptimized, false);
        ILEMSDocument document = lemsReader.readModel(lemsStringOptimized);

        //         NeuroMLConverter neuromlConverter = new NeuroMLConverter();
        //         NeuroMLDocument neuroml = neuromlConverter.urlToNeuroML(url);

        NeuroMLConverter neuromlConverter = new NeuroMLConverter();
        String neuromlString = URLReader.readStringFromURL(url);
        NeuroMLDocument neuroml = neuromlConverter.loadNeuroML(neuromlString);

        String neuromlStringOptimized = reader.processLEMSInclusions(neuromlString, false);
        neuromlStringOptimized = reader.processLEMSInclusions(neuromlStringOptimized);
        NeuroMLDocument neuroml_inclusions = neuromlConverter.loadNeuroML(neuromlStringOptimized);

        model = new ModelWrapper(UUID.randomUUID().toString());
        model.setInstancePath(instancePath);
        // two different interpretations of the same file, one used to simulate the other used to visualize
        model.wrapModel(NeuroMLAccessUtility.LEMS_ID, document);
        //model.wrapModel(NeuroMLAccessUtility.LEMS_ID_INCLUSIONS, document_inclusions);
        model.wrapModel(NeuroMLAccessUtility.NEUROML_ID, neuroml);
        model.wrapModel(NeuroMLAccessUtility.NEUROML_ID_INCLUSIONS, neuroml_inclusions);
        model.wrapModel(NeuroMLAccessUtility.URL_ID, url);
        model.wrapModel(NeuroMLAccessUtility.SUBENTITIES_MAPPING_ID, new HashMap<String, EntityNode>());
        model.wrapModel(NeuroMLAccessUtility.DISCOVERED_COMPONENTS, new HashMap<String, Base>());
        model.wrapModel(LEMSAccessUtility.DISCOVERED_LEMS_COMPONENTS, new HashMap<String, Object>());

        model.wrapModel(NeuroMLAccessUtility.DISCOVERED_NESTED_COMPONENTS_ID, new ArrayList<String>());
    } catch (IOException e) {
        throw new ModelInterpreterException(e);
    } catch (ContentError e) {
        throw new ModelInterpreterException(e);
    } catch (JAXBException e) {
        throw new ModelInterpreterException(e);
    } catch (Exception e) {
        throw new ModelInterpreterException(e);
    }
    return model;
}

From source file:edu.harvard.hul.ois.fits.junit.VideoStdSchemaTestXmlUnit.java

@Test
public void testVideoXmlUnitCombinedOutput_DV() throws Exception {

    File input = new File("testfiles/FITS-SAMPLE-26.mov");
    Fits fits = new Fits();
    FitsOutput fitsOut = fits.examine(input);

    // Output stream for FITS to write to 
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    // Create combined output in the stream passed in
    Fits.outputStandardCombinedFormat(fitsOut, out);

    // Turn output stream into a String HtmlUnit can use
    String actualXmlStr = new String(out.toByteArray(), "UTF-8");

    // Read in the expected XML file
    Scanner scan = new Scanner(new File("testfiles/output/FITS-SAMPLE-26_mov_Combined.xml"));
    String expectedXmlStr = scan.useDelimiter("\\Z").next();
    scan.close();

    // Set up XMLUnit
    XMLUnit.setIgnoreWhitespace(true);//from   w w  w .j a v  a2 s  . c  o m
    XMLUnit.setNormalizeWhitespace(true);

    Diff diff = new Diff(expectedXmlStr, actualXmlStr);

    // Initialize attributes or elements to ignore for difference checking
    diff.overrideDifferenceListener(new IgnoreNamedElementsDifferenceListener("version", "toolversion",
            "dateModified", "fslastmodified", "startDate", "startTime", "timestamp", "fitsExecutionTime",
            "executionTime", "filepath", "location", "ebucore:locator"));

    DetailedDiff detailedDiff = new DetailedDiff(diff);

    // Display any Differences
    List<Difference> diffs = detailedDiff.getAllDifferences();
    if (!diff.identical()) {
        StringBuffer differenceDescription = new StringBuffer();
        differenceDescription.append(diffs.size()).append(" differences");

        System.out.println(differenceDescription.toString());
        for (Difference difference : diffs) {
            System.out.println(difference.toString());
        }

    }

    assertTrue("Differences in XML", diff.identical());

}

From source file:edu.harvard.hul.ois.fits.junit.VideoStdSchemaTestXmlUnit.java

@Test
public void testVideoXmlUnitStandardOutput_DV() throws Exception {

    // First generate the FITS output
    File input = new File("testfiles/FITS-SAMPLE-26.mov");
    Fits fits = new Fits();
    FitsOutput fitsOut = fits.examine(input);

    // Output stream for FITS to write to 
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    // Create standard output in the stream passed in
    Fits.outputStandardSchemaXml(fitsOut, out);

    // Turn output stream into a String HtmlUnit can use
    String actualXmlStr = new String(out.toByteArray(), "UTF-8");

    // Read in the expected XML file
    Scanner scan = new Scanner(new File("testfiles/output/FITS-SAMPLE-26_mov_Standard.xml"));
    String expectedXmlStr = scan.useDelimiter("\\Z").next();
    scan.close();

    // Set up XMLUnit
    XMLUnit.setIgnoreWhitespace(true);/*w  w  w .  j av a  2  s.com*/
    XMLUnit.setNormalizeWhitespace(true);

    Diff diff = new Diff(expectedXmlStr, actualXmlStr);

    // Initialize attributes or elements to ignore for difference checking
    diff.overrideDifferenceListener(new IgnoreNamedElementsDifferenceListener("version", "toolversion",
            "dateModified", "fslastmodified", "startDate", "startTime", "timestamp", "fitsExecutionTime",
            "executionTime",
            // Not in Standard Output
            //"filepath",
            //"location",
            "ebucore:locator"));

    DetailedDiff detailedDiff = new DetailedDiff(diff);

    // Display any Differences
    List<Difference> diffs = detailedDiff.getAllDifferences();
    if (!diff.identical()) {
        StringBuffer differenceDescription = new StringBuffer();
        differenceDescription.append(diffs.size()).append(" differences");

        System.out.println(differenceDescription.toString());
        for (Difference difference : diffs) {
            System.out.println(difference.toString());
        }

    }

    assertTrue("Differences in XML", diff.identical());

}

From source file:com.ibm.bluemix.samples.UploadServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("Upload Servlet");

    try {//www  .  j  av  a 2s . c o  m
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                // item is the file (and not a field), read it in and add to List
                Scanner scanner = new Scanner(new InputStreamReader(item.getInputStream(), "UTF-8"));
                List<String> lines = new ArrayList<String>();
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine().trim();
                    if (line.length() > 0) {
                        lines.add(line);
                    }
                }
                scanner.close();

                // add lines to database
                int rows = db.addPosts(lines);
                String msg = "Added " + rows + " rows.";
                request.setAttribute("msg", msg);
                break;
            }
        }

        request.setAttribute("posts", db.getResults());
    } catch (Exception e) {
        request.setAttribute("msg", e.getMessage());
        e.printStackTrace(System.err);
    }

    response.setContentType("text/html");
    response.setStatus(200);
    request.getRequestDispatcher("/home.jsp").forward(request, response);
}