/**
   * Reset the commit order from the session's descriptors. This uses the constraint dependencies in
   * the descriptor's mappings, to decide which descriptors are dependent on which other
   * descriptors. Multiple computations of the commit order should produce the same ordering. This
   * is done to improve performance on unit of work writes through decreasing the stack size, and
   * acts as a deadlock avoidance mechanism.
   */
  public void initializeCommitOrder() {
    Vector descriptors = Helper.buildVectorFromMapElements(getSession().getDescriptors());

    // Must ensure uniqueness, some descriptor my be register twice for interfaces.
    descriptors = Helper.addAllUniqueToVector(new Vector(descriptors.size()), descriptors);
    Object[] descriptorsArray = new Object[descriptors.size()];
    for (int index = 0; index < descriptors.size(); index++) {
      descriptorsArray[index] = descriptors.elementAt(index);
    }
    Arrays.sort(descriptorsArray, new DescriptorCompare());
    descriptors = new Vector(descriptors.size());
    for (int index = 0; index < descriptorsArray.length; index++) {
      descriptors.addElement(descriptorsArray[index]);
    }

    CommitOrderCalculator calculator = new CommitOrderCalculator(getSession());
    calculator.addNodes(descriptors);
    calculator.calculateMappingDependencies();
    calculator.orderCommits();
    descriptors = calculator.getOrderedDescriptors();

    calculator = new CommitOrderCalculator(getSession());
    calculator.addNodes(descriptors);
    calculator.calculateSpecifiedDependencies();
    calculator.orderCommits();

    setCommitOrder(calculator.getOrderedClasses());
  }
  public void setup() {
    if (getSession().getPlatform().isDB2()) {
      throw new TestWarningException(
          "This test is not supposed to work with DB2. "
              + org.eclipse.persistence.internal.helper.Helper.cr()
              + "\t\tBecause as expected, sql string contains (t0.F_NAME = NULL) when the query is executed the second time with argument null, and '=NULL' is illegal syntax on DB2."
              + org.eclipse.persistence.internal.helper.Helper.cr()
              + "\t\tHence, executing the query would result in runtime exception.");
    }
    query =
        (ReadObjectQuery)
            getSession()
                .getDescriptor(
                    org.eclipse.persistence.testing.models.employee.domain.Employee.class)
                .getQueryManager()
                .getQuery("shouldPrepareQuery");

    queryCopy = (ReadObjectQuery) query.clone();
    ExpressionBuilder ex = new ExpressionBuilder();
    queryCopy.setSelectionCriteria(ex.get("firstName").equal(ex.getParameter("firstName1")));
    queryCopy.addArgument("firstName1");

    vec = new Vector();
    vec.add("Bob");
    getSession().executeQuery(queryCopy, vec);
  }
  public void test() {
    try {
      test1ResultIsTrue = Helper.compareCharArrays(array1, array2);
      test2ResultIsTrue = Helper.compareCharArrays(array1, array3);

    } catch (Exception e) {
      this.e = e;
      throw new TestErrorException(
          "An exception should not have been thrown when comparing char array content.");
    }
  }
  /**
   * INTERNAL: Those objects that need/want to initialize more meta data should override this
   * method.
   */
  public DatabaseField getDatabaseField() {
    // Initialize the DatabaseField with values and defaults.
    DatabaseField databaseField = new DatabaseField();

    databaseField.setName(
        m_name == null ? "" : m_name,
        Helper.getDefaultStartDatabaseDelimiter(),
        Helper.getDefaultEndDatabaseDelimiter());
    databaseField.setColumnDefinition(m_columnDefinition == null ? "" : m_columnDefinition);

    return databaseField;
  }
  /**
   * INTERNAL: This method perform all necessary steps(verification, pre-build the target directory)
   * prior to the invocation of the weaving function.
   */
  private void preProcess() throws URISyntaxException, MalformedURLException {
    // Instantiate default session log
    AbstractSessionLog.getLog().setLevel(this.logLevel);
    if (logWriter != null) {
      ((DefaultSessionLog) AbstractSessionLog.getLog()).setWriter(logWriter);
    }

    // Make sure the source is existing
    if (!(new File(Helper.toURI(source)).exists())) {
      throw StaticWeaveException.missingSource();
    }

    URI targetURI = Helper.toURI(target);
    // Verification target and source, two use cases create warning or exception.
    // 1. If source is directory and target is jar -
    //   This will lead unknown outcome, user attempt to use this tool to pack outcome into a Jar.
    //   Warning message will be logged, this is can be worked around by other utilities.
    // 2. Both source and target are specified as a same jar -
    //   User was trying to perform weaving in same Jar which is not supported, an Exception will be
    // thrown.
    if (isDirectory(source) && targetURI.toString().endsWith(".jar")) {
      AbstractSessionLog.getLog()
          .log(
              SessionLog.WARNING,
              ToStringLocalization.buildMessage(
                  "staticweave_processor_unknown_outcome", new Object[] {null}));
    }

    if (!isDirectory(source) && target.toString().equals(source.toString())) {
      throw StaticWeaveException.weaveInplaceForJar(source.toString());
    }

    // pre-create target if it is directory and dose not exist.
    // Using the method File.isDirectory() is not enough to determine what the type(dir or jar)
    // of the target(specified by URL)that user want to create. File.isDirectory() will return false
    // in
    // two possibilities, the location either is not directory or the location dose not exist.
    // Therefore pre-build of the directory target is required. Pre-build for the file(JAR) target
    // is not required since it gets built automatically by opening outputstream.
    if (!(new File(targetURI)).exists()) {
      if (!targetURI.toString().endsWith(".jar")) {
        (new File(targetURI)).mkdirs();
        // if directory fails to build, which may leads to unknown outcome since it will
        // be treated as single file in the class StaticWeaveHandler and automatically gets built
        // by outputstream.

        // re-assign URL.
        target = (new File(targetURI)).toURL();
      }
    }
  }
  /** INTERNAL: Note: the order of calls in this method are important. */
  protected void setFieldName(DatabaseField field, String defaultName, String context) {
    // This may set the use delimited identifier flag to true.
    field.setName(
        getName(field, defaultName, context),
        Helper.getDefaultStartDatabaseDelimiter(),
        Helper.getDefaultEndDatabaseDelimiter());

    // The check is necessary to avoid overriding a true setting (set after
    // setting the name of the field). We don't want to override it at this
    // point if the global flag is set to false.
    if (useDelimitedIdentifier()) {
      field.setUseDelimiters(useDelimitedIdentifier());
    }
  }
  /** INTERNAL: Visit an executable and create a MetadataMethod object. */
  @Override
  public MetadataMethod visitExecutable(
      ExecutableElement executableElement, MetadataClass metadataClass) {
    MetadataMethod method = new MetadataMethod(metadataClass.getMetadataFactory(), metadataClass);

    // Set the name.
    method.setName(executableElement.getSimpleName().toString());

    // Set the attribute name.
    method.setAttributeName(Helper.getAttributeNameFromMethodName(method.getName()));

    // Set the modifiers.
    method.setModifiers(getModifiers(executableElement.getModifiers()));

    // Visit executable element for the parameters, return type and generic type.
    executableElement.asType().accept(typeVisitor, method);

    // Set the annotations.
    buildMetadataAnnotations(method, executableElement.getAnnotationMirrors());

    // Handle multiple methods with the same name.
    MetadataMethod existing = metadataClass.getMethods().get(method.getName());
    if (existing == null) {
      metadataClass.addMethod(method);
    } else {
      while (existing.getNext() != null) {
        existing = existing.getNext();
      }
      existing.setNext(method);
    }

    return method;
  }
Beispiel #8
0
 /**
  * Returns a String that represents the value of this object.
  *
  * @return a string representation of the receiver
  */
 public String toString() {
   return org.eclipse.persistence.internal.helper.Helper.getShortClassName(this.getClass())
       + ": "
       + this.getFirstName()
       + " "
       + this.getLastName();
 }
 @Override
 public String toString() {
   return org.eclipse.persistence.internal.helper.Helper.getShortClassName(getClass())
       + "("
       + getName()
       + ") ";
 }
 /**
  * Ensure the value being set is supported by the mapping. If the mapping is direct/basic and the
  * mapping's type is primitive ensure the non-primitive type is allowed.
  */
 public void checkSet(String propertyName, Object value) throws DynamicException {
   DatabaseMapping mapping = getMapping(propertyName);
   if (value == null) {
     if (mapping.isCollectionMapping()
         || (mapping.getAttributeClassification() != null
             && mapping.getAttributeClassification().isPrimitive())) {
       throw DynamicException.invalidSetPropertyType(mapping, value);
     }
     return;
   }
   Class<?> expectedType = mapping.getAttributeClassification();
   if (mapping.isForeignReferenceMapping()) {
     if (mapping.isCollectionMapping()) {
       if (((CollectionMapping) mapping).getContainerPolicy().isMapPolicy()) {
         expectedType = Map.class;
       } else {
         expectedType = Collection.class;
       }
     } else {
       expectedType = ((ForeignReferenceMapping) mapping).getReferenceClass();
     }
   }
   if (expectedType != null && expectedType.isPrimitive() && !value.getClass().isPrimitive()) {
     expectedType = Helper.getObjectClass(expectedType);
   }
   if (expectedType != null && !expectedType.isAssignableFrom(value.getClass())) {
     throw DynamicException.invalidSetPropertyType(mapping, value);
   }
 }
 /** Return any tables that are defined by this expression (and not its base). */
 @Override
 public List<DatabaseTable> getOwnedTables() {
   ClassDescriptor descriptor = getDescriptor();
   List<DatabaseTable> tables = null;
   if (descriptor == null) {
     List additionalTables = getAdditionalTables();
     if (additionalTables == null) {
       return null;
     } else {
       return new ArrayList(additionalTables);
     }
   } else if (descriptor.isAggregateDescriptor()) {
     return null;
   } else if ((descriptor.getHistoryPolicy() != null)
       && (getAsOfClause() != null && getAsOfClause().getValue() != null)) {
     tables = descriptor.getHistoryPolicy().getHistoricalTables();
   } else if (isUsingOuterJoinForMultitableInheritance()) {
     tables = descriptor.getInheritancePolicy().getAllTables();
   } else {
     tables = descriptor.getTables();
   }
   List additionalTables = getAdditionalTables();
   if (additionalTables != null) {
     tables = new Vector(tables);
     Helper.addAllUniqueToList(tables, additionalTables);
     return tables;
   }
   return tables;
 }
  /** INTERNAL: */
  public String toString() {
    StringWriter writer = new StringWriter();
    writer.write(Helper.getShortClassName(getClass()));
    writer.write("(");

    for (int index = 0; index < getFields().size(); index++) {
      writer.write(Helper.cr());
      writer.write("\t");
      writer.write(String.valueOf((getFields().elementAt(index))));
      writer.write(" => ");
      writer.write(String.valueOf((getValues().elementAt(index))));
    }
    writer.write(")");

    return writer.toString();
  }
  /** INTERNAL: Return the type for a specified implementor */
  protected Object getTypeForImplementor(Class implementor) {
    Object type = getTypeIndicatorTranslation().get(implementor);
    if (type == Helper.getNullWrapper()) {
      type = null;
    }

    return type;
  }
  /** PUBLIC: Add a type indicator conversion to this mapping. */
  public void addClassIndicator(Class implementer, Object typeIndicator) {
    if (typeIndicator == null) {
      typeIndicator = Helper.getNullWrapper();
    }

    getTypeIndicatorTranslation().put(implementer, typeIndicator);
    getTypeIndicatorTranslation().put(typeIndicator, implementer);
  }
  /**
   * INTERNAL: Extract the direct values from the specified field value. Return them in a vector.
   * The field value better be an Array.
   */
  public Vector buildDirectValuesFromFieldValue(Object fieldValue) throws DatabaseException {

    if (fieldValue == null) {
      return null;
    }

    return Helper.vectorFromArray((Object[]) fieldValue);
  }
 /** Determine whether or not the URL is pointing to directory. */
 private boolean isDirectory(URL url) throws URISyntaxException {
   File file = new File(Helper.toURI(url));
   if (file.isDirectory()) {
     return true;
   } else {
     return false;
   }
 }
 /** Return the string for logging purposes. */
 public String getLogString(Accessor accessor) {
   StringWriter writer = new StringWriter();
   writer.write("Executing ");
   writer.write(toString());
   writer.write(Helper.cr());
   writer.write("\tspec => ");
   writer.write(String.valueOf(getInteractionSpec()));
   writer.write(Helper.cr());
   writer.write("\tproperties => ");
   writer.write(String.valueOf(getProperties()));
   writer.write(Helper.cr());
   writer.write("\txml => ");
   Element dom = createInputDOM((EISAccessor) accessor);
   EISDOMRecord record = new EISDOMRecord(dom);
   record.transformToWriter(writer);
   return writer.toString();
 }
 public void printClasses(List classes) {
   for (Iterator iterator = classes.iterator(); iterator.hasNext(); ) {
     System.out.print(
         org.eclipse.persistence.internal.helper.Helper.getShortClassName(
             (Class) iterator.next()));
     System.out.print(", ");
   }
   System.out.println(":");
 }
 /**
  * INTERNAL: Appends an Oracle specific Timestamp, if usesNativeSQL is true otherwise use the ODBC
  * format. Native Format: to_timestamp ('1997-11-06 10:35:45.656' , 'yyyy-mm-dd hh:mm:ss.ff')
  */
 protected void appendTimestamp(java.sql.Timestamp timestamp, Writer writer) throws IOException {
   if (usesNativeSQL()) {
     writer.write("to_timestamp('");
     writer.write(Helper.printTimestamp(timestamp));
     writer.write("','yyyy-mm-dd HH24:MI:SS.FF')");
   } else {
     super.appendTimestamp(timestamp, writer);
   }
 }
 /** Return a house policy with null values for its Ref and nested table fields. For bug 2730536 */
 public static HousePolicy example3() {
   HousePolicy housePolicy = new HousePolicy();
   housePolicy.setPolicyNumber(783);
   housePolicy.setDescription("vacant home.");
   housePolicy.setDateOfConstruction(Helper.dateFromString("1997/06/10"));
   housePolicy.setMaxCoverage(50000);
   housePolicy.setDescription("Fire and flood coverage");
   return housePolicy;
 }
  public void test() {
    try {
      test1ResultIsTrue = Helper.classIsSubclass(LargeProject.class, null);

    } catch (Exception e) {
      this.e = e;
      throw new TestErrorException(
          "An exception should not have been thrown when checking for status as a subclass when superclass is null.");
    }
  }
 /** Return an example claim instance. */
 public static HousePolicy example2() {
   HousePolicy housePolicy = new HousePolicy();
   housePolicy.setPolicyNumber(102);
   housePolicy.setDescription("Nice house.");
   housePolicy.setDateOfConstruction(Helper.dateFromString("1997/06/12"));
   housePolicy.setMaxCoverage(11111);
   housePolicy.setDescription("Theft Coverage");
   housePolicy.addClaim(HouseClaim.example3());
   return housePolicy;
 }
 /** Return an example claim instance. */
 public static HousePolicy example1() {
   HousePolicy housePolicy = new HousePolicy();
   housePolicy.setPolicyNumber(101);
   housePolicy.setDescription("Nice house.");
   housePolicy.setDateOfConstruction(Helper.dateFromString("1997/06/10"));
   housePolicy.setMaxCoverage(50000);
   housePolicy.setDescription("Fire and flood coverage");
   housePolicy.addClaim(HouseClaim.example1());
   housePolicy.addClaim(HouseClaim.example2());
   return housePolicy;
 }
 public String toString() {
   if (isInstantiated()) {
     return "{" + getValue() + "}";
   } else {
     return "{"
         + Helper.getShortClassName(getClass())
         + ": "
         + ToStringLocalization.buildMessage("not_instantiated", (Object[]) null)
         + "}";
   }
 }
 /**
  * INTERNAL: Build the appropriate field value for the specified set of direct values. The
  * database better be expecting an ARRAY.
  */
 public Object buildFieldValueFromDirectValues(
     Vector directValues, String elementDataTypeName, AbstractSession session)
     throws DatabaseException {
   Object[] fields = Helper.arrayFromVector(directValues);
   try {
     ((DatabaseAccessor) session.getAccessor()).incrementCallCount(session);
     java.sql.Connection connection = ((DatabaseAccessor) session.getAccessor()).getConnection();
     return session.getPlatform().createArray(elementDataTypeName, fields, session, connection);
   } catch (java.sql.SQLException ex) {
     throw DatabaseException.sqlException(ex, session, false);
   } finally {
     ((DatabaseAccessor) session.getAccessor()).decrementCallCount();
   }
 }
  /** INTERNAL: Return the implementor for a specified type */
  protected Object getImplementorForType(Object type, AbstractSession session) {
    if (type == null) {
      return getTypeIndicatorTranslation().get(Helper.getNullWrapper());
    }

    // Must ensure the type is the same, i.e. Integer != BigDecimal.
    try {
      type = session.getDatasourcePlatform().convertObject(type, getTypeField().getType());
    } catch (ConversionException e) {
      throw ConversionException.couldNotBeConverted(this, getDescriptor(), e);
    }

    return getTypeIndicatorTranslation().get(type);
  }
 /** INTERNAL: */
 protected synchronized void initializeConnectionData(Connection conn) throws SQLException {
   if (isConnectionDataInitialized) {
     return;
   }
   driverVersion = conn.getMetaData().getDriverVersion();
   // printCalendar for versions greater or equal 9 and less than 10.2.0.4
   shouldPrintCalendar =
       Helper.compareVersions("9", driverVersion) <= 0
           && Helper.compareVersions(driverVersion, "10.2.0.4") < 0;
   if (Helper.compareVersions(driverVersion, "11.1.0.7") < 0) {
     isTimestampInGmt = false;
   } else {
     if (conn instanceof OracleConnection) {
       String timestampTzInGmtPropStr =
           ((OracleConnection) conn)
               .getProperties()
               .getProperty("oracle.jdbc.timestampTzInGmt", "true");
       isTimestampInGmt = timestampTzInGmtPropStr.equalsIgnoreCase("true");
     } else {
       isTimestampInGmt = true;
     }
   }
   isConnectionDataInitialized = true;
 }
 /** INTERNAL: */
 public void startDocument(String encoding, String version) {
   try {
     writer.write("<?xml version=\"");
     writer.write(version);
     writer.write('\"');
     if (null != encoding) {
       writer.write(" encoding=\"");
       writer.write(encoding);
       writer.write('\"');
     }
     writer.write("?>");
     writer.write(Helper.cr());
   } catch (IOException e) {
     throw XMLMarshalException.marshalException(e);
   }
 }
 protected void verify() {
   if (results.size() != expectedResults.size()) {
     throw new TestErrorException("ReportQuery test failed: The result size are different");
   }
   BigDecimal expected =
       (BigDecimal) ((ReportQueryResult) expectedResults.firstElement()).getByIndex(0);
   BigDecimal result =
       (BigDecimal)
           ConversionManager.getDefaultManager()
               .convertObject(
                   ((ReportQueryResult) results.firstElement()).getByIndex(0), BigDecimal.class);
   if (!Helper.compareBigDecimals(expected, result)) {
     throw new TestErrorException(
         "ReportQuery test failed: The results did not match (" + expected + ", " + result + ")");
   }
 }
Beispiel #30
0
  /**
   * INTERNAL: For this Type generate classes
   *
   * @param packageName
   * @param nr
   */
  public void preInitialize(String packageName, List namespaceResolvers) {
    String instanceClassName = getInstanceClassName();
    if (null == instanceClassName) {
      if (null == packageName) {
        String uri = getURI();
        if (null == uri) {
          packageName = SDOUtil.getDefaultPackageName() + SDOConstants.JAVA_PACKAGE_NAME_SEPARATOR;
        } else {
          packageName =
              SDOUtil.getPackageNameFromURI(uri) + SDOConstants.JAVA_PACKAGE_NAME_SEPARATOR;
        }
      }

      // Verify and fix any Class name that does not conform to conventions
      // run the class name through the JAXB mangler
      String mangledClassName = SDOUtil.className(getName(), false, true, true);

      // we will not fix any type collision at this time as a result of class renaming
      // write fully qualified java class name
      StringBuffer fullClassName = new StringBuffer(packageName);
      fullClassName.append(mangledClassName);
      setInstanceClassName(fullClassName.toString());
    }
    AbstractSessionLog.getLog()
        .log(
            AbstractSessionLog.FINER, //
            "sdo_type_generation_processing_type", //
            new Object[] {Helper.getShortClassName(getClass()), getInstanceClassName()});

    initializeNamespaces(namespaceResolvers);
    getXmlDescriptor().setJavaClassName(getImplClassName());

    // See SDOResolvable enhancement
    String schemaContext = getName();
    if (getXmlDescriptor().getNamespaceResolver() != null) {
      String prefix = getXmlDescriptor().getNamespaceResolver().resolveNamespaceURI(getURI());
      if ((prefix != null) && !prefix.equals(SDOConstants.EMPTY_STRING)) {
        schemaContext = prefix + SDOConstants.SDO_XPATH_NS_SEPARATOR_FRAGMENT + schemaContext;
      }
    }
    String schemaContextWithSlash = SDOConstants.SDO_XPATH_SEPARATOR_FRAGMENT + schemaContext;

    XMLSchemaReference schemaRef = new XMLSchemaClassPathReference();
    schemaRef.setSchemaContext(schemaContextWithSlash);
    schemaRef.setType(XMLSchemaReference.COMPLEX_TYPE);
    getXmlDescriptor().setSchemaReference(schemaRef);
  }