org.spongepowered.api.data.DataView Java Examples

The following examples show how to use org.spongepowered.api.data.DataView. 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: EntityResult.java    From Prism with MIT License 6 votes vote down vote up
@Override
public ActionableResult rollback() {

    DataView entityData = formatEntityData();

    Optional<EntitySnapshot> snapshot = Sponge.getRegistry().createBuilder(Builder.class).build(entityData);
    if (!snapshot.isPresent()) {
        return ActionableResult.skipped(SkipReason.INVALID);
    }

    Optional<Entity> entity = snapshot.get().restore();
    if (!entity.isPresent()) {
        return ActionableResult.skipped(SkipReason.INVALID);
    }

    // Don't let it burn to death (again?)
    entity.get().get(IgniteableData.class).ifPresent(data -> entity.get().offer(data.fireTicks().set(0)));

    // Heal, it was probably killed.
    entity.get().get(HealthData.class).ifPresent(data -> entity.get().offer(data.health().set(data.maxHealth().get())));

    return ActionableResult.success(new Transaction<>(new SerializableNonExistent(), entity.get()));
}
 
Example #2
Source File: BlockResult.java    From Prism with MIT License 6 votes vote down vote up
public DataView formatBlockData(DataView finalBlock, @Nonnull Object optionalLocation) {
    Preconditions.checkNotNull(optionalLocation, "The location you are formatting cannot be null.");
    DataView location = (DataView) optionalLocation;
    DataView position = DataContainer.createNew();
    position.set(DataQueries.X, location.get(DataQueries.X).get());
    position.set(DataQueries.Y, location.get(DataQueries.Y).get());
    position.set(DataQueries.Z, location.get(DataQueries.Z).get());
    finalBlock.set(DataQueries.Position, position);
    finalBlock.set(DataQueries.WorldUuid, location.get(DataQueries.WorldUuid).get());

    int blockStateVersion = finalBlock.getInt(DataQueries.BlockState.then(DataQueries.ContentVersion)).orElse(1);
    if (blockStateVersion == 1) {
        // Unsafe data includes coordinates
        Optional<Object> optionalUnsafeData = finalBlock.get(DataQueries.UnsafeData);
        if (optionalUnsafeData.isPresent()) {
            DataView unsafeData = (DataView) optionalUnsafeData.get();
            unsafeData.set(DataQueries.X, location.get(DataQueries.X).get());
            unsafeData.set(DataQueries.Y, location.get(DataQueries.Y).get());
            unsafeData.set(DataQueries.Z, location.get(DataQueries.Z).get());
            finalBlock.set(DataQueries.UnsafeData, unsafeData);
        }
    }

    return finalBlock;
}
 
Example #3
Source File: PrismRecord.java    From Prism with MIT License 6 votes vote down vote up
/**
 * Removes unnecessary/duplicate data from a BlockSnapshot's DataContainer.
 *
 * @param block {@link BlockSnapshot BlockSnapshot}
 * @return Formatted {@link DataContainer DataContainer}
 */
private DataContainer formatBlockDataContainer(BlockSnapshot block) {
    Preconditions.checkNotNull(block);
    Preconditions.checkNotNull(block.getState(), "Missing BlockState: " + block.toString());

    DataContainer blockData = block.toContainer();
    blockData.remove(DataQueries.Position);
    blockData.remove(DataQueries.WorldUuid);

    DataView unsafeData = blockData.getObject(DataQueries.UnsafeData, DataView.class).orElse(null);
    if (unsafeData != null) {
        unsafeData.remove(DataQueries.X);
        unsafeData.remove(DataQueries.Y);
        unsafeData.remove(DataQueries.Z);
        blockData.set(DataQueries.UnsafeData, unsafeData);
    }

    return blockData;
}
 
Example #4
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 #5
Source File: InventorySerializer.java    From EagleFactions with MIT License 6 votes vote down vote up
public static List<DataView> serializeInventory(Inventory inventory) {
    DataContainer container;
    List<DataView> slots = new LinkedList<>();

    int i = 0;
    Optional<ItemStack> stack;

    for (Inventory inv : inventory.slots()) {
        stack = inv.peek();

        if (stack.isPresent()) {
            container = DataContainer.createNew(SafetyMode.ALL_DATA_CLONED);

            container.set(SLOT, i);
            container.set(STACK, serializeItemStack(stack.get()));

            slots.add(container);
        }

        i++;
    }

    return slots;
}
 
Example #6
Source File: VirtualChestItem.java    From VirtualChest with GNU Lesser General Public License v3.0 6 votes vote down vote up
private VirtualChestItem(
        VirtualChestPlugin plugin,
        DataView serializedStack,
        Tuple<String, CompiledScript> requirements,
        VirtualChestActionDispatcher primaryAction,
        VirtualChestActionDispatcher secondaryAction,
        VirtualChestActionDispatcher primaryShiftAction,
        VirtualChestActionDispatcher secondaryShiftAction,
        List<String> ignoredPermissions)
{
    this.plugin = plugin;
    this.serializer = new VirtualChestItemStackSerializer(plugin);

    this.serializedStack = serializedStack;
    this.requirements = requirements;
    this.primaryAction = primaryAction;
    this.secondaryAction = secondaryAction;
    this.primaryShiftAction = primaryShiftAction;
    this.secondaryShiftAction = secondaryShiftAction;
    this.ignoredPermissions = ignoredPermissions;
}
 
Example #7
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 #8
Source File: EntityResult.java    From Prism with MIT License 5 votes vote down vote up
private DataView formatEntityData() {
    DataView entity = data.getView(DataQueries.Entity).get();

    // Restore Position
    DataView location = data.getView(DataQueries.Location).get();
    entity.set(DataQueries.WorldUuid, location.getString(DataQueries.WorldUuid).get());
    location.remove(DataQueries.WorldUuid);
    entity.set(DataQueries.Position, location);

    // UnsafeData
    DataView unsafe = entity.getView(DataQueries.UnsafeData).get();

    List<Double> coordinates = new ArrayList<>();
    coordinates.add(location.getDouble(DataQueries.X).get());
    coordinates.add(location.getDouble(DataQueries.Y).get());
    coordinates.add(location.getDouble(DataQueries.Z).get());
    unsafe.set(DataQueries.Pos, coordinates);

    DataView rotation = entity.getView(DataQueries.Rotation).get();
    /* @todo For now this is commented out as we are not using it yet.
    List<Double> rot = new ArrayList<>();
    rot.add(rotation.getDouble(DataQueries.Y).get());
    rot.add(rotation.getDouble(DataQueries.Z).get());
    */
    unsafe.set(DataQueries.Rotation, rotation);

    entity.set(DataQueries.UnsafeData, unsafe);

    return entity;
}
 
Example #9
Source File: VirtualChestActionDispatcher.java    From VirtualChest with GNU Lesser General Public License v3.0 5 votes vote down vote up
public VirtualChestActionDispatcher(List<DataView> views)
{
    this.size = views.size();

    ImmutableList.Builder<VirtualChestHandheldItem> handheldItemBuilder = ImmutableList.builder();
    ImmutableList.Builder<Boolean> keepInventoryOpenBuilder = ImmutableList.builder();

    ImmutableList.Builder<List<String>> commandsBuilder = ImmutableList.builder();
    ImmutableList.Builder<List<String>> commandsAfterBuilder = ImmutableList.builder();
    ImmutableList.Builder<List<String>> commandsBeforeBuilder = ImmutableList.builder();

    ImmutableList.Builder<DataContainer> dataContainerBuilder = ImmutableList.builder();

    for (DataView view : views)
    {
        handheldItemBuilder.add(this.parseHandheldItem(view));
        keepInventoryOpenBuilder.add(view.getBoolean(KEEP_INVENTORY_OPEN).orElse(false));

        commandsBuilder.add(parseCommand(view.getString(COMMAND).orElse("")));
        commandsAfterBuilder.add(parseCommand(view.getString(COMMAND_AFTER).orElse("")));
        commandsBeforeBuilder.add(parseCommand(view.getString(COMMAND_BEFORE).orElse("")));

        dataContainerBuilder.add(view.copy());
    }

    this.handheldItem = handheldItemBuilder.build();
    this.keepInventoryOpen = keepInventoryOpenBuilder.build();

    this.commands = commandsBuilder.build();
    this.commandsAfter = commandsAfterBuilder.build();
    this.commandsBefore = commandsBeforeBuilder.build();

    this.views = dataContainerBuilder.build();
}
 
Example #10
Source File: DataUtil.java    From Prism with MIT License 5 votes vote down vote up
/**
 * Build a DataView from provided JSON.
 * @param json JsonObject
 * @return DataView
 */
public static DataView dataViewFromJson(JsonObject json) {
    DataContainer data = DataContainer.createNew();
    for (Entry<String, JsonElement> entry : json.entrySet()) {
        Optional<Object> value = jsonElementToObject(entry.getValue());
        if (value.isPresent()) {
            data.set(unescapeQuery(entry.getKey()), value.get());
        } else {
            Prism.getInstance().getLogger().error(String.format("Failed to transform %s data.", entry.getKey()));
        }
    }

    return data;
}
 
Example #11
Source File: VirtualChestHandheldItem.java    From VirtualChest with GNU Lesser General Public License v3.0 5 votes vote down vote up
public VirtualChestHandheldItem(DataView view)
{
    super(view.copy());
    this.count = view.getInt(COUNT).orElse(1);
    this.repetitionLimit = view.getInt(REPETITION_UPPER_LIMIT).orElse(0);
    this.searchInventory = view.getBoolean(SEARCH_INVENTORY).orElse(Boolean.FALSE);
}
 
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 VirtualChestItem deserialize(VirtualChestPlugin plugin, DataView data) throws InvalidDataException
{
    DataView serializedStack = data.getView(ITEM).orElseThrow(() -> new InvalidDataException("Expected Item"));

    String requirementString = data.getString(REQUIREMENTS).orElse("");
    Tuple<String, CompiledScript> requirements = plugin.getScriptManager().prepare(requirementString);

    List<String> ignoredPermissions = data.getStringList(IGNORED_PERMISSIONS).orElse(ImmutableList.of());

    List<DataView> actionList = getViewListOrSingletonList(ACTION, data);
    List<DataView> primaryList = getViewListOrSingletonList(PRIMARY_ACTION, data);
    List<DataView> secondaryList = getViewListOrSingletonList(SECONDARY_ACTION, data);
    List<DataView> primaryShiftList = getViewListOrSingletonList(PRIMARY_SHIFT_ACTION, data);
    List<DataView> secondaryShiftList = getViewListOrSingletonList(SECONDARY_SHIFT_ACTION, data);

    List<DataView> primaryListFinal = primaryList.isEmpty() ? actionList : primaryList;
    List<DataView> secondaryListFinal = secondaryList.isEmpty() ? actionList : secondaryList;
    List<DataView> primaryShiftListFinal = primaryShiftList.isEmpty() ? primaryListFinal : primaryShiftList;
    List<DataView> secondaryShiftListFinal = secondaryShiftList.isEmpty() ? secondaryListFinal : secondaryShiftList;

    VirtualChestActionDispatcher primaryAction = new VirtualChestActionDispatcher(primaryListFinal);
    VirtualChestActionDispatcher secondaryAction = new VirtualChestActionDispatcher(secondaryListFinal);
    VirtualChestActionDispatcher primaryShiftAction = new VirtualChestActionDispatcher(primaryShiftListFinal);
    VirtualChestActionDispatcher secondaryShiftAction = new VirtualChestActionDispatcher(secondaryShiftListFinal);

    return new VirtualChestItem(plugin, serializedStack, requirements,
            primaryAction, secondaryAction, primaryShiftAction, secondaryShiftAction, ignoredPermissions);
}
 
Example #14
Source File: VirtualChestItem.java    From VirtualChest with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static DataContainer serialize(VirtualChestPlugin plugin, VirtualChestItem item) throws InvalidDataException
{
    DataContainer container = SpongeUnimplemented.newDataContainer(DataView.SafetyMode.ALL_DATA_CLONED);

    container.set(ITEM, item.serializedStack);
    container.set(REQUIREMENTS, item.requirements.getFirst());
    container.set(IGNORED_PERMISSIONS, item.ignoredPermissions);

    item.primaryAction.getObjectForSerialization().ifPresent(o -> container.set(PRIMARY_ACTION, o));
    item.secondaryAction.getObjectForSerialization().ifPresent(o -> container.set(SECONDARY_ACTION, o));
    item.primaryShiftAction.getObjectForSerialization().ifPresent(o -> container.set(PRIMARY_SHIFT_ACTION, o));
    item.secondaryShiftAction.getObjectForSerialization().ifPresent(o -> container.set(SECONDARY_SHIFT_ACTION, o));

    return container;
}
 
Example #15
Source File: SpongeUnimplemented.java    From VirtualChest with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean isNBTMatched(Optional<DataView> matcher, ItemStackSnapshot item)
{
    try
    {
        Object nbt2 = GET_TAG_COMPOUND.invoke(FROM_SNAPSHOT_TO_NATIVE.invoke(item));
        Object nbt1 = matcher.isPresent() ? TRANSLATE_DATA.invoke(GET_INSTANCE.invoke(), matcher.get()) : null;
        return (boolean) ARE_NBT_EQUALS.invoke(nbt1, nbt2, true);
    }
    catch (Throwable throwable)
    {
        throw new UnsupportedOperationException(throwable);
    }
}
 
Example #16
Source File: VirtualChestTriggerItem.java    From VirtualChest with GNU Lesser General Public License v3.0 4 votes vote down vote up
public VirtualChestTriggerItem(DataView triggerItemConfiguration)
{
    super(triggerItemConfiguration.copy());
    this.enablePrimary = triggerItemConfiguration.getBoolean(ENABLE_PRIMARY_ACTION).orElse(true);
    this.enableSecondary = triggerItemConfiguration.getBoolean(ENABLE_SECONDARY_ACTION).orElse(true);
}
 
Example #17
Source File: LookupCallback.java    From Prism with MIT License 4 votes vote down vote up
private Text buildResult(Result result) {
    Text.Builder resultMessage = Text.builder();
    resultMessage.append(Text.of(TextColors.DARK_AQUA, result.getSourceName(), " "));
    resultMessage.append(Text.of(TextColors.WHITE, result.getEventVerb(), " "));

    Text.Builder hoverMessage = Text.builder();
    hoverMessage.append(Format.prefix(), Text.NEW_LINE);
    hoverMessage.append(Text.of(TextColors.DARK_GRAY, "Source: ", TextColors.WHITE, result.getSourceName(), Text.NEW_LINE));
    hoverMessage.append(Text.of(TextColors.DARK_GRAY, "PrismEvent: ", TextColors.WHITE, result.getEventName(), Text.NEW_LINE));

    String quantity = result.data.getString(DataQueries.Quantity).orElse(null);
    if (StringUtils.isNotBlank(quantity)) {
        resultMessage.append(Text.of(TextColors.DARK_AQUA, quantity, " "));
        hoverMessage.append(Text.of(TextColors.DARK_GRAY, "Quantity: ", TextColors.WHITE, quantity, Text.NEW_LINE));
    }

    String target = result.data.getString(DataQueries.Target).orElse("Unknown");
    if (StringUtils.isNotBlank(target)) {
        resultMessage.append(Text.of(TextColors.DARK_AQUA, Format.item(target, false), " "));
        hoverMessage.append(Text.of(TextColors.DARK_GRAY, "Target: ", TextColors.WHITE, target, Text.NEW_LINE));
    }

    String id = result.data.getString(DataQueries.Id).orElse(null);
    if (StringUtils.isNotBlank(id)) {
        hoverMessage.append(Text.of(TextColors.DARK_GRAY, "Id: ", TextColors.WHITE, id, Text.NEW_LINE));
    }

    String container = result.data.getString(DataQueries.Container).orElse(null);
    if (StringUtils.isNotBlank(container)) {
        hoverMessage.append(Text.of(TextColors.DARK_GRAY, "Container: ", TextColors.WHITE, container, Text.NEW_LINE));
    }

    if (result instanceof ResultAggregate) {
        int count = result.data.getInt(DataQueries.Count).orElse(0);
        if (count > 0) {
            resultMessage.append(Text.of(TextColors.GREEN, "x", count, " "));
            hoverMessage.append(Text.of(TextColors.DARK_GRAY, "Count: ", TextColors.WHITE, count));
        }
    }

    if (result instanceof ResultComplete) {
        ResultComplete resultComplete = (ResultComplete) result;

        resultMessage.append(Text.of(TextColors.WHITE, resultComplete.getRelativeTime()));
        hoverMessage.append(Text.of(TextColors.DARK_GRAY, "Time: ", TextColors.WHITE, resultComplete.getTime(), Text.NEW_LINE));

        DataView location = (DataView) resultComplete.data.get(DataQueries.Location).orElse(null);
        if (location != null) {
            int x = location.getInt(DataQueries.X).orElse(0);
            int y = location.getInt(DataQueries.Y).orElse(0);
            int z = location.getInt(DataQueries.Z).orElse(0);
            World world = location.get(DataQueries.WorldUuid).flatMap(TypeUtil::uuidFromObject).flatMap(Sponge.getServer()::getWorld).orElse(null);

            hoverMessage.append(Text.of(TextColors.DARK_GRAY, "Location: ", TextColors.WHITE, Format.location(x, y, z, world, false)));
            if (this.querySession.hasFlag(Flag.EXTENDED)) {
                resultMessage.append(Text.of(Text.NEW_LINE, TextColors.GRAY, " - ", Format.location(x, y, z, world, true)));
                hoverMessage.append(Text.of(Text.NEW_LINE, Text.NEW_LINE, TextColors.GRAY, "Click location to teleport."));
            }
        }
    }

    resultMessage.onHover(TextActions.showText(hoverMessage.build()));
    return resultMessage.build();
}
 
Example #18
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 #19
Source File: MySQLRecords.java    From Prism with MIT License 4 votes vote down vote up
@Override
public StorageWriteResult write(List<DataContainer> containers) throws Exception {

    List<String> extraData = new ArrayList<>();
    Map<Integer, String> extraDataMap = new HashMap<>();

    String sql = String.format("INSERT INTO %srecords(%s, %s, %s, %s, %s, %s, %s, %s, %s)" +
                    " values(?, ?, UNHEX(?), ?, ?, ?, ?, UNHEX(?), ?)",
            tablePrefix,
            DataQueries.Created, DataQueries.EventName, DataQueries.WorldUuid,
            DataQueries.X, DataQueries.Y, DataQueries.Z,
            DataQueries.Target, DataQueries.Player, DataQueries.Cause
    );

    try (Connection conn = MySQLStorageAdapter.getConnection(); PreparedStatement statement = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
        conn.setAutoCommit(false);

        for (DataContainer container : containers) {
            DataView location = container.getView(DataQueries.Location).get();

            String playerUUID = null;
            Optional<String> player = container.getString(DataQueries.Player);
            if (player.isPresent()) {
                playerUUID = TypeUtil.uuidStringToDbString(player.get());
            }

            statement.setLong( 1, System.currentTimeMillis() / 1000L );
            statement.setObject(2, container.getString(DataQueries.EventName).get());
            statement.setString(3, TypeUtil.uuidStringToDbString(location.getString(DataQueries.WorldUuid).get()));
            statement.setInt(4, location.getInt(DataQueries.X).get());
            statement.setInt(5, location.getInt(DataQueries.Y).get());
            statement.setInt(6, location.getInt(DataQueries.Z).get());
            statement.setString(7, container.getString(DataQueries.Target).orElse(null));
            statement.setString(8, playerUUID);
            statement.setString(9, container.getString(DataQueries.Cause).orElse(null));
            statement.addBatch();

            // Remove some data not needed for extra storage
            container.remove(DataQueries.Location);
            container.remove(DataQueries.EventName);
            container.remove(DataQueries.Player);
            container.remove(DataQueries.Cause);
            container.remove(DataQueries.Target);

            extraData.add(DataUtil.jsonFromDataView(container).toString());
        }

        statement.executeBatch();
        ResultSet keys = statement.getGeneratedKeys();
        conn.commit();

        int i = 0;
        while (keys.next()) {
            extraDataMap.put(keys.getInt(1), extraData.get(i));
            i++;
        }

        if (containers.size() != extraData.size()) {
            Prism.getInstance().getLogger().debug("Container has more information than we have extra entries for.");
        }

        writeExtraData(extraDataMap);
    }

    return null;
}
 
Example #20
Source File: H2Records.java    From Prism with MIT License 4 votes vote down vote up
@Override
public StorageWriteResult write(List<DataContainer> containers) throws Exception {
    String sql = String.format("INSERT INTO %srecords(%s, %s, %s, %s, %s, %s, %s, %s, %s)" +
                    " values(?, ?, ?, ?, ?, ?, ?, ?, ?)",
            tablePrefix,
            DataQueries.Created, DataQueries.EventName, DataQueries.WorldUuid,
            DataQueries.X, DataQueries.Y, DataQueries.Z,
            DataQueries.Target, DataQueries.Player, DataQueries.Cause
    );

    try (Connection conn = H2StorageAdapter.getConnection(); PreparedStatement statement = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {

        for (DataContainer container : containers) {
            DataView location = container.getView(DataQueries.Location).get();

            String playerUUID = null;
            Optional<String> player = container.getString(DataQueries.Player);
            if (player.isPresent()) {
                playerUUID = player.get();
            }

            statement.setLong( 1, System.currentTimeMillis() / 1000L );
            statement.setObject(2, container.getString(DataQueries.EventName).get());
            statement.setObject(3, location.getString(DataQueries.WorldUuid).get());
            statement.setInt(4, location.getInt(DataQueries.X).get());
            statement.setInt(5, location.getInt(DataQueries.Y).get());
            statement.setInt(6, location.getInt(DataQueries.Z).get());
            statement.setString(7, container.getString(DataQueries.Target).orElse(null));
            statement.setString(8, playerUUID);
            statement.setString(9, container.getString(DataQueries.Cause).orElse(null));

            // Remove some data not needed for extra storage
            container.remove(DataQueries.Location);
            container.remove(DataQueries.EventName);
            container.remove(DataQueries.Player);
            container.remove(DataQueries.Cause);
            container.remove(DataQueries.Target);

            statement.executeUpdate();
            ResultSet keys = statement.getGeneratedKeys();

            while (keys.next()) {
                writeExtraData(keys.getInt(1), DataUtil.jsonFromDataView(container).toString());
            }
        }
    }

    return null;
}
 
Example #21
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 #22
Source File: BlockResult.java    From Prism with MIT License 4 votes vote down vote up
@Override
public ActionableResult restore() {

    Optional<Object> optionalFinal = data.get(DataQueries.ReplacementBlock);
    if (!optionalFinal.isPresent()) {
        return ActionableResult.skipped(SkipReason.INVALID);
    }

    // Our data is stored with a different structure, so we'll need
    // a little manual effort to reformat it.
    DataView finalBlock = ((DataView) optionalFinal.get()).copy();

    // Build World UUID / Vec3 data BlockSnapshot expects
    Optional<Object> optionalLocation = data.get(DataQueries.Location);
    if (!optionalLocation.isPresent()) {
        return ActionableResult.skipped(SkipReason.INVALID_LOCATION);
    }

    // Format
    finalBlock = formatBlockData(finalBlock, optionalLocation.get());

    Optional<BlockSnapshot> optionalSnapshot = Sponge.getRegistry().createBuilder(Builder.class).build(finalBlock);
    if (!optionalSnapshot.isPresent()) {
        return ActionableResult.skipped(SkipReason.INVALID);
    }

    BlockSnapshot snapshot = optionalSnapshot.get();

    if (!snapshot.getLocation().isPresent()) {
        return ActionableResult.skipped(SkipReason.INVALID_LOCATION);
    }

    Location<World> location = snapshot.getLocation().get();

    // Filter unsafe blocks
    if (BlockUtil.rejectIllegalApplierBlock(snapshot.getState().getType())) {
        return ActionableResult.skipped(SkipReason.ILLEGAL_BLOCK);
    }

    // Current block in this space.
    BlockSnapshot original = location.getBlock().snapshotFor(location);

    // Actually restore!
    if (!optionalSnapshot.get().restore(true, BlockChangeFlags.NONE)) {
        return ActionableResult.skipped(SkipReason.UNKNOWN);
    }

    // Final block in this space.
    BlockSnapshot resultingBlock = location.getBlock().snapshotFor(location);
    return ActionableResult.success(new Transaction<>(original, resultingBlock));

}
 
Example #23
Source File: BlockResult.java    From Prism with MIT License 4 votes vote down vote up
@Override
public ActionableResult rollback() {

    Optional<Object> optionalOriginal = data.get(DataQueries.OriginalBlock);

    if (!optionalOriginal.isPresent()) {
        return ActionableResult.skipped(SkipReason.INVALID);
    }

    // Our data is stored with a different structure, so we'll need
    // a little manual effort to reformat it.
    DataView finalBlock = ((DataView) optionalOriginal.get()).copy();

    // Build World UUID / Vec3 data BlockSnapshot expects
    Optional<Object> optionalLocation = data.get(DataQueries.Location);
    if (!optionalLocation.isPresent()) {
        return ActionableResult.skipped(SkipReason.INVALID_LOCATION);
    }

    // Format
    finalBlock = formatBlockData(finalBlock, optionalLocation.get());

    Optional<BlockSnapshot> optionalSnapshot = Sponge.getRegistry().createBuilder(Builder.class).build(finalBlock);
    if (!optionalSnapshot.isPresent()) {
        return ActionableResult.skipped(SkipReason.INVALID);
    }

    BlockSnapshot snapshot = optionalSnapshot.get();

    if (!snapshot.getLocation().isPresent()) {
        return ActionableResult.skipped(SkipReason.INVALID_LOCATION);
    }

    Location<World> location = snapshot.getLocation().get();

    // Filter unsafe blocks
    if (BlockUtil.rejectIllegalApplierBlock(snapshot.getState().getType())) {
        return ActionableResult.skipped(SkipReason.ILLEGAL_BLOCK);
    }

    // Current block in this space.
    BlockSnapshot original = location.getBlock().snapshotFor(location);

    // Actually restore!
    if (!optionalSnapshot.get().restore(true, BlockChangeFlags.NONE)) {
        return ActionableResult.skipped(SkipReason.UNKNOWN);
    }

    // Final block in this space.
    BlockSnapshot resultingBlock = location.getBlock().snapshotFor(location);

    return ActionableResult.success(new Transaction<>(original, resultingBlock));

}
 
Example #24
Source File: VirtualChestActionDispatcher.java    From VirtualChest with GNU Lesser General Public License v3.0 4 votes vote down vote up
private VirtualChestHandheldItem parseHandheldItem(DataView view)
{
    return view.getView(HANDHELD_ITEM).map(VirtualChestHandheldItem::new).orElse(VirtualChestHandheldItem.DEFAULT);
}
 
Example #25
Source File: VirtualChestItemTemplateWithNBT.java    From VirtualChest with GNU Lesser General Public License v3.0 4 votes vote down vote up
public VirtualChestItemTemplateWithNBT(DataView view)
{
    super(view.copy());
    this.nbt = this.toContainer().getView(UNSAFE_NBT);
}
 
Example #26
Source File: VirtualChestItemTemplateWithNBT.java    From VirtualChest with GNU Lesser General Public License v3.0 4 votes vote down vote up
public VirtualChestItemTemplateWithNBT()
{
    super(SpongeUnimplemented.newDataContainer(DataView.SafetyMode.ALL_DATA_CLONED));
    this.nbt = Optional.empty();
}
 
Example #27
Source File: VirtualChestItemStackSerializer.java    From VirtualChest with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public ItemStack apply(Player player, DataView view) throws InvalidDataException
{
    return this.deserializeItemFrom(this.applyPlaceholders(player, view));
}
 
Example #28
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 #29
Source File: SpongeUnimplemented.java    From VirtualChest with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
public static DataContainer newDataContainer(DataView.SafetyMode safetyMode)
{
    return new org.spongepowered.api.data.MemoryDataContainer(safetyMode);
}
 
Example #30
Source File: InventorySerializer.java    From EagleFactions with MIT License 4 votes vote down vote up
public static ItemStack deserializeItemStack(DataView data) {
    return ItemStack.builder().fromContainer(data).build();
}