List of usage examples for org.springframework.core.io Resource getInputStream
InputStream getInputStream() throws IOException;
From source file:org.localmatters.serializer.tool.ConfigWriterFromClassTest.java
/** * Convert the content of the given resource into a string * @param resource The resource/*ww w .java2s .c om*/ * @return The corresponding string * @throws IOException */ private static String resourceToString(Resource resource) throws IOException { InputStream is = resource.getInputStream(); StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); try { String line = null; String sep = ""; while ((line = reader.readLine()) != null) { sb.append(sep).append(line); sep = "\n"; } } finally { is.close(); } return sb.toString(); }
From source file:example.UserInitializer.java
private static List<User> readUsers(Resource resource) throws Exception { Scanner scanner = new Scanner(resource.getInputStream()); String line = scanner.nextLine(); scanner.close();/*from ww w . j ava 2s. com*/ FlatFileItemReader<User> reader = new FlatFileItemReader<User>(); reader.setResource(resource); DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); tokenizer.setNames(line.split(",")); tokenizer.setStrict(false); DefaultLineMapper<User> lineMapper = new DefaultLineMapper<User>(); lineMapper.setFieldSetMapper(fields -> { User user = new User(); user.setEmail(fields.readString("email")); user.setFirstname(capitalize(fields.readString("first"))); user.setLastname(capitalize(fields.readString("last"))); user.setNationality(fields.readString("nationality")); String city = Arrays.stream(fields.readString("city").split(" "))// .map(StringUtils::capitalize)// .collect(Collectors.joining(" ")); String street = Arrays.stream(fields.readString("street").split(" "))// .map(StringUtils::capitalize)// .collect(Collectors.joining(" ")); try { user.setAddress(new Address(city, street, fields.readString("zip"))); } catch (IllegalArgumentException e) { user.setAddress(new Address(city, street, fields.readString("postcode"))); } user.setPicture(new Picture(fields.readString("large"), fields.readString("medium"), fields.readString("thumbnail"))); user.setUsername(fields.readString("username")); user.setPassword(fields.readString("password")); return user; }); lineMapper.setLineTokenizer(tokenizer); reader.setLineMapper(lineMapper); reader.setRecordSeparatorPolicy(new DefaultRecordSeparatorPolicy()); reader.setLinesToSkip(1); reader.open(new ExecutionContext()); List<User> users = new ArrayList<>(); User user = null; do { user = reader.read(); if (user != null) { users.add(user); } } while (user != null); return users; }
From source file:com.opengamma.elsql.ElSqlBundle.java
private static List<String> loadResource(Resource resource) { InputStream in = null;/* ww w .jav a2 s . c o m*/ try { in = resource.getInputStream(); return IOUtils.readLines(in); } catch (IOException ex) { throw new RuntimeException(ex); } finally { IOUtils.closeQuietly(in); } }
From source file:com.jidesoft.spring.richclient.docking.LayoutManager.java
/** * Loads a the previously saved layout for the current page. If no * previously persisted layout exists for the given page the built * in default layout is used./* w w w . j a v a2 s. c om*/ * * @param manager The docking manager to use * @param pageId The page to get the layout for * @return a boolean saying if the layout requested was previously saved */ public static boolean loadPageLayoutData(DockingManager manager, String pageId, Perspective perspective) { manager.beginLoadLayoutData(); try { //if(isValidLayout(manager, pageId, perspective)){ try { String pageLayout = MessageFormat.format(PAGE_LAYOUT, new Object[] { pageId, perspective.getId() }); //manager.setLayoutDirectory("."); manager.setUsePref(false); manager.loadLayoutDataFromFile(pageLayout); logger.info("Used existing layout"); return true; } catch (Exception exc) //} // else{ { logger.info("Using default layout"); Resource r = Application.instance().getApplicationContext() .getResource("classpath:layout/default.layout"); manager.loadLayoutFrom(r.getInputStream()); return false; } } catch (Exception e) { logger.info("Using default layout"); manager.setUsePref(true); manager.loadLayoutData(); return false; } }
From source file:com.groupon.odo.proxylib.Utils.java
/** * Copies file from a resource to a local temp file * * @param sourceResource//from w w w . ja v a 2 s . c o m * @return Absolute filename of the temp file * @throws Exception */ public static File copyResourceToLocalFile(String sourceResource, String destFileName) throws Exception { try { Resource keystoreFile = new ClassPathResource(sourceResource); InputStream in = keystoreFile.getInputStream(); File outKeyStoreFile = new File(destFileName); FileOutputStream fop = new FileOutputStream(outKeyStoreFile); byte[] buf = new byte[512]; int num; while ((num = in.read(buf)) != -1) { fop.write(buf, 0, num); } fop.flush(); fop.close(); in.close(); return outKeyStoreFile; } catch (IOException ioe) { throw new Exception("Could not copy keystore file: " + ioe.getMessage()); } }
From source file:lichen.orm.LichenOrmModule.java
public static DataSource buildDataSource(@Symbol(LichenOrmSymbols.DATABASE_CFG_FILE) String dbCfgFile, RegistryShutdownHub shutdownHub) throws IOException, ProxoolException { ResourceLoader resourceLoader = new DefaultResourceLoader(); Resource resource = resourceLoader.getResource(dbCfgFile); Properties info = new Properties(); info.load(resource.getInputStream()); PropertyConfigurator.configure(info); String poolNameKey = F.flow(info.keySet()).filter(new Predicate<Object>() { public boolean accept(Object element) { return element.toString().contains("alias"); }//from w w w.jav a2 s. c o m }).first().toString(); if (poolNameKey == null) { throw new RuntimeException("?poolName"); } final String poolName = info.getProperty(poolNameKey); //new datasource ProxoolDataSource ds = new ProxoolDataSource(poolName); //register to shutdown shutdownHub.addRegistryShutdownListener(new RegistryShutdownListener() { public void registryDidShutdown() { Flow<?> flow = F.flow(ProxoolFacade.getAliases()).filter(new Predicate<String>() { public boolean accept(String element) { return element.equals(poolName); } }); if (flow.count() == 1) { try { ProxoolFacade.removeConnectionPool(poolName); } catch (ProxoolException e) { //do nothing } } } }); return ds; }
From source file:com.textocat.textokit.morph.dictionary.MorphDictionaryAPIFactory.java
private static synchronized void initialize() { if (defaultApi != null) { return;/*from ww w . j ava2s . com*/ } log.info("Searching for MorphDictionaryAPI implementations..."); Set<String> implClassNames = Sets.newHashSet(); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try { for (Resource implDeclRes : resolver .getResources("classpath*:META-INF/uima-ext/morph-dictionary-impl.txt")) { InputStream is = implDeclRes.getInputStream(); try { String implClassName = IOUtils.toString(is, "UTF-8").trim(); if (!implClassNames.add(implClassName)) { throw new IllegalStateException( String.format( "The classpath contains duplicate declaration of implementation '%s'. " + "Last one has been read from %s.", implClassName, implDeclRes.getURL())); } } finally { IOUtils.closeQuietly(is); } } } catch (IOException e) { throw new IllegalStateException(e); } if (implClassNames.isEmpty()) { throw new IllegalStateException(String.format("Can't find an implementation of MorphDictionaryAPI")); } if (implClassNames.size() > 1) { throw new IllegalStateException(String.format("More than one implementations have been found:\n%s\n" + "Adjust the app classpath or get an implementation by ID.", implClassNames)); } String implClassName = implClassNames.iterator().next(); log.info("Found MorphDictionaryAPI implementation: {}", implClassName); try { @SuppressWarnings("unchecked") Class<? extends MorphDictionaryAPI> implClass = (Class<? extends MorphDictionaryAPI>) Class .forName(implClassName); defaultApi = implClass.newInstance(); } catch (Exception e) { throw new IllegalStateException("Can't instantiate the MorphDictionaryAPI implementation", e); } }
From source file:org.craftercms.deployer.utils.ConfigurationUtils.java
public static YamlConfiguration loadYamlConfiguration(Resource resource) throws DeploymentConfigurationException { try {//from w w w . j a va 2s. c o m try (Reader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(), "UTF-8"))) { return doLoadYamlConfiguration(reader); } } catch (Exception e) { throw new DeploymentConfigurationException("Failed to load YAML configuration at " + resource, e); } }
From source file:net.sourceforge.vulcan.spring.jdbc.JdbcSchemaMigrator.java
private static String loadResource(Resource resource) throws IOException { InputStream inputStream = null; try {/*from w w w .j av a 2 s .c o m*/ inputStream = resource.getInputStream(); return IOUtils.toString(inputStream); } finally { if (inputStream != null) { inputStream.close(); } } }
From source file:org.eclipse.gemini.blueprint.test.internal.util.jar.JarUtils.java
/** * Convenience method for reading a manifest from a given resource. Will * assume the resource points to a jar.// w ww . j av a2s . c om * * @param resource * @return */ public static Manifest getManifest(Resource resource) { try { return getManifest(resource.getInputStream()); } catch (IOException ex) { // ignore } return null; }