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
18 changes: 9 additions & 9 deletions source/contributing/implementation/datamanipulator.rst
Expand Up @@ -75,7 +75,7 @@ The second constructor must
this.registerGettersAndSetters();
}

...
[...]

}

Expand Down Expand Up @@ -125,7 +125,7 @@ to values. Since a ``Key`` always contains a corresponding ``DataQuery``, just u
.. code-block:: java

public DataContainer toContainer() {
return new MemoryDataContainer()
return DataContainer.createNew()
.set(Keys.HEALTH, this.currentHealth)
.set(Keys.MAX_HEALTH, this.maximumHealth);
}
Expand Down Expand Up @@ -214,7 +214,7 @@ There add a line to register (and create) your used keys.

.. code-block:: java

keyMap.put("health"), makeSingleKey(Double.class, MutableBoundedValue.class, of("Health")));
keyMap.put("health", makeSingleKey(Double.class, MutableBoundedValue.class, of("Health")));
Copy link
Member

Choose a reason for hiding this comment

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

All the key stuff needs to be updated to use the register method like so:

this.register(Key.builder().type(TypeTokens.BOUNDED_DOUBLE_VALUE_TOKEN).id("health").name("Health").query(of("Health")).build())

Copy link
Member Author

Choose a reason for hiding this comment

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

Fixed

keyMap.put("max_health", makeSingleKey(Double.class, MutableBoundedValue.class, of("MaxHealth")));


Expand Down Expand Up @@ -333,7 +333,7 @@ Therefore we just return ``failNoData()`` and do not override the ``doesDataExis
.. code-block:: java

public DataTransactionResult remove(DataHolder dataHolder) {
return DataTransactionBuilder.failNoData();
return DataTransactionResult.failNoData();
}


Expand Down Expand Up @@ -424,7 +424,7 @@ and construct ``HealthValueProcessor`` as follows.
.. code-block:: java

public class HealthValueProcessor extends AbstractSpongeValueProcessor<EntityLivingBase, Double,
MutableBoundedValue<Double> {
MutableBoundedValue<Double>> {

public HealthValueProcessor() {
super(EntityLivingBase.class, Keys.HEALTH);
Expand Down Expand Up @@ -486,7 +486,7 @@ This implementation will reject values outside of the bounds used in our value c
.. code-block:: java

public DataTransactionResult removeFrom(ValueContainer<?> container) {
return DataTransactionBuilder.failNoData();
return DataTransactionResult.failNoData();
}

Since the data is guaranteed to be always present, attempts to remove it will just fail.
Expand All @@ -506,7 +506,7 @@ handles. For every pair of mutable / immutable ``DataManipulator``\ s at least o

.. code-block:: java

dataRegistry.registerDataProcessorAndImpl(HealthData.class, SpongeHealthData.class,
DataUtil.registerDataProcessorAndImpl(HealthData.class, SpongeHealthData.class,
ImmutableHealthData.class, ImmutableSpongeHealthData.class,
new HealthDataProcessor());

Expand All @@ -519,8 +519,8 @@ can be registered by subsequent calls of the ``registerValueProcessor()`` method

.. code-block:: java

dataRegistry.registerValueProcessor(Keys.HEALTH, new HealthValueProcessor());
dataRegistry.registerValueProcessor(Keys.MAX_HEALTH, new MaxHealthValueProcessor());
DataUtil.registerValueProcessor(Keys.HEALTH, new HealthValueProcessor());
DataUtil.registerValueProcessor(Keys.MAX_HEALTH, new MaxHealthValueProcessor());


Implementing Block Data
Expand Down
5 changes: 4 additions & 1 deletion source/plugin/assets.rst
Expand Up @@ -50,7 +50,10 @@ following code:
import java.nio.file.Files;

if (Files.notExists(configPath)) {
plugin.getAsset("default.conf").copyToFile(configPath);
Optional<Asset> asset = plugin.getAsset("default.conf");
if (asset.isPresent()) {
Copy link
Member

Choose a reason for hiding this comment

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

Can simplify this to

plugin.getAsset("default.conf").ifPresent(asset -> asset.copyToDirectory(configPath));

Copy link
Member Author

Choose a reason for hiding this comment

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

Changed

asset.get().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
6 changes: 1 addition & 5 deletions source/plugin/entities/spawning.rst
Expand Up @@ -23,9 +23,6 @@ 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.world.Location;
import org.spongepowered.api.world.World;

Expand All @@ -35,8 +32,7 @@ For example, let's try to spawn a Creeper:
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());
world.spawnEntity(creeper);
Copy link
Member

Choose a reason for hiding this comment

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

Should be pushing to the cause stack frame for a SpawnType.

Copy link
Member Author

Choose a reason for hiding this comment

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

Fixed

}

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
19 changes: 7 additions & 12 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 @@ -107,14 +107,9 @@ 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());
extent.spawnEntity(item);
Copy link
Member

Choose a reason for hiding this comment

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

Likewise here, need to add the SpawnType to the context.

Copy link
Member

Choose a reason for hiding this comment

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

Can wrap with:

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

Copy link
Member Author

Choose a reason for hiding this comment

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

Fixed

}

Creating an ItemStack From a Block
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