List of usage examples for org.apache.commons.vfs2 FileObject getContent
FileContent getContent() throws FileSystemException;
From source file:org.eobjects.analyzer.cli.CliRunner.java
protected void runJob(AnalyzerBeansConfiguration configuration) throws Throwable { final JaxbJobReader jobReader = new JaxbJobReader(configuration); final String jobFilePath = _arguments.getJobFile(); final FileObject jobFile = VFS.getManager().resolveFile(jobFilePath); final Map<String, String> variableOverrides = _arguments.getVariableOverrides(); final InputStream inputStream = jobFile.getContent().getInputStream(); final AnalysisJobBuilder analysisJobBuilder; try {//from www. ja v a2s.c o m analysisJobBuilder = jobReader.create(inputStream, variableOverrides); } finally { FileHelper.safeClose(inputStream); } final AnalysisRunner runner = new AnalysisRunnerImpl(configuration, new CliProgressAnalysisListener()); final AnalysisResultFuture resultFuture = runner.run(analysisJobBuilder.toAnalysisJob()); resultFuture.await(); if (resultFuture.isSuccessful()) { final CliOutputType outputType = _arguments.getOutputType(); AnalysisResultWriter writer = outputType.createWriter(); writer.write(resultFuture, configuration, _writerRef, _outputStreamRef); } else { write("ERROR!"); write("------"); List<Throwable> errors = resultFuture.getErrors(); write(errors.size() + " error(s) occurred while executing the job:"); for (Throwable throwable : errors) { write("------"); StringWriter stringWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(stringWriter)); write(stringWriter.toString()); } throw errors.get(0); } }
From source file:org.eobjects.analyzer.configuration.JaxbConfigurationReader.java
public AnalyzerBeansConfiguration create(FileObject file) { InputStream inputStream = null; try {/*from ww w . j av a 2 s .c o m*/ inputStream = file.getContent().getInputStream(); return create(inputStream); } catch (FileSystemException e) { throw new IllegalArgumentException(e); } finally { FileHelper.safeClose(inputStream); } }
From source file:org.eobjects.analyzer.util.VFSUtilsTest.java
public void test2HttpAccess() throws Exception { // first check if we have a connection try {// w w w .ja v a 2 s. c o m InetAddress.getByName("eobjects.org"); } catch (UnknownHostException e) { System.err.println("Skipping test " + getClass().getSimpleName() + "." + getName() + " since we don't seem to be able to reach eobjects.org"); e.printStackTrace(); return; } FileObject file = VFSUtils.getFileSystemManager().resolveFile("http://eobjects.org"); InputStream in = file.getContent().getInputStream(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String readLine = reader.readLine(); assertNotNull(readLine); } finally { in.close(); } }
From source file:org.eobjects.datacleaner.actions.DownloadFilesActionListener.java
@Override protected FileObject[] doInBackground() throws Exception { for (int i = 0; i < _urls.length; i++) { final String url = _urls[i]; final FileObject file = _files[i]; InputStream inputStream = null; OutputStream outputStream = null; try {//from w w w .j a va 2 s .co m byte[] buffer = new byte[1024]; final HttpGet method = new HttpGet(url); if (!_cancelled) { final HttpResponse response = _httpClient.execute(method); if (response.getStatusLine().getStatusCode() != 200) { throw new InvalidHttpResponseException(url, response); } final HttpEntity responseEntity = response.getEntity(); final long expectedSize = responseEntity.getContentLength(); if (expectedSize > 0) { publish(new Task() { @Override public void execute() throws Exception { _downloadProgressWindow.setExpectedSize(file.getName().getBaseName(), expectedSize); } }); } inputStream = responseEntity.getContent(); if (!file.exists()) { file.createFile(); } outputStream = file.getContent().getOutputStream(); long bytes = 0; for (int numBytes = inputStream.read(buffer); numBytes != -1; numBytes = inputStream .read(buffer)) { if (_cancelled) { break; } outputStream.write(buffer, 0, numBytes); bytes += numBytes; final long totalBytes = bytes; publish(new Task() { @Override public void execute() throws Exception { _downloadProgressWindow.setProgress(file.getName().getBaseName(), totalBytes); } }); } if (!_cancelled) { publish(new Task() { @Override public void execute() throws Exception { _downloadProgressWindow.setFinished(file.getName().getBaseName()); } }); } } } catch (IOException e) { logger.debug("IOException occurred while downloading files", e); throw e; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { logger.warn("Could not close input stream: " + e.getMessage(), e); } } if (outputStream != null) { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { logger.warn("Could not flush & close output stream: " + e.getMessage(), e); } } } if (_cancelled) { logger.info("Deleting non-finished download-file '{}'", file); file.delete(); } } return _files; }
From source file:org.eobjects.datacleaner.actions.OpenAnalysisJobActionListener.java
public ResultWindow openAnalysisResult(final FileObject fileObject, DCModule parentModule) { final AnalysisResult analysisResult; try {/*from w w w. j a va 2 s . c o m*/ ChangeAwareObjectInputStream is = new ChangeAwareObjectInputStream( fileObject.getContent().getInputStream()); try { is.addClassLoader(ExtensionPackage.getExtensionClassLoader()); analysisResult = (AnalysisResult) is.readObject(); } finally { FileHelper.safeClose(is); } } catch (Exception e) { throw new IllegalStateException(e); } final File file = VFSUtils.toFile(fileObject); if (file != null) { _userPreferences.setAnalysisJobDirectory(file.getParentFile()); _userPreferences.addRecentJobFile(fileObject); } final Injector injector = Guice.createInjector(new DCModule(parentModule, null) { public FileObject getJobFilename() { return fileObject; }; @Override public AnalysisResult getAnalysisResult() { return analysisResult; } @Override public AnalysisJobBuilder getAnalysisJobBuilder(AnalyzerBeansConfiguration configuration) { return null; } }); ResultWindow resultWindow = injector.getInstance(ResultWindow.class); resultWindow.open(); return resultWindow; }
From source file:org.eobjects.datacleaner.actions.SaveAnalysisJobActionListener.java
@Override public void actionPerformed(ActionEvent event) { final String actionCommand = event.getActionCommand(); _window.setStatusLabelNotice();/*from w w w . j a v a 2 s . c o m*/ _window.setStatusLabelText(LABEL_TEXT_SAVING_JOB); AnalysisJob analysisJob = null; try { _window.applyPropertyValues(); analysisJob = _analysisJobBuilder.toAnalysisJob(); } catch (Exception e) { if ("No Analyzers in job".equals(e.getMessage())) { // TODO: Have a better way to diagnose this issue int result = JOptionPane.showConfirmDialog(_window.toComponent(), "You job does not have any analyzer components in it, and is thus 'incomplete'. Do you want to save it anyway?", "No analyzers in job", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (result == JOptionPane.YES_OPTION) { analysisJob = _analysisJobBuilder.toAnalysisJob(false); } else { return; } } else { String detail = _window.getStatusLabelText(); if (LABEL_TEXT_SAVING_JOB.equals(detail)) { detail = e.getMessage(); } WidgetUtils.showErrorMessage("Errors in job", "Please fix the errors that exist in the job before saving it:\n\n" + detail, e); return; } } final FileObject existingFile = _window.getJobFile(); final FileObject file; if (existingFile == null || ACTION_COMMAND_SAVE_AS.equals(actionCommand)) { // ask the user to select a file to save to ("Save as" scenario) final DCFileChooser fileChooser = new DCFileChooser(_userPreferences.getAnalysisJobDirectory()); fileChooser.setFileFilter(FileFilters.ANALYSIS_XML); final int result = fileChooser.showSaveDialog(_window.toComponent()); if (result != JFileChooser.APPROVE_OPTION) { return; } FileObject candidate = fileChooser.getSelectedFileObject(); final boolean exists; try { final String baseName = candidate.getName().getBaseName(); if (!baseName.endsWith(".xml")) { final FileObject parent = candidate.getParent(); file = parent.resolveFile(baseName + FileFilters.ANALYSIS_XML.getExtension()); } else { file = candidate; } exists = file.exists(); } catch (FileSystemException e) { throw new IllegalStateException("Failed to prepare file for saving", e); } if (exists) { int overwrite = JOptionPane.showConfirmDialog(_window.toComponent(), "Are you sure you want to overwrite the file '" + file.getName() + "'?", "Overwrite existing file?", JOptionPane.YES_NO_OPTION); if (overwrite != JOptionPane.YES_OPTION) { return; } } } else { // overwrite existing file ("Save" scenario). file = existingFile; } try { final FileObject parent = file.getParent(); final File parentFile = VFSUtils.toFile(parent); if (parentFile != null) { _userPreferences.setAnalysisJobDirectory(parentFile); } } catch (FileSystemException e) { logger.warn("Failed to determine parent of {}: {}", file, e.getMessage()); } final String author = System.getProperty("user.name"); final String jobName = null; final String jobDescription = "Created with DataCleaner " + Version.getEdition() + " " + Version.getVersion(); final String jobVersion = null; final JaxbJobWriter writer = new JaxbJobWriter(_configuration, new JaxbJobMetadataFactoryImpl(author, jobName, jobDescription, jobVersion)); OutputStream outputStream = null; try { outputStream = file.getContent().getOutputStream(); writer.write(analysisJob, outputStream); } catch (IOException e1) { throw new IllegalStateException(e1); } finally { FileHelper.safeClose(outputStream); } if (file instanceof DelegateFileObject) { // this "file" is probably a HTTP URL resource (often provided by DC // monitor) final DelegateFileObject delegateFileObject = (DelegateFileObject) file; final String scheme = file.getName().getScheme(); if ("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme)) { final String uri = delegateFileObject.getName().getURI(); final MonitorConnection monitorConnection = _userPreferences.getMonitorConnection(); if (monitorConnection.matchesURI(uri) && monitorConnection.isAuthenticationEnabled() && monitorConnection.getEncodedPassword() == null) { // password is not configured, ask for it. final MonitorConnectionDialog dialog = new MonitorConnectionDialog(_window.getWindowContext(), _userPreferences); dialog.openBlocking(); } final PublishJobToMonitorActionListener publisher = new PublishJobToMonitorActionListener( delegateFileObject, _window.getWindowContext(), _userPreferences); publisher.actionPerformed(event); } else { throw new UnsupportedOperationException("Unexpected delegate file object: " + delegateFileObject + " (delegate: " + delegateFileObject.getDelegateFile() + ")"); } } else { _userPreferences.addRecentJobFile(file); } _window.setJobFile(file); _window.setStatusLabelNotice(); _window.setStatusLabelText("Saved job to file " + file.getName().getBaseName()); }
From source file:org.eobjects.datacleaner.bootstrap.Bootstrap.java
/** * Looks up a file, either based on a user requested filename (typically a * CLI parameter, may be a URL) or by a relative filename defined in the * system-/*from w w w . j ava 2 s . c o m*/ * * @param userRequestedFilename * the user requested filename, may be null * @param localFilename * the relative filename defined by the system * @param userPreferences * @return * @throws FileSystemException */ private FileObject resolveFile(final String userRequestedFilename, final String localFilename, UserPreferences userPreferences) throws FileSystemException { final FileObject dataCleanerHome = DataCleanerHome.get(); if (userRequestedFilename == null) { return dataCleanerHome.resolveFile(localFilename); } else { String lowerCaseFilename = userRequestedFilename.toLowerCase(); if (lowerCaseFilename.startsWith("http://") || lowerCaseFilename.startsWith("https://")) { if (!GraphicsEnvironment.isHeadless()) { // download to a RAM file. final FileObject targetDirectory = VFSUtils.getFileSystemManager() .resolveFile("ram:///datacleaner/temp"); if (!targetDirectory.exists()) { targetDirectory.createFolder(); } final URI uri; try { uri = new URI(userRequestedFilename); } catch (URISyntaxException e) { throw new IllegalArgumentException("Illegal URI: " + userRequestedFilename, e); } final WindowContext windowContext = new SimpleWindowContext(); @SuppressWarnings("resource") MonitorHttpClient httpClient = new SimpleWebServiceHttpClient(); MonitorConnection monitorConnection = null; // check if URI points to DC monitor. If so, make sure // credentials are entered. if (userPreferences != null && userPreferences.getMonitorConnection() != null) { monitorConnection = userPreferences.getMonitorConnection(); if (monitorConnection.matchesURI(uri)) { if (monitorConnection.isAuthenticationEnabled()) { if (monitorConnection.getEncodedPassword() == null) { final MonitorConnectionDialog dialog = new MonitorConnectionDialog( windowContext, userPreferences); dialog.openBlocking(); } monitorConnection = userPreferences.getMonitorConnection(); httpClient = monitorConnection.getHttpClient(); } } } try { final String[] urls = new String[] { userRequestedFilename }; final String[] targetFilenames = DownloadFilesActionListener.createTargetFilenames(urls); final FileObject[] files = downloadFiles(urls, targetDirectory, targetFilenames, windowContext, httpClient, monitorConnection); assert files.length == 1; final FileObject ramFile = files[0]; if (logger.isInfoEnabled()) { final InputStream in = ramFile.getContent().getInputStream(); try { final String str = FileHelper .readInputStreamAsString(ramFile.getContent().getInputStream(), "UTF8"); logger.info("Downloaded file contents: {}\n{}", userRequestedFilename, str); } finally { FileHelper.safeClose(in); } } final String scheme = uri.getScheme(); final int defaultPort; if ("http".equals(scheme)) { defaultPort = 80; } else { defaultPort = 443; } final UrlFileName fileName = new UrlFileName(scheme, uri.getHost(), uri.getPort(), defaultPort, null, null, uri.getPath(), FileType.FILE, uri.getQuery()); AbstractFileSystem fileSystem = (AbstractFileSystem) dataCleanerHome.getFileSystem(); return new DelegateFileObject(fileName, fileSystem, ramFile); } finally { httpClient.close(); userPreferences.setMonitorConnection(monitorConnection); } } } return VFSUtils.getFileSystemManager().resolveFile(userRequestedFilename); } }
From source file:org.eobjects.datacleaner.user.DataCleanerHome.java
private static void copyIfNonExisting(FileObject candidate, FileSystemManager manager, String filename) throws FileSystemException { FileObject file = candidate.resolveFile(filename); if (file.exists()) { logger.info("File already exists in DATACLEANER_HOME: " + filename); return;/*from www. j a v a 2 s . c o m*/ } FileObject parentFile = file.getParent(); if (!parentFile.exists()) { parentFile.createFolder(); } final ResourceManager resourceManager = ResourceManager.get(); final URL url = resourceManager.getUrl("datacleaner-home/" + filename); InputStream in = null; OutputStream out = null; try { in = url.openStream(); out = file.getContent().getOutputStream(); FileHelper.copy(in, out); } catch (IOException e) { throw new IllegalArgumentException(e); } finally { FileHelper.safeClose(in, out); } }
From source file:org.eobjects.datacleaner.user.UserPreferencesImpl.java
public static UserPreferences load(final FileObject userPreferencesFile, final boolean loadDatabaseDrivers) { try {//from w w w .jav a 2 s . c om if (userPreferencesFile == null || !userPreferencesFile.exists()) { logger.info("User preferences file does not exist"); return new UserPreferencesImpl(userPreferencesFile); } } catch (FileSystemException e1) { logger.debug("Could not determine if file exists: {}", userPreferencesFile); } ChangeAwareObjectInputStream inputStream = null; try { inputStream = new ChangeAwareObjectInputStream(userPreferencesFile.getContent().getInputStream()); inputStream.addRenamedClass("org.eobjects.datacleaner.user.UserPreferences", UserPreferencesImpl.class); UserPreferencesImpl result = (UserPreferencesImpl) inputStream.readObject(); if (loadDatabaseDrivers) { List<UserDatabaseDriver> installedDatabaseDrivers = result.getDatabaseDrivers(); for (UserDatabaseDriver userDatabaseDriver : installedDatabaseDrivers) { try { userDatabaseDriver.loadDriver(); } catch (IllegalStateException e) { logger.error("Could not load database driver", e); } } } result._userPreferencesFile = userPreferencesFile; result.refreshProxySettings(); return result; } catch (InvalidClassException e) { logger.warn("User preferences file version does not match application version: {}", e.getMessage()); return new UserPreferencesImpl(userPreferencesFile); } catch (Exception e) { logger.warn("Could not read user preferences file", e); return new UserPreferencesImpl(userPreferencesFile); } finally { FileHelper.safeClose(inputStream); } }
From source file:org.esupportail.portlet.filemanager.portlet.PortletControllerDownloadEvent.java
@EventMapping(EsupFileManagerConstants.DOWNLOAD_REQUEST_QNAME_STRING) public void downloadEvent(EventRequest request, EventResponse response) { log.info("PortletControllerDownloadEvent.downloadEvent from EsupFilemanager is called"); // INIT /*from w w w . j a v a 2s . c o m*/ portletController.init(request); PortletPreferences prefs = request.getPreferences(); String[] prefsDefaultPathes = prefs.getValues(PortletController.PREF_DEFAULT_PATH, null); boolean showHiddenFiles = "true".equals(prefs.getValue(PortletController.PREF_SHOW_HIDDEN_FILES, "false")); userParameters.setShowHiddenFiles(showHiddenFiles); UploadActionType uploadOption = UploadActionType.valueOf(prefs .getValue(PortletController.PREF_UPLOAD_ACTION_EXIST_FILE, UploadActionType.OVERRIDE.toString())); userParameters.setUploadOption(uploadOption); serverAccess.initializeServices(userParameters); // DefaultPath String defaultPath = serverAccess.getFirstAvailablePath(userParameters, prefsDefaultPathes); // Event final Event event = request.getEvent(); final DownloadRequest downloadRequest = (DownloadRequest) event.getValue(); String fileUrl = downloadRequest.getUrl(); // FS boolean success = false; try { FileSystemManager fsManager = VFS.getManager(); FileSystemOptions fsOptions = new FileSystemOptions(); FileObject file = fsManager.resolveFile(fileUrl, fsOptions); FileContent fc = file.getContent(); String baseName = fc.getFile().getName().getBaseName(); InputStream inputStream = fc.getInputStream(); success = serverAccess.putFile(defaultPath, baseName, inputStream, userParameters, userParameters.getUploadOption()); } catch (FileSystemException e) { log.error("putFile failed for this downloadEvent", e); } //Build the result object final DownloadResponse downloadResponse = new DownloadResponse(); if (success) downloadResponse.setSummary("Upload OK"); else downloadResponse.setSummary("Upload Failed"); //Add the result to the results and send the event response.setEvent(EsupFileManagerConstants.DOWNLOAD_RESPONSE_QNAME, downloadResponse); }