Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you under the Apache License, Version 2.0 (the
   * "License"); you may not use this file except in compliance
   * with the License.  You may obtain a copy of the License at
   * 
  *   http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing,
  * software distributed under the License is distributed on an
  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  * KIND, either express or implied.  See the License for the
  * specific language governing permissions and limitations
  * under the License.    
  */
 package org.apache.tuscany.sca.databinding.javabeans;
 
 import java.util.List;
 import java.util.Map;
 
 
Transformer to convert data from XML to JavaBean

Version:
$Rev: 916888 $ $Date: 2010-02-27 00:44:05 +0000 (Sat, 27 Feb 2010) $
 
 public abstract class XML2JavaBeanTransformer<T> extends BaseTransformer<T, Objectimplements
         PullTransformer<T, Object> {
 
     public static final String SET = "set";
     public static final QName QNAME_MESSAGE = new QName("message");
 
     protected SimpleTypeMapperImpl mapper;
 
     public XML2JavaBeanTransformer() {
         this. = new SimpleTypeMapperImpl();
     }
 
     @Override
     public int getWeight() {
         return .;
     }
     
     public Object transform(T sourceTransformationContext context) {
         //FIXME why is the logical type sometimes a Class instead of an XMLType?
         if (context.getSourceDataType().getLogical() instanceof XMLType) {
             XMLType xmlType = (XMLTypecontext.getSourceDataType().getLogical();
             return toJavaObject(xmlType.getTypeName(), getRootElement(source), context);
         } else {
             return toJavaObject(nullgetRootElement(source), context);
         }
     }
 
     public Object toJavaObject(QName xmlType, T xmlElementTransformationContext context) {
         if (xmlType != null && .isSimpleXSDType(xmlType)) {
             return .toJavaObject(xmlTypegetText(xmlElement), context);
         } else {
             Class<?> javaType = (Class<?>)context.getTargetDataType().getPhysical();
             return createJavaObject(xmlElementjavaTypecontext);
         }
     }
     
     @SuppressWarnings("unchecked")
     private <L> L createJavaObject(T elementClass<L> javaTypeTransformationContext context
         throws XML2JavaMapperException {
         if (isTextOnly(element)) {
             return (L) .toJavaObject(.getXMLType(javaType).getQName(),
                                                  getText(element),
                                                  context);
         } else {
             String fieldName = null;
             try {
                 L javaInstance;
                 T detailMsg = null;
                 if (Throwable.class.isAssignableFrom(javaType)) {
                     T msgElement = getFirstChildWithName(element);
                     if (msgElement != null && isTextOnly(msgElement)) {
                         detailMsg = msgElement;  // skip this when handling child elements
                         Constructor constructor = javaType.getConstructor(new Class[] {String.class});
                         javaInstance = (L)constructor.newInstance(new Object[] {getText(detailMsg)});
                     } else {
                        javaInstance = javaType.newInstance();
                    }
                } else {
                    javaInstance = javaType.newInstance();
                }
                Map<FieldList<Object>> arrayFields = new Hashtable<FieldList<Object>>();
                Map<MethodList<Object>> arraySetters = new Hashtable<MethodList<Object>>();
                
                for (Iterator<T> childElements = getChildElements(element); childElements.hasNext(); ) {
                    T childElement = childElements.next();
                    if (!isTextElement(childElement) && childElement != detailMsg) {
                        fieldName = getElementName(childElement);
                        try {
                            Field javaField = javaType.getField(fieldName);
                            setFieldValue(javaInstance,
                                          javaField,
                                          childElement,
                                          arrayFields,
                                          context);
                        } catch (NoSuchFieldException e1) {
                            setFieldValueUsingSetter(javaType,
                                                     javaInstance,
                                                     fieldName,
                                                     childElement,
                                                     arraySetters,
                                                     context);
                        }
                    }
                }
                setArrayValues(javaInstancearrayFieldsarraySetters);
                return javaInstance;
            } catch (Exception e2) {
                XML2JavaMapperException xml2JavaEx = new XML2JavaMapperException(e2);
                xml2JavaEx.setJavaType(javaType);
                xml2JavaEx.setJavaFieldName(fieldName);
                throw xml2JavaEx;
            }
        }
    }
    private void setFieldValue(Object javaInstance,
                               Field javaField,
                               T fieldValue,
                               Map<FieldList<Object>> arrayFields,
                               TransformationContext contextthrows IllegalAccessException {
        Class<?> javaFieldType = (Class<?>) javaField.getType();
        if (javaFieldType.isArray()) {
            Class<?> componentType = javaFieldType.getComponentType();
            List<ObjectfldValueArray = arrayFields.get(javaField);
            if (fldValueArray == null) {
                fldValueArray = new ArrayList<Object>();
                arrayFields.put(javaFieldfldValueArray);
            }
            fldValueArray.add(createJavaObject(fieldValuecomponentTypecontext));
        } else {
            javaField.setAccessible(true);
            javaField.set(javaInstancecreateJavaObject(fieldValuejavaFieldTypecontext));
        }
    }
    private void setFieldValueUsingSetter(Class javaType,
                                          Object javaInstance,
                                          String fieldName,
                                          T fieldValue,
                                          Map<MethodList<Object>> arraySetters,
                                          TransformationContext contextthrows IllegalAccessException,
                                                                        InvocationTargetException {
        char firstChar = Character.toUpperCase(fieldName.charAt(0));
        StringBuilder methodName = new StringBuilder( + fieldName);
        methodName.setCharAt(.length(), firstChar);
        boolean methodNotFound = true;
        for (int methodCount = 0; methodNotFound && methodCount < javaType.getMethods().length; ++methodCount) {
            Method aMethod = javaType.getMethods()[methodCount];
            if (aMethod.getName().equals(methodName.toString())
                    && aMethod.getParameterTypes().length == 1) {
                Class<?> paramType = aMethod.getParameterTypes()[0];
                if (paramType.isArray()) {
                    Class<?> componentType = paramType.getComponentType();
                    List<ObjectsetterValueArray = arraySetters.get(aMethod);
                    if (setterValueArray == null) {
                        setterValueArray = new ArrayList<Object>();
                        arraySetters.put(aMethodsetterValueArray);
                    }
                    setterValueArray.add(createJavaObject(fieldValuecomponentTypecontext));
                } else {
                    aMethod.invoke(javaInstancenew Object[] {createJavaObject(fieldValue,
                                                                                 paramType,
                                                                                 context)});
                }
                methodNotFound = false;
            }
        }
        if (methodNotFound) {
            XML2JavaMapperException xml2JavaEx =
                    new XML2JavaMapperException("No field or setter method to configure xml data");
            xml2JavaEx.setJavaFieldName(fieldName);
            xml2JavaEx.setJavaType(javaType);
            throw xml2JavaEx;
        }
    }
    private void setArrayValues(Object javaInstance,
                                Map<FieldList<Object>> arrayFields,
                                Map<MethodList<Object>> arraySettersthrows IllegalAccessException,
                                                                       InvocationTargetException {
        if (arrayFields.size() > 0) {
            for (Field javaField : arrayFields.keySet()) {
                javaField.setAccessible(true);
                if (javaField.getType().getComponentType().isPrimitive()) {
                    javaField.set(javaInstancecreatePrimitiveArray(javaField.getType()
                                                                              .getComponentType(),
                                                                     arrayFields.get(javaField)));
                } else {
                    javaField.set(javaInstance,
                                  createNonPrimitiveArray(javaField.getType().getComponentType(),
                                                          arrayFields.get(javaField)));
                }
            }
        }
        if (arraySetters.size() > 0) {
            for (Method aMethod : arraySetters.keySet()) {
                Class<?> paramType = aMethod.getParameterTypes()[0];
                if (paramType.getComponentType().isPrimitive()) {
                    aMethod.invoke(javaInstance,
                                   new Object[] {createPrimitiveArray(paramType.getComponentType(),
                                                                       arraySetters.get(aMethod))});
                } else {
                    aMethod.invoke(javaInstance,
                                   new Object[] {createNonPrimitiveArray(paramType.getComponentType(),
                                                                          arraySetters.get(aMethod))});
                }
            }
        }
    }
    private Object createNonPrimitiveArray(Class fieldTypeList values) {
        Object objectArray = Array.newInstance(fieldTypevalues.size());
        for (int count = 0; count < values.size(); ++count) {
            Array.set(objectArraycountvalues.get(count));
        }
        return objectArray;
    }
    private Object createPrimitiveArray(Class fieldTypeList values) {
        if (fieldType.isPrimitive()) {
            if (fieldType.getName().equals("int")) {
                int[] primitiveValues = new int[values.size()];
                for (int count = 0; count < values.size(); ++count) {
                    primitiveValues[count] = ((Integervalues.get(count)).intValue();
                }
                return primitiveValues;
            } else if (fieldType.getName().equals("float")) {
                float[] primitiveValues = new float[values.size()];
                for (int count = 0; count < values.size(); ++count) {
                    primitiveValues[count] = ((Floatvalues.get(count)).floatValue();
                }
                return primitiveValues;
            } else if (fieldType.getName().equals("boolean")) {
                boolean[] primitiveValues = new boolean[values.size()];
                for (int count = 0; count < values.size(); ++count) {
                    primitiveValues[count] = ((Booleanvalues.get(count)).booleanValue();
                }
                return primitiveValues;
            } else if (fieldType.getName().equals("char")) {
                char[] primitiveValues = new char[values.size()];
                for (int count = 0; count < values.size(); ++count) {
                    primitiveValues[count] = ((Charactervalues.get(count)).charValue();
                }
                return primitiveValues;
            } else if (fieldType.getName().equals("byte")) {
                byte[] primitiveValues = new byte[values.size()];
                for (int count = 0; count < values.size(); ++count) {
                    primitiveValues[count] = ((Bytevalues.get(count)).byteValue();
                }
                return primitiveValues;
            } else if (fieldType.getName().equals("short")) {
                short[] primitiveValues = new short[values.size()];
                for (int count = 0; count < values.size(); ++count) {
                    primitiveValues[count] = ((Shortvalues.get(count)).shortValue();
                }
                return primitiveValues;
            } else if (fieldType.getName().equals("long")) {
                long[] primitiveValues = new long[values.size()];
                for (int count = 0; count < values.size(); ++count) {
                    primitiveValues[count] = ((Longvalues.get(count)).longValue();
                }
                return primitiveValues;
            } else if (fieldType.getName().equals("double")) {
                double[] primitiveValues = new double[values.size()];
                for (int count = 0; count < values.size(); ++count) {
                    primitiveValues[count] = ((Doublevalues.get(count)).doubleValue();
                }
                return primitiveValues;
            }
        }
        return values;
    }
    public abstract String getText(T sourcethrows XML2JavaMapperException;
    public abstract Iterator<T> getChildElements(T parentthrows XML2JavaMapperException;
    public abstract String getElementName(T elementthrows XML2JavaMapperException;
    public abstract boolean isTextElement(T elementthrows XML2JavaMapperException;
    
    public abstract boolean isTextOnly(T elementthrows XML2JavaMapperException;
    public abstract T getFirstChildWithName(T elementQName namethrows XML2JavaMapperException;
    public abstract T getRootElement(T elementthrows XML2JavaMapperException;
    @Override
    public Class<ObjectgetTargetType() {
        return Object.class;
    }
    @Override
    public String getTargetDataBinding() {
        return .;
    }
New to GrepCode? Check out our FAQ X