org.simpleframework.xml.stream.HyphenStyle Java Examples

The following examples show how to use org.simpleframework.xml.stream.HyphenStyle. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CombinedStrategyTest.java    From simplexml with Apache License 2.0 6 votes vote down vote up
public void testCombinationStrategyWithStyle() throws Exception {
   Registry registry = new Registry();
   AnnotationStrategy annotationStrategy = new AnnotationStrategy();
   RegistryStrategy registryStrategy = new RegistryStrategy(registry, annotationStrategy);
   Style style = new HyphenStyle();
   Format format = new Format(style);
   Persister persister = new Persister(registryStrategy, format);
   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, "/combination-example/item/value");
   assertElementHasValue(text, "/combination-example/item/value", "1");
   assertElementHasValue(text, "/combination-example/item/type", RegistryItemConverter.class.getName());
   assertElementExists(text, "/combination-example/overridden-item");
   assertElementHasAttribute(text, "/combination-example/overridden-item", "value", "2");
   assertElementHasAttribute(text, "/combination-example/overridden-item", "type", AnnotationItemConverter.class.getName());
   assertElementExists(text, "/combination-example/extended-item");
   assertElementHasAttribute(text, "/combination-example/extended-item", "value", "3");
   assertElementHasAttribute(text, "/combination-example/extended-item", "type", ExtendedItemConverter.class.getName());      
}
 
Example #2
Source File: PathWithConverterTest.java    From simplexml with Apache License 2.0 6 votes vote down vote up
public void testConverterWithPathInHyphenStyle() throws Exception {
   Style style = new HyphenStyle();
   Format format = new Format(style);
   Strategy strategy = new AnnotationStrategy();
   Persister persister = new Persister(strategy, format);
   ServerDetails primary = new ServerDetails("host1.blah.com", 4567, "PRIMARY");
   ServerDetails secondary = new ServerDetails("host2.foo.com", 4567, "SECONDARY");
   ServerDetailsReference reference = new ServerDetailsReference(primary, secondary);
   StringWriter writer = new StringWriter();
   persister.write(reference, writer);
   System.out.println(writer);
   ServerDetailsReference recovered = persister.read(ServerDetailsReference.class, writer.toString());
   assertEquals(recovered.getPrimary().getHost(), reference.getPrimary().getHost());
   assertEquals(recovered.getPrimary().getPort(), reference.getPrimary().getPort());
   assertEquals(recovered.getPrimary().getName(), reference.getPrimary().getName());
   assertEquals(recovered.getSecondary().getHost(), reference.getSecondary().getHost());
   assertEquals(recovered.getSecondary().getPort(), reference.getSecondary().getPort());
   assertEquals(recovered.getSecondary().getName(), reference.getSecondary().getName());
}
 
Example #3
Source File: UnionStyleTest.java    From simplexml with Apache License 2.0 6 votes vote down vote up
public void testHyphenStyle() throws Exception {
   Style style = new HyphenStyle();
   Format format = new Format(style);
   Persister persister = new Persister(format);
   UnionListExample example = persister.read(UnionListExample.class, HYPHEN_SOURCE);
   List<Entry> entry = example.list;
   assertEquals(entry.size(), 4);
   assertEquals(entry.get(0).getClass(), IntegerEntry.class);
   assertEquals(entry.get(0).foo(), 111);
   assertEquals(entry.get(1).getClass(), DoubleEntry.class);
   assertEquals(entry.get(1).foo(), 222.0);
   assertEquals(entry.get(2).getClass(), StringEntry.class);
   assertEquals(entry.get(2).foo(), "A");
   assertEquals(entry.get(3).getClass(), StringEntry.class);
   assertEquals(entry.get(3).foo(), "B");
   assertEquals(example.entry.getClass(), IntegerEntry.class);
   assertEquals(example.entry.foo(), 777);
   persister.write(example, System.out);
   validate(persister, example);
}
 
Example #4
Source File: UARTActivity.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void onRenameConfiguration(final String newName) {
	final boolean exists = databaseHelper.configurationExists(newName);
	if (exists) {
		Toast.makeText(this, R.string.uart_configuration_name_already_taken, Toast.LENGTH_LONG).show();
		return;
	}

	final String oldName = configuration.getName();
	configuration.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(configuration, writer);
		final String xml = writer.toString();

		databaseHelper.renameConfiguration(oldName, newName, xml);
		wearableSynchronizer.onConfigurationAddedOrEdited(preferences.getLong(PREFS_CONFIGURATION, 0), configuration);
		refreshConfigurations();
	} catch (final Exception e) {
		Log.e(TAG, "Error while renaming configuration", e);
	}
}
 
Example #5
Source File: UARTActivity.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Saves the given configuration in the database.
 */
private void saveConfiguration() {
	final UartConfiguration configuration = this.configuration;
	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();

		databaseHelper.updateConfiguration(configuration.getName(), xml);
		wearableSynchronizer.onConfigurationAddedOrEdited(preferences.getLong(PREFS_CONFIGURATION, 0), configuration);
	} catch (final Exception e) {
		Log.e(TAG, "Error while creating a new configuration", e);
	}
}
 
Example #6
Source File: StyleTest.java    From simplexml with Apache License 2.0 5 votes vote down vote up
public void testCase() throws Exception {
   Style style = new HyphenStyle();
   Format format = new Format(style);
   Persister writer = new Persister(format);
   Persister reader = new Persister();
   CaseExample example = reader.read(CaseExample.class, SOURCE);
   
   assertEquals(example.version, 1.0f);
   assertEquals(example.name, "example");
   assertEquals(example.URL, "http://domain.com/");
   
   writer.write(example, System.err);
   validate(example, reader); 
   validate(example, writer);
}
 
Example #7
Source File: UARTActivity.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Method called when Google API Client connects to Wearable.API.
 */
@Override
public void onConnected(final Bundle bundle) {
	// Ensure the Wearable API was connected
	if (!wearableSynchronizer.hasConnectedApi())
		return;

	if (!preferences.getBoolean(PREFS_WEAR_SYNCED, false)) {
		new Thread(() -> {
			final Cursor cursor = databaseHelper.getConfigurations();
			try {
				while (cursor.moveToNext()) {
					final long id = cursor.getLong(0 /* _ID */);
					try {
						final String xml = cursor.getString(2 /* XML */);
						final Format format = new Format(new HyphenStyle());
						final Serializer serializer = new Persister(format);
						final UartConfiguration configuration = serializer.read(UartConfiguration.class, xml);
						wearableSynchronizer.onConfigurationAddedOrEdited(id, configuration).await();
					} catch (final Exception e) {
						Log.w(TAG, "Deserializing configuration with id " + id + " failed", e);
					}
				}
				preferences.edit().putBoolean(PREFS_WEAR_SYNCED, true).apply();
			} finally {
				cursor.close();
			}
		}).start();
	}
}
 
Example #8
Source File: UARTActivity.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onItemSelected(final AdapterView<?> parent, final View view, final int position, final long id) {
	if (position > 0) { // FIXME this is called twice after rotation.
		try {
			final String xml = databaseHelper.getConfiguration(id);
			final Format format = new Format(new HyphenStyle());
			final Serializer serializer = new Persister(format);
			configuration = serializer.read(UartConfiguration.class, xml);
			configurationListener.onConfigurationChanged(configuration);
		} catch (final Exception e) {
			Log.e(TAG, "Selecting configuration failed", e);

			String message;
			if (e.getLocalizedMessage() != null)
				message = e.getLocalizedMessage();
			else if (e.getCause() != null && e.getCause().getLocalizedMessage() != null)
				message = e.getCause().getLocalizedMessage();
			else
				message = "Unknown error";
			final String msg = message;
			Snackbar.make(container, R.string.uart_configuration_loading_failed, Snackbar.LENGTH_INDEFINITE)
					.setAction(R.string.uart_action_details, v ->
							new AlertDialog.Builder(UARTActivity.this)
									.setMessage(msg)
									.setTitle(R.string.uart_action_details)
									.setPositiveButton(R.string.ok, null)
									.show())
					.show();
			return;
		}

		preferences.edit().putLong(PREFS_CONFIGURATION, id).apply();
	}
}
 
Example #9
Source File: UARTActivity.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onNewConfiguration(final String name, final boolean duplicate) {
	final boolean exists = databaseHelper.configurationExists(name);
	if (exists) {
		Toast.makeText(this, R.string.uart_configuration_name_already_taken, Toast.LENGTH_LONG).show();
		return;
	}

	UartConfiguration configuration = this.configuration;
	if (!duplicate)
		configuration = new UartConfiguration();
	configuration.setName(name);

	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();

		final long id = databaseHelper.addConfiguration(name, xml);
		wearableSynchronizer.onConfigurationAddedOrEdited(id, configuration);
		refreshConfigurations();
		selectConfiguration(configurationsAdapter.getItemPosition(id));
	} catch (final Exception e) {
		Log.e(TAG, "Error while creating a new configuration", e);
	}
}
 
Example #10
Source File: UARTActivity.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Converts the old configuration, stored in preferences, into the first XML configuration and saves it to the database.
 * If there is already any configuration in the database this method does nothing.
 */
private void ensureFirstConfiguration(@NonNull final DatabaseHelper databaseHelper) {
	// This method ensures that the "old", single configuration has been saved to the database.
	if (databaseHelper.getConfigurationsCount() == 0) {
		final UartConfiguration configuration = new UartConfiguration();
		configuration.setName("First configuration");
		final Command[] commands = configuration.getCommands();

		for (int i = 0; i < 9; ++i) {
			final String cmd = preferences.getString(PREFS_BUTTON_COMMAND + i, null);
			if (cmd != null) {
				final Command command = new Command();
				command.setCommand(cmd);
				command.setActive(preferences.getBoolean(PREFS_BUTTON_ENABLED + i, false));
				command.setEol(0); // default one
				command.setIconIndex(preferences.getInt(PREFS_BUTTON_ICON + i, 0));
				commands[i] = command;
			}
		}

		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();

			databaseHelper.addConfiguration(configuration.getName(), xml);
		} catch (final Exception e) {
			Log.e(TAG, "Error while creating default configuration", e);
		}
	}
}
 
Example #11
Source File: SimpleXmlConverterFactoryTest.java    From jus with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    queue = Jus.newRequestQueue();
    Format format = new Format(0, null, new HyphenStyle(), Verbosity.HIGH);
    Persister persister = new Persister(format);
    RetroProxy retroProxy = new RetroProxy.Builder()
            .baseUrl(server.url("/").toString())
            .addConverterFactory(SimpleXmlConverterFactory.create(persister))
            .requestQueue(queue)
            .build();
    service = retroProxy.create(Service.class);
}
 
Example #12
Source File: ApiModule.java    From klingar with Apache License 2.0 4 votes vote down vote up
@Provides @Singleton SimpleXmlConverterFactory provideSimpleXmlConverterFactory() {
  return SimpleXmlConverterFactory.create(new Persister(new Format(new HyphenStyle())));
}
 
Example #13
Source File: ValidationTestCase.java    From simplexml with Apache License 2.0 4 votes vote down vote up
public static synchronized void validate(Object type, Serializer out) throws Exception {
    String fileName = type.getClass().getSimpleName() + ".xml";
    StringWriter buffer = new StringWriter();
    out.write(type, buffer);
    String text = buffer.toString();
    byte[] octets = text.getBytes("UTF-8");
    System.out.write(octets);
    System.out.flush();
    FileSystem.writeBytes(fileName, octets);       
    validate(text);
    
    //File domDestination = new File(directory, type.getClass().getSimpleName() + ".dom.xml");
    //File asciiDestination = new File(directory, type.getClass().getSimpleName() + ".ascii-dom.xml");
    //OutputStream domFile = new FileOutputStream(domDestination);
    //OutputStream asciiFile = new FileOutputStream(asciiDestination);
    //Writer asciiOut = new OutputStreamWriter(asciiFile, "iso-8859-1");
    
    /*
     * This DOM document is the result of serializing the object in to a 
     * string. The document can then be used to validate serialization.
     */
    //Document doc = builder.parse(new InputSource(new StringReader(text)));   
    
    //transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    //transformer.transform(new DOMSource(doc), new StreamResult(domFile));
    //transformer.transform(new DOMSource(doc), new StreamResult(asciiOut));    
    
    //domFile.close();      
    //asciiFile.close();
    out.validate(type.getClass(), text);
   
    String hyphenFile =  type.getClass().getSimpleName() + ".hyphen.xml";
    Strategy strategy = new CycleStrategy("ID", "REFERER");
    Visitor visitor = new DebugVisitor();
    strategy = new VisitorStrategy(visitor, strategy);
    Style style = new HyphenStyle();
    Format format = new Format(style);
    Persister hyphen = new Persister(strategy, format);
    StringWriter hyphenWriter = new StringWriter();
    
    hyphen.write(type, hyphenWriter);
    hyphen.write(type, System.out);
    hyphen.read(type.getClass(), hyphenWriter.toString());
    FileSystem.writeString(hyphenFile, hyphenWriter.toString());
    
    String camelCaseFile = type.getClass().getSimpleName() + ".camel-case.xml";
    Style camelCaseStyle = new CamelCaseStyle(true, false);
    Format camelCaseFormat = new Format(camelCaseStyle);
    Persister camelCase = new Persister(strategy, camelCaseFormat);
    StringWriter camelCaseWriter =  new StringWriter();
   
    camelCase.write(type, camelCaseWriter);
    camelCase.write(type, System.out);
    camelCase.read(type.getClass(), camelCaseWriter.toString());
    FileSystem.writeString(camelCaseFile, camelCaseWriter.toString());
}
 
Example #14
Source File: UARTActivity.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Loads the configuration from the given input stream.
 * @param is the input stream
 */
private void loadConfiguration(@NonNull final InputStream is) {
	try {
		final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		final StringBuilder builder = new StringBuilder();
		for (String line = reader.readLine(); line != null; line = reader.readLine()) {
			builder.append(line).append("\n");
		}
		final String xml = builder.toString();

		final Format format = new Format(new HyphenStyle());
		final Serializer serializer = new Persister(format);
		final UartConfiguration configuration = serializer.read(UartConfiguration.class, xml);

		final String name = configuration.getName();
		if (!databaseHelper.configurationExists(name)) {
			final long id = databaseHelper.addConfiguration(name, xml);
			wearableSynchronizer.onConfigurationAddedOrEdited(id, configuration);
			refreshConfigurations();
			new Handler().post(() -> selectConfiguration(configurationsAdapter.getItemPosition(id)));
		} else {
			Toast.makeText(this, R.string.uart_configuration_name_already_taken, Toast.LENGTH_LONG).show();
		}
	} catch (final Exception e) {
		Log.e(TAG, "Loading configuration failed", e);

		String message;
		if (e.getLocalizedMessage() != null)
			message = e.getLocalizedMessage();
		else if (e.getCause() != null && e.getCause().getLocalizedMessage() != null)
			message = e.getCause().getLocalizedMessage();
		else
			message = "Unknown error";
		final String msg = message;
		Snackbar.make(container, R.string.uart_configuration_loading_failed, Snackbar.LENGTH_INDEFINITE)
				.setAction(R.string.uart_action_details, v ->
						new AlertDialog.Builder(UARTActivity.this)
								.setMessage(msg)
								.setTitle(R.string.uart_action_details)
								.setPositiveButton(R.string.ok, null)
								.show())
				.show();
	}
}