Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make (most of) the examples executable again #695

Merged
merged 12 commits into from Jun 19, 2018
259 changes: 163 additions & 96 deletions source/contributing/implementation/datamanipulator.rst

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions source/contributing/implementation/mixins.rst
Expand Up @@ -57,7 +57,7 @@ that attempt to use Sponge.
}

// Other methods skipped
}
};

This applies to all classes that are annotated with ``@Mixin``. Classes that are not touched by the mixin processor may make use of those
features. There are two ways to work around this.
Expand Down Expand Up @@ -127,10 +127,10 @@ the other. For example:
return new Collection<ItemStack>() {
@Override
public Iterator<ItemStack> iterator() {
return new SampleIterator<>();
return new SampleIterator();
}

// Other methods skipped
}
};
}
}
2 changes: 1 addition & 1 deletion source/plugin/assets.rst
Expand Up @@ -50,7 +50,7 @@ following code:
import java.nio.file.Files;

if (Files.notExists(configPath)) {
plugin.getAsset("default.conf").copyToFile(configPath);
plugin.getAsset("default.conf").ifPresent(asset -> asset.copyToDirectory(configPath));
}

.. note::
Expand Down
2 changes: 1 addition & 1 deletion source/plugin/blocks/tileentities.rst
Expand Up @@ -111,7 +111,7 @@ an inventory extend the :javadoc:`TileEntityCarrier` interface it suffices to ca
if (entity instanceof TileEntityCarrier) {
TileEntityCarrier carrier = (TileEntityCarrier) entity;
Inventory inventory = carrier.getInventory();
...
[...]
}
}

Expand Down
14 changes: 7 additions & 7 deletions source/plugin/commands/commandcallable.rst
Expand Up @@ -101,14 +101,14 @@ A ``Dispatcher`` is also a ``CommandCallable``, so it can be registered like any

.. code-block:: java

import org.spongepowered.api.command.dispatcher.SimpleDispatcher;
import org.spongepowered.api.command.dispatcher.SimpleDispatcher;

CommandCallable subCommand1 = ...;
CommandCallable subCommand2 = ...;
CommandCallable subCommand1 = ...;
CommandCallable subCommand2 = ...;

SimpleDispatcher rootCommand = new SimpleDispatcher();
SimpleDispatcher rootCommand = new SimpleDispatcher();

rootCommand.register(subCommand1, "subcommand1", "sub1");
rootCommand.register(subCommand2, "subcommand2", "sub2");
rootCommand.register(subCommand1, "subcommand1", "sub1");
rootCommand.register(subCommand2, "subcommand2", "sub2");

Sponge.getCommandManager().register(this, rootCommand, "root");
Sponge.getCommandManager().register(this, rootCommand, "root");
2 changes: 1 addition & 1 deletion source/plugin/configuration/nodes.rst
Expand Up @@ -112,7 +112,7 @@ method while providing a ``TypeToken`` representing the ``UUID`` class.

import java.util.UUID;

UUID mayor = rootNode.getNode("towns", "aFLARDia", "mayor").get(TypeToken.of(UUID.class));
UUID mayor = rootNode.getNode("towns", "aFLARDia", "mayor").getValue(TypeToken.of(UUID.class));

This prompts Configurate to locate the proper ``TypeSerializer`` for ``UUID``\ s and then use it to convert the stored
value into a ``UUID``. The ``TypeSerializer`` (and by extension the above method) may throw an ``ObjectMappingException``
Expand Down
8 changes: 4 additions & 4 deletions source/plugin/configuration/serialization.rst
Expand Up @@ -25,7 +25,7 @@ Imagine a data structure tracking how many diamonds a player has mined. It might
private UUID playerUUID;
private int diamonds;

...
[...]
}

Also assume some methods to access those fields, a nice constructor setting both of those etc.
Expand Down Expand Up @@ -114,7 +114,7 @@ class with the :javadoc:`ConfigSerializable` and :javadoc:`Setting` annotations.
@Setting(comment="Number of diamonds mined")
private int diamonds;

...
[...]
}

The above example can now be serialized and deserialized from config nodes without further registration. The
Expand Down Expand Up @@ -155,14 +155,14 @@ Your plugin can just acquire a ``GuiceObjectMapperFactory`` simply by dependency
import ninja.leaping.configurate.loader.ConfigurationLoader;
import ninja.leaping.configurate.objectmapping.GuiceObjectMapperFactory;

@Plugin(name="IStoleThisFromZml", id="shamelesslystolen", version="0.8.15")
@Plugin(name="IStoleThisFromZml", id="shamelesslystolen", version="0.8.15", description = "Stolen")
public class StolenCodeExample {

@Inject private GuiceObjectMapperFactory factory;
@Inject private ConfigurationLoader<CommentedConfigurationNode> loader;

@Listener
public void enable(GamePreInitializationEvent event) {
public void enable(GamePreInitializationEvent event) throws IOException, ObjectMappingException {
CommentedConfigurationNode node =
loader.load(ConfigurationOptions.defaults().setObjectMapperFactory(factory));
DiamondCounter myDiamonds = node.getValue(TypeToken.of(DiamondCounter.class));
Expand Down
6 changes: 3 additions & 3 deletions source/plugin/data/custom/serialization.rst
Expand Up @@ -80,7 +80,7 @@ two methods:

@Override
public DataContainer toContainer() {
return new MemoryDataContainer()
return DataContainer.createNew()
.set(DataQuery.of("Name"), this.name)
.set(Queries.CONTENT_VERSION, getContentVersion());
}
Expand Down Expand Up @@ -119,8 +119,8 @@ the builder.

.. code-block:: java

org.spongepowered.api.data.persistence.DataContentUpdater
org.spongepowered.api.text.Text
import org.spongepowered.api.data.persistence.DataContentUpdater
import org.spongepowered.api.text.Text

public class NameUpdater implements DataContentUpdater {

Expand Down
2 changes: 1 addition & 1 deletion source/plugin/data/datamanipulators.rst
Expand Up @@ -32,7 +32,7 @@ try to heal someone (or something).

import java.util.Optional;

public static DataTransactionResult heal(DataHolder target) {
public static void heal(DataHolder target) {
Optional<HealthData> healthOptional = target.get(HealthData.class);
if (healthOptional.isPresent()) {
HealthData healthData = healthOptional.get();
Expand Down
6 changes: 3 additions & 3 deletions source/plugin/economy/practices.rst
Expand Up @@ -55,13 +55,13 @@ Here's how you **should** withdraw money:
import org.spongepowered.api.service.economy.transaction.ResultType;
import org.spongepowered.api.service.economy.transaction.TransactionResult;

EconomyService service = ...
Account account = ...
EconomyService service = ...;
Account account = ...;
BigDecimal requiredAmount = BigDecimal.valueOf(20);

TransactionResult result = account.withdraw(service.getDefaultCurrency(),
requiredAmount, Cause.source(this).build());
if (result.getResult() == ResultType.SUCCESS)) {
if (result.getResult() == ResultType.SUCCESS) {
// Success!
} else if (result.getResult() == ResultType.FAILED || result.getResult() == ResultType.ACCOUNT_NO_FUNDS) {
// Something went wrong!
Expand Down
6 changes: 3 additions & 3 deletions source/plugin/entities/modifying.rst
Expand Up @@ -52,8 +52,8 @@ An example of changing an ``Entity``\ s explosive radius to 50 can be seen below
import org.spongepowered.api.data.manipulator.mutable.entity.ExplosiveRadiusData;

public void explosionRadius50(Entity creeper) {
ExplosiveRadiusData radiusData = creeper.get(ExplosiveRadiusData.class).get();
creeper.offer(radiusData.explosiveRadius().set(50));
ExplosionRadiusData radiusData = creeper.get(ExplosionRadiusData.class).get();
creeper.offer(radiusData.explosionRadius().setTo(50));
}

This will get the ``ExplosiveRadiusData`` of our ``Entity`` for our use. We then use that data to set the explosive
Expand Down Expand Up @@ -83,7 +83,7 @@ Another, shorter way to do this is by just using :javadoc:`Keys` on our ``Entity
import org.spongepowered.api.data.key.Keys;

public void explosionRadius50(Entity creeper) {
creeper.offer(Keys.EXPLOSIVE_RADIUS, 50);
creeper.offer(Keys.EXPLOSION_RADIUS, Optional.of(50));
creeper.offer(Keys.DISPLAY_NAME, Text.of(TextColors.DARK_AQUA, "Inscrutable"));
}

Expand Down
15 changes: 8 additions & 7 deletions source/plugin/entities/spawning.rst
Expand Up @@ -23,20 +23,21 @@ For example, let's try to spawn a Creeper:

import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.EntityTypes;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.entity.spawn.SpawnCause;
import org.spongepowered.api.event.cause.entity.spawn.SpawnTypes;
import org.spongepowered.api.event.CauseStackManager.StackFrame;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;

import java.util.Optional;

public void spawnEntity(Location<World> spawnLocation) {
World world = spawnLocation.getExtent();
Entity creeper = world
.createEntity(EntityTypes.CREEPER, spawnLocation.getPosition());
SpawnCause spawnCause = SpawnCause.builder().type(SpawnTypes.PLUGIN).build();
world.spawnEntity(creeper, Cause.source(spawnCause).build());

Entity creeper = world.createEntity(EntityTypes.CREEPER, spawnLocation.getPosition());

try (StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if the cause stack manager is documented, but may want to add a code comment that the context needs to be wrapped in the frame because of the changes.

Likewise, mention that the plugin's PluginContainer is already pushed to the cause stack.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Like this?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah that works.

frame.addContext(EventContextKeys.PLUGIN, pluginContainer);
world.spawnEntity(creeper);
}
}

This will grab the world from our ``Location``, which we will need for the actual spawning. Next, it uses
Expand Down
10 changes: 5 additions & 5 deletions source/plugin/event/causes.rst
Expand Up @@ -184,8 +184,8 @@ as the :javadoc:`EventContextKeys#PLAYER_SIMULATED` context, in addition to anyt

.. code-block:: java

CommandSource sourceRunningSudo;
Player playerToSimulate;
CommandSource sourceRunningSudo = ...;
Player playerToSimulate = ...;
try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {

frame.pushCause(sourceRunningSudo);
Expand Down Expand Up @@ -229,9 +229,9 @@ to the cause would be the root cause.

.. code-block:: java

CommandSource sourceRunningSudo;
Player playerToSimulate;
PluginContainer plugin;
CommandSource sourceRunningSudo = ...;
Player playerToSimulate = ...;
PluginContainer plugin = ...;

EventContext context = EventContext.builder()
.add(EventContextKeys.PLAYER_SIMULATED, playerToSimulate.getProfile())
Expand Down
2 changes: 1 addition & 1 deletion source/plugin/event/filters.rst
Expand Up @@ -62,7 +62,7 @@ An example with :javadoc:`Include` could be:

@Listener
@Include({DamageEntityEvent.class, DestructEntityEvent.class})
public void onEvent(EntityEvent event) {
public void onEvent(TargetEntityEvent event) {
// do something
}

Expand Down
8 changes: 4 additions & 4 deletions source/plugin/event/listeners.rst
Expand Up @@ -89,7 +89,7 @@ before other server modifications.

@Override
public void handle(ChangeBlockEvent.Break event) throws Exception {
...
[...]
}
}

Expand All @@ -115,7 +115,7 @@ which accepts an instance of the class containing the event listeners.

.. code-block:: java

EventListener listener = ...
EventListener listener = ...;
Sponge.getEventManager().unregisterListeners(listener);

Alternatively, you can use :javadoc:`EventManager#unregisterPluginListeners(Object)`, passing in a reference to the
Expand All @@ -124,7 +124,7 @@ event listeners, including those registered with ``@Listener`` annotations.

.. code-block:: java

MyPlugin plugin = ...
MyPlugin plugin = ...;
Sponge.getEventManager().unregisterPluginListeners(plugin);

.. _about_listener:
Expand Down Expand Up @@ -193,7 +193,7 @@ Example: Firing LightningEvent
import org.spongepowered.api.event.action.LightningEvent;
import org.spongepowered.api.event.cause.Cause;

LightningEvent lightningEvent = SpongeEventFactory.createLightningEvent(Cause.source(plugin).build());
LightningEvent lightningEvent = SpongeEventFactory.createLightningEventPre(Cause.source(plugin).build());
Sponge.getEventManager().post(lightningEvent);

.. warning::
Expand Down
3 changes: 1 addition & 2 deletions source/plugin/injection.rst
Expand Up @@ -163,8 +163,7 @@ The recommended way to obtain your config file is through Guice, along with the
private Path configDir;

@Inject
@ConfigDir(sharedRoot = false)
private void setConfigDir(Path configDir) {
private void setConfigDir(@ConfigDir(sharedRoot = false) Path configDir) {
this.configDir = configDir;
}

Expand Down
25 changes: 11 additions & 14 deletions source/plugin/items/creating.rst
Expand Up @@ -50,12 +50,12 @@ include this all before ``return superMegaAwesomeSword;``.

EnchantmentData enchantmentData = superMegaAwesomeSword
.getOrCreate(EnchantmentData.class).get();
final List<Enchantment> enchantments = Sponge.getRegistry()
.getAllOf(Enchantment.class).stream().collect(Collectors.toList());
final List<EnchantmentType> enchantments = Sponge.getRegistry()
.getAllOf(EnchantmentType.class).stream().collect(Collectors.toList());

for (Enchantment enchantment : enchantments) {
for (EnchantmentType enchantment : enchantments) {
enchantmentData.set(enchantmentData.enchantments()
.add(new ItemEnchantment(enchantment, 1000)));
.add(Enchantment.of(enchantment, 1000)));
}
superMegaAwesomeSword.offer(enchantmentData);

Expand Down Expand Up @@ -96,9 +96,7 @@ An example is shown below:

import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.EntityTypes;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.entity.spawn.EntitySpawnCause;
import org.spongepowered.api.event.cause.entity.spawn.SpawnTypes;
import org.spongepowered.api.event.CauseStackManager.StackFrame;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.extent.Extent;
Expand All @@ -107,13 +105,12 @@ An example is shown below:

public void spawnItem(ItemStack superMegaAwesomeSword, Location<World> spawnLocation) {
Extent extent = spawnLocation.getExtent();
Optional<Entity> optional = extent
.createEntity(EntityTypes.ITEM, spawnLocation.getPosition());
if (optional.isPresent()) {
Entity item = optional.get();
item.offer(Keys.REPRESENTED_ITEM, superMegaAwesomeSword.createSnapshot());
extent.spawnEntity(item, Cause.source(EntitySpawnCause.builder()
.entity(item).type(SpawnTypes.PLUGIN).build()).build());
Entity item = extent.createEntity(EntityTypes.ITEM, spawnLocation.getPosition());
item.offer(Keys.REPRESENTED_ITEM, superMegaAwesomeSword.createSnapshot());

try (StackFrame frame = Sponge.getCauseStackManager().pushStackFrame()) {
frame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.PLACEMENT);
extent.spawnEntity(item);
}
}

Expand Down
2 changes: 1 addition & 1 deletion source/plugin/items/usage.rst
Expand Up @@ -27,7 +27,7 @@ Checking the type of the item is very simple. You just need to call the :javadoc
import org.spongepowered.api.item.inventory.ItemStack;

public boolean isStick(ItemStack stack) {
ItemType type = stack.getItem();
ItemType type = stack.getType();
return type.equals(ItemTypes.STICK);
}

Expand Down
8 changes: 4 additions & 4 deletions source/plugin/logging.rst
Expand Up @@ -80,10 +80,10 @@ Emitting a message with your logger is very simple.

.. code-block:: java

getLogger().info(String);
getLogger().debug(String);
getLogger().warn(String);
getLogger().error(String);
getLogger().info("String");
getLogger().debug("String");
getLogger().warn("String");
getLogger().error("String");

The String is the message you wish to emit. For example:

Expand Down
14 changes: 7 additions & 7 deletions source/plugin/manager.rst
Expand Up @@ -27,7 +27,7 @@ section) to allow for an easy center of information about the specific plugin. A
compability or extended features by means of your calling plugin.

Obtaining the Plugin Manager
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can get an instance of the server's ``PluginManager`` using a few different ways.

Expand Down Expand Up @@ -62,7 +62,7 @@ parameter.

.. code-block:: java

private PluginManager pluginManager = serviceManager.provide(PluginManager.class);
private PluginManager pluginManager = serviceManager.provideUnchecked(PluginManager.class);

3. The Game Instance
--------------------
Expand Down Expand Up @@ -106,15 +106,15 @@ With the plugin manager, it is possible to get all plugins currently loaded thro

import org.spongepowered.api.plugin.PluginContainer;

import java.util.List;
import java.util.Collection;

private List<PluginContainer> plugins = pluginManager.getPlugins();
private Collection<PluginContainer> plugins = pluginManager.getPlugins();

Or, it is possible to obtain an instance to a plugin container directly, by the example shown below:

.. code-block:: java

private PluginContainer myOtherPlugin = pluginManager.getPlugin("myOtherPluginId").orNull();
private PluginContainer myOtherPlugin = pluginManager.getPlugin("myOtherPluginId").orElse(null);

The PluginContainer Class
~~~~~~~~~~~~~~~~~~~~~~~~~
Expand All @@ -131,8 +131,8 @@ its name.

.. code-block:: java

private PluginContainer myOtherPlugin = pluginManager.getPlugin("myOtherPluginId").orNull();
private MyOtherPlugin pluginInstance = (MyOtherPlugin) myOtherPlugin.getInstance();
private PluginContainer myOtherPlugin = pluginManager.getPlugin("myOtherPluginId").orElse(null);
private MyOtherPlugin pluginInstance = (MyOtherPlugin) myOtherPlugin.getInstance().orElse(null);

.. note::

Expand Down