org.spongepowered.api.data.DataQuery Java Examples

The following examples show how to use org.spongepowered.api.data.DataQuery. 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: MongoRecords.java    From Prism with MIT License 6 votes vote down vote up
/**
  * Convert a mongo Document to a DataContainer.
  * @param document Mongo document.
  * @return Data container.
  */
 private DataContainer documentToDataContainer(Document document) {
     DataContainer result = DataContainer.createNew();

     for (String key : document.keySet()) {
         DataQuery query = DataUtil.unescapeQuery(key);
         Object value = document.get(key);

         if (value instanceof Document) {
             PrimitiveArray primitiveArray = PrimitiveArray.of((Document) value);
             if (primitiveArray != null) {
                 result.set(query, primitiveArray.getArray());
                 continue;
             }

             result.set(query, documentToDataContainer((Document) value));
         } else {
             result.set(query, value);
         }
     }

     return result;
}
 
Example #2
Source File: DataUtil.java    From Prism with MIT License 6 votes vote down vote up
/**
 * Helper method for writing values to a {@link DataView DataView}.
 *
 * @param dataView DataView
 * @param path DataQuery
 * @param value Object
 * @throws IllegalArgumentException If an attempt is made to change an existing value.
 */
public static void writeToDataView(DataView dataView, DataQuery path, Object value) throws IllegalArgumentException {
    Preconditions.checkNotNull(dataView);
    Preconditions.checkNotNull(path);

    Object currentValue = dataView.get(path).orElse(null);
    if (currentValue != null) {
        if (!currentValue.equals(value)) {
            throw new IllegalArgumentException("Attempted to overwrite " + path.toString());
        }

        Prism.getInstance().getLogger().warn("Attempted to overwrite {} with the same value", path.toString(), new Exception());
        return;
    }

    dataView.set(path, value);
}
 
Example #3
Source File: AbstractFactionStorage.java    From EagleFactions with MIT License 6 votes vote down vote up
private FactionChest getFactionChest(final Connection connection, final String factionName) throws SQLException, IOException, ClassNotFoundException
{
    FactionChest factionChest = new FactionChestImpl(factionName);
    PreparedStatement preparedStatement = connection.prepareStatement(SELECT_CHEST_WHERE_FACTIONNAME);
    preparedStatement.setString(1, factionName);
    ResultSet resultSet = preparedStatement.executeQuery();
    if (resultSet.first())
    {
        byte[] factionChestItems = resultSet.getBytes("ChestItems");
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(factionChestItems);
        DataContainer dataContainer = DataFormats.NBT.readFrom(byteArrayInputStream);
        byteArrayInputStream.close();
        Inventory inventory = Inventory.builder().of(InventoryArchetypes.CHEST).build(this.plugin);
        InventorySerializer.deserializeInventory(dataContainer.getViewList(DataQuery.of("inventory")).orElse(new ArrayList<>()), inventory);
        factionChest = new FactionChestImpl(factionName, inventory);
    }
    resultSet.close();
    preparedStatement.close();
    return factionChest;
}
 
Example #4
Source File: VirtualChestItemStackSerializer.java    From VirtualChest with GNU Lesser General Public License v3.0 6 votes vote down vote up
private <T, U extends BaseValue<T>> void deserializeForKeys(
        ConfigurationNode node, DataQuery dataQuery, BiConsumer<Key<U>, T> consumer) throws InvalidDataException
{
    if (KEYS.containsKey(dataQuery))
    {
        try
        {
            @SuppressWarnings("unchecked")
            Key<U> key = (Key<U>) KEYS.get(dataQuery);
            @SuppressWarnings("unchecked")
            TypeToken<T> elementToken = (TypeToken<T>) key.getElementToken();
            consumer.accept(key, Optional.ofNullable(node.getValue(elementToken))
                    .orElseThrow(() -> new InvalidDataException("No value present")));
        }
        catch (ObjectMappingException e)
        {
            throw new InvalidDataException(e);
        }
    }
    else if (!EXCEPTIONS.contains(dataQuery))
    {
        throw new InvalidDataException("No matched query present");
    }
}
 
Example #5
Source File: ItemInfoExecutor.java    From EssentialCmds with MIT License 6 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (src instanceof Player)
	{
		Player player = (Player) src;

		if (player.getItemInHand(HandTypes.MAIN_HAND).isPresent())
		{
			ItemStack itemInHand = player.getItemInHand(HandTypes.MAIN_HAND).get();
			player.sendMessage(Text.of(TextColors.GOLD, "The name of the item in your hand is: ", TextColors.GRAY, itemInHand.getTranslation().get()));
			player.sendMessage(Text.of(TextColors.GOLD, "The ID of the item in your hand is: ", TextColors.GRAY, itemInHand.getItem().getId()));
			player.sendMessage(Text.of(TextColors.GOLD, "The meta of the item in your hand is: ", TextColors.GRAY, itemInHand.toContainer().get(DataQuery.of("UnsafeDamage")).get().toString()));
		}
		else
		{
			player.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You must hold an item."));
		}
	}
	else
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You must be an in-game player to use this command."));
	}

	return CommandResult.success();
}
 
Example #6
Source File: ElementRegistry.java    From HuskyUI-Plugin with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Convert an ItemStack into an ElementID
 *
 * @param stack ItemStack to pull ElementID from
 * @return ElementID, if it exists. This ID may not actually be associated with an Element, so please verify that before use with {@link #elementExists(int)}.
 */
public Optional<Integer> getElementIDFromItemStack(ItemStack stack){
    if(stack.getType() == ItemTypes.AIR || stack.getType() == ItemTypes.NONE) return Optional.empty();
    Optional<Object> optRegID = stack.toContainer().get(DataQuery.of("UnsafeData", "regid"));
    if(optRegID.isPresent()){
        return Optional.of((int)optRegID.get());
    }
    return Optional.empty();
}
 
Example #7
Source File: DataUtil.java    From Prism with MIT License 5 votes vote down vote up
/**
 * Encodes all non-alphanumeric characters in the provided DataQuery,
 * the encodes parts are then joined with a non-encoded symbol.
 *
 * Fixes https://github.com/prism/Prism/issues/90
 *
 * @param dataQuery Unescaped DataQuery
 * @return Escaped string
 */
public static String escapeQuery(DataQuery dataQuery) {
    List<String> parts = Lists.newArrayList();

    for (String part : dataQuery.getParts()) {
        parts.add(escape(part));
    }

    return StringUtils.join(parts, '/');
}
 
Example #8
Source File: PrismRecord.java    From Prism with MIT License 5 votes vote down vote up
/**
 * Save the current record.
 */
public void save() {
    DataUtil.writeToDataView(getDataContainer(), DataQueries.Created, new Date());
    DataUtil.writeToDataView(getDataContainer(), DataQueries.EventName, getEvent());

    DataQuery causeKey = DataQueries.Cause;
    String causeValue = "environment";
    if (getSource() instanceof Player) {
        causeKey = DataQueries.Player;
        causeValue = ((Player) getSource()).getUniqueId().toString();
    } else if (getSource() instanceof Entity) {
        causeValue = ((Entity) getSource()).getType().getName();
    }

    DataUtil.writeToDataView(getDataContainer(), causeKey, causeValue);

    // Source filtered?
    if (!Prism.getInstance().getFilterList().allowsSource(getSource())) {
        return;
    }

    // Original block filtered?
    Optional<BlockType> originalBlockType = getDataContainer().getObject(DataQueries.OriginalBlock.then(DataQueries.BlockState).then(DataQueries.BlockType), BlockType.class);
    if (originalBlockType.map(Prism.getInstance().getFilterList()::allows).orElse(false)) {
        return;
    }

    // Replacement block filtered?
    Optional<BlockType> replacementBlockType = getDataContainer().getObject(DataQueries.ReplacementBlock.then(DataQueries.BlockState).then(DataQueries.BlockType), BlockType.class);
    if (replacementBlockType.map(Prism.getInstance().getFilterList()::allows).orElse(false)) {
        return;
    }

    // Queue the finished record for saving
    RecordingQueue.add(this);
}
 
Example #9
Source File: FieldCondition.java    From Prism with MIT License 5 votes vote down vote up
/**
 * Build a condition for use with querying the storage.
 *
 * @param field DataQuery matching the field name.
 * @param matchRule MatchRule describing comparison of values.
 * @param value List, String or Number value.
 */
public FieldCondition(DataQuery field, MatchRule matchRule, Object value) {
    checkNotNull(field);
    checkNotNull(matchRule);
    checkNotNull(value);
    this.field = field;
    this.matchRule = matchRule;
    this.value = value;
}
 
Example #10
Source File: InfoWorldCommand.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    WorldProperties world;
    if (!args.hasAny("world")) {
        checkIfPlayer(src);
        Player p = (Player) src;
        world = p.getWorld().getProperties();
    } else {
        world = args.<WorldProperties>getOne("world").get();
    }
    Messages.send(src, "world.command.world.info.single.title", "%world%", world.getWorldName());
    Messages.send(src, "world.command.world.info.single.id-uuid", "%id%", world.getUniqueId().toString());
    String numeric;
    try {
        numeric = world.getAdditionalProperties().getView(DataQuery.of("SpongeData")).get().get(DataQuery.of("dimensionId")).get().toString();
    } catch (Exception ex) {
        numeric = "?";
    }
    Messages.send(src, "world.command.world.info.single.id-numeric", "%id%", numeric);
    Messages.send(src, "world.command.world.info.single.enabled", "%enabled%", world.loadOnStartup() ? Messages.getFormatted(src, "world.enabled") : Messages.getFormatted(src, "world.disabled"));
    Messages.send(src, "world.command.world.info.single.difficulty", "%difficulty%", world.getDifficulty().getName());
    Messages.send(src, "world.command.world.info.single.gamemode", "%gamemode%", world.getGameMode().getName());
    Messages.send(src, "world.command.world.info.single.hardcore", "%hardcore%", world.isHardcore() ? Messages.getFormatted(src, "world.enabled") : Messages.getFormatted(src, "world.disabled"));
    Messages.send(src, "world.command.world.info.single.pvp", "%pvp%", world.isPVPEnabled() ? Messages.getFormatted(src, "world.enabled") : Messages.getFormatted(src, "world.disabled"));
    src.sendMessage(Messages.getFormatted(src, "world.command.world.info.single.gamerules").toBuilder().onClick(TextActions.runCommand("/world gamerule " + world.getWorldName())).build());
    return CommandResult.success();
}
 
Example #11
Source File: BlockInfoExecutor.java    From EssentialCmds with MIT License 5 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (src instanceof Player)
	{
		Player player = (Player) src;

		BlockRay<World> playerBlockRay = BlockRay.from(player).blockLimit(5).build();
		BlockRayHit<World> finalHitRay = null;

		while (playerBlockRay.hasNext())
		{
			BlockRayHit<World> currentHitRay = playerBlockRay.next();

			if (!player.getWorld().getBlockType(currentHitRay.getBlockPosition()).equals(BlockTypes.AIR))
			{
				finalHitRay = currentHitRay;
				break;
			}
		}

		if (finalHitRay != null)
		{
			player.sendMessage(Text.of(TextColors.GOLD, "The name of the block you're looking at is: ", TextColors.GRAY, finalHitRay.getLocation().getBlock().getType().getTranslation().get()));
			player.sendMessage(Text.of(TextColors.GOLD, "The ID of the block you're looking at is: ", TextColors.GRAY, finalHitRay.getLocation().getBlock().getName()));
			Optional<Object> metaDataQuery = finalHitRay.getLocation().getBlock().toContainer().get(DataQuery.of("UnsafeMeta"));
			player.sendMessage(Text.of(TextColors.GOLD, "The meta of the block you're looking at is: ", TextColors.GRAY, metaDataQuery.isPresent() ? metaDataQuery.get().toString() : 0));
		}
		else
		{
			player.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You're not looking at any block within range."));
		}
	}
	else
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You must be an in-game player to use this command."));
	}

	return CommandResult.success();
}
 
Example #12
Source File: VirtualChestInventoryBuilder.java    From VirtualChest with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected Optional<VirtualChestInventory> buildContent(DataView view) throws InvalidDataException
{
    this.items.clear();
    for (DataQuery key : view.getKeys(false))
    {
        String keyString = key.toString();
        if (keyString.startsWith(VirtualChestInventory.KEY_PREFIX))
        {
            SlotIndex slotIndex = SlotIndex.of(VirtualChestInventory.keyToSlotIndex(keyString));
            for (DataView dataView : VirtualChestItem.getViewListOrSingletonList(key, view))
            {
                VirtualChestItem item = VirtualChestItem.deserialize(plugin, dataView);
                this.items.put(slotIndex, item);
            }
        }
    }

    this.title = view.getString(VirtualChestInventory.TITLE)
            .map(TextSerializers.FORMATTING_CODE::deserialize)
            .orElseThrow(() -> new InvalidDataException("Expected title"));

    this.height = view.getInt(VirtualChestInventory.HEIGHT)
            .orElseThrow(() -> new InvalidDataException("Expected height"));

    this.triggerItems.clear();
    VirtualChestItem.getViewListOrSingletonList(VirtualChestInventory.TRIGGER_ITEM, view)
            .forEach(dataView -> this.triggerItems.add(new VirtualChestTriggerItem(dataView)));

    this.openActionCommand = view.getString(VirtualChestInventory.OPEN_ACTION_COMMAND);

    this.closeActionCommand = view.getString(VirtualChestInventory.CLOSE_ACTION_COMMAND);

    this.updateIntervalTick = view.getInt(VirtualChestInventory.UPDATE_INTERVAL_TICK).orElse(0);

    this.actionIntervalTick = view.getInt(VirtualChestInventory.ACCEPTABLE_ACTION_INTERVAL_TICK);

    return Optional.of(new VirtualChestInventory(this.plugin, this));
}
 
Example #13
Source File: VirtualChestItem.java    From VirtualChest with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static List<DataView> getViewListOrSingletonList(DataQuery key, DataView view)
{
    Optional<List<?>> listOptional = view.getList(key);
    if (!listOptional.isPresent())
    {
        return view.getView(key).map(Collections::singletonList).orElseGet(Collections::emptyList);
    }
    ImmutableList.Builder<DataView> builder = ImmutableList.builder();
    for (Object data : listOptional.get())
    {
        DataContainer container = SpongeUnimplemented.newDataContainer(DataView.SafetyMode.NO_DATA_CLONED);
        container.set(key, data).getView(key).ifPresent(builder::add);
    }
    return builder.build();
}
 
Example #14
Source File: ElementRegistry.java    From HuskyUI-Plugin with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get an inventory-ready itemstack for any given element
 *
 * @param elementID ElementID to get an itemstack of.
 * @return ItemStack of given element.
 */
public ItemStack getItemStackForElement(int elementID){
    if(elements.containsKey(elementID)){
        return ItemStack.builder()
                .fromContainer(elements.get(elementID)
                        .getItem()
                        .toContainer()
                        .set(DataQuery.of("UnsafeData", "regid"), elementID))
                .build();
    }
    throw new RuntimeException("Cannot get ItemStack: Element id \"" + elementID + "\" is not registered.");
}
 
Example #15
Source File: GDSpongeClaimSchematic.java    From GriefDefender with MIT License 5 votes vote down vote up
public GDSpongeClaimSchematic(Claim claim, Schematic schematic, String name, Instant creationDate) {
    this.claim = claim;
    this.schematic = schematic;
    this.name = schematic.getMetadata().getString(DataQuery.of(".", Schematic.METADATA_NAME)).orElse(name);
    this.origin = claim.getLesserBoundaryCorner();
    this.dateCreated = creationDate != null ? creationDate : Instant.now();
}
 
Example #16
Source File: VirtualChestItemStackSerializer.java    From VirtualChest with GNU Lesser General Public License v3.0 4 votes vote down vote up
private ConfigurationNode convertToConfigurationNode(DataView view)
{
    ConfigurationOptions configurationOptions = ConfigurationOptions.defaults().setSerializers(this.serializers);
    Map<?, ?> values = view.getMap(DataQuery.of()).orElseThrow(InvalidDataException::new);
    return SimpleConfigurationNode.root(configurationOptions).setValue(values);
}
 
Example #17
Source File: DataUtil.java    From Prism with MIT License 4 votes vote down vote up
/**
 * Converts a DataView object into a JsonObject.
 *
 * @param view DataView
 * @return JsonObject JsonObject representation of the DataView
 */
public static JsonObject jsonFromDataView(DataView view) {
    JsonObject jsonObject = new JsonObject();
    Gson gson = new GsonBuilder().create();

    Set<DataQuery> keys = view.getKeys(false);
    for (DataQuery query : keys) {

        String key = escapeQuery(query);
        Object value = view.get(query).orElse(null);

        if (value == null) {
            // continue
        } else if (value instanceof Collection) {
            List<Object> convertedList = Lists.newArrayList();
            for (Object object : (Collection<?>) value) {
                if (object == null) {
                    // continue
                } else if (object instanceof Collection) {
                    convertedList.add(gson.toJsonTree(object));
                } else if (object instanceof DataView) {
                    convertedList.add(jsonFromDataView((DataView) object));
                } else if (DataUtil.isPrimitiveType(object)) {
                    convertedList.add(gson.toJsonTree(object));
                } else if (object.getClass().isArray()) {
                    convertedList.add(gson.toJsonTree(new PrimitiveArray(object)));
                } else if (object.getClass().isEnum()) {
                    // convertedList.add(object.toString());
                } else {
                    Prism.getInstance().getLogger().error("Unsupported json list data type: " + object.getClass().getName() + " for key " + key);
                }

                if (!convertedList.isEmpty()) {
                    jsonObject.add(key, gson.toJsonTree(convertedList));
                }
            }
        } else if (value instanceof Boolean) {
            jsonObject.addProperty(key, (Boolean) value);
        } else if (value instanceof Character) {
            jsonObject.addProperty(key, (Character) value);
        } else if (value instanceof DataView) {
            jsonObject.add(key, jsonFromDataView((DataView) value));
        } else if (value instanceof Number) {
            jsonObject.addProperty(key, (Number) value);
        } else if (value instanceof String) {
            jsonObject.addProperty(key, (String) value);
        } else if (value.getClass().isArray()) {
            jsonObject.add(key, gson.toJsonTree(new PrimitiveArray(value)));
        } else {
            // Prism.getInstance().getLogger().error("Unsupported json data type: " + value.getClass().getName() + " for key " + key);
        }
    }

    return jsonObject;
}
 
Example #18
Source File: MongoRecords.java    From Prism with MIT License 4 votes vote down vote up
/**
 * Converts a DataView to a Document, recursively if needed.
 *
 * @param view Data view/container.
 * @return Document for Mongo storage.
 */
private Document documentFromView(DataView view) {
    Document document = new Document();

    Set<DataQuery> keys = view.getKeys(false);
    for (DataQuery query : keys) {
        String key = DataUtil.escapeQuery(query);
        Object value = view.get(query).orElse(null);

        if (value == null) {
            // continue
        } else if (value instanceof Collection) {
            List<Object> convertedList = Lists.newArrayList();
            for (Object object : (Collection<?>) value) {
                if (object == null) {
                    // continue
                } else if (object instanceof DataView) {
                    convertedList.add(documentFromView((DataView) object));
                } else if (DataUtil.isPrimitiveType(object)) {
                    convertedList.add(object);
                } else if (object.getClass().isArray()) {
                    document.append(key, new PrimitiveArray(object));
                } else if (object.getClass().isEnum()) {
                    // Ignoring, this data should exist elsewhere in the document.
                    // this is ConnectedDirections and other vanilla manipulators
                    // convertedList.add(object.toString());
                }  else {
                    Prism.getInstance().getLogger().error("Unsupported list data type: " + object.getClass().getName());
                }
            }

            if (!convertedList.isEmpty()) {
                document.append(key, convertedList);
            }
        } else if (value instanceof DataView) {
            document.append(key, documentFromView((DataView) value));
        } else if (value.getClass().isArray()) {
            document.append(key, new PrimitiveArray(value));
        } else {
            if (key.equals(DataQueries.Player.toString())) {
                document.append(DataQueries.Player.toString(), value);
            } else {
                document.append(key, value);
            }
        }
    }

    return document;
}
 
Example #19
Source File: DataUtil.java    From Prism with MIT License 3 votes vote down vote up
/**
 * Decodes all encoded characters in the provided String,
 * the string is split by a non-encoded symbol and each part is then decoded
 * and finally a DataQuery is created using the decoded parts.
 *
 * Fixes https://github.com/prism/Prism/issues/90
 *
 * @param string Escaped string
 * @return Unescaped DataQuery
 */
public static DataQuery unescapeQuery(String string) {
    List<String> parts = Lists.newArrayList();
    for (String part : StringUtils.split(string, '/')) {
        parts.add(unescape(part));
    }

    return DataQuery.of(parts);
}
 
Example #20
Source File: SQLQuery.java    From Prism with MIT License 2 votes vote down vote up
/**
 * Add a value mutator.
 *
 * @param path DataQuery
 * @param mutator QueryValueMutator mutator
 * @return Builder
 */
public Builder valueMutator(DataQuery path, QueryValueMutator mutator) {
    valueMutators.put(path, mutator);
    return this;
}
 
Example #21
Source File: FieldCondition.java    From Prism with MIT License 2 votes vote down vote up
/**
 * Statically build a new condition.
 *
 * @param query DataQuery matching the field name.
 * @param matchRule MatchRule describing comparison of values.
 * @param value List, String or Number value.
 * @return Condition
 */
public static FieldCondition of(DataQuery query, MatchRule matchRule, Object value) {
    return new FieldCondition(query, matchRule, value);
}
 
Example #22
Source File: FieldCondition.java    From Prism with MIT License 2 votes vote down vote up
/**
 * Statically build a new condition.
 *
 * @param field DataQuery matching the field name.
 * @param value Range of values.
 * @return Condition
 */
public static FieldCondition of(DataQuery field, Range<?> value) {
    return new FieldCondition(field, MatchRule.BETWEEN, value);
}
 
Example #23
Source File: FieldCondition.java    From Prism with MIT License 2 votes vote down vote up
/**
 * Returns the DataQuery name for the field
 * this condition applies to.
 *
 * @return DataQuery DataQuery field name.
 */
public DataQuery getFieldName() {
    return field;
}