Java 类org.simpleframework.xml.core.Persister 实例源码

项目:shortstories    文件:ChoiceActivity.java   
@Override
protected void performPreFinishOperations() {
    Serializer serializer = new Persister();
    String choiceXml = getIntent().getExtras().getString(IntentUtil.EXTRA_CHOICE_XML);
    try {
        mChoice = serializer.read(Choice.class, choiceXml);
    } catch (Exception e) {
        Log.d(TAG, e.toString());
        return;
    }
    Settings settings = new Settings(this);
    mNotificationPriority = settings.notificationPriority();
    mGoHomeNewScenario = settings.goHomeNewScenario();
    mExpandNotificationsNewScenario = settings.expandNotificationsNewScenario();
    setAchievements();
    maybeAdjustProgress();
    showScenarioNotification();
    disableExistingShortcuts();
    addChoiceShortcuts();
    goHomeToHideShortcuts();
    expandNotificationsPanelDelayed();
}
项目:shortstories    文件:IntentUtil.java   
public static Intent addShowScenarioShortcut(Context context, Choice choice) {
    Intent addShowScenarioShortcutIntent = new Intent(context, AddShowScenarioShortcutActivity.class);
    addShowScenarioShortcutIntent = IntentCompat.makeRestartActivityTask(addShowScenarioShortcutIntent.getComponent());
    addShowScenarioShortcutIntent.setAction(Intent.ACTION_VIEW);
    addShowScenarioShortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    Serializer serializer = new Persister();
    ByteArrayOutputStream choiceOutputStream = new ByteArrayOutputStream();
    try {
        serializer.write(choice, choiceOutputStream);
    } catch (Exception e) {
        Log.d(TAG, e.toString());
    }
    String choiceXml = choiceOutputStream.toString();
    addShowScenarioShortcutIntent.putExtra(EXTRA_CHOICE_XML, choiceXml);
    return addShowScenarioShortcutIntent;
}
项目:oneops    文件:NotificationConfigurator.java   
public void init() {
    InputStream is = this.getClass().getResourceAsStream("/notification.config.xml");
    if (is == null) {
        logger.warn("Notification config file not found!");
        return;
    }
    Serializer serializer = new Persister();
    try {
        this.ruleList = serializer.read(NotificationRuleList.class, is);
        is.close();
    } catch (Exception e) {
        logger.error("Read configuration file error!");
        e.printStackTrace();
    }
    if (ruleList != null && ruleList.getRules() != null) {
        ruleMap = new HashMap<>();
        for (NotificationRule rule : ruleList.getRules()) {
            EventSource source = rule.getSource();
            if (!ruleMap.containsKey(source)) {
                ruleMap.put(source, new ArrayList<>());
            }
            ruleMap.get(source).add(rule);
        }
        configured = true;
    }
}
项目:Android-DFU-App    文件:UARTActivity.java   
@Override
public void onRenameConfiguration(final String newName) {
    final boolean exists = mDatabaseHelper.configurationExists(newName);
    if (exists) {
        Toast.makeText(this, R.string.uart_configuration_name_already_taken, Toast.LENGTH_LONG).show();
        return;
    }

    final String oldName = mConfiguration.getName();
    mConfiguration.setName(newName);

    try {
        final Format format = new Format(new HyphenStyle());
        final Strategy strategy = new VisitorStrategy(new CommentVisitor());
        final Serializer serializer = new Persister(strategy, format);
        final StringWriter writer = new StringWriter();
        serializer.write(mConfiguration, writer);
        final String xml = writer.toString();

        mDatabaseHelper.renameConfiguration(oldName, newName, xml);
        mWearableSynchronizer.onConfigurationAddedOrEdited(mPreferences.getLong(PREFS_CONFIGURATION, 0), mConfiguration);
        refreshConfigurations();
    } catch (final Exception e) {
        Log.e(TAG, "Error while renaming configuration", e);
    }
}
项目:Android-DFU-App    文件:UARTActivity.java   
/**
 * Saves the given configuration in the database.
 */
private void saveConfiguration() {
    final UartConfiguration configuration = mConfiguration;
    try {
        final Format format = new Format(new HyphenStyle());
        final Strategy strategy = new VisitorStrategy(new CommentVisitor());
        final Serializer serializer = new Persister(strategy, format);
        final StringWriter writer = new StringWriter();
        serializer.write(configuration, writer);
        final String xml = writer.toString();

        mDatabaseHelper.updateConfiguration(configuration.getName(), xml);
        mWearableSynchronizer.onConfigurationAddedOrEdited(mPreferences.getLong(PREFS_CONFIGURATION, 0), configuration);
    } catch (final Exception e) {
        Log.e(TAG, "Error while creating a new configuration", e);
    }
}
项目:Proyecto-DASI    文件:RecursoPersistenciaEntornosSimulacionImp1.java   
public EscenarioSimulacionRobtsVictms obtenerInfoEscenarioSimulacion(String identFicheroInfoPersistencia){
         try {
              File ficheroEscenario = this.obtenerFicheroEscenario(identFicheroInfoPersistencia);

                if(ficheroEscenario== null){
//                    dirFicherosPersistencia.mkdir();
//                    rutaFicheroInfoPersistencia= dirFicherosPersistencia.getAbsolutePath()+"\\";
                System.out.println("El fichero   : "+ identFicheroInfoPersistencia+ " No existe " );

                }else {
                   Serializer serializer = new Persister();
//                 EscenarioSimulacionRobtsVictms escenario = serializer.read(EscenarioSimulacionRobtsVictms.class,ficheroEscenario, false);
                return serializer.read(EscenarioSimulacionRobtsVictms.class,ficheroEscenario, false);
//                        serializer.read(EscenarioSimulacionRobtsVictms.class,ficheroEscenario, false);

                }   
                }catch (Exception e) { // catches ANY exception
        e.printStackTrace();
        }
         return null;
     }
项目:Proyecto-DASI    文件:RecursoPersistenciaEntornosSimulacionImp1.java   
public   InfoCasoSimulacion obtenerInfoCasoSimulacion(String identFicheroCaso) {
       try {
              File ficheroEscenario = this.obtenerFicheroCasoSimulacion(identFicheroCaso);

                if(ficheroEscenario== null){
//                    dirFicherosPersistencia.mkdir();
//                    rutaFicheroInfoPersistencia= dirFicherosPersistencia.getAbsolutePath()+"\\";
                System.out.println("El fichero   : "+ identFicheroCaso+ " No existe " );

                }else {
                   Serializer serializer = new Persister();
//                 EscenarioSimulacionRobtsVictms escenario = serializer.read(EscenarioSimulacionRobtsVictms.class,ficheroEscenario, false);
                return serializer.read(InfoCasoSimulacion.class,ficheroEscenario, false);


                }   
                }catch (Exception e) { // catches ANY exception
        e.printStackTrace();
    }
         return null;
     }
项目:Proyecto-DASI    文件:PersistenciaVisualizadorEscenarios.java   
public EscenarioSimulacionRobtsVictms obtenerInfoEscenarioSimulacion(String rutaFicheroInfoPersistencia){
         try {
              File ficheroEscenario = new File(rutaFicheroInfoPersistencia);
                if(!ficheroEscenario.exists()){
//                    dirFicherosPersistencia.mkdir();
//                    rutaFicheroInfoPersistencia= dirFicherosPersistencia.getAbsolutePath()+"\\";
                System.out.println("El fichero   : "+ rutaFicheroInfoPersistencia+ " No existe " );

                }else {
                   Serializer serializer = new Persister();
                return   serializer.read(EscenarioSimulacionRobtsVictms.class,ficheroEscenario, false);

                }   
                }catch (Exception e) { // catches ANY exception
        e.printStackTrace();
    }
         return null;
     }
项目:flexibee    文件:InternalDocumentTest.java   
@Test
public void parseFromXmlToObject() throws Exception {
    String xml = "<winstrom version=\"1.0\">\n" +
        "    <interni-doklad>\n" +
        "        <typDokl>code:ID</typDokl>\n" +
        "        <datVyst>2011-01-01+01:00</datVyst>\n" +
        "        <varSym>123</varSym><!-- účet MD -->\n" +
        "    </interni-doklad>\n" +
        "</winstrom>";


    Serializer serializer = new Persister(Factory.matchers());

    WinstromRequest example = serializer.read(WinstromRequest.class, xml);

    assertThat(example.getInternalDocument()).isNotNull();
    assertThat(example.getInternalDocument().getIssued()).isEqualTo("2011-01-01");
    assertThat(example.getInternalDocument().getVariableSymbol()).isEqualTo("123");
}
项目:Saiy-PS    文件:ResolveWolframAlpha.java   
public boolean validate(@NonNull final String question) {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "validate");
    }

    final Serializer serializer = new Persister();

    try {

        final ValidateQueryResult result = serializer.read(ValidateQueryResult.class, question, false);
        return result.passedValidation();

    } catch (final Exception e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "Exception");
            e.printStackTrace();
        }
    }

    return false;
}
项目:healthvault-java-sdk    文件:XmlSerializer.java   
private static Serializer getReadSerializer() throws Exception {
    if (readSerializer == null) {
    Log.d("hv", "Begin Creating Serializer");
       RegistryMatcher matcher = new RegistryMatcher();
       matcher.bind(Date.class, new DateFormatTransformer());

       Registry registry = new Registry();
       registry.bind(String.class, SimpleXMLStringConverter.class);
       Strategy strategy = new RegistryStrategy(registry);

       Serializer s = new Persister(strategy, matcher);
    Log.d("hv", "Done Creating Serializer");

    readSerializer = s;
    }
       return readSerializer;
}
项目:Asynchronous-Android-Programming    文件:XMLConverter.java   
@Override
public POJO decode(Body body) throws Exception {
    Serializer serializer = new Persister();
    InputStream is =null;
    RawBody rawBody = (RawBody)body;
    POJO obj = null;
    try {
        is= new ByteArrayInputStream(rawBody.getContent());
        BufferedReader bfReader = new BufferedReader(new InputStreamReader(is));
        obj = (POJO) serializer.read(clazz,bfReader);
        Log.i("asd", "asd");
    } finally {
        if(is != null) is.close();
    }
    return obj;
}
项目:c2mon    文件:TagConfigImpl.java   
public static TagConfigImpl fromXml(final String xml) throws Exception {

    TagConfigImpl conf = null;
    StringReader sr = null;
    Serializer serializer = new Persister(new AnnotationStrategy());

    try {
      sr = new StringReader(xml);
      conf = serializer.read(TagConfigImpl.class, new StringReader(xml), false);
    } finally {

      if (sr != null) {
        sr.close();
      }
    }

    return conf;
  }
项目:c2mon    文件:AlarmValueImpl.java   
public static AlarmValueImpl fromXml(final String xml) throws Exception {

      AlarmValueImpl alarmVal = null;
      StringReader sr = null;
      Serializer serializer = new Persister(new AnnotationStrategy());

      try {
          sr = new StringReader(xml);
          alarmVal = serializer.read(AlarmValueImpl.class, new StringReader(xml), false);
      } finally {

          if (sr != null) {
              sr.close();
          }
      }

      return alarmVal;
  }
项目:c2mon    文件:CommandTagImpl.java   
public static CommandTagImpl fromXml(final String xml) throws Exception {

    CommandTagImpl commandTag = null;
    StringReader sr = null;
    Serializer serializer = new Persister(new AnnotationStrategy());

    try {
      sr = new StringReader(xml);
      commandTag = serializer.read(CommandTagImpl.class, new StringReader(xml), false);
    } finally {

      if (sr != null) {
        sr.close();
      }
    }

    return commandTag;
  }
项目:c2mon    文件:DeviceFacadeImpl.java   
/**
 * Parse the XML representation of the properties of a device (which comes
 * from configuration) and return it as a list of {@link DeviceProperty}
 * objects.
 *
 * @param xmlString the XML representation string of the device properties
 *
 * @return the list of device properties
 * @throws Exception if the XML could not be parsed
 */
private List<DeviceProperty> parseDevicePropertiesXML(String xmlString) throws Exception {
  List<DeviceProperty> deviceProperties = new ArrayList<>();

  Serializer serializer = new Persister();
  DevicePropertyList devicePropertyList = serializer.read(DevicePropertyList.class, xmlString);

  for (DeviceProperty deviceProperty : devicePropertyList.getDeviceProperties()) {

    // Remove all whitespace and control characters
    if (deviceProperty.getValue() != null) {
      deviceProperty.setValue(deviceProperty.getValue().replaceAll("[\u0000-\u001f]", "").trim());
    }

    deviceProperties.add(deviceProperty);
  }

  return deviceProperties;
}
项目:reactive-ampache    文件:SerializeUtils.java   
public <T> T fromXml(String xmlString,Class<T> classOfT) throws Exception {
        // remove all characters before the beginning of the xml string
        // some ampache servers send 2 bytes before the actual xml
        String firstLetter = String.valueOf(xmlString.charAt(0));
        while (!firstLetter.equals("<")) {
            xmlString = xmlString.substring(1);
            firstLetter = String.valueOf(xmlString.charAt(0));
        }

        String lastLetter = String.valueOf(xmlString.charAt(xmlString.length()-1));
        while (!lastLetter.equals(">")) {
            xmlString = xmlString.substring(0,xmlString.length()-1);
            lastLetter = String.valueOf(xmlString.charAt(xmlString.length()-1));
        }

        // simple parser will fail when it finds & surrounded by spaces
        xmlString = xmlString.replace(" & "," &amp; ");
//        xmlString = xmlString.replace("?","&#63;");

        Serializer serializer = new Persister();
        Reader reader = new StringReader(xmlString);
        return serializer.read(classOfT, reader, false);
    }
项目:mesh    文件:StopWatchLogger.java   
public void flush() {
        Serializer serializer = new Persister();
        Testsuite example = new Testsuite(clazz, 0f);
        for (Entry<String, Double> entry : entries.entrySet()) {
            example.getTestcases().add(new Testcase(entry.getKey(), clazz.getName(), String.valueOf(entry.getValue()/(double)1000)));
        }
        File reportFile = new File("target", "TEST-" + clazz.getName() + ".performance.xml");
        try {
//          serializer.write(example, System.out);
            serializer.write(example, reportFile);
        } catch (Exception e) {
            log.error("Error while saving {" + reportFile.getAbsolutePath() + "} for {" + clazz.getName() + "}", e);
        }


    }
项目:code    文件:DefaultingPersist.java   
public static DefaultingModel load(String filename) {
    DefaultingModel read = null;
    Strategy strategy = new CycleStrategy("id", "ref");
    Serializer serializer = new Persister(strategy);
    File source = new File(filename);

    try {
        read = serializer.read(DefaultingModel.class, source);

        if (read != null ) {
            read.finish();
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    return read;
}
项目:code    文件:Persist.java   
public static Model load(String filename) {
    Model read = null;
    Strategy strategy = new CycleStrategy("id", "ref");
    Serializer serializer = new Persister(strategy);
    File source = new File(filename);

    try {
        read = serializer.read(Model.class, source);

        if (read != null ) {
            read.finish();
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    return read;
}
项目:code    文件:Persist.java   
public static HeuristicsModel load(String filename) {
    HeuristicsModel read = null;
    Strategy strategy = new CycleStrategy("id", "ref");
    Serializer serializer = new Persister(strategy);
    File source = new File(filename);
    try {
        if (source.exists()) {
            read = serializer.read(HeuristicsModel.class, source);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    return read;
}
项目:code    文件:TestUtils.java   
public static BaseTraceability load(String filename) {
    BaseTraceability read = null;
    Strategy strategy = new CycleStrategy("id", "ref");
    Serializer serializer = new Persister(strategy);
    File source = new File(filename);

    try {
        read = serializer.read(BaseTraceability.class, source);
    }
    catch (Exception e) {
        System.err.println("Exception when loading file:"+ filename);
        e.printStackTrace();
    }

    return read;
}
项目:ChiptuneTracker    文件:SaveFileListener.java   
@Override
public void selected(Array<FileHandle> files) {
    File file = files.first().file();
    if(!file.exists() || file.canWrite()) {
        Serializer serializer = new Persister();
        try {
            serializer.write(ChiptuneTracker.getInstance().getData(), file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(dataManager.getCurrentFile() == null) {
            dataManager.setCurrentFile(new StringBuilder());
        }
        dataManager.getCurrentFile().setLength(0);
        dataManager.getCurrentFile().append(file.getAbsolutePath());
        ChiptuneTracker.getInstance().setChangeData(false);
        additionalActions();
    }
    else {
        Dialogs.showErrorDialog(ChiptuneTracker.getInstance().getAsciiTerminal().getStage(), "Unable to write in the file !");
    }
    ((View) ChiptuneTracker.getInstance().getScreen()).setListActorTouchables(Touchable.enabled);
}
项目:ChiptuneTracker    文件:DataManager.java   
public void save() throws Exception {
    if(currentFile != null) {
        File file = new File(currentFile.toString());
        if(file.canWrite()) {
            Serializer serializer = new Persister();
            serializer.write(ChiptuneTracker.getInstance().getData(), file);
            ChiptuneTracker.getInstance().setChangeData(false);
        }
        else {
            throw new IOException("Unable to write in the file !");
        }
    }
    else {
        saveAs();
    }
}
项目:webapp-stack    文件:Configuration.java   
public static void init() throws Exception{
    String configuration_filepath = System.getProperty("application.data.path")+"/"+System.getProperty("application.name")+".cfg.xml";
    Serializer serializer = new Persister();
    File file = new File(configuration_filepath);
    if(file.exists()){
        instance = serializer.read(Configuration.class, file);
    }else{
        instance = serializer.read(Configuration.class, Configuration.class.getResourceAsStream("/"+System.getProperty("application.name")+".default.cfg.xml"));
        logger.warn("Configuration file "+configuration_filepath+" not found. Using default configuration.");
        file.getParentFile().mkdirs();
        file.createNewFile();
        serializer.write(instance, file);
        logger.info("Configuration file "+configuration_filepath+" created.");
    }
    instance.datapath = System.getProperty("application.data.path");
    instance.applicationName = System.getProperty("application.name");
}
项目:openmeetings    文件:BackupImport.java   
private void importChat(File f) throws Exception {
    log.info("Room groups import complete, starting chat messages import");
    Registry registry = new Registry();
    Strategy strategy = new RegistryStrategy(registry);
    Serializer serializer = new Persister(strategy);

    registry.bind(User.class, new UserConverter(userDao, userMap));
    registry.bind(Room.class, new RoomConverter(roomDao, roomMap));
    registry.bind(Date.class, DateConverter.class);

    List<ChatMessage> list = readList(serializer, f, "chat_messages.xml", "chat_messages", ChatMessage.class);
    for (ChatMessage m : list) {
        m.setId(null);
        if (m.getFromUser() == null || m.getFromUser().getId() == null) {
            continue;
        }
        chatDao.update(m, m.getSent());
    }
}
项目:openmeetings    文件:BackupImport.java   
private void importContacts(File f) throws Exception {
    log.info("Private message folder import complete, starting user contacts import");
    Registry registry = new Registry();
    Strategy strategy = new RegistryStrategy(registry);
    Serializer serializer = new Persister(strategy);

    registry.bind(User.class, new UserConverter(userDao, userMap));

    List<UserContact> list = readList(serializer, f, "userContacts.xml", "usercontacts", UserContact.class);
    for (UserContact uc : list) {
        Long ucId = uc.getId();
        UserContact storedUC = userContactDao.get(ucId);

        if (storedUC == null && uc.getContact() != null && uc.getContact().getId() != null) {
            uc.setId(null);
            if (uc.getOwner() != null && uc.getOwner().getId() == null) {
                uc.setOwner(null);
            }
            uc = userContactDao.update(uc);
            userContactMap.put(ucId, uc.getId());
        }
    }
}
项目:openmeetings    文件:BackupImport.java   
private void importRoomFiles(File f) throws Exception {
    log.info("Poll import complete, starting room files import");
    Registry registry = new Registry();
    Strategy strategy = new RegistryStrategy(registry);
    Serializer serializer = new Persister(strategy);

    registry.bind(BaseFileItem.class, new BaseFileItemConverter(fileItemDao, fileItemMap));

    List<RoomFile> list = readList(serializer, f, "roomFiles.xml", "RoomFiles", RoomFile.class, true);
    for (RoomFile rf : list) {
        Room r = roomDao.get(roomMap.get(rf.getRoomId()));
        if (r == null || rf.getFile() == null || rf.getFile().getId() == null) {
            continue;
        }
        if (r.getFiles() == null) {
            r.setFiles(new ArrayList<>());
        }
        rf.setId(null);
        rf.setRoomId(r.getId());
        r.getFiles().add(rf);
        roomDao.update(r, null);
    }
}
项目:simple-xml-serializers    文件:TypeConverterTest.java   
@Nonnull
public static <T> T testSerialization(@Nonnull Class<T> type, @Nonnull T in) throws Exception {
    Persister persister = new Persister(new AnnotationStrategy(), newRegistryMatcher());

    LOG.info("In:  " + in);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    persister.write(in, os);
    byte[] data = os.toByteArray();
    LOG.info("Xml:  " + new String(data, Charsets.UTF_8));

    ByteArrayInputStream is = new ByteArrayInputStream(data);
    T out = persister.read(type, is);
    LOG.info("Out: " + out);

    return out;
}
项目:simplexml    文件:Test5Test.java   
public void testSerialize() throws Exception{
   Serializer s = new Persister();
   StringWriter sw = new StringWriter();
   //FIXME serialization is ok
   s.write(new Test5(new MyElementA(), new MyElementA(), new MyElementB()), sw);    
   String serializedForm = sw.toString();
   System.out.println(serializedForm);
   System.out.println();
   //FIXME but no idea what is happening
   Test5 o = s.read(Test5.class, serializedForm);
   sw.getBuffer().setLength(0);
   s.write(o, sw);
   System.out.println(sw.toString());
   System.out.println();
   sw.getBuffer().setLength(0);
}
项目:EasyVote    文件:WahlzettelDesign.java   
/**
 * l�dt die XML Datei in die Klasse rein. Sollte die Datei nicht gefunden
 * werden, wird null zur�ckgegeben.
 * 
 * @return
 * @throws ConfigFileException
 * @throws WahlzettelDesignKeyNotFoundException
 * @throws Exception
 */
private static WahlzettelDesign loadXML() throws ConfigFileException,
        WahlzettelDesignKeyNotFoundException {

    String filename = getJarExecutionDirectory()+ ConfigHandler.getInstance().getConfigValue(
            ConfigVars.WAHLZETTELDESIGNDATEI);
    //System.out.println("WZD: "+filename);
    Serializer deserializer = new Persister();
    File source = new File(filename);
    //System.out.println("exist"+source.exists());
    WahlzettelDesign wzd;
    try {
        wzd = deserializer.read(WahlzettelDesign.class, source);
    } catch (Exception e) {
        throw new WahlzettelDesignKeyNotFoundException(
                "Das Lesen der Wahlzettel-XML Datei (" + filename
                        + ") ist fehlgeschlagen.");
    }
    return wzd;
    // System.out.println(example.election_name);

}
项目:simplexml    文件:SimpleExecutor.java   
public Duration write(TestRun test) throws Exception {
long start = System.currentTimeMillis();
   Persister persister = new Persister();
   Class schemaClass = test.getSchemaClass();
   Object result = persister.read(schemaClass, test.getSourceStream());

   // Perform once to build up schema cache
   if(test.isDebug()) {
      persister.write(result, System.out);
   }
   long startWrite = System.currentTimeMillis();

   for(int i = 0; i < test.getIterations(); i++) {
      persister.write(result, test.getResultWriter());        
   }
   return new Duration(start, startWrite, test.getIterations());
}
项目:simplexml    文件:RegistryMatcherTest.java   
public void testMatcher() throws Exception {
   RegistryMatcher matcher = new RegistryMatcher();
   Transform<C> transform = new CTransform();
   matcher.bind(A.class, ATransform.class);
   matcher.bind(B.class, BTransform.class);
   matcher.bind(C.class, transform);
   Transform<A> a = matcher.match(A.class);
   Transform<B> b = matcher.match(B.class);
   Transform<C> c = matcher.match(C.class);
   A ia = a.read("A");
   B ib = b.read("B");
   C ic = c.read("C");
   assertEquals(ia.getValue(), "A");
   assertEquals(ib.getValue(), "B");
   assertEquals(ic.getValue(), "C");
   Persister persister = new Persister(matcher);
   Example example = new Example(ia, ib, ic);
   StringWriter writer = new StringWriter();
   persister.write(example, writer);
   String text = writer.toString();
   assertElementExists(text, "/example");
   assertElementExists(text, "/example/a");
   assertElementHasValue(text, "/example/a", "A");
   assertElementHasAttribute(text, "/example", "b", "B");
   assertElementHasAttribute(text, "/example", "c", "C");
}
项目:simplexml    文件:DateTransformTest.java   
public void testPersistence() throws Exception {
   long now = System.currentTimeMillis();
   Date date = new Date(now);      
   Persister persister = new Persister();
   DateExample example = new DateExample(date);
   StringWriter out = new StringWriter();

   assertEquals(example.attribute, date);
   assertEquals(example.element, date);
   assertEquals(example.array[0], date);
   assertEquals(example.list.get(0), date);
   assertEquals(example.list.get(1), date);

   persister.write(example, out);
   String text = out.toString();

   example = persister.read(DateExample.class, text);

   assertEquals(example.attribute, date);
   assertEquals(example.element, date);
   assertEquals(example.array[0], date);
   assertEquals(example.list.get(0), date);
   assertEquals(example.list.get(1), date);

   validate(example, persister);      
}
项目:simplexml    文件:HackJobToGrabFloatingTextTest.java   
public void testHackJob() throws Exception {
   Class<?> type = Class.forName("org.simpleframework.xml.stream.DocumentProvider");
   Constructor<?> constructor = type.getDeclaredConstructor();
   constructor.setAccessible(true);
   Object value = constructor.newInstance();
   Field[] fields = NodeBuilder.class.getDeclaredFields();

   for(Field field : fields) {
      if(field.getName().equalsIgnoreCase("provider")) {
         field.setAccessible(true);
         field.set(null, value);
      }
   }
   StringReader reader = new StringReader(SOURCE);
   InputNode source = NodeBuilder.read(reader);
   AnnotationStrategy strategy = new AnnotationStrategy();
   Persister persister = new Persister(strategy);
   Something something = persister.read(Something.class, source);

   assertNotNull(something);
   assertEquals(something.text, "some inner text");
   assertEquals(something.child1, "11");
   assertEquals(something.child2, "True");
}
项目:simplexml    文件:RegistryConverterCycleTest.java   
public void testCycle() throws Exception {
   Style style = new CamelCaseStyle();
   Format format = new Format(style);
   Registry registry = new Registry();
   Address address = new Address("An Address");
   Person person = new Person(address, "Niall", 30);
   CycleStrategy referencer = new CycleStrategy();
   RegistryStrategy strategy = new RegistryStrategy(registry, referencer);
   Serializer serializer = new Persister(strategy, format);
   Converter converter = new PersonConverter(serializer);
   Club club = new Club(address);

   club.addMember(person);
   registry.bind(Person.class, converter);

   serializer.write(club, System.out);
}
项目:simplexml    文件:DefaultEmptyTest.java   
public void testDefaults() throws Exception {
   Persister persister = new Persister();
   DefaultExample example = persister.read(DefaultExample.class, SOURCE);

   assertEquals(example.name, "test");
   assertEquals(example.text, "some text");
   assertNotNull(example.stringList);
   assertNotNull(example.stringMap);
   assertNotNull(example.stringArray);

   persister.write(example, System.out);

   validate(persister, example);

   persister.write(new DefaultExample("name", "example text"), System.out);
}
项目:simplexml    文件:CombinedStrategyTest.java   
public void testCombinedStrategy() throws Exception {
   Registry registry = new Registry();
   AnnotationStrategy annotationStrategy = new AnnotationStrategy();
   RegistryStrategy registryStrategy = new RegistryStrategy(registry, annotationStrategy);
   Persister persister = new Persister(registryStrategy);
   CombinationExample example = new CombinationExample(1, 2, 3);
   StringWriter writer = new StringWriter();

   registry.bind(Item.class, RegistryItemConverter.class);
   persister.write(example, writer);

   String text = writer.toString();
   System.out.println(text);

   assertElementExists(text, "/combinationExample/item/value");
   assertElementHasValue(text, "/combinationExample/item/value", "1");
   assertElementHasValue(text, "/combinationExample/item/type", RegistryItemConverter.class.getName());
   assertElementExists(text, "/combinationExample/overriddenItem");
   assertElementHasAttribute(text, "/combinationExample/overriddenItem", "value", "2");
   assertElementHasAttribute(text, "/combinationExample/overriddenItem", "type", AnnotationItemConverter.class.getName());
   assertElementExists(text, "/combinationExample/extendedItem");
   assertElementHasAttribute(text, "/combinationExample/extendedItem", "value", "3");
   assertElementHasAttribute(text, "/combinationExample/extendedItem", "type", ExtendedItemConverter.class.getName());
}
项目:simplexml    文件:AnnotationTypeTest.java   
public void testAnnotationType() throws Exception {
   Strategy strategy = new AnnotationStrategy();
   Persister persister = new Persister(strategy);
   StringWriter writer = new StringWriter();
   AnnotationExample example = persister.read(AnnotationExample.class, SOURCE);

   persister.write(example, writer);

   String text = writer.toString();

   assertElementHasAttribute(text, "/annotationExample", "age", "10");
   assertElementHasAttribute(text, "/annotationExample/name", "key", "name");

   AnnotationExample result = persister.read(AnnotationExample.class, text);

   assertEquals(example.name, result.name);
   assertEquals(example.age, result.age);

   validate(result, persister);
}
项目:simplexml    文件:ConverterMapTest.java   
public void testMap() throws Exception {
   Strategy strategy = new AnnotationStrategy();
   Serializer serializer = new Persister(strategy);
   MapHolder holder = new MapHolder();

   holder.put("a", "A");
   holder.put("b", "B");
   holder.put("c", "C");
   holder.put("d", "D");
   holder.put("e", "E");
   holder.put("f", "F");

   serializer.write(holder, System.out);

   validate(holder, serializer);
}