Search in sources :

Example 1 with GlobalSettings

use of com.openmeap.model.dto.GlobalSettings in project OpenMEAP by OpenMEAP.

the class DeploymentListingsBacking method createDeployment.

private Deployment createDeployment(String creator, ApplicationVersion version, String deploymentType) {
    GlobalSettings settings = modelManager.getGlobalSettings();
    Deployment depl = new Deployment();
    depl.setType(Deployment.Type.valueOf(deploymentType));
    depl.setApplicationArchive(version.getArchive());
    depl.setCreateDate(new java.util.Date());
    depl.setCreator(creator);
    depl.setVersionIdentifier(version.getIdentifier());
    version.getApplication().addDeployment(depl);
    return depl;
}
Also used : Deployment(com.openmeap.model.dto.Deployment) GlobalSettings(com.openmeap.model.dto.GlobalSettings)

Example 2 with GlobalSettings

use of com.openmeap.model.dto.GlobalSettings 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 3 with GlobalSettings

use of com.openmeap.model.dto.GlobalSettings 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 4 with GlobalSettings

use of com.openmeap.model.dto.GlobalSettings in project OpenMEAP by OpenMEAP.

the class WebViewServlet method service.

@SuppressWarnings("unchecked")
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    logger.trace("in service");
    ModelManager mgr = getModelManager();
    GlobalSettings settings = mgr.getGlobalSettings();
    String validTempPath = settings.validateTemporaryStoragePath();
    if (validTempPath != null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, validTempPath);
    }
    String pathInfo = request.getPathInfo();
    String[] pathParts = pathInfo.split("[/]");
    if (pathParts.length < 4) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
    String remove = pathParts[1] + "/" + pathParts[2] + "/" + pathParts[3];
    String fileRelative = pathInfo.replace(remove, "");
    String applicationNameString = URLDecoder.decode(pathParts[APP_NAME_INDEX], FormConstants.CHAR_ENC_DEFAULT);
    String archiveHash = URLDecoder.decode(pathParts[APP_VER_INDEX], FormConstants.CHAR_ENC_DEFAULT);
    Application app = mgr.getModelService().findApplicationByName(applicationNameString);
    ApplicationArchive arch = mgr.getModelService().findApplicationArchiveByHashAndAlgorithm(app, archiveHash, "MD5");
    String authSalt = app.getProxyAuthSalt();
    String authToken = URLDecoder.decode(pathParts[AUTH_TOKEN_INDEX], FormConstants.CHAR_ENC_DEFAULT);
    try {
        if (!AuthTokenProvider.validateAuthToken(authSalt, authToken)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
    } catch (DigestException e1) {
        throw new GenericRuntimeException(e1);
    }
    File fileFull = new File(arch.getExplodedPath(settings.getTemporaryStoragePath()).getAbsolutePath() + "/" + fileRelative);
    try {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String mimeType = fileNameMap.getContentTypeFor(fileFull.toURL().toString());
        response.setContentType(mimeType);
        response.setContentLength(Long.valueOf(fileFull.length()).intValue());
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //response.setStatus(HttpServletResponse.SC_FOUND);
            inputStream = new FileInputStream(fileFull);
            outputStream = response.getOutputStream();
            Utils.pipeInputStreamIntoOutputStream(inputStream, outputStream);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            response.getOutputStream().flush();
            response.getOutputStream().close();
        }
    } catch (FileNotFoundException e) {
        logger.error("Exception {}", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IOException ioe) {
        logger.error("Exception {}", ioe);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileNotFoundException(java.io.FileNotFoundException) GlobalSettings(com.openmeap.model.dto.GlobalSettings) IOException(java.io.IOException) ModelManager(com.openmeap.model.ModelManager) GenericRuntimeException(com.openmeap.util.GenericRuntimeException) FileNameMap(java.net.FileNameMap) ApplicationArchive(com.openmeap.model.dto.ApplicationArchive) FileInputStream(java.io.FileInputStream) DigestException(com.openmeap.digest.DigestException) Application(com.openmeap.model.dto.Application) File(java.io.File)

Example 5 with GlobalSettings

use of com.openmeap.model.dto.GlobalSettings in project OpenMEAP by OpenMEAP.

the class ServletManagementServletTest method testRefreshApplication.

@Test
public void testRefreshApplication() throws Exception {
    MockHttpServletRequest request = new Request();
    MockHttpServletResponse response = new MockHttpServletResponse();
    String randomUuid = UUID.randomUUID().toString();
    GlobalSettings settings = modelManager.getGlobalSettings();
    /////////////////
    // validate that finding the application, modifying it, and then finding it again 
    // will return an object with the same modifications.
    Application app = modelManager.getModelService().findByPrimaryKey(Application.class, 1L);
    app.setName(randomUuid);
    Assert.assertTrue(modelManager.getModelService().findByPrimaryKey(Application.class, 1L).getName().equals(randomUuid));
    modelManager.refresh(app, null);
    app = modelManager.getModelService().findByPrimaryKey(Application.class, 1L);
    Assert.assertTrue(!modelManager.getModelService().findByPrimaryKey(Application.class, 1L).getName().equals(randomUuid));
    ServiceManagementServlet servlet = new ServiceManagementServlet();
    servlet.setModelManager(modelManager);
    servlet.setModelServiceRefreshHandler(new ModelServiceRefreshHandler());
    servlet.getModelServiceRefreshHandler().setModelManager(modelManager);
    ////////////////////
    // validate the happy path of providing all the required information
    String authSalt = servlet.getAuthSalt();
    String authToken = AuthTokenProvider.newAuthToken(authSalt);
    request.setParameter(UrlParamConstants.REFRESH_TYPE, "Application");
    request.setParameter(UrlParamConstants.REFRESH_OBJ_PKID, "1");
    request.setParameter(UrlParamConstants.AUTH_TOKEN, authToken);
    request.setParameter(UrlParamConstants.ACTION, ModelEntityEventAction.MODEL_REFRESH.getActionName());
    servlet.service(request, response);
    String contentString = response.getContentAsString();
    JSONObjectBuilder job = new JSONObjectBuilder();
    Result result = (Result) job.fromJSON(new JSONObject(contentString), new Result());
    Assert.assertTrue(result.getStatus().equals(Result.Status.SUCCESS));
    Assert.assertTrue(!modelManager.getModelService().findByPrimaryKey(Application.class, 1L).getName().equals(randomUuid));
    ////////////////////
    // validate that failing to provide auth token fails to refresh cache
    app = modelManager.getModelService().findByPrimaryKey(Application.class, 1L);
    app.setName(randomUuid);
    response = new MockHttpServletResponse();
    request.removeParameter(UrlParamConstants.AUTH_TOKEN);
    request.setParameter(UrlParamConstants.ACTION, ModelEntityEventAction.MODEL_REFRESH.getActionName());
    request.setParameter(UrlParamConstants.REFRESH_TYPE, "Application");
    request.setParameter(UrlParamConstants.REFRESH_OBJ_PKID, "1");
    servlet.service(request, response);
    contentString = response.getContentAsString();
    result = (Result) job.fromJSON(new JSONObject(contentString), new Result());
    Assert.assertTrue(result.getStatus().equals(Result.Status.FAILURE));
    Assert.assertTrue(modelManager.getModelService().findByPrimaryKey(Application.class, 1L).getName().equals(randomUuid));
}
Also used : JSONObjectBuilder(com.openmeap.json.JSONObjectBuilder) JSONObject(com.openmeap.thirdparty.org.json.me.JSONObject) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ModelServiceRefreshHandler(com.openmeap.model.event.handler.ModelServiceRefreshHandler) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) GlobalSettings(com.openmeap.model.dto.GlobalSettings) Application(com.openmeap.model.dto.Application) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Result(com.openmeap.services.dto.Result) Test(org.junit.Test)

Aggregations

GlobalSettings (com.openmeap.model.dto.GlobalSettings)22 ClusterNode (com.openmeap.model.dto.ClusterNode)7 File (java.io.File)7 PersistenceException (javax.persistence.PersistenceException)7 Application (com.openmeap.model.dto.Application)6 ApplicationVersion (com.openmeap.model.dto.ApplicationVersion)6 IOException (java.io.IOException)6 MessagesEvent (com.openmeap.event.MessagesEvent)5 ApplicationArchive (com.openmeap.model.dto.ApplicationArchive)5 HashMap (java.util.HashMap)5 DigestException (com.openmeap.digest.DigestException)4 Deployment (com.openmeap.model.dto.Deployment)4 GenericRuntimeException (com.openmeap.util.GenericRuntimeException)4 FileOperationException (com.openmeap.file.FileOperationException)3 InvalidPropertiesException (com.openmeap.model.InvalidPropertiesException)3 ModelManager (com.openmeap.model.ModelManager)3 FileInputStream (java.io.FileInputStream)3 ArrayList (java.util.ArrayList)3 ClusterNotificationException (com.openmeap.cluster.ClusterNotificationException)2 EventNotificationException (com.openmeap.event.EventNotificationException)2