List of usage examples for java.util Scanner close
public void close()
From source file:com.axelor.controller.ConnectionToPrestashop.java
@SuppressWarnings("finally") @Transactional//from w ww .j a va2 s .c o m public String syncAddress() { String message = ""; try { List<Integer> prestashopIdList = new ArrayList<Integer>(); List<Integer> erpIdList = new ArrayList<Integer>(); List<Address> erpList = Address.all().fetch(); for (Address prestahopAddress : erpList) { erpIdList.add(prestahopAddress.getPrestashopid()); } URL url = new URL("http://localhost/client-lib/crud/action.php?resource=addresses&action=getallid&Akey=" + apiKey); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); InputStream inputStream = connection.getInputStream(); Scanner scan = new Scanner(inputStream); while (scan.hasNext()) { String data = scan.nextLine(); System.out.println(data); prestashopIdList.add(Integer.parseInt(data)); } System.out.println("From Prestashop Addresses :: " + prestashopIdList.size()); System.out.println("From ERP Addresses :: " + erpIdList.size()); scan.close(); // Check new entries in the prestashop Iterator<Integer> prestaListIterator = prestashopIdList.iterator(); while (prestaListIterator.hasNext()) { Integer tempId = prestaListIterator.next(); System.out.println("Current AddressPrestashopId for operation ::" + tempId); if (erpIdList.contains(tempId)) { com.axelor.pojo.Address tempAddress = getAddress(tempId); String dateUpdate = tempAddress.getDate_upd(); LocalDateTime dt1 = LocalDateTime.parse(dateUpdate, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")); Address pAddress = Address.all().filter("prestashopid=?", tempId).fetchOne(); LocalDateTime dt2 = pAddress.getUpdatedOn(); if (dt2 != null) { int diff = Seconds.secondsBetween(dt2, dt1).getSeconds(); if (diff > 1) updateAddress(tempAddress, tempId); } else { updateAddress(tempAddress, tempId); } erpIdList.remove(tempId); } else { System.out.println("Current AddressPrestashopId for insertion operation ::" + tempId); // insert new data in ERP Database insertAddress(tempId); erpIdList.remove(tempId); } } if (erpIdList.isEmpty()) { System.out.println("Synchronization is completed."); message = "done"; } else { // delete from ERP Iterator<Integer> erpListIterator = erpIdList.iterator(); while (erpListIterator.hasNext()) { Integer tempId = erpListIterator.next(); if (tempId != 0) { Address addressDelete = Address.all().filter("prestashopid=?", tempId).fetchOne(); String fullName = addressDelete.getFullName(); // addressDelete.remove(); addressDelete.setArchived(Boolean.TRUE); System.out.println("Address deleted ::" + fullName); } } while (prestaListIterator.hasNext()) { Integer tempId = prestaListIterator.next(); System.out.println("Currently in prestashop ::" + tempId); } System.out.println("Synchronization is completed."); message = "done"; } } catch (Exception e) { message = "Wrong Authentication Key or Key has been disabled."; } finally { return message; } }
From source file:edu.utah.further.core.util.text.LineListFileScanner.java
/** * Template method that parses an entire input from a scanner. * * @param scanner//from w w w.j av a 2 s. c o m * provides input * @param lineScanner * scans each line into an entity * @return list of entities, one per line */ @Override protected List<T> parseInput(final Scanner scanner) { final List<T> entities = CollectionUtil.newList(); int lineNumber = 0; String line = null; try { while (scanner.hasNextLine()) { lineNumber++; line = scanner.nextLine(); if (isIgnoreBlankLines() && StringUtils.isBlank(line)) { if (log.isDebugEnabled()) { log.debug("Ignoring blank line " + lineNumber); } } else { if (log.isDebugEnabled()) { log.debug("Parsing line " + lineNumber + ": " + quote(line)); } final String filteredLine = filterLine(line); entities.add(getLineScanner().parse(filteredLine)); } } } catch (final Exception e) { throw new ApplicationException("Failed to parse file at line " + lineNumber + ": " + quote(line), e); } finally { // Ensure the underlying stream is always closed scanner.close(); } return entities; }
From source file:Balo.MainFrame.java
public void getDataFileToJTable() { String fileNameDefined = "src/Balo/Data_1.csv"; File file = new File(fileNameDefined); int i = 0;//from ww w .j a v a 2s.c o m dvDynamic[0] = new Dovat(); //Get value from csv file try { Scanner inputStream = new Scanner(file); inputStream.useDelimiter(","); while (inputStream.hasNext()) { dvDynamic[i + 1] = dvGreedy[i] = new Dovat(); dvDynamic[i + 1].ten = dvGreedy[i].ten = inputStream.next().trim(); dvDynamic[i + 1].soluong = dvGreedy[i].soluong = Integer.valueOf(inputStream.next().trim()); dvDynamic[i + 1].giatri = dvGreedy[i].giatri = Integer.valueOf(inputStream.next().trim()); dvDynamic[i + 1].trongluong = dvGreedy[i].trongluong = Integer.valueOf(inputStream.next().trim()); i++; } //Set number of Items numOfItem = i; //Get weight bag weightBag = Integer.parseInt(TextW.getText()); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } //Set value for JTable for (int item = 0; item < numOfItem; item++) { Object[] row = new Object[4]; row[0] = dvGreedy[item].ten; row[1] = dvGreedy[item].soluong; row[2] = dvGreedy[item].giatri; row[3] = dvGreedy[item].trongluong; model.addRow(row); } }
From source file:it.acubelab.smaph.SmaphAnnotator.java
/** * Issue the query to bing, return the json object. * //www .jav a 2 s . c om * @param query * the query. * @param retryLeft * how many retry left we have (if zero, will return an empty * object in case of failure). * @return the JSON object as returned by the Bing Api. * @throws Exception * is the call to the API failed. */ private synchronized JSONObject queryBing(String query, int retryLeft) throws Exception { boolean forceCacheOverride = retryLeft < BING_RETRY; if (forceCacheOverride) Thread.sleep(1000); String accountKeyAuth = Base64.encode((bingKey + ":" + bingKey).getBytes(), 0); URL url = new URL( "https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%2Bspell%2BRelatedSearch%27&Query=%27" + URLEncoder.encode(query, "utf8") + "%27&Options=%27EnableHighlighting%27&Market=%27en-US%27&Adult=%27Off%27&$format=Json"); JSONObject result = null; byte[] compressed = url2jsonCache.get(url.toExternalForm()); if (compressed != null) result = new JSONObject(SmaphUtils.decompress(compressed)); boolean cached = !forceCacheOverride && result != null; SmaphAnnotatorDebugger.out.printf("%s%s %s%n", forceCacheOverride ? "<forceCacheOverride>" : "", cached ? "<cached>" : "Querying", url); if (!cached) { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(0); connection.setRequestProperty("Authorization", "Basic " + accountKeyAuth); connection.setRequestProperty("Accept", "*/*"); connection.setRequestProperty("Content-Type", "multipart/form-data"); connection.setUseCaches(false); if (connection.getResponseCode() != 200) { Scanner s = new Scanner(connection.getErrorStream()).useDelimiter("\\A"); System.err.printf("Got HTTP error %d. Message is: %s%n", connection.getResponseCode(), s.next()); s.close(); throw new RuntimeException("Got response code:" + connection.getResponseCode()); } Scanner s = new Scanner(connection.getInputStream()).useDelimiter("\\A"); String resultStr = s.hasNext() ? s.next() : ""; result = new JSONObject(resultStr); url2jsonCache.put(url.toExternalForm(), SmaphUtils.compress(result.toString())); increaseFlushCounter(); } if (recacheNeeded(result) && retryLeft > 0) return queryBing(query, retryLeft - 1); return result; }
From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java
public static Double[][] subsetDoubleVectors(InputStream in, Set<Integer> columns, int numCases) throws IOException { Double[][] retVector = new Double[columns.size()][numCases]; Scanner scanner = new Scanner(in); scanner.useDelimiter("\\n"); for (int caseIndex = 0; caseIndex < numCases; caseIndex++) { if (scanner.hasNext()) { String[] line = (scanner.next()).split("\t", -1); int j = 0; for (Integer i : columns) { try { // TODO: verify that NaN and +-Inf are going to be // handled correctly here! -- L.A. // NO, "+-Inf" is not handled correctly; see the // comment further down below. retVector[j][caseIndex] = new Double(line[i]); } catch (NumberFormatException ex) { retVector[j][caseIndex] = null; // missing value }/*from w w w. j av a2 s . c om*/ j++; } } else { scanner.close(); throw new IOException("Tab file has fewer rows than the stored number of cases!"); } } int tailIndex = numCases; while (scanner.hasNext()) { String nextLine = scanner.next(); if (!"".equals(nextLine)) { scanner.close(); throw new IOException("Tab file has more nonempty rows than the stored number of cases (" + numCases + ")! current index: " + tailIndex + ", line: " + nextLine); } tailIndex++; } scanner.close(); return retVector; }
From source file:com.smi.travel.monitor.MonitorGalileo.java
@Override void buildContentList(String file) { String galiFile = this.monitorDirectory + file; Path fFilePath;/* ww w .j a v a 2 s . c o m*/ fFilePath = Paths.get(galiFile); lineData = new ArrayList<String>(); lineData.add(""); sectionData = new MultiValueMap(); Scanner scanner = null; try { scanner = new Scanner(fFilePath, ENCODING.name()); while (scanner.hasNextLine()) { String line = scanner.nextLine(); // System.out.println(line); if (line.matches(MonitorGalileo.SECTION_PATTERN)) { String key = line.substring(0, 3); // System.out.println("Key " + key + " ** Line " + line); sectionData.put(key, line); } else { lineData.add(line); } } } catch (IOException ex) { ex.printStackTrace(); } finally { if (scanner != null) { scanner.close(); } } }
From source file:com.joliciel.csvLearner.CSVLearner.java
private CSVEventListReader getReader(TrainingSetType trainingSetType, boolean splitEventsByFile) throws IOException { LOG.info("Generating event list from CSV files..."); CSVEventListReader reader = new CSVEventListReader(); reader.setResultFilePath(resultFilePath); reader.setFeatureDirPath(featureDir); reader.setTestSegment(testSegment);// w ww . j a v a 2s. c om reader.setGroupedFeatureDirPath(groupedFeatureDir); reader.setTrainingSetType(trainingSetType); reader.setIncludedOutcomes(includedOutcomes); reader.setExcludedOutcomes(excludedOutcomes); reader.setSkipUnknownEvents(skipUnknownEvents); reader.setSplitEventsByFile(splitEventsByFile); if (featureFilePath != null) { File featureFile = new File(featureFilePath); Set<String> features = new TreeSet<String>(); Scanner scanner = new Scanner(featureFile); try { while (scanner.hasNextLine()) { features.add(scanner.nextLine().trim().replace(' ', '_')); } } finally { scanner.close(); } reader.setIncludedFeatures(features); } if (testIdFilePath != null) { File testIdFile = new File(testIdFilePath); Set<String> testIds = new TreeSet<String>(); Scanner scanner = new Scanner(testIdFile); try { while (scanner.hasNextLine()) { testIds.add(scanner.nextLine().trim()); } } finally { scanner.close(); } reader.setTestIds(testIds); } reader.read(); return reader; }
From source file:io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java
private String fileToString(File file, String charset) { StringBuilder fileContents = new StringBuilder((int) file.length()); Scanner scanner;/*from w w w . j a v a 2s . c o m*/ try { scanner = new Scanner(file, charset); } catch (FileNotFoundException e) { throw new RuntimeException(e); } String lineSeparator = System.getProperty(LINE_SEPARATOR); try { while (scanner.hasNextLine()) { fileContents.append(scanner.nextLine()).append(lineSeparator); } return fileContents.toString(); } finally { scanner.close(); } }
From source file:csns.importer.parser.csula.RosterParserImpl.java
/** * This parser handles the format under Self Service -> Faculty Center -> My * Schedule on GET. A sample record is as follows: * "Doe,John M 302043188 3.00 Engr, Comp Sci, & Tech CS MS". Again, not all * fields may be present./* w w w . ja v a2 s.co m*/ */ private List<ImportedUser> parse2(String text) { List<ImportedUser> students = new ArrayList<ImportedUser>(); Stack<String> stack = new Stack<String>(); Scanner scanner = new Scanner(text); scanner.useDelimiter("\\s+|\\r\\n|\\r|\\n"); while (scanner.hasNext()) { String name = ""; do { String token = scanner.next(); if (!isName(token)) stack.push(token); else { name = token; while (!stack.isEmpty() && !isDegree(stack.peek())) name = stack.pop() + " " + name; break; } } while (scanner.hasNext()); String cin = ""; boolean cinFound = false; while (scanner.hasNext()) { cin = scanner.next(); if (isCin(cin)) { cinFound = true; break; } else name += " " + cin; } if (cinFound) { ImportedUser student = new ImportedUser(); student.setCin(cin); student.setName(name); students.add(student); } } scanner.close(); return students; }