Search in sources :

Example 1 with Result

use of com.openmeap.services.dto.Result 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)

Example 2 with Result

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

use of com.openmeap.services.dto.Result in project OpenMEAP by OpenMEAP.

the class ServiceManagementServlet method healthCheck.

/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
private Result healthCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String json = Utils.readInputStream(request.getInputStream(), FormConstants.CHAR_ENC_DEFAULT);
    Result result = null;
    try {
        ClusterNodeRequest nodeRequest = (ClusterNodeRequest) new JSONObjectBuilder().fromJSON(new JSONObject(json), new ClusterNodeRequest());
        Map<String, String> properties = (Map<String, String>) context.getBean("openmeapServicesWebPropertiesMap");
        synchronized (properties) {
            properties.put("clusterNodeUrlPrefix", nodeRequest.getClusterNode().getServiceWebUrlPrefix());
            properties.put("fileSystemStoragePathPrefix", nodeRequest.getClusterNode().getFileSystemStoragePathPrefix());
        }
        result = new Result(Result.Status.SUCCESS);
    } catch (JSONException e) {
        result = new Result();
        result.setStatus(Result.Status.FAILURE);
        String msg = "Failed to parse health status check JSON - " + json;
        logger.error(msg);
        result.setMessage(msg);
    }
    return result;
}
Also used : JSONObjectBuilder(com.openmeap.json.JSONObjectBuilder) JSONObject(com.openmeap.thirdparty.org.json.me.JSONObject) JSONException(com.openmeap.thirdparty.org.json.me.JSONException) ClusterNodeRequest(com.openmeap.cluster.dto.ClusterNodeRequest) Map(java.util.Map) Result(com.openmeap.services.dto.Result)

Example 4 with Result

use of com.openmeap.services.dto.Result in project OpenMEAP by OpenMEAP.

the class ServiceManagementServlet method refresh.

/**
	 * Handles the notification that this node should refresh some object from the database.
	 * 
	 * @param os
	 * @param request
	 * @param response
	 * @throws IOException
	 */
private Result refresh(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/javascript");
    String refreshType = (String) request.getParameter("type");
    String objectId = (String) request.getParameter("id");
    Result result = null;
    if (refreshType != null && objectId != null) {
        logger.info("Received request to refresh {} with id {}", refreshType, objectId);
        try {
            modelServiceRefreshHandler.handleRefresh(refreshType, objectId);
            logger.info("Refresh for {} with id {} was successful", refreshType, objectId);
            result = new Result(Result.Status.SUCCESS);
        } catch (Exception e) {
            String msg = "Exception occurred refreshing " + refreshType + " with object id " + objectId;
            logger.error(msg, e);
            result = new Result(Result.Status.FAILURE, msg);
        }
    } else {
        String msg = "Must specify refresh target class, object primary key, and authentication token.";
        logger.error(msg, request);
        result = new Result(Result.Status.FAILURE, msg);
    }
    return result;
}
Also used : JSONException(com.openmeap.thirdparty.org.json.me.JSONException) DigestException(com.openmeap.digest.DigestException) InvalidPropertiesException(com.openmeap.model.InvalidPropertiesException) GenericRuntimeException(com.openmeap.util.GenericRuntimeException) IOException(java.io.IOException) EventHandlingException(com.openmeap.event.EventHandlingException) Result(com.openmeap.services.dto.Result)

Example 5 with Result

use of com.openmeap.services.dto.Result in project OpenMEAP by OpenMEAP.

the class ServiceManagementServlet method handleArchiveEvent.

@SuppressWarnings(value = { "rawtypes", "unchecked" })
private Result handleArchiveEvent(EventHandler eventHandler, Event event, Map<Object, Object> paramMap) throws IOException {
    String hash = firstValue(UrlParamConstants.APPARCH_HASH, paramMap);
    String hashType = firstValue(UrlParamConstants.APPARCH_HASH_ALG, paramMap);
    logger.info("Received request archive upload notification {}:{}", hashType, hash);
    Result result = null;
    if (hash != null && hashType != null) {
        ApplicationArchive arch = new ApplicationArchive();
        arch.setHash(hash);
        arch.setHashAlgorithm(hashType);
        try {
            paramMap.put("archive", arch);
            eventHandler.handle(event);
            result = new Result(Result.Status.SUCCESS);
        } catch (EventHandlingException che) {
            String msg = "Exception occurred handing the ArchiveUploadEvent";
            logger.error(msg, che);
            result = new Result(Result.Status.FAILURE, msg);
        }
    } else {
        String msg = "Either the hash(" + hash + ") or the hashType(" + hashType + ") was null.  Both are needed to process an archive event";
        logger.error(msg);
        result = new Result(Result.Status.FAILURE, msg);
    }
    return result;
}
Also used : EventHandlingException(com.openmeap.event.EventHandlingException) ApplicationArchive(com.openmeap.model.dto.ApplicationArchive) Result(com.openmeap.services.dto.Result)

Aggregations

Result (com.openmeap.services.dto.Result)6 JSONObject (com.openmeap.thirdparty.org.json.me.JSONObject)4 JSONObjectBuilder (com.openmeap.json.JSONObjectBuilder)3 ClusterNodeRequest (com.openmeap.cluster.dto.ClusterNodeRequest)2 EventHandlingException (com.openmeap.event.EventHandlingException)2 InvalidPropertiesException (com.openmeap.model.InvalidPropertiesException)2 ClusterNode (com.openmeap.model.dto.ClusterNode)2 GlobalSettings (com.openmeap.model.dto.GlobalSettings)2 JSONException (com.openmeap.thirdparty.org.json.me.JSONException)2 GenericRuntimeException (com.openmeap.util.GenericRuntimeException)2 Map (java.util.Map)2 DigestException (com.openmeap.digest.DigestException)1 HttpResponse (com.openmeap.http.HttpResponse)1 Application (com.openmeap.model.dto.Application)1 ApplicationArchive (com.openmeap.model.dto.ApplicationArchive)1 MapPayloadEvent (com.openmeap.model.event.MapPayloadEvent)1 ModelServiceRefreshHandler (com.openmeap.model.event.handler.ModelServiceRefreshHandler)1 IOException (java.io.IOException)1 PrintWriter (java.io.PrintWriter)1 Method (java.lang.reflect.Method)1