Search in sources :

Example 1 with InvalidPropertiesException

use of com.openmeap.model.InvalidPropertiesException in project OpenMEAP by OpenMEAP.

the class ServiceManagementServlet method service.

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Result result = null;
    PrintWriter os = new PrintWriter(response.getOutputStream());
    logger.debug("Request uri: {}", request.getRequestURI());
    logger.debug("Request url: {}", request.getRequestURL());
    logger.debug("Query string: {}", request.getQueryString());
    if (logger.isDebugEnabled()) {
        logger.debug("Parameter map: {}", ParameterMapUtils.toString(request.getParameterMap()));
    }
    String action = request.getParameter(UrlParamConstants.ACTION);
    if (action == null) {
        action = "";
    }
    if (!authenticates(request)) {
        logger.error("Request failed to authenticate ", request);
        result = new Result(Result.Status.FAILURE, "Authentication failed");
        sendResult(response, os, result);
        return;
    }
    if (action.equals(ModelEntityEventAction.MODEL_REFRESH.getActionName())) {
        logger.trace("Processing refresh");
        result = refresh(request, response);
        sendResult(response, os, result);
        return;
    } else if (action.equals(ClusterNodeRequest.HEALTH_CHECK)) {
        logger.trace("Cluster node health check");
        result = healthCheck(request, response);
        sendResult(response, os, result);
        return;
    }
    GlobalSettings settings = modelManager.getGlobalSettings();
    ClusterNode clusterNode = modelManager.getClusterNode();
    if (clusterNode == null) {
        throw new RuntimeException("openmeap-services-web needs to be configured as a cluster node in the settings of the admin interface.");
    }
    Map<Method, String> validationErrors = clusterNode.validate();
    if (validationErrors != null) {
        throw new RuntimeException(new InvalidPropertiesException(clusterNode, validationErrors));
    }
    if (request.getParameter("clearPersistenceContext") != null && context instanceof AbstractApplicationContext) {
        logger.trace("Clearing persistence context");
        clearPersistenceContext();
    } else if (action.equals(ModelEntityEventAction.ARCHIVE_UPLOAD.getActionName())) {
        logger.trace("Processing archive upload - max file size: {}, storage path prefix: {}", settings.getMaxFileUploadSize(), clusterNode.getFileSystemStoragePathPrefix());
        archiveUploadHandler.setFileSystemStoragePathPrefix(clusterNode.getFileSystemStoragePathPrefix());
        Map<Object, Object> paramMap = ServletUtils.cloneParameterMap(settings.getMaxFileUploadSize(), clusterNode.getFileSystemStoragePathPrefix(), request);
        result = handleArchiveEvent(archiveUploadHandler, new MapPayloadEvent(paramMap), paramMap);
    } else if (action.equals(ModelEntityEventAction.ARCHIVE_DELETE.getActionName())) {
        logger.trace("Processing archive delete - max file size: {}, storage path prefix: {}", settings.getMaxFileUploadSize(), clusterNode.getFileSystemStoragePathPrefix());
        archiveDeleteHandler.setFileSystemStoragePathPrefix(clusterNode.getFileSystemStoragePathPrefix());
        Map<Object, Object> paramMap = ServletUtils.cloneParameterMap(settings.getMaxFileUploadSize(), clusterNode.getFileSystemStoragePathPrefix(), request);
        result = handleArchiveEvent(archiveDeleteHandler, new MapPayloadEvent(paramMap), paramMap);
    }
    sendResult(response, os, result);
}
Also used : ClusterNode(com.openmeap.model.dto.ClusterNode) GlobalSettings(com.openmeap.model.dto.GlobalSettings) MapPayloadEvent(com.openmeap.model.event.MapPayloadEvent) Method(java.lang.reflect.Method) Result(com.openmeap.services.dto.Result) InvalidPropertiesException(com.openmeap.model.InvalidPropertiesException) GenericRuntimeException(com.openmeap.util.GenericRuntimeException) AbstractApplicationContext(org.springframework.context.support.AbstractApplicationContext) JSONObject(com.openmeap.thirdparty.org.json.me.JSONObject) Map(java.util.Map) PrintWriter(java.io.PrintWriter)

Example 2 with InvalidPropertiesException

use of com.openmeap.model.InvalidPropertiesException 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)

Example 3 with InvalidPropertiesException

use of com.openmeap.model.InvalidPropertiesException in project OpenMEAP by OpenMEAP.

the class AddModifyApplicationVersionBacking method processApplicationVersionFromParameters.

private void processApplicationVersionFromParameters(Application app, ApplicationVersion version, List<ProcessingEvent> events, Map<Object, Object> parameterMap) {
    // then create a new archive for it.
    if (version.getPk() == null) {
        version.setArchive(new ApplicationArchive());
        version.getArchive().setApplication(app);
        version.setApplication(app);
    }
    fillInApplicationVersionFromParameters(app, version, events, parameterMap);
    if (version != null && version.getArchive() == null) {
        events.add(new MessagesEvent("Application archive could not be created.  Not creating empty version."));
    } else {
        try {
            modelManager.begin();
            version.setLastModifier(firstValue("userPrincipalName", parameterMap));
            ApplicationArchive savedArchive = version.getArchive();
            version.setArchive(null);
            savedArchive = modelManager.addModify(savedArchive, events);
            version.setArchive(savedArchive);
            version = modelManager.addModify(version, events);
            app.addVersion(version);
            app = modelManager.addModify(app, events);
            modelManager.commit(events);
            modelManager.refresh(app, events);
            events.add(new MessagesEvent("Application version successfully created/modified!"));
        } catch (InvalidPropertiesException ipe) {
            modelManager.rollback();
            logger.error("Unable to add/modify version " + version.getIdentifier(), ipe);
            events.add(new MessagesEvent("Unable to add/modify version - " + ipe.getMessage()));
        } catch (PersistenceException pe) {
            modelManager.rollback();
            logger.error("Unable to add/modify version " + version.getIdentifier(), pe);
            events.add(new MessagesEvent("Unable to add/modify version - " + pe.getMessage()));
        }
    }
}
Also used : InvalidPropertiesException(com.openmeap.model.InvalidPropertiesException) MessagesEvent(com.openmeap.event.MessagesEvent) PersistenceException(javax.persistence.PersistenceException) ApplicationArchive(com.openmeap.model.dto.ApplicationArchive)

Example 4 with InvalidPropertiesException

use of com.openmeap.model.InvalidPropertiesException in project OpenMEAP by OpenMEAP.

the class AddModifyApplicationBacking method process.

/**
 * With the first of the bean name matching "addModifyApp", there are
 * three ways to access this:
 *    - request has applicationId and processTarget - modifying an application
 *    - request has applicationId only              - pulling up an application to modify
 *    - request has processTarget only              - submitting a brand new application
 *
 * See the WEB-INF/ftl/form-application-addmodify.ftl for input/output parameters.
 *
 * @param context Not referenced at all, may be null
 * @param templateVariables Variables output to for the view
 * @param parameterMap Parameters passed in to drive processing
 * @return on errors, returns an array of error processingevents
 * @see TemplatedSectionBacking::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);
    Application app = new Application();
    if (ParameterMapUtils.notEmpty(FormConstants.APP_ID, parameterMap)) {
        app = modelManager.getModelService().findByPrimaryKey(Application.class, Long.valueOf(ParameterMapUtils.firstValue(FormConstants.APP_ID, parameterMap)));
    }
    Boolean mayCreate = modelManager.getAuthorizer().may(Authorizer.Action.CREATE, new Application());
    Boolean mayModify = modelManager.getAuthorizer().may(Authorizer.Action.MODIFY, app);
    Boolean willProcess = mayCreate || mayModify;
    if (!willProcess) {
        events.add(new MessagesEvent("Current user does not have permissions to make changes here"));
    }
    templateVariables.put("willProcess", willProcess);
    // the user is submitting the form for either an add or modify
    if (ParameterMapUtils.notEmpty(FormConstants.PROCESS_TARGET, parameterMap) && PROCESS_TARGET.equals(((String[]) parameterMap.get(FormConstants.PROCESS_TARGET))[0]) && willProcess) {
        app = createApplicationFromParameters(app, parameterMap, events);
        if (ParameterMapUtils.firstValue("submit", parameterMap).equals("true")) {
            if (events.size() == 0) {
                try {
                    app.setLastModifier(firstValue("userPrincipalName", parameterMap));
                    modelManager.begin();
                    app = modelManager.addModify(app, events);
                    modelManager.commit(events);
                    events.add(new MessagesEvent("Application successfully created/modified!"));
                } catch (InvalidPropertiesException e) {
                    events.add(new MessagesEvent(String.format("Application add/modify failed: %s %s", ExceptionUtils.getRootCauseMessage(e), ExceptionUtils.getRootCauseStackTrace(e)[0])));
                    logger.error("Add/Modify application with id " + app.getId() + " failed", e);
                    modelManager.rollback();
                } catch (PersistenceException e) {
                    events.add(new MessagesEvent(String.format("Application add/modify failed: %s %s", ExceptionUtils.getRootCauseMessage(e), ExceptionUtils.getRootCauseStackTrace(e)[0])));
                    logger.error("Add/Modify application with id " + app.getId() + " failed", e);
                    modelManager.rollback();
                }
            }
            if (app == null && ParameterMapUtils.notEmpty(FormConstants.APP_ID, parameterMap))
                app = modelManager.getModelService().findByPrimaryKey(Application.class, Long.valueOf(ParameterMapUtils.firstValue(FormConstants.APP_ID, parameterMap)));
        }
        if (ParameterMapUtils.notEmpty("delete", parameterMap) && ParameterMapUtils.firstValue("delete", parameterMap).equals("true")) {
            if (!ParameterMapUtils.empty("deleteConfirm", parameterMap) && ParameterMapUtils.firstValue("deleteConfirm", parameterMap).equals(FormConstants.APP_DELETE_CONFIRM_TEXT)) {
                try {
                    modelManager.begin();
                    modelManager.delete(app, events);
                    modelManager.commit(events);
                    events.add(new MessagesEvent("Application successfully deleted!"));
                    app = null;
                    // we remove the applicationId parameter, so that the form can populate empty
                    parameterMap.remove(FormConstants.APP_ID);
                } catch (Exception e) {
                    events.add(new MessagesEvent(String.format("Application delete failed: %s %s", ExceptionUtils.getRootCauseMessage(e), ExceptionUtils.getRootCauseStackTrace(e)[0])));
                    logger.error("Deleting application with id " + app.getId() + " failed", e);
                    modelManager.rollback();
                }
            } else {
                events.add(new MessagesEvent("You must confirm your desire to delete by typing in the delete confirmation message."));
            }
        }
    } else // the user is visiting the page to view or modify an application
    if (ParameterMapUtils.notEmpty(FormConstants.APP_ID, parameterMap)) {
        app = modelManager.getModelService().findByPrimaryKey(Application.class, Long.valueOf(ParameterMapUtils.firstValue(FormConstants.APP_ID, parameterMap)));
    }
    if (app == null && ParameterMapUtils.notEmpty(FormConstants.APP_ID, parameterMap)) {
        events.add(new MessagesEvent("Application with id " + ParameterMapUtils.firstValue(FormConstants.APP_ID, parameterMap) + " not found"));
    } else if (app != null && app.getId() != null) {
        // in order to create the
        ApplicationVersion testVer = new ApplicationVersion();
        testVer.setApplication(app);
        Boolean mayCreateVersions = modelManager.getAuthorizer().may(Authorizer.Action.CREATE, testVer);
        if (mayCreateVersions) {
            events.add(new AddSubNavAnchorEvent(new Anchor("?bean=addModifyAppVersionPage&applicationId=" + app.getId(), "Create new version", "Create new version")));
        }
        events.add(new AddSubNavAnchorEvent(new Anchor("?bean=appVersionListingsPage&applicationId=" + app.getId(), "Version Listings", "Version Listings")));
        events.add(new AddSubNavAnchorEvent(new Anchor("?bean=deploymentListingsPage&applicationId=" + app.getId(), "Deployment History", "Deployment History")));
    }
    fillInVariablesFromApplication(templateVariables, app);
    return events;
}
Also used : ApplicationVersion(com.openmeap.model.dto.ApplicationVersion) ArrayList(java.util.ArrayList) AddSubNavAnchorEvent(com.openmeap.admin.web.events.AddSubNavAnchorEvent) InvalidPropertiesException(com.openmeap.model.InvalidPropertiesException) PersistenceException(javax.persistence.PersistenceException) InvalidPropertiesException(com.openmeap.model.InvalidPropertiesException) Anchor(com.openmeap.web.html.Anchor) MessagesEvent(com.openmeap.event.MessagesEvent) PersistenceException(javax.persistence.PersistenceException) ProcessingEvent(com.openmeap.event.ProcessingEvent) Application(com.openmeap.model.dto.Application)

Example 5 with InvalidPropertiesException

use of com.openmeap.model.InvalidPropertiesException in project OpenMEAP by OpenMEAP.

the class DeploymentAddModifyNotifier method maintainDeploymentHistoryLength.

/**
 * Trim the deployment history table. Deleting old archives as we go.
 * @param app
 * @throws EventNotificationException
 * @throws PersistenceException
 * @throws InvalidPropertiesException
 */
private Boolean maintainDeploymentHistoryLength(Application app, List<ProcessingEvent> events) throws EventNotificationException {
    getModelManager().getModelService().refresh(app);
    Integer lengthToMaintain = app.getDeploymentHistoryLength();
    List<Deployment> deployments = app.getDeployments();
    if (deployments != null && deployments.size() > lengthToMaintain) {
        Integer currentSize = deployments.size();
        List<Deployment> newDeployments = new ArrayList<Deployment>(deployments.subList(currentSize - lengthToMaintain, currentSize));
        List<Deployment> oldDeployments = new ArrayList<Deployment>(deployments.subList(0, currentSize - lengthToMaintain));
        for (Deployment deployment : oldDeployments) {
            getModelManager().delete(deployment, events);
        }
        for (Deployment deployment : newDeployments) {
            app.getDeployments().add(deployment);
        }
        try {
            getModelManager().addModify(app, events);
        } catch (InvalidPropertiesException e) {
            throw new EventNotificationException(e);
        } catch (PersistenceException e) {
            throw new EventNotificationException(e);
        }
        return true;
    }
    return false;
}
Also used : InvalidPropertiesException(com.openmeap.model.InvalidPropertiesException) EventNotificationException(com.openmeap.event.EventNotificationException) ArrayList(java.util.ArrayList) PersistenceException(javax.persistence.PersistenceException) Deployment(com.openmeap.model.dto.Deployment)

Aggregations

InvalidPropertiesException (com.openmeap.model.InvalidPropertiesException)5 PersistenceException (javax.persistence.PersistenceException)4 MessagesEvent (com.openmeap.event.MessagesEvent)3 ArrayList (java.util.ArrayList)3 ProcessingEvent (com.openmeap.event.ProcessingEvent)2 ClusterNode (com.openmeap.model.dto.ClusterNode)2 GlobalSettings (com.openmeap.model.dto.GlobalSettings)2 AddSubNavAnchorEvent (com.openmeap.admin.web.events.AddSubNavAnchorEvent)1 EventNotificationException (com.openmeap.event.EventNotificationException)1 Application (com.openmeap.model.dto.Application)1 ApplicationArchive (com.openmeap.model.dto.ApplicationArchive)1 ApplicationVersion (com.openmeap.model.dto.ApplicationVersion)1 Deployment (com.openmeap.model.dto.Deployment)1 MapPayloadEvent (com.openmeap.model.event.MapPayloadEvent)1 Result (com.openmeap.services.dto.Result)1 JSONObject (com.openmeap.thirdparty.org.json.me.JSONObject)1 GenericRuntimeException (com.openmeap.util.GenericRuntimeException)1 Anchor (com.openmeap.web.html.Anchor)1 PrintWriter (java.io.PrintWriter)1 Method (java.lang.reflect.Method)1