List of usage examples for org.apache.commons.vfs FileObject getContent
public FileContent getContent() throws FileSystemException;
From source file:net.sf.jvifm.ui.ZipLister.java
private File extractToTemp(FileObject fileObject) { String basename = fileObject.getName().getBaseName(); File tempFile = null;//from w ww.j a va 2 s . c o m try { String tmpPath = System.getProperty("java.io.tmpdir"); tempFile = new File(FilenameUtils.concat(tmpPath, basename)); byte[] buf = new byte[4096]; BufferedInputStream bin = new BufferedInputStream(fileObject.getContent().getInputStream()); BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(tempFile)); while (bin.read(buf, 0, 1) != -1) { bout.write(buf, 0, 1); } bout.close(); bin.close(); // by barney } catch (Throwable e) { e.printStackTrace(); } return tempFile; }
From source file:com.learningobjects.community.abgm.logic.ControllerJob.java
private void download(String sourceUrl, File destinationFile) throws IOException { logger.log(Level.INFO, "Downloading or copying file from " + sourceUrl + " to " + destinationFile); FileObject sourceFileObject = null; OutputStream outputStream = null; try {// www. ja v a 2s . co m // special case sftp so that new hosts work out of the box. other options could go here too SftpFileSystemConfigBuilder sftpFileSystemConfigBuilder = SftpFileSystemConfigBuilder.getInstance(); FileSystemOptions fileSystemOptions = new FileSystemOptions(); sftpFileSystemConfigBuilder.setStrictHostKeyChecking(fileSystemOptions, "no"); // actually try to get the file FileSystemManager fsManager = VFS.getManager(); sourceFileObject = fsManager.resolveFile(sourceUrl, fileSystemOptions); FileContent sourceFileContent = sourceFileObject.getContent(); InputStream inputStream = sourceFileContent.getInputStream(); outputStream = new FileOutputStream(destinationFile); // do the copy - this is probably a dupe of commons io, and many others byte[] buffer = new byte[8192]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } } finally { if (outputStream != null) { outputStream.close(); } if (sourceFileObject != null) { sourceFileObject.close(); // this will close the fileContent object, too } } }
From source file:egovframework.rte.fdl.filehandling.FilehandlingServiceTest.java
/** * ? ?? ? ? ./*from w ww .ja v a2 s .c o m*/ * ? ? ? ?? ?. * @throws Exception */ @Test public void testAccessFile() throws Exception { FileSystemManager manager = VFS.getManager(); FileObject baseDir = manager.resolveFile(System.getProperty("user.dir")); FileObject file = manager.resolveFile(baseDir, "testfolder/file1.txt"); // ? file.delete(Selectors.SELECT_FILES); assertFalse(file.exists()); // ? ? file.createFile(); assertTrue(file.exists()); FileContent fileContent = file.getContent(); assertEquals(0, fileContent.getSize()); // ? String string = "test."; OutputStream os = fileContent.getOutputStream(); try { os.write(string.getBytes()); os.flush(); } catch (Exception e) { throw new Exception(e); } finally { os.close(); } assertNotSame(0, fileContent.getSize()); // ? ? StringBuffer sb = new StringBuffer(); FileObject writtenFile = manager.resolveFile(baseDir, "testfolder/file1.txt"); FileContent writtenContents = writtenFile.getContent(); InputStream is = writtenContents.getInputStream(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); for (String line = ""; (line = reader.readLine()) != null; sb.append(line)) ; } catch (Exception e) { throw new Exception(e); } finally { is.close(); } // ? ? assertEquals(sb.toString(), string); }
From source file:be.ibridge.kettle.trans.step.exceloutput.ExcelOutput.java
public boolean openNewFile() { boolean retval = false; try {//from w w w.jav a 2s.c o m WorkbookSettings ws = new WorkbookSettings(); ws.setLocale(Locale.getDefault()); if (!Const.isEmpty(meta.getEncoding())) { ws.setEncoding(meta.getEncoding()); } FileObject file = KettleVFS.getFileObject(buildFilename()); // Add this to the result file names... ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, file, getTransMeta().getName(), getStepname()); resultFile.setComment("This file was created with an Excel output step"); addResultFile(resultFile); // Create the workboook if (!meta.isTemplateEnabled()) { // Create a new Workbook data.workbook = Workbook.createWorkbook(file.getContent().getOutputStream(), ws); // Create a sheet? data.sheet = data.workbook.createSheet("Sheet1", 0); } else { // create the workbook from the template Workbook tmpWorkbook = Workbook .getWorkbook(new File(StringUtil.environmentSubstitute(meta.getTemplateFileName()))); data.workbook = Workbook.createWorkbook(file.getContent().getOutputStream(), tmpWorkbook); tmpWorkbook.close(); // use only the first sheet as template data.sheet = data.workbook.getSheet(0); // save inital number of columns data.templateColumns = data.sheet.getColumns(); } // Renamme Sheet if (!Const.isEmpty(meta.getSheetname())) { data.sheet.setName(meta.getSheetname()); } if (meta.isSheetProtected()) { // Protect Sheet by setting password data.sheet.getSettings().setProtected(true); data.sheet.getSettings().setPassword(meta.getPassword()); } // Set the initial position... data.positionX = 0; if (meta.isTemplateEnabled() && meta.isTemplateAppend()) { data.positionY = data.sheet.getRows(); } else { data.positionY = 0; } retval = true; } catch (Exception e) { logError("Error opening new file : " + e.toString()); } // System.out.println("end of newFile(), splitnr="+splitnr); data.splitnr++; return retval; }
From source file:com.thinkberg.moxo.dav.PutHandler.java
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { FileObject object = getResourceManager().getFileObject(request.getPathInfo()); try {//w w w .j a v a2 s . co m LockManager.getInstance().checkCondition(object, getIf(request)); } catch (LockException e) { if (e.getLocks() != null) { response.sendError(SC_LOCKED); } else { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); } return; } // it is forbidden to write data on a folder if (object.exists() && FileType.FOLDER.equals(object.getType())) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } FileObject parent = object.getParent(); if (!parent.exists()) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } if (!FileType.FOLDER.equals(parent.getType())) { response.sendError(HttpServletResponse.SC_CONFLICT); return; } InputStream is = request.getInputStream(); OutputStream os = object.getContent().getOutputStream(); log("PUT sends " + request.getHeader("Content-length") + " bytes"); log("PUT copied " + Util.copyStream(is, os) + " bytes"); os.flush(); object.close(); response.setStatus(HttpServletResponse.SC_CREATED); }
From source file:egovframework.rte.fdl.filehandling.EgovFileUtil.java
/** * <p>//from w w w .j ava2 s.co m * ? ??? . * </p> * @param cmd * <code>String[]</code> * @return ? ? ? * @throws FileSystemException */ public List ls(final String[] cmd) throws FileSystemException { List list = new ArrayList(); int pos = 1; final boolean recursive; if (cmd.length > pos && cmd[pos].equals("-R")) { recursive = true; pos++; } else { recursive = false; } final FileObject file; if (cmd.length > pos) { file = manager.resolveFile(basefile, cmd[pos]); } else { file = basefile; } if (file.getType() == FileType.FOLDER) { // List the contents log.info("Contents of " + file.getName()); log.info(listChildren(file, recursive, "")); // list.add(file.getName()); } else { // Stat the file log.info(file.getName()); final FileContent content = file.getContent(); log.info("Size: " + content.getSize() + " bytes."); final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); final String lastMod = dateFormat.format(new Date(content.getLastModifiedTime())); log.info("Last modified: " + lastMod); } return list; }
From source file:com.thinkberg.webdav.PutHandler.java
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { FileObject object = VFSBackend.resolveFile(request.getPathInfo()); try {/*from ww w . j a v a 2 s .c o m*/ if (!LockManager.getInstance().evaluateCondition(object, getIf(request)).result) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } } catch (LockException e) { response.sendError(SC_LOCKED); return; } catch (ParseException e) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // it is forbidden to write data on a folder if (object.exists() && FileType.FOLDER.equals(object.getType())) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } FileObject parent = object.getParent(); if (!parent.exists()) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } if (!FileType.FOLDER.equals(parent.getType())) { response.sendError(HttpServletResponse.SC_CONFLICT); return; } InputStream is = request.getInputStream(); OutputStream os = object.getContent().getOutputStream(); long bytesCopied = Util.copyStream(is, os); String contentLengthHeader = request.getHeader("Content-length"); LOG.debug(String.format("sent %d/%s bytes", bytesCopied, contentLengthHeader == null ? "unknown" : contentLengthHeader)); os.flush(); object.close(); response.setStatus(HttpServletResponse.SC_CREATED); }
From source file:mondrian.spi.impl.ApacheVfsVirtualFileHandler.java
public InputStream readVirtualFile(String url) throws FileSystemException { // Treat catalogUrl as an Apache VFS (Virtual File System) URL. // VFS handles all of the usual protocols (http:, file:) // and then some. FileSystemManager fsManager = VFS.getManager(); if (fsManager == null) { throw Util.newError("Cannot get virtual file system manager"); }//from w w w .ja v a 2 s .c o m // Workaround VFS bug. if (url.startsWith("file://localhost")) { url = url.substring("file://localhost".length()); } if (url.startsWith("file:")) { url = url.substring("file:".length()); } //work around for VFS bug not closing http sockets // (Mondrian-585) if (url.startsWith("http")) { try { return new URL(url).openStream(); } catch (IOException e) { throw Util.newError("Could not read URL: " + url); } } File userDir = new File("").getAbsoluteFile(); FileObject file = fsManager.resolveFile(userDir, url); FileContent fileContent = null; try { // Because of VFS caching, make sure we refresh to get the latest // file content. This refresh may possibly solve the following // workaround for defect MONDRIAN-508, but cannot be tested, so we // will leave the work around for now. file.refresh(); // Workaround to defect MONDRIAN-508. For HttpFileObjects, verifies // the URL of the file retrieved matches the URL passed in. A VFS // cache bug can cause it to treat URLs with different parameters // as the same file (e.g. http://blah.com?param=A, // http://blah.com?param=B) if (file instanceof HttpFileObject && !file.getName().getURI().equals(url)) { fsManager.getFilesCache().removeFile(file.getFileSystem(), file.getName()); file = fsManager.resolveFile(userDir, url); } if (!file.isReadable()) { throw Util.newError("Virtual file is not readable: " + url); } fileContent = file.getContent(); } finally { file.close(); } if (fileContent == null) { throw Util.newError("Cannot get virtual file content: " + url); } return fileContent.getInputStream(); }
From source file:com.panet.imeta.trans.steps.fixedinput.FixedInput.java
public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta = (FixedInputMeta) smi;//from ww w . j a v a 2s . c om data = (FixedInputData) sdi; if (super.init(smi, sdi)) { try { data.preferredBufferSize = Integer.parseInt(environmentSubstitute(meta.getBufferSize())); data.lineWidth = Integer.parseInt(environmentSubstitute(meta.getLineWidth())); data.filename = environmentSubstitute(meta.getFilename()); if (Const.isEmpty(data.filename)) { logError(Messages.getString("FixedInput.MissingFilename.Message")); return false; } FileObject fileObject = KettleVFS.getFileObject(data.filename); try { FileInputStream fileInputStream = KettleVFS.getFileInputStream(fileObject); data.fc = fileInputStream.getChannel(); data.bb = ByteBuffer.allocateDirect(data.preferredBufferSize); } catch (IOException e) { logError(e.toString()); return false; } // Add filename to result filenames ? if (meta.isAddResultFile()) { ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, fileObject, getTransMeta().getName(), toString()); resultFile.setComment("File was read by a Fixed input step"); addResultFile(resultFile); } logBasic("Opened file with name [" + data.filename + "]"); data.stopReading = false; if (meta.isRunningInParallel()) { data.stepNumber = getUniqueStepNrAcrossSlaves(); data.totalNumberOfSteps = getUniqueStepCountAcrossSlaves(); data.fileSize = fileObject.getContent().getSize(); } // OK, now we need to skip a number of bytes in case we're doing a parallel read. // if (meta.isRunningInParallel()) { int totalLineWidth = data.lineWidth + meta.getLineSeparatorLength(); // including line separator bytes long nrRows = data.fileSize / totalLineWidth; // 100.000 / 100 = 1000 rows long rowsToSkip = Math.round(data.stepNumber * nrRows / (double) data.totalNumberOfSteps); // 0, 333, 667 long nextRowsToSkip = Math .round((data.stepNumber + 1) * nrRows / (double) data.totalNumberOfSteps); // 333, 667, 1000 data.rowsToRead = nextRowsToSkip - rowsToSkip; long bytesToSkip = rowsToSkip * totalLineWidth; logBasic("Step #" + data.stepNumber + " is skipping " + bytesToSkip + " to position in file, then it's reading " + data.rowsToRead + " rows."); data.fc.position(bytesToSkip); } return true; } catch (IOException e) { logError("Error opening file '" + meta.getFilename() + "' : " + e.toString()); logError(Const.getStackTracker(e)); } } return false; }
From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java
public static double getFileSize(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList, Object FunctionContext) { try {/*from w ww . j ava 2s .c o m*/ if (ArgList.length == 1 && !isNull(ArgList[0]) && !isUndefined(ArgList[0])) { if (ArgList[0].equals(null)) return 0; FileObject file = null; try { // Source file file = KettleVFS.getFileObject((String) ArgList[0]); long filesize = 0; if (file.exists()) { if (file.getType().equals(FileType.FILE)) filesize = file.getContent().getSize(); else new RuntimeException("[" + (String) ArgList[0] + "] is not a file!"); } else { new RuntimeException("file [" + (String) ArgList[0] + "] can not be found!"); } return filesize; } catch (IOException e) { throw new RuntimeException("The function call getFileSize throw an error : " + e.toString()); } finally { if (file != null) try { file.close(); } catch (Exception e) { } } } else { throw new RuntimeException("The function call getFileSize is not valid."); } } catch (Exception e) { throw new RuntimeException(e.toString()); } }