List of usage examples for org.apache.commons.vfs2 FileObject getContent
FileContent getContent() throws FileSystemException;
From source file:net.dempsy.distconfig.apahcevfs.Utils.java
public static Properties read(final FileObject file) throws IOException { final Properties props = new Properties(); if (file == null) return props; boolean isopen = false; try (InputStream is = file.getContent().getInputStream()) { isopen = true;/*from w w w.j av a 2 s.c o m*/ props.load(is); } catch (final FileSystemException fse) { if (isopen) throw fse; // otherwise we assume the file didn't exist ... which is fine. } return props; }
From source file:com.yenlo.synapse.transport.vfs.VFSUtils.java
private static boolean verifyLock(byte[] lockValue, FileObject lockObject) { try {//from ww w . j ava 2 s. c o m InputStream is = lockObject.getContent().getInputStream(); byte[] val = new byte[lockValue.length]; // noinspection ResultOfMethodCallIgnored is.read(val); if (Arrays.equals(lockValue, val) && is.read() == -1) { return true; } else { log.debug("The lock has been acquired by an another party"); } } catch (FileSystemException e) { log.error("Couldn't verify the lock", e); return false; } catch (IOException e) { log.error("Couldn't verify the lock", e); return false; } return false; }
From source file:gridool.sqlet.catalog.PartitioningConf.java
private static void loadSettingsFromCsv(String uri, List<Partition> list) throws SqletException { final InputStream is; try {//from ww w . j a v a 2s .c om FileSystemManager fsManager = VFS.getManager(); FileObject fileObj = fsManager.resolveFile(uri); FileContent fileContent = fileObj.getContent(); is = fileContent.getInputStream(); } catch (FileSystemException e) { throw new SqletException(SqletErrorType.configFailed, "failed to load a file: " + uri, e); } InputStreamReader reader = new InputStreamReader(new FastBufferedInputStream(is)); HeaderAwareCsvReader csvReader = new HeaderAwareCsvReader(reader, ',', '"'); final Map<String, Integer> headerMap; try { headerMap = csvReader.parseHeader(); } catch (IOException e) { throw new SqletException(SqletErrorType.configFailed, "failed to parse a header: " + uri, e); } final int[] fieldIndexes = toFieldIndexes(headerMap); final Map<GridNode, Partition> masterSlave = new HashMap<GridNode, Partition>(128); while (csvReader.next()) { String nodeStr = csvReader.get(fieldIndexes[0]); String masterStr = csvReader.get(fieldIndexes[1]); String dbUrl = csvReader.get(fieldIndexes[2]); String user = csvReader.get(fieldIndexes[3]); String password = csvReader.get(fieldIndexes[4]); String mapOutput = csvReader.get(fieldIndexes[5]); Preconditions.checkNotNull(nodeStr, dbUrl); GridNode node = GridUtils.getNode(nodeStr); Partition p = new Partition(node, dbUrl, user, password, mapOutput); if (masterStr == null || masterStr.length() == 0) { masterSlave.put(node, p); list.add(p); } else { GridNode master = GridUtils.getNode(masterStr); Partition masterPartition = masterSlave.get(master); if (masterPartition == null) { LOG.error("Master partition is not found for slave: " + p); } else { masterPartition.addSlave(p); } } } }
From source file:ch.descabato.browser.BackupBrowser.java
public static void main2(final String[] args) throws InterruptedException, InvocationTargetException, SecurityException, IOException { if (args.length > 1) throw new IllegalArgumentException( "SYNTAX: java... " + BackupBrowser.class.getName() + " [initialPath]"); SwingUtilities.invokeAndWait(new Runnable() { @Override//ww w . j a v a2 s. c om public void run() { tryLoadSubstanceLookAndFeel(); final JFrame f = new JFrame("OtrosVfsBrowser demo"); f.addWindowListener(finishedListener); Container contentPane = f.getContentPane(); contentPane.setLayout(new BorderLayout()); DataConfiguration dc = null; final PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration(); File favoritesFile = new File("favorites.properties"); propertiesConfiguration.setFile(favoritesFile); if (favoritesFile.exists()) { try { propertiesConfiguration.load(); } catch (ConfigurationException e) { e.printStackTrace(); } } dc = new DataConfiguration(propertiesConfiguration); propertiesConfiguration.setAutoSave(true); final VfsBrowser comp = new VfsBrowser(dc, (args.length > 0) ? args[0] : null); comp.setSelectionMode(SelectionMode.FILES_ONLY); comp.setMultiSelectionEnabled(true); comp.setApproveAction(new AbstractAction(Messages.getMessage("demo.showContentButton")) { @Override public void actionPerformed(ActionEvent e) { FileObject[] selectedFiles = comp.getSelectedFiles(); System.out.println("Selected files count=" + selectedFiles.length); for (FileObject selectedFile : selectedFiles) { try { FileSize fileSize = new FileSize(selectedFile.getContent().getSize()); System.out.println(selectedFile.getName().getURI() + ": " + fileSize.toString()); Desktop.getDesktop() .open(new File(new URI(selectedFile.getURL().toExternalForm()))); // byte[] bytes = readBytes(selectedFile.getContent().getInputStream(), 150 * 1024l); // JScrollPane sp = new JScrollPane(new JTextArea(new String(bytes))); // JDialog d = new JDialog(f); // d.setTitle("Content of file: " + selectedFile.getName().getFriendlyURI()); // d.getContentPane().add(sp); // d.setSize(600, 400); // d.setVisible(true); } catch (Exception e1) { LOGGER.error("Failed to read file", e1); JOptionPane.showMessageDialog(f, (e1.getMessage() == null) ? e1.toString() : e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } } }); comp.setCancelAction(new AbstractAction(Messages.getMessage("general.cancelButtonText")) { @Override public void actionPerformed(ActionEvent e) { f.dispose(); try { propertiesConfiguration.save(); } catch (ConfigurationException e1) { e1.printStackTrace(); } System.exit(0); } }); contentPane.add(comp); f.pack(); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }); while (!finished) Thread.sleep(100); }
From source file:hadoopInstaller.io.XMLDocumentReader.java
public static Document parse(FileObject xmlDocument, FileObject xsdDocument) throws InstallerConfigurationParseError { try {/*from w w w . ja v a 2s . c o m*/ // Validate against XML Schema DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(new StreamSource(xsdDocument.getContent().getInputStream())); dbf.setValidating(false); dbf.setSchema(schema); DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(new ParseErrorHandler()); return db.parse(xmlDocument.getContent().getInputStream()); } catch (ParserConfigurationException | SAXException | IOException e) { throw new InstallerConfigurationParseError(e, "XMLDocumentReader.ParseError", xmlDocument.getName()); //$NON-NLS-1$ } }
From source file:com.googlecode.vfsjfilechooser2.utils.VFSUtils.java
/** * Returns a buffered input stream from a file * @param fileObject A file object/* www .j a va 2s . co m*/ * @return an InputStream from the file object * @throws FileSystemException An exception while getting the file */ public static InputStream getInputStream(FileObject fileObject) throws FileSystemException { return new BufferedInputStream(fileObject.getContent().getInputStream()); }
From source file:com.googlecode.vfsjfilechooser2.utils.VFSUtils.java
/** * Returns a buffered output stream from a file * @param fileObject A file object//from w w w .jav a2 s .co m * @return an OutputStream from the file object * @throws FileSystemException An exception while getting the file */ public static OutputStream getOutputStream(FileObject fileObject) throws FileSystemException { return new BufferedOutputStream(fileObject.getContent().getOutputStream()); }
From source file:it.geosolutions.geobatch.destination.common.utils.RemoteBrowserUtils.java
/** * Download a remote file to a local path * // w ww .j ava2 s. c om * @param fo * @param localPath * @return File with the content * @throws IOException */ public static File downloadFile(FileObject fo, String localPath) throws IOException { // open input stream from the remote file BufferedInputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(fo.getContent().getInputStream()); // open output stream to local file os = new BufferedOutputStream(new FileOutputStream(localPath)); int c; // do copying while ((c = is.read()) != -1) { os.write(c); } } catch (FileSystemException e) { throw new IOException("Can't open input stream", e); } finally { if (os != null) { os.close(); } if (is != null) { is.close(); } } return new File(localPath); }
From source file:cz.lbenda.dataman.db.DbStructureFactory.java
public static void loadDatabaseStructureFromXML(DatabaseStructureType databaseStructure, DbConfig dbConfig) { if (databaseStructure == null) { return;/*from w ww . j ava 2s.co m*/ } if (!StringUtils.isBlank(databaseStructure.getSrc())) { new Thread(() -> { try { FileSystemManager fsManager = VFS.getManager(); FileObject fileObject = fsManager.resolveFile((FileObject) null, databaseStructure.getSrc()); InputStream is = fileObject.getContent().getInputStream(); loadDatabaseStructureFromXML(is, dbConfig); } catch (FileSystemException e) { LOG.error("Problem with getting FS manager or read data from file", e); ExceptionMessageFrmController .showException("Problem with getting FS manager or read data from file", e); } }).start(); } else { new Thread(() -> { dbConfig.getCatalogs().clear(); Map<Object, TableDesc> tableDescFromTableType = new HashMap<>(); Map<Object, ColumnDesc> columnDescFromColumnType = new HashMap<>(); databaseStructure.getCatalog().forEach(catalogType -> { CatalogDesc catalogDesc = new CatalogDesc(catalogType.getName()); dbConfig.getCatalogs().add(catalogDesc); catalogType.getSchema().forEach(schemaType -> { SchemaDesc schemaDesc = new SchemaDesc(catalogDesc, schemaType.getName()); catalogDesc.getSchemas().add(schemaDesc); schemaType.getTable().forEach(tableType -> { TableDesc tableDesc = new TableDesc(schemaDesc, tableType.getTableType(), tableType.getName()); tableDesc.setDbConfig(dbConfig); tableDescFromTableType.put(tableType, tableDesc); schemaDesc.getTables().add(tableDesc); tableType.getColumn().forEach(columnType -> { ColumnDesc columnDesc = new ColumnDesc(tableDesc, columnType.getName(), columnType.getLabel(), dataTypeTypeToColumnType(columnType.getDataType()), columnType.getSize(), columnType.getScale(), columnType.isNullable(), columnType.isAutoincrement(), columnType.isGenerated(), columnType.getDefaultValue()); columnDescFromColumnType.put(columnType, columnDesc); columnDesc.setPosition(tableDesc.getColumns().size() + 1); columnDesc.setPK(columnType.isIsPK()); tableDesc.getColumns().add(columnDesc); }); }); }); }); databaseStructure.getCatalog() .forEach(catalogType -> catalogType.getSchema().forEach(schemaType -> schemaType.getTable() .forEach(tableType -> tableType.getForeignKey().forEach(foreignKeyType -> { ForeignKey foreignKey = new ForeignKey(foreignKeyType.getName(), tableDescFromTableType.get(foreignKeyType.getMasterTable()), columnDescFromColumnType .get(foreignKeyType.getMasterColumn().get(0).getColumn()), tableDescFromTableType.get(tableType), columnDescFromColumnType .get(foreignKeyType.getSlaveColumn().get(0).getColumn()), foreignKeyType.getUpdateRule(), foreignKeyType.getDeleteRule()); foreignKey.getMasterTable().getForeignKeys().add(foreignKey); foreignKey.getSlaveTable().getForeignKeys().add(foreignKey); })))); }).run(); } }
From source file:com.yenlo.synapse.transport.vfs.VFSUtils.java
/** * Acquires a file item lock before processing the item, guaranteing that the file is not * processed while it is being uploaded and/or the item is not processed by two listeners * * @param fsManager used to resolve the processing file * @param fo representing the processing file item * @return boolean true if the lock has been acquired or false if not *///from w w w . ja va2s.c o m public synchronized static boolean acquireLock(FileSystemManager fsManager, FileObject fo) { // generate a random lock value to ensure that there are no two parties // processing the same file Random random = new Random(); byte[] lockValue = String.valueOf(random.nextLong()).getBytes(); try { // check whether there is an existing lock for this item, if so it is assumed // to be processed by an another listener (downloading) or a sender (uploading) // lock file is derived by attaching the ".lock" second extension to the file name String fullPath = fo.getName().getURI(); int pos = fullPath.indexOf("?"); if (pos != -1) { fullPath = fullPath.substring(0, pos); } FileObject lockObject = fsManager.resolveFile(fullPath + ".lock"); if (lockObject.exists()) { log.debug("There seems to be an external lock, aborting the processing of the file " + fo.getName() + ". This could possibly be due to some other party already " + "processing this file or the file is still being uploaded"); } else { // write a lock file before starting of the processing, to ensure that the // item is not processed by any other parties lockObject.createFile(); OutputStream stream = lockObject.getContent().getOutputStream(); try { stream.write(lockValue); stream.flush(); stream.close(); } catch (IOException e) { lockObject.delete(); log.error("Couldn't create the lock file before processing the file " + fullPath, e); return false; } finally { lockObject.close(); } // check whether the lock is in place and is it me who holds the lock. This is // required because it is possible to write the lock file simultaneously by // two processing parties. It checks whether the lock file content is the same // as the written random lock value. // NOTE: this may not be optimal but is sub optimal FileObject verifyingLockObject = fsManager.resolveFile(fullPath + ".lock"); if (verifyingLockObject.exists() && verifyLock(lockValue, verifyingLockObject)) { return true; } } } catch (FileSystemException fse) { log.error("Cannot get the lock for the file : " + maskURLPassword(fo.getName().getURI()) + " before processing"); } return false; }