/**
   * Commit the current transaction, writing any unflushed changes to the database.
   *
   * @throws IllegalStateException if isActive() is false.
   * @throws RollbackException if the commit fails.
   */
  public void commit() {
    assertActive();

    if (tx.getRollbackOnly()) {
      // This is thrown by the underlying transaction but we want to have a RollbackException here
      // so intercept it
      if (NucleusLogger.TRANSACTION.isDebugEnabled()) {
        NucleusLogger.TRANSACTION.debug(Localiser.msg("015020"));
      }
      throw new RollbackException(Localiser.msg("015020"));
    }

    try {
      tx.commit();
    } catch (NucleusTransactionException nte) {
      Throwable cause = nte.getCause();
      Throwable pe = null;
      if (cause instanceof NucleusException) {
        pe = NucleusJPAHelper.getJPAExceptionForNucleusException((NucleusException) cause);
      } else {
        pe = cause;
      }
      throw new RollbackException(Localiser.msg("015007"), pe);
    } catch (NucleusException ne) {
      throw NucleusJPAHelper.getJPAExceptionForNucleusException(ne);
    }
  }
  /**
   * Method to check if an element is already persistent, or is managed by a different
   * ExecutionContext. If not persistent, this will persist it.
   *
   * @param ec execution context
   * @param element The element
   * @param fieldValues any initial field values to use if persisting the element
   * @return Whether the element was persisted during this call
   */
  protected boolean validateElementForWriting(
      ExecutionContext ec, Object element, FieldValues fieldValues) {
    // TODO Pass in cascade flag and if element not present then throw exception
    // Check the element type for this collection
    if (!elementIsPersistentInterface
        && !validateElementType(ec.getClassLoaderResolver(), element)) {
      throw new ClassCastException(
          Localiser.msg(
              "056033",
              element.getClass().getName(),
              ownerMemberMetaData.getFullFieldName(),
              elementType));
    }

    boolean persisted = false;
    if (elementsAreEmbedded || elementsAreSerialised) {
      // Element is embedded/serialised so has no id
    } else {
      ObjectProvider elementSM = ec.findObjectProvider(element);
      if (elementSM != null && elementSM.isEmbedded()) {
        // Element is already with ObjectProvider and is embedded in another field!
        throw new NucleusUserException(
            Localiser.msg("056028", ownerMemberMetaData.getFullFieldName(), element));
      }

      persisted = SCOUtils.validateObjectForWriting(ec, element, fieldValues);
    }
    return persisted;
  }
  /*
   * (non-Javadoc)
   * @see
   * org.datanucleus.store.rdbms.mapping.datastore.AbstractDatastoreMapping#getObject(java.sql.ResultSet, int)
   */
  @Override
  public Object getObject(ResultSet resultSet, int param) {
    Object so = null;

    try {
      InputStream is = resultSet.getBinaryStream(param);
      if (!resultSet.wasNull()) {
        if (getJavaTypeMapping() instanceof FileMapping) {
          so = StreamableSpooler.instance().spoolStream(is);
        } else {
          // TODO Support other types
          throw new NucleusDataStoreException(
              "getObject unsupported for java type mapping of type " + getJavaTypeMapping());
        }
      }
    } catch (IOException e) {
      throw new NucleusDataStoreException(
          Localiser.msg("055002", "Object", "" + param, column, e.getMessage()), e);
    } catch (SQLException e) {
      throw new NucleusDataStoreException(
          Localiser.msg("055002", "Object", "" + param, column, e.getMessage()), e);
    }

    return so;
  }
 public void setString(PreparedStatement ps, int param, String value) {
   try {
     if (getDatastoreAdapter().supportsOption(DatastoreAdapter.BLOB_SET_USING_SETSTRING)) {
       if (value == null) {
         if (column.isDefaultable() && column.getDefaultValue() != null) {
           ps.setString(param, column.getDefaultValue().toString().trim());
         } else {
           ps.setNull(param, getJDBCType());
         }
       } else {
         ps.setString(param, value);
       }
     } else {
       if (value == null) {
         if (column != null && column.isDefaultable() && column.getDefaultValue() != null) {
           ps.setBlob(param, new BlobImpl(column.getDefaultValue().toString().trim()));
         } else {
           ps.setNull(param, getJDBCType());
         }
       } else {
         ps.setBlob(param, new BlobImpl(value));
       }
     }
   } catch (SQLException e) {
     throw new NucleusDataStoreException(
         Localiser.msg("055001", "String", "" + value, column, e.getMessage()), e);
   } catch (IOException e) {
     throw new NucleusDataStoreException(
         Localiser.msg("055001", "String", "" + value, column, e.getMessage()), e);
   }
 }
  public int getSize(ObjectProvider ownerOP) {
    int numRows;

    String sizeStmt = getSizeStmt();
    try {
      ExecutionContext ec = ownerOP.getExecutionContext();
      ManagedConnection mconn = storeMgr.getConnection(ec);
      SQLController sqlControl = storeMgr.getSQLController();
      try {
        PreparedStatement ps = sqlControl.getStatementForQuery(mconn, sizeStmt);
        try {
          int jdbcPosition = 1;
          jdbcPosition =
              BackingStoreHelper.populateOwnerInStatement(ownerOP, ec, ps, jdbcPosition, this);
          if (getElementInfo() != null && getElementInfo().length == 1) {
            // TODO Allow for multiple element types (e.g interface implementations)
            for (int i = 0; i < getElementInfo().length; i++) {
              if (getElementInfo()[i].getDiscriminatorMapping() != null) {
                jdbcPosition =
                    BackingStoreHelper.populateElementDiscriminatorInStatement(
                        ec, ps, jdbcPosition, true, getElementInfo()[i], clr);
              }
            }
          }
          if (getRelationDiscriminatorMapping() != null) {
            jdbcPosition =
                BackingStoreHelper.populateRelationDiscriminatorInStatement(
                    ec, ps, jdbcPosition, this);
          }

          ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, sizeStmt, ps);
          try {
            if (!rs.next()) {
              throw new NucleusDataStoreException(Localiser.msg("056007", sizeStmt));
            }

            numRows = rs.getInt(1);
            JDBCUtils.logWarnings(rs);
          } finally {
            rs.close();
          }
        } finally {
          sqlControl.closeStatement(mconn, ps);
        }
      } finally {
        mconn.release();
      }
    } catch (SQLException e) {
      throw new NucleusDataStoreException(Localiser.msg("056007", sizeStmt), e);
    }

    return numRows;
  }
  /**
   * Accessor for the MetaData for the specified class, read from annotations. The annotations can
   * be of any supported type.
   *
   * @param cls The class
   * @param pmd PackageMetaData to use as a parent
   * @param clr ClassLoader resolver
   * @return The ClassMetaData
   */
  public AbstractClassMetaData getMetaDataForClass(
      Class cls, PackageMetaData pmd, ClassLoaderResolver clr) {
    if (cls == null) {
      return null;
    }

    Annotation[] annotations = cls.getAnnotations();
    if (annotations == null || annotations.length == 0) {
      return null;
    }

    // Find an annotation reader for this classes annotations (if we have one)
    String readerClassName = null;
    for (int i = 0; i < annotations.length; i++) {
      String reader = annotationReaderLookup.get(annotations[i].annotationType().getName());
      if (reader != null) {
        readerClassName = reader;
        break;
      }
    }
    if (readerClassName == null) {
      NucleusLogger.METADATA.debug(Localiser.msg("044202", cls.getName()));
      return null;
    }

    AnnotationReader reader = annotationReaders.get(readerClassName);
    if (reader == null) {
      // Try to create this AnnotationReader
      try {
        Class[] ctrArgs = new Class[] {ClassConstants.METADATA_MANAGER};
        Object[] ctrParams = new Object[] {metadataMgr};
        PluginManager pluginMgr = metadataMgr.getNucleusContext().getPluginManager();
        reader =
            (AnnotationReader)
                pluginMgr.createExecutableExtension(
                    "org.datanucleus.annotations",
                    "reader",
                    readerClassName,
                    "reader",
                    ctrArgs,
                    ctrParams);
        annotationReaders.put(
            readerClassName,
            reader); // Save the annotation reader in case we have more of this type
      } catch (Exception e) {
        NucleusLogger.METADATA.warn(
            Localiser.msg("MetaData.AnnotationReaderNotFound", readerClassName));
        return null;
      }
    }

    return reader.getMetaDataForClass(cls, pmd, clr);
  }
Ejemplo n.º 7
0
 /**
  * Method to return this class/field managed object as a string.
  *
  * @return String version of this class/field managed object.
  */
 public String toString() {
   MetaData metadata = getMetaData();
   if (metadata instanceof ClassMetaData) {
     ClassMetaData cmd = (ClassMetaData) metadata;
     return Localiser.msg(
         "035004",
         name,
         tableName != null ? tableName : "(none)",
         cmd.getInheritanceMetaData().getStrategy().toString());
   } else if (metadata instanceof AbstractMemberMetaData) {
     return Localiser.msg("035005", name, tableName);
   } else {
     return Localiser.msg("035004", name, tableName);
   }
 }
  /*
   * (non-Javadoc)
   * @see org.datanucleus.store.rdbms.mapping.AbstractLargeBinaryRDBMSMapping#getObject(java.lang.Object,
   * int)
   */
  @Override
  public Object getObject(ResultSet rs, int param) {
    byte[] bytes = null;
    try {
      // Retrieve the bytes of the object directly
      bytes = rs.getBytes(param);
      if (bytes == null) {
        return null;
      }
    } catch (SQLException sqle) {
      try {
        // Retrieve the bytes using the Blob (if getBytes not supported e.g HSQLDB 2.0)
        Blob blob = rs.getBlob(param);
        if (blob == null) {
          return null;
        }
        bytes = blob.getBytes(1, (int) blob.length());
        if (bytes == null) {
          return null;
        }
      } catch (SQLException sqle2) {
        throw new NucleusDataStoreException(
            Localiser.msg("055002", "Object", "" + param, column, sqle2.getMessage()), sqle2);
      }
    }

    return getObjectForBytes(bytes, param);
  }
Ejemplo n.º 9
0
  /**
   * Method to remove an element from the ArrayList.
   *
   * @param index The element position.
   * @return The object that was removed
   */
  public synchronized Object remove(int index) {
    makeDirty();

    if (useCache) {
      loadFromStore();
    }

    int size = (useCache ? delegate.size() : -1);
    Object delegateObject = (useCache ? delegate.remove(index) : null);

    Object backingObject = null;
    if (backingStore != null) {
      if (SCOUtils.useQueuedUpdate(queued, ownerOP)) {
        backingObject = delegateObject;
        ownerOP
            .getExecutionContext()
            .addOperationToQueue(new ListRemoveAtOperation(ownerOP, backingStore, index));
      } else {
        try {
          backingObject = backingStore.remove(ownerOP, index, size);
        } catch (NucleusDataStoreException dse) {
          NucleusLogger.PERSISTENCE.warn(
              Localiser.msg("023013", "remove", ownerMmd.getName(), dse));
          backingObject = null;
        }
      }
    }

    if (ownerOP != null && !ownerOP.getExecutionContext().getTransaction().isActive()) {
      ownerOP.getExecutionContext().processNontransactionalUpdate();
    }

    return (backingStore != null ? backingObject : delegateObject);
  }
  /** Method to delete the object from the datastore. */
  protected void internalDeletePersistent() {
    if (isDeleting()) {
      throw new NucleusUserException(Localiser.msg("026008"));
    }

    activity = ActivityState.DELETING;
    try {
      if (dirty) {
        clearDirtyFlags();

        // Clear the PM's knowledge of our being dirty. This calls flush() which does nothing
        myEC.flushInternal(false);
      }

      myEC.getNucleusContext();
      if (!isEmbedded()) {
        // Nothing to delete if embedded
        getStoreManager().getPersistenceHandler().deleteObject(this);
      }

      preDeleteLoadedFields = null;
    } finally {
      activity = ActivityState.NONE;
    }
  }
  public void executeClear(ObjectProvider ownerOP) {
    String clearStmt = getClearStmt();
    try {
      ExecutionContext ec = ownerOP.getExecutionContext();
      ManagedConnection mconn = storeMgr.getConnection(ec);
      SQLController sqlControl = storeMgr.getSQLController();
      try {
        PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, clearStmt, false);
        try {
          int jdbcPosition = 1;
          jdbcPosition =
              BackingStoreHelper.populateOwnerInStatement(ownerOP, ec, ps, jdbcPosition, this);
          if (getRelationDiscriminatorMapping() != null) {
            BackingStoreHelper.populateRelationDiscriminatorInStatement(ec, ps, jdbcPosition, this);
          }

          sqlControl.executeStatementUpdate(ec, mconn, clearStmt, ps, true);
        } finally {
          sqlControl.closeStatement(mconn, ps);
        }
      } finally {
        mconn.release();
      }
    } catch (SQLException e) {
      throw new NucleusDataStoreException(Localiser.msg("056013", clearStmt), e);
    }
  }
  public MemberAnnotationHandler getHandlerForMemberAnnotation(String annotationName) {
    if (memberAnnotationHandlerAnnotations == null
        || !memberAnnotationHandlerAnnotations.contains(annotationName)) {
      return null;
    }

    MemberAnnotationHandler handler = memberAnnotationHandlers.get(annotationName);
    if (handler == null) {
      // Try to create this MemberAnnotationHandler
      try {
        PluginManager pluginMgr = metadataMgr.getNucleusContext().getPluginManager();
        handler =
            (MemberAnnotationHandler)
                pluginMgr.createExecutableExtension(
                    "org.datanucleus.member_annotation_handler",
                    "annotation-class",
                    annotationName,
                    "handler",
                    null,
                    null);
        memberAnnotationHandlers.put(annotationName, handler);
      } catch (Exception e) {
        NucleusLogger.METADATA.warn(
            Localiser.msg("MetaData.MemberAnnotationHandlerNotFound", annotationName));
        return null;
      }
    }

    return handler;
  }
  /* (non-Javadoc)
   * @see org.datanucleus.store.rdbms.sql.method.SQLMethod#getExpression(org.datanucleus.store.rdbms.sql.expression.SQLExpression, java.util.List)
   */
  public SQLExpression getExpression(SQLExpression expr, List<SQLExpression> args) {
    if (args == null || args.size() == 0 || args.size() > 1) {
      throw new NucleusException(Localiser.msg("060016", "containsValue", "MapExpression", 1));
    }

    MapExpression mapExpr = (MapExpression) expr;
    SQLExpression valExpr = args.get(0);

    if (valExpr.isParameter()) {
      // Value is a parameter so make sure its type is set
      AbstractMemberMetaData mmd = mapExpr.getJavaTypeMapping().getMemberMetaData();
      if (mmd != null && mmd.getMap() != null) {
        Class valCls =
            stmt.getQueryGenerator()
                .getClassLoaderResolver()
                .classForName(mmd.getMap().getValueType());
        stmt.getQueryGenerator().bindParameter(valExpr.getParameterName(), valCls);
      }
    }

    if (mapExpr instanceof MapLiteral) {
      MapLiteral lit = (MapLiteral) mapExpr;
      Map map = (Map) lit.getValue();
      if (map == null || map.size() == 0) {
        return new BooleanLiteral(stmt, expr.getJavaTypeMapping(), Boolean.FALSE);
      }

      // TODO If valExpr is a parameter and mapExpr is derived from a parameter ?
      MapValueLiteral mapValueLiteral = lit.getValueLiteral();
      BooleanExpression bExpr = null;
      List<SQLExpression> elementExprs = mapValueLiteral.getValueExpressions();
      for (int i = 0; i < elementExprs.size(); i++) {
        if (bExpr == null) {
          bExpr = (elementExprs.get(i)).eq(valExpr);
        } else {
          bExpr = bExpr.ior((elementExprs.get(i)).eq(valExpr));
        }
      }
      if (bExpr != null) {
        bExpr.encloseInParentheses();
      }
      return bExpr;
    }

    if (stmt.getQueryGenerator().getCompilationComponent() == CompilationComponent.FILTER) {
      boolean needsSubquery = getNeedsSubquery();

      // TODO Check if *this* "containsValue" is negated, not any of them (and remove above check)
      if (needsSubquery) {
        NucleusLogger.QUERY.debug(
            "map.containsValue on " + mapExpr + "(" + valExpr + ") using SUBQUERY");
        return containsAsSubquery(mapExpr, valExpr);
      }
      NucleusLogger.QUERY.debug(
          "map.containsValue on " + mapExpr + "(" + valExpr + ") using INNERJOIN");
      return containsAsInnerJoin(mapExpr, valExpr);
    }
    return containsAsSubquery(mapExpr, valExpr);
  }
Ejemplo n.º 14
0
  /**
   * Method to execute a PreparedStatement query, and return the ResultSet. Prints logging
   * information about timings.
   *
   * @param conn The connection (required since the one on PreparedStatement is not always the same
   *     so we can't use it)
   * @param stmt The statement text
   * @param ps The Prepared Statement
   * @return The ResultSet from the query
   * @throws SQLException Thrown if an error occurs
   */
  public ResultSet executeStatementQuery(
      ExecutionContext ec, ManagedConnection conn, String stmt, PreparedStatement ps)
      throws SQLException {
    if (supportsBatching) {
      ConnectionStatementState state = getConnectionStatementState(conn);
      if (state != null) {
        if (state.processable) {
          // Current batch statement is processable now so lets just process it before processing
          // our query
          processConnectionStatement(conn);
        } else {
          // Current wait statement is not processable now so leave it in wait state
          if (NucleusLogger.DATASTORE_RETRIEVE.isDebugEnabled()) {
            NucleusLogger.DATASTORE_RETRIEVE.debug(LOCALISER.msg("052106", state.stmtText, stmt));
          }
        }
      }
    }

    // Execute this query
    long startTime = System.currentTimeMillis();
    if (NucleusLogger.DATASTORE_NATIVE.isDebugEnabled()) {
      if (ps instanceof ParamLoggingPreparedStatement) {
        NucleusLogger.DATASTORE_NATIVE.debug(
            ((ParamLoggingPreparedStatement) ps).getStatementWithParamsReplaced());
      } else {
        NucleusLogger.DATASTORE_NATIVE.debug(stmt);
      }
    }

    ResultSet rs = ps.executeQuery();
    if (ec != null && ec.getStatistics() != null) {
      // Add to statistics
      ec.getStatistics().incrementNumReads();
    }

    ps.clearBatch();
    if (NucleusLogger.DATASTORE_RETRIEVE.isDebugEnabled()) {
      NucleusLogger.DATASTORE_RETRIEVE.debug(
          LOCALISER.msg("045000", (System.currentTimeMillis() - startTime)));
    }

    return rs;
  }
  /**
   * Clear the association from owner to all elements. Provides cascade-delete when the elements
   * being deleted are PC types.
   *
   * @param ownerOP ObjectProvider for the container.
   */
  public void clear(ObjectProvider ownerOP) {
    Collection dependentElements = null;
    CollectionMetaData collmd = ownerMemberMetaData.getCollection();
    boolean dependent = collmd.isDependentElement();
    if (ownerMemberMetaData.isCascadeRemoveOrphans()) {
      dependent = true;
    }
    if (dependent && !collmd.isEmbeddedElement() && !collmd.isSerializedElement()) {
      // Retain the dependent elements that need deleting after clearing
      dependentElements = new HashSet();
      Iterator iter = iterator(ownerOP);
      while (iter.hasNext()) {
        dependentElements.add(iter.next());
      }
    }

    String clearStmt = getClearStmt();
    try {
      ExecutionContext ec = ownerOP.getExecutionContext();
      ManagedConnection mconn = storeMgr.getConnection(ec);
      SQLController sqlControl = storeMgr.getSQLController();
      try {
        PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, clearStmt, false);
        try {
          int jdbcPosition = 1;
          jdbcPosition =
              BackingStoreHelper.populateOwnerInStatement(ownerOP, ec, ps, jdbcPosition, this);
          if (relationDiscriminatorMapping != null) {
            BackingStoreHelper.populateRelationDiscriminatorInStatement(ec, ps, jdbcPosition, this);
          }

          sqlControl.executeStatementUpdate(ec, mconn, clearStmt, ps, true);
        } finally {
          sqlControl.closeStatement(mconn, ps);
        }
      } finally {
        mconn.release();
      }
    } catch (SQLException e) {
      throw new NucleusDataStoreException(Localiser.msg("056013", clearStmt), e);
    }

    // Cascade-delete
    if (dependentElements != null && dependentElements.size() > 0) {
      Iterator iter = dependentElements.iterator();
      while (iter.hasNext()) {
        Object obj = iter.next();
        if (ownerOP.getExecutionContext().getApiAdapter().isDeleted(obj)) {
          // Element is tagged for deletion so will be deleted at flush(), and we dont need it
          // immediately
        } else {
          ownerOP.getExecutionContext().deleteObjectInternal(obj);
        }
      }
    }
  }
Ejemplo n.º 16
0
  /**
   * Convenience method to create a new PreparedStatement for a query.
   *
   * @param conn The Connection to use for the statement
   * @param stmtText Statement text
   * @param resultSetType Type of result set
   * @param resultSetConcurrency Concurrency for the result set
   * @return The PreparedStatement
   * @throws SQLException thrown if an error occurs creating the statement
   */
  public PreparedStatement getStatementForQuery(
      ManagedConnection conn, String stmtText, String resultSetType, String resultSetConcurrency)
      throws SQLException {
    Connection c = (Connection) conn.getConnection();
    if (supportsBatching) {
      // Check for a waiting batched statement that is ready for processing
      ConnectionStatementState state = getConnectionStatementState(conn);
      if (state != null && state.processable) {
        // Process the batch statement before returning our new query statement
        processConnectionStatement(conn);
      }
    }

    // Create a new PreparedStatement for this query
    PreparedStatement ps = null;
    if (resultSetType != null || resultSetConcurrency != null) {
      int rsTypeValue = ResultSet.TYPE_FORWARD_ONLY;
      if (resultSetType != null) {
        if (resultSetType.equals("scroll-sensitive")) {
          rsTypeValue = ResultSet.TYPE_SCROLL_SENSITIVE;
        } else if (resultSetType.equals("scroll-insensitive")) {
          rsTypeValue = ResultSet.TYPE_SCROLL_INSENSITIVE;
        }
      }

      int rsConcurrencyValue = ResultSet.CONCUR_READ_ONLY;
      if (resultSetConcurrency != null && resultSetConcurrency.equals("updateable")) {
        rsConcurrencyValue = ResultSet.CONCUR_UPDATABLE;
      }
      ps = c.prepareStatement(stmtText, rsTypeValue, rsConcurrencyValue);
      ps
          .clearBatch(); // In case using statement caching and given one with batched statements
                         // left hanging (C3P0)
    } else {
      ps = c.prepareStatement(stmtText);
      ps
          .clearBatch(); // In case using statement caching and given one with batched statements
                         // left hanging (C3P0)
    }

    if (queryTimeout > 0) {
      // Apply any query timeout
      ps.setQueryTimeout(queryTimeout / 1000); // queryTimeout is in milliseconds
    }
    if (NucleusLogger.DATASTORE.isDebugEnabled()) {
      NucleusLogger.DATASTORE.debug(LOCALISER.msg("052110", StringUtils.toJVMIDString(ps)));
    }

    if (!jdbcStatements) {
      // Wrap with our parameter logger
      ps = new ParamLoggingPreparedStatement(ps, stmtText);
      ((ParamLoggingPreparedStatement) ps).setParamsInAngleBrackets(paramValuesInBrackets);
    }

    return ps;
  }
  /**
   * This method requires synchronization so that we don't end up registering the same property more
   * than once.
   */
  @Override
  protected synchronized StoreData newStoreData(ClassMetaData cmd, ClassLoaderResolver clr) {
    InheritanceStrategy strat = cmd.getInheritanceMetaData().getStrategy();

    // The overarching rule for supported inheritance strategies is that we
    // don't split the state of an object across multiple entities.
    // TODO This is all nonsense. This datastore only allows "COMPLETE_TABLE" really so ignore the
    // inheritance
    // and remove the need for DatastoreClass
    if (strat == InheritanceStrategy.SUBCLASS_TABLE) {
      // Table mapped into the table(s) of subclass(es)
      // Just add the SchemaData entry with no table - managed by subclass
      return buildStoreDataWithNoTable(cmd);
    } else if (strat == InheritanceStrategy.COMPLETE_TABLE) {
      if (cmd.isAbstract()) {
        // Abstract class with "complete-table" so gets no table
        return buildStoreDataWithNoTable(cmd);
      }
      return buildStoreData(cmd, clr);
    } else if (strat == InheritanceStrategy.NEW_TABLE
        && (cmd.getSuperAbstractClassMetaData() == null
            || cmd.getSuperAbstractClassMetaData().getInheritanceMetaData().getStrategy()
                == InheritanceStrategy.SUBCLASS_TABLE)) {
      // New Table means you store your fields and your fields only (no fields from superclasses).
      // This only ok if you don't have a persistent superclass or your persistent superclass has
      // delegated responsibility for storing its fields to you.
      return buildStoreData(cmd, clr);
    } else if (MetaDataUtils.isNewOrSuperclassTableInheritanceStrategy(cmd)) {
      // Table mapped into table of superclass
      // Find the superclass - should have been created first
      AbstractClassMetaData[] managingCmds = getClassesManagingTableForClass(cmd, clr);
      DatastoreTable superTable;
      if (managingCmds != null && managingCmds.length == 1) {
        MappedStoreData superData =
            (MappedStoreData) storeDataMgr.get(managingCmds[0].getFullClassName());
        if (superData != null) {
          // Specify the table if it already exists
          superTable = (DatastoreTable) superData.getDatastoreContainerObject();
          return buildStoreDataWithTable(cmd, superTable);
        }
      }
    }

    // TODO Don't do this. GAE basically supports "complete-table" always so we should just ignore
    // any
    // inheritance metadata that implies otherwise.
    boolean jpa = getApiAdapter().getName().equalsIgnoreCase("JPA");
    String unsupportedMsg =
        GAE_LOCALISER.msg(
            jpa ? "AppEngine.BadInheritance.JPA" : "AppEngine.BadInheritance.JDO",
            cmd.getInheritanceMetaData().getStrategy().toString(),
            cmd.getFullClassName(),
            getApiAdapter().getName());
    throw new UnsupportedInheritanceStrategyException(unsupportedMsg);
  }
Ejemplo n.º 18
0
  public void registerExtensions() {
    if (extensionPoints.length > 0) {
      return;
    }
    List registeringExtensions = new ArrayList();

    BundleContext ctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext();

    // parse the plugin files
    DocumentBuilder docBuilder = OSGiBundleParser.getDocumentBuilder();
    org.osgi.framework.Bundle[] osgiBundles = ctx.getBundles();
    for (org.osgi.framework.Bundle osgiBundle : osgiBundles) {
      URL pluginURL = osgiBundle.getEntry("plugin.xml");

      if (pluginURL == null) {
        continue;
      }

      Bundle bundle = registerBundle(osgiBundle);
      if (bundle == null) {
        // No MANIFEST.MF for this plugin.xml so ignore it
        continue;
      }

      List[] elements =
          OSGiBundleParser.parsePluginElements(docBuilder, this, pluginURL, bundle, osgiBundle);
      registerExtensionPointsForPluginInternal(elements[0], false);
      registeringExtensions.addAll(elements[1]);
    }
    extensionPoints =
        extensionPointsByUniqueId
            .values()
            .toArray(new ExtensionPoint[extensionPointsByUniqueId.values().size()]);

    // Register the extensions now that we have the extension-points all loaded
    for (int i = 0; i < registeringExtensions.size(); i++) {
      Extension extension = (Extension) registeringExtensions.get(i);
      ExtensionPoint exPoint = getExtensionPoint(extension.getExtensionPointId());
      if (exPoint == null) {
        if (extension.getPlugin() != null
            && extension.getPlugin().getSymbolicName() != null
            && extension.getPlugin().getSymbolicName().startsWith(DATANUCLEUS_PKG)) {
          NucleusLogger.GENERAL.warn(
              Localiser.msg(
                  "024002",
                  extension.getExtensionPointId(),
                  extension.getPlugin().getSymbolicName(),
                  extension.getPlugin().getManifestLocation()));
        }
      } else {
        extension.setExtensionPoint(exPoint);
        exPoint.addExtension(extension);
      }
    }
  }
  /* (non-Javadoc)
   * @see org.datanucleus.store.rdbms.sql.method.SQLMethod#getExpression(org.datanucleus.store.rdbms.sql.expression.SQLExpression, java.util.List)
   */
  public SQLExpression getExpression(SQLExpression expr, List<SQLExpression> args) {
    if (expr == null) {
      if (args != null && args.size() > 0) {
        throw new NucleusException("COUNTSTAR takes no argument");
      }

      return new AggregateNumericExpression(stmt, getMappingForClass(long.class), "COUNT(*)");
    }

    throw new NucleusException(Localiser.msg("060002", "COUNT", expr));
  }
Ejemplo n.º 20
0
  /**
   * Constructor.
   *
   * @param tableName The Table SQL identifier
   * @param mmd Member meta data for the owner field/property
   * @param storeMgr Manager for the datastore.
   */
  protected JoinTable(
      DatastoreIdentifier tableName, AbstractMemberMetaData mmd, RDBMSStoreManager storeMgr) {
    super(tableName, storeMgr);

    this.mmd = mmd;
    this.ownerType = mmd.getClassName(true);

    if (mmd.getPersistenceModifier() == FieldPersistenceModifier.NONE) {
      throw new NucleusException(Localiser.msg("057006", mmd.getName())).setFatal();
    }
  }
 /*
  * (non-Javadoc)
  * @see
  * org.datanucleus.store.rdbms.mapping.datastore.AbstractDatastoreMapping#setObject(java.sql.PreparedStatement, int, java.lang.Object)
  */
 @Override
 public void setObject(PreparedStatement ps, int param, Object value) {
   try {
     if (value == null) {
       ps.setNull(param, Types.LONGVARBINARY);
     } else if (value instanceof File) {
       File file = (File) value;
       ps.setBinaryStream(param, new FileInputStream(file), (int) file.length());
     } else {
       // TODO Support other types
       throw new NucleusDataStoreException(
           "setObject unsupported for java type " + value.getClass().getName());
     }
   } catch (SQLException e) {
     throw new NucleusDataStoreException(
         Localiser.msg("055001", "Object", "" + value, column, e.getMessage()), e);
   } catch (IOException e) {
     throw new NucleusDataStoreException(
         Localiser.msg("055001", "Object", "" + value, column, e.getMessage()), e);
   }
 }
Ejemplo n.º 22
0
  /**
   * Method to remove a collection of elements from the List.
   *
   * @param elements Collection of elements to remove
   * @return Whether it was successful.
   */
  public boolean removeAll(Collection elements) {
    makeDirty();

    if (useCache) {
      loadFromStore();
    }

    int size = (useCache ? delegate.size() : -1);
    Collection contained = null;
    if (backingStore != null && SCOUtils.useQueuedUpdate(queued, ownerOP)) {
      // Check which are contained before updating the delegate
      contained = new java.util.HashSet();
      for (Object elem : elements) {
        if (contains(elem)) {
          contained.add(elem);
        }
      }
    }
    boolean delegateSuccess = delegate.removeAll(elements);

    if (backingStore != null) {
      boolean backingSuccess = true;
      if (SCOUtils.useQueuedUpdate(queued, ownerOP)) {
        backingSuccess = false;
        for (Object element : contained) {
          backingSuccess = true;
          ownerOP
              .getExecutionContext()
              .addOperationToQueue(
                  new CollectionRemoveOperation(ownerOP, backingStore, element, true));
        }
      } else {
        try {
          backingSuccess = backingStore.removeAll(ownerOP, elements, size);
        } catch (NucleusDataStoreException dse) {
          NucleusLogger.PERSISTENCE.warn(
              Localiser.msg("023013", "removeAll", ownerMmd.getName(), dse));
          backingSuccess = false;
        }
      }

      if (ownerOP != null && !ownerOP.getExecutionContext().getTransaction().isActive()) {
        ownerOP.getExecutionContext().processNontransactionalUpdate();
      }

      return backingSuccess;
    }

    if (ownerOP != null && !ownerOP.getExecutionContext().getTransaction().isActive()) {
      ownerOP.getExecutionContext().processNontransactionalUpdate();
    }
    return delegateSuccess;
  }
Ejemplo n.º 23
0
 /** Method to initialise the SCO for use. */
 public void initialise() {
   initialiseDelegate();
   if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
     NucleusLogger.PERSISTENCE.debug(
         LOCALISER.msg(
             "023003",
             ownerOP.getObjectAsPrintable(),
             ownerMmd.getName(),
             "" + size(),
             SCOUtils.getSCOWrapperOptionsMessage(true, false, false, false)));
   }
 }
Ejemplo n.º 24
0
/** Evaluator for the method "{listExpr}.get(idxExpr)". */
public class ListGetMethodEvaluator implements InvocationEvaluator {
  /** Localisation utility for output messages */
  protected static final Localiser LOCALISER =
      Localiser.getInstance(
          "org.datanucleus.Localisation", org.datanucleus.ClassConstants.NUCLEUS_CONTEXT_LOADER);

  /* (non-Javadoc)
   * @see org.datanucleus.query.evaluator.memory.InvocationEvaluator#evaluate(org.datanucleus.query.expression.InvokeExpression, org.datanucleus.query.evaluator.memory.InMemoryExpressionEvaluator)
   */
  public Object evaluate(
      InvokeExpression expr, Object invokedValue, InMemoryExpressionEvaluator eval) {
    String method = expr.getOperation();

    if (invokedValue == null) {
      return null;
    }
    if (!(invokedValue instanceof List)) {
      throw new NucleusException(
          LOCALISER.msg("021011", method, invokedValue.getClass().getName()));
    }

    Object param = expr.getArguments().get(0);
    Object paramValue = null;
    if (param instanceof Literal) {
      paramValue = ((Literal) param).getLiteral();
    } else if (param instanceof PrimaryExpression) {
      PrimaryExpression primExpr = (PrimaryExpression) param;
      paramValue = eval.getValueForPrimaryExpression(primExpr);
    } else if (param instanceof ParameterExpression) {
      ParameterExpression paramExpr = (ParameterExpression) param;
      paramValue = QueryUtils.getValueForParameterExpression(eval.getParameterValues(), paramExpr);
    } else if (param instanceof VariableExpression) {
      VariableExpression varExpr = (VariableExpression) param;
      try {
        paramValue = eval.getValueForVariableExpression(varExpr);
      } catch (VariableNotSetException vnse) {
        // Throw an exception with the possible values of elements
        throw new VariableNotSetException(varExpr, ((List) invokedValue).toArray());
      }
    } else {
      throw new NucleusException(
          "Dont currently support use of get(" + param.getClass().getName() + ")");
    }

    int paramInt;
    if (paramValue instanceof Number) {
      paramInt = ((Number) paramValue).intValue();
    } else {
      throw new NucleusException("List.get() should take in an integer but is " + paramValue);
    }
    return ((List) invokedValue).get(paramInt);
  }
}
 /* (non-Javadoc)
  * @see org.datanucleus.store.rdbms.sql.method.SQLMethod#getExpression(org.datanucleus.store.rdbms.sql.expression.SQLExpression, java.util.List)
  */
 public SQLExpression getExpression(SQLExpression expr, List<SQLExpression> args) {
   if (!expr.isParameter() && expr instanceof StringLiteral) {
     JavaTypeMapping m = exprFactory.getMappingForType(int.class, false);
     String val = (String) ((StringLiteral) expr).getValue();
     return new IntegerLiteral(stmt, m, Integer.valueOf(val.length()), null);
   } else if (expr instanceof StringExpression || expr instanceof ParameterLiteral) {
     ArrayList funcArgs = new ArrayList();
     funcArgs.add(expr);
     return new NumericExpression(stmt, getMappingForClass(int.class), "CHAR_LENGTH", funcArgs);
   } else {
     throw new NucleusException(Localiser.msg("060001", "length", expr));
   }
 }
Ejemplo n.º 26
0
  /**
   * Convenience method to apply the user specification of &lt;primary-key&gt; columns
   *
   * @param pkmd MetaData for the primary key
   */
  protected void applyUserPrimaryKeySpecification(PrimaryKeyMetaData pkmd) {
    ColumnMetaData[] pkCols = pkmd.getColumnMetaData();
    for (int i = 0; i < pkCols.length; i++) {
      String colName = pkCols[i].getName();
      boolean found = false;
      for (int j = 0; j < ownerMapping.getNumberOfDatastoreMappings(); j++) {
        if (ownerMapping
            .getDatastoreMapping(j)
            .getColumn()
            .getIdentifier()
            .getName()
            .equals(colName)) {
          ownerMapping.getDatastoreMapping(j).getColumn().setPrimaryKey();
          found = true;
        }
      }

      if (!found) {
        for (int j = 0; j < keyMapping.getNumberOfDatastoreMappings(); j++) {
          if (keyMapping
              .getDatastoreMapping(j)
              .getColumn()
              .getIdentifier()
              .getName()
              .equals(colName)) {
            keyMapping.getDatastoreMapping(j).getColumn().setPrimaryKey();
            found = true;
          }
        }
      }

      if (!found) {
        for (int j = 0; j < valueMapping.getNumberOfDatastoreMappings(); j++) {
          if (valueMapping
              .getDatastoreMapping(j)
              .getColumn()
              .getIdentifier()
              .getName()
              .equals(colName)) {
            valueMapping.getDatastoreMapping(j).getColumn().setPrimaryKey();
            found = true;
          }
        }
      }

      if (!found) {
        throw new NucleusUserException(Localiser.msg("057040", toString(), colName));
      }
    }
  }
Ejemplo n.º 27
0
  /** Method to load all elements from the "backing store" where appropriate. */
  protected void loadFromStore() {
    if (backingStore != null && !isCacheLoaded) {
      if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
        NucleusLogger.PERSISTENCE.debug(
            Localiser.msg("023006", ownerOP.getObjectAsPrintable(), ownerMmd.getName()));
      }
      delegate.clear();

      // Populate the delegate with the keys/values from the store
      SCOUtils.populateMapDelegateWithStoreData(delegate, backingStore, ownerOP);

      isCacheLoaded = true;
    }
  }
Ejemplo n.º 28
0
  /** Method to load all elements from the "backing store" where appropriate. */
  protected void loadFromStore() {
    if (backingStore != null && !isCacheLoaded) {
      if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
        NucleusLogger.PERSISTENCE.debug(
            Localiser.msg("023006", ownerOP.getObjectAsPrintable(), ownerMmd.getName()));
      }
      delegate.clear();
      Iterator iter = backingStore.iterator(ownerOP);
      while (iter.hasNext()) {
        delegate.add(iter.next());
      }

      isCacheLoaded = true;
    }
  }
Ejemplo n.º 29
0
  /* (non-Javadoc)
   * @see org.datanucleus.query.evaluator.memory.InvocationEvaluator#evaluate(org.datanucleus.query.expression.InvokeExpression, org.datanucleus.query.evaluator.memory.InMemoryExpressionEvaluator)
   */
  public Object evaluate(
      InvokeExpression expr, Object invokedValue, InMemoryExpressionEvaluator eval) {
    String method = expr.getOperation();

    if (invokedValue == null) {
      return Boolean.FALSE;
    }
    if (!(invokedValue instanceof Date)) {
      throw new NucleusException(
          Localiser.msg("021011", method, invokedValue.getClass().getName()));
    }

    Calendar cal = Calendar.getInstance();
    cal.setTime((Date) invokedValue);
    return Integer.valueOf(cal.get(Calendar.MONTH));
  }
  /**
   * Convenience method to retrieve field values from an L2 cached object if they are loaded in that
   * object. If the object is not in the L2 cache then just returns, and similarly if the required
   * fields aren't available.
   *
   * @param fieldNumbers Numbers of fields to load from the L2 cache
   * @return The fields that couldn't be loaded
   */
  protected int[] loadFieldsFromLevel2Cache(int[] fieldNumbers) {
    // Only continue if there are fields, and not being deleted/flushed etc
    if (fieldNumbers == null
        || fieldNumbers.length == 0
        || myEC.isFlushing()
        || myLC.isDeleted()
        || isDeleting()
        || getExecutionContext().getTransaction().isCommitting()) {
      return fieldNumbers;
    }
    // TODO Drop this check when we're confident that this doesn't affect some use-cases
    if (!myEC.getNucleusContext()
        .getConfiguration()
        .getBooleanProperty(PropertyNames.PROPERTY_CACHE_L2_LOADFIELDS, true)) {
      return fieldNumbers;
    }

    Level2Cache l2cache = myEC.getNucleusContext().getLevel2Cache();
    if (l2cache != null && myEC.getNucleusContext().isClassCacheable(cmd)) {
      CachedPC<T> cachedPC = l2cache.get(myID);
      if (cachedPC != null) {
        int[] cacheFieldsToLoad =
            ClassUtils.getFlagsSetTo(cachedPC.getLoadedFields(), fieldNumbers, true);
        if (cacheFieldsToLoad != null && cacheFieldsToLoad.length > 0) {
          if (NucleusLogger.CACHE.isDebugEnabled()) {
            NucleusLogger.CACHE.debug(
                Localiser.msg(
                    "026034",
                    StringUtils.toJVMIDString(getObject()),
                    myID,
                    StringUtils.intArrayToString(cacheFieldsToLoad)));
          }

          L2CacheRetrieveFieldManager l2RetFM = new L2CacheRetrieveFieldManager(this, cachedPC);
          this.replaceFields(cacheFieldsToLoad, l2RetFM);
          int[] fieldsNotLoaded = l2RetFM.getFieldsNotLoaded();
          if (fieldsNotLoaded != null) {
            for (int i = 0; i < fieldsNotLoaded.length; i++) {
              loadedFields[fieldsNotLoaded[i]] = false;
            }
          }
        }
      }
    }

    return ClassUtils.getFlagsSetTo(loadedFields, fieldNumbers, false);
  }