List of usage examples for java.util Scanner Scanner
public Scanner(ReadableByteChannel source, Charset charset)
From source file:eu.dasish.annotation.backend.dao.impl.JdbcResourceDaoTest.java
public static String getTestDataInsertSql() throws FileNotFoundException, URISyntaxException { final URL sqlUrl = JdbcResourceDaoTest.class.getResource("/test-data/InsertTestData.sql"); String sqlString = new Scanner(new File(sqlUrl.toURI()), "UTF8").useDelimiter("\\Z").next(); return sqlString; }
From source file:io.anserini.doc.GenerateRegressionDocsTest.java
@Test public void main() throws Exception { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); URL resource = GenerateRegressionDocsTest.class.getResource("/regression/all.yaml"); DataModel data = mapper.readValue(Paths.get(resource.toURI()).toFile(), DataModel.class); //System.out.println(ReflectionToStringBuilder.toString(data, ToStringStyle.MULTI_LINE_STYLE)); for (String collection : data.getCollections().keySet()) { Map<String, String> valuesMap = new HashMap<>(); valuesMap.put("index_cmds", data.generateIndexingCommand(collection)); valuesMap.put("ranking_cmds", data.generateRankingCommand(collection)); valuesMap.put("eval_cmds", data.generateEvalCommand(collection)); valuesMap.put("effectiveness", data.generateEffectiveness(collection)); StrSubstitutor sub = new StrSubstitutor(valuesMap); URL template = GenerateRegressionDocsTest.class .getResource(String.format("/docgen/templates/%s.template", collection)); Scanner scanner = new Scanner(Paths.get(template.toURI()).toFile(), "UTF-8"); String text = scanner.useDelimiter("\\A").next(); scanner.close();/*from w ww. j a va 2s . c o m*/ String resolvedString = sub.replace(text); FileUtils.writeStringToFile(new File(String.format("docs/experiments-%s.md", collection)), resolvedString, "UTF-8"); } }
From source file:biblivre3.marcutils.MarcReader.java
public static Record marcToRecord(final String marc, final MaterialType mt, final RecordStatus status) { final String splitter = detectSplitter(marc); final String escaped = HtmlEntityEscaper.replaceHtmlEntities(marc); Scanner scanner = null;//from w ww .j a v a2s .co m try { final ByteArrayInputStream bais = new ByteArrayInputStream(escaped.getBytes("UTF-8")); scanner = new Scanner(bais, "UTF-8"); } catch (UnsupportedEncodingException uee) { log.error(uee.getMessage(), uee); scanner = new Scanner(escaped); } final List<String> text = new ArrayList<String>(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.trim().length() > 3) { text.add(line); } } final String tags[] = new String[text.size()]; final String values[] = new String[text.size()]; for (int i = 0; i < text.size(); i++) { final String line = text.get(i); if (!line.toUpperCase().startsWith("LEADER")) { tags[i] = line.substring(0, 3).toUpperCase(); values[i] = line.substring(4, text.get(i).length()).trim(); } else { tags[i] = line.substring(0, 6).toUpperCase(); values[i] = line.substring(7, text.get(i).length()).trim(); } } final Leader leader = setLeader(tags, values, mt, status); final MarcFactory factory = MarcFactory.newInstance(); final Record record = factory.newRecord(leader); setControlFields(record, tags, values); setDataFields(record, tags, values, splitter); return record; }
From source file:org.energyos.espi.thirdparty.mocks.MockRestTemplate.java
@SuppressWarnings("unchecked") @Override//w ww. ja v a 2s. c o m public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) throws RestClientException { ClassPathResource sourceFile = new ClassPathResource("/fixtures/test_usage_data.xml"); String inputStreamString; try { inputStreamString = new Scanner(sourceFile.getInputStream(), "UTF-8").useDelimiter("\\A").next(); return new ResponseEntity<>((T) inputStreamString, HttpStatus.OK); } catch (IOException e) { e.printStackTrace(); throw new RestClientException("The file import broke."); } }
From source file:com.ksc.auth.profile.internal.ProfilesConfigFileLoader.java
/** * Loads the credential profiles from the given input stream. * * @param is input stream from where the profile details are read. * @throws IOException/* w w w . ja v a 2 s.c o m*/ */ private static Map<String, Profile> loadProfiles(InputStream is, ProfileCredentialsService profileCredentialsService) throws IOException { ProfilesConfigFileLoaderHelper helper = new ProfilesConfigFileLoaderHelper(); Map<String, Map<String, String>> allProfileProperties = helper .parseProfileProperties(new Scanner(is, StringUtils.UTF8.name())); // Convert the loaded property map to credential objects Map<String, Profile> profilesByName = new LinkedHashMap<String, Profile>(); for (Entry<String, Map<String, String>> entry : allProfileProperties.entrySet()) { String profileName = entry.getKey(); Map<String, String> properties = entry.getValue(); if (profileName.startsWith("profile ")) { LOG.warn("The legacy profile format requires the 'profile ' prefix before the profile name. " + "The latest code does not require such prefix, and will consider it as part of the profile name. " + "Please remove the prefix if you are seeing this warning."); } assertParameterNotEmpty(profileName, "Unable to load credentials into profile: ProfileName is empty."); if (properties.containsKey(Profile.ROLE_ARN)) { profilesByName.put(profileName, fromAssumeRole(profileName, properties, allProfileProperties, profileCredentialsService)); } else { profilesByName.put(profileName, fromStaticCredentials(profileName, properties)); } } return profilesByName; }
From source file:org.neo4j.ogm.session.response.JsonResponse.java
public JsonResponse(CloseableHttpResponse response) { try {//from w w w.java2s. c o m this.response = response; this.results = response.getEntity().getContent(); this.scanner = new Scanner(results, "UTF-8"); } catch (IOException ioException) { throw new RuntimeException(ioException); } }
From source file:com.bealearts.template.SimpleTemplate.java
/** * Load a template file//w w w. ja v a2s .c o m * @throws FileNotFoundException */ public void loadTemplate(File template) throws FileNotFoundException { this.blockMap = new HashMap<String, BlockContent>(); this.blockData = null; StringBuilder text = new StringBuilder(); String NL = System.getProperty("line.separator"); Scanner scanner = new Scanner(new FileInputStream(template), "UTF-8"); try { while (scanner.hasNextLine()) { text.append(scanner.nextLine() + NL); } } finally { scanner.close(); } this.parseTemplate(text.toString()); }
From source file:eu.project.ttc.resources.FixedExpressionResource.java
public void load(DataResource data) throws ResourceInitializationException { InputStream inputStream = null; try {// w w w . jav a 2 s. c om inputStream = data.getInputStream(); Scanner scanner = null; try { String fixedExpression, line; String[] str; scanner = new Scanner(inputStream, "UTF-8"); scanner.useDelimiter(TermSuiteConstants.LINE_BREAK); while (scanner.hasNext()) { line = scanner.next().split(TermSuiteConstants.DIESE)[0].trim(); str = line.split(TermSuiteConstants.TAB); fixedExpression = str[0]; fixedExpressionLemmas.add(fixedExpression); } } catch (Exception e) { throw new ResourceInitializationException(e); } finally { IOUtils.closeQuietly(scanner); } } catch (IOException e) { LOGGER.error("Could not load file {}", data.getUrl()); throw new ResourceInitializationException(e); } finally { IOUtils.closeQuietly(inputStream); } }
From source file:org.apache.uima.ruta.resource.CSVTable.java
private void buildTable(InputStream stream) { Scanner sc = new Scanner(stream, Charset.forName("UTF-8").name()); sc.useDelimiter("\\n"); tableData = new ArrayList<List<String>>(); while (sc.hasNext()) { String line = sc.next().trim(); line = line.replaceAll(";;", "; ;"); String[] lineElements = line.split(";"); List<String> row = Arrays.asList(lineElements); tableData.add(row);/* w ww .ja v a 2 s .c om*/ } sc.close(); }
From source file:info.mallmc.framework.util.ProfileLoader.java
private void addProperties(GameProfile profile) { String uuid = getUUID(skinOwner); try {/*from w ww . j a v a 2s .c om*/ // Get the name from SwordPVP URL url = new URL( "https://sessionserver.mojang.com/session/minecraft/profile/" + uuid + "?unsigned=false"); URLConnection uc = url.openConnection(); uc.setUseCaches(false); uc.setDefaultUseCaches(false); uc.addRequestProperty("User-Agent", "Mozilla/5.0"); uc.addRequestProperty("Cache-Control", "no-cache, no-store, must-revalidate"); uc.addRequestProperty("Pragma", "no-cache"); // Parse it String json = new Scanner(uc.getInputStream(), "UTF-8").useDelimiter("\\A").next(); JSONParser parser = new JSONParser(); Object obj = parser.parse(json); JSONArray properties = (JSONArray) ((JSONObject) obj).get("properties"); for (int i = 0; i < properties.size(); i++) { try { JSONObject property = (JSONObject) properties.get(i); String name = (String) property.get("name"); String value = (String) property.get("value"); String signature = property.containsKey("signature") ? (String) property.get("signature") : null; if (signature != null) { profile.getProperties().put(name, new Property(name, value, signature)); } else { profile.getProperties().put(name, new Property(value, name)); } } catch (Exception e) { L.ogError(LL.ERROR, Trigger.LOAD, "Failed to apply auth property", "Failed to apply auth property"); } } } catch (Exception e) { ; // Failed to load skin } }