Search in sources :

Example 66 with EventResult

use of org.alfresco.bm.event.EventResult in project records-management by Alfresco.

the class ScheduleInPlaceRecordLoaders method processEvent.

@Override
protected EventResult processEvent(Event event) throws Exception {
    if (!enabled) {
        return new EventResult(DECLARING_NOT_WANTED_MSG, new Event(getEventNameComplete(), null));
    }
    long sessionCount = sessionService.getActiveSessionsCount();
    int loaderSessionsToCreate = maxActiveLoaders - (int) sessionCount;
    StringBuilder eventOutputMsg = new StringBuilder();
    List<Event> nextEvents = new ArrayList<>(loaderSessionsToCreate + 1);
    /*
         * Prepare files
         */
    restCoreAPI.authenticateUser(new UserModel(username, password));
    prepareFilesToBeDeclared(eventOutputMsg);
    if (unscheduledFilesCache.isEmpty()) {
        // Make sure there are no files in process of being declared.
        int scheduledInPlaceRecords = (int) recordService.getRecordCountInSpecifiedPaths(ExecutionState.SCHEDULED.name(), null);
        if (scheduledInPlaceRecords > 0) {
            // Reschedule self. Allow events to finish before raising the done event
            Event nextEvent = new Event(getEventNameRescheduleSelf(), System.currentTimeMillis() + loadCheckDelay, null);
            nextEvents.add(nextEvent);
            eventOutputMsg.append("Waiting for " + scheduledInPlaceRecords + " in progress declare in place records events. Rescheduled self.");
            return new EventResult(eventOutputMsg.toString(), nextEvents);
        }
        // no more files to declare, raise done event
        return new EventResult(DONE_EVENT_MSG, new Event(getEventNameComplete(), null));
    }
    /*
         * Schedule worker events
         */
    for (int i = 0; i < loaderSessionsToCreate; i++) {
        RecordData record = unscheduledFilesCache.poll();
        if (record == null) {
            break;
        }
        try {
            nextEvents.add(scheduleFile(record, eventOutputMsg));
        } catch (EventAlreadyScheduledException ex) {
            logger.info("File " + record.getId() + " has already been scheduled. Skip it.", ex);
        }
    }
    numberOfRecordsDeclared += nextEvents.size();
    /*
         * Reschedule self
         */
    Event nextEvent = new Event(getEventNameRescheduleSelf(), System.currentTimeMillis() + loadCheckDelay, null);
    nextEvents.add(nextEvent);
    eventOutputMsg.append("Raised further " + (nextEvents.size() - 1) + " events and rescheduled self.");
    return new EventResult(eventOutputMsg.toString(), nextEvents);
}
Also used : UserModel(org.alfresco.utility.model.UserModel) EventAlreadyScheduledException(org.alfresco.bm.dataload.rm.exceptions.EventAlreadyScheduledException) EventResult(org.alfresco.bm.event.EventResult) RecordData(org.alfresco.bm.dataload.rm.services.RecordData) ArrayList(java.util.ArrayList) Event(org.alfresco.bm.event.Event)

Example 67 with EventResult

use of org.alfresco.bm.event.EventResult in project records-management by Alfresco.

the class CreateRMSite method processEvent.

@Override
public EventResult processEvent(Event event) throws Exception {
    mandatoryObject("event", event);
    DBObject dataObj = (DBObject) event.getData();
    if (dataObj == null) {
        throw new IllegalStateException("This processor requires data object with fields '" + FIELD_SITE_ID + ", " + FIELD_SITE_MANAGER_NAME + "'.");
    }
    String siteId = (String) dataObj.get(FIELD_SITE_ID);
    String siteManager = (String) dataObj.get(FIELD_SITE_MANAGER_NAME);
    String siteManagersPassword = (String) dataObj.get(FIELD_SITE_MANAGER_PASSWORD);
    Boolean onlyLoadInDb = (Boolean) dataObj.get(FIELD_ONLY_DB_LOAD);
    if (isBlank(siteId) || isBlank(siteManager) || isBlank(siteManagersPassword)) {
        return new EventResult("Requests data not complete for site creation: " + dataObj, false);
    }
    SiteData site = siteDataService.getSite(siteId);
    if (site != null) {
        if (site.getCreationState() == Created) {
            return new EventResult("RM Site already exists in DB: " + site, false);
        }
        if (site.getCreationState() != Created) {
            return new EventResult("Site state has changed: " + site, false);
        }
    }
    String msg = null;
    RMSiteAPI rmSiteAPI = restAPIFactory.getRMSiteAPI(new UserModel(siteManager, siteManagersPassword));
    String guid = null;
    if (onlyLoadInDb == null) {
        RMSite siteModel = RMSite.builder().compliance(STANDARD).title(RM_SITE_TITLE).description(RM_SITE_DESC).build();
        RMSite rmSite = rmSiteAPI.createRMSite(siteModel);
        String statusCode = restAPIFactory.getRmRestWrapper().getStatusCode();
        if (HttpStatus.valueOf(Integer.parseInt(statusCode)) != HttpStatus.CREATED) {
            return new EventResult("RM site could not be created.", false);
        }
        guid = rmSite.getGuid();
        msg = "Created site: " + siteId + " Site creator: " + siteManager;
    } else {
        RMSite alreadyCreatedRMSite = rmSiteAPI.getSite();
        guid = alreadyCreatedRMSite.getGuid();
        msg = "RM site already exists, just loading it in the DB.";
    }
    if (site == null) {
        // Create data
        site = new SiteData();
        site.setSiteId(siteId);
        site.setTitle(RM_SITE_TITLE);
        site.setGuid(RM_SITE_GUID);
        site.setDomain(RM_SITE_DOMAIN);
        site.setDescription(RM_SITE_DESC);
        site.setSitePreset(RM_SITE_PRESET);
        site.setVisibility(RM_SITE_VISIBILITY);
        site.setType(RM_SITE_TYPE);
        site.setCreationState(Scheduled);
        siteDataService.addSite(site);
    }
    // Start by marking them as failures in order to handle all eventualities
    siteDataService.setSiteCreationState(siteId, null, Failed);
    siteDataService.setSiteMemberCreationState(siteId, siteManager, Failed);
    SiteMemberData siteMember = siteDataService.getSiteMember(RM_SITE_ID, siteManager);
    if (siteMember == null) {
        // Record the administrator
        SiteMemberData rmAdminMember = new SiteMemberData();
        rmAdminMember.setCreationState(Created);
        rmAdminMember.setRole(Administrator.toString());
        rmAdminMember.setSiteId(RM_SITE_ID);
        rmAdminMember.setUsername(siteManager);
        siteDataService.addSiteMember(rmAdminMember);
    }
    // Mark the site.
    siteDataService.setSiteCreationState(siteId, guid, Created);
    siteDataService.setSiteMemberCreationState(siteId, siteManager, Created);
    loadSpecialContainersInDB(siteId, siteManager, siteManagersPassword);
    event = new Event(eventNameSiteCreated, null);
    if (logger.isDebugEnabled()) {
        logger.debug(msg);
    }
    return new EventResult(msg, event);
}
Also used : SiteData(org.alfresco.bm.site.SiteData) UserModel(org.alfresco.utility.model.UserModel) RMSiteAPI(org.alfresco.rest.rm.community.requests.gscore.api.RMSiteAPI) SiteMemberData(org.alfresco.bm.site.SiteMemberData) EventResult(org.alfresco.bm.event.EventResult) RMSite(org.alfresco.rest.rm.community.model.site.RMSite) Event(org.alfresco.bm.event.Event) DBObject(com.mongodb.DBObject)

Example 68 with EventResult

use of org.alfresco.bm.event.EventResult in project records-management by Alfresco.

the class ScheduleUnfiledRecordLoaders method processEvent.

@Override
protected EventResult processEvent(Event event) throws Exception {
    // Are there still sessions active?
    long sessionCount = sessionService.getActiveSessionsCount();
    int loaderSessionsToCreate = maxActiveLoaders - (int) sessionCount;
    List<Event> nextEvents = new ArrayList<Event>(maxActiveLoaders);
    // Do we actually need to do anything
    if (!isUploadUnfiledRecords()) {
        return new EventResult("Uploading of Unfiled Records not wanted.", new Event(getEventNameLoadingComplete(), null));
    }
    if (unfiledRecordsNumber > 0) {
        // Prepare Records
        prepareUnfiledRecords(loaderSessionsToCreate, nextEvents);
    }
    // If there are no events, then we have finished
    String msg = null;
    if (loaderSessionsToCreate > 0 && nextEvents.isEmpty()) {
        // There are no records to load even though there are sessions available
        mapOfRecordsPerUnfiledRecordFolder = null;
        Event nextEvent = new Event(getEventNameLoadingComplete(), null);
        nextEvents.add(nextEvent);
        msg = "Loading completed.  Raising 'done' event.";
    } else {
        // Reschedule self
        Event nextEvent = new Event(getEventNameScheduleLoaders(), System.currentTimeMillis() + loadCheckDelay, null);
        nextEvents.add(nextEvent);
        msg = "Raised further " + (nextEvents.size() - 1) + " events and rescheduled self.";
    }
    if (logger.isDebugEnabled()) {
        logger.debug(msg);
    }
    EventResult result = new EventResult(msg, nextEvents);
    return result;
}
Also used : EventResult(org.alfresco.bm.event.EventResult) ArrayList(java.util.ArrayList) Event(org.alfresco.bm.event.Event)

Example 69 with EventResult

use of org.alfresco.bm.event.EventResult in project records-management by Alfresco.

the class DeclareInPlaceRecords method processEvent.

@Override
protected EventResult processEvent(Event event) throws Exception {
    StringBuilder eventOutputMsg = new StringBuilder("Declaring file as record: \n");
    super.suspendTimer();
    if (event == null) {
        throw new IllegalStateException("This processor requires an event.");
    }
    DBObject dataObj = (DBObject) event.getData();
    if (dataObj == null) {
        throw new IllegalStateException(MessageFormat.format(INVALID_DATA_MSG_TEMPLATE, FIELD_ID, FIELD_USERNAME, FIELD_PASSWORD));
    }
    String id = (String) dataObj.get(FIELD_ID);
    String username = (String) dataObj.get(FIELD_USERNAME);
    String password = (String) dataObj.get(FIELD_PASSWORD);
    if (isBlank(id) || isBlank(username) || isBlank(password)) {
        throw new IllegalStateException(MessageFormat.format(INVALID_DATA_MSG_TEMPLATE, FIELD_ID, FIELD_USERNAME, FIELD_PASSWORD));
    }
    try {
        // Get the record from database
        RecordData dbRecord = recordService.getRecord(id);
        if (dbRecord.getExecutionState() != ExecutionState.SCHEDULED) {
            throw new IllegalStateException("The record + " + id + " was found but it was already processed");
        }
        // Call the REST API
        super.resumeTimer();
        RestAPIFactory restAPIFactory = getRestAPIFactory();
        Record record = restAPIFactory.getFilesAPI(new UserModel(username, password)).declareAsRecord(id);
        String statusCode = restAPIFactory.getRmRestWrapper().getStatusCode();
        super.suspendTimer();
        TimeUnit.MILLISECONDS.sleep(declareInPlaceRecordDelay);
        if (HttpStatus.valueOf(Integer.parseInt(statusCode)) == HttpStatus.CREATED) {
            String recordParentId = record.getParentId();
            String unfiledContainerId = getRestAPIFactory().getUnfiledContainersAPI().getUnfiledContainer(FilePlanComponentAlias.UNFILED_RECORDS_CONTAINER_ALIAS).getId();
            if (!unfiledContainerId.equals(recordParentId)) {
                dbRecord.setExecutionState(ExecutionState.FAILED);
                recordService.updateRecord(dbRecord);
                return new EventResult("Declaring record with id=" + id + " didn't take place.", false);
            }
            eventOutputMsg.append("success");
            dbRecord.setExecutionState(ExecutionState.UNFILED_RECORD_DECLARED);
            dbRecord.setName(record.getName());
            String parentPath = fileFolderService.getFolder(recordParentId).getPath();
            fileFolderService.incrementFileCount(UNFILED_CONTEXT, parentPath, 1);
            dbRecord.setParentPath(parentPath);
        } else {
            eventOutputMsg.append("Failed with code " + statusCode + ".\n " + restAPIFactory.getRmRestWrapper().assertLastError().getBriefSummary() + ". \n" + restAPIFactory.getRmRestWrapper().assertLastError().getStackTrace());
            dbRecord.setExecutionState(ExecutionState.FAILED);
        }
        recordService.updateRecord(dbRecord);
        return new EventResult(eventOutputMsg.toString(), new Event(getEventNameInPlaceRecordsDeclared(), dataObj));
    } catch (Exception e) {
        String error = e.getMessage();
        String stack = ExceptionUtils.getStackTrace(e);
        // Grab REST API information
        DBObject data = BasicDBObjectBuilder.start().append("error", error).append(FIELD_ID, id).append(FIELD_USERNAME, username).append(FIELD_PASSWORD, password).append("stack", stack).get();
        // Build failure result
        return new EventResult(data, false);
    }
}
Also used : UserModel(org.alfresco.utility.model.UserModel) RecordData(org.alfresco.bm.dataload.rm.services.RecordData) EventResult(org.alfresco.bm.event.EventResult) RestAPIFactory(org.alfresco.rest.core.RestAPIFactory) Event(org.alfresco.bm.event.Event) Record(org.alfresco.rest.rm.community.model.record.Record) DBObject(com.mongodb.DBObject)

Example 70 with EventResult

use of org.alfresco.bm.event.EventResult in project records-management by Alfresco.

the class CreateRMSiteMember method processEvent.

@Override
protected EventResult processEvent(Event event) throws Exception {
    if (event == null) {
        throw new IllegalStateException("This processor requires an event.");
    }
    DBObject dataObj = (DBObject) event.getData();
    if (dataObj == null) {
        throw new IllegalStateException("This processor requires data with field " + FIELD_USERNAME);
    }
    String username = (String) dataObj.get(FIELD_USERNAME);
    EventProcessorResponse response = null;
    Event nextEvent = null;
    String msg = null;
    // Check the input
    if (StringUtils.isBlank(username)) {
        dataObj.put(MSG_KEY, INVALID_SITE_MEMBER_REQUEST_MSG);
        return new EventResult(dataObj, false);
    }
    // Get the membership data
    SiteMemberData siteMember = siteDataService.getSiteMember(PATH_SNIPPET_RM_SITE_ID, username);
    if (siteMember == null) {
        dataObj.put(MSG_KEY, MessageFormat.format(SITE_MEMBER_MISSING_MSG_TEMPLATE, username));
        return new EventResult(dataObj, false);
    }
    if (siteMember.getCreationState() != DataCreationState.Scheduled) {
        dataObj.put(MSG_KEY, MessageFormat.format(SITE_MEMBER_ALREADY_PROCESSED_MSG_TEMPLATE, siteMember));
        return new EventResult(dataObj, false);
    }
    // Start by marking it as a failure in order to handle all failure paths
    siteDataService.setSiteMemberCreationState(PATH_SNIPPET_RM_SITE_ID, username, DataCreationState.Failed);
    String roleStr = siteMember.getRole();
    try {
        // assign RM roles to new members as admin user
        RMUserAPI rmUserAPI = getRestAPIFactory().getRMUserAPI();
        rmUserAPI.assignRoleToUser(username, roleStr);
        siteDataService.setSiteMemberCreationState(PATH_SNIPPET_RM_SITE_ID, username, DataCreationState.Created);
        siteMember = siteDataService.getSiteMember(PATH_SNIPPET_RM_SITE_ID, username);
        EventDataObject responseData = new EventDataObject(STATUS.SUCCESS, siteMember);
        response = new EventProcessorResponse("Added RM site member", true, responseData);
        msg = MessageFormat.format(CREATED_RM_SITE_MEMBER_MSG_TEMPLATE, response);
        nextEvent = new Event(eventNameRMSiteMemberCreated, null);
    } catch (Exception e) {
        // Failure
        throw new RuntimeException("Create RM site member as user: admin failed (" + e.getMessage() + "): " + siteMember, e);
    }
    logger.debug(msg);
    EventResult result = new EventResult(msg, nextEvent);
    return result;
}
Also used : SiteMemberData(org.alfresco.bm.site.SiteMemberData) EventResult(org.alfresco.bm.event.EventResult) EventDataObject(org.alfresco.bm.event.selector.EventDataObject) Event(org.alfresco.bm.event.Event) DBObject(com.mongodb.DBObject) RMUserAPI(org.alfresco.rest.rm.community.requests.gscore.api.RMUserAPI) EventProcessorResponse(org.alfresco.bm.event.selector.EventProcessorResponse)

Aggregations

EventResult (org.alfresco.bm.event.EventResult)133 Test (org.junit.Test)119 Event (org.alfresco.bm.event.Event)109 DBObject (com.mongodb.DBObject)101 StopWatch (org.apache.commons.lang3.time.StopWatch)97 FolderData (org.alfresco.bm.cm.FolderData)77 UserModel (org.alfresco.utility.model.UserModel)35 LoadSingleComponentUnitTest (org.alfresco.bm.dataload.LoadSingleComponentUnitTest)23 SiteData (org.alfresco.bm.site.SiteData)20 SiteMemberData (org.alfresco.bm.site.SiteMemberData)17 RestCoreAPI (org.alfresco.rest.requests.coreAPI.RestCoreAPI)15 RecordData (org.alfresco.bm.dataload.rm.services.RecordData)14 UnfiledContainerChild (org.alfresco.rest.rm.community.model.unfiledcontainer.UnfiledContainerChild)12 UserData (org.alfresco.bm.user.UserData)11 Node (org.alfresco.rest.requests.Node)10 Site (org.alfresco.rest.requests.Site)10 File (java.io.File)9 ArrayList (java.util.ArrayList)9 UnfiledContainer (org.alfresco.rest.rm.community.model.unfiledcontainer.UnfiledContainer)9 RestWrapper (org.alfresco.rest.core.RestWrapper)8