/**
   * @param writer
   * @param includeHistory
   * @param session
   * @throws DataAccessException
   * @throws HibernateException
   */
  private void writeObjects(
      final Writer writer,
      final boolean includeHistory,
      final Session session,
      final boolean preserveIds)
      throws DataAccessException, HibernateException {
    // Container für die Objekte
    final List<Object> all = new ArrayList<Object>();
    final XStream stream = initXStream(session, true);
    final XStream defaultXStream = initXStream(session, false);

    session.flush();
    // Alles laden
    List<?> list = session.createQuery("select o from java.lang.Object o").setReadOnly(true).list();
    list = (List<?>) CollectionUtils.select(list, PredicateUtils.uniquePredicate());
    final int size = list.size();
    log.info("Writing " + size + " objects");
    for (final Iterator<?> it = list.iterator(); it.hasNext(); ) {
      final Object obj = it.next();
      if (log.isDebugEnabled()) {
        log.debug("loaded object " + obj);
      }
      if ((obj instanceof HistoryEntry || obj instanceof PropertyDelta)
          && includeHistory == false) {
        continue;
      }
      Hibernate.initialize(obj);
      final Class<?> targetClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj);
      final ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(targetClass);
      if (classMetadata == null) {
        log.fatal("Can't init " + obj + " of type " + targetClass);
        continue;
      }
      // initalisierung des Objekts...
      defaultXStream.marshal(obj, new CompactWriter(new NullWriter()));

      if (preserveIds == false) {
        // Nun kann die ID gelöscht werden
        classMetadata.setIdentifier(obj, null, EntityMode.POJO);
      }
      if (log.isDebugEnabled()) {
        log.debug("loading evicted object " + obj);
      }
      if (this.ignoreFromTopLevelListing.contains(targetClass) == false) {
        all.add(obj);
      }
    }
    // und schreiben
    try {
      writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n");
    } catch (final IOException ex) {
      // ignore, will fail on stream.marshal()
    }
    log.info("Wrote " + all.size() + " objects");
    final MarshallingStrategy marshallingStrategy = new ProxyIdRefMarshallingStrategy();
    stream.setMarshallingStrategy(marshallingStrategy);
    stream.marshal(all, new PrettyPrintWriter(writer));
  }
  /** Performs tasks to resolve the lazy instantiation. */
  private synchronized void init() {
    if (!initialized) {
      // Mimic the behavior of XStream's JVM class
      String vendor = System.getProperty("java.vm.vendor");
      float version = 1.3f;
      try {
        version = Float.parseFloat(System.getProperty("java.version").substring(0, 3));
      } catch (NumberFormatException nfe) {
        // Keep the default
      }
      Class unsafe = null;
      try {
        unsafe = Class.forName("sun.misc.Unsafe", false, getClass().getClassLoader());
      } catch (ClassNotFoundException cnfe) {
        // Keep the default
      }
      ReflectionProvider reflectionProvider = null;
      if ((vendor.contains("Sun")
              || vendor.contains("Oracle")
              || vendor.contains("Apple")
              || vendor.contains("Hewlett-Packard")
              || vendor.contains("IBM")
              || vendor.contains("Blackdown"))
          && version >= 1.4f
          && unsafe != null) {
        try {
          reflectionProvider =
              (ReflectionProvider)
                  Class.forName(
                          "com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider",
                          false,
                          getClass().getClassLoader())
                      .newInstance();
        } catch (InstantiationException ie) {
          reflectionProvider = new PureJavaReflectionProvider();
        } catch (IllegalAccessException iae) {
          reflectionProvider = new PureJavaReflectionProvider();
        } catch (ClassNotFoundException cnfe) {
          reflectionProvider = new PureJavaReflectionProvider();
        }
      } else {
        reflectionProvider = new PureJavaReflectionProvider();
      }
      HierarchicalStreamDriver driver = new DomDriver();

      xs = new XStream(reflectionProvider, driver);
      xs.setMarshallingStrategy(new LockssReferenceByXPathMarshallingStrategy(lockssContext));
      xs.registerConverter(new LockssDateConverter());
      initialized = true;
    }
  }
 /** @return */
 private XStream initXStream(final Session session, final boolean nullifyPk) {
   final XStream xstream =
       new XStream() {
         @Override
         protected MapperWrapper wrapMapper(final MapperWrapper next) {
           return new HibernateMapper(new HibernateCollectionsMapper(next));
         }
       };
   // Converter für die Hibernate-Collections
   xstream.registerConverter(new HibernateCollectionConverter(xstream.getConverterLookup()));
   xstream.registerConverter(
       new HibernateProxyConverter(
           xstream.getMapper(), new PureJavaReflectionProvider(), xstream.getConverterLookup()),
       XStream.PRIORITY_VERY_HIGH);
   xstream.setMarshallingStrategy(
       new XStreamMarshallingStrategy(XStreamMarshallingStrategy.RELATIVE));
   init(xstream);
   return xstream;
 }
  @Test
  public void synchronizedCollectionText()
      throws NoSuchFieldException, SecurityException, IllegalArgumentException,
          IllegalAccessException {
    Map<String, String> map = Collections.synchronizedMap(new LinkedHashMap<String, String>());
    map.put("hello", "world");
    map.put("second", "value");

    XStream xs = new XStream();
    xs.setMarshallingStrategy(
        new MigratingMarshallingStrategy(new MigrationManager("com.t3.", true)));

    System.out.println(xs.toXML(map));
    Map<String, String> map2 = (Map<String, String>) xs.fromXML(xs.toXML(map));

    Assert.assertEquals(map, map2);
    Assert.assertEquals(map.getClass(), map2.getClass());

    // make shure that is map is of the same type
    Field f = map.getClass().getDeclaredField("m");
    f.setAccessible(true);
    Assert.assertEquals(f.get(map).getClass(), LinkedHashMap.class);
    Assert.assertEquals(f.get(map2).getClass(), LinkedHashMap.class);
  }
Exemple #5
0
  private Pair<String, Object> parseEntry(Node node) {
    NodeList nl = node.getChildNodes();
    String name = null;
    Object value = null;
    for (int i = 0; i < nl.getLength(); i++) {
      Node ii = nl.item(i);

      ii = resolve(ii);

      System.out.println(" entry, name <" + ii.getNodeName() + ">");

      if (ii.getNodeName().equals("field.core.dispatch.iVisualElement_-VisualElementProperty")) {

        NodeList childNodes = ii.getChildNodes();
        for (int j = 0; j < childNodes.getLength(); j++) {

          Node cn = childNodes.item(j);
          cn = resolve(cn);

          System.out.println(" property <" + cn.getNodeName() + ">");
          if (cn.getNodeName().equals("name")) {
            name = cn.getTextContent();
            System.out.println(" name is <" + name + ">");
          }
        }
      } else if (ii.getNodeName().equals("string")) {
        value = ii.getTextContent().trim();
      } else if (ii.getNodeName().equals("float")) {
        value = Float.parseFloat(ii.getTextContent().trim());
      } else if (ii.getNodeName().equals("double")) {
        value = Double.parseDouble(ii.getTextContent().trim());
      } else {
; // System.out.println(" node is xml <" + loadProperties + ">");

        if (loadProperties) {
          try {
            String xml = nodeToString(ii);
            if (xml.trim().length() == 0) continue;
            if (xml.contains("reference=")) continue;
            if (xml.contains("id=")) continue;

            ; // System.out.println(" xml is <" + xml + ">");
            xml = "<object-stream>" + xml + "</object-stream>";

            XStream stream = new XStream(new Sun14ReflectionProvider());
            stream.registerConverter(new ChannelSerializer());
            stream.registerConverter(new FloatBufferSerializer());
            stream.registerConverter(new MarkerSerializer(stream.getClassMapper()));
            stream.setMarshallingStrategy(new ReferenceByIdMarshallingStrategy());
            Object o = stream.createObjectInputStream(new StringReader(xml)).readObject();
            value = o;
            ; // System.out.println(" -- loaded <" + value + ">");
          } catch (Throwable t) {
            System.out.println(
                " trouble loading contents of <" + ii.getNodeName() + "> continuing on");
          }
        }
      }
    }

    //		System.out.println(" got <" + name + " = " + value + ">");

    if (name == null) return null;
    if (value == null) return null;
    else return new Pair<String, Object>(name, value);
  }
  /**
   * Configure the XStream instance with this marshaller's bean properties.
   *
   * @param xstream the {@code XStream} instance
   */
  protected void configureXStream(XStream xstream) {
    if (this.converters != null) {
      for (int i = 0; i < this.converters.length; i++) {
        if (this.converters[i] instanceof Converter) {
          xstream.registerConverter((Converter) this.converters[i], i);
        } else if (this.converters[i] instanceof SingleValueConverter) {
          xstream.registerConverter((SingleValueConverter) this.converters[i], i);
        } else {
          throw new IllegalArgumentException(
              "Invalid ConverterMatcher [" + this.converters[i] + "]");
        }
      }
    }

    if (this.marshallingStrategy != null) {
      xstream.setMarshallingStrategy(this.marshallingStrategy);
    }
    if (this.mode != null) {
      xstream.setMode(this.mode);
    }

    try {
      if (this.aliases != null) {
        Map<String, Class<?>> classMap = toClassMap(this.aliases);
        for (Map.Entry<String, Class<?>> entry : classMap.entrySet()) {
          xstream.alias(entry.getKey(), entry.getValue());
        }
      }
      if (this.aliasesByType != null) {
        Map<String, Class<?>> classMap = toClassMap(this.aliasesByType);
        for (Map.Entry<String, Class<?>> entry : classMap.entrySet()) {
          xstream.aliasType(entry.getKey(), entry.getValue());
        }
      }
      if (this.fieldAliases != null) {
        for (Map.Entry<String, String> entry : this.fieldAliases.entrySet()) {
          String alias = entry.getValue();
          String field = entry.getKey();
          int idx = field.lastIndexOf('.');
          if (idx != -1) {
            String className = field.substring(0, idx);
            Class<?> clazz = ClassUtils.forName(className, this.beanClassLoader);
            String fieldName = field.substring(idx + 1);
            xstream.aliasField(alias, clazz, fieldName);
          } else {
            throw new IllegalArgumentException("Field name [" + field + "] does not contain '.'");
          }
        }
      }
    } catch (ClassNotFoundException ex) {
      throw new IllegalStateException("Failed to load specified alias class", ex);
    }

    if (this.useAttributeForTypes != null) {
      for (Class<?> type : this.useAttributeForTypes) {
        xstream.useAttributeFor(type);
      }
    }
    if (this.useAttributeFor != null) {
      for (Map.Entry<?, ?> entry : this.useAttributeFor.entrySet()) {
        if (entry.getKey() instanceof String) {
          if (entry.getValue() instanceof Class) {
            xstream.useAttributeFor((String) entry.getKey(), (Class<?>) entry.getValue());
          } else {
            throw new IllegalArgumentException(
                "'useAttributesFor' takes Map<String, Class> when using a map key of type String");
          }
        } else if (entry.getKey() instanceof Class) {
          Class<?> key = (Class<?>) entry.getKey();
          if (entry.getValue() instanceof String) {
            xstream.useAttributeFor(key, (String) entry.getValue());
          } else if (entry.getValue() instanceof List) {
            @SuppressWarnings("unchecked")
            List<Object> listValue = (List<Object>) entry.getValue();
            for (Object element : listValue) {
              if (element instanceof String) {
                xstream.useAttributeFor(key, (String) element);
              }
            }
          } else {
            throw new IllegalArgumentException(
                "'useAttributesFor' property takes either Map<Class, String> "
                    + "or Map<Class, List<String>> when using a map key of type Class");
          }
        } else {
          throw new IllegalArgumentException(
              "'useAttributesFor' property takes either a map key of type String or Class");
        }
      }
    }

    if (this.implicitCollections != null) {
      for (Map.Entry<Class<?>, String> entry : this.implicitCollections.entrySet()) {
        String[] collectionFields = StringUtils.commaDelimitedListToStringArray(entry.getValue());
        for (String collectionField : collectionFields) {
          xstream.addImplicitCollection(entry.getKey(), collectionField);
        }
      }
    }
    if (this.omittedFields != null) {
      for (Map.Entry<Class<?>, String> entry : this.omittedFields.entrySet()) {
        String[] fields = StringUtils.commaDelimitedListToStringArray(entry.getValue());
        for (String field : fields) {
          xstream.omitField(entry.getKey(), field);
        }
      }
    }

    if (this.annotatedClasses != null) {
      xstream.processAnnotations(this.annotatedClasses);
    }
    if (this.autodetectAnnotations) {
      xstream.autodetectAnnotations(true);
    }
  }