Package com.webobjects.eocontrol

Examples of com.webobjects.eocontrol.EOEditingContext


    Format wholeNumberFormatter = new DecimalFormat("#,##0");
   
    long startTime = System.currentTimeMillis();
   
    // Note we use the superclass convenience method here.
    EOEditingContext ec = newEditingContext();
    ec.lock();
    try {
      // Fetch the TaskInfo
      TaskInfo taskInfo = (TaskInfo) ec.faultForGlobalID(_taskInfoGID, ec);
      _totalCount = taskInfo.countResultItems().longValue();
     
      // Task start time
      // This is a demo, so we are going to replace the prime processing times with the factorial processing times
      taskInfo.setStartTime(new NSTimestamp(startTime));
     
      // For demo purposes we will use batches and EC recycling, which would be common for processing huge data sets
      ERXFetchSpecification<ResultItem> fs = taskInfo.fetchSpecificationForResultItems();
     
      // Batch iterator
      ERXFetchSpecificationBatchIterator fsIterator = new ERXFetchSpecificationBatchIterator(fs, ec);

      // Loop for a period of time
      while (fsIterator.hasNext() && !_isStopped) {
        @SuppressWarnings("unchecked")
        NSArray<ResultItem> batch = fsIterator.nextBatch();
       
        for (ResultItem resultItem : batch) {
          resultItem.setWorkflowState(ResultItem.WORKFLOW_CHECKING_FACTORIAL);
          performFactorialProcessing(resultItem);
          resultItem.setWorkflowState(ResultItem.WORKFLOW_PROCESSING_COMPLETE);

          ec.saveChanges();
         
         
          _elapsedTime = System.currentTimeMillis() - startTime;
         
          // Update progress variables
          _countCompleted++;
          _percentComplete = (double)(_countCompleted) / (double)_totalCount;
          _status = wholeNumberFormatter.format(_countCompleted) + " numbers checked for factorial proximity";
         
          if (_isStopped) {
            break;
          }

        }
       
        // Swap in a fresh EC for the next batch to help with memory management
        EOEditingContext freshEC = newEditingContext();
        ec.unlock();
        ec = freshEC;
        freshEC.lock();
       
        fsIterator.setEditingContext(ec);
       
        // We need to refault taskInfo into the new EC after swapping
        taskInfo = (TaskInfo) ec.faultForGlobalID(_taskInfoGID, ec);
View Full Code Here


    public boolean tryToSaveChanges(boolean validateObject) { // throws Throwable {
      validationLog.debug("tryToSaveChanges calling validateForSave");
      boolean saved = false;
      if(object()!=null) {
        EOEditingContext ec = object().editingContext();
        boolean shouldRevert = false;
        try {
          if (object()!=null && validateObject && shouldValidateBeforeSave()) {
            if (ec.insertedObjects().containsObject(object()))
              object().validateForInsert();
            else
              object().validateForUpdate();
          }
            if (object()!=null && shouldSaveChanges() && ec.hasChanges()) {
                try {
                    ec.saveChanges();
                } catch (RuntimeException e) {
                    if( shouldRevertUponSaveFailure() ) {
                        shouldRevert = true;
                    }
                    throw e;
                }
        }
          saved = true;
        } catch (NSValidation.ValidationException ex) {
          setErrorMessage(ERXLocalizer.currentLocalizer().localizedTemplateStringForKeyWithObject("CouldNotSave", ex));
          validationFailedWithException(ex, ex.object(), "saveChangesExceptionKey");
        } catch(EOGeneralAdaptorException ex) {
          if(ERXEOAccessUtilities.isOptimisticLockingFailure(ex) && shouldRecoverFromOptimisticLockingFailure()) {
            EOEnterpriseObject eo = ERXEOAccessUtilities.refetchFailedObject(ec, ex);
            setErrorMessage(ERXLocalizer.currentLocalizer().localizedTemplateStringForKeyWithObject("CouldNotSavePleaseReapply", d2wContext()));
            validationFailedWithException(ex, eo, "CouldNotSavePleaseReapply");
            } else if(ERXEOAccessUtilities.isUniqueFailure(ex)) {
              EOEnterpriseObject eo = ERXEOAccessUtilities.refetchFailedObject(ec, ex);
              setErrorMessage(ERXLocalizer.currentLocalizer().localizedTemplateStringForKeyWithObject("DatabaseUniqException", d2wContext()));
              validationFailedWithException(ex, eo, "DatabaseUniqException");
          } else {
            throw ex;
          }
      } finally {
        if( shouldRevert ) {
          ec.lock();
          try {
            ec.revert();
          } finally {
            ec.unlock();
          }
        }
      }
      } else {
        saved = true;
View Full Code Here

    }
   
  // ACTIONS
 
  public WOActionResults indexMoviesAction() {
    EOEditingContext ec = ERXEC.newEditingContext();
    NSArray<Movie> eos = Movie.fetchAllMovies(ec);
    moviesIndex().clear();
    moviesIndex().addObjectsToIndex(ec, eos);
    return null;
  }
View Full Code Here

    }
    return null;
  }
 
  public WOActionResults showDetailsAction() {
    EOEditingContext ec = ERXEC.newEditingContext();
    Movie movie = (Movie)ec.faultForGlobalID(currentDocument().eoKeyGlobalId(), ec);
   
    MovieDetails nextPage = (MovieDetails)pageWithName(MovieDetails.class.getName());
    nextPage.setMovie(movie);

    return nextPage;
View Full Code Here

    if (increasePkBy < 1) increasePkBy = 1;

    String where = "where eoentity_name = '" + entityName + "'";
    if(false) {
      // AK: this should actually be the correct way...
      EOEditingContext ec = ERXEC.newEditingContext();
      ec.lock();
      try {
        EODatabaseContext dbc = ERXEOAccessUtilities.databaseContextForEntityNamed((EOObjectStoreCoordinator) ec.rootObjectStore(), entityName);
        dbc.lock();
        try {
          EOEntity entity = ERXEOAccessUtilities.entityNamed(ec, entityName);
          EOAdaptorChannel channel = (EOAdaptorChannel) dbc.adaptorContext().channels().lastObject();
          NSArray result = channel.primaryKeysForNewRowsWithEntity(increasePkBy, entity);
          return (Long) ((NSDictionary) result.lastObject()).allValues().lastObject();
        } finally {
          dbc.unlock();
        }
      } finally {
        ec.unlock();
      }
    } else {
      ERXJDBCConnectionBroker broker = ERXJDBCConnectionBroker.connectionBrokerForEntityNamed(entityName);
      Connection con = broker.getConnection();
      try {
View Full Code Here

        if (hasBinding("dataSource") && valueForBinding("list") == null)
            return (EODataSource) valueForBinding("dataSource");
        if (hasBinding("list")) {
            NSArray nsarray = (NSArray) valueForBinding("list");
            nsarray = ERXArrayUtilities.removeNullValues(nsarray);
            EOEditingContext eoeditingcontext
                = (nsarray != null && nsarray.count() > 0
                   ? ((EOEnterpriseObject) nsarray.objectAtIndex(0))
                   .editingContext()
                   : null);
            String entityName = (String) valueForBinding("entityName");
View Full Code Here

    for (Enumeration pages = _pages.objectEnumerator(); pages.hasMoreElements();) {
      String pageName = (String) pages.nextElement();
      WOContext context = ERXWOContext.newContext();
      session._awakeInContext(context);
      try {
        EOEditingContext ec = ERXEC.newEditingContext();
        ec.lock();
        try {
          log.info("Creating page: " + pageName);
          WOComponent page = D2W.factory().pageForConfigurationNamed(pageName, session);
          context._setPageElement(page);
          context._setCurrentComponent(page);
          String task = ERD2WFactory.taskFromPage(page);
          String entityName = ERD2WFactory.entityNameFromPage(page);
          if (page instanceof InspectPageInterface) {
            InspectPageInterface ipi = (InspectPageInterface) page;
            ipi.setObject(EOUtilities.createAndInsertInstance(ec, entityName));
            ipi.setNextPage(page);
          } else if (page instanceof ListPageInterface) {
            ListPageInterface lpi = (ListPageInterface) page;
            lpi.setDataSource(ERXEOControlUtilities.dataSourceForArray(ec, entityName, new NSArray(EOUtilities.createAndInsertInstance(ec, entityName))));
            lpi.setNextPage(page);
          } else if (page instanceof SelectPageInterface) {
            SelectPageInterface lpi = (SelectPageInterface) page;
            lpi.setDataSource(ERXEOControlUtilities.dataSourceForArray(ec, entityName, new NSArray(EOUtilities.createAndInsertInstance(ec, entityName))));
          } else if (page instanceof ConfirmPageInterface) {
            ConfirmPageInterface cpi = (ConfirmPageInterface) page;
            // nothing
          } else if (page instanceof QueryPageInterface) {
            QueryPageInterface qpi = (QueryPageInterface) page;
            // nothing
          } else {
            log.info("Unsupported: " + pageName + " -> " + page.name());
          }
          page.appendToResponse(new ERXResponse(), context);
        } finally {
          ec.unlock();
        }
      } catch(Throwable t) {
        log.error("Error running: " + pageName + ":" +  t.getMessage() + " Tree: " + ERXWOContext.componentPath(context));
      } finally {
        session._sleepInContext(context);
View Full Code Here

            this.relationshipEntityName = relationshipEntityName;
        }

        public void setValueInObject(EOEnterpriseObject eo) {
            Object defaultValue = stringValue;
            EOEditingContext ec = eo.editingContext();

            if(stringValue.charAt(0) == '@') { // computed key
                if(stringValue.equals("@new")) {
                    EOClassDescription cd = EOClassDescription.classDescriptionForEntityName(relationshipEntityName);
                    EOEnterpriseObject newObject = cd.createInstanceWithEditingContext(eo.editingContext(), null);
                    ec.insertObject(newObject);
                    eo.addObjectToBothSidesOfRelationshipWithKey(newObject,key);
                } else if(stringValue.startsWith("@threadStorage.")) {
                    String keyPath = stringValue.substring("@threadStorage.".length());
                    Object o = ERXThreadStorage.valueForKey(keyPath);
                    if(keyPath.indexOf(".") > 0) {
                        keyPath = stringValue.substring(keyPath.indexOf(".")+1);
                        o = NSKeyValueCodingAdditions.Utility.valueForKeyPath(o, keyPath);
                    }
                    if(o != null) {
                        if(o instanceof EOEnterpriseObject) {
                            ERXEOControlUtilities.addObjectToObjectOnBothSidesOfRelationshipWithKey((EOEnterpriseObject)o, eo, key);
                        } else if(o instanceof NSArray) {
                            NSArray newObjects = (NSArray)o;
                            for(Enumeration e = newObjects.objectEnumerator(); e.hasMoreElements();) {
                                ERXEOControlUtilities.addObjectToObjectOnBothSidesOfRelationshipWithKey((EOEnterpriseObject)e.nextElement(), eo, key);
                            }
                        } else {
                            defaultLog.warn("setValueInObject: Object is neither an EO nor an array");
                        }
                    }
                }
            } else {
                if (adaptorType == AdaptorNumberType) {
                    defaultValue = Integer.valueOf(stringValue);
                }
                EOGlobalID gid = EOKeyGlobalID.globalIDWithEntityName(relationshipEntityName, new Object[] {defaultValue});
                EOEnterpriseObject fault = ec.faultForGlobalID(gid,ec);
                eo.addObjectToBothSidesOfRelationshipWithKey(fault,key);
            }
        }
View Full Code Here

    if (record != null) {
      String entityName = (String) valueForBinding("entityName");
      if (entityName == null) {
        entityName = ERXRestClassDescriptionFactory.entityNameForObject(record);
      }
      EOEditingContext editingContext = ERXEC.newEditingContext();
      Object entityID = IERXRestDelegate.Factory.delegateForEntityNamed(entityName).primaryKeyForObject(record, new ERXRestContext(editingContext));
      editingContext.dispose();
      linkUrl = ERXRouteUrlUtils.actionUrlForEntity(context(), entityName, entityID, action, format, queryParameters, secure, includeSessionID);
    }
    else {
      String entityName = (String) valueForBinding("entityName");
      String id = (String) valueForBinding("id");
View Full Code Here

   
    public WOComponent queryAction() {
        WOComponent result = null;
        if(entity() != null) {
            // construct datasource
          EOEditingContext ec = ERXEC.newEditingContext(session().defaultEditingContext().parentObjectStore());
            queryDataSource = new EODatabaseDataSource(ec, entity().name());
            queryDataSource.setAuxiliaryQualifier(displayGroup().qualifierFromQueryValues());

            ListPageInterface lpi;
            if(listConfigurationName() != null) {
View Full Code Here

TOP

Related Classes of com.webobjects.eocontrol.EOEditingContext

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.