Search in sources :

Example 1 with MessagesEvent

use of com.openmeap.event.MessagesEvent in project OpenMEAP by OpenMEAP.

the class DeploymentListingsBacking method process.

public Collection<ProcessingEvent> process(ProcessingContext context, Map<Object, Object> templateVariables, Map<Object, Object> parameterMap) {
    List<ProcessingEvent> events = new ArrayList<ProcessingEvent>();
    templateVariables.put(FormConstants.PROCESS_TARGET, PROCESS_TARGET);
    String appId = firstValue(FormConstants.APP_ID, parameterMap);
    String appVerId = firstValue("versionId", parameterMap);
    String deploymentType = firstValue("deploymentType", parameterMap);
    String processTarget = firstValue(FormConstants.PROCESS_TARGET, parameterMap);
    Application app = null;
    try {
        app = modelManager.getModelService().findByPrimaryKey(Application.class, Long.valueOf(appId));
    } catch (NumberFormatException nfe) {
        events.add(new MessagesEvent("A valid applicationId must be supplied to either view or create deployments."));
    }
    events.add(new AddSubNavAnchorEvent(new Anchor("?bean=addModifyAppPage&applicationId=" + app.getId(), "View/Modify Application", "View/Modify Application")));
    events.add(new AddSubNavAnchorEvent(new Anchor("?bean=appVersionListingsPage&applicationId=" + app.getId(), "Version Listings", "Version Listings")));
    // TODO: I'm pretty sure I should create new deployments elsewhere and forward to here from there.
    if (deploymentType != null && PROCESS_TARGET.compareTo(processTarget) == 0 && app != null) {
        ApplicationVersion version = null;
        try {
            version = modelManager.getModelService().findByPrimaryKey(ApplicationVersion.class, Long.valueOf(appVerId));
        } catch (NumberFormatException nfe) {
            events.add(new MessagesEvent("A valid versionId must be supplied to create a deployment."));
        }
        if (version != null) {
            Deployment depl = createDeployment(firstValue("userPrincipalName", parameterMap), version, deploymentType);
            try {
                modelManager.begin();
                depl = modelManager.addModify(depl, events);
                modelManager.commit(events);
                events.add(new MessagesEvent("Deployment successfully completed."));
            } catch (Exception pe) {
                modelManager.rollback();
                Throwable root = ExceptionUtils.getRootCause(pe);
                events.add(new MessagesEvent(String.format("An exception was thrown creating the deployment: %s %s", root.getMessage(), ExceptionUtils.getStackTrace(root))));
            }
        }
    }
    // making sure to order the deployments by date
    if (app != null && app.getDeployments() != null) {
        List<Deployment> deployments = modelManager.getModelService().findDeploymentsByApplication(app);
        Collections.sort(deployments, new Deployment.DateComparator());
        templateVariables.put("deployments", deployments);
        GlobalSettings settings = modelManager.getGlobalSettings();
        Map<String, String> urls = new HashMap<String, String>();
        for (Deployment depl : deployments) {
            urls.put(depl.getApplicationArchive().getHash(), depl.getApplicationArchive().getDownloadUrl(settings));
        }
        templateVariables.put("deployments", deployments);
        templateVariables.put("archiveUrls", urls);
    }
    return events;
}
Also used : ApplicationVersion(com.openmeap.model.dto.ApplicationVersion) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) AddSubNavAnchorEvent(com.openmeap.admin.web.events.AddSubNavAnchorEvent) Deployment(com.openmeap.model.dto.Deployment) GlobalSettings(com.openmeap.model.dto.GlobalSettings) InvalidPropertiesException(com.openmeap.model.InvalidPropertiesException) PersistenceException(javax.persistence.PersistenceException) Anchor(com.openmeap.web.html.Anchor) MessagesEvent(com.openmeap.event.MessagesEvent) ProcessingEvent(com.openmeap.event.ProcessingEvent) Application(com.openmeap.model.dto.Application)

Example 2 with MessagesEvent

use of com.openmeap.event.MessagesEvent in project OpenMEAP by OpenMEAP.

the class DeploymentAddModifyNotifier method notify.

@Override
public <E extends Event<Deployment>> void notify(final E event, List<ProcessingEvent> events) throws ClusterNotificationException {
    ApplicationArchive archive = (ApplicationArchive) ((Deployment) event.getPayload()).getApplicationArchive();
    File archiveFile = archive.getFile(getModelManager().getGlobalSettings().getTemporaryStoragePath());
    if (!archiveFile.exists()) {
        String msg = String.format("The archive file %s cannot be found.  This could be because you opted to fill in the version details yourself.", archiveFile.getAbsoluteFile());
        logger.warn(msg);
        events.add(new MessagesEvent(msg));
        return;
    }
    super.notify(event, events);
}
Also used : MessagesEvent(com.openmeap.event.MessagesEvent) ApplicationArchive(com.openmeap.model.dto.ApplicationArchive) File(java.io.File)

Example 3 with MessagesEvent

use of com.openmeap.event.MessagesEvent in project OpenMEAP by OpenMEAP.

the class ArchiveFileHelper method maintainFileSystemCleanliness.

/**
 * Trim the deployment history table.  Deleting old archives as we go.
 * @param app
 * @throws PersistenceException
 * @throws InvalidPropertiesException
 */
public static void maintainFileSystemCleanliness(ModelManager modelManager, FileOperationManager fileManager, ApplicationArchive archive, List<ProcessingEvent> events) {
    ModelService modelService = modelManager.getModelService();
    GlobalSettings settings = modelManager.getGlobalSettings();
    // check to see if any deployments or versions are currently using this archive
    int versions = modelService.countVersionsByHashAndHashAlg(archive.getHash(), archive.getHashAlgorithm());
    int deployments = modelService.countDeploymentsByHashAndHashAlg(archive.getHash(), archive.getHashAlgorithm());
    // either more than one archive has this file
    Boolean archiveIsInUseElsewhere = deployments > 0 || versions > 0;
    if (!archiveIsInUseElsewhere) {
        // delete the web-view
        try {
            if (fileManager.exists(archive.getHash())) {
                fileManager.deleteDir(archive.getHash());
            }
        } catch (Exception ioe) {
            logger.error("There was an exception deleting the old web-view directory", ioe);
            events.add(new MessagesEvent(String.format("Upload process will continue.  There was an exception deleting the old web-view directory: %s", ioe.getMessage())));
        }
        // delete the zip file
        String originalFile = archive.getHash() + ".zip";
        try {
            if (fileManager.exists(originalFile)) {
                fileManager.delete(originalFile);
            }
        } catch (FileOperationException foe) {
            String mesg = String.format("Failed to delete old file %s, was different so proceeding anyhow.", originalFile);
            logger.error(mesg);
            events.add(new MessagesEvent(mesg));
        }
        modelManager.delete(archive, events);
    }
}
Also used : FileOperationException(com.openmeap.file.FileOperationException) MessagesEvent(com.openmeap.event.MessagesEvent) GlobalSettings(com.openmeap.model.dto.GlobalSettings) IOException(java.io.IOException) PersistenceException(javax.persistence.PersistenceException) FileOperationException(com.openmeap.file.FileOperationException)

Example 4 with MessagesEvent

use of com.openmeap.event.MessagesEvent in project OpenMEAP by OpenMEAP.

the class AddModifyApplicationVersionBacking method fillInApplicationVersionFromParameters.

private void fillInApplicationVersionFromParameters(Application app, ApplicationVersion version, List<ProcessingEvent> events, Map<Object, Object> parameterMap) {
    version.setIdentifier(firstValue("identifier", parameterMap));
    if (version.getArchive() == null) {
        version.setArchive(new ApplicationArchive());
        version.getArchive().setApplication(app);
    }
    version.setApplication(app);
    version.setNotes(firstValue("notes", parameterMap));
    Boolean archiveUncreated = true;
    // if there was an uploadArchive, then attempt to auto-assemble the rest of parameters
    if (parameterMap.get("uploadArchive") != null) {
        if (!(parameterMap.get("uploadArchive") instanceof FileItem)) {
            events.add(new MessagesEvent("Uploaded file not processed!  Is the archive storage path set in settings?"));
        } else {
            FileItem item = (FileItem) parameterMap.get("uploadArchive");
            Long size = item.getSize();
            if (size > 0) {
                try {
                    File tempFile = ServletUtils.tempFileFromFileItem(modelManager.getGlobalSettings().getTemporaryStoragePath(), item);
                    ApplicationArchive archive = version.getArchive();
                    archive.setNewFileUploaded(tempFile.getAbsolutePath());
                    archiveUncreated = false;
                } catch (Exception ioe) {
                    logger.error("An error transpired creating an uploadArchive temp file: {}", ioe);
                    events.add(new MessagesEvent(ioe.getMessage()));
                    return;
                } finally {
                    item.delete();
                }
            } else {
                events.add(new MessagesEvent("Uploaded file not processed!  Is the archive storage path set in settings?"));
            }
        }
    }
    // else there was no zip archive uploaded
    if (archiveUncreated) {
        ApplicationArchive archive = version.getArchive();
        archive.setHashAlgorithm(firstValue("hashType", parameterMap));
        archive.setHash(firstValue("hash", parameterMap));
        ApplicationArchive arch = modelManager.getModelService().findApplicationArchiveByHashAndAlgorithm(app, archive.getHash(), archive.getHashAlgorithm());
        if (arch != null) {
            version.setArchive(arch);
            archive = arch;
        }
        archive.setUrl(firstValue("url", parameterMap));
        if (notEmpty("bytesLength", parameterMap)) {
            archive.setBytesLength(Integer.valueOf(firstValue("bytesLength", parameterMap)));
        }
        if (notEmpty("bytesLengthUncompressed", parameterMap)) {
            archive.setBytesLengthUncompressed(Integer.valueOf(firstValue("bytesLengthUncompressed", parameterMap)));
        }
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) MessagesEvent(com.openmeap.event.MessagesEvent) ApplicationArchive(com.openmeap.model.dto.ApplicationArchive) ZipFile(java.util.zip.ZipFile) File(java.io.File) InvalidPropertiesException(com.openmeap.model.InvalidPropertiesException) IOException(java.io.IOException) PersistenceException(javax.persistence.PersistenceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 5 with MessagesEvent

use of com.openmeap.event.MessagesEvent in project OpenMEAP by OpenMEAP.

the class GlobalSettingsBacking method process.

@Override
public Collection<ProcessingEvent> process(ProcessingContext context, Map<Object, Object> templateVariables, Map<Object, Object> parameterMap) {
    List<ProcessingEvent> events = new ArrayList<ProcessingEvent>();
    GlobalSettings settings = modelManager.getGlobalSettings();
    // setup the variables required for form render
    templateVariables.put(PROCESS_TARGET_PARAM, ProcessingTargets.GLOBAL_SETTINGS);
    Boolean hasPerm = modelManager.getAuthorizer().may(Action.MODIFY, settings);
    templateVariables.put("mayModify", hasPerm);
    if (hasPerm == Boolean.FALSE) {
        events.add(new MessagesEvent("The user logged in does not have permissions to change the global settings."));
    }
    if (!empty(PROCESS_TARGET_PARAM, parameterMap)) {
        if (!empty(EXT_SVC_URL_PREFIX_PARAM, parameterMap)) {
            String svcUrl = firstValue(EXT_SVC_URL_PREFIX_PARAM, parameterMap);
            settings.setExternalServiceUrlPrefix(svcUrl);
        }
        if (!empty(MAX_FILE_UPLOAD_SIZE_PARAM, parameterMap)) {
            Integer maxFileUploadSize = Integer.valueOf(firstValue(MAX_FILE_UPLOAD_SIZE_PARAM, parameterMap));
            settings.setMaxFileUploadSize(maxFileUploadSize);
        }
        // process the storage path parameter
        if (!empty(STORAGE_PATH_PARAM, parameterMap)) {
            String path = firstValue(STORAGE_PATH_PARAM, parameterMap);
            settings.setTemporaryStoragePath(path);
        }
        // process auth salt
        if (!empty(AUTH_SALT_PARAM, parameterMap)) {
            if (empty(AUTH_SALT_VERIFY_PARAM, parameterMap) || !equalsEachOther(AUTH_SALT_PARAM, AUTH_SALT_VERIFY_PARAM, parameterMap)) {
                events.add(new MessagesEvent("Authentication salt and salt verify must match"));
            } else {
                settings.setServiceManagementAuthSalt(firstValue(AUTH_SALT_PARAM, parameterMap));
            }
        }
        List<ClusterNode> toDelete = new ArrayList<ClusterNode>();
        // process the ClusterNode objects
        if (parameterMap.get(CLUSTER_NODE_URLS_PARAM) != null) {
            String[] clusterNodeUrls = (String[]) parameterMap.get(CLUSTER_NODE_URLS_PARAM);
            String[] clusterNodePaths = (String[]) parameterMap.get(CLUSTER_NODE_PATHS_PARAM);
            int end = clusterNodeUrls.length;
            // make sure there is a map in cluster nodes
            List<ClusterNode> clusterNodes = settings.getClusterNodes();
            if (clusterNodes == null) {
                clusterNodes = new Vector<ClusterNode>();
                settings.setClusterNodes(clusterNodes);
            }
            // iterate over each node configuration, updating the clusterNodes as per input
            boolean warn = false;
            for (int i = 0; i < end; i++) {
                String thisNodeUrl = clusterNodeUrls[i].trim();
                String thisNodePath = clusterNodePaths[i].trim();
                if (thisNodeUrl.length() == 0 && warn == false) {
                    warn = true;
                    events.add(new MessagesEvent("A cluster node must be specified.  The service url must be internally accessible by the administrative service, and should point to the services context.  The rest of settings changes will be applied."));
                    continue;
                }
                // remove any nodes that no longer appear
                List<String> urls = Arrays.asList(clusterNodeUrls);
                List<String> urlsToRemove = new ArrayList<String>();
                for (ClusterNode node : clusterNodes) {
                    if (!urls.contains(node.getServiceWebUrlPrefix())) {
                        urlsToRemove.add(node.getServiceWebUrlPrefix());
                    }
                }
                for (String url : urlsToRemove) {
                    ClusterNode node = settings.getClusterNode(url);
                    clusterNodes.remove(node);
                    modelManager.delete(node, events);
                }
                ClusterNode node = null;
                if ((node = settings.getClusterNode(thisNodeUrl)) != null) {
                    node.setFileSystemStoragePathPrefix(thisNodePath);
                } else {
                    ClusterNode thisNode = new ClusterNode();
                    thisNode.setServiceWebUrlPrefix(thisNodeUrl);
                    thisNode.setFileSystemStoragePathPrefix(thisNodePath);
                    settings.addClusterNode(thisNode);
                }
            }
            // remove any nodes that no longer appear
            List<String> urls = Arrays.asList(clusterNodeUrls);
            for (ClusterNode node : settings.getClusterNodes()) {
                if (!urls.contains(node.getServiceWebUrlPrefix())) {
                    toDelete.add(node);
                }
            }
        }
        try {
            modelManager.begin();
            if (toDelete != null) {
                for (ClusterNode node : toDelete) {
                    settings.removeClusterNode(node);
                    modelManager.delete(node, events);
                }
            }
            modelManager.addModify(settings, events);
            modelManager.commit(events);
            modelManager.refresh(settings, events);
            events.add(new MessagesEvent("The settings were successfully modified."));
        } catch (InvalidPropertiesException e) {
            modelManager.rollback();
            logger.info("Invalid properties submitted for an application", e);
            events.add(new MessagesEvent(e.getMessage()));
        } catch (PersistenceException e) {
            modelManager.rollback();
            logger.error("An exception occurred commiting the transaction", e);
            events.add(new MessagesEvent(e.getMessage()));
        }
        try {
            healthChecker.refreshSettings();
            List<Exception> es = healthChecker.checkNowAndWait();
            if (es.size() > 0) {
                for (Exception e : es) {
                    events.add(new MessagesEvent(e.getMessage()));
                }
            }
        } catch (InterruptedException e) {
            logger.error("Exception occurred waiting on the health check thread after updating global settings", e);
            events.add(new MessagesEvent(e.getMessage()));
        }
    }
    if (settings.getExternalServiceUrlPrefix() != null) {
        templateVariables.put(EXT_SVC_URL_PREFIX_PARAM, settings.getExternalServiceUrlPrefix());
    }
    if (settings.getTemporaryStoragePath() != null) {
        templateVariables.put(STORAGE_PATH_PARAM, settings.getTemporaryStoragePath());
    }
    if (settings.getServiceManagementAuthSalt() != null) {
        templateVariables.put(AUTH_SALT_PARAM, settings.getServiceManagementAuthSalt());
        templateVariables.put(AUTH_SALT_VERIFY_PARAM, settings.getServiceManagementAuthSalt());
    }
    if (settings.getClusterNodes() != null && settings.getClusterNodes().size() > 0) {
        if (healthChecker != null) {
            for (ClusterNode node : settings.getClusterNodes()) {
                ClusterNode checkerNode = healthChecker.getSettings().getClusterNode(node.getServiceWebUrlPrefix());
                if (checkerNode != null) {
                    synchronized (checkerNode) {
                        node.setLastStatus(checkerNode.getLastStatus());
                        Date date = null;
                        node.setLastStatusCheck((Date) ((date = checkerNode.getLastStatusCheck()) != null ? date.clone() : null));
                        node.setLastStatusMessage(checkerNode.getLastStatusMessage());
                    }
                }
            }
        }
        templateVariables.put(CLUSTER_NODES_VAR, settings.getClusterNodes());
    }
    if (settings.getMaxFileUploadSize() != null) {
        templateVariables.put(MAX_FILE_UPLOAD_SIZE_PARAM, settings.getMaxFileUploadSize());
    }
    if (events.size() > 0)
        return events;
    return null;
}
Also used : ClusterNode(com.openmeap.model.dto.ClusterNode) ArrayList(java.util.ArrayList) GlobalSettings(com.openmeap.model.dto.GlobalSettings) InvalidPropertiesException(com.openmeap.model.InvalidPropertiesException) PersistenceException(javax.persistence.PersistenceException) Date(java.util.Date) InvalidPropertiesException(com.openmeap.model.InvalidPropertiesException) MessagesEvent(com.openmeap.event.MessagesEvent) PersistenceException(javax.persistence.PersistenceException) ProcessingEvent(com.openmeap.event.ProcessingEvent)

Aggregations

MessagesEvent (com.openmeap.event.MessagesEvent)15 PersistenceException (javax.persistence.PersistenceException)9 InvalidPropertiesException (com.openmeap.model.InvalidPropertiesException)6 ProcessingEvent (com.openmeap.event.ProcessingEvent)5 Application (com.openmeap.model.dto.Application)5 ApplicationArchive (com.openmeap.model.dto.ApplicationArchive)5 GlobalSettings (com.openmeap.model.dto.GlobalSettings)5 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 AddSubNavAnchorEvent (com.openmeap.admin.web.events.AddSubNavAnchorEvent)4 ApplicationVersion (com.openmeap.model.dto.ApplicationVersion)4 Anchor (com.openmeap.web.html.Anchor)4 File (java.io.File)4 Deployment (com.openmeap.model.dto.Deployment)3 ZipFile (java.util.zip.ZipFile)3 FileOperationException (com.openmeap.file.FileOperationException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 DigestException (com.openmeap.digest.DigestException)1 ClusterNode (com.openmeap.model.dto.ClusterNode)1 GenericProcessingEvent (com.openmeap.web.GenericProcessingEvent)1