List of usage examples for java.util Scanner close
public void close()
From source file:jp.ikedam.jenkins.plugins.extensible_choice_parameter.DatabaseChoiceListProvider.java
/** * /* ww w. j a v a2 s . co m*/ * @return */ private List<String> performDbQuery() { Connection conn = null; ResultSet resultat = null; List<String> resultList = new ArrayList<String>(); try { String driver = getJdbcDriver(); if (driver == null || StringUtils.isEmpty(driver)) { LOGGER.log(Level.WARNING, "Invalid driver"); } Class.forName(driver); String user = getDbUsername(); if (user == null || StringUtils.isEmpty(user)) { LOGGER.log(Level.WARNING, "Invalid user"); } String password = getDbPassword(); if (password == null || StringUtils.isEmpty(password)) { LOGGER.log(Level.WARNING, "Invalid password"); } String urlBase = getJdbcUrl(); if (urlBase == null || StringUtils.isEmpty(urlBase)) { LOGGER.log(Level.WARNING, "Invalid JDBC URL"); } String colomndb = getDbColumn(); if (colomndb == null || StringUtils.isEmpty(colomndb)) { LOGGER.log(Level.WARNING, "Invalid column"); } String namedb = getDbName(); if (namedb == null || StringUtils.isEmpty(namedb)) { LOGGER.log(Level.WARNING, "Invalid DB name"); } String tabledb = getDbTable(); if (tabledb == null || StringUtils.isEmpty(tabledb)) { LOGGER.log(Level.WARNING, "table database invalid"); } conn = DriverManager.getConnection(urlBase, user, password); // By default, a SELECT * is performed String selectQuery = "select " + colomndb + " from " + namedb + "." + tabledb; // Use plain old JDBC to build and execute the query against the configured db Statement statement = conn.createStatement(); boolean result = statement.execute(selectQuery); if (result) { resultat = statement.executeQuery(selectQuery); while (resultat.next()) { resultList.add(resultat.getString(1)); } } else { LOGGER.log(Level.WARNING, "No result found with the query: " + selectQuery); } } catch (SQLException se) { LOGGER.log(Level.SEVERE, "Unable to access the database: " + dbName + "." + se); } catch (ClassNotFoundException e) { LOGGER.log(Level.SEVERE, "The driver " + jdbcDriver + " cannot be found in the classpath."); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Unable to access the database: " + dbName + "." + e); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException se) { LOGGER.log(Level.SEVERE, "Fermeture de connection impossible, SQLException : " + se); } } // If no results are returned, read values from the fallback file if configured if (resultList.isEmpty()) { Scanner scanner = null; try { scanner = new Scanner(new FileInputStream(getFallbackFilePath())); while (scanner.hasNextLine()) { String env = scanner.nextLine().trim(); if (StringUtils.isNotBlank(env)) { resultList.add(env); } } } catch (FileNotFoundException e) { LOGGER.log(Level.WARNING, "Unable to read the fallback file: " + e); } finally { if (scanner != null) { scanner.close(); } } } // Perform alphabetical sorting on results Collections.sort(resultList); return resultList; }
From source file:com.gitblit.HtpasswdUserService.java
/** * Reads the realm file and rebuilds the in-memory lookup tables. *///from ww w. j a v a 2 s . c o m protected synchronized void read() { // This is done in two steps in order to avoid calling GitBlit.getFileOrFolder(String, String) which will segfault for unit tests. String file = settings.getString(KEY_HTPASSWD_FILE, DEFAULT_HTPASSWD_FILE); if (!file.equals(htpasswdFilePath)) { // The htpasswd file setting changed. Rediscover the file. this.htpasswdFilePath = file; this.htpasswdFile = GitBlit.getFileOrFolder(file); this.htUsers.clear(); this.forceReload = true; } if (htpasswdFile.exists() && (forceReload || (htpasswdFile.lastModified() != lastModified))) { forceReload = false; lastModified = htpasswdFile.lastModified(); htUsers.clear(); Pattern entry = Pattern.compile("^([^:]+):(.+)"); Scanner scanner = null; try { scanner = new Scanner(new FileInputStream(htpasswdFile)); while (scanner.hasNextLine()) { String line = scanner.nextLine().trim(); if (!line.isEmpty() && !line.startsWith("#")) { Matcher m = entry.matcher(line); if (m.matches()) { htUsers.put(m.group(1), m.group(2)); } } } } catch (Exception e) { logger.error(MessageFormat.format("Failed to read {0}", htpasswdFile), e); } finally { if (scanner != null) scanner.close(); } } }
From source file:it.polito.tellmefirst.web.rest.clients.ClientEpub.java
private HashMap<String, String> parseEpub(File file) throws IOException, TMFVisibleException { LOG.debug("[parseEpub] - BEGIN"); ZipFile fi = new ZipFile(file); for (Enumeration e = fi.entries(); e.hasMoreElements();) { ZipEntry entry = (ZipEntry) e.nextElement(); if (entry.getName().endsWith("ncx")) { InputStream tocMaybeDirty = fi.getInputStream(entry); Scanner scanner = new Scanner(tocMaybeDirty, "UTF-8").useDelimiter("\\A"); String theString = scanner.hasNext() ? scanner.next() : ""; tocMaybeDirty.close();//from w w w.j a va 2 s.c o m scanner.close(); String res = theString.replaceAll(">[\\s]*?<", "><"); InputStream toc = new ByteArrayInputStream(res.getBytes(StandardCharsets.UTF_8)); try { DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = dBuilder.parse(toc); toc.close(); if (doc.hasChildNodes()) { findNavMap(doc.getChildNodes()); } } catch (Exception ex) { LOG.error("Unable to navigate the TOC"); } removeEmptyTOC(epub); //search anchors in links and split Set set = epub.entrySet(); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry me = (Map.Entry) i.next(); if (me.getValue().toString().contains("#")) { String[] parts = me.getValue().toString().split("#"); String anchor = parts[1]; epub.put(me.getKey().toString(), anchor); } } } if (entry.getName().endsWith("opf")) { //manage files because order is important InputStream content = fi.getInputStream(entry); Scanner scanner = new Scanner(content, "UTF-8").useDelimiter("\\A"); String contentString = scanner.hasNext() ? scanner.next() : ""; content.close(); scanner.close(); String filenameRegex = "href=\"(.*.htm(|l))\".*media-type=\"application/xhtml"; Pattern pattern = Pattern.compile(filenameRegex); Matcher matcher = pattern.matcher(contentString); Integer count = 0; while (matcher.find()) { files.put(count, matcher.group(1)); count++; } } if (entry.getName().endsWith("html") || entry.getName().endsWith("htm") || entry.getName().endsWith("xhtml")) { InputStream htmlFile = fi.getInputStream(entry); Scanner scanner = new Scanner(htmlFile, "UTF-8").useDelimiter("\\A"); String htmlString = scanner.hasNext() ? scanner.next() : ""; String regex1 = htmlString.replaceAll("^[^_]*?<body>", ""); //remove head String regex2 = regex1.replaceAll("</body>.*$", ""); //remove tail String htmlCleaned = regex2.replaceAll("<a.*?/>", ""); //anchor with one tag String[] bits = entry.getName().split("/"); String fileName = bits[bits.length - 1]; htmls.put(fileName, htmlCleaned); } } fi.close(); Integer i; for (i = 0; i < files.size(); i++) { stringBuilder.append("<p id=\"" + files.get(i) + "\"></p>"); // "anchor" also the heads of each files stringBuilder.append(htmls.get(files.get(i))); } String htmlAll = stringBuilder.toString(); /* We have all needed files, start to split For each link -> made a chunk Start from the bottom */ Metadata metadata = new Metadata(); Parser parser = new HtmlParser(); ListIterator<Map.Entry<String, String>> iter = new ArrayList<>(epub.entrySet()).listIterator(epub.size()); while (iter.hasPrevious()) { Map.Entry<String, String> me = iter.previous(); try { ContentHandler contenthandler = new BodyContentHandler(10 * htmlAll.length()); Scanner sc = new Scanner(htmlAll); sc.useDelimiter("id=\"" + me.getValue().toString() + "\">"); htmlAll = sc.next(); InputStream stream = new ByteArrayInputStream(sc.next().getBytes(StandardCharsets.UTF_8)); parser.parse(stream, contenthandler, metadata, new ParseContext()); String chapterText = contenthandler.toString().toLowerCase().replaceAll("\\d+.*", ""); String chapterTextWithoutNo = chapterText.replaceAll("\\d+.*", ""); // Remove the Project Gutenberg meta information from the text String chapterTextCleaned = chapterTextWithoutNo.split("end of the project gutenberg ebook")[0]; epub.put(me.getKey().toString(), chapterTextCleaned); } catch (Exception ex) { LOG.error("Unable to parse content for index: " + me.getKey() + ", this chapter will be deleted"); removeChapter(epub, me.getKey().toString()); } } /* I remove the Project Gutenberg license chapter from the Map, because it is useless for the classification and it generates a Lucene Exception in case of the Italian language (the license text is always in English). You can use this method in order to remove each chapter that is useless for classifying your Epub document. */ removeChapter(epub, "A Word from Project Gutenberg"); removeEmptyItems(epub); //If the Epub file has a bad structure, I try to use the basic Epub extractor of Tika. if (epub.size() == 0) { LOG.info("The Epub file has a bad structure. Try to use the Tika extractor"); epub.put("All text", autoParseAll(file)); } removeEmptyItems(epub); if (epub.size() == 0) { LOG.error("Unable to extract text from this Epub"); throw new TMFVisibleException("Unable to extract any text from this Epub."); } removeDownloadedFile(TEMPORARY_PATH); LOG.debug("[parseEpub] - END"); return epub; }
From source file:com.pinterest.arcee.autoscaling.AwsAutoScalingManager.java
private Map<String, String> transformUserDataToConfigMap(String clusterName, String userData) throws Exception { String userDataString = userData.replace(String.format(userDataTemplate, clusterName, pinfoEnvironment), "");//from www. jav a 2 s .c om Map<String, String> resultMap = new HashMap<>(); if (userDataString.length() == 0) { return resultMap; } Scanner scanner = new Scanner(userDataString); while (scanner.hasNextLine()) { String line = scanner.nextLine(); List<String> config = Arrays.asList(line.split(": ")); if (config.size() == 2) { resultMap.put(config.get(0), config.get(1)); } } scanner.close(); return resultMap; }
From source file:ca.ualberta.cs.expenseclaim.dao.ExpenseClaimDao.java
private ExpenseClaimDao(Context context) { claimList = new ArrayList<ExpenseClaim>(); File file = new File(context.getFilesDir(), FILENAME); Scanner scanner = null; try {/*w w w.j a v a2 s .co m*/ scanner = new Scanner(file); while (scanner.hasNextLine()) { JSONObject jo = new JSONObject(scanner.nextLine()); ExpenseClaim claim = new ExpenseClaim(); claim.setId(jo.getInt("id")); claim.setName(jo.getString("name")); claim.setDescription(jo.getString("description")); claim.setStartDate(new Date(jo.getLong("startDate"))); claim.setEndDate(new Date(jo.getLong("endDate"))); claim.setStatus(jo.getString("status")); if (maxId < claim.getId()) { maxId = claim.getId(); } claimList.add(claim); } } catch (Exception e) { e.printStackTrace(); } finally { if (scanner != null) { scanner.close(); } } maxId++; }
From source file:com.ibm.devops.dra.AbstractDevOpsAction.java
/** * Get the build number//ww w. j a v a 2 s. c o m * @param build * @return */ public String getBuildNumber(String jobName, Run build) { String jName = ""; Scanner s = new Scanner(jobName).useDelimiter("/"); while (s.hasNext()) { // this will loop through the string until the last string(job name) is reached. jName = s.next(); } s.close(); String buildNumber = jName + ":" + build.getNumber(); return buildNumber; }
From source file:ca.ualberta.cs.expenseclaim.dao.ExpenseItemDao.java
private ExpenseItemDao(Context context) { itemList = new ArrayList<ExpenseItem>(); File file = new File(context.getFilesDir(), FILENAME); Scanner scanner = null; try {/*from ww w . j av a 2 s.c o m*/ scanner = new Scanner(file); while (scanner.hasNextLine()) { JSONObject jo = new JSONObject(scanner.nextLine()); ExpenseItem item = new ExpenseItem(); item.setId(jo.getInt("id")); item.setClaimId(jo.getInt("claimId")); item.setCategory(jo.getString("category")); item.setDescription(jo.getString("description")); item.setDate(new Date(jo.getLong("date"))); item.setAmount(jo.getDouble("amount")); item.setUnit(jo.getString("unit")); if (maxId < item.getId()) { maxId = item.getId(); } itemList.add(item); } } catch (Exception e) { e.printStackTrace(); } finally { if (scanner != null) { scanner.close(); } } maxId++; }
From source file:io.github.binout.wordpress2html.writer.PostWriter.java
private String getFullHtml() { String content = post.getHtmlContent(); boolean pre = false; StringBuilder builder = new StringBuilder(); Scanner scanner = new Scanner(content); while (scanner.hasNextLine()) { String line = scanner.nextLine(); // String line; // process the line line = line.replaceAll("</?pre>", " "); if (line.contains("[code") || line.contains("[sourcecode")) { pre = true;/*from w ww.jav a 2s. c om*/ } if (pre) { if (line.contains("[/code") || line.contains("[/sourcecode")) { pre = false; } line = line.replaceAll("<", "<"); line = line.replaceAll(">", ">"); line = line.replaceAll("&", "&"); line = line.replaceAll("(\\[.*code .*\\])", "$1<pre>"); line = line.replaceAll("(\\[\\/.*code\\])", "</pre>"); builder.append(line).append("\n"); } else { builder.append(line).append("</p><p>"); } } scanner.close(); if (post.getTitle().startsWith("XML")) { System.out.println(builder.toString()); } return "<html><head>" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />" + "</head>" + "<body>" + builder.toString() + "</body></html>"; }
From source file:com.gatf.executor.core.AcceptanceTestContext.java
private void initSoapContextAndHttpHeaders() throws Exception { Field[] declaredFields = HttpHeaders.class.getDeclaredFields(); for (Field field : declaredFields) { if (java.lang.reflect.Modifier.isStatic(field.getModifiers()) && field.getType().equals(String.class)) { httpHeaders.put(field.get(null).toString().toLowerCase(), field.get(null).toString()); }//from ww w . j a va 2 s. c o m } File file = null; if (gatfExecutorConfig.getWsdlLocFile() != null && !gatfExecutorConfig.getWsdlLocFile().trim().isEmpty()) file = getResourceFile(gatfExecutorConfig.getWsdlLocFile()); if (file != null) { Scanner s = new Scanner(file); s.useDelimiter("\n"); List<String> list = new ArrayList<String>(); while (s.hasNext()) { list.add(s.next().replace("\r", "")); } s.close(); for (String wsdlLoc : list) { if (!wsdlLoc.trim().isEmpty()) { String[] wsdlLocParts = wsdlLoc.split(","); logger.info("Started Parsing WSDL location - " + wsdlLocParts[1]); Wsdl wsdl = Wsdl.parse(wsdlLocParts[1]); for (QName bindingName : wsdl.getBindings()) { SoapBuilder builder = wsdl.getBuilder(bindingName); for (SoapOperation operation : builder.getOperations()) { String request = builder.buildInputMessage(operation); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document soapMessage = db.parse(new ByteArrayInputStream(request.getBytes())); if (gatfExecutorConfig.isDistributedLoadTests()) { soapStrMessages.put(wsdlLocParts[0] + operation.getOperationName(), request); } soapMessages.put(wsdlLocParts[0] + operation.getOperationName(), soapMessage); if (operation.getSoapAction() != null) { soapActions.put(wsdlLocParts[0] + operation.getOperationName(), operation.getSoapAction()); } logger.info("Adding message for SOAP operation - " + operation.getOperationName()); } soapEndpoints.put(wsdlLocParts[0], builder.getServiceUrls().get(0)); logger.info("Adding SOAP Service endpoint - " + builder.getServiceUrls().get(0)); } logger.info("Done Parsing WSDL location - " + wsdlLocParts[1]); } } } }
From source file:com.valygard.aohruthless.Joystick.java
/** * Reads config file using a Scanner to search for tabs. In yaml files, the * presences of tabs instead of whitespace will cause the file to reset due * to snakeyaml errors. As a preventative measure, the scanner will read the * file for any tabs and an IllegalArgumentException will be thrown, * effectively forcing the file to remain in its current state until the * user fixes the file./*from w ww. jav a 2 s . com*/ * * @throws IllegalArgumentException * if a tab is found. */ private void scanConfig() { // declare our scanner variable Scanner scan = null; try { scan = new Scanner(file); int row = 0; String line = ""; while (scan.hasNextLine()) { line = scan.nextLine(); row++; if (line.indexOf("\t") != -1) { // Tell the user where the tab is! String error = ("Tab found in config-file on line # " + row + "!"); throw new IllegalArgumentException(error); } } /* * load the file, if tabs were found then this will never execute * because of IllegalArgumentException */ config.load(file); } catch (IOException | InvalidConfigurationException e) { e.printStackTrace(); } finally { if (scan != null) { scan.close(); } } }