List of usage examples for org.apache.commons.vfs2 FileObject getContent
FileContent getContent() throws FileSystemException;
From source file:org.horiam.ResourceManager.model.TestObjectToXmlToObject.java
@Test public void dTest() throws JAXBException, IOException { System.out.println("\nTest unmarshall User...\n"); JAXBContext context = JAXBContext.newInstance(User.class); Unmarshaller unmarshaller = context.createUnmarshaller(); for (User user : users) { FileObject file = xmls.get(user.getId()); InputStream is = file.getContent().getInputStream(); User compare = (User) unmarshaller.unmarshal(is); assertNotSame("Objects must have different references", user, compare); assertTrue("Objects must be equal", user.equals(compare)); is.close();/*from w ww. jav a 2 s . co m*/ } }
From source file:org.horiam.ResourceManager.model.TestObjectToXmlToObject.java
@Test public void eTest() throws JAXBException, IOException { System.out.println("\nTest unmarshall Resource...\n"); JAXBContext context = JAXBContext.newInstance(Resource.class); Unmarshaller unmarshaller = context.createUnmarshaller(); for (Resource resource : resources) { FileObject file = xmls.get(resource.getId()); InputStream is = file.getContent().getInputStream(); Resource compare = (Resource) unmarshaller.unmarshal(is); assertNotSame("Objects must have different references", resource, compare); assertTrue("Objects must be equal", resource.equals(compare)); is.close();/*from ww w . j a v a 2 s . c om*/ } }
From source file:org.horiam.ResourceManager.model.TestObjectToXmlToObject.java
@Test public void fTest() throws JAXBException, IOException { System.out.println("\nTest unmarshall Task...\n"); JAXBContext context = JAXBContext.newInstance(Task.class); Unmarshaller unmarshaller = context.createUnmarshaller(); for (Task task : tasks) { FileObject file = xmls.get(task.getId()); InputStream is = file.getContent().getInputStream(); Task compare = (Task) unmarshaller.unmarshal(is); assertNotSame("Objects must have different references", task, compare); assertTrue("Objects must be equal", task.equals(compare)); is.close();// w ww. j ava 2 s . co m } }
From source file:org.jahia.modules.external.modules.ModulesDataSource.java
/** * Allows to know the nodetype associated to a filetype. * * @param fileObject the file object that we want to know the associated nodetype * @return the associated nodetype/* w w w . j a v a 2 s .c o m*/ * @throws FileSystemException */ @Override public String getDataType(FileObject fileObject) throws FileSystemException { String relativeName = getFile("/").getName().getRelativeName(fileObject.getName()); int relativeDepth = ".".equals(relativeName) ? 0 : StringUtils.split(relativeName, "/").length; String type = null; if (fileObject.getType().equals(FileType.FOLDER)) { if (relativeDepth == ROOT_DEPTH_TOKEN) { // we are in root type = Constants.JAHIANT_MODULEVERSIONFOLDER; } else { if (relativeDepth == TARGET_DEPTH_TOKEN && StringUtils.equals("target", fileObject.getName().getBaseName())) { type = "jnt:mavenTargetFolder"; } else if (StringUtils.equals("resources", fileObject.getName().getBaseName()) && relativeDepth == SOURCES_DEPTH_TOKEN) { type = "jnt:folder"; } else if (relativeDepth == NODETYPE_FOLDER_DEPTH_TOKEN && isNodeType(fileObject.getName().getBaseName())) { type = Constants.JAHIANT_NODETYPEFOLDER; } else if (relativeDepth == TEMPLATE_TYPE_FOLDER_DEPTH_TOKEN) { FileObject parent = fileObject.getParent(); if (parent != null && Constants.JAHIANT_NODETYPEFOLDER.equals(getDataType(parent))) { type = Constants.JAHIANT_TEMPLATETYPEFOLDER; } } else if (StringUtils.split(relativeName, "/").length >= SOURCES_DEPTH_TOKEN && StringUtils .equals(StringUtils.split(relativeName, "/")[SOURCES_DEPTH_TOKEN - 1], "java")) { type = "jnt:javaPackageFolder"; } } if (type == null) { type = folderTypeMapping.get(fileObject.getName().getBaseName()); } } else { String extension = fileObject.getName().getExtension(); if (StringUtils.isNotEmpty(extension)) { type = fileTypeMapping.get(extension); if (type == null) { try { if (ScriptEngineUtils.canFactoryForExtensionProcessViews(extension, module.getBundle().getHeaders())) { type = Constants.JAHIANT_VIEWFILE; } } catch (IllegalArgumentException e) { // ignore: no ScriptEngineFactory exists for the provided extension } } } } if (type != null && StringUtils.equals(type, "jnt:propertiesFile")) { // we've detected a properties file, check if its parent is of type jnt:resourceBundleFolder // -> than this one gets the type jnt:resourceBundleFile; otherwise just jnt:file FileObject parent = fileObject.getParent(); type = parent != null && StringUtils.equals(Constants.JAHIANT_RESOURCEBUNDLE_FOLDER, getDataType(parent)) ? Constants.JAHIANT_RESOURCEBUNDLE_FILE : type; } boolean isFile = fileObject.getType() == FileType.FILE; if (isFile && relativeDepth == VIEWS_FOLDER_DEPTH_TOKEN && (fileObject.getParent() != null && StringUtils.equals(Constants.JAHIANT_TEMPLATETYPEFOLDER, getDataType(fileObject.getParent())))) { if (StringUtils.endsWith(fileObject.getName().toString(), PROPERTIES_EXTENSION)) { type = JNT_EDITABLE_FILE; } else { type = Constants.JAHIANT_VIEWFILE; } } String contentType = getContentType(fileObject.getContent()); if (type == null && isFile) { boolean isMedia = contentType != null && (contentType.contains("image") || contentType.contains("video") || contentType.contains("audio") || contentType.contains("flash")); if (!isMedia) { type = JNT_EDITABLE_FILE; } } // in case of the file name ends with .xml.generated we should have no type. if (StringUtils.endsWith(fileObject.getName().toString(), ".xml.generated")) { type = null; } return type != null ? type : super.getDataType(fileObject); }
From source file:org.jahia.modules.external.modules.ModulesDataSource.java
private void saveProperties(ExternalData data) throws RepositoryException { OutputStream outputStream = null; try {//from w ww. ja va 2s . c om ExtendedNodeType propertiesType = NodeTypeRegistry.getInstance() .getNodeType(Constants.JAHIAMIX_VIEWPROPERTIES); Map<String, ExtendedPropertyDefinition> propertyDefinitionMap = propertiesType .getDeclaredPropertyDefinitionsAsMap(); Properties properties = new SortedProperties(); for (Map.Entry<String, String[]> property : data.getProperties().entrySet()) { if (propertyDefinitionMap.containsKey(property.getKey())) { String[] v = property.getValue(); if (v != null) { String propertyValue = StringUtils.join(v, ","); if (propertyDefinitionMap.get(property.getKey()).getRequiredType() != PropertyType.BOOLEAN || !propertyValue.equals("false")) { properties.put(property.getKey(), propertyValue); } } } } FileObject file = getFile(StringUtils.substringBeforeLast(data.getPath(), ".") + PROPERTIES_EXTENSION); Properties original = new Properties(); if (file.exists()) { original.load(file.getContent().getInputStream()); for (String s : propertyDefinitionMap.keySet()) { original.remove(s); } } properties.putAll(original); if (!properties.isEmpty()) { outputStream = file.getContent().getOutputStream(); properties.store(outputStream, data.getPath()); } else { if (file.exists()) { file.delete(); } } ResourceBundle.clearCache(); } catch (FileSystemException e) { logger.error(e.getMessage(), e); throw new RepositoryException("Failed to write source code", e); } catch (IOException e) { logger.error(e.getMessage(), e); throw new RepositoryException("Failed to write source code", e); } catch (NoSuchNodeTypeException e) { logger.error("Unable to find type : " + data.getType() + " for node " + data.getPath(), e); throw e; } finally { IOUtils.closeQuietly(outputStream); } }
From source file:org.jahia.modules.external.modules.ModulesDataSource.java
private void saveCndResourceBundle(ExternalData data, String key) throws RepositoryException { String resourceBundleName = module.getResourceBundleName(); if (resourceBundleName == null) { resourceBundleName = "resources." + module.getId(); }//from w w w.j a va2 s.co m String rbBasePath = "/src/main/resources/resources/" + StringUtils.substringAfterLast(resourceBundleName, "."); Map<String, Map<String, String[]>> i18nProperties = data.getI18nProperties(); if (i18nProperties != null) { List<File> newFiles = new ArrayList<File>(); for (Map.Entry<String, Map<String, String[]>> entry : i18nProperties.entrySet()) { String lang = entry.getKey(); Map<String, String[]> properties = entry.getValue(); String[] values = properties.get(Constants.JCR_TITLE); String title = ArrayUtils.isEmpty(values) ? null : values[0]; values = properties.get(Constants.JCR_DESCRIPTION); String description = ArrayUtils.isEmpty(values) ? null : values[0]; String rbPath = rbBasePath + "_" + lang + PROPERTIES_EXTENSION; InputStream is = null; InputStreamReader isr = null; OutputStream os = null; OutputStreamWriter osw = null; try { FileObject file = getFile(rbPath); FileContent content = file.getContent(); Properties p = new SortedProperties(); if (file.exists()) { is = content.getInputStream(); isr = new InputStreamReader(is, Charsets.ISO_8859_1); p.load(isr); isr.close(); is.close(); } else if (StringUtils.isBlank(title) && StringUtils.isBlank(description)) { continue; } else { newFiles.add(new File(file.getName().getPath())); } if (!StringUtils.isEmpty(title)) { p.setProperty(key, title); } if (!StringUtils.isEmpty(description)) { p.setProperty(key + "_description", description); } os = content.getOutputStream(); osw = new OutputStreamWriter(os, Charsets.ISO_8859_1); p.store(osw, rbPath); ResourceBundle.clearCache(); } catch (FileSystemException e) { logger.error("Failed to save resourceBundle", e); throw new RepositoryException("Failed to save resourceBundle", e); } catch (IOException e) { logger.error("Failed to save resourceBundle", e); throw new RepositoryException("Failed to save resourceBundle", e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(isr); IOUtils.closeQuietly(os); IOUtils.closeQuietly(osw); } } SourceControlManagement sourceControl = module.getSourceControl(); if (sourceControl != null) { try { sourceControl.add(newFiles); } catch (IOException e) { logger.error("Failed to add files to source control", e); throw new RepositoryException("Failed to add new files to source control: " + newFiles, e); } } } }
From source file:org.jahia.modules.external.vfs.VFSDataSource.java
public ExternalData getItemByPath(String path) throws PathNotFoundException { try {/*w w w . ja v a 2s .c om*/ if (path.endsWith(JCR_CONTENT_SUFFIX)) { FileObject fileObject = getFile(StringUtils.substringBeforeLast(path, JCR_CONTENT_SUFFIX)); FileContent content = fileObject.getContent(); if (!fileObject.exists()) { throw new PathNotFoundException(path); } return getFileContent(content); } else { FileObject fileObject = getFile(path); if (!fileObject.exists()) { throw new PathNotFoundException(path); } return getFile(fileObject); } } catch (FileSystemException e) { throw new PathNotFoundException("File system exception while trying to retrieve " + path, e); } }
From source file:org.jahia.modules.external.vfs.VFSDataSource.java
@Override public List<ExternalData> getChildrenNodes(String path) throws RepositoryException { try {/*from www . j a va 2 s . c om*/ if (!path.endsWith(JCR_CONTENT_SUFFIX)) { FileObject fileObject = getFile(path); if (fileObject.getType() == FileType.FILE) { final FileContent content = fileObject.getContent(); return Collections.singletonList(getFileContent(content)); } else if (fileObject.getType() == FileType.FOLDER) { fileObject.refresh(); //in case of folder, refresh because it could be changed external FileObject[] files = fileObject.getChildren(); if (files.length > 0) { List<ExternalData> children = new LinkedList<ExternalData>(); for (FileObject object : files) { if (getSupportedNodeTypes().contains(getDataType(object))) { children.add(getFile(object)); if (object.getType() == FileType.FILE) { children.add(getFileContent(object.getContent())); } } } return children; } else { return Collections.emptyList(); } } else { if (fileObject.exists()) { logger.warn("Found non file or folder entry at path {}, maybe an alias. VFS file type: {}", fileObject, fileObject.getType()); } else { throw new PathNotFoundException(path); } } } } catch (FileSystemException e) { logger.error("Cannot get node children", e); } return Collections.emptyList(); }
From source file:org.jahia.modules.external.vfs.VFSDataSource.java
private ExternalData getFile(FileObject fileObject) throws FileSystemException { String type = getDataType(fileObject); Map<String, String[]> properties = new HashMap<String, String[]>(); List<String> addedMixins = new ArrayList<>(); final FileContent content = fileObject.getContent(); if (content != null) { long lastModifiedTime = fileObject.getContent().getLastModifiedTime(); if (lastModifiedTime > 0) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(lastModifiedTime); String[] timestamp = new String[] { ISO8601.format(calendar) }; properties.put(Constants.JCR_CREATED, timestamp); properties.put(Constants.JCR_LASTMODIFIED, timestamp); }/* w ww.j a v a 2 s . com*/ // Add jmix:image mixin in case of the file is a picture. if (content.getContentInfo() != null && content.getContentInfo().getContentType() != null && fileObject.getContent().getContentInfo().getContentType().matches("image/(.*)")) { addedMixins.add(Constants.JAHIAMIX_IMAGE); } } String path = fileObject.getName().getPath().substring(rootPath.length()); if (!path.startsWith("/")) { path = "/" + path; } ExternalData result = new ExternalData(path, path, type, properties); result.setMixin(addedMixins); return result; }
From source file:org.kalypso.commons.io.VFSUtilities.java
/** * This function copies a source file to a given destination. If no filename is given in the destination file handle, * the filename of the source is used.<br> * <br>//from ww w . j a v a 2 s . c om * It is tried to copy the file three times. If all three tries has failed, only then an IOException is thrown. <br> * All other exceptions are thrown normally. * * @param source * The source file. * @param destination * The destination file or path. * @param overwrite * If set, always overwrite existing and newer files */ public static void copyFileTo(final FileObject source, final FileObject destination, final boolean overwrite) throws IOException { if (source.equals(destination)) { KalypsoCommonsDebug.DEBUG.printf(Messages.getString("org.kalypso.commons.io.VFSUtilities.1"), //$NON-NLS-1$ source.getName(), destination.getName()); return; } /* Some variables for handling the errors. */ boolean success = false; int cnt = 0; while (success == false) { try { if (FileType.FOLDER.equals(source.getType())) throw new IllegalArgumentException(Messages.getString("org.kalypso.commons.io.VFSUtilities.2")); //$NON-NLS-1$ /* If the destination is only a directory, use the sources filename for the destination file. */ FileObject destinationFile = destination; if (FileType.FOLDER.equals(destination.getType())) destinationFile = destination.resolveFile(source.getName().getBaseName()); if (overwrite || !destinationFile.exists() || destinationFile.getContent().getSize() != source.getContent().getSize()) { /* Copy file. */ KalypsoCommonsDebug.DEBUG.printf("Copy file '%s' to '%s'...%n", source.getName(), //$NON-NLS-1$ destinationFile.getName()); FileUtil.copyContent(source, destinationFile); source.close(); } /* End copying of this file, because it was a success. */ success = true; } catch (final IOException e) { /* An error has occurred while copying the file. */ KalypsoCommonsDebug.DEBUG.printf("An error has occured with the message: %s%n", //$NON-NLS-1$ e.getLocalizedMessage()); /* If a certain amount (here 2) of retries was reached before, re-throw the error. */ if (cnt >= 2) { KalypsoCommonsDebug.DEBUG.printf("The second retry has failed, rethrowing the error...%n"); //$NON-NLS-1$ throw e; } /* Retry the copying of the file. */ cnt++; KalypsoCommonsDebug.DEBUG.printf("Retry: %s%n", String.valueOf(cnt)); //$NON-NLS-1$ success = false; /* Wait for some milliseconds. */ try { Thread.sleep(1000); } catch (final InterruptedException e1) { /* * Runs in the next loop then and if no error occurs then, it is ok. If an error occurs again, it is an * exception thrown on the last failed retry or it is slept again. */ } } } }