public synchronized XMLContext getXmlContext() {
   if (xmlContext == null) {
     xmlContext = new XMLContext(getTopLinkProject());
     XMLConversionManager xmlConversionManager = getXmlConversionManager();
     xmlConversionManager.setLoader(this.loader);
     xmlConversionManager.setTimeZone(TimeZone.getTimeZone("GMT"));
     xmlConversionManager.setTimeZoneQualified(true);
   }
   return xmlContext;
 }
 public XMLConversionManager getXmlConversionManager() {
   XMLConversionManager xcm =
       (XMLConversionManager)
           getXmlContext()
               .getSession(0)
               .getDatasourceLogin()
               .getDatasourcePlatform()
               .getConversionManager();
   xcm.setTrimGMonth(true);
   return xcm;
 }
 /**
  * INTERNAL: Extract the primary key values from the row, then create an
  * org.eclipse.persistence.internal.oxm.Reference instance and stored it on the session's
  * org.eclipse.persistence.internal.oxm.ReferenceResolver.
  */
 public Object readFromRowIntoObject(
     AbstractRecord databaseRow,
     JoinedAttributeManager joinManager,
     Object targetObject,
     ObjectBuildingQuery sourceQuery,
     AbstractSession executionSession)
     throws DatabaseException {
   ClassDescriptor descriptor = sourceQuery.getSession().getClassDescriptor(getReferenceClass());
   ContainerPolicy cp = this.getContainerPolicy();
   Vector pkFieldNames = referenceDescriptor.getPrimaryKeyFieldNames();
   Vector primaryKeyValues = new Vector();
   primaryKeyValues.setSize(pkFieldNames.size());
   HashMap primaryKeyMap = new HashMap();
   // for each source xmlField, get the value from the row and store
   for (Iterator fieldIt = getFields().iterator(); fieldIt.hasNext(); ) {
     XMLField fld = (XMLField) fieldIt.next();
     XMLField tgtFld = (XMLField) getSourceToTargetKeyFieldAssociations().get(fld);
     Object fieldValue = databaseRow.getValues(fld);
     if ((fieldValue == null)
         || (fieldValue instanceof String)
         || !(fieldValue instanceof Vector)) {
       return cp.containerInstance();
     }
     // fix for bug# 5687430
     // need to get the actual type of the target (i.e. int, String, etc.)
     // and use the converted value when checking the cache.
     XMLConversionManager xmlConversionManager =
         (XMLConversionManager) executionSession.getDatasourcePlatform().getConversionManager();
     Vector newValues = new Vector();
     for (Iterator valIt = ((Vector) fieldValue).iterator(); valIt.hasNext(); ) {
       for (StringTokenizer stok = new StringTokenizer((String) valIt.next());
           stok.hasMoreTokens(); ) {
         Object value =
             xmlConversionManager.convertObject(
                 stok.nextToken(), descriptor.getTypedField(tgtFld).getType());
         if (value != null) {
           newValues.add(value);
         }
       }
     }
     primaryKeyMap.put(tgtFld.getXPath(), newValues);
   }
   // store the Reference instance on the resolver for use during mapping resolution phase
   ReferenceResolver resolver = ReferenceResolver.getInstance(sourceQuery.getSession());
   if (resolver != null) {
     resolver.addReference(new Reference(this, targetObject, referenceClass, primaryKeyMap));
   }
   return null;
 }
 /** INTERNAL: Add the field-value pair to the document. */
 public void add(DatabaseField key, Object value) {
   if (null == value) {
     return;
   }
   XMLField xmlField = convertToXMLField(key);
   XPathFragment lastFragment = xmlField.getLastXPathFragment();
   XMLConversionManager xcm =
       (XMLConversionManager) session.getDatasourcePlatform().getConversionManager();
   if (lastFragment.nameIsText()) {
     String stringValue = (String) xcm.convertObject(value, String.class);
     characters(stringValue);
   } else if (lastFragment.isAttribute()) {
     String stringValue = (String) xcm.convertObject(value, String.class);
     attribute(lastFragment, xmlField.getNamespaceResolver(), stringValue);
   } else {
     element(lastFragment);
   }
 }
  /**
   * INTERNAL: Create (if necessary) and populate a reference object that will be used during the
   * mapping reference resolution phase after unmarshalling is complete.
   *
   * @param record
   * @param xmlField
   * @param object
   * @param session
   * @return
   */
  public void buildReference(
      UnmarshalRecord record, XMLField xmlField, Object object, AbstractSession session) {
    ReferenceResolver resolver = ReferenceResolver.getInstance(session);
    if (resolver == null) {
      return;
    }

    Object srcObject = record.getCurrentObject();
    Reference reference = resolver.getReference(this, srcObject);
    // if reference is null, create a new instance and set it on the resolver
    if (reference == null) {
      reference = new Reference(this, srcObject, getReferenceClass(), new HashMap());
      resolver.addReference(reference);
    }

    XMLField tgtFld = (XMLField) getSourceToTargetKeyFieldAssociations().get(xmlField);
    String tgtXPath = tgtFld.getXPath();
    Vector pks;
    HashMap primaryKeyMap = reference.getPrimaryKeyMap();
    if (primaryKeyMap.containsKey(tgtXPath)) {
      pks = (Vector) primaryKeyMap.get(tgtXPath);
    } else {
      pks = new Vector();
      primaryKeyMap.put(tgtXPath, pks);
    }

    ClassDescriptor descriptor = session.getClassDescriptor(getReferenceClass());
    Class type = descriptor.getTypedField(tgtFld).getType();
    XMLConversionManager xmlConversionManager =
        (XMLConversionManager) session.getDatasourcePlatform().getConversionManager();
    for (StringTokenizer stok = new StringTokenizer((String) object); stok.hasMoreTokens(); ) {
      Object value = xmlConversionManager.convertObject(stok.nextToken(), type);
      if (value != null) {
        pks.add(value);
      }
    }
  }
 @SuppressWarnings("unchecked")
 @Override
 public void handleSqlType(String sqlTypeName, int typecode, String targetTypeName) {
   if (!stac.isEmpty()) {
     ListenerHelper listenerHelper = stac.pop();
     if (listenerHelper.isAttribute()) {
       AttributeFieldHelper attributeFieldHelper = (AttributeFieldHelper) listenerHelper;
       attributeFieldHelper.setSqlTypeName(sqlTypeName);
       String fieldName = attributeFieldHelper.attributeFieldName();
       String attributeName = fieldName.toLowerCase();
       ListenerHelper listenerHelper2 = stac.peek();
       if (listenerHelper2.isObject()) {
         ObjectTypeHelper objectTypeHelper = (ObjectTypeHelper) listenerHelper2;
         XMLDescriptor xdesc = descriptorMap.get(objectTypeHelper.objectTypename());
         DatabaseMapping dm = xdesc.getMappingForAttributeName(attributeName);
         if (dm == null) {
           XMLDirectMapping fieldMapping = new XMLDirectMapping();
           fieldMapping.setAttributeName(attributeName);
           XMLField xField = new XMLField(attributeName + "/text()");
           xField.setRequired(true);
           QName qnameFromDatabaseType = qnameFromDatabaseType(listenerHelper);
           xField.setSchemaType(qnameFromDatabaseType);
           // special case to avoid Calendar problems
           if (qnameFromDatabaseType == DATE_QNAME) {
             fieldMapping.setAttributeClassification(java.sql.Date.class);
             xField.addXMLConversion(DATE_QNAME, java.sql.Date.class);
             xField.addJavaConversion(java.sql.Date.class, DATE_QNAME);
             xdesc.getNamespaceResolver().put(SCHEMA_PREFIX, W3C_XML_SCHEMA_NS_URI);
           } else {
             Class attributeClass =
                 (Class) XMLConversionManager.getDefaultXMLTypes().get(qnameFromDatabaseType);
             if (attributeClass == null) {
               attributeClass = Object_Class;
             }
             fieldMapping.setAttributeClassification(attributeClass);
           }
           fieldMapping.setField(xField);
           AbstractNullPolicy nullPolicy = fieldMapping.getNullPolicy();
           nullPolicy.setNullRepresentedByEmptyNode(false);
           nullPolicy.setMarshalNullRepresentation(XSI_NIL);
           nullPolicy.setNullRepresentedByXsiNil(true);
           fieldMapping.setNullPolicy(nullPolicy);
           xdesc
               .getNamespaceResolver()
               .put(
                   SCHEMA_INSTANCE_PREFIX,
                   W3C_XML_SCHEMA_INSTANCE_NS_URI); // to support xsi:nil policy
           xdesc.addMapping(fieldMapping);
         }
         // last attribute, pop ObjectTypeHelper off stack
         int numAttributes = objectTypeHelper.decrNumAttributes();
         if (numAttributes == 0) {
           stac.pop();
         }
       } else if (listenerHelper2.isArray()) {
         SqlArrayTypeHelper sqlArrayTypeHelper = (SqlArrayTypeHelper) listenerHelper2;
         XMLDescriptor xdesc = descriptorMap.get(sqlArrayTypeHelper.arrayTypename());
         DatabaseMapping dm = xdesc.getMappingForAttributeName(attributeName);
         if (dm == null) {
           XMLCompositeDirectCollectionMapping dirCollectMapping =
               new XMLCompositeDirectCollectionMapping();
           SqltypeHelper componentType = new SqltypeHelper(sqlTypeName);
           dirCollectMapping.setAttributeElementClass(
               attributeClassFromDatabaseType((DefaultListenerHelper) componentType));
           dirCollectMapping.setAttributeName(attributeName);
           dirCollectMapping.setUsesSingleNode(true);
           dirCollectMapping.setXPath(attributeName + "/text()");
           XMLField xField = (XMLField) dirCollectMapping.getField();
           xField.setRequired(true);
           xField.setSchemaType(qnameFromDatabaseType(componentType));
           dirCollectMapping.useCollectionClassName("java.util.ArrayList");
           AbstractNullPolicy nullPolicy = dirCollectMapping.getNullPolicy();
           nullPolicy.setNullRepresentedByEmptyNode(false);
           nullPolicy.setMarshalNullRepresentation(XSI_NIL);
           nullPolicy.setNullRepresentedByXsiNil(true);
           dirCollectMapping.setNullPolicy(nullPolicy);
           xdesc
               .getNamespaceResolver()
               .put(
                   SCHEMA_INSTANCE_PREFIX,
                   W3C_XML_SCHEMA_INSTANCE_NS_URI); // to support xsi:nil policy
           xdesc.addMapping(dirCollectMapping);
         }
       }
     } else if (listenerHelper.isArray()) {
       SqlArrayTypeHelper sqlArrayTypeHelper2 = (SqlArrayTypeHelper) listenerHelper;
       XMLDescriptor xdesc = descriptorMap.get(sqlArrayTypeHelper2.arrayTypename());
       DatabaseMapping dm = xdesc.getMappingForAttributeName(ITEMS_MAPPING_ATTRIBUTE_NAME);
       if (dm == null) {
         XMLCompositeDirectCollectionMapping itemsMapping =
             new XMLCompositeDirectCollectionMapping();
         SqltypeHelper componentType = new SqltypeHelper(sqlTypeName);
         itemsMapping.setAttributeElementClass(
             attributeClassFromDatabaseType((DefaultListenerHelper) componentType));
         itemsMapping.setAttributeName(ITEMS_MAPPING_ATTRIBUTE_NAME);
         itemsMapping.setUsesSingleNode(true);
         itemsMapping.setXPath(ITEM_MAPPING_NAME + "/text()");
         XMLField xField = (XMLField) itemsMapping.getField();
         xField.setRequired(true);
         xField.setSchemaType(qnameFromDatabaseType(componentType));
         itemsMapping.useCollectionClassName("java.util.ArrayList");
         AbstractNullPolicy nullPolicy = itemsMapping.getNullPolicy();
         nullPolicy.setNullRepresentedByEmptyNode(false);
         nullPolicy.setMarshalNullRepresentation(XSI_NIL);
         nullPolicy.setNullRepresentedByXsiNil(true);
         itemsMapping.setNullPolicy(nullPolicy);
         xdesc
             .getNamespaceResolver()
             .put(
                 SCHEMA_INSTANCE_PREFIX,
                 W3C_XML_SCHEMA_INSTANCE_NS_URI); // to support xsi:nil policy
         xdesc.addMapping(itemsMapping);
       }
       ListenerHelper listenerHelper2 = stac.peek();
       if (listenerHelper2.isAttribute()) {
         // type built above used in field definition of object further up stack
         stac.pop();
         AttributeFieldHelper fieldHelper = (AttributeFieldHelper) listenerHelper2;
         ListenerHelper listenerHelper3 = stac.peek();
         if (listenerHelper3.isObject()) {
           ObjectTypeHelper objectTypeHelper = (ObjectTypeHelper) listenerHelper3;
           XMLDescriptor xdesc2 = descriptorMap.get(objectTypeHelper.objectTypename());
           String fieldName = fieldHelper.attributeFieldName();
           DatabaseMapping dm2 = xdesc2.getMappingForAttributeName(fieldName.toLowerCase());
           if (dm2 == null) {
             XMLCompositeDirectCollectionMapping fieldMapping =
                 new XMLCompositeDirectCollectionMapping();
             SqltypeHelper componentType = new SqltypeHelper(sqlTypeName);
             fieldMapping.setAttributeElementClass(
                 attributeClassFromDatabaseType((DefaultListenerHelper) componentType));
             fieldMapping.setAttributeName(fieldName.toLowerCase());
             XMLField field =
                 new XMLField(fieldName.toLowerCase() + "/" + ITEM_MAPPING_NAME + "/text()");
             field.setRequired(true);
             fieldMapping.setField(field);
             field.setSchemaType(qnameFromDatabaseType(componentType));
             fieldMapping.useCollectionClassName("java.util.ArrayList");
             AbstractNullPolicy nullPolicy = fieldMapping.getNullPolicy();
             nullPolicy.setNullRepresentedByEmptyNode(false);
             nullPolicy.setMarshalNullRepresentation(XSI_NIL);
             nullPolicy.setNullRepresentedByXsiNil(true);
             fieldMapping.setNullPolicy(nullPolicy);
             xdesc2
                 .getNamespaceResolver()
                 .put(
                     SCHEMA_INSTANCE_PREFIX,
                     W3C_XML_SCHEMA_INSTANCE_NS_URI); // to support xsi:nil policy
             xdesc2.addMapping(fieldMapping);
           }
           // last attribute, pop ObjectTypeHelper off stack
           int numAttributes = objectTypeHelper.decrNumAttributes();
           if (numAttributes == 0) {
             stac.pop();
           }
         }
       }
     }
   }
 }
  /**
   * Access the DataObject value by using the fragment containing query informations.
   *
   * @param frag one string fragment in the path
   * @param openBracketIndex the index of open bracket in a fragment
   * @param closeBracketIndex the index of close bracket in a fragment
   * @param equalsignIndex the index of equalsign in string fragment quoted by brackets
   * @param caller the DataObject that passes the path information in
   * @param callerProperty the name of the property
   * @return the DataObject as value of the property having name as the above callerProperty
   */
  private DataObject getDataObjectFromQuery(
      String frag,
      int openBracketIndex,
      int closeBracketIndex,
      int equalsignIndex,
      DataObject caller,
      String callerProperty) {
    try {
      // trim off any whitespace for property names
      String propertyNameOfQryDataObject =
          frag.substring(openBracketIndex + 1, equalsignIndex + openBracketIndex).trim();
      List objects = caller.getList(caller.getInstanceProperty(callerProperty));
      String query = frag.substring(equalsignIndex + openBracketIndex + 1, closeBracketIndex);
      String value = null;
      int firstQuoteIndex = query.indexOf('\'');
      int lastQuoteIndex = query.lastIndexOf('\'');
      if ((firstQuoteIndex == -1)
          && (lastQuoteIndex == -1)) { // !! note: case: [number=1'23'] is assume not to happen !!
        firstQuoteIndex = query.indexOf("\"");
        lastQuoteIndex = query.lastIndexOf("\"");
      }
      if ((firstQuoteIndex != -1)
          && (lastQuoteIndex != -1)
          && (firstQuoteIndex < lastQuoteIndex)) { // quoted string existed
        value = query.substring(firstQuoteIndex + 1, lastQuoteIndex);
      } else {
        // if the value is not enclosed on quotes, trim off any whitespace
        value = query.trim();
      }
      Iterator iterObjects = objects.iterator();
      Object queryValue = value;
      Object actualValue = null;
      while (iterObjects.hasNext()) {
        DataObject cur = (DataObject) iterObjects.next();
        Property p = cur.getInstanceProperty(propertyNameOfQryDataObject);
        if (p != null) {
          try {
            queryValue =
                XMLConversionManager.getDefaultXMLManager()
                    .convertObject(queryValue, p.getType().getInstanceClass());
          } catch (ConversionException e) {
            // do nothing, skip
          }

          if (!p.isMany()) {
            actualValue = cur.get(p);
            if (actualValue.equals(queryValue)) {
              return cur;
            }
          } else { // case p is many type
            List values = cur.getList(p);
            Iterator iterValues = values.iterator();

            while (iterValues.hasNext()) {
              actualValue = iterValues.next();
              if (actualValue.equals(queryValue)) {
                return cur;
              }
            }
          }
        }
      }

      return null;
    } catch (IllegalArgumentException e) {
      return null;
    }
  }
  /**
   * Create an instance of XMLRoot populated from the contents of the provided JAXBElement. XMLRoot
   * will be used to hold the contents of the JAXBElement while the marshal operation is performed
   * by TopLink OXM. This will avoid adding any runtime dependencies to TopLink.
   *
   * @param elt
   * @return
   */
  private Root createXMLRootFromJAXBElement(JAXBElement elt) {
    // create an XMLRoot to hand into the marshaller
    Root xmlroot = new Root();
    Object objectValue = elt.getValue();
    xmlroot.setObject(objectValue);
    QName qname = elt.getName();
    xmlroot.setLocalName(qname.getLocalPart());
    xmlroot.setNamespaceURI(qname.getNamespaceURI());
    xmlroot.setDeclaredType(elt.getDeclaredType());
    xmlroot.setNil(elt.isNil());
    if (elt.getDeclaredType() == CoreClassConstants.ABYTE
        || elt.getDeclaredType() == CoreClassConstants.APBYTE
        || elt.getDeclaredType().getCanonicalName().equals("javax.activation.DataHandler")
        || elt.getDeclaredType().isEnum()) {
      // need a binary data mapping so need to wrap
      Class generatedClass =
          getClassToGeneratedClasses().get(elt.getDeclaredType().getCanonicalName());
      if (!elt.getDeclaredType().isEnum()) {
        xmlroot.setSchemaType(Constants.BASE_64_BINARY_QNAME);
      }
      if (generatedClass != null && WrappedValue.class.isAssignableFrom(generatedClass)) {
        ClassDescriptor desc =
            xmlMarshaller.getXMLContext().getSession(generatedClass).getDescriptor(generatedClass);
        Object newObject = desc.getInstantiationPolicy().buildNewInstance();
        ((WrappedValue) newObject).setValue(objectValue);
        xmlroot.setObject(newObject);
        return xmlroot;
      }
    } else {
      xmlroot.setSchemaType(
          (QName)
              org.eclipse.persistence.internal.oxm.XMLConversionManager.getDefaultJavaTypes()
                  .get(elt.getDeclaredType()));
    }

    if (elt instanceof WrappedValue) {
      xmlroot.setObject(elt);
      return xmlroot;
    }
    Map<QName, Class> qNameToGeneratedClasses = jaxbContext.getQNameToGeneratedClasses();
    if (qNameToGeneratedClasses != null) {
      Class theClass = qNameToGeneratedClasses.get(qname);
      if (theClass != null && WrappedValue.class.isAssignableFrom(theClass)) {
        ClassDescriptor desc =
            xmlMarshaller.getXMLContext().getSession(theClass).getDescriptor(theClass);
        Object newObject = desc.getInstantiationPolicy().buildNewInstance();
        ((WrappedValue) newObject).setValue(objectValue);
        xmlroot.setObject(newObject);
        return xmlroot;
      }
    }

    Class generatedClass = null;
    if (jaxbContext.getTypeMappingInfoToGeneratedType() != null) {
      if (jaxbContext.getTypeToTypeMappingInfo() != null) {
        if (elt.getDeclaredType() != null && elt.getDeclaredType().isArray()) {
          TypeMappingInfo tmi = jaxbContext.getTypeToTypeMappingInfo().get(elt.getDeclaredType());
          generatedClass = jaxbContext.getTypeMappingInfoToGeneratedType().get(tmi);
        } else if (elt instanceof JAXBTypeElement) {
          Type objectType = ((JAXBTypeElement) elt).getType();
          TypeMappingInfo tmi = jaxbContext.getTypeToTypeMappingInfo().get(objectType);
          generatedClass = jaxbContext.getTypeMappingInfoToGeneratedType().get(tmi);
        }
      }
    } else {
      if (elt.getDeclaredType() != null && elt.getDeclaredType().isArray()) {
        if (jaxbContext.getArrayClassesToGeneratedClasses() != null) {
          generatedClass =
              jaxbContext
                  .getArrayClassesToGeneratedClasses()
                  .get(elt.getDeclaredType().getCanonicalName());
        }
      } else if (elt instanceof JAXBTypeElement) {
        Type objectType = ((JAXBTypeElement) elt).getType();
        generatedClass = jaxbContext.getCollectionClassesToGeneratedClasses().get(objectType);
      }
    }

    if (generatedClass != null) {
      ClassDescriptor desc =
          xmlMarshaller.getXMLContext().getSession(generatedClass).getDescriptor(generatedClass);
      Object newObject = desc.getInstantiationPolicy().buildNewInstance();
      ((ManyValue) newObject).setItem(objectValue);
      xmlroot.setObject(newObject);
    }

    return xmlroot;
  }