예제 #1
0
    /*
     * (non-Javadoc)
     *
     * @see
     * com.thoughtworks.xstream.converters.Converter#unmarshal(com.thoughtworks
     * .xstream.io.HierarchicalStreamReader,
     * com.thoughtworks.xstream.converters.UnmarshallingContext)
     */
    @Override
    @SuppressWarnings("unchecked")
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
      InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder();

      while (reader.hasMoreChildren()) {
        reader.moveDown();

        String nodeName = reader.getNodeName();

        if (ELEM_HOST.equals(nodeName)) {
          builder.setHostName(reader.getValue());
        } else if (ELEM_INSTANCE_ID.equals(nodeName)) {
          builder.setInstanceId(reader.getValue());
        } else if (ELEM_APP.equals(nodeName)) {
          builder.setAppName(reader.getValue());
        } else if (ELEM_IP.equals(nodeName)) {
          builder.setIPAddr(reader.getValue());
        } else if (ELEM_SID.equals(nodeName)) {
          builder.setSID(reader.getValue());
        } else if (ELEM_IDENTIFYING_ATTR.equals(nodeName)) {
          // nothing;
        } else if (ELEM_STATUS.equals(nodeName)) {
          builder.setStatus(InstanceStatus.toEnum(reader.getValue()));
        } else if (ELEM_OVERRIDDEN_STATUS.equals(nodeName)) {
          builder.setOverriddenStatus(InstanceStatus.toEnum(reader.getValue()));
        } else if (ELEM_PORT.equals(nodeName)) {
          builder.setPort(Integer.valueOf(reader.getValue()).intValue());
          // Defaults to true
          builder.enablePort(PortType.UNSECURE, !"false".equals(reader.getAttribute(ATTR_ENABLED)));
        } else if (ELEM_SECURE_PORT.equals(nodeName)) {
          builder.setSecurePort(Integer.valueOf(reader.getValue()).intValue());
          // Defaults to false
          builder.enablePort(PortType.SECURE, "true".equals(reader.getAttribute(ATTR_ENABLED)));
        } else if (ELEM_COUNTRY_ID.equals(nodeName)) {
          builder.setCountryId(Integer.valueOf(reader.getValue()).intValue());
        } else if (NODE_DATACENTER.equals(nodeName)) {
          builder.setDataCenterInfo(
              (DataCenterInfo) context.convertAnother(builder, DataCenterInfo.class));
        } else if (NODE_LEASE.equals(nodeName)) {
          builder.setLeaseInfo((LeaseInfo) context.convertAnother(builder, LeaseInfo.class));
        } else if (NODE_METADATA.equals(nodeName)) {
          builder.setMetadata((Map<String, String>) context.convertAnother(builder, Map.class));
        } else {
          autoUnmarshalEligible(reader, builder.getRawInstance());
        }

        reader.moveUp();
      }

      return builder.build();
    }
 @Override
 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext uc) {
   String code = reader.getAttribute(CURRENCY_CODE_ATTRIBUTE_NAME);
   Currency currency = new Currency(code);
   String exchangeRateString = reader.getAttribute(CURRENCY_EXCHANGE_RATE_ATTRIBUTE_NAME);
   // seems to return null if attribute isn't present, improvement
   // of docs requested as
   // https://github.com/x-stream/xstream/issues/47
   if (exchangeRateString != null) {
     double exchangeRate = Double.valueOf(exchangeRateString);
     currency.setExchangeRate(exchangeRate);
   }
   return currency;
 }
 private Class determineType(
     HierarchicalStreamReader reader,
     boolean validField,
     Object result,
     String fieldName,
     Class definedInCls) {
   String classAttribute = reader.getAttribute(mapper.aliasForAttribute("class"));
   Class fieldType = reflectionProvider.getFieldType(result, fieldName, definedInCls);
   if (classAttribute != null) {
     Class specifiedType = mapper.realClass(classAttribute);
     if (fieldType.isAssignableFrom(specifiedType))
       // make sure that the specified type in XML is compatible with the field type.
       // this allows the code to evolve in more flexible way.
       return specifiedType;
   }
   if (!validField) {
     Class itemType = mapper.getItemTypeForItemFieldName(result.getClass(), fieldName);
     if (itemType != null) {
       return itemType;
     } else {
       return mapper.realClass(reader.getNodeName());
     }
   } else {
     return mapper.defaultImplementationOf(fieldType);
   }
 }
예제 #4
0
  @Override
  public FIXMLRoot unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

    FIXMLRoot root = new FIXMLRoot();
    root.setVersion(reader.getAttribute("v"));
    root.setReleaseDate(reader.getAttribute("r"));
    root.setSchemaDate(reader.getAttribute("s"));

    if (reader.hasMoreChildren()) {
      reader.moveDown();
      root.setMessage((Message) context.convertAnother(root, Message.class));
      reader.moveUp();
    }

    return root;
  }
예제 #5
0
  @Override
  public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
    Birthday birthday = new Birthday();
    String gender = reader.getAttribute("gender");
    if (gender != null) {
      if (gender.length() > 0) {

        if (gender.startsWith("f")) {
          birthday.setGenderFemale();
        } else if (gender.startsWith("m")) {
          birthday.setGenderMale();
        } else {
          throw new ConversionException("Invalid gender value: " + gender);
        }
      } else {
        throw new ConversionException("Empty string is invalid gender value");
      }
    }
    while (reader.hasMoreChildren()) {
      reader.moveDown();
      if ("person".equals(reader.getNodeName())) {
        Person person = (Person) context.convertAnother(birthday, Person.class);
        birthday.setPerson(person);
      } else if ("birth".equals(reader.getNodeName())) {
        Calendar date = (Calendar) context.convertAnother(birthday, Calendar.class);
        birthday.setDate(date);
      }
      reader.moveUp();
    }
    return birthday;
  }
 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
   String nullAttribute = reader.getAttribute("null");
   if (nullAttribute != null && nullAttribute.equals("true")) {
     return new Character('\0');
   } else {
     return new Character(reader.getValue().charAt(0));
   }
 }
 private Class determineType(HierarchicalStreamReader reader, Object result, String fieldName) {
   String classAttribute = reader.getAttribute(classAttributeIdentifier);
   if (classAttribute != null) {
     return classMapper.realClass(classAttribute);
   } else {
     return classMapper.defaultImplementationOf(beanProvider.getPropertyType(result, fieldName));
   }
 }
예제 #8
0
 @Override
 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
   List<String> names = new ArrayList<String>();
   while (reader.hasMoreChildren()) {
     reader.moveDown();
     names.add(reader.getAttribute(Constants.ATTRIBUTE_PLAYER_NAME));
     reader.moveUp();
   }
   return new PlayersXML(names);
 }
 @Override
 protected void unmarshalEntry(
     HierarchicalStreamReader reader, UnmarshallingContext context, Map map) {
   String key = reader.getNodeName();
   if (key.equals(getEntryNodeName())) key = reader.getAttribute("key");
   if (key == null) {
     super.unmarshalEntry(reader, context, map);
   } else {
     unmarshalStringKey(reader, context, map, key);
   }
 }
예제 #10
0
    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

      String c0 = reader.getAttribute(Constants.ATTRIBUTE_PLACEMENT_C0);
      String d0 = reader.getAttribute(Constants.ATTRIBUTE_PLACEMENT_D0);
      String a0 = reader.getAttribute(Constants.ATTRIBUTE_PLACEMENT_A0);
      String c1 = reader.getAttribute(Constants.ATTRIBUTE_PLACEMENT_C1);
      String d1 = reader.getAttribute(Constants.ATTRIBUTE_PLACEMENT_D1);
      String a1 = reader.getAttribute(Constants.ATTRIBUTE_PLACEMENT_A1);

      Placement placement =
          new Placement(
              Color.valueOf(c0),
              Integer.valueOf(d0),
              Integer.valueOf(a0),
              Color.valueOf(c1),
              Integer.valueOf(d1),
              Integer.valueOf(a1));
      return new PlacementXML(placement);
    }
예제 #11
0
    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

      String c0 = reader.getAttribute("orange");
      String d0 = reader.getAttribute("red");
      String a0 = reader.getAttribute("green");
      String c1 = reader.getAttribute("yellow");
      String d1 = reader.getAttribute("purple");
      String a1 = reader.getAttribute("blue");

      Score score = new Score();
      score.setValue(Color.ORANGE, Integer.valueOf(c0));
      score.setValue(Color.RED, Integer.valueOf(d0));
      score.setValue(Color.GREEN, Integer.valueOf(a0));
      score.setValue(Color.YELLOW, Integer.valueOf(c1));
      score.setValue(Color.PURPLE, Integer.valueOf(d1));
      score.setValue(Color.BLUE, Integer.valueOf(a1));

      return score;
    }
 protected Object instantiateNewInstance(
     HierarchicalStreamReader reader, UnmarshallingContext context) {
   String readResolveValue = reader.getAttribute(mapper.aliasForAttribute("resolves-to"));
   Object currentObject = context.currentObject();
   if (currentObject != null) {
     return currentObject;
   } else if (readResolveValue != null) {
     return reflectionProvider.newInstance(mapper.realClass(readResolveValue));
   } else {
     return reflectionProvider.newInstance(context.getRequiredType());
   }
 }
예제 #13
0
 @Override
 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
   String name = reader.getAttribute(Constants.ATTRIBUTE_RESULT_NAME);
   List<Placement> placements = new ArrayList<Placement>();
   while (reader.hasMoreChildren()) {
     reader.moveDown();
     PlacementXML placementXML = (PlacementXML) context.convertAnother(null, PlacementXML.class);
     placements.add(placementXML.getPlacement());
     reader.moveUp();
   }
   return new ResultXML(name, placements);
 }
예제 #14
0
  public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

    Object obj = context.currentObject();
    if (obj == null) {
      try {
        obj = context.getRequiredType().newInstance();
      } catch (Exception e) {
        throw new ObjectAccessException(
            "Cannot construct " + context.getRequiredType().getName(), e);
      }
    }

    Iterator attNames = reader.getAttributeNames();
    while (attNames.hasNext()) {
      String attName = (String) attNames.next();
      if (attName.equals(textName)) {
        continue;
      }

      try {
        Field field = obj.getClass().getDeclaredField(mapper.realMember(obj.getClass(), attName));
        if (!field.isAccessible()) {
          field.setAccessible(true);
        }
        String v = reader.getAttribute(attName);
        if (null == v || "".equals(v)) {
          continue;
        }
        Class fieldType = field.getType();
        Constructor strnum = fieldType.getDeclaredConstructor(String.class);
        field.set(obj, strnum.newInstance(v));
      } catch (Exception e) {
        e.printStackTrace();
        throw new ObjectAccessException("Cannot construct " + obj.getClass(), e);
      }
    }
    String value = reader.getValue();
    if (null != value && !"".equals(value)) {
      try {
        Field field = obj.getClass().getDeclaredField(mapper.realMember(obj.getClass(), textName));
        if (!field.isAccessible()) {
          field.setAccessible(true);
        }
        field.set(obj, value);
      } catch (Exception e) {
        e.printStackTrace();
        throw new ObjectAccessException("Cannot construct " + obj.getClass(), e);
      }
    }
    return obj;
  }
예제 #15
0
    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

      if (Constants.TAG_NULL_TILE.equals(reader.getNodeName())) {
        Tile tile = new NullTile();
        return tile;
      } else {
        String c0 = reader.getAttribute(Constants.ATTRIBUTE_TILE_C0);
        String c1 = reader.getAttribute(Constants.ATTRIBUTE_TILE_C1);

        Tile tile = new Tile(Color.valueOf(c0), Color.valueOf(c1));
        return new TileXML(tile);
      }
    }
예제 #16
0
    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

      String players = reader.getAttribute(Constants.ATTRIBUTE_BOARD_PLAYERS);
      int numberOfPlayers = new Integer(players).intValue();

      List<Placement> currentPlacements = new ArrayList<Placement>();
      while (reader.hasMoreChildren()) {
        reader.moveDown();
        PlacementXML placementXML = (PlacementXML) context.convertAnother(null, PlacementXML.class);
        currentPlacements.add(placementXML.getPlacement());
        reader.moveUp();
      }

      return new BoardXML(numberOfPlayers, currentPlacements);
    }
예제 #17
0
 public void copy(HierarchicalStreamReader source, HierarchicalStreamWriter destination) {
   destination.startNode(source.getNodeName());
   int attributeCount = source.getAttributeCount();
   for (int i = 0; i < attributeCount; i++) {
     destination.addAttribute(source.getAttributeName(i), source.getAttribute(i));
   }
   String value = source.getValue();
   if (value != null && value.length() > 0) {
     destination.setValue(value);
   }
   while (source.hasMoreChildren()) {
     source.moveDown();
     copy(source, destination);
     source.moveUp();
   }
   destination.endNode();
 }
 protected void unmarshalStringKey(
     HierarchicalStreamReader reader, UnmarshallingContext context, Map map, String key) {
   String type = reader.getAttribute("type");
   Object value;
   if (type == null && reader.hasMoreChildren()) {
     reader.moveDown();
     value = readItem(reader, context, map);
     reader.moveUp();
   } else {
     Class typeC = type != null ? mapper().realClass(type) : String.class;
     try {
       value = TypeCoercions.coerce(reader.getValue(), typeC);
     } catch (Exception e) {
       log.warn("FAILED to coerce " + reader.getValue() + " to " + typeC + ": " + e);
       throw Exceptions.propagate(e);
     }
   }
   map.put(key, value);
 }
예제 #19
0
    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

      String numberOfPlayersStr = reader.getAttribute(Constants.ATTRIBUTE_ACCEPT_PLAYER);
      int numberOfPlayers;
      try {
        numberOfPlayers = Integer.parseInt(numberOfPlayersStr);
      } catch (NumberFormatException e) {
        return null;
      }
      List<Tile> tiles = new ArrayList<Tile>();
      while (reader.hasMoreChildren()) {
        reader.moveDown();
        TileXML tileXML = (TileXML) context.convertAnother(null, TileXML.class);
        tiles.add(tileXML.getTile());
        reader.moveUp();
      }
      return new AcceptXML(numberOfPlayers, tiles);
    }
예제 #20
0
    public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) {
      final WorkItemHandlerModelImpl wih = new WorkItemHandlerModelImpl();
      wih.setType(reader.getAttribute("type"));
      /* TODO make qualifiers working properly before readd them to the xml
      String qualifierType = reader.getAttribute("qualifier");
      if (qualifierType != null) {
          wih.newQualifierModel(qualifierType);
      }

      readNodes( reader, new AbstractXStreamConverter.NodeReader() {
          public void onNode(HierarchicalStreamReader reader,
                             String name,
                             String value) {
              if ( "qualifier".equals( name ) ) {
                  QualifierModelImpl qualifier = readObject(reader, context, QualifierModelImpl.class);
                  wih.setQualifierModel(qualifier);
              }
          }
      } );
      */
      return wih;
    }
 @SuppressWarnings("unchecked")
 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
   List interfaces = new ArrayList();
   InvocationHandler handler = null;
   while (reader.hasMoreChildren()) {
     reader.moveDown();
     String elementName = reader.getNodeName();
     if (elementName.equals("interface")) {
       interfaces.add(mapper.realClass(reader.getValue()));
     } else if (elementName.equals("handler")) {
       Class handlerType = mapper.realClass(reader.getAttribute("class"));
       handler = (InvocationHandler) context.convertAnother(null, handlerType);
     }
     reader.moveUp();
   }
   if (handler == null) {
     throw new ConversionException("No InvocationHandler specified for dynamic proxy");
   }
   Class[] interfacesAsArray = new Class[interfaces.size()];
   interfaces.toArray(interfacesAsArray);
   return Proxy.newProxyInstance(classLoader, interfacesAsArray, handler);
 }
예제 #22
0
    public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) {
      final KieSessionModelImpl kSession = new KieSessionModelImpl();
      kSession.name = reader.getAttribute("name");
      kSession.setDefault("true".equals(reader.getAttribute("default")));

      String kSessionType = reader.getAttribute("type");
      kSession.setType(
          kSessionType != null
              ? KieSessionType.valueOf(kSessionType.toUpperCase())
              : KieSessionType.STATEFUL);

      String clockType = reader.getAttribute("clockType");
      if (clockType != null) {
        kSession.setClockType(ClockTypeOption.get(clockType));
      }

      String beliefSystem = reader.getAttribute("beliefSystem");
      if (beliefSystem != null) {
        kSession.setBeliefSystem(BeliefSystemTypeOption.get(beliefSystem));
      }

      String scope = reader.getAttribute("scope");
      if (scope != null) {
        kSession.setScope(scope);
      }

      readNodes(
          reader,
          new AbstractXStreamConverter.NodeReader() {
            public void onNode(HierarchicalStreamReader reader, String name, String value) {
              if ("listeners".equals(name)) {
                while (reader.hasMoreChildren()) {
                  reader.moveDown();
                  String nodeName = reader.getNodeName();
                  ListenerModelImpl listener = readObject(reader, context, ListenerModelImpl.class);
                  listener.setKSession(kSession);
                  listener.setKind(ListenerModel.Kind.fromString(nodeName));
                  kSession.addListenerModel(listener);
                  reader.moveUp();
                }
              } else if ("workItemHandlers".equals(name)) {
                List<WorkItemHandlerModelImpl> wihs =
                    readObjectList(reader, context, WorkItemHandlerModelImpl.class);
                for (WorkItemHandlerModelImpl wih : wihs) {
                  wih.setKSession(kSession);
                  kSession.addWorkItemHandelerModel(wih);
                }
              } else if ("consoleLogger".equals(name)) {
                String consoleLogger = reader.getAttribute("name");
                kSession.setConsoleLogger(consoleLogger == null ? "" : consoleLogger);
              } else if ("fileLogger".equals(name)) {
                FileLoggerModelImpl fileLoggerModel =
                    new FileLoggerModelImpl(reader.getAttribute("file"));
                try {
                  fileLoggerModel.setInterval(Integer.parseInt(reader.getAttribute("interval")));
                } catch (Exception e) {
                }
                try {
                  fileLoggerModel.setThreaded(
                      Boolean.parseBoolean(reader.getAttribute("threaded")));
                } catch (Exception e) {
                }
                kSession.fileLogger = fileLoggerModel;
              }
            }
          });
      return kSession;
    }
예제 #23
0
 /* (non-Javadoc)
  * @see com.thoughtworks.xstream.converters.Converter#unmarshal(com.thoughtworks.xstream.io.HierarchicalStreamReader, com.thoughtworks.xstream.converters.UnmarshallingContext)
  */
 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
   URI uri = URI.create(reader.getAttribute("uri"));
   return XExtensionManager.instance().getByUri(uri);
 }
  // ----------------------------------------------------------
  public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
    //        Object current = context.currentObject();
    Object result = getInstance(context);
    //        Object result = null;
    if (top == true && key != null && cache != null) {
      // This is simply to prevent infinite recursion when you get an
      // object out of the store that references this object. This stored
      // object will be overwritten when everything is finished.
      cache.put(key, new StoredObject(key, "ALIAS", result, Snapshot.getLocal(), Long.MAX_VALUE));
      top = false;
    }
    Map<String, Object> fields = null;
    UUID id = null;
    if (reader.getAttribute(XMLConstants.FIELDSET_ATTRIBUTE) != null) {
      String objId = reader.getAttribute(XMLConstants.ID_ATTRIBUTE);
      id = UUID.fromString(objId);
      @SuppressWarnings("unchecked")
      Map<String, Object> realFields =
          (Map<String, Object>) mapConverter.unmarshal(reader, context);
      fields = realFields;
    } else {
      result = super.unmarshal(reader, context);
      if (result instanceof TreeMap && !TreeMap.class.isAssignableFrom(context.getRequiredType())) {
        @SuppressWarnings("unchecked")
        Map<String, Object> realFields = (Map<String, Object>) result;
        fields = realFields;
      }
    }

    if (fields != null) {
      try {
        Method initFieldsMethod = result.getClass().getMethod("initializeFields", (Class<?>) null);
        initFieldsMethod.invoke(result, (Object[]) null);
      } catch (Exception e) {
        // its ok if this doesnt exist
      }
      //            result = reflectionProvider.newInstance( context.getRequiredType() );
      restoreObjectFromFieldMap(result, fields); /*
                                                               * && pjProvider
                                                               * != null
                                                               */
      //            {
      //                try
      //                {
      //                    Method initFieldsMethod = result.getClass()
      //                        .getMethod( "initializeFields", (Class<?>)null );
      //                    initFieldsMethod.invoke( result, (Object[])null );
      //                }
      //                catch ( Exception e )
      //                {
      //                    try
      //                    {
      //                        Constructor<?> defaultConst = result.getClass()
      //                            .getConstructor();
      //                        Object newResult = defaultConst.newInstance();
      //                        restoreObjectFromFieldMap( newResult, fields );
      //                        result = newResult;
      //
      //                    }
      //                    catch ( SecurityException e1 )
      //                    {
      //                        System.err.println( "You made your default constructor for "
      //                            + result.getClass().getName()
      //                            + " private.  If you would like it to be used"
      //                            + " by the persistence library please make it public" );
      //                    }
      //                    catch ( NoSuchMethodException e2 )
      //                    {
      //                        System.err.println( "The shared object \""
      //                            + result.getClass().getName()
      //                            + "\" you have loaded did not "
      //                            + "contain all of the fields present in your original object.  "
      //                            + "We were also unable to find a method with the signature
      // \"public "
      //                            + "void initializeFields()\" or the "
      //                            + "default constructor \"public "
      //                            + result.getClass().getName()
      //                            + "()\".  If you have made assumptions "
      //                            + "about the state of certain fields in your "
      //                            + result.getClass().getName()
      //                            + " Object please provide one of these methods to initialize the
      // fields "
      //                            + "not present in the datastore." );
      //                    }
      //                    catch ( Exception e3 )
      //                    {
      //                        System.err.println( "An exception occured when initializing your
      // object with the default constructor." );
      //                    }
      //
      //                }
      //            }

      if (result != null) {
        Snapshot.getLocal().resolveObject(id, result, fields);
      }
    }

    return result;
  }
  private Plot createPlot(HierarchicalStreamReader reader) {
    Plot plot = null;
    if (reader.getNodeName().equals("barPlot")) {
      BarPlot barPlot = new BarPlot();
      barPlot.getGrid().setVisible(false);
      String flavor = reader.getAttribute("flavor");
      if (flavor != null) {
        try {
          barPlot.setFlavor(Enum.valueOf(BarPlotFlavor.class, flavor.toUpperCase()));
        } catch (Exception ex) {
          // Do nothing, we'll stay with the default.
        }
      }
      plot = barPlot;
    } else if (reader.getNodeName().equals("linePlot")) {
      LinePlot linePlot = new LinePlot();
      linePlot.getGrid().setVisible(false);
      String flavor = reader.getAttribute("flavor");
      if (flavor != null) {
        try {
          linePlot.setFlavor(Enum.valueOf(LinePlotFlavor.class, flavor.toUpperCase()));
        } catch (Exception ex) {
          // Do nothing, we'll stay with the default.
        }
      }
      plot = linePlot;
    } else if (reader.getNodeName().equals("areaPlot")) {
      AreaPlot areaPlot = new AreaPlot();
      areaPlot.getGrid().setVisible(false);
      plot = areaPlot;
    } else if (reader.getNodeName().equals("scatterPlot")) {
      ScatterPlot scatterPlot = new ScatterPlot();
      scatterPlot.getGrid().setVisible(false);
      plot = scatterPlot;
    } else if (reader.getNodeName().equals("piePlot")) {
      PiePlot piePlot = new PiePlot();
      piePlot.getLabels().setVisible(false);
      piePlot.setAnimate(Boolean.parseBoolean(reader.getAttribute("animate")));
      try {
        piePlot.setStartAngle(Integer.parseInt(reader.getAttribute("startAngle")));
      } catch (Exception ex) {
        // Do nothing.We won't set the start angle
      }
      plot = piePlot;
    } else if (reader.getNodeName().equals("dialPlot")) {
      DialPlot dialPlot = new DialPlot();
      dialPlot.setAnimate(Boolean.parseBoolean(reader.getAttribute("animate")));
      plot = dialPlot;
    }

    String orientation = reader.getAttribute("orientation");
    if (orientation != null) {
      try {
        plot.setOrientation(Enum.valueOf(Orientation.class, orientation.toUpperCase()));
      } catch (Exception ex) {
        // Do nothing, we'll stay with the default.
      }
    }

    String cssStyle = reader.getAttribute("style");
    if (cssStyle != null) {
      plot.getStyle().setStyleString(cssStyle);
    }

    while (reader.hasMoreChildren()) {
      reader.moveDown();
      if (reader.getNodeName().equals("palette")) {
        CssStyle paintStyle = new CssStyle();
        Palette palette = new Palette();
        while (reader.hasMoreChildren()) {
          reader.moveDown();
          if (reader.getNodeName().equals("paint")) {
            cssStyle = reader.getAttribute("style");
            if (cssStyle != null) {
              paintStyle.setStyleString(cssStyle);
              Integer color = paintStyle.getColor();
              if (color != null) {
                palette.add(color);
              }
            }
          }
          reader.moveUp();
        }
        if (palette.size() > 0) {
          plot.setPalette(palette);
        }
      }
      if ((reader.getNodeName().equals("verticalAxis")
              || reader.getNodeName().equals("horizontalAxis"))
          && (plot instanceof TwoAxisPlot)) {
        TwoAxisPlot twoAxisPlot = (TwoAxisPlot) plot;
        Axis axis =
            (reader.getNodeName().equals("verticalAxis")
                ? twoAxisPlot.getVerticalAxis()
                : twoAxisPlot.getHorizontalAxis());
        String axisLabelOrientation = reader.getAttribute("labelOrientation");
        try {
          axis.setLabelOrientation(
              Enum.valueOf(LabelOrientation.class, axisLabelOrientation.toUpperCase()));
        } catch (Exception ex) {
          // Do nothing, we'll stay with the default.
        }
        if (axis instanceof NumericAxis) {
          NumericAxis numericAxis = (NumericAxis) axis;
          String minValueStr = reader.getAttribute("minValue");
          if (minValueStr != null) {
            try {
              numericAxis.setMinValue(Integer.parseInt(minValueStr));
            } catch (NumberFormatException ex) {
              try {
                numericAxis.setMinValue(Double.parseDouble(minValueStr));
              } catch (NumberFormatException ex2) {
                // Do nothing. No min value will be assigned.
              }
            }
          }
          String maxValueStr = reader.getAttribute("maxValue");
          if (maxValueStr != null) {
            if (maxValueStr != null) {
              try {
                numericAxis.setMaxValue(Integer.parseInt(maxValueStr));
              } catch (NumberFormatException ex) {
                try {
                  numericAxis.setMaxValue(Double.parseDouble(maxValueStr));
                } catch (NumberFormatException ex2) {
                  // Do nothing. No min value will be assigned.
                }
              }
            }
          }
        }
        cssStyle = reader.getAttribute("style");
        if (cssStyle != null) {
          axis.getStyle().setStyleString(cssStyle);
        }
        while (reader.hasMoreChildren()) {
          reader.moveDown();
          String legend = reader.getValue();
          if (legend != null) {
            axis.getLegend().setText(legend);
          }
          cssStyle = reader.getAttribute("style");
          if (cssStyle != null) {
            axis.getLegend().getStyle().setStyleString(cssStyle);
          }
          reader.moveUp();
        }
      }

      if (reader.getNodeName().equals("grid") && (plot instanceof TwoAxisPlot)) {
        TwoAxisPlot twoAxisPlot = (TwoAxisPlot) plot;
        Grid grid = twoAxisPlot.getGrid();
        grid.setVisible(true);
        while (reader.hasMoreChildren()) {
          reader.moveDown();
          if (reader.getNodeName().equals("verticalLines")) {
            cssStyle = reader.getAttribute("style");
            if (cssStyle != null) {
              grid.getVerticalLineStyle().setStyleString(cssStyle);
            }
          } else if (reader.getNodeName().equals("horizontalLines")) {
            cssStyle = reader.getAttribute("style");
            if (cssStyle != null) {
              grid.getHorizontalLineStyle().setStyleString(cssStyle);
            }
          }
          reader.moveUp();
        }
      }

      if (reader.getNodeName().equals("scale") && (plot instanceof DialPlot)) {
        while (reader.hasMoreChildren()) {
          CssStyle rangeStyle = new CssStyle();
          Integer color = null;
          Double rangeMin = null;
          Double rangeMax = null;
          reader.moveDown();
          if (reader.getNodeName().equals("range")) {
            cssStyle = reader.getAttribute("style");
            if (cssStyle != null) {
              rangeStyle.setStyleString(cssStyle);
              color = rangeStyle.getColor();
            }
            String str = reader.getAttribute("min");
            if (str != null) {
              rangeMin = new Double(str);
            }
            str = reader.getAttribute("max");
            if (str != null) {
              rangeMax = new Double(str);
            }
            ((DialPlot) plot).getScale().addRange(new DialRange(rangeMin, rangeMax, color));
          }
          reader.moveUp();
        }
      }
      if (reader.getNodeName().equals("labels") && (plot instanceof PiePlot)) {
        PiePlot piePlot = (PiePlot) plot;
        piePlot.getLabels().setVisible(true);
        cssStyle = reader.getAttribute("style");
        if (cssStyle != null) {
          piePlot.getLabels().getStyle().setStyleString(cssStyle);
        }
      }
      if (reader.getNodeName().equals("annotation") && (plot instanceof DialPlot)) {
        DialPlot dialPlot = (DialPlot) plot;
        String annotation = reader.getValue();
        if (annotation != null) {
          dialPlot.getAnnotation().setText(annotation);
        }
        cssStyle = reader.getAttribute("style");
        if (cssStyle != null) {
          dialPlot.getAnnotation().getStyle().setStyleString(cssStyle);
        }
      }
      reader.moveUp();
    }
    return plot;
  }
 @Override
 protected void readAdditional(
     DrawComponent dc, HierarchicalStreamReader reader, UnmarshallingContext context) {
   LineDrawComponent ldc = (LineDrawComponent) dc;
   ldc.setConnect(Boolean.parseBoolean(reader.getAttribute(CONNECT)));
 }
  public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

    ChartModel chartModel = new ChartModel();
    chartModel.setChartEngineId(reader.getAttribute("chartEngine"));

    String attribute = reader.getAttribute("theme");
    if (attribute != null) {
      try {
        chartModel.setTheme(Enum.valueOf(ChartTheme.class, attribute.toUpperCase()));
      } catch (Exception e) {
        // Do nothing
      }
    }

    String cssStyle = reader.getAttribute("style");
    if (cssStyle != null) {
      chartModel.getStyle().setStyleString(cssStyle);
    }

    while (reader.hasMoreChildren()) {
      reader.moveDown();
      if (reader.getNodeName().equals("title")) {
        String title = reader.getValue();
        if (title != null) {
          chartModel.getTitle().setText(title);
        }
        cssStyle = reader.getAttribute("style");
        if (cssStyle != null) {
          chartModel.getTitle().getStyle().setStyleString(cssStyle);
        }
        attribute = reader.getAttribute("location");
        if (attribute != null) {
          try {
            chartModel
                .getTitle()
                .setLocation(Enum.valueOf(TitleLocation.class, attribute.toUpperCase()));
          } catch (Exception e) {
            // Do nothing
          }
        }
      } else if (reader.getNodeName().equals("subtitle")) {
        String subtitle = reader.getValue();
        if ((subtitle != null) && (subtitle.trim().length() > 0)) {
          StyledText styledText = new StyledText(subtitle);
          cssStyle = reader.getAttribute("style");
          if (cssStyle != null) {
            styledText.getStyle().setStyleString(cssStyle);
          }
          chartModel.getSubtitles().add(styledText);
        }
      } else if (reader.getNodeName().equals("legend")) {
        chartModel.getLegend().setVisible(true);
        cssStyle = reader.getAttribute("style");
        if (cssStyle != null) {
          chartModel.getLegend().getStyle().setStyleString(cssStyle);
        }
      } else if (reader.getNodeName().equals("barPlot")
          || reader.getNodeName().equals("linePlot")
          || reader.getNodeName().equals("areaPlot")
          || reader.getNodeName().equals("piePlot")
          || reader.getNodeName().equals("dialPlot")
          || reader.getNodeName().equals("scatterPlot")) {
        chartModel.setPlot(createPlot(reader));
      }
      reader.moveUp();
    }

    return chartModel;
  }
  public Object doUnmarshal(
      final Object result,
      final HierarchicalStreamReader reader,
      final UnmarshallingContext context) {
    final SeenFields seenFields = new SeenFields();
    Iterator it = reader.getAttributeNames();
    // Remember outermost Saveable encountered, for reporting below
    if (result instanceof Saveable && context.get("Saveable") == null)
      context.put("Saveable", result);

    // Process attributes before recursing into child elements.
    while (it.hasNext()) {
      String attrAlias = (String) it.next();
      String attrName = mapper.attributeForAlias(attrAlias);
      Class classDefiningField = determineWhichClassDefinesField(reader);
      boolean fieldExistsInClass = fieldDefinedInClass(result, attrName);
      if (fieldExistsInClass) {
        Field field = reflectionProvider.getField(result.getClass(), attrName);
        SingleValueConverter converter =
            mapper.getConverterFromAttribute(field.getDeclaringClass(), attrName, field.getType());
        Class type = field.getType();
        if (converter == null) {
          converter = mapper.getConverterFromItemType(type);
        }
        if (converter != null) {
          Object value = converter.fromString(reader.getAttribute(attrAlias));
          if (type.isPrimitive()) {
            type = Primitives.box(type);
          }
          if (value != null && !type.isAssignableFrom(value.getClass())) {
            throw new ConversionException(
                "Cannot convert type " + value.getClass().getName() + " to type " + type.getName());
          }
          reflectionProvider.writeField(result, attrName, value, classDefiningField);
          seenFields.add(classDefiningField, attrName);
        }
      }
    }

    Map implicitCollectionsForCurrentObject = null;
    while (reader.hasMoreChildren()) {
      reader.moveDown();

      try {
        String fieldName = mapper.realMember(result.getClass(), reader.getNodeName());
        boolean implicitCollectionHasSameName =
            mapper.getImplicitCollectionDefForFieldName(result.getClass(), reader.getNodeName())
                != null;

        Class classDefiningField = determineWhichClassDefinesField(reader);
        boolean fieldExistsInClass =
            !implicitCollectionHasSameName && fieldDefinedInClass(result, fieldName);

        Class type =
            determineType(reader, fieldExistsInClass, result, fieldName, classDefiningField);
        final Object value;
        if (fieldExistsInClass) {
          Field field = reflectionProvider.getField(result.getClass(), fieldName);
          value = unmarshalField(context, result, type, field);
          // TODO the reflection provider should have returned the proper field in first place ....
          Class definedType =
              reflectionProvider.getFieldType(result, fieldName, classDefiningField);
          if (!definedType.isPrimitive()) {
            type = definedType;
          }
        } else {
          value = context.convertAnother(result, type);
        }

        if (value != null && !type.isAssignableFrom(value.getClass())) {
          LOGGER.warning(
              "Cannot convert type " + value.getClass().getName() + " to type " + type.getName());
          // behave as if we didn't see this element
        } else {
          if (fieldExistsInClass) {
            reflectionProvider.writeField(result, fieldName, value, classDefiningField);
            seenFields.add(classDefiningField, fieldName);
          } else {
            implicitCollectionsForCurrentObject =
                writeValueToImplicitCollection(
                    context, value, implicitCollectionsForCurrentObject, result, fieldName);
          }
        }
      } catch (NonExistentFieldException e) {
        LOGGER.log(WARNING, "Skipping a non-existent field " + e.getFieldName(), e);
        addErrorInContext(context, e);
      } catch (CannotResolveClassException e) {
        LOGGER.log(WARNING, "Skipping a non-existent type", e);
        addErrorInContext(context, e);
      } catch (LinkageError e) {
        LOGGER.log(WARNING, "Failed to resolve a type", e);
        addErrorInContext(context, e);
      }

      reader.moveUp();
    }

    // Report any class/field errors in Saveable objects
    if (context.get("ReadError") != null && context.get("Saveable") == result) {
      OldDataMonitor.report((Saveable) result, (ArrayList<Throwable>) context.get("ReadError"));
      context.put("ReadError", null);
    }
    return result;
  }
예제 #29
0
 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
   OrmEntity entity = new OrmEntity();
   entity.setClassName(reader.getAttribute("class"));
   return entity;
 }
 private Class determineWhichClassDefinesField(HierarchicalStreamReader reader) {
   String definedIn = reader.getAttribute(mapper.aliasForAttribute("defined-in"));
   return definedIn == null ? null : mapper.realClass(definedIn);
 }