Java 类org.simpleframework.xml.Serializer 实例源码

项目: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    文件:WinstromRequestTest.java   
@Test
public void parseRequestToXml() throws Exception {
    WinstromRequest request = WinstromRequest.builder()
            .issuedInvoice(IssuedInvoice.builder()
                    .company("code:ABCFIRM1#")
                    .documentType("code:FAKTURA")
                    .withoutItems(true)
                    .sumWithoutVat(BigDecimal.valueOf(1000))
                    .build()).build();

    ByteArrayOutputStream result = new ByteArrayOutputStream();
    Serializer serializer = Factory.persister();
    serializer.write(request, result);

    String xml = "<winstrom version=\"1.0\">\n" +
            "  <faktura-vydana>\n" +
            "    <typDokl>code:FAKTURA</typDokl>\n" +
            "    <firma>code:ABCFIRM1#</firma>\n" +
            "    <bezPolozek>true</bezPolozek>\n" +
            "    <sumDphZakl>1000</sumDphZakl>\n" +
            "  </faktura-vydana>\n" +
            "</winstrom>";
    assertThat(result.toString()).isXmlEqualTo(xml);
}
项目:flexibee    文件:IssuedInvoiceTest.java   
@Test
public void LocalDateIsParsed() throws Exception {
    WinstromRequest envelope = WinstromRequest.builder()
            .issuedInvoice(IssuedInvoice.builder()
                    .issued(LocalDate.of(2017, 4, 2))
                    .build()).build();

    ByteArrayOutputStream result = new ByteArrayOutputStream();
    Serializer serializer = Factory.persister();
    serializer.write(envelope, result);

    String xml = "<winstrom version=\"1.0\">\n" +
            "    <faktura-vydana>\n" +
            "        <datVyst>2017-04-02</datVyst>\n" +
            "    </faktura-vydana>\n" +
            "</winstrom>";
    assertThat(result.toString()).isXmlEqualTo(xml);
}
项目:flexibee    文件:IssuedInvoiceTest.java   
@Test
public void paymentStatusIsParsedCorrectly() throws Exception {
    String xml = "<winstrom version=\"1.0\">\n" +
            "    <faktura-vydana>\n" +
            "        <stavUhrK>stavUhr.uhrazenoRucne</stavUhrK>\n" +
            "    </faktura-vydana>\n" +
            "</winstrom>\n";

    WinstromRequest envelope = WinstromRequest.builder()
            .issuedInvoice(
                    IssuedInvoice.builder()
                            .paymentStatus(PaymentStatus.MANUALLY)
                            .build()
            ).build();

    ByteArrayOutputStream result = new ByteArrayOutputStream();
    Serializer serializer = Factory.persister();
    serializer.write(envelope, result);

    assertThat(result.toString()).isXmlEqualTo(xml);
}
项目: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    文件:ConfigurationLoaderImpl.java   
@Override
public List<ConfigurationReportHeader> getConfigurationReports() {
  List<ConfigurationReportHeader> reports = new ArrayList<>();

  // Read all report files and deserialise them
  try {
    ArrayList<File> files = new ArrayList<>(Arrays.asList(new File(reportDirectory).listFiles(new ConfigurationReportFileFilter())));
    Serializer serializer = getSerializer();

    for (File file : files) {
      ConfigurationReportHeader report = serializer.read(ConfigurationReportHeader.class, file);
      log.debug("Deserialised configuration report {}", report.getId());
      reports.add(report);
    }

  } catch (Exception e) {
    log.error("Error deserialising configuration report", e);
  }

  return reports;
}
项目:c2mon    文件:ConfigurationLoaderImpl.java   
@Override
public List<ConfigurationReport> getConfigurationReports(String id) {
  List<ConfigurationReport> reports = new ArrayList<>();

  try {
    ArrayList<File> files = new ArrayList<>(Arrays.asList(new File(reportDirectory).listFiles(new ConfigurationReportFileFilter(id))));
    Serializer serializer = getSerializer();

    for (File file : files) {
      ConfigurationReport report = serializer.read(ConfigurationReport.class, file);
      log.debug("Deserialised configuration report {}", report.getId());
      reports.add(report);
    }

  } catch (Exception e) {
    log.error("Error deserialising configuration report", e);
  }

  return reports;
}
项目: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    文件:OOGUtils.java   
public static OGraph load(String filename, boolean postProcess) {
    Serializer serializer = getSerializer();
    File source = new File(filename);

    OGraph read = null;
    try {
        read = serializer.read(OGraph.class, source);
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    if ( read != null ) {
        _postProcess(read);
    }

    return read;
}
项目:code    文件:OOGUtils.java   
public static OGraph loadGZIP(String filename, boolean postProcess) {
    Serializer serializer = getSerializer();

    OGraph read = null;
    try {
        InputStream gzipInputStream = new GZIPInputStream(new FileInputStream(filename));
        read = serializer.read(OGraph.class, gzipInputStream);
        gzipInputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    if ( read != null ) {
        _postProcess(read);
    }

    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();
    }
}
项目:simplexml    文件:Test4_2Test.java   
public void testSerialization() throws Exception{
   Serializer s = new Persister();
   StringWriter sw = new StringWriter();     

   String serializedForm =    "<test4>\n" + 
                        "   <single-element class=\"org.simpleframework.xml.core.Test4_2Test$MyElementC\"/>\n" +
                        "</test4>";
   System.out.println(serializedForm);
   System.out.println();

   Test4_2 o = s.read(Test4_2.class, serializedForm);

   //FIXME read ignores the class statement

   MyElementC ec = (MyElementC) o.element;

   sw.getBuffer().setLength(0);
   s.write(new Test4_2(new MyElementC()), sw);
   //FIXME it would be great, if this worked. Actually it works for ElementUnionLists.
   System.out.println(sw.toString());
   System.out.println();

}
项目:simplexml    文件:EmptyMapEntryTest.java   
/**
 * @param args the command line arguments
 */
public void testEmptyMapEntry() throws Exception {
    Strategy resolver = new CycleStrategy("id", "ref");
    Serializer s = new Persister(resolver);
    StringWriter w = new StringWriter();
    SimpleBug1 bug1 = new SimpleBug1();

    assertEquals(bug1.test1.data.get("key1"), "value1");
    assertEquals(bug1.test1.data.get("key2"), "value1");
    assertEquals(bug1.test1.data.get("key3"), "");
    assertEquals(bug1.test1.data.get(""), "");

    s.write(bug1, w);
    System.err.println(w.toString());

    SimpleBug1 bug2 = s.read(SimpleBug1.class, w.toString());

    assertEquals(bug1.test1.data.get("key1"), bug2.test1.data.get("key1"));
    assertEquals(bug1.test1.data.get("key2"), bug2.test1.data.get("key2"));       
    assertEquals(bug2.test1.data.get("key1"), "value1");
    assertEquals(bug2.test1.data.get("key2"), "value1");
    assertNull(bug2.test1.data.get("key3"));
    assertNull(bug2.test1.data.get(null));

    validate(s, bug1);
}
项目:simplexml    文件:ProviderInformationTest.java   
public String toString()
{
   Serializer serializer = new Persister();
   StringWriter xmlWriter = new StringWriter();
   try
   {
      serializer.write( itsSolutionPackageDeployment, xmlWriter );
   }
   catch (Exception exception)
   {
      final Writer result = new StringWriter(); 
      final PrintWriter printWriter = new PrintWriter(result);
      exception.printStackTrace(printWriter);
      System.out.println( "serializer.write exception " + exception.getMessage() );
      System.out.println( result.toString() );
      xmlWriter.append( "serializer.write exception " + exception.getMessage() );
   }
   return xmlWriter.toString();
}
项目: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    文件:Test2_ReplaceTest.java   
public void testReplace() throws Exception{
   Serializer s = new Persister();
   StringWriter sw = new StringWriter();
   Test2A element = new Test2A(null);
   s.write(new Test2A(element, element), sw);      
   String serializedForm = sw.toString();
   System.out.println(serializedForm);
   System.out.println();

   //"element" is serialzed differently depending on whether it is serialized as a part of a list or not.
   //Apparently the replace method is not applied when "element" is serialized as part of a list.
   //Particularly the replace method is only called once, when debugging the serialization. However it should be called twice.

   //Test2 o = s.read(Test2.class, serializedForm);

   sw.getBuffer().setLength(0);
}
项目:simplexml    文件:UnionEmptyListBugTest.java   
public void testListBug() throws Exception {
   Serializer serializer = new Persister();
   ElementListUnionBug element = new ElementListUnionBug();
   StringWriter writer = new StringWriter();
   serializer.write(element, writer);
   String text = writer.toString();
   assertElementExists(text, "/elementListUnionBug");
   assertElementDoesNotExist(text, "/elementListUnionBug/string");
   assertElementDoesNotExist(text, "/elementListUnionBug/integer");
   writer = new StringWriter();
   element.values.add("A");
   element.values.add(111);    
   serializer.write(element, writer);
   text = writer.toString();
   System.out.println(text);
   assertElementExists(text, "/elementListUnionBug/string");
   assertElementHasValue(text, "/elementListUnionBug/string", "A");
   assertElementExists(text, "/elementListUnionBug/integer");
   assertElementHasValue(text, "/elementListUnionBug/integer", "111");
}
项目:simplexml    文件:RegistryConverterTest.java   
public void testPersonConverter() throws Exception {
   Style style = new CamelCaseStyle();
   Format format = new Format(style);
   Registry registry = new Registry();
   Person person = new Person("Niall", 30);
   RegistryStrategy strategy = new RegistryStrategy(registry);
   Serializer serializer = new Persister(strategy, format);
   Converter converter = new PersonConverter(serializer);
   StringWriter writer = new StringWriter();

   registry.bind(Person.class, converter);

   PersonProfile profile = new PersonProfile(person);
   serializer.write(profile, writer);

   System.out.println(writer.toString());

   PersonProfile read = serializer.read(PersonProfile.class, writer.toString());

   assertEquals(read.person.name, "Niall");
   assertEquals(read.person.age, 30);
}
项目:Android-nRF-Toolbox    文件: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);
    }
}
项目:openmeetings    文件:BackupImport.java   
private void importRoomGroups(File f) throws Exception {
    log.info("Room import complete, starting room groups import");
    Registry registry = new Registry();
    Strategy strategy = new RegistryStrategy(registry);
    Serializer serializer = new Persister(strategy);

    registry.bind(Group.class, new GroupConverter(groupDao, groupMap));
    registry.bind(Room.class, new RoomConverter(roomDao, roomMap));

    List<RoomGroup> list = readList(serializer, f, "rooms_organisation.xml", "room_organisations", RoomGroup.class);
    for (RoomGroup ro : list) {
        Room r = roomDao.get(ro.getRoom().getId());
        if (r == null || ro.getGroup() == null || ro.getGroup().getId() == null) {
            continue;
        }
        if (r.getGroups() == null) {
            r.setGroups(new ArrayList<>());
        }
        ro.setId(null);
        ro.setRoom(r);
        r.getGroups().add(ro);
        roomDao.update(r, null);
    }
}