Example usage for org.apache.commons.vfs2 FileObject createFile

List of usage examples for org.apache.commons.vfs2 FileObject createFile

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 FileObject createFile.

Prototype

void createFile() throws FileSystemException;

Source Link

Document

Creates this file, if it does not exist.

Usage

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 . java  2 s. 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;
}

From source file:com.msopentech.odatajclient.testservice.utils.FSManager.java

public FileObject putInMemory(final InputStream is, final String path) throws IOException {
    final FileObject memObject = fsManager.resolveFile(MEM_PREFIX + path);

    if (memObject.exists()) {
        memObject.delete();//from  ww w  .ja  v  a  2 s . c  om
    }

    // create in-memory file
    memObject.createFile();

    // read in-memory content
    final OutputStream os = memObject.getContent().getOutputStream();
    IOUtils.copy(is, os);
    IOUtils.closeQuietly(is);
    IOUtils.closeQuietly(os);

    return memObject;
}

From source file:com.ewcms.publication.deploy.provider.DeployOperatorBase.java

/**
 * //  ww w. j a va2 s  .c o  m
 * 
 * @param root
 *            
 * @param path
 *            
 * @return
 * @throws FileSystemException
 */
protected FileObject getTargetFileObject(FileObject root, String path) throws FileSystemException {
    FileObject out = root.resolveFile(path, NameScope.DESCENDENT);
    if (!out.exists()) {
        out.createFile();
    }
    return out;
}

From source file:com.sludev.commons.vfs.simpleshell.SimpleShell.java

/**
 * Does a 'touch' command.//from w ww . ja v a 2 s. c o  m
 * 
 * @param cmd
 * @throws java.lang.Exception
 */
public void touch(final String[] cmd) throws Exception {
    if (cmd.length < 2) {
        throw new Exception("USAGE: touch <path>");
    }
    final FileObject file = mgr.resolveFile(cwd, cmd[1]);
    if (!file.exists()) {
        file.createFile();
    }
    file.getContent().setLastModifiedTime(System.currentTimeMillis());
}

From source file:com.google.code.docbook4j.renderer.FORenderer.java

@Override
protected FileObject postProcess(final FileObject xmlSource, final FileObject xslSource,
        final FileObject xsltResult, final FileObject userConfigXml) throws Docbook4JException {

    FileObject target = null;
    try {/*from   w w w  .  j av a  2  s.  c  o m*/

        final FopFactory fopFactory = FopFactory.newInstance();

        final FOUserAgent userAgent = fopFactory.newFOUserAgent();
        userAgent.setBaseURL(xmlSource.getParent().getURL().toExternalForm());
        userAgent.setURIResolver(new VfsURIResolver());

        enhanceFOUserAgent(userAgent);

        String tmpPdf = "tmp://" + UUID.randomUUID().toString();
        target = FileObjectUtils.resolveFile(tmpPdf);
        target.createFile();

        Configuration configuration = createFOPConfig(userConfigXml);
        if (configuration != null) {
            fopFactory.setUserConfig(configuration);
            fopFactory.setBaseURL(userConfigXml.getParent().getURL().toExternalForm());
            fopFactory.setFontBaseURL(userConfigXml.getParent().getURL().toExternalForm());
        }

        Fop fop = fopFactory.newFop(getMimeType(), userAgent, target.getContent().getOutputStream());

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(); // identity
        // transformer
        transformer.setParameter("use.extensions", "1");
        transformer.setParameter("fop.extensions", "0");
        transformer.setParameter("fop1.extensions", "1");

        Source src = new StreamSource(xsltResult.getContent().getInputStream());
        Result res = new SAXResult(fop.getDefaultHandler());
        transformer.transform(src, res);
        return target;

    } catch (FileSystemException e) {
        throw new Docbook4JException("Error create filesystem manager!", e);
    } catch (TransformerException e) {
        throw new Docbook4JException("Error transforming fo to pdf!", e);
    } catch (FOPException e) {
        throw new Docbook4JException("Error transforming fo to pdf!", e);
    } catch (ConfigurationException e) {
        throw new Docbook4JException("Error loading user configuration!", e);
    } catch (SAXException e) {
        throw new Docbook4JException("Error loading user configuration!", e);
    } catch (IOException e) {
        throw new Docbook4JException("Error loading user configuration!", e);
    } finally {
        FileObjectUtils.closeFileObjectQuietly(target);
    }

}

From source file:fi.mystes.synapse.mediator.vfs.VfsFileTransferUtility.java

/**
 * Helper method to create lock file for multithreading.
 * /*w  w  w  .j  a  va2 s.  c  om*/
 * @param targetPath
 *            Target file path
 * @return URI of lock file
 * @throws FileSystemException
 *             If lock file creation fails
 */
private String createLockFile(String targetPath) throws FileSystemException {
    FileObject lockFile = resolveFile(lockFilePath(targetPath));
    log.debug("About to create lock file: " + fileObjectNameForDebug(lockFile));
    if (lockFile.exists()) {
        throw new FileSystemException("Lock file " + fileObjectNameForDebug(lockFile)
                + " already exists, refusing to create lock file");
    }
    lockFile.createFile();
    log.debug("Created lock file " + fileObjectNameForDebug(lockFile));

    String uri = lockFile.getName().getURI();

    lockFile.close();

    return uri;
}

From source file:com.yenlo.synapse.transport.vfs.VFSTransportSender.java

/**
 * Send the given message over the VFS transport
 *
 * @param msgCtx the axis2 message context
 * @throws AxisFault on error/*  w ww  .  ja v  a  2  s . c  o  m*/
 */
public void sendMessage(MessageContext msgCtx, String targetAddress, OutTransportInfo outTransportInfo)
        throws AxisFault {

    if (waitForSynchronousResponse(msgCtx)) {
        throw new AxisFault("The VFS transport doesn't support synchronous responses. "
                + "Please use the appropriate (out only) message exchange pattern.");
    }

    VFSOutTransportInfo vfsOutInfo = null;

    if (targetAddress != null) {
        vfsOutInfo = new VFSOutTransportInfo(targetAddress, globalFileLockingFlag);
    } else if (outTransportInfo != null && outTransportInfo instanceof VFSOutTransportInfo) {
        vfsOutInfo = (VFSOutTransportInfo) outTransportInfo;
    }

    if (vfsOutInfo != null) {
        FileObject replyFile = null;
        try {

            boolean wasError = true;
            int retryCount = 0;
            int maxRetryCount = vfsOutInfo.getMaxRetryCount();
            long reconnectionTimeout = vfsOutInfo.getReconnectTimeout();
            boolean append = vfsOutInfo.isAppend();

            while (wasError) {

                try {
                    retryCount++;
                    replyFile = fsManager.resolveFile(vfsOutInfo.getOutFileURI());

                    if (replyFile == null) {
                        log.error("replyFile is null");
                        throw new FileSystemException("replyFile is null");
                    }
                    wasError = false;

                } catch (FileSystemException e) {
                    log.error("cannot resolve replyFile", e);
                    if (maxRetryCount <= retryCount) {
                        handleException("cannot resolve replyFile repeatedly: " + e.getMessage(), e);
                    }
                }

                if (wasError) {
                    try {
                        Thread.sleep(reconnectionTimeout);
                    } catch (InterruptedException e2) {
                        e2.printStackTrace();
                    }
                }
            }

            if (replyFile.exists()) {

                if (replyFile.getType() == FileType.FOLDER) {
                    // we need to write a file containing the message to this folder
                    FileObject responseFile = fsManager.resolveFile(replyFile,
                            VFSUtils.getFileName(msgCtx, vfsOutInfo));

                    // if file locking is not disabled acquire the lock
                    // before uploading the file
                    if (vfsOutInfo.isFileLockingEnabled()) {
                        acquireLockForSending(responseFile, vfsOutInfo);
                        if (!responseFile.exists()) {
                            responseFile.createFile();
                        }
                        populateResponseFile(responseFile, msgCtx, append, true);
                        VFSUtils.releaseLock(fsManager, responseFile);
                    } else {
                        if (!responseFile.exists()) {
                            responseFile.createFile();
                        }
                        populateResponseFile(responseFile, msgCtx, append, false);
                    }

                } else if (replyFile.getType() == FileType.FILE) {

                    // if file locking is not disabled acquire the lock
                    // before uploading the file
                    if (vfsOutInfo.isFileLockingEnabled()) {
                        acquireLockForSending(replyFile, vfsOutInfo);
                        populateResponseFile(replyFile, msgCtx, append, true);
                        VFSUtils.releaseLock(fsManager, replyFile);
                    } else {
                        populateResponseFile(replyFile, msgCtx, append, false);
                    }

                } else {
                    handleException("Unsupported reply file type : " + replyFile.getType() + " for file : "
                            + vfsOutInfo.getOutFileURI());
                }
            } else {
                // if file locking is not disabled acquire the lock before uploading the file
                if (vfsOutInfo.isFileLockingEnabled()) {
                    acquireLockForSending(replyFile, vfsOutInfo);
                    replyFile.createFile();
                    populateResponseFile(replyFile, msgCtx, append, true);
                    VFSUtils.releaseLock(fsManager, replyFile);
                } else {
                    replyFile.createFile();
                    populateResponseFile(replyFile, msgCtx, append, false);
                }
            }
        } catch (FileSystemException e) {
            handleException("Error resolving reply file : " + vfsOutInfo.getOutFileURI(), e);
        } finally {
            if (replyFile != null) {
                try {
                    replyFile.close();
                } catch (FileSystemException ignore) {
                }
            }
        }
    } else {
        handleException("Unable to determine out transport information to send message");
    }
}

From source file:de.unioninvestment.portal.explorer.view.vfs.TableView.java

public void attach() {

    selectedDir = cb.getVfsUrl();/*from  w ww  . ja va2s  . com*/
    try {

        final VFSFileExplorerPortlet app = instance;
        final User user = (User) app.getUser();
        final FileSystemManager fFileSystemManager = fileSystemManager;
        final FileSystemOptions fOpts = opts;

        final Table table = new Table() {

            private static final long serialVersionUID = 1L;

            protected String formatPropertyValue(Object rowId, Object colId, Property property) {

                if (TABLE_PROP_FILE_NAME.equals(colId)) {
                    if (property != null && property.getValue() != null) {
                        return getDisplayPath(property.getValue().toString());
                    }
                }
                if (TABLE_PROP_FILE_DATE.equals(colId)) {
                    if (property != null && property.getValue() != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("dd.MMM yyyy HH:mm:ss");
                        return sdf.format((Date) property.getValue());
                    }
                }
                return super.formatPropertyValue(rowId, colId, property);
            }

        };
        table.setSizeFull();
        table.setMultiSelect(true);
        table.setSelectable(true);
        table.setImmediate(true);
        table.addContainerProperty(TABLE_PROP_FILE_NAME, String.class, null);
        table.addContainerProperty(TABLE_PROP_FILE_SIZE, Long.class, null);
        table.addContainerProperty(TABLE_PROP_FILE_DATE, Date.class, null);
        if (app != null) {
            app.getEventBus().addHandler(TableChangedEvent.class, new TableChangedEventHandler() {
                private static final long serialVersionUID = 1L;

                @Override
                public void onValueChanged(TableChangedEvent event) {
                    try {
                        selectedDir = event.getNewDirectory();
                        fillTableData(event.getNewDirectory(), table, fFileSystemManager, fOpts, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        table.addListener(new Table.ValueChangeListener() {
            private static final long serialVersionUID = 1L;

            public void valueChange(ValueChangeEvent event) {

                Set<?> value = (Set<?>) event.getProperty().getValue();
                if (null == value || value.size() == 0) {
                    markedRows = null;
                } else {
                    markedRows = value;
                }
            }
        });

        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);

        Button btDownload = new Button("Download File(s)");
        btDownload.addListener(new Button.ClickListener() {
            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {
                if (markedRows == null || markedRows.size() == 0)
                    getWindow().showNotification("No Files selected !",
                            Window.Notification.TYPE_WARNING_MESSAGE);
                else {
                    String[] files = new String[markedRows.size()];
                    int fileCount = 0;

                    for (Object item : markedRows) {
                        Item it = table.getItem(item);
                        files[fileCount] = it.getItemProperty(TABLE_PROP_FILE_NAME).toString();
                        fileCount++;
                    }

                    File dlFile = null;
                    if (fileCount == 1) {
                        try {
                            String fileName = files[0];
                            dlFile = getFileFromVFSObject(fFileSystemManager, fOpts, fileName);
                            logger.log(Level.INFO,
                                    "vfs2portlet: download file " + fileName + " by " + user.getScreenName());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        byte[] buf = new byte[1024];

                        try {
                            dlFile = File.createTempFile("Files", ".zip");
                            ZipOutputStream out = new ZipOutputStream(
                                    new FileOutputStream(dlFile.getAbsolutePath()));
                            for (int i = 0; i < files.length; i++) {
                                String fileName = files[i];
                                logger.log(Level.INFO, "vfs2portlet: download file " + fileName + " by "
                                        + user.getScreenName());
                                File f = getFileFromVFSObject(fFileSystemManager, fOpts, fileName);
                                FileInputStream in = new FileInputStream(f);
                                out.putNextEntry(new ZipEntry(f.getName()));
                                int len;
                                while ((len = in.read(buf)) > 0) {
                                    out.write(buf, 0, len);
                                }
                                out.closeEntry();
                                in.close();
                            }
                            out.close();
                        } catch (IOException e) {
                        }

                    }

                    if (dlFile != null) {
                        try {
                            DownloadResource downloadResource = new DownloadResource(dlFile, getApplication());
                            getApplication().getMainWindow().open(downloadResource, "_new");
                        } catch (FileNotFoundException e) {
                            getWindow().showNotification("File not found !",
                                    Window.Notification.TYPE_ERROR_MESSAGE);
                            e.printStackTrace();
                        }

                    }

                    if (dlFile != null) {
                        dlFile.delete();
                    }
                }

            }
        });

        Button btDelete = new Button("Delete File(s)");
        btDelete.addListener(new Button.ClickListener() {
            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {

                if (markedRows == null || markedRows.size() == 0)
                    getWindow().showNotification("No Files selected !",
                            Window.Notification.TYPE_WARNING_MESSAGE);
                else {
                    for (Object item : markedRows) {
                        Item it = table.getItem(item);
                        String fileToDelete = it.getItemProperty(TABLE_PROP_FILE_NAME).toString();
                        logger.log(Level.INFO, "Delete File " + fileToDelete);
                        try {
                            FileObject delFile = fFileSystemManager.resolveFile(fileToDelete, fOpts);
                            logger.log(Level.INFO, "vfs2portlet: delete file " + delFile.getName() + " by "
                                    + user.getScreenName());
                            boolean b = delFile.delete();
                            if (b)
                                logger.log(Level.INFO, "delete ok");
                            else
                                logger.log(Level.INFO, "delete failed");
                        } catch (FileSystemException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

        Button selAll = new Button("Select All", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                table.setValue(table.getItemIds());
            }
        });

        Button selNone = new Button("Select None", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                table.setValue(null);
            }
        });

        final UploadReceiver receiver = new UploadReceiver();
        upload = new Upload(null, receiver);
        upload.setImmediate(true);
        upload.setButtonCaption("File Upload");

        upload.addListener((new Upload.SucceededListener() {

            private static final long serialVersionUID = 1L;

            public void uploadSucceeded(SucceededEvent event) {

                try {
                    String fileName = receiver.getFileName();
                    ByteArrayOutputStream bos = receiver.getUploadedFile();
                    byte[] buf = bos.toByteArray();
                    ByteArrayInputStream bis = new ByteArrayInputStream(buf);
                    String fileToAdd = selectedDir + "/" + fileName;
                    logger.log(Level.INFO,
                            "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName());
                    FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts);
                    localFile.createFile();
                    OutputStream localOutputStream = localFile.getContent().getOutputStream();
                    IOUtils.copy(bis, localOutputStream);
                    localOutputStream.flush();
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    app.getMainWindow().showNotification("Upload " + fileName + " successful ! ",
                            Notification.TYPE_TRAY_NOTIFICATION);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }));

        upload.addListener(new Upload.FailedListener() {
            private static final long serialVersionUID = 1L;

            public void uploadFailed(FailedEvent event) {
                System.out.println("Upload failed ! ");
            }
        });

        multiFileUpload = new MultiFileUpload() {

            private static final long serialVersionUID = 1L;

            protected void handleFile(File file, String fileName, String mimeType, long length) {
                try {
                    byte[] buf = FileUtils.readFileToByteArray(file);
                    ByteArrayInputStream bis = new ByteArrayInputStream(buf);
                    String fileToAdd = selectedDir + "/" + fileName;
                    logger.log(Level.INFO,
                            "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName());
                    FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts);
                    localFile.createFile();
                    OutputStream localOutputStream = localFile.getContent().getOutputStream();
                    IOUtils.copy(bis, localOutputStream);
                    localOutputStream.flush();
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                } catch (FileSystemException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            protected FileBuffer createReceiver() {
                FileBuffer receiver = super.createReceiver();
                /*
                 * Make receiver not to delete files after they have been
                 * handled by #handleFile().
                 */
                receiver.setDeleteFiles(false);
                return receiver;
            }
        };
        multiFileUpload.setUploadButtonCaption("Upload File(s)");

        HorizontalLayout filterGrp = new HorizontalLayout();
        filterGrp.setSpacing(true);
        final TextField tfFilter = new TextField();
        Button btFileFilter = new Button("Filter", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                String filterVal = (String) tfFilter.getValue();
                try {
                    if (filterVal == null || filterVal.length() == 0) {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    } else {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, filterVal);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        Button btResetFileFilter = new Button("Reset", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                try {
                    tfFilter.setValue("");
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                } catch (ReadOnlyException e) {
                    e.printStackTrace();
                } catch (ConversionException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        filterGrp.addComponent(tfFilter);
        filterGrp.addComponent(btFileFilter);
        filterGrp.addComponent(btResetFileFilter);

        addComponent(filterGrp);

        addComponent(table);

        HorizontalLayout btGrp = new HorizontalLayout();

        btGrp.setSpacing(true);
        btGrp.addComponent(selAll);
        btGrp.setComponentAlignment(selAll, Alignment.MIDDLE_CENTER);
        btGrp.addComponent(selNone);
        btGrp.setComponentAlignment(selNone, Alignment.MIDDLE_CENTER);
        btGrp.addComponent(btDownload);
        btGrp.setComponentAlignment(btDownload, Alignment.MIDDLE_CENTER);

        List<Role> roles = null;
        boolean matchUserRole = false;
        try {

            if (user != null) {
                roles = user.getRoles();

            }
        } catch (SystemException e) {
            e.printStackTrace();
        }

        if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() == 0) {
            btGrp.addComponent(btDelete);
            btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER);
        } else if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() > 0) {
            matchUserRole = isUserInRole(roles, cb.getDeleteRoles());
            if (matchUserRole) {
                btGrp.addComponent(btDelete);
                btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER);
            }

        }
        if (cb.isUploadEnabled() && cb.getUploadRoles().length() == 0) {
            btGrp.addComponent(upload);
            btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER);
            btGrp.addComponent(multiFileUpload);
            btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER);
        } else if (cb.isUploadEnabled() && cb.getUploadRoles().length() > 0) {

            matchUserRole = isUserInRole(roles, cb.getUploadRoles());
            if (matchUserRole) {
                btGrp.addComponent(upload);
                btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER);
                btGrp.addComponent(multiFileUpload);
                btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER);
            }
        }
        addComponent(btGrp);

    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:de.innovationgate.wgpublisher.services.WGACoreServicesImpl.java

public void updateFSDesignResource(RemoteSession session, String path, DataSource content, long lastModified)
        throws WGAServiceException {
    if (!isAdminServiceEnabled()) {
        throw new WGAServiceException("Administrative services are disabled");
    }/*ww w .  ja v  a 2 s  . c  om*/

    if (!isAdminSession(session)) {
        throw new WGAServiceException("You need an administrative login to access this service.");
    }

    WGADesignSource source = _core.getDesignManager().getDesignSources()
            .get(WGAConfiguration.UID_DESIGNSOURCE_FILESYSTEM);
    if (source instanceof FileSystemDesignSource) {
        FileSystemDesignSource fsSource = (FileSystemDesignSource) source;
        try {
            fsSource.getDir().refresh();
            FileObject resource = fsSource.getDir().resolveFile(path);

            String basePath = fsSource.getDir().getURL().getPath();
            String resourcePath = resource.getURL().getPath();
            if (!resourcePath.startsWith(basePath)) {
                throw new WGAServiceException(
                        new IllegalArgumentException("Illegal design resource path '" + path + "'."));
            }

            resource.createFile();
            OutputStream out = resource.getContent().getOutputStream();
            InputStream in = content.getInputStream();
            WGUtils.inToOut(in, out, 1024);
            out.close();
            in.close();
            resource.getContent().setLastModifiedTime(lastModified);

            clearDesignFileCache(fsSource, fsSource.getDir().getName().getRelativeName(resource.getName()));

        } catch (FileSystemException e) {
            //            throw new WGAServiceException("Updating FSDesignResource '" + path + "' failed.", e);
        } catch (IOException e) {
            throw new WGAServiceException("Updating FSDesignResource '" + path + "' failed.", e);
        }
    }
}

From source file:de.innovationgate.wgpublisher.design.fs.FileSystemDesignManager.java

protected void doInitialDeployment(String designKey) throws WGAPIException, IOException, InstantiationException,
        IllegalAccessException, WGDesignSyncException {

    // Creat folders
    getOrCreateFolders();/*from  w w w . j  a va  2s. c o m*/

    // Deploy TMLs
    Iterator modules = getDB().getTMLModules().iterator();
    WGTMLModule mod;
    while (modules.hasNext()) {
        mod = (WGTMLModule) modules.next();
        if (isValidDesignName(mod.getName())) {
            initialDeployTMLModule(mod);
        } else {
            _log.warn("Could not use '" + mod.getDocumentKey()
                    + "' for design deployment since the name contains invalid characters");
        }
    }

    // Deploy file containers
    Iterator containers = getDB().getFileContainers().iterator();
    WGFileContainer con;
    while (containers.hasNext()) {
        con = (WGFileContainer) containers.next();
        if (isValidDesignName(con.getName())) {
            initialDeployFileContainer(con);
        } else {
            _log.warn("Could not use '" + con.getDocumentKey()
                    + "' for design deployment since the name contains invalid characters");
        }
    }

    // Deploy script modules
    Iterator scripts = getDB().getCSSJSModules().iterator();
    WGCSSJSModule script;
    while (scripts.hasNext()) {
        script = (WGCSSJSModule) scripts.next();
        if (isValidDesignName(script.getName())) {
            initialDeployScriptModule(script);
        } else {
            _log.warn("Could not use '" + script.getDocumentKey()
                    + "' for design deployment since the name contains invalid characters");
        }
    }

    // Create sync info and store it to directory
    _syncInfo = new DesignDefinition();
    _syncInfo.setDesignKey(designKey);
    if (_core.getWgaConfiguration().getDesignConfiguration().getDefaultEncoding() != null) {
        _syncInfo.setFileEncoding(_core.getWgaConfiguration().getDesignConfiguration().getDefaultEncoding());
    } else {
        // if encoding not specified set to platform encoding
        _syncInfo.setFileEncoding(System.getProperty("file.encoding"));
    }
    FileObject syncInfoFile = getSyncInfoFile();
    _log.info("Creating design definition file " + syncInfoFile.getName().getPath());
    syncInfoFile.createFile();
    storeSyncInfo(syncInfoFile);

    _log.info("Initial deploy finished");

}