use of org.spongepowered.api.CatalogType in project LanternServer by LanternPowered.
the class MemoryDataView method set.
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public DataView set(DataQuery path, Object value) {
checkNotNull(path, "path");
checkNotNull(value, "value");
final LanternDataManager manager = getDataManager();
final List<String> parts = path.getParts();
final String key = parts.get(0);
if (parts.size() > 1) {
final DataQuery subQuery = of(key);
final Optional<DataView> subViewOptional = getUnsafeView(subQuery);
final DataView subView;
if (!subViewOptional.isPresent()) {
createView(subQuery);
subView = (DataView) this.map.get(key);
} else {
subView = subViewOptional.get();
}
subView.set(path.popFirst(), value);
return this;
}
Optional<DataTypeSerializer> optDataTypeSerializer;
TypeToken typeToken;
if (value instanceof DataView) {
checkArgument(value != this, "Cannot set a DataView to itself.");
// always have to copy a data view to avoid overwriting existing
// views and to set the interior path correctly.
copyDataView(path, (DataView) value);
} else if (value instanceof DataSerializable) {
final DataContainer valueContainer = ((DataSerializable) value).toContainer();
checkArgument(!(valueContainer).equals(this), "Cannot insert self-referencing DataSerializable");
// see above for why this is copied
copyDataView(path, valueContainer);
} else if (value instanceof CatalogType) {
return set(path, ((CatalogType) value).getId());
} else if (value instanceof Integer || value instanceof Byte || value instanceof Short || value instanceof Float || value instanceof Double || value instanceof Long || value instanceof String || value instanceof Character || value instanceof Boolean) {
this.map.put(key, value);
return this;
} else if (manager != null && (optDataTypeSerializer = manager.getTypeSerializer(typeToken = TypeToken.of(value.getClass()))).isPresent()) {
final DataTypeSerializer serializer = optDataTypeSerializer.get();
final Object serialized = serializer.serialize(typeToken, manager.getTypeSerializerContext(), value);
if (serialized instanceof DataContainer) {
final DataContainer container = (DataContainer) serialized;
checkArgument(!container.equals(this), "Cannot insert self-referencing Objects!");
// see above for why this is copied
copyDataView(path, container);
} else {
this.map.put(key, serialized);
}
} else if (value instanceof Collection) {
setCollection(key, (Collection) value);
} else if (value instanceof Map) {
setMap(key, (Map) value);
} else if (value.getClass().isArray()) {
if (this.safety == SafetyMode.ALL_DATA_CLONED || this.safety == SafetyMode.CLONED_ON_SET) {
if (value instanceof byte[]) {
this.map.put(key, ArrayUtils.clone((byte[]) value));
} else if (value instanceof short[]) {
this.map.put(key, ArrayUtils.clone((short[]) value));
} else if (value instanceof int[]) {
this.map.put(key, ArrayUtils.clone((int[]) value));
} else if (value instanceof long[]) {
this.map.put(key, ArrayUtils.clone((long[]) value));
} else if (value instanceof float[]) {
this.map.put(key, ArrayUtils.clone((float[]) value));
} else if (value instanceof double[]) {
this.map.put(key, ArrayUtils.clone((double[]) value));
} else if (value instanceof boolean[]) {
this.map.put(key, ArrayUtils.clone((boolean[]) value));
} else {
this.map.put(key, ArrayUtils.clone((Object[]) value));
}
} else {
this.map.put(key, value);
}
} else {
this.map.put(key, value);
}
return this;
}
use of org.spongepowered.api.CatalogType in project LanternServer by LanternPowered.
the class CommandParticle method completeSpec.
@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
specBuilder.arguments(new PatternMatchingCommandElement(Text.of("type")) {
@Override
protected Iterable<String> getChoices(CommandSource source) {
return Sponge.getGame().getRegistry().getAllOf(ParticleType.class).stream().filter(type -> ((LanternParticleType) type).getInternalType().isPresent()).map(CatalogType::getId).collect(Collectors.toList());
}
@Override
protected Object getValue(String choice) throws IllegalArgumentException {
final Optional<ParticleType> ret = Sponge.getGame().getRegistry().getType(ParticleType.class, choice);
if (!ret.isPresent() || !((LanternParticleType) ret.get()).getInternalType().isPresent()) {
throw new IllegalArgumentException("Invalid input " + choice + " was found");
}
return ret.get();
}
}, GenericArguments2.targetedVector3d(Text.of("position")), // The default value should be 0 for x, y and z
GenericArguments2.vector3d(Text.of("offset"), Vector3d.ZERO), GenericArguments2.doubleNum(Text.of("speed"), 1.0), GenericArguments.optional(GenericArguments2.integer(Text.of("count"), 1)), GenericArguments.optional(new CommandElement(Text.of("mode")) {
@Nullable
@Override
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
return args.next();
}
@Override
public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
Optional<String> arg = args.nextIfPresent();
if (arg.isPresent()) {
return Stream.of("normal", "force").filter(new StartsWithPredicate(arg.get())).collect(Collectors.toList());
}
return Collections.emptyList();
}
}), GenericArguments.optional(GenericArguments.player(Text.of("player"))), GenericArguments.optional(new CommandElement(Text.of("params")) {
@Nullable
@Override
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
List<Integer> params = new ArrayList<>();
while (args.hasNext()) {
String arg = args.next();
try {
params.add(Integer.parseInt(arg));
} catch (NumberFormatException e) {
throw args.createError(t("Expected an integer, but input '%s' was not", arg));
}
}
return params.stream().mapToInt(i -> i).toArray();
}
@Override
public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
return Collections.emptyList();
}
})).executor((src, args) -> {
final LanternParticleType particleType = args.<LanternParticleType>getOne("type").get();
final int particleId = particleType.getInternalType().getAsInt();
final Vector3f position = args.<Vector3d>getOne("position").get().toFloat();
final Vector3f offset = args.<Vector3d>getOne("offset").get().toFloat();
final float speed = args.<Double>getOne("speed").get().floatValue();
final int count = args.<Integer>getOne("count").orElse(1);
final boolean longDistance = args.<String>getOne("mode").map(mode -> mode.equalsIgnoreCase("force")).orElse(false);
final int[] params = args.<int[]>getOne("params").orElse(new int[0]);
final LanternWorld world = CommandHelper.getWorld(src, args);
final int dataLength;
if (particleType == ParticleTypes.BLOCK_CRACK || particleType == ParticleTypes.BLOCK_DUST || particleType == ParticleTypes.FALLING_DUST) {
dataLength = 1;
} else if (particleType == ParticleTypes.ITEM_CRACK) {
dataLength = 2;
} else {
dataLength = 0;
}
if (params.length != dataLength) {
throw new CommandException(t("Invalid parameters (%s), length mismatch (got %s, expected %s) for the particle type %s", Arrays.toString(params), params.length, dataLength, particleType.getId()));
}
final MessagePlayOutSpawnParticle message = new MessagePlayOutSpawnParticle(particleId, position, offset, speed, count, params, longDistance);
if (args.hasAny("player")) {
args.<LanternPlayer>getOne("player").get().getConnection().send(message);
} else {
for (LanternPlayer player : world.getRawPlayers()) {
player.getConnection().send(message);
}
}
src.sendMessage(t("commands.particle.success", particleType.getName(), count));
return CommandResult.success();
});
}
use of org.spongepowered.api.CatalogType in project Nucleus by NucleusPowered.
the class SetWorthCommand method executeCommand.
@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
String id = getCatalogTypeFromHandOrArgs(src, item, args).getId();
Type transactionType = args.<Type>getOne(type).get();
double newCost = args.<Double>getOne(cost).get();
if (newCost < 0) {
newCost = -1;
}
// Get the item from the system.
ItemDataNode node = itemDataService.getDataForItem(id);
// Get the current item worth.
double currentWorth = transactionType.getter.apply(node);
String worth;
String newWorth;
if (econHelper.economyServiceExists()) {
worth = econHelper.getCurrencySymbol(currentWorth);
newWorth = econHelper.getCurrencySymbol(newCost);
} else {
src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.setworth.noeconservice"));
worth = String.valueOf(currentWorth);
newWorth = String.valueOf(newCost);
}
String name;
Optional<CatalogType> type = Util.getCatalogTypeForItemFromId(id);
name = type.map(Util::getTranslatableIfPresentOnCatalogType).orElse(id);
if (currentWorth == newCost) {
if (currentWorth < 0) {
src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.setworth.alreadyunavailable", name, transactionType.getTranslation()));
} else {
src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.setworth.samecost", transactionType.getTranslation(), name, worth));
}
return CommandResult.empty();
}
// Set the item worth.
transactionType.setter.accept(node, newCost);
itemDataService.setDataForItem(id, node);
// Tell the user.
if (currentWorth == -1) {
src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.setworth.success.new", name, transactionType.getTranslation(), newWorth));
} else if (newCost == -1) {
src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.setworth.success.removed", name, transactionType.getTranslation(), worth));
} else {
src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.setworth.success.changed", name, transactionType.getTranslation(), newWorth, worth));
}
return CommandResult.success();
}
use of org.spongepowered.api.CatalogType in project Nucleus by NucleusPowered.
the class WorthCommand method executeCommand.
@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
CatalogType type = getCatalogTypeFromHandOrArgs(src, item, args);
String id = type.getId();
// Get the item from the system.
ItemDataNode node = itemDataService.getDataForItem(id);
// Get the current item worth.
MessageProvider provider = plugin.getMessageProvider();
if (!econHelper.economyServiceExists()) {
src.sendMessage(provider.getTextMessageWithFormat("command.setworth.noeconservice"));
}
double buyPrice = node.getServerBuyPrice();
double sellPrice = node.getServerSellPrice();
StringBuilder stringBuilder = new StringBuilder();
if (buyPrice >= 0) {
stringBuilder.append(provider.getMessageWithFormat("command.worth.buy", econHelper.getCurrencySymbol(node.getServerBuyPrice())));
}
if (sellPrice >= 0) {
if (stringBuilder.length() > 0) {
stringBuilder.append(" - ");
}
stringBuilder.append(provider.getMessageWithFormat("command.worth.sell", econHelper.getCurrencySymbol(node.getServerSellPrice())));
}
if (stringBuilder.length() == 0) {
src.sendMessage(provider.getTextMessageWithFormat("command.worth.nothing", Util.getTranslatableIfPresentOnCatalogType(type)));
} else {
src.sendMessage(provider.getTextMessageWithFormat("command.worth.something", Util.getTranslatableIfPresentOnCatalogType(type), stringBuilder.toString()));
}
return CommandResult.success();
}
use of org.spongepowered.api.CatalogType in project SpongeCommon by SpongePowered.
the class MemoryDataView method set.
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public DataView set(DataQuery path, Object value) {
checkNotNull(path, "path");
checkNotNull(value, "value");
checkState(this.container != null);
@Nullable DataManager manager;
// TODO: this call to getDataManager each set can be cleaned up
try {
manager = Sponge.getDataManager();
} catch (Exception e) {
manager = null;
}
List<String> parts = path.getParts();
String key = parts.get(0);
if (parts.size() > 1) {
DataQuery subQuery = of(key);
Optional<DataView> subViewOptional = this.getUnsafeView(subQuery);
DataView subView;
if (!subViewOptional.isPresent()) {
this.createView(subQuery);
subView = (DataView) this.map.get(key);
} else {
subView = subViewOptional.get();
}
subView.set(path.popFirst(), value);
return this;
}
if (value instanceof DataView) {
checkArgument(value != this, "Cannot set a DataView to itself.");
// always have to copy a data view to avoid overwriting existing
// views and to set the interior path correctly.
copyDataView(path, (DataView) value);
} else if (value instanceof DataSerializable) {
DataContainer valueContainer = ((DataSerializable) value).toContainer();
checkArgument(!(valueContainer).equals(this), "Cannot insert self-referencing DataSerializable");
// see above for why this is copied
copyDataView(path, valueContainer);
} else if (value instanceof CatalogType) {
return set(path, ((CatalogType) value).getId());
} else if (manager != null && manager.getTranslator(value.getClass()).isPresent()) {
DataTranslator serializer = manager.getTranslator(value.getClass()).get();
final DataContainer container = serializer.translate(value);
checkArgument(!container.equals(this), "Cannot insert self-referencing Objects!");
// see above for why this is copied
copyDataView(path, container);
} else if (value instanceof Collection) {
setCollection(key, (Collection) value);
} else if (value instanceof Map) {
setMap(key, (Map) value);
} else if (value.getClass().isArray()) {
if (this.safety == SafetyMode.ALL_DATA_CLONED || this.safety == SafetyMode.CLONED_ON_SET) {
if (value instanceof byte[]) {
this.map.put(key, ArrayUtils.clone((byte[]) value));
} else if (value instanceof short[]) {
this.map.put(key, ArrayUtils.clone((short[]) value));
} else if (value instanceof int[]) {
this.map.put(key, ArrayUtils.clone((int[]) value));
} else if (value instanceof long[]) {
this.map.put(key, ArrayUtils.clone((long[]) value));
} else if (value instanceof float[]) {
this.map.put(key, ArrayUtils.clone((float[]) value));
} else if (value instanceof double[]) {
this.map.put(key, ArrayUtils.clone((double[]) value));
} else if (value instanceof boolean[]) {
this.map.put(key, ArrayUtils.clone((boolean[]) value));
} else {
this.map.put(key, ArrayUtils.clone((Object[]) value));
}
} else {
this.map.put(key, value);
}
} else {
this.map.put(key, value);
}
return this;
}
Aggregations