Search in sources :

Example 6 with GlobalSettings

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

the class AbstractClusterServiceMgmtNotifier method notify.

public <E extends Event<T>> void notify(final E event, List<ProcessingEvent> events) throws ClusterNotificationException {
    final ThrowableList exceptions = new ThrowableList();
    onBeforeNotify(event);
    final Map<String, Boolean> urlRequestCompleteStatus = new HashMap<String, Boolean>();
    GlobalSettings globalSettings = modelManager.getGlobalSettings();
    List<ClusterNode> clusterNodes = globalSettings.getClusterNodes();
    for (ClusterNode thisNode : clusterNodes) {
        URL thisUrl = null;
        try {
            thisUrl = new URL(thisNode.getServiceWebUrlPrefix());
        } catch (MalformedURLException e) {
            logger.error("Could not create URL object from " + thisNode.getServiceWebUrlPrefix() + ": {}", e);
            continue;
        }
        if (executorService != null) {
            logger.debug("Making request to {} using the executor.", thisUrl);
            executorService.execute(new Runnable() {

                URL url;

                public void run() {
                    notifyMakeRequest(exceptions, url, urlRequestCompleteStatus, event);
                }

                Runnable setUrl(URL url) {
                    this.url = url;
                    return this;
                }
            }.setUrl(thisUrl));
        } else {
            logger.debug("Making request to {} serially.", thisUrl);
            notifyMakeRequest(exceptions, thisUrl, urlRequestCompleteStatus, event);
        }
    }
    // this set of if-else handles any exceptions in the list accumulated
    if (executorService != null && executorTimeout != null) {
        try {
            // terminate, but make sure nothing is still waiting when we terminate
            if (!executorService.awaitTermination(executorTimeout, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
                List<String> waiting = new ArrayList<String>();
                for (Map.Entry<String, Boolean> completed : urlRequestCompleteStatus.entrySet()) {
                    if (completed.getValue().equals(Boolean.FALSE)) {
                        waiting.add(completed.getKey());
                    }
                }
                logger.error("Blocking timed-out still waiting to notify: {}", StringUtils.join(waiting, ", "));
                throw new ClusterNotificationException(String.format("Blocking timed-out still waiting to notify: %s", StringUtils.join(waiting, ", ")));
            }
        } catch (InterruptedException ie) {
            throw new ClusterNotificationException("The notification thread was interrupted", ie);
        }
    } else if (exceptions.size() > 0) {
        throw new ClusterNotificationException(String.format("The following exceptions were thrown: %s", exceptions.getMessages()));
    }
    onAfterNotify(event);
}
Also used : ClusterNode(com.openmeap.model.dto.ClusterNode) ThrowableList(com.openmeap.util.ThrowableList) MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) GlobalSettings(com.openmeap.model.dto.GlobalSettings) URL(java.net.URL) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with GlobalSettings

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

the class FileOperationManagerImpl method _setup.

private void _setup() throws FileOperationException {
    if (fileResourceManager != null) {
        return;
    }
    GlobalSettings settings = (GlobalSettings) modelService.findByPrimaryKey(GlobalSettings.class, 1L);
    if (settings.getTemporaryStoragePath() == null || !new File(settings.getTemporaryStoragePath()).exists()) {
        String msg = "The storage path has not been set in GlobalSettings.  Use the settings page to fix this.";
        logger.error(msg);
        throw new FileOperationException(msg);
    }
    FileResourceManager resMgr = new FileResourceManager(settings.getTemporaryStoragePath(), settings.getTemporaryStoragePath() + "/tmp", false, new SLF4JLoggerFacade(LoggerFactory.getLogger(FileResourceManager.class)));
    fileResourceManager = resMgr;
}
Also used : SLF4JLoggerFacade(com.openmeap.util.SLF4JLoggerFacade) FileResourceManager(org.apache.commons.transaction.file.FileResourceManager) GlobalSettings(com.openmeap.model.dto.GlobalSettings) File(java.io.File) ZipFile(java.util.zip.ZipFile)

Example 8 with GlobalSettings

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

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

the class AdminTest method testUpdateApplicationVersion.

public void testUpdateApplicationVersion() throws Exception {
    GlobalSettings settings = modelManager.getGlobalSettings();
    // validate that an unused archive is deleted
    // update version update
    // and that it is recreated when reuploaded
    ApplicationVersion version1 = modelManager.getModelService().findAppVersionByNameAndId(APP_NAME, VERSION_01);
    String response = Utils.readInputStream(helper.postAddModifyAppVer(version1, new File(this.getClass().getResource(VERSION_02_ZIP).getFile())).getResponseBody(), FormConstants.CHAR_ENC_DEFAULT);
    modelManager.getModelService().clearPersistenceContext();
    version1 = modelManager.getModelService().findAppVersionByNameAndId(APP_NAME, VERSION_01);
    ApplicationVersion version2 = modelManager.getModelService().findAppVersionByNameAndId(APP_NAME, VERSION_01);
    Assert.assertTrue(version1.getArchive().getHash().equals(VERSION_02_HASH));
    Assert.assertTrue(version2.getArchive().getHash().equals(VERSION_02_HASH));
    Assert.assertSame(version2.getArchive(), version1.getArchive());
    // now restore the archive of version1
    // and validate that version2's archive is not erroneously updated.
    response = Utils.readInputStream(helper.postAddModifyAppVer(version1, new File(this.getClass().getResource(VERSION_01_ZIP).getFile())).getResponseBody(), FormConstants.CHAR_ENC_DEFAULT);
    modelManager.getModelService().clearPersistenceContext();
    version1 = modelManager.getModelService().findAppVersionByNameAndId(APP_NAME, VERSION_01);
    version2 = modelManager.getModelService().findAppVersionByNameAndId(APP_NAME, VERSION_02);
    Assert.assertTrue(version1.getArchive().getHash().equals(VERSION_01_HASH));
    Assert.assertTrue(version1.getArchive().getFile(settings.getTemporaryStoragePath()).exists());
    Assert.assertTrue(version2.getArchive().getHash().equals(VERSION_02_HASH));
    Assert.assertTrue(version2.getArchive().getFile(settings.getTemporaryStoragePath()).exists());
    Assert.assertNotSame(version2.getArchive(), version1.getArchive());
    Result result = helper.getConnectionOpen(version1, SLIC_VERSION);
    Assert.assertTrue(result.getConnectionOpenResponse().getUpdate() == null);
    Assert.assertTrue(AuthTokenProvider.validateAuthToken(version1.getApplication().getProxyAuthSalt(), result.getConnectionOpenResponse().getAuthToken()));
}
Also used : ApplicationVersion(com.openmeap.model.dto.ApplicationVersion) GlobalSettings(com.openmeap.model.dto.GlobalSettings) File(java.io.File) Result(com.openmeap.protocol.dto.Result)

Example 10 with GlobalSettings

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

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