diff --git a/refinedstorage2-core-api/src/main/java/com/refinedmods/refinedstorage2/api/core/filter/Filter.java b/refinedstorage2-core-api/src/main/java/com/refinedmods/refinedstorage2/api/core/filter/Filter.java deleted file mode 100644 index f2d7ee7f3..000000000 --- a/refinedstorage2-core-api/src/main/java/com/refinedmods/refinedstorage2/api/core/filter/Filter.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.refinedmods.refinedstorage2.api.core.filter; - -import java.util.HashSet; -import java.util.Set; -import java.util.function.UnaryOperator; -import java.util.stream.Collectors; - -import org.apiguardian.api.API; - -@API(status = API.Status.STABLE, since = "2.0.0-milestone.1.0") -public class Filter { - private final Set templates = new HashSet<>(); - private FilterMode mode = FilterMode.BLOCK; - private UnaryOperator normalizer = value -> value; - - public FilterMode getMode() { - return mode; - } - - public void setNormalizer(final UnaryOperator normalizer) { - this.normalizer = normalizer; - } - - public void setMode(final FilterMode mode) { - this.mode = mode; - } - - public boolean isAllowed(final Object template) { - final Object normalized = normalizer.apply(template); - return switch (mode) { - case ALLOW -> templates.contains(normalized); - case BLOCK -> !templates.contains(normalized); - }; - } - - public void setTemplates(final Set templates) { - this.templates.clear(); - this.templates.addAll(templates.stream().map(normalizer).collect(Collectors.toSet())); - } -} diff --git a/refinedstorage2-core-api/src/test/java/com/refinedmods/refinedstorage2/api/core/filter/FilterTest.java b/refinedstorage2-core-api/src/test/java/com/refinedmods/refinedstorage2/api/core/filter/FilterTest.java deleted file mode 100644 index 96ab9392e..000000000 --- a/refinedstorage2-core-api/src/test/java/com/refinedmods/refinedstorage2/api/core/filter/FilterTest.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.refinedmods.refinedstorage2.api.core.filter; - -import java.util.Set; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -class FilterTest { - private Filter sut; - - @BeforeEach - void setUp() { - sut = new Filter(); - } - - @Test - void testDefaults() { - // Assert - assertThat(sut.getMode()).isEqualTo(FilterMode.BLOCK); - } - - @Test - void testEmptyBlocklistShouldAllowAll() { - // Act - final boolean allowed = sut.isAllowed("Dirt"); - - // Assert - assertThat(allowed).isTrue(); - } - - @Test - void testEmptyAllowlistAllowsNone() { - // Arrange - sut.setMode(FilterMode.ALLOW); - - // Act - final boolean allowed = sut.isAllowed("Dirt"); - - // Assert - assertThat(allowed).isFalse(); - } - - @Test - void testAllowlist() { - // Arrange - sut.setMode(FilterMode.ALLOW); - sut.setTemplates(Set.of("Dirt", "Stone")); - - // Act - final boolean allowsDirt = sut.isAllowed("Dirt"); - final boolean allowsStone = sut.isAllowed("Stone"); - final boolean allowsSponge = sut.isAllowed("Sponge"); - - // Assert - assertThat(allowsDirt).isTrue(); - assertThat(allowsStone).isTrue(); - assertThat(allowsSponge).isFalse(); - } - - @Test - void testBlocklist() { - // Arrange - sut.setTemplates(Set.of("Dirt", "Stone")); - - // Act - final boolean allowsDirt = sut.isAllowed("Dirt"); - final boolean allowsStone = sut.isAllowed("Stone"); - final boolean allowsSponge = sut.isAllowed("Sponge"); - - // Assert - assertThat(allowsDirt).isFalse(); - assertThat(allowsStone).isFalse(); - assertThat(allowsSponge).isTrue(); - } - - @Test - void shouldBeAbleToModifyTemplates() { - // Arrange - sut.setTemplates(Set.of("Stone")); - - final boolean allowsDirt = sut.isAllowed("Dirt"); - final boolean allowsStone = sut.isAllowed("Stone"); - final boolean allowsSponge = sut.isAllowed("Sponge"); - - // Act - sut.setTemplates(Set.of("Dirt", "Sponge")); - - final boolean allowsDirtAfter = sut.isAllowed("Dirt"); - final boolean allowsStoneAfter = sut.isAllowed("Stone"); - final boolean allowsSpongeAfter = sut.isAllowed("Sponge"); - - // Assert - assertThat(allowsDirt).isTrue(); - assertThat(allowsStone).isFalse(); - assertThat(allowsSponge).isTrue(); - - assertThat(allowsDirtAfter).isFalse(); - assertThat(allowsStoneAfter).isTrue(); - assertThat(allowsSpongeAfter).isFalse(); - } - - @Test - void testAllowlistNormalizer() { - // Arrange - sut.setNormalizer(n -> { - if (n instanceof String str && !str.endsWith("!")) { - return str + "!"; - } - return n; - }); - sut.setMode(FilterMode.ALLOW); - sut.setTemplates(Set.of("A", "B")); - - // Act & assert - assertThat(sut.isAllowed("A")).isTrue(); - assertThat(sut.isAllowed("A!")).isTrue(); - assertThat(sut.isAllowed("B")).isTrue(); - assertThat(sut.isAllowed("B!")).isTrue(); - assertThat(sut.isAllowed("C")).isFalse(); - assertThat(sut.isAllowed("C!")).isFalse(); - } - - @Test - void testBlocklistNormalizer() { - // Arrange - sut.setNormalizer(n -> { - if (n instanceof String str && !str.endsWith("!")) { - return str + "!"; - } - return n; - }); - sut.setMode(FilterMode.BLOCK); - sut.setTemplates(Set.of("A", "B")); - - // Act & assert - assertThat(sut.isAllowed("A")).isFalse(); - assertThat(sut.isAllowed("A!")).isFalse(); - assertThat(sut.isAllowed("B")).isFalse(); - assertThat(sut.isAllowed("B!")).isFalse(); - assertThat(sut.isAllowed("C")).isTrue(); - assertThat(sut.isAllowed("C!")).isTrue(); - } -} diff --git a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/operations/GridOperations.java b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/operations/GridOperations.java index 0def0f376..6aa6abb48 100644 --- a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/operations/GridOperations.java +++ b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/operations/GridOperations.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage2.api.grid.operations; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.ExtractableStorage; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; @@ -7,11 +8,9 @@ /** * Grid operations, used for grids to interact with the storage network. - * - * @param the resource type */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") -public interface GridOperations { +public interface GridOperations { /** * Tries to move a resource from the network storage to the destination. * The amount being extracted depends on the extraction mode. @@ -20,7 +19,7 @@ public interface GridOperations { * @param extractMode the extract mode * @param destination the destination */ - boolean extract(T resource, GridExtractMode extractMode, InsertableStorage destination); + boolean extract(ResourceKey resource, GridExtractMode extractMode, InsertableStorage destination); /** * Tries to move a resource from the source to the network storage. @@ -30,5 +29,5 @@ public interface GridOperations { * @param insertMode the insertion mode * @param source the source */ - boolean insert(T resource, GridInsertMode insertMode, ExtractableStorage source); + boolean insert(ResourceKey resource, GridInsertMode insertMode, ExtractableStorage source); } diff --git a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/operations/GridOperationsImpl.java b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/operations/GridOperationsImpl.java index 77bb71bf3..bd4bd156e 100644 --- a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/operations/GridOperationsImpl.java +++ b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/operations/GridOperationsImpl.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.api.grid.operations; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.ExtractableStorage; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; @@ -12,10 +13,10 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") -public class GridOperationsImpl implements GridOperations { - private final StorageChannel storageChannel; +public class GridOperationsImpl implements GridOperations { + private final StorageChannel storageChannel; private final Actor actor; - private final ToLongFunction maxAmountProvider; + private final ToLongFunction maxAmountProvider; private final long singleAmount; /** @@ -25,9 +26,9 @@ public class GridOperationsImpl implements GridOperations { * @param singleAmount amount that needs to be extracted when using * {@link GridInsertMode#SINGLE_RESOURCE} or {@link GridExtractMode#SINGLE_RESOURCE} */ - public GridOperationsImpl(final StorageChannel storageChannel, + public GridOperationsImpl(final StorageChannel storageChannel, final Actor actor, - final ToLongFunction maxAmountProvider, + final ToLongFunction maxAmountProvider, final long singleAmount) { this.storageChannel = storageChannel; this.actor = actor; @@ -36,9 +37,9 @@ public GridOperationsImpl(final StorageChannel storageChannel, } @Override - public boolean extract(final T resource, + public boolean extract(final ResourceKey resource, final GridExtractMode extractMode, - final InsertableStorage destination) { + final InsertableStorage destination) { final long amount = getExtractableAmount(resource, extractMode); if (amount == 0) { return false; @@ -46,12 +47,12 @@ public boolean extract(final T resource, return TransferHelper.transfer(resource, amount, actor, storageChannel, destination, storageChannel) > 0; } - private long getExtractableAmount(final T resource, final GridExtractMode extractMode) { + private long getExtractableAmount(final ResourceKey resource, final GridExtractMode extractMode) { final long extractableAmount = getExtractableAmount(resource); return adjustExtractableAmountAccordingToExtractMode(extractMode, extractableAmount); } - private long getExtractableAmount(final T resource) { + private long getExtractableAmount(final ResourceKey resource) { final long totalSize = storageChannel.get(resource).map(ResourceAmount::getAmount).orElse(0L); final long maxAmount = maxAmountProvider.applyAsLong(resource); return Math.min(totalSize, maxAmount); @@ -67,7 +68,9 @@ private long adjustExtractableAmountAccordingToExtractMode(final GridExtractMode } @Override - public boolean insert(final T resource, final GridInsertMode insertMode, final ExtractableStorage source) { + public boolean insert(final ResourceKey resource, + final GridInsertMode insertMode, + final ExtractableStorage source) { final long amount = switch (insertMode) { case ENTIRE_RESOURCE -> maxAmountProvider.applyAsLong(resource); case SINGLE_RESOURCE -> singleAmount; diff --git a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/operations/NoopGridOperations.java b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/operations/NoopGridOperations.java index 8b090f3c2..55d2257bb 100644 --- a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/operations/NoopGridOperations.java +++ b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/operations/NoopGridOperations.java @@ -1,20 +1,21 @@ package com.refinedmods.refinedstorage2.api.grid.operations; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.ExtractableStorage; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; -public class NoopGridOperations implements GridOperations { +public class NoopGridOperations implements GridOperations { @Override - public boolean extract(final T resource, + public boolean extract(final ResourceKey resource, final GridExtractMode extractMode, - final InsertableStorage destination) { + final InsertableStorage destination) { return false; } @Override - public boolean insert(final T resource, + public boolean insert(final ResourceKey resource, final GridInsertMode insertMode, - final ExtractableStorage source) { + final ExtractableStorage source) { return false; } } diff --git a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridResourceFactory.java b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridResourceFactory.java index 02dad0f83..9827d0e94 100644 --- a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridResourceFactory.java +++ b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridResourceFactory.java @@ -9,5 +9,5 @@ @FunctionalInterface @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.6") public interface GridResourceFactory { - Optional apply(ResourceAmount resourceAmount); + Optional apply(ResourceAmount resourceAmount); } diff --git a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridView.java b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridView.java index f2bd0074d..d8e5f3c10 100644 --- a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridView.java +++ b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridView.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage2.api.grid.view; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; @@ -58,11 +59,10 @@ public interface GridView { void setSortingDirection(GridSortingDirection sortingDirection); /** - * @param the resource type * @param resource the resource * @return the tracked resource, if present */ - Optional getTrackedResource(T resource); + Optional getTrackedResource(ResourceKey resource); /** * Sorts the view list. @@ -74,12 +74,11 @@ public interface GridView { * Applies a change to a resource. Will update the backing list, and will also update the view list (depending * if the view is preventing sorting). * - * @param the resource type * @param resource the resource * @param amount the amount, can be negative or positive * @param trackedResource the tracked resource, can be null */ - void onChange(T resource, long amount, @Nullable TrackedResource trackedResource); + void onChange(ResourceKey resource, long amount, @Nullable TrackedResource trackedResource); /** * @return the view list @@ -89,7 +88,7 @@ public interface GridView { /** * @return a copy of the backing list */ - ResourceList copyBackingList(); + ResourceList copyBackingList(); /** * Clears the backing list, view list and tracked resources index. diff --git a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridViewBuilder.java b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridViewBuilder.java index 8f82db67e..056234a13 100644 --- a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridViewBuilder.java +++ b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridViewBuilder.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage2.api.grid.view; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import javax.annotation.Nullable; @@ -14,13 +15,12 @@ public interface GridViewBuilder { /** * Adds a resource in the backing and view list. * - * @param the resource type * @param resource the resource * @param amount the amount * @param trackedResource the tracked resource, can be null * @return this builder */ - GridViewBuilder withResource(T resource, long amount, @Nullable TrackedResource trackedResource); + GridViewBuilder withResource(ResourceKey resource, long amount, @Nullable TrackedResource trackedResource); /** * @return a {@link GridView} with the specified resources diff --git a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridViewBuilderImpl.java b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridViewBuilderImpl.java index bd7269e51..3ee9bd1e1 100644 --- a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridViewBuilderImpl.java +++ b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridViewBuilderImpl.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage2.api.grid.view; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; import com.refinedmods.refinedstorage2.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; @@ -13,8 +14,8 @@ @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.4") public class GridViewBuilderImpl implements GridViewBuilder { private final GridResourceFactory resourceFactory; - private final ResourceList backingList = new ResourceListImpl<>(); - private final Map trackedResources = new HashMap<>(); + private final ResourceList backingList = new ResourceListImpl(); + private final Map trackedResources = new HashMap<>(); private final GridSortingType identitySortingType; private final GridSortingType defaultSortingType; @@ -27,9 +28,9 @@ public GridViewBuilderImpl(final GridResourceFactory resourceFactory, } @Override - public GridViewBuilder withResource(final T resource, - final long amount, - @Nullable final TrackedResource trackedResource) { + public GridViewBuilder withResource(final ResourceKey resource, + final long amount, + @Nullable final TrackedResource trackedResource) { backingList.add(resource, amount); trackedResources.put(resource, trackedResource); return this; diff --git a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridViewImpl.java b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridViewImpl.java index 1565f62b8..a331cfd68 100644 --- a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridViewImpl.java +++ b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridViewImpl.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage2.api.core.CoreValidations; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; import com.refinedmods.refinedstorage2.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage2.api.resource.list.ResourceListOperationResult; @@ -25,13 +26,13 @@ public class GridViewImpl implements GridView { private static final Logger LOGGER = LoggerFactory.getLogger(GridViewImpl.class); - private final ResourceList backingList; + private final ResourceList backingList; private final Comparator identitySort; private final GridResourceFactory resourceFactory; - private final Map trackedResources = new HashMap<>(); + private final Map trackedResources = new HashMap<>(); private List viewList = new ArrayList<>(); - private final Map viewListIndex = new HashMap<>(); + private final Map viewListIndex = new HashMap<>(); private GridSortingType sortingType; private GridSortingDirection sortingDirection = GridSortingDirection.ASCENDING; @@ -48,8 +49,8 @@ public class GridViewImpl implements GridView { * @param defaultSortingType the default sorting type */ public GridViewImpl(final GridResourceFactory resourceFactory, - final ResourceList backingList, - final Map initialTrackedResources, + final ResourceList backingList, + final Map initialTrackedResources, final GridSortingType identitySortingType, final GridSortingType defaultSortingType) { this.resourceFactory = resourceFactory; @@ -90,7 +91,7 @@ public void setSortingDirection(final GridSortingDirection sortingDirection) { } @Override - public Optional getTrackedResource(final T resource) { + public Optional getTrackedResource(final ResourceKey resource) { return Optional.ofNullable(trackedResources.get(resource)); } @@ -101,7 +102,7 @@ public void sort() { viewListIndex.clear(); final List newViewList = new ArrayList<>(); - for (final ResourceAmount backingListItem : backingList.getAll()) { + for (final ResourceAmount backingListItem : backingList.getAll()) { resourceFactory.apply(backingListItem).ifPresent(gridResource -> { if (filter.test(gridResource)) { newViewList.add(gridResource); @@ -116,8 +117,10 @@ public void sort() { } @Override - public void onChange(final T resource, final long amount, @Nullable final TrackedResource trackedResource) { - final ResourceListOperationResult operationResult = updateBackingList(resource, amount); + public void onChange(final ResourceKey resource, + final long amount, + @Nullable final TrackedResource trackedResource) { + final ResourceListOperationResult operationResult = updateBackingList(resource, amount); updateOrRemoveTrackedResource(resource, trackedResource); @@ -135,7 +138,7 @@ public void onChange(final T resource, final long amount, @Nullable final Tr } } - private ResourceListOperationResult updateBackingList(final T resource, final long amount) { + private ResourceListOperationResult updateBackingList(final ResourceKey resource, final long amount) { if (amount < 0) { return backingList.remove(resource, Math.abs(amount)).orElseThrow(RuntimeException::new); } else { @@ -143,7 +146,8 @@ private ResourceListOperationResult updateBackingList(final T resource, f } } - private void updateOrRemoveTrackedResource(final T resource, @Nullable final TrackedResource trackedResource) { + private void updateOrRemoveTrackedResource(final ResourceKey resource, + @Nullable final TrackedResource trackedResource) { if (trackedResource == null) { trackedResources.remove(resource); } else { @@ -151,9 +155,9 @@ private void updateOrRemoveTrackedResource(final T resource, @Nullable final } } - private void reinsertZeroedResourceIntoViewList(final T resource, - final ResourceListOperationResult operationResult, - final GridResource oldGridResource) { + private void reinsertZeroedResourceIntoViewList(final ResourceKey resource, + final ResourceListOperationResult operationResult, + final GridResource oldGridResource) { LOGGER.debug("{} was zeroed, unzeroing", resource); final GridResource newResource = resourceFactory.apply(operationResult.resourceAmount()).orElseThrow(); viewListIndex.put(resource, newResource); @@ -164,9 +168,9 @@ private void reinsertZeroedResourceIntoViewList(final T resource, viewList.set(index, newResource); } - private void handleChangeForExistingResource(final T resource, - final ResourceListOperationResult operationResult, - final GridResource gridResource) { + private void handleChangeForExistingResource(final ResourceKey resource, + final ResourceListOperationResult operationResult, + final GridResource gridResource) { final boolean noLongerAvailable = !operationResult.available(); final boolean canBeSorted = !preventSorting; if (canBeSorted) { @@ -180,9 +184,9 @@ private void handleChangeForExistingResource(final T resource, } } - private void updateExistingResourceInViewList(final T resource, - final GridResource gridResource, - final boolean noLongerAvailable) { + private void updateExistingResourceInViewList(final ResourceKey resource, + final GridResource gridResource, + final boolean noLongerAvailable) { viewList.remove(gridResource); if (noLongerAvailable) { viewListIndex.remove(resource); @@ -193,8 +197,8 @@ private void updateExistingResourceInViewList(final T resource, } } - private void handleChangeForNewResource(final T resource, - final ResourceListOperationResult operationResult) { + private void handleChangeForNewResource(final ResourceKey resource, + final ResourceListOperationResult operationResult) { final GridResource gridResource = resourceFactory.apply(operationResult.resourceAmount()).orElseThrow(); if (filter.test(gridResource)) { LOGGER.debug("Filter allowed, actually adding {}", resource); @@ -245,8 +249,8 @@ public List getViewList() { } @Override - public ResourceList copyBackingList() { - final ResourceList copy = new ResourceListImpl<>(); + public ResourceList copyBackingList() { + final ResourceList copy = new ResourceListImpl(); backingList.getAll().forEach(copy::add); return copy; } diff --git a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridStorageChannelProvider.java b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridStorageChannelProvider.java deleted file mode 100644 index c4e7b6fa0..000000000 --- a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridStorageChannelProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.refinedmods.refinedstorage2.api.grid.watcher; - -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; - -import java.util.Set; - -import org.apiguardian.api.API; - -/** - * Provides the {@link GridWatcherManagerImpl} with {@link StorageChannel}s. - */ -@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.3") -public interface GridStorageChannelProvider { - Set> getStorageChannelTypes(); - - StorageChannel getStorageChannel(StorageChannelType type); -} diff --git a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcher.java b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcher.java index f762f0aab..1b070f92b 100644 --- a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcher.java +++ b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcher.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.api.grid.watcher; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import javax.annotation.Nullable; @@ -22,18 +22,11 @@ public interface GridWatcher { /** * Called when a resource is changed. * - * @param the resource type - * @param storageChannelType the relevant storage channel type - * @param resource the resource - * @param change the changed amount - * @param trackedResource the tracked resource, if present + * @param resource the resource + * @param change the changed amount + * @param trackedResource the tracked resource, if present */ - void onChanged( - StorageChannelType storageChannelType, - T resource, - long change, - @Nullable TrackedResource trackedResource - ); + void onChanged(ResourceKey resource, long change, @Nullable TrackedResource trackedResource); /** * Usually called when the grid network has been changed. diff --git a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcherManager.java b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcherManager.java index 2e2055c62..02fe5aca5 100644 --- a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcherManager.java +++ b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcherManager.java @@ -1,6 +1,9 @@ package com.refinedmods.refinedstorage2.api.grid.watcher; import com.refinedmods.refinedstorage2.api.storage.Actor; +import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; + +import javax.annotation.Nullable; import org.apiguardian.api.API; @@ -10,17 +13,15 @@ */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.3.3") public interface GridWatcherManager { - void addWatcher( - GridWatcher watcher, - Class actorType, - GridStorageChannelProvider storageChannelProvider - ); + void addWatcher(GridWatcher watcher, + Class actorType, + @Nullable StorageChannel storageChannel); - void attachAll(GridStorageChannelProvider storageChannelProvider); + void attachAll(@Nullable StorageChannel storageChannel); - void removeWatcher(GridWatcher watcher, GridStorageChannelProvider storageChannelProvider); + void removeWatcher(GridWatcher watcher, @Nullable StorageChannel storageChannel); - void detachAll(GridStorageChannelProvider storageChannelProvider); + void detachAll(StorageChannel storageChannel); void activeChanged(boolean active); } diff --git a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcherManagerImpl.java b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcherManagerImpl.java index 2a7f2dfbb..c86437cab 100644 --- a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcherManagerImpl.java +++ b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcherManagerImpl.java @@ -1,10 +1,11 @@ package com.refinedmods.refinedstorage2.api.grid.watcher; import com.refinedmods.refinedstorage2.api.storage.Actor; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; +import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import java.util.HashMap; import java.util.Map; +import javax.annotation.Nullable; import org.apiguardian.api.API; import org.slf4j.Logger; @@ -20,19 +21,21 @@ public class GridWatcherManagerImpl implements GridWatcherManager { public void addWatcher( final GridWatcher watcher, final Class actorType, - final GridStorageChannelProvider storageChannelProvider + @Nullable final StorageChannel storageChannel ) { if (watchers.containsKey(watcher)) { throw new IllegalArgumentException("Watcher is already registered"); } final GridWatcherRegistration registration = new GridWatcherRegistration(watcher, actorType); - attachAll(registration, storageChannelProvider, false); + if (storageChannel != null) { + attach(registration, storageChannel, false); + } watchers.put(watcher, registration); LOGGER.info("Added watcher {}, new count is {}", watcher, watchers.size()); } @Override - public void attachAll(final GridStorageChannelProvider storageChannelProvider) { + public void attachAll(@Nullable final StorageChannel storageChannel) { // If we get here we are affected by a network split or network merge. // At this point, all the storages that are affected by the split or merge have not yet been processed // as the grid has the highest priority. @@ -40,67 +43,46 @@ public void attachAll(final GridStorageChannelProvider storageChannelProvider) { // Invalidate all watcher data, the resources that were synced earlier are no longer valid because we have // a brand-new network. watcher.invalidate(); - // Re-attach the watcher to the new network, and send all the resources from the new network. - // Resources from the old network are not part of the new network yet, as mentioned above, - // but those will be synced when the storages are re-added. - attachAll(registration, storageChannelProvider, true); + if (storageChannel != null) { + // Re-attach the watcher to the new network, and send all the resources from the new network. + // Resources from the old network are not part of the new network yet, as mentioned above, + // but those will be synced when the storages are re-added. + attach(registration, storageChannel, true); + } }); } - private void attachAll(final GridWatcherRegistration registration, - final GridStorageChannelProvider storageChannelProvider, - final boolean replay) { - storageChannelProvider.getStorageChannelTypes().forEach(storageChannelType -> attach( - registration, - storageChannelType, - storageChannelProvider, - replay - )); - } - - private void attach( + private void attach( final GridWatcherRegistration registration, - final StorageChannelType storageChannelType, - final GridStorageChannelProvider storageChannelProvider, + final StorageChannel storageChannel, final boolean replay ) { - LOGGER.info("Attaching {} to {}", registration, storageChannelType); - registration.attach(storageChannelProvider.getStorageChannel(storageChannelType), storageChannelType, replay); + LOGGER.info("Attaching {} to {}", registration, storageChannel); + registration.attach(storageChannel, replay); } @Override - public void removeWatcher(final GridWatcher watcher, final GridStorageChannelProvider storageChannelProvider) { + public void removeWatcher(final GridWatcher watcher, @Nullable final StorageChannel storageChannel) { final GridWatcherRegistration registration = watchers.get(watcher); if (registration == null) { throw new IllegalArgumentException("Watcher is not registered"); } - detachAll(registration, storageChannelProvider); + if (storageChannel != null) { + detach(registration, storageChannel); + } watchers.remove(watcher); LOGGER.info("Removed watcher {}, remaining {}", watcher, watchers.size()); } @Override - public void detachAll(final GridStorageChannelProvider storageChannelProvider) { + public void detachAll(final StorageChannel storageChannel) { LOGGER.info("Detaching {} watchers", watchers.size()); - watchers.values().forEach(w -> detachAll(w, storageChannelProvider)); + watchers.values().forEach(watcher -> detach(watcher, storageChannel)); } - private void detachAll(final GridWatcherRegistration registration, - final GridStorageChannelProvider storageChannelProvider) { - storageChannelProvider.getStorageChannelTypes().forEach(storageChannelType -> detach( - registration, - storageChannelType, - storageChannelProvider - )); - } - - private void detach( - final GridWatcherRegistration registration, - final StorageChannelType storageChannelType, - final GridStorageChannelProvider storageChannelProvider - ) { - LOGGER.info("Detaching {} from {}", registration, storageChannelType); - registration.detach(storageChannelProvider.getStorageChannel(storageChannelType), storageChannelType); + private void detach(final GridWatcherRegistration registration, final StorageChannel storageChannel) { + LOGGER.info("Detaching {} from {}", registration, storageChannel); + registration.detach(storageChannel); } @Override diff --git a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcherRegistration.java b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcherRegistration.java index d3d71e50c..a7a54ef0e 100644 --- a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcherRegistration.java +++ b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcherRegistration.java @@ -3,26 +3,22 @@ import com.refinedmods.refinedstorage2.api.resource.list.listenable.ResourceListListener; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; -import java.util.HashMap; -import java.util.Map; +import javax.annotation.Nullable; class GridWatcherRegistration { private final GridWatcher watcher; private final Class actorType; - private final Map, ResourceListListener> listeners = new HashMap<>(); + @Nullable + private ResourceListListener listener; GridWatcherRegistration(final GridWatcher watcher, final Class actorType) { this.watcher = watcher; this.actorType = actorType; } - void attach(final StorageChannel storageChannel, - final StorageChannelType storageChannelType, - final boolean replay) { - final ResourceListListener listener = change -> watcher.onChanged( - storageChannelType, + void attach(final StorageChannel storageChannel, final boolean replay) { + this.listener = change -> watcher.onChanged( change.resourceAmount().getResource(), change.change(), storageChannel.findTrackedResourceByActorType( @@ -31,10 +27,8 @@ void attach(final StorageChannel storageChannel, ).orElse(null) ); storageChannel.addListener(listener); - listeners.put(storageChannelType, listener); if (replay) { storageChannel.getAll().forEach(resourceAmount -> watcher.onChanged( - storageChannelType, resourceAmount.getResource(), resourceAmount.getAmount(), storageChannel.findTrackedResourceByActorType( @@ -45,10 +39,11 @@ void attach(final StorageChannel storageChannel, } } - @SuppressWarnings("unchecked") - void detach(final StorageChannel storageChannel, final StorageChannelType storageChannelType) { - final ResourceListListener listener = (ResourceListListener) listeners.get(storageChannelType); + void detach(final StorageChannel storageChannel) { + if (listener == null) { + return; + } storageChannel.removeListener(listener); - listeners.remove(storageChannelType); + listener = null; } } diff --git a/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/TestResource.java b/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/TestResource.java new file mode 100644 index 000000000..1843f394f --- /dev/null +++ b/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/TestResource.java @@ -0,0 +1,10 @@ +package com.refinedmods.refinedstorage2.api.grid; + +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; + +public enum TestResource implements ResourceKey { + A, + B, + C, + D +} diff --git a/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/query/GridQueryParserImplTest.java b/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/query/GridQueryParserImplTest.java index 7ba867ffa..2951c16e4 100644 --- a/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/query/GridQueryParserImplTest.java +++ b/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/query/GridQueryParserImplTest.java @@ -2,10 +2,14 @@ import com.refinedmods.refinedstorage2.api.grid.view.FakeGridResourceAttributeKeys; import com.refinedmods.refinedstorage2.api.grid.view.GridResource; -import com.refinedmods.refinedstorage2.api.grid.view.GridResourceImpl; +import com.refinedmods.refinedstorage2.api.grid.view.GridResourceAttributeKey; +import com.refinedmods.refinedstorage2.api.grid.view.GridView; +import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import com.refinedmods.refinedstorage2.query.lexer.LexerTokenMappings; import com.refinedmods.refinedstorage2.query.parser.ParserOperatorMappings; +import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.function.Predicate; @@ -31,8 +35,8 @@ void testEmptyQuery(final String query) throws GridQueryParserException { final Predicate predicate = queryParser.parse(query); // Assert - assertThat(predicate.test(new GridResourceImpl("Dirt"))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Glass"))).isTrue(); + assertThat(predicate.test(new R("Dirt"))).isTrue(); + assertThat(predicate.test(new R("Glass"))).isTrue(); } @ParameterizedTest @@ -42,8 +46,8 @@ void testNameQuery(final String query) throws GridQueryParserException { final Predicate predicate = queryParser.parse(query); // Assert - assertThat(predicate.test(new GridResourceImpl("Dirt"))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Glass"))).isFalse(); + assertThat(predicate.test(new R("Dirt"))).isTrue(); + assertThat(predicate.test(new R("Glass"))).isFalse(); } @ParameterizedTest @@ -53,8 +57,8 @@ void testModQuery(final String query) throws GridQueryParserException { final Predicate predicate = queryParser.parse(query); // Assert - assertThat(predicate.test(new GridResourceImpl("Sponge", 1, "rs", "Refined Storage", Set.of()))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Glass"))).isFalse(); + assertThat(predicate.test(new R("Sponge", 1, "rs", "Refined Storage", Set.of()))).isTrue(); + assertThat(predicate.test(new R("Glass"))).isFalse(); } @ParameterizedTest @@ -65,8 +69,8 @@ void testTagQuery(final String query) throws GridQueryParserException { // Assert assertThat(predicate.test( - new GridResourceImpl("Sponge", 1, "mc", "Minecraft", Set.of("underwater", "unrelated")))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Dirt", 1, "mc", "Minecraft", Set.of("transparent")))).isFalse(); + new R("Sponge", 1, "mc", "Minecraft", Set.of("underwater", "unrelated")))).isTrue(); + assertThat(predicate.test(new R("Dirt", 1, "mc", "Minecraft", Set.of("transparent")))).isFalse(); } @Test @@ -85,8 +89,8 @@ void testImplicitAndQuery() throws GridQueryParserException { final Predicate predicate = queryParser.parse("DirT di RT"); // Assert - assertThat(predicate.test(new GridResourceImpl("Dirt"))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Glass"))).isFalse(); + assertThat(predicate.test(new R("Dirt"))).isTrue(); + assertThat(predicate.test(new R("Glass"))).isFalse(); } @Test @@ -95,9 +99,9 @@ void testImplicitAndQueryInParenthesis() throws GridQueryParserException { final Predicate predicate = queryParser.parse("(DirT di RT) || (sto stone)"); // Assert - assertThat(predicate.test(new GridResourceImpl("Dirt"))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Glass"))).isFalse(); - assertThat(predicate.test(new GridResourceImpl("Stone"))).isTrue(); + assertThat(predicate.test(new R("Dirt"))).isTrue(); + assertThat(predicate.test(new R("Glass"))).isFalse(); + assertThat(predicate.test(new R("Stone"))).isTrue(); } @Test @@ -106,10 +110,10 @@ void testImplicitAndQueryWithUnaryOperator() throws GridQueryParserException { final Predicate predicate = queryParser.parse("@minecraft >5"); // Assert - assertThat(predicate.test(new GridResourceImpl("Dirt", 6, "minecraft", "Minecraft", Set.of()))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Glass", 5, "minecraft", "Minecraft", Set.of()))).isFalse(); - assertThat(predicate.test(new GridResourceImpl("Sponge", 5, "rs", "Refined Storage", Set.of()))).isFalse(); - assertThat(predicate.test(new GridResourceImpl("Cobblestone", 6, "rs", "Refined Storage", Set.of()))).isFalse(); + assertThat(predicate.test(new R("Dirt", 6, "minecraft", "Minecraft", Set.of()))).isTrue(); + assertThat(predicate.test(new R("Glass", 5, "minecraft", "Minecraft", Set.of()))).isFalse(); + assertThat(predicate.test(new R("Sponge", 5, "rs", "Refined Storage", Set.of()))).isFalse(); + assertThat(predicate.test(new R("Cobblestone", 6, "rs", "Refined Storage", Set.of()))).isFalse(); } @Test @@ -118,8 +122,8 @@ void testAndQuery() throws GridQueryParserException { final Predicate predicate = queryParser.parse("DirT && di && RT"); // Assert - assertThat(predicate.test(new GridResourceImpl("Dirt"))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Glass"))).isFalse(); + assertThat(predicate.test(new R("Dirt"))).isTrue(); + assertThat(predicate.test(new R("Glass"))).isFalse(); } @Test @@ -128,13 +132,13 @@ void testOrQuery() throws GridQueryParserException { final Predicate predicate = queryParser.parse("dir || glass || StoNe"); // Assert - assertThat(predicate.test(new GridResourceImpl("Dirt"))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Glass"))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Stone"))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Cobblestone"))).isTrue(); + assertThat(predicate.test(new R("Dirt"))).isTrue(); + assertThat(predicate.test(new R("Glass"))).isTrue(); + assertThat(predicate.test(new R("Stone"))).isTrue(); + assertThat(predicate.test(new R("Cobblestone"))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Sponge"))).isFalse(); - assertThat(predicate.test(new GridResourceImpl("Furnace"))).isFalse(); + assertThat(predicate.test(new R("Sponge"))).isFalse(); + assertThat(predicate.test(new R("Furnace"))).isFalse(); } @Test @@ -143,11 +147,11 @@ void testSimpleNotQuery() throws GridQueryParserException { final Predicate predicate = queryParser.parse("!stone"); // Assert - assertThat(predicate.test(new GridResourceImpl("Dirt"))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Glass"))).isTrue(); + assertThat(predicate.test(new R("Dirt"))).isTrue(); + assertThat(predicate.test(new R("Glass"))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Stone"))).isFalse(); - assertThat(predicate.test(new GridResourceImpl("Cobblestone"))).isFalse(); + assertThat(predicate.test(new R("Stone"))).isFalse(); + assertThat(predicate.test(new R("Cobblestone"))).isFalse(); } @Test @@ -156,11 +160,11 @@ void testNotQueryWithMultipleOrParts() throws GridQueryParserException { final Predicate predicate = queryParser.parse("!(stone || dirt)"); // Assert - assertThat(predicate.test(new GridResourceImpl("Sponge"))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Glass"))).isTrue(); + assertThat(predicate.test(new R("Sponge"))).isTrue(); + assertThat(predicate.test(new R("Glass"))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Stone"))).isFalse(); - assertThat(predicate.test(new GridResourceImpl("Dirt"))).isFalse(); + assertThat(predicate.test(new R("Stone"))).isFalse(); + assertThat(predicate.test(new R("Dirt"))).isFalse(); } @Test @@ -171,12 +175,12 @@ void testComplexModQuery() throws GridQueryParserException { ); // Assert - assertThat(predicate.test(new GridResourceImpl("Sponge", 1, "rs", "Refined Storage", Set.of()))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Bucket", 1, "rs", "Refined Storage", Set.of()))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Saddle", 1, "rs", "Refined Storage", Set.of()))).isFalse(); + assertThat(predicate.test(new R("Sponge", 1, "rs", "Refined Storage", Set.of()))).isTrue(); + assertThat(predicate.test(new R("Bucket", 1, "rs", "Refined Storage", Set.of()))).isTrue(); + assertThat(predicate.test(new R("Saddle", 1, "rs", "Refined Storage", Set.of()))).isFalse(); - assertThat(predicate.test(new GridResourceImpl("Glass", 1, "mc", "Minecraft", Set.of()))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Furnace", 1, "mc", "Minecraft", Set.of()))).isFalse(); + assertThat(predicate.test(new R("Glass", 1, "mc", "Minecraft", Set.of()))).isTrue(); + assertThat(predicate.test(new R("Furnace", 1, "mc", "Minecraft", Set.of()))).isFalse(); } @Test @@ -185,8 +189,8 @@ void testLessThanUnaryCountQuery() throws GridQueryParserException { final Predicate predicate = queryParser.parse("<5"); // Assert - assertThat(predicate.test(new GridResourceImpl("Glass", 5))).isFalse(); - assertThat(predicate.test(new GridResourceImpl("Glass", 4))).isTrue(); + assertThat(predicate.test(new R("Glass", 5))).isFalse(); + assertThat(predicate.test(new R("Glass", 4))).isTrue(); } @Test @@ -195,9 +199,9 @@ void testLessThanEqualsUnaryCountQuery() throws GridQueryParserException { final Predicate predicate = queryParser.parse("<=5"); // Assert - assertThat(predicate.test(new GridResourceImpl("Glass", 6))).isFalse(); - assertThat(predicate.test(new GridResourceImpl("Glass", 5))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Glass", 4))).isTrue(); + assertThat(predicate.test(new R("Glass", 6))).isFalse(); + assertThat(predicate.test(new R("Glass", 5))).isTrue(); + assertThat(predicate.test(new R("Glass", 4))).isTrue(); } @Test @@ -206,8 +210,8 @@ void testGreaterThanUnaryCountQuery() throws GridQueryParserException { final Predicate predicate = queryParser.parse(">5"); // Assert - assertThat(predicate.test(new GridResourceImpl("Glass", 5))).isFalse(); - assertThat(predicate.test(new GridResourceImpl("Glass", 6))).isTrue(); + assertThat(predicate.test(new R("Glass", 5))).isFalse(); + assertThat(predicate.test(new R("Glass", 6))).isTrue(); } @Test @@ -216,9 +220,9 @@ void testGreaterThanEqualsUnaryCountQuery() throws GridQueryParserException { final Predicate predicate = queryParser.parse(">=5"); // Assert - assertThat(predicate.test(new GridResourceImpl("Glass", 4))).isFalse(); - assertThat(predicate.test(new GridResourceImpl("Glass", 5))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Glass", 6))).isTrue(); + assertThat(predicate.test(new R("Glass", 4))).isFalse(); + assertThat(predicate.test(new R("Glass", 5))).isTrue(); + assertThat(predicate.test(new R("Glass", 6))).isTrue(); } @Test @@ -227,9 +231,9 @@ void testEqualsUnaryCountQuery() throws GridQueryParserException { final Predicate predicate = queryParser.parse("=5"); // Assert - assertThat(predicate.test(new GridResourceImpl("Glass", 4))).isFalse(); - assertThat(predicate.test(new GridResourceImpl("Glass", 5))).isTrue(); - assertThat(predicate.test(new GridResourceImpl("Glass", 6))).isFalse(); + assertThat(predicate.test(new R("Glass", 4))).isFalse(); + assertThat(predicate.test(new R("Glass", 5))).isTrue(); + assertThat(predicate.test(new R("Glass", 6))).isFalse(); } @ParameterizedTest @@ -253,4 +257,66 @@ void testInvalidTokenInUnaryCountQuery(final String operator) { // Assert assertThat(e.getMessage()).isEqualTo("Count filtering expects an integer number"); } + + private static class R implements GridResource { + private final String name; + private final long amount; + private final Map> attributes; + + R(final String name) { + this(name, 1); + } + + R(final String name, final long amount) { + this.name = name; + this.amount = amount; + this.attributes = Map.of(); + } + + R( + final String name, + final long amount, + final String modId, + final String modName, + final Set tags + ) { + this.name = name; + this.amount = amount; + this.attributes = Map.of( + FakeGridResourceAttributeKeys.MOD_ID, Set.of(modId), + FakeGridResourceAttributeKeys.MOD_NAME, Set.of(modName), + FakeGridResourceAttributeKeys.TAGS, tags + ); + } + + @Override + public Optional getTrackedResource(final GridView view) { + return Optional.empty(); + } + + @Override + public long getAmount() { + return amount; + } + + @Override + public String getName() { + return name; + } + + @Override + public Set getAttribute(final GridResourceAttributeKey key) { + return attributes.getOrDefault(key, Set.of()); + } + + @Override + public boolean isZeroed() { + return false; + } + + @Override + public void setZeroed(final boolean zeroed) { + throw new UnsupportedOperationException(); + } + } } diff --git a/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/service/GridOperationsImplTest.java b/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/service/GridOperationsImplTest.java index 9bf3e05e0..fb8a08f09 100644 --- a/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/service/GridOperationsImplTest.java +++ b/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/service/GridOperationsImplTest.java @@ -5,6 +5,7 @@ import com.refinedmods.refinedstorage2.api.grid.operations.GridInsertMode; import com.refinedmods.refinedstorage2.api.grid.operations.GridOperationsImpl; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; import com.refinedmods.refinedstorage2.api.storage.Storage; @@ -20,18 +21,20 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import static com.refinedmods.refinedstorage2.api.grid.TestResource.A; +import static com.refinedmods.refinedstorage2.api.grid.TestResource.B; import static org.assertj.core.api.Assertions.assertThat; class GridOperationsImplTest { private static final long MAX_COUNT = 15; - private StorageChannel storageChannel; - private GridOperationsImpl sut; + private StorageChannel storageChannel; + private GridOperationsImpl sut; @BeforeEach void setUp() { - storageChannel = new StorageChannelImpl<>(); - sut = new GridOperationsImpl<>(storageChannel, GridActor.INSTANCE, r -> MAX_COUNT, 1); + storageChannel = new StorageChannelImpl(); + sut = new GridOperationsImpl(storageChannel, GridActor.INSTANCE, r -> MAX_COUNT, 1); } @Nested @@ -40,14 +43,14 @@ class InsertTest { @EnumSource(GridInsertMode.class) void shouldInsertIntoDestination(final GridInsertMode insertMode) { // Arrange - final Storage source = new LimitedStorageImpl<>(100); - source.insert("A", MAX_COUNT * 3, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage source = new LimitedStorageImpl(100); + source.insert(A, MAX_COUNT * 3, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new TrackedStorageImpl<>(new LimitedStorageImpl<>(100), () -> 0L); + final Storage destination = new TrackedStorageImpl(new LimitedStorageImpl(100), () -> 0L); storageChannel.addSource(destination); // Act - final boolean success = sut.insert("A", insertMode, source); + final boolean success = sut.insert(A, insertMode, source); // Assert assertThat(success).isTrue(); @@ -58,12 +61,12 @@ void shouldInsertIntoDestination(final GridInsertMode insertMode) { }; assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", expectedAmount) + new ResourceAmount(A, expectedAmount) ); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", (MAX_COUNT * 3) - expectedAmount) + new ResourceAmount(A, (MAX_COUNT * 3) - expectedAmount) ); - assertThat(storageChannel.findTrackedResourceByActorType("A", GridActor.class)) + assertThat(storageChannel.findTrackedResourceByActorType(A, GridActor.class)) .get() .usingRecursiveComparison() .isEqualTo(new TrackedResource(GridActor.NAME, 0)); @@ -73,44 +76,44 @@ void shouldInsertIntoDestination(final GridInsertMode insertMode) { @EnumSource(GridInsertMode.class) void shouldNotInsertIntoDestinationWhenResourceIsNotPresentInSource(final GridInsertMode insertMode) { // Arrange - final Storage source = new LimitedStorageImpl<>(100); + final Storage source = new LimitedStorageImpl(100); - final Storage destination = new TrackedStorageImpl<>(new LimitedStorageImpl<>(100), () -> 0L); + final Storage destination = new TrackedStorageImpl(new LimitedStorageImpl(100), () -> 0L); storageChannel.addSource(destination); // Act - final boolean success = sut.insert("A", insertMode, source); + final boolean success = sut.insert(A, insertMode, source); // Assert assertThat(success).isFalse(); assertThat(storageChannel.getAll()).isEmpty(); assertThat(source.getAll()).isEmpty(); - assertThat(storageChannel.findTrackedResourceByActorType("A", GridActor.class)).isEmpty(); + assertThat(storageChannel.findTrackedResourceByActorType(A, GridActor.class)).isEmpty(); } @ParameterizedTest @EnumSource(GridInsertMode.class) void shouldNotInsertIntoDestinationWhenNoSpaceIsPresentInDestination(final GridInsertMode insertMode) { // Arrange - final Storage source = new LimitedStorageImpl<>(100); - source.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage source = new LimitedStorageImpl(100); + source.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new TrackedStorageImpl<>(new LimitedStorageImpl<>(100), () -> 0L); + final Storage destination = new TrackedStorageImpl(new LimitedStorageImpl(100), () -> 0L); storageChannel.addSource(destination); - storageChannel.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final boolean success = sut.insert("A", insertMode, source); + final boolean success = sut.insert(A, insertMode, source); // Assert assertThat(success).isFalse(); assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100) + new ResourceAmount(A, 100) ); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100) + new ResourceAmount(A, 100) ); - assertThat(storageChannel.findTrackedResourceByActorType("A", GridActor.class)).isEmpty(); + assertThat(storageChannel.findTrackedResourceByActorType(A, GridActor.class)).isEmpty(); } } @@ -119,25 +122,25 @@ class InsertEntireResourceTest { @Test void shouldInsertIntoDestinationWithRemainder() { // Arrange - final Storage source = new LimitedStorageImpl<>(100); - source.insert("A", MAX_COUNT, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage source = new LimitedStorageImpl(100); + source.insert(A, MAX_COUNT, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new TrackedStorageImpl<>(new LimitedStorageImpl<>(100), () -> 0L); + final Storage destination = new TrackedStorageImpl(new LimitedStorageImpl(100), () -> 0L); storageChannel.addSource(destination); - storageChannel.insert("A", 100 - MAX_COUNT + 1, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(A, 100 - MAX_COUNT + 1, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final boolean success = sut.insert("A", GridInsertMode.ENTIRE_RESOURCE, source); + final boolean success = sut.insert(A, GridInsertMode.ENTIRE_RESOURCE, source); // Assert assertThat(success).isTrue(); assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100) + new ResourceAmount(A, 100) ); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 1) + new ResourceAmount(A, 1) ); - assertThat(storageChannel.findTrackedResourceByActorType("A", GridActor.class)) + assertThat(storageChannel.findTrackedResourceByActorType(A, GridActor.class)) .get() .usingRecursiveComparison() .isEqualTo(new TrackedResource(GridActor.NAME, 0)); @@ -152,9 +155,9 @@ void shouldInsertWhenLessIsRequestedFromSourceBecauseDestinationIsAlmostFull() { // This is why we override extract to block extraction of non-entire buckets. // Arrange - final Storage source = new LimitedStorageImpl<>(100) { + final Storage source = new LimitedStorageImpl(100) { @Override - public long extract(final String resource, + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor source) { @@ -164,24 +167,24 @@ public long extract(final String resource, return super.extract(resource, amount, action, source); } }; - source.insert("A", MAX_COUNT, Action.EXECUTE, EmptyActor.INSTANCE); + source.insert(A, MAX_COUNT, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new TrackedStorageImpl<>(new LimitedStorageImpl<>(100), () -> 0L); + final Storage destination = new TrackedStorageImpl(new LimitedStorageImpl(100), () -> 0L); storageChannel.addSource(destination); - storageChannel.insert("A", 100 - MAX_COUNT + 1, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(A, 100 - MAX_COUNT + 1, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final boolean success = sut.insert("A", GridInsertMode.ENTIRE_RESOURCE, source); + final boolean success = sut.insert(A, GridInsertMode.ENTIRE_RESOURCE, source); // Assert assertThat(success).isFalse(); assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100 - MAX_COUNT + 1) + new ResourceAmount(A, 100 - MAX_COUNT + 1) ); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", MAX_COUNT) + new ResourceAmount(A, MAX_COUNT) ); - assertThat(storageChannel.findTrackedResourceByActorType("A", GridActor.class)).isEmpty(); + assertThat(storageChannel.findTrackedResourceByActorType(A, GridActor.class)).isEmpty(); } } @@ -191,14 +194,14 @@ class ExtractTest { @EnumSource(GridExtractMode.class) void shouldExtractFromSourceToDestination(final GridExtractMode extractMode) { // Arrange - final Storage destination = new LimitedStorageImpl<>(100); + final Storage destination = new LimitedStorageImpl(100); - final Storage source = new TrackedStorageImpl<>(new LimitedStorageImpl<>(100), () -> 0L); + final Storage source = new TrackedStorageImpl(new LimitedStorageImpl(100), () -> 0L); storageChannel.addSource(source); - storageChannel.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final boolean success = sut.extract("A", extractMode, destination); + final boolean success = sut.extract(A, extractMode, destination); // Assert assertThat(success).isTrue(); @@ -210,12 +213,12 @@ void shouldExtractFromSourceToDestination(final GridExtractMode extractMode) { }; assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100 - expectedExtracted) + new ResourceAmount(A, 100 - expectedExtracted) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", expectedExtracted) + new ResourceAmount(A, expectedExtracted) ); - assertThat(storageChannel.findTrackedResourceByActorType("A", GridActor.class)) + assertThat(storageChannel.findTrackedResourceByActorType(A, GridActor.class)) .get() .usingRecursiveComparison() .isEqualTo(new TrackedResource(GridActor.NAME, 0)); @@ -225,44 +228,44 @@ void shouldExtractFromSourceToDestination(final GridExtractMode extractMode) { @EnumSource(GridExtractMode.class) void shouldNotExtractFromSourceWhenResourceIsNotPresentInSource(final GridExtractMode extractMode) { // Arrange - final Storage destination = new LimitedStorageImpl<>(100); + final Storage destination = new LimitedStorageImpl(100); - final Storage source = new TrackedStorageImpl<>(new LimitedStorageImpl<>(100), () -> 0L); + final Storage source = new TrackedStorageImpl(new LimitedStorageImpl(100), () -> 0L); storageChannel.addSource(source); // Act - final boolean success = sut.extract("A", extractMode, destination); + final boolean success = sut.extract(A, extractMode, destination); // Assert assertThat(success).isFalse(); assertThat(storageChannel.getAll()).isEmpty(); assertThat(destination.getAll()).isEmpty(); - assertThat(storageChannel.findTrackedResourceByActorType("A", GridActor.class)).isNotPresent(); + assertThat(storageChannel.findTrackedResourceByActorType(A, GridActor.class)).isNotPresent(); } @ParameterizedTest @EnumSource(GridExtractMode.class) void shouldNotExtractFromSourceIfThereIsNoSpaceInDestination(final GridExtractMode extractMode) { // Arrange - final Storage destination = new LimitedStorageImpl<>(100); - destination.insert("B", 100, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage destination = new LimitedStorageImpl(100); + destination.insert(B, 100, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage source = new TrackedStorageImpl<>(new LimitedStorageImpl<>(100), () -> 0L); + final Storage source = new TrackedStorageImpl(new LimitedStorageImpl(100), () -> 0L); storageChannel.addSource(source); - storageChannel.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final boolean success = sut.extract("A", extractMode, destination); + final boolean success = sut.extract(A, extractMode, destination); // Assert assertThat(success).isFalse(); assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100) + new ResourceAmount(A, 100) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("B", 100) + new ResourceAmount(B, 100) ); - assertThat(storageChannel.findTrackedResourceByActorType("A", GridActor.class)).isEmpty(); + assertThat(storageChannel.findTrackedResourceByActorType(A, GridActor.class)).isEmpty(); } } @@ -271,22 +274,22 @@ class ExtractEntireResourceTest { @Test void shouldExtractEntireResourceFromSourceToDestinationIfResourceIsLessThanMaxCount() { // Arrange - final Storage destination = new LimitedStorageImpl<>(100); + final Storage destination = new LimitedStorageImpl(100); - final Storage source = new TrackedStorageImpl<>(new LimitedStorageImpl<>(100), () -> 0L); + final Storage source = new TrackedStorageImpl(new LimitedStorageImpl(100), () -> 0L); storageChannel.addSource(source); - storageChannel.insert("A", MAX_COUNT - 1, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(A, MAX_COUNT - 1, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final boolean success = sut.extract("A", GridExtractMode.ENTIRE_RESOURCE, destination); + final boolean success = sut.extract(A, GridExtractMode.ENTIRE_RESOURCE, destination); // Assert assertThat(success).isTrue(); assertThat(storageChannel.getAll()).isEmpty(); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", MAX_COUNT - 1) + new ResourceAmount(A, MAX_COUNT - 1) ); - assertThat(storageChannel.findTrackedResourceByActorType("A", GridActor.class)) + assertThat(storageChannel.findTrackedResourceByActorType(A, GridActor.class)) .get() .usingRecursiveComparison() .isEqualTo(new TrackedResource(GridActor.NAME, 0)); @@ -295,24 +298,24 @@ void shouldExtractEntireResourceFromSourceToDestinationIfResourceIsLessThanMaxCo @Test void shouldExtractEntireResourceWithRemainderFromSourceToDestinationIfThereIsNotEnoughSpaceInDestination() { // Arrange - final Storage destination = new LimitedStorageImpl<>(MAX_COUNT - 1); + final Storage destination = new LimitedStorageImpl(MAX_COUNT - 1); - final Storage source = new TrackedStorageImpl<>(new LimitedStorageImpl<>(100), () -> 0L); + final Storage source = new TrackedStorageImpl(new LimitedStorageImpl(100), () -> 0L); storageChannel.addSource(source); - storageChannel.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final boolean success = sut.extract("A", GridExtractMode.ENTIRE_RESOURCE, destination); + final boolean success = sut.extract(A, GridExtractMode.ENTIRE_RESOURCE, destination); // Assert assertThat(success).isTrue(); assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100 - MAX_COUNT + 1) + new ResourceAmount(A, 100 - MAX_COUNT + 1) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", MAX_COUNT - 1) + new ResourceAmount(A, MAX_COUNT - 1) ); - assertThat(storageChannel.findTrackedResourceByActorType("A", GridActor.class)) + assertThat(storageChannel.findTrackedResourceByActorType(A, GridActor.class)) .get() .usingRecursiveComparison() .isEqualTo(new TrackedResource(GridActor.NAME, 0)); @@ -324,22 +327,22 @@ class ExtractHalfResourceTest { @Test void shouldExtractSingleAmountIfResourceHasSingleAmountWhenExtractingHalfResourceFromSourceToDestination() { // Arrange - final Storage destination = new LimitedStorageImpl<>(MAX_COUNT); + final Storage destination = new LimitedStorageImpl(MAX_COUNT); - final Storage source = new TrackedStorageImpl<>(new LimitedStorageImpl<>(100), () -> 0L); + final Storage source = new TrackedStorageImpl(new LimitedStorageImpl(100), () -> 0L); storageChannel.addSource(source); - storageChannel.insert("A", 1, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(A, 1, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final boolean success = sut.extract("A", GridExtractMode.HALF_RESOURCE, destination); + final boolean success = sut.extract(A, GridExtractMode.HALF_RESOURCE, destination); // Assert assertThat(success).isTrue(); assertThat(storageChannel.getAll()).isEmpty(); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 1) + new ResourceAmount(A, 1) ); - assertThat(storageChannel.findTrackedResourceByActorType("A", GridActor.class)) + assertThat(storageChannel.findTrackedResourceByActorType(A, GridActor.class)) .get() .usingRecursiveComparison() .isEqualTo(new TrackedResource(GridActor.NAME, 0)); diff --git a/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/view/GridResourceImpl.java b/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/view/GridResourceImpl.java index 783d81fa1..9b4581044 100644 --- a/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/view/GridResourceImpl.java +++ b/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/view/GridResourceImpl.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.api.grid.view; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import java.util.Collections; @@ -8,37 +9,20 @@ import java.util.Optional; import java.util.Set; -public class GridResourceImpl implements GridResource { - private final ResourceAmount resourceAmount; +class GridResourceImpl implements GridResource { + private final ResourceAmount resourceAmountRef; private final Map> attributes; private boolean zeroed; - public GridResourceImpl(final String name, final long amount) { - this(new ResourceAmount<>(name, amount)); + GridResourceImpl(final ResourceKey resource, final long amount) { + this(new ResourceAmount(resource, amount)); } - public GridResourceImpl(final String name) { - this(new ResourceAmount<>(name, 1)); - } - - public GridResourceImpl(final ResourceAmount resourceAmount) { - this.resourceAmount = resourceAmount; - this.attributes = Map.of( - FakeGridResourceAttributeKeys.MOD_ID, Set.of(resourceAmount.getResource().toString()), - FakeGridResourceAttributeKeys.MOD_NAME, Set.of(resourceAmount.getResource().toString()) - ); - } - - public GridResourceImpl(final String name, - final long amount, - final String modId, - final String modName, - final Set tags) { - this.resourceAmount = new ResourceAmount<>(name, amount); + GridResourceImpl(final ResourceAmount resourceAmountRef) { + this.resourceAmountRef = resourceAmountRef; this.attributes = Map.of( - FakeGridResourceAttributeKeys.MOD_ID, Set.of(modId), - FakeGridResourceAttributeKeys.MOD_NAME, Set.of(modName), - FakeGridResourceAttributeKeys.TAGS, tags + FakeGridResourceAttributeKeys.MOD_ID, Set.of(resourceAmountRef.getResource().toString()), + FakeGridResourceAttributeKeys.MOD_NAME, Set.of(resourceAmountRef.getResource().toString()) ); } @@ -49,17 +33,17 @@ public GridResourceImpl zeroed() { @Override public Optional getTrackedResource(final GridView view) { - return view.getTrackedResource(resourceAmount.getResource()); + return view.getTrackedResource(resourceAmountRef.getResource()); } @Override public long getAmount() { - return resourceAmount.getAmount(); + return resourceAmountRef.getAmount(); } @Override public String getName() { - return resourceAmount.getResource().toString(); + return resourceAmountRef.getResource().toString(); } @Override @@ -79,6 +63,6 @@ public void setZeroed(final boolean zeroed) { @Override public String toString() { - return resourceAmount.toString(); + return resourceAmountRef.getResource().toString(); } } diff --git a/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/view/GridViewImplTest.java b/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/view/GridViewImplTest.java index c705edde4..6bbf024f0 100644 --- a/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/view/GridViewImplTest.java +++ b/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/view/GridViewImplTest.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.api.grid.view; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; @@ -11,6 +12,10 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static com.refinedmods.refinedstorage2.api.grid.TestResource.A; +import static com.refinedmods.refinedstorage2.api.grid.TestResource.B; +import static com.refinedmods.refinedstorage2.api.grid.TestResource.C; +import static com.refinedmods.refinedstorage2.api.grid.TestResource.D; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -39,23 +44,19 @@ void shouldAddResourcesWithSameNameButDifferentIdentity() { // Arrange final GridViewBuilder builder = new GridViewBuilderImpl( resourceAmount -> Optional.of(new GridResourceWithMetadata(resourceAmount)), - (view) -> Comparator.comparing(GridResource::getName), - (view) -> Comparator.comparing(GridResource::getAmount) + view -> Comparator.comparing(GridResource::getName), + view -> Comparator.comparing(GridResource::getAmount) ); final GridView view = builder.build(); // Act - view.onChange(new ResourceWithMetadata("A", 1), 1, null); - view.onChange(new ResourceWithMetadata("A", 2), 1, null); + view.onChange(new ResourceWithMetadata(A, 1), 1, null); + view.onChange(new ResourceWithMetadata(A, 2), 1, null); // Assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceWithMetadata(new ResourceAmount<>( - new ResourceWithMetadata("A", 1), 1 - )), - new GridResourceWithMetadata(new ResourceAmount<>( - new ResourceWithMetadata("A", 2), 1 - )) + new GridResourceWithMetadata(new ResourceAmount(new ResourceWithMetadata(A, 1), 1)), + new GridResourceWithMetadata(new ResourceAmount(new ResourceWithMetadata(A, 2), 1)) ); } @@ -66,27 +67,27 @@ void shouldPreserveOrderWhenSortingAndTwoResourcesHaveTheSameQuantity() { view.setSortingDirection(GridSortingDirection.DESCENDING); // Act & assert - view.onChange("A", 10, null); - view.onChange("A", 5, null); - view.onChange("B", 15, null); - view.onChange("C", 2, null); + view.onChange(A, 10, null); + view.onChange(A, 5, null); + view.onChange(B, 15, null); + view.onChange(C, 2, null); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("B", 15), - new GridResourceImpl("A", 15), - new GridResourceImpl("C", 2) + new GridResourceImpl(B, 15), + new GridResourceImpl(A, 15), + new GridResourceImpl(C, 2) ); - view.onChange("A", -15, null); - view.onChange("A", 15, null); + view.onChange(A, -15, null); + view.onChange(A, 15, null); - view.onChange("B", -15, null); - view.onChange("B", 15, null); + view.onChange(B, -15, null); + view.onChange(B, 15, null); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("B", 15), - new GridResourceImpl("A", 15), - new GridResourceImpl("C", 2) + new GridResourceImpl(B, 15), + new GridResourceImpl(A, 15), + new GridResourceImpl(C, 2) ); } @@ -94,27 +95,27 @@ void shouldPreserveOrderWhenSortingAndTwoResourcesHaveTheSameQuantity() { void shouldLoadResourcesAndRetrieveTrackedResourcesProperly() { // Arrange final GridView view = viewBuilder - .withResource("A", 1, new TrackedResource("Raoul", 1)) - .withResource("A", 1, new TrackedResource("RaoulA", 2)) - .withResource("B", 1, new TrackedResource("VDB", 3)) - .withResource("B", 1, null) - .withResource("D", 1, null) + .withResource(A, 1, new TrackedResource("Raoul", 1)) + .withResource(A, 1, new TrackedResource("RaoulA", 2)) + .withResource(B, 1, new TrackedResource("VDB", 3)) + .withResource(B, 1, null) + .withResource(D, 1, null) .build(); // Act - final Optional a = view.getTrackedResource("A"); - final Optional b = view.getTrackedResource("B"); - final Optional d = view.getTrackedResource("D"); - final ResourceList backingList = view.copyBackingList(); + final Optional a = view.getTrackedResource(A); + final Optional b = view.getTrackedResource(B); + final Optional d = view.getTrackedResource(D); + final ResourceList backingList = view.copyBackingList(); // Assert assertThat(a).get().usingRecursiveComparison().isEqualTo(new TrackedResource("RaoulA", 2)); assertThat(b).isEmpty(); assertThat(d).isEmpty(); assertThat(backingList.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 2), - new ResourceAmount<>("B", 2), - new ResourceAmount<>("D", 1) + new ResourceAmount(A, 2), + new ResourceAmount(B, 2), + new ResourceAmount(D, 1) ); } @@ -122,8 +123,8 @@ void shouldLoadResourcesAndRetrieveTrackedResourcesProperly() { void shouldInsertNewResource() { // Arrange final GridView view = viewBuilder - .withResource("B", 15, null) - .withResource("D", 10, null) + .withResource(B, 15, null) + .withResource(D, 10, null) .build(); view.sort(); @@ -132,20 +133,20 @@ void shouldInsertNewResource() { view.setListener(listener); // Act - view.onChange("A", 12, null); + view.onChange(A, 12, null); // Assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("A", 12), - new GridResourceImpl("B", 15) + new GridResourceImpl(D, 10), + new GridResourceImpl(A, 12), + new GridResourceImpl(B, 15) ); assertThat(view.copyBackingList().getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("D", 10), - new ResourceAmount<>("A", 12), - new ResourceAmount<>("B", 15) + new ResourceAmount(D, 10), + new ResourceAmount(A, 12), + new ResourceAmount(B, 15) ); verify(listener, times(1)).run(); } @@ -154,12 +155,12 @@ void shouldInsertNewResource() { void shouldSetFilterAndSort() { // Arrange final GridView view = viewBuilder - .withResource("A", 10, null) - .withResource("B", 10, null) + .withResource(A, 10, null) + .withResource(B, 10, null) .build(); - final Predicate filterA = resource -> resource.getName().equals("A"); - final Predicate filterB = resource -> resource.getName().equals("B"); + final Predicate filterA = resource -> resource.getName().equals(A.name()); + final Predicate filterB = resource -> resource.getName().equals(B.name()); // Act final Predicate previousFilter1 = view.setFilterAndSort(filterA); @@ -169,7 +170,7 @@ void shouldSetFilterAndSort() { assertThat(previousFilter1).isNotNull(); assertThat(previousFilter2).isEqualTo(filterA); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("B", 10) + new GridResourceImpl(B, 10) ); } @@ -177,22 +178,22 @@ void shouldSetFilterAndSort() { void shouldNotInsertNewResourceWhenFilteringProhibitsIt() { // Arrange final GridView view = viewBuilder - .withResource("B", 15, null) - .withResource("D", 10, null) + .withResource(B, 15, null) + .withResource(D, 10, null) .build(); - view.setFilterAndSort(resource -> !resource.getName().equals("A")); + view.setFilterAndSort(resource -> !resource.getName().equals(A.name())); final Runnable listener = mock(Runnable.class); view.setListener(listener); // Act - view.onChange("A", 12, null); + view.onChange(A, 12, null); // Assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("B", 15) + new GridResourceImpl(D, 10), + new GridResourceImpl(B, 15) ); verify(listener, never()).run(); } @@ -201,9 +202,9 @@ void shouldNotInsertNewResourceWhenFilteringProhibitsIt() { void shouldCallListenerWhenSorting() { // Arrange final GridView view = viewBuilder - .withResource("B", 6, null) - .withResource("A", 15, null) - .withResource("D", 10, null) + .withResource(B, 6, null) + .withResource(A, 15, null) + .withResource(D, 10, null) .build(); final Runnable listener = mock(Runnable.class); @@ -221,9 +222,9 @@ void shouldCallListenerWhenSorting() { void shouldUpdateExistingResource() { // Arrange final GridView view = viewBuilder - .withResource("B", 6, null) - .withResource("A", 15, null) - .withResource("D", 10, null) + .withResource(B, 6, null) + .withResource(A, 15, null) + .withResource(D, 10, null) .build(); view.sort(); @@ -232,20 +233,20 @@ void shouldUpdateExistingResource() { view.setListener(listener); // Act - view.onChange("B", 5, null); + view.onChange(B, 5, null); // Assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("B", 11), - new GridResourceImpl("A", 15) + new GridResourceImpl(D, 10), + new GridResourceImpl(B, 11), + new GridResourceImpl(A, 15) ); assertThat(view.copyBackingList().getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("D", 10), - new ResourceAmount<>("B", 11), - new ResourceAmount<>("A", 15) + new ResourceAmount(D, 10), + new ResourceAmount(B, 11), + new ResourceAmount(A, 15) ); verify(listener, times(1)).run(); } @@ -254,30 +255,30 @@ void shouldUpdateExistingResource() { void shouldNotUpdateExistingResourceWhenFilteringProhibitsIt() { // Arrange final GridView view = viewBuilder - .withResource("B", 6, null) - .withResource("A", 15, null) - .withResource("D", 10, null) + .withResource(B, 6, null) + .withResource(A, 15, null) + .withResource(D, 10, null) .build(); - view.setFilterAndSort(resource -> !resource.getName().equals("B")); + view.setFilterAndSort(resource -> !resource.getName().equals(B.name())); final Runnable listener = mock(Runnable.class); view.setListener(listener); // Act - view.onChange("B", 5, null); + view.onChange(B, 5, null); // Assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("A", 15) + new GridResourceImpl(D, 10), + new GridResourceImpl(A, 15) ); assertThat(view.copyBackingList().getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("B", 11), - new ResourceAmount<>("D", 10), - new ResourceAmount<>("A", 15) + new ResourceAmount(B, 11), + new ResourceAmount(D, 10), + new ResourceAmount(A, 15) ); verify(listener, never()).run(); } @@ -286,9 +287,9 @@ void shouldNotUpdateExistingResourceWhenFilteringProhibitsIt() { void shouldNotReorderExistingResourceWhenPreventingSorting() { // Arrange final GridView view = viewBuilder - .withResource("B", 6, null) - .withResource("A", 15, null) - .withResource("D", 10, null) + .withResource(B, 6, null) + .withResource(A, 15, null) + .withResource(D, 10, null) .build(); view.sort(); @@ -298,9 +299,9 @@ void shouldNotReorderExistingResourceWhenPreventingSorting() { // Act & assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("B", 6), - new GridResourceImpl("D", 10), - new GridResourceImpl("A", 15) + new GridResourceImpl(B, 6), + new GridResourceImpl(D, 10), + new GridResourceImpl(A, 15) ); final boolean changed = view.setPreventSorting(true); @@ -308,20 +309,20 @@ void shouldNotReorderExistingResourceWhenPreventingSorting() { final boolean changed2 = view.setPreventSorting(true); assertThat(changed2).isFalse(); - view.onChange("B", 5, null); + view.onChange(B, 5, null); verify(listener, never()).run(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("B", 11), - new GridResourceImpl("D", 10), - new GridResourceImpl("A", 15) + new GridResourceImpl(B, 11), + new GridResourceImpl(D, 10), + new GridResourceImpl(A, 15) ); assertThat(view.copyBackingList().getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("B", 11), - new ResourceAmount<>("D", 10), - new ResourceAmount<>("A", 15) + new ResourceAmount(B, 11), + new ResourceAmount(D, 10), + new ResourceAmount(A, 15) ); final boolean changed3 = view.setPreventSorting(false); @@ -329,16 +330,16 @@ void shouldNotReorderExistingResourceWhenPreventingSorting() { view.sort(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("B", 11), - new GridResourceImpl("A", 15) + new GridResourceImpl(D, 10), + new GridResourceImpl(B, 11), + new GridResourceImpl(A, 15) ); assertThat(view.copyBackingList().getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("B", 11), - new ResourceAmount<>("D", 10), - new ResourceAmount<>("A", 15) + new ResourceAmount(B, 11), + new ResourceAmount(D, 10), + new ResourceAmount(A, 15) ); } @@ -347,18 +348,18 @@ void shouldUpdateTrackedResourceAfterReceivingChange() { // Act final GridView view = viewBuilder.build(); - view.onChange("A", 1, new TrackedResource("Raoul", 1)); - view.onChange("A", 1, new TrackedResource("RaoulA", 2)); + view.onChange(A, 1, new TrackedResource("Raoul", 1)); + view.onChange(A, 1, new TrackedResource("RaoulA", 2)); - view.onChange("B", 1, new TrackedResource("VDB", 3)); - view.onChange("B", 1, null); + view.onChange(B, 1, new TrackedResource("VDB", 3)); + view.onChange(B, 1, null); - view.onChange("D", 1, null); + view.onChange(D, 1, null); // Assert - final Optional a = view.getTrackedResource("A"); - final Optional b = view.getTrackedResource("B"); - final Optional c = view.getTrackedResource("D"); + final Optional a = view.getTrackedResource(A); + final Optional b = view.getTrackedResource(B); + final Optional c = view.getTrackedResource(D); assertThat(a).get().usingRecursiveComparison().isEqualTo(new TrackedResource("RaoulA", 2)); assertThat(b).isEmpty(); @@ -369,9 +370,9 @@ void shouldUpdateTrackedResourceAfterReceivingChange() { void shouldUpdateExistingResourceWhenPerformingPartialRemoval() { // Arrange final GridView view = viewBuilder - .withResource("B", 20, null) - .withResource("A", 15, null) - .withResource("D", 10, null) + .withResource(B, 20, null) + .withResource(A, 15, null) + .withResource(D, 10, null) .build(); view.sort(); @@ -380,20 +381,20 @@ void shouldUpdateExistingResourceWhenPerformingPartialRemoval() { view.setListener(listener); // Act - view.onChange("B", -7, null); + view.onChange(B, -7, null); // Assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("B", 13), - new GridResourceImpl("A", 15) + new GridResourceImpl(D, 10), + new GridResourceImpl(B, 13), + new GridResourceImpl(A, 15) ); assertThat(view.copyBackingList().getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("D", 10), - new ResourceAmount<>("B", 13), - new ResourceAmount<>("A", 15) + new ResourceAmount(D, 10), + new ResourceAmount(B, 13), + new ResourceAmount(A, 15) ); verify(listener, times(1)).run(); } @@ -402,23 +403,23 @@ void shouldUpdateExistingResourceWhenPerformingPartialRemoval() { void shouldNotUpdateExistingResourceWhenPerformingPartialRemovalAndFilteringProhibitsIt() { // Arrange final GridView view = viewBuilder - .withResource("B", 20, null) - .withResource("A", 15, null) - .withResource("D", 10, null) + .withResource(B, 20, null) + .withResource(A, 15, null) + .withResource(D, 10, null) .build(); - view.setFilterAndSort(resource -> !resource.getName().equals("B")); + view.setFilterAndSort(resource -> !resource.getName().equals(B.name())); final Runnable listener = mock(Runnable.class); view.setListener(listener); // Act - view.onChange("B", -7, null); + view.onChange(B, -7, null); // Assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("A", 15) + new GridResourceImpl(D, 10), + new GridResourceImpl(A, 15) ); verify(listener, never()).run(); } @@ -427,9 +428,9 @@ void shouldNotUpdateExistingResourceWhenPerformingPartialRemovalAndFilteringProh void shouldNotReorderExistingResourceWhenPerformingPartialRemovalAndPreventingSorting() { // Arrange final GridView view = viewBuilder - .withResource("B", 20, null) - .withResource("A", 15, null) - .withResource("D", 10, null) + .withResource(B, 20, null) + .withResource(A, 15, null) + .withResource(D, 10, null) .build(); view.sort(); @@ -439,29 +440,29 @@ void shouldNotReorderExistingResourceWhenPerformingPartialRemovalAndPreventingSo // Act & assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("A", 15), - new GridResourceImpl("B", 20) + new GridResourceImpl(D, 10), + new GridResourceImpl(A, 15), + new GridResourceImpl(B, 20) ); view.setPreventSorting(true); - view.onChange("B", -7, null); + view.onChange(B, -7, null); verify(listener, never()).run(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("A", 15), - new GridResourceImpl("B", 13) + new GridResourceImpl(D, 10), + new GridResourceImpl(A, 15), + new GridResourceImpl(B, 13) ); view.setPreventSorting(false); view.sort(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("B", 13), - new GridResourceImpl("A", 15) + new GridResourceImpl(D, 10), + new GridResourceImpl(B, 13), + new GridResourceImpl(A, 15) ); } @@ -469,9 +470,9 @@ void shouldNotReorderExistingResourceWhenPerformingPartialRemovalAndPreventingSo void shouldRemoveExistingResourceCompletely() { // Arrange final GridView view = viewBuilder - .withResource("B", 20, null) - .withResource("A", 15, null) - .withResource("D", 10, null) + .withResource(B, 20, null) + .withResource(A, 15, null) + .withResource(D, 10, null) .build(); view.sort(); @@ -480,18 +481,18 @@ void shouldRemoveExistingResourceCompletely() { view.setListener(listener); // Act - view.onChange("B", -20, null); + view.onChange(B, -20, null); // Assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("A", 15) + new GridResourceImpl(D, 10), + new GridResourceImpl(A, 15) ); assertThat(view.copyBackingList().getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("D", 10), - new ResourceAmount<>("A", 15) + new ResourceAmount(D, 10), + new ResourceAmount(A, 15) ); verify(listener, times(1)).run(); } @@ -500,9 +501,9 @@ void shouldRemoveExistingResourceCompletely() { void shouldNotReorderWhenRemovingExistingResourceCompletelyAndPreventingSorting() { // Arrange final GridView view = viewBuilder - .withResource("A", 15, null) - .withResource("B", 20, null) - .withResource("D", 10, null) + .withResource(A, 15, null) + .withResource(B, 20, null) + .withResource(D, 10, null) .build(); view.sort(); @@ -512,39 +513,39 @@ void shouldNotReorderWhenRemovingExistingResourceCompletelyAndPreventingSorting( // Act & assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("A", 15), - new GridResourceImpl("B", 20) + new GridResourceImpl(D, 10), + new GridResourceImpl(A, 15), + new GridResourceImpl(B, 20) ); view.setPreventSorting(true); - view.onChange("B", -20, null); + view.onChange(B, -20, null); verify(listener, never()).run(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("A", 15), - new GridResourceImpl("B", 20).zeroed() + new GridResourceImpl(D, 10), + new GridResourceImpl(A, 15), + new GridResourceImpl(B, 20).zeroed() ); assertThat(view.copyBackingList().getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("D", 10), - new ResourceAmount<>("A", 15) + new ResourceAmount(D, 10), + new ResourceAmount(A, 15) ); view.setPreventSorting(false); view.sort(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("A", 15) + new GridResourceImpl(D, 10), + new GridResourceImpl(A, 15) ); assertThat(view.copyBackingList().getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("D", 10), - new ResourceAmount<>("A", 15) + new ResourceAmount(D, 10), + new ResourceAmount(A, 15) ); } @@ -552,9 +553,9 @@ void shouldNotReorderWhenRemovingExistingResourceCompletelyAndPreventingSorting( void shouldReuseExistingResourceWhenPreventingSortingAndRemovingExistingResourceCompletelyAndThenReinserting() { // Arrange final GridView view = viewBuilder - .withResource("A", 15, null) - .withResource("B", 20, null) - .withResource("D", 10, null) + .withResource(A, 15, null) + .withResource(B, 20, null) + .withResource(D, 10, null) .build(); view.sort(); @@ -564,40 +565,40 @@ void shouldReuseExistingResourceWhenPreventingSortingAndRemovingExistingResource // Act & assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("A", 15), - new GridResourceImpl("B", 20) + new GridResourceImpl(D, 10), + new GridResourceImpl(A, 15), + new GridResourceImpl(B, 20) ); // Delete the item view.setPreventSorting(true); - view.onChange("B", -20, null); + view.onChange(B, -20, null); verify(listener, never()).run(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("A", 15), - new GridResourceImpl("B", 20).zeroed() + new GridResourceImpl(D, 10), + new GridResourceImpl(A, 15), + new GridResourceImpl(B, 20).zeroed() ); // Re-insert the item - view.onChange("B", 5, null); + view.onChange(B, 5, null); verify(listener, never()).run(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("A", 15), - new GridResourceImpl("B", 5) + new GridResourceImpl(D, 10), + new GridResourceImpl(A, 15), + new GridResourceImpl(B, 5) ); // Re-insert the item again - view.onChange("B", 3, null); + view.onChange(B, 3, null); verify(listener, never()).run(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl("D", 10), - new GridResourceImpl("A", 15), - new GridResourceImpl("B", 8) + new GridResourceImpl(D, 10), + new GridResourceImpl(A, 15), + new GridResourceImpl(B, 8) ); } @@ -605,9 +606,9 @@ void shouldReuseExistingResourceWhenPreventingSortingAndRemovingExistingResource void shouldClear() { // Arrange final GridView view = viewBuilder - .withResource("A", 15, new TrackedResource("Source", 0)) - .withResource("B", 20, new TrackedResource("Source", 0)) - .withResource("D", 10, new TrackedResource("Source", 0)) + .withResource(A, 15, new TrackedResource("Source", 0)) + .withResource(B, 20, new TrackedResource("Source", 0)) + .withResource(D, 10, new TrackedResource("Source", 0)) .build(); // Act @@ -616,16 +617,16 @@ void shouldClear() { // Assert assertThat(view.getViewList()).isEmpty(); assertThat(view.copyBackingList().getAll()).isEmpty(); - assertThat(view.getTrackedResource("A")).isEmpty(); - assertThat(view.getTrackedResource("B")).isEmpty(); - assertThat(view.getTrackedResource("D")).isEmpty(); + assertThat(view.getTrackedResource(A)).isEmpty(); + assertThat(view.getTrackedResource(B)).isEmpty(); + assertThat(view.getTrackedResource(D)).isEmpty(); } - private record ResourceWithMetadata(String name, int metadata) { + private record ResourceWithMetadata(ResourceKey resource, int metadata) implements ResourceKey { } private static class GridResourceWithMetadata extends GridResourceImpl { - GridResourceWithMetadata(final ResourceAmount resourceAmount) { + GridResourceWithMetadata(final ResourceAmount resourceAmount) { super(resourceAmount); } } diff --git a/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcherManagerImplTest.java b/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcherManagerImplTest.java index e8fee120c..77c5f2ced 100644 --- a/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcherManagerImplTest.java +++ b/refinedstorage2-grid-api/src/test/java/com/refinedmods/refinedstorage2/api/grid/watcher/GridWatcherManagerImplTest.java @@ -5,14 +5,15 @@ import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelImpl; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; - -import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InOrder; +import static com.refinedmods.refinedstorage2.api.grid.TestResource.A; +import static com.refinedmods.refinedstorage2.api.grid.TestResource.B; +import static com.refinedmods.refinedstorage2.api.grid.TestResource.C; +import static com.refinedmods.refinedstorage2.api.grid.TestResource.D; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -23,44 +24,27 @@ class GridWatcherManagerImplTest { GridWatcherManager sut; - StorageChannelType storageChannelType = StorageChannelImpl::new; - StorageChannel storageChannel; - GridStorageChannelProvider storageChannelProvider; + StorageChannel storageChannel; @BeforeEach void setUp() { sut = new GridWatcherManagerImpl(); - storageChannel = new StorageChannelImpl<>(); - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannelProvider = new GridStorageChannelProvider() { - @Override - public Set> getStorageChannelTypes() { - return Set.of(storageChannelType); - } - - @Override - @SuppressWarnings("unchecked") - public StorageChannel getStorageChannel(final StorageChannelType type) { - if (type == storageChannelType) { - return (StorageChannel) storageChannel; - } - throw new IllegalArgumentException(); - } - }; + storageChannel = new StorageChannelImpl(); + storageChannel.addSource(new InMemoryStorageImpl()); } @Test void shouldAddWatcherAndNotifyOfChanges() { // Arrange final GridWatcher watcher = mock(GridWatcher.class); - storageChannel.insert("A", 10, Action.EXECUTE, FakeActor.INSTANCE); + storageChannel.insert(A, 10, Action.EXECUTE, FakeActor.INSTANCE); // Act - sut.addWatcher(watcher, FakeActor.class, storageChannelProvider); - storageChannel.insert("B", 5, Action.EXECUTE, FakeActor.INSTANCE); + sut.addWatcher(watcher, FakeActor.class, storageChannel); + storageChannel.insert(B, 5, Action.EXECUTE, FakeActor.INSTANCE); // Assert - verify(watcher, times(1)).onChanged(storageChannelType, "B", 5, null); + verify(watcher, times(1)).onChanged(B, 5, null); verifyNoMoreInteractions(watcher); } @@ -68,12 +52,12 @@ void shouldAddWatcherAndNotifyOfChanges() { void shouldNotAddDuplicateWatcher() { // Arrange final GridWatcher watcher = mock(GridWatcher.class); - sut.addWatcher(watcher, FakeActor.class, storageChannelProvider); + sut.addWatcher(watcher, FakeActor.class, storageChannel); // Act & assert assertThrows( IllegalArgumentException.class, - () -> sut.addWatcher(watcher, FakeActor.class, storageChannelProvider), + () -> sut.addWatcher(watcher, FakeActor.class, storageChannel), "Watcher is already registered" ); } @@ -82,12 +66,12 @@ void shouldNotAddDuplicateWatcher() { void shouldRemoveWatcher() { // Arrange final GridWatcher watcher = mock(GridWatcher.class); - storageChannel.insert("A", 10, Action.EXECUTE, FakeActor.INSTANCE); - sut.addWatcher(watcher, FakeActor.class, storageChannelProvider); + storageChannel.insert(A, 10, Action.EXECUTE, FakeActor.INSTANCE); + sut.addWatcher(watcher, FakeActor.class, storageChannel); // Act - sut.removeWatcher(watcher, storageChannelProvider); - storageChannel.insert("B", 5, Action.EXECUTE, FakeActor.INSTANCE); + sut.removeWatcher(watcher, storageChannel); + storageChannel.insert(B, 5, Action.EXECUTE, FakeActor.INSTANCE); // Assert verifyNoInteractions(watcher); @@ -101,7 +85,7 @@ void shouldNotRemoveWatcherThatIsNotRegistered() { // Act & assert assertThrows( IllegalArgumentException.class, - () -> sut.removeWatcher(watcher, storageChannelProvider), + () -> sut.removeWatcher(watcher, storageChannel), "Watcher is not registered" ); } @@ -110,19 +94,19 @@ void shouldNotRemoveWatcherThatIsNotRegistered() { void shouldAddAndRemoveAndAddWatcherAgain() { // Arrange final GridWatcher watcher = mock(GridWatcher.class); - storageChannel.insert("A", 10, Action.EXECUTE, FakeActor.INSTANCE); + storageChannel.insert(A, 10, Action.EXECUTE, FakeActor.INSTANCE); // Act - sut.addWatcher(watcher, FakeActor.class, storageChannelProvider); - storageChannel.insert("B", 5, Action.EXECUTE, FakeActor.INSTANCE); - sut.removeWatcher(watcher, storageChannelProvider); - storageChannel.insert("C", 4, Action.EXECUTE, FakeActor.INSTANCE); - sut.addWatcher(watcher, FakeActor.class, storageChannelProvider); - storageChannel.insert("D", 3, Action.EXECUTE, FakeActor.INSTANCE); + sut.addWatcher(watcher, FakeActor.class, storageChannel); + storageChannel.insert(B, 5, Action.EXECUTE, FakeActor.INSTANCE); + sut.removeWatcher(watcher, storageChannel); + storageChannel.insert(C, 4, Action.EXECUTE, FakeActor.INSTANCE); + sut.addWatcher(watcher, FakeActor.class, storageChannel); + storageChannel.insert(D, 3, Action.EXECUTE, FakeActor.INSTANCE); // Assert - verify(watcher, times(1)).onChanged(storageChannelType, "B", 5, null); - verify(watcher, times(1)).onChanged(storageChannelType, "D", 3, null); + verify(watcher, times(1)).onChanged(B, 5, null); + verify(watcher, times(1)).onChanged(D, 3, null); verifyNoMoreInteractions(watcher); } @@ -130,16 +114,16 @@ void shouldAddAndRemoveAndAddWatcherAgain() { void shouldDetachAll() { // Arrange final GridWatcher watcher = mock(GridWatcher.class); - storageChannel.insert("A", 10, Action.EXECUTE, FakeActor.INSTANCE); - sut.addWatcher(watcher, FakeActor.class, storageChannelProvider); + storageChannel.insert(A, 10, Action.EXECUTE, FakeActor.INSTANCE); + sut.addWatcher(watcher, FakeActor.class, storageChannel); // Act - sut.detachAll(storageChannelProvider); - storageChannel.insert("B", 10, Action.EXECUTE, FakeActor.INSTANCE); + sut.detachAll(storageChannel); + storageChannel.insert(B, 10, Action.EXECUTE, FakeActor.INSTANCE); assertThrows(IllegalArgumentException.class, () -> sut.addWatcher( watcher, FakeActor.class, - storageChannelProvider + storageChannel ), "Watcher is already registered"); // Assert @@ -150,22 +134,22 @@ void shouldDetachAll() { void shouldAttachAll() { // Arrange final GridWatcher watcher = mock(GridWatcher.class); - storageChannel.insert("A", 10, Action.EXECUTE, FakeActor.INSTANCE); - sut.addWatcher(watcher, FakeActor.class, storageChannelProvider); - sut.detachAll(storageChannelProvider); - storageChannel.insert("B", 5, Action.EXECUTE, FakeActor.INSTANCE); + storageChannel.insert(A, 10, Action.EXECUTE, FakeActor.INSTANCE); + sut.addWatcher(watcher, FakeActor.class, storageChannel); + sut.detachAll(storageChannel); + storageChannel.insert(B, 5, Action.EXECUTE, FakeActor.INSTANCE); // Act - sut.attachAll(storageChannelProvider); - storageChannel.insert("C", 4, Action.EXECUTE, FakeActor.INSTANCE); + sut.attachAll(storageChannel); + storageChannel.insert(C, 4, Action.EXECUTE, FakeActor.INSTANCE); // Assert final InOrder inOrder = inOrder(watcher); inOrder.verify(watcher, times(1)).invalidate(); - inOrder.verify(watcher, times(1)).onChanged(storageChannelType, "A", 10, null); - inOrder.verify(watcher, times(1)).onChanged(storageChannelType, "B", 5, null); - inOrder.verify(watcher, times(1)).onChanged(storageChannelType, "C", 4, null); - inOrder.verifyNoMoreInteractions(); + verify(watcher, times(1)).onChanged(A, 10, null); + verify(watcher, times(1)).onChanged(B, 5, null); + verify(watcher, times(1)).onChanged(C, 4, null); + verifyNoMoreInteractions(watcher); } @Test @@ -173,7 +157,7 @@ void shouldNotifyAboutActivenessChange() { // Arrange final GridWatcher watcher = mock(GridWatcher.class); sut.activeChanged(true); - sut.addWatcher(watcher, FakeActor.class, storageChannelProvider); + sut.addWatcher(watcher, FakeActor.class, storageChannel); // Act sut.activeChanged(false); diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/component/StorageNetworkComponent.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/component/StorageNetworkComponent.java index 544f6f7d6..80abdd04e 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/component/StorageNetworkComponent.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/component/StorageNetworkComponent.java @@ -1,22 +1,14 @@ package com.refinedmods.refinedstorage2.api.network.component; -import com.refinedmods.refinedstorage2.api.grid.watcher.GridStorageChannelProvider; import com.refinedmods.refinedstorage2.api.storage.Actor; -import com.refinedmods.refinedstorage2.api.storage.Storage; import com.refinedmods.refinedstorage2.api.storage.TrackedResourceAmount; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import java.util.List; -import java.util.function.Predicate; import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.1") -public interface StorageNetworkComponent extends NetworkComponent, GridStorageChannelProvider { - StorageChannel getStorageChannel(StorageChannelType type); - - boolean hasSource(Predicate> matcher); - - List> getResources(StorageChannelType type, Class actorType); +public interface StorageNetworkComponent extends NetworkComponent, StorageChannel { + List getResources(Class actorType); } diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/component/StorageProvider.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/component/StorageProvider.java index 63161372b..efb73f178 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/component/StorageProvider.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/component/StorageProvider.java @@ -1,15 +1,12 @@ package com.refinedmods.refinedstorage2.api.network.component; import com.refinedmods.refinedstorage2.api.storage.Storage; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; - -import java.util.Optional; import org.apiguardian.api.API; /** * Implement this on {@link com.refinedmods.refinedstorage2.api.network.node.NetworkNode}s that can provide a storage - * for a given {@link StorageChannelType}. + * to the network. * Never modify a {@link com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel} * from a {@link com.refinedmods.refinedstorage2.api.network.node.NetworkNode} directly. * Use this interface to help you manage the lifecycle of your storage, to ensure that your storage is added or removed @@ -20,13 +17,10 @@ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") public interface StorageProvider { /** - * Returns an optional storage for the given storage channel type. * This method is called when a {@link com.refinedmods.refinedstorage2.api.network.node.NetworkNode} is added or * removed from a network. * - * @param channelType the storage channel type - * @param the type of resource - * @return the storage for the given channel, if present + * @return the storage */ - Optional> getStorageForChannel(StorageChannelType channelType); + Storage getStorage(); } diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/AbstractConfiguredProxyStorage.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/AbstractConfiguredProxyStorage.java index 883f18a2b..d40723398 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/AbstractConfiguredProxyStorage.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/AbstractConfiguredProxyStorage.java @@ -3,6 +3,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.core.CoreValidations; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.AccessMode; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.Storage; @@ -16,7 +17,7 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.4") -public abstract class AbstractConfiguredProxyStorage> implements Storage, Priority { +public abstract class AbstractConfiguredProxyStorage implements Storage, Priority { @Nullable private S delegate; private final StorageConfiguration config; @@ -31,7 +32,7 @@ protected AbstractConfiguredProxyStorage(final StorageConfiguration config, fina } @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { if (delegate == null || config.getAccessMode() == AccessMode.INSERT || !config.isActive()) { return 0; } @@ -39,7 +40,7 @@ public long extract(final T resource, final long amount, final Action action, fi } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { if (delegate == null || config.getAccessMode() == AccessMode.EXTRACT || !config.isActive() @@ -50,7 +51,7 @@ public long insert(final T resource, final long amount, final Action action, fin } @Override - public Collection> getAll() { + public Collection getAll() { return delegate == null ? Collections.emptySet() : delegate.getAll(); } diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/AbstractImmutableConfiguredProxyStorage.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/AbstractImmutableConfiguredProxyStorage.java index ab50cac5f..df1977a85 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/AbstractImmutableConfiguredProxyStorage.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/AbstractImmutableConfiguredProxyStorage.java @@ -5,8 +5,8 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.4") -public abstract class AbstractImmutableConfiguredProxyStorage> - extends AbstractConfiguredProxyStorage { +public abstract class AbstractImmutableConfiguredProxyStorage + extends AbstractConfiguredProxyStorage { private static final String ERROR_MESSAGE = "Cannot modify immutable proxy"; protected AbstractImmutableConfiguredProxyStorage(final StorageConfiguration config, final S delegate) { diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/AbstractStorageNetworkNode.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/AbstractStorageNetworkNode.java index 253bccaab..2fcb85df7 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/AbstractStorageNetworkNode.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/AbstractStorageNetworkNode.java @@ -1,10 +1,10 @@ package com.refinedmods.refinedstorage2.api.network.node; -import com.refinedmods.refinedstorage2.api.core.filter.Filter; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; +import com.refinedmods.refinedstorage2.api.resource.filter.Filter; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; import com.refinedmods.refinedstorage2.api.storage.AccessMode; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import java.util.Set; import java.util.function.UnaryOperator; @@ -38,7 +38,7 @@ public FilterMode getFilterMode() { } @Override - public boolean isAllowed(final Object resource) { + public boolean isAllowed(final ResourceKey resource) { return filter.isAllowed(resource); } @@ -59,16 +59,14 @@ private void trySortSources() { return; } final StorageNetworkComponent storage = network.getComponent(StorageNetworkComponent.class); - getRelevantStorageChannelTypes().forEach(type -> storage.getStorageChannel(type).sortSources()); + storage.sortSources(); } - protected abstract Set> getRelevantStorageChannelTypes(); - - public void setFilterTemplates(final Set templates) { - filter.setTemplates(templates); + public void setFilters(final Set filters) { + filter.setFilters(filters); } - public void setNormalizer(final UnaryOperator normalizer) { + public void setNormalizer(final UnaryOperator normalizer) { filter.setNormalizer(normalizer); } } diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/StorageConfiguration.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/StorageConfiguration.java index 489852874..9647a18e8 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/StorageConfiguration.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/StorageConfiguration.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.api.network.node; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; import com.refinedmods.refinedstorage2.api.storage.AccessMode; import com.refinedmods.refinedstorage2.api.storage.composite.Priority; @@ -14,7 +15,7 @@ public interface StorageConfiguration extends Priority { FilterMode getFilterMode(); - boolean isAllowed(Object resource); + boolean isAllowed(ResourceKey resource); void setFilterMode(FilterMode filterMode); diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/exporter/ExporterTransferStrategy.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/exporter/ExporterTransferStrategy.java index 233cd7745..931008d22 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/exporter/ExporterTransferStrategy.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/exporter/ExporterTransferStrategy.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.api.network.node.exporter; import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import org.apiguardian.api.API; @@ -10,5 +11,5 @@ */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.4") public interface ExporterTransferStrategy { - boolean transfer(Object resource, Actor actor, Network network); + boolean transfer(ResourceKey resource, Actor actor, Network network); } diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/externalstorage/ExternalStorageProviderFactory.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/externalstorage/ExternalStorageProviderFactory.java index 306f055ea..8b1f3dc98 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/externalstorage/ExternalStorageProviderFactory.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/externalstorage/ExternalStorageProviderFactory.java @@ -1,6 +1,5 @@ package com.refinedmods.refinedstorage2.api.network.node.externalstorage; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.api.storage.external.ExternalStorageProvider; import java.util.Optional; @@ -8,15 +7,14 @@ import org.apiguardian.api.API; /** - * Provides the external storage with an {@link ExternalStorageProvider} for a given {@link StorageChannelType}. + * Provides the {@link com.refinedmods.refinedstorage2.api.storage.external.ExternalStorage} + * with an {@link ExternalStorageProvider}. */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.4") @FunctionalInterface public interface ExternalStorageProviderFactory { /** - * @param channelType the channel type - * @param the resource type - * @return the external storage provider + * @return the external storage provider, if present */ - Optional> create(StorageChannelType channelType); + Optional create(); } diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterSource.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterSource.java index 24ed983b0..a2fff4aa8 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterSource.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterSource.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage2.api.network.node.importer; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.ExtractableStorage; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; @@ -13,13 +14,11 @@ * for insertion into the target network. * A valid source for the importer needs to be a {@link InsertableStorage} as well, so that transfers that end up * failing can be given back to the source. - * - * @param the resource type */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.1") -public interface ImporterSource extends ExtractableStorage, InsertableStorage { +public interface ImporterSource extends ExtractableStorage, InsertableStorage { /** * @return the resources that this source has */ - Iterator getResources(); + Iterator getResources(); } diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterTransferStrategy.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterTransferStrategy.java index 68406d6ee..e1a035e3c 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterTransferStrategy.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterTransferStrategy.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.api.network.node.importer; -import com.refinedmods.refinedstorage2.api.core.filter.Filter; import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.resource.filter.Filter; import com.refinedmods.refinedstorage2.api.storage.Actor; import org.apiguardian.api.API; diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterTransferStrategyImpl.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterTransferStrategyImpl.java index 9d7dd1bfa..4a9e15a64 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterTransferStrategyImpl.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterTransferStrategyImpl.java @@ -1,12 +1,12 @@ package com.refinedmods.refinedstorage2.api.network.node.importer; -import com.refinedmods.refinedstorage2.api.core.filter.Filter; import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; +import com.refinedmods.refinedstorage2.api.resource.filter.Filter; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.TransferHelper; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import java.util.Iterator; import java.util.Objects; @@ -14,33 +14,27 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.1") -public class ImporterTransferStrategyImpl implements ImporterTransferStrategy { - private final ImporterSource source; - private final StorageChannelType storageChannelType; +public class ImporterTransferStrategyImpl implements ImporterTransferStrategy { + private final ImporterSource source; private final long transferQuota; - public ImporterTransferStrategyImpl(final ImporterSource source, - final StorageChannelType storageChannelType, - final long transferQuota) { + public ImporterTransferStrategyImpl(final ImporterSource source, final long transferQuota) { this.source = source; - this.storageChannelType = storageChannelType; this.transferQuota = transferQuota; } @Override public boolean transfer(final Filter filter, final Actor actor, final Network network) { - final StorageChannel storageChannel = network - .getComponent(StorageNetworkComponent.class) - .getStorageChannel(storageChannelType); + final StorageChannel storageChannel = network.getComponent(StorageNetworkComponent.class); return transfer(filter, actor, storageChannel); } - private boolean transfer(final Filter filter, final Actor actor, final StorageChannel storageChannel) { + private boolean transfer(final Filter filter, final Actor actor, final StorageChannel storageChannel) { long totalTransferred = 0; - T workingResource = null; - final Iterator iterator = source.getResources(); + ResourceKey workingResource = null; + final Iterator iterator = source.getResources(); while (iterator.hasNext() && totalTransferred < transferQuota) { - final T resource = iterator.next(); + final ResourceKey resource = iterator.next(); if (workingResource != null) { totalTransferred += performTransfer(storageChannel, actor, totalTransferred, workingResource, resource); } else if (filter.isAllowed(resource)) { @@ -54,21 +48,21 @@ private boolean transfer(final Filter filter, final Actor actor, final StorageCh return totalTransferred > 0; } - private long performTransfer(final StorageChannel storageChannel, + private long performTransfer(final StorageChannel storageChannel, final Actor actor, final long totalTransferred, - final T workingResource, - final T resource) { + final ResourceKey workingResource, + final ResourceKey resource) { if (Objects.equals(workingResource, resource)) { return performTransfer(storageChannel, actor, totalTransferred, resource); } return 0L; } - private long performTransfer(final StorageChannel storageChannel, + private long performTransfer(final StorageChannel storageChannel, final Actor actor, final long totalTransferred, - final T resource) { + final ResourceKey resource) { return TransferHelper.transfer( resource, transferQuota - totalTransferred, diff --git a/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/NetworkTestExtension.java b/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/NetworkTestExtension.java index 134fd5891..b3ba7aba9 100644 --- a/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/NetworkTestExtension.java +++ b/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/NetworkTestExtension.java @@ -193,11 +193,10 @@ public Object resolveParameter(final ParameterContext parameterContext, .orElseThrow(); } - private StorageChannel getNetworkStorageChannel(final String networkId) { + private StorageChannel getNetworkStorageChannel(final String networkId) { return networkMap .get(networkId) - .getComponent(StorageNetworkComponent.class) - .getStorageChannel(NetworkTestFixtures.STORAGE_CHANNEL_TYPE); + .getComponent(StorageNetworkComponent.class); } private EnergyNetworkComponent getNetworkEnergy(final String networkId) { diff --git a/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/NetworkTestFixtures.java b/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/NetworkTestFixtures.java index 122c7e57c..f0ffcc3a5 100644 --- a/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/NetworkTestFixtures.java +++ b/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/NetworkTestFixtures.java @@ -9,14 +9,8 @@ import com.refinedmods.refinedstorage2.api.network.impl.component.EnergyNetworkComponentImpl; import com.refinedmods.refinedstorage2.api.network.impl.component.GraphNetworkComponentImpl; import com.refinedmods.refinedstorage2.api.network.impl.component.StorageNetworkComponentImpl; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelImpl; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; - -import java.util.Set; public final class NetworkTestFixtures { - public static final StorageChannelType STORAGE_CHANNEL_TYPE = StorageChannelImpl::new; - public static final Set> STORAGE_CHANNEL_TYPES = Set.of(STORAGE_CHANNEL_TYPE); public static final ComponentMapFactory NETWORK_COMPONENT_MAP_FACTORY = new ComponentMapFactory<>(); @@ -31,7 +25,7 @@ public final class NetworkTestFixtures { ); NETWORK_COMPONENT_MAP_FACTORY.addFactory( StorageNetworkComponent.class, - network -> new StorageNetworkComponentImpl(STORAGE_CHANNEL_TYPES) + network -> new StorageNetworkComponentImpl() ); } diff --git a/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/TestResource.java b/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/TestResource.java new file mode 100644 index 000000000..d5fa8fd57 --- /dev/null +++ b/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/TestResource.java @@ -0,0 +1,13 @@ +package com.refinedmods.refinedstorage2.network.test; + +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; + +public enum TestResource implements ResourceKey { + A, + A_ALTERNATIVE, + A_ALTERNATIVE2, + B, + B_ALTERNATIVE, + C, + D +} diff --git a/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/nodefactory/ExternalStorageNetworkNodeFactory.java b/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/nodefactory/ExternalStorageNetworkNodeFactory.java index f4038d2c6..363df863b 100644 --- a/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/nodefactory/ExternalStorageNetworkNodeFactory.java +++ b/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/nodefactory/ExternalStorageNetworkNodeFactory.java @@ -1,29 +1,19 @@ package com.refinedmods.refinedstorage2.network.test.nodefactory; import com.refinedmods.refinedstorage2.api.network.impl.node.externalstorage.ExternalStorageNetworkNode; -import com.refinedmods.refinedstorage2.api.network.impl.node.externalstorage.TrackedStorageRepositoryProvider; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.api.storage.tracked.InMemoryTrackedStorageRepository; -import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedStorageRepository; import com.refinedmods.refinedstorage2.network.test.AddNetworkNode; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import java.util.Map; public class ExternalStorageNetworkNodeFactory extends AbstractNetworkNodeFactory { @Override protected ExternalStorageNetworkNode innerCreate(final AddNetworkNode ctx, final Map properties) { - final ExternalStorageNetworkNode node = new ExternalStorageNetworkNode(getEnergyUsage(properties)); - node.initialize( - NetworkTestFixtures.STORAGE_CHANNEL_TYPES, - () -> 0L, - new TrackedStorageRepositoryProvider() { - @Override - public TrackedStorageRepository getRepository(final StorageChannelType type) { - return new InMemoryTrackedStorageRepository<>(); - } - } + final ExternalStorageNetworkNode externalStorage = new ExternalStorageNetworkNode( + getEnergyUsage(properties), + () -> 0L ); - return node; + externalStorage.setTrackingRepository(new InMemoryTrackedStorageRepository()); + return externalStorage; } } diff --git a/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/nodefactory/MultiStorageNetworkNodeFactory.java b/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/nodefactory/MultiStorageNetworkNodeFactory.java index fb8194f0d..bc35dea09 100644 --- a/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/nodefactory/MultiStorageNetworkNodeFactory.java +++ b/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/nodefactory/MultiStorageNetworkNodeFactory.java @@ -2,7 +2,6 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.multistorage.MultiStorageNetworkNode; import com.refinedmods.refinedstorage2.network.test.AddNetworkNode; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import java.util.Map; @@ -17,7 +16,6 @@ protected MultiStorageNetworkNode innerCreate(final AddNetworkNode ctx, final Ma return new MultiStorageNetworkNode( getEnergyUsage(properties), energyUsagePerStorage, - NetworkTestFixtures.STORAGE_CHANNEL_TYPES, size ); } diff --git a/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/nodefactory/StorageNetworkNodeFactory.java b/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/nodefactory/StorageNetworkNodeFactory.java index dc61a2a6a..d7c3c9d1f 100644 --- a/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/nodefactory/StorageNetworkNodeFactory.java +++ b/refinedstorage2-network-test/src/main/java/com/refinedmods/refinedstorage2/network/test/nodefactory/StorageNetworkNodeFactory.java @@ -2,16 +2,12 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.storage.StorageNetworkNode; import com.refinedmods.refinedstorage2.network.test.AddNetworkNode; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import java.util.Map; -public class StorageNetworkNodeFactory extends AbstractNetworkNodeFactory> { +public class StorageNetworkNodeFactory extends AbstractNetworkNodeFactory { @Override - protected StorageNetworkNode innerCreate(final AddNetworkNode ctx, final Map properties) { - return new StorageNetworkNode<>( - getEnergyUsage(properties), - NetworkTestFixtures.STORAGE_CHANNEL_TYPE - ); + protected StorageNetworkNode innerCreate(final AddNetworkNode ctx, final Map properties) { + return new StorageNetworkNode(getEnergyUsage(properties)); } } diff --git a/refinedstorage2-network-test/src/test/java/com/refinedmods/refinedstorage2/network/test/NetworkNodeFactoryTest.java b/refinedstorage2-network-test/src/test/java/com/refinedmods/refinedstorage2/network/test/NetworkNodeFactoryTest.java index 580bb60f2..baf5f2079 100644 --- a/refinedstorage2-network-test/src/test/java/com/refinedmods/refinedstorage2/network/test/NetworkNodeFactoryTest.java +++ b/refinedstorage2-network-test/src/test/java/com/refinedmods/refinedstorage2/network/test/NetworkNodeFactoryTest.java @@ -31,7 +31,7 @@ class NetworkNodeFactoryTest { @AddNetworkNode SimpleNetworkNode simple; @AddNetworkNode - StorageNetworkNode storage; + StorageNetworkNode storage; @AddNetworkNode InterfaceNetworkNode interfaceNode; @AddNetworkNode diff --git a/refinedstorage2-network-test/src/test/java/com/refinedmods/refinedstorage2/network/test/NetworkTestExtensionTest.java b/refinedstorage2-network-test/src/test/java/com/refinedmods/refinedstorage2/network/test/NetworkTestExtensionTest.java index fdc23d6d2..45af0666f 100644 --- a/refinedstorage2-network-test/src/test/java/com/refinedmods/refinedstorage2/network/test/NetworkTestExtensionTest.java +++ b/refinedstorage2-network-test/src/test/java/com/refinedmods/refinedstorage2/network/test/NetworkTestExtensionTest.java @@ -36,7 +36,7 @@ class NetworkTestExtensionTest { @AddNetworkNode(networkId = "a", properties = { @AddNetworkNode.Property(key = AbstractNetworkNodeFactory.PROPERTY_ENERGY_USAGE, longValue = 10) }) - StorageNetworkNode storageInA; + StorageNetworkNode storageInA; @AddNetworkNode(networkId = "b", properties = { @AddNetworkNode.Property(key = AbstractNetworkNodeFactory.PROPERTY_ACTIVE, boolValue = false) @@ -107,16 +107,12 @@ void shouldAddNetworkNodeToGraph() { @Test void shouldInjectStorageChannel( - @InjectNetworkStorageChannel(networkId = "a") final StorageChannel storageChannelA, - @InjectNetworkStorageChannel(networkId = "b") final StorageChannel storageChannelB + @InjectNetworkStorageChannel(networkId = "a") final StorageChannel storageChannelA, + @InjectNetworkStorageChannel(networkId = "b") final StorageChannel storageChannelB ) { // Assert - assertThat(storageChannelA).isSameAs( - a.getComponent(StorageNetworkComponent.class) - .getStorageChannel(NetworkTestFixtures.STORAGE_CHANNEL_TYPE)); - assertThat(storageChannelB).isSameAs( - b.getComponent(StorageNetworkComponent.class) - .getStorageChannel(NetworkTestFixtures.STORAGE_CHANNEL_TYPE)); + assertThat(storageChannelA).isSameAs(a.getComponent(StorageNetworkComponent.class)); + assertThat(storageChannelB).isSameAs(b.getComponent(StorageNetworkComponent.class)); } @Test @@ -146,7 +142,7 @@ class NestedTest { Network nestedNetwork; @AddNetworkNode(networkId = "a") - StorageNetworkNode nodeInA; + StorageNetworkNode nodeInA; @Test void testNestedNetworkAndNestedNetworkNode() { diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/component/StorageNetworkComponentImpl.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/component/StorageNetworkComponentImpl.java index 0b59cc7e6..12c16a5d7 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/component/StorageNetworkComponentImpl.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/component/StorageNetworkComponentImpl.java @@ -3,104 +3,50 @@ import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; import com.refinedmods.refinedstorage2.api.network.component.StorageProvider; import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; +import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.Storage; import com.refinedmods.refinedstorage2.api.storage.TrackedResourceAmount; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; +import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelImpl; -import java.util.Collection; import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class StorageNetworkComponentImpl implements StorageNetworkComponent { +public class StorageNetworkComponentImpl extends StorageChannelImpl implements StorageNetworkComponent { private static final Logger LOGGER = LoggerFactory.getLogger(StorageNetworkComponentImpl.class); - private final Map, StorageChannel> channels; + public StorageNetworkComponentImpl() { + } - public StorageNetworkComponentImpl(final Collection> storageChannelTypes) { - this.channels = storageChannelTypes.stream().collect(Collectors.toUnmodifiableMap( - type -> type, - StorageChannelType::create - )); + protected StorageNetworkComponentImpl(final ResourceList list) { + super(list); } @Override - @SuppressWarnings({"rawtypes", "unchecked"}) public void onContainerAdded(final NetworkNodeContainer container) { if (container.getNode() instanceof StorageProvider provider) { - for (final Map.Entry, StorageChannel> entry : channels.entrySet()) { - tryAddStorageFromProviderToChannel(provider, (StorageChannelType) entry.getKey(), entry.getValue()); - } + final Storage storage = provider.getStorage(); + LOGGER.debug("Adding source {} from provider {}", storage, provider); + addSource(storage); } } - private void tryAddStorageFromProviderToChannel(final StorageProvider provider, - final StorageChannelType type, - final StorageChannel channel) { - provider.getStorageForChannel(type).ifPresent(storage -> { - LOGGER.debug("Adding source {} to channel {} from provider {}", storage, type, provider); - channel.addSource(storage); - }); - } - @Override - @SuppressWarnings({"rawtypes", "unchecked"}) public void onContainerRemoved(final NetworkNodeContainer container) { if (container.getNode() instanceof StorageProvider provider) { - for (final Map.Entry, StorageChannel> entry : channels.entrySet()) { - final StorageChannelType storageChannelType = entry.getKey(); - final StorageChannel storageChannel = entry.getValue(); - tryRemoveStorageFromProviderFromChannel(provider, storageChannelType, storageChannel); - } - } - } - - private void tryRemoveStorageFromProviderFromChannel(final StorageProvider provider, - final StorageChannelType type, - final StorageChannel channel) { - provider.getStorageForChannel(type).ifPresent(storage -> { - LOGGER.debug("Removing source {} from channel {} of provider {}", storage, type, provider); - channel.removeSource(storage); - }); - } - - @SuppressWarnings("unchecked") - @Override - public StorageChannel getStorageChannel(final StorageChannelType type) { - return (StorageChannel) channels.get(type); - } - - @Override - public Set> getStorageChannelTypes() { - return channels.keySet(); - } - - @Override - @SuppressWarnings({"unchecked", "rawtypes"}) - public boolean hasSource(final Predicate> matcher) { - for (final Map.Entry, StorageChannel> entry : channels.entrySet()) { - final StorageChannel storageChannel = entry.getValue(); - if (storageChannel.hasSource(matcher)) { - return true; - } + final Storage storage = provider.getStorage(); + LOGGER.debug("Removing source {} of provider {}", storage, provider); + removeSource(storage); } - return false; } @Override - public List> getResources(final StorageChannelType type, - final Class actorType) { - final StorageChannel storageChannel = getStorageChannel(type); - return storageChannel.getAll().stream().map(resourceAmount -> new TrackedResourceAmount<>( + public List getResources(final Class actorType) { + return getAll().stream().map(resourceAmount -> new TrackedResourceAmount( resourceAmount, - storageChannel.findTrackedResourceByActorType(resourceAmount.getResource(), actorType).orElse(null) + findTrackedResourceByActorType(resourceAmount.getResource(), actorType).orElse(null) )).toList(); } } diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/AbstractDetectorAmountStrategy.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/AbstractDetectorAmountStrategy.java index 8d099242c..0266f5c37 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/AbstractDetectorAmountStrategy.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/AbstractDetectorAmountStrategy.java @@ -2,11 +2,10 @@ import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; public abstract class AbstractDetectorAmountStrategy implements DetectorAmountStrategy { - protected StorageChannel getStorageChannel(final Network network, final ResourceTemplate template) { - return network.getComponent(StorageNetworkComponent.class).getStorageChannel(template.storageChannelType()); + protected StorageChannel getStorageChannel(final Network network) { + return network.getComponent(StorageNetworkComponent.class); } } diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/DetectorAmountStrategy.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/DetectorAmountStrategy.java index 378223b7f..931249e0b 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/DetectorAmountStrategy.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/DetectorAmountStrategy.java @@ -1,8 +1,8 @@ package com.refinedmods.refinedstorage2.api.network.impl.node.detector; import com.refinedmods.refinedstorage2.api.network.Network; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; public interface DetectorAmountStrategy { - long getAmount(Network network, ResourceTemplate template); + long getAmount(Network network, ResourceKey configuredResource); } diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/DetectorAmountStrategyImpl.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/DetectorAmountStrategyImpl.java index 131596c1c..02ad3a74d 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/DetectorAmountStrategyImpl.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/DetectorAmountStrategyImpl.java @@ -2,13 +2,13 @@ import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; public class DetectorAmountStrategyImpl extends AbstractDetectorAmountStrategy { @Override - public long getAmount(final Network network, final ResourceTemplate template) { - return getStorageChannel(network, template) - .get(template.resource()) + public long getAmount(final Network network, final ResourceKey configuredResource) { + return getStorageChannel(network) + .get(configuredResource) .map(ResourceAmount::getAmount) .orElse(0L); } diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/DetectorNetworkNode.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/DetectorNetworkNode.java index 14d56f74c..73dff0160 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/DetectorNetworkNode.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/DetectorNetworkNode.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.api.network.impl.node.detector; import com.refinedmods.refinedstorage2.api.network.node.AbstractNetworkNode; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import javax.annotation.Nullable; @@ -11,7 +11,7 @@ public class DetectorNetworkNode extends AbstractNetworkNode { private long amount; private DetectorMode mode = DetectorMode.EQUAL; @Nullable - private ResourceTemplate template; + private ResourceKey configuredResource; @Nullable private DetectorAmountStrategy amountStrategy; @@ -24,8 +24,8 @@ public long getEnergyUsage() { return energyUsage; } - public void setFilterTemplate(@Nullable final ResourceTemplate filterTemplate) { - this.template = filterTemplate; + public void setConfiguredResource(@Nullable final ResourceKey configuredResource) { + this.configuredResource = configuredResource; } public DetectorMode getMode() { @@ -49,10 +49,10 @@ public void setAmountStrategy(@Nullable final DetectorAmountStrategy amountStrat } public boolean isActivated() { - if (template == null || network == null || !isActive() || amountStrategy == null) { + if (configuredResource == null || network == null || !isActive() || amountStrategy == null) { return false; } - final long amountInNetwork = amountStrategy.getAmount(network, template); + final long amountInNetwork = amountStrategy.getAmount(network, configuredResource); return switch (mode) { case UNDER -> amountInNetwork < amount; case EQUAL -> amountInNetwork == amount; diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/CompositeExporterTransferStrategy.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/CompositeExporterTransferStrategy.java index b110f704f..fccf71623 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/CompositeExporterTransferStrategy.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/CompositeExporterTransferStrategy.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.node.exporter.ExporterTransferStrategy; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import java.util.List; @@ -14,7 +15,7 @@ public CompositeExporterTransferStrategy(final List st } @Override - public boolean transfer(final Object resource, final Actor actor, final Network network) { + public boolean transfer(final ResourceKey resource, final Actor actor, final Network network) { for (final ExporterTransferStrategy strategy : strategies) { if (strategy.transfer(resource, actor, network)) { return true; diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/ExporterNetworkNode.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/ExporterNetworkNode.java index 8cdb29c10..9db98bc38 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/ExporterNetworkNode.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/ExporterNetworkNode.java @@ -6,6 +6,7 @@ import com.refinedmods.refinedstorage2.api.network.node.exporter.ExporterTransferStrategy; import com.refinedmods.refinedstorage2.api.network.node.task.Task; import com.refinedmods.refinedstorage2.api.network.node.task.TaskExecutor; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import java.util.ArrayList; @@ -43,9 +44,9 @@ public void doWork() { taskExecutor.execute(tasks, context); } - public void setFilterTemplates(final List templates) { + public void setFilters(final List filters) { tasks.clear(); - tasks.addAll(templates.stream().map(TaskImpl::new).toList()); + tasks.addAll(filters.stream().map(TaskImpl::new).toList()); } public void setEnergyUsage(final long energyUsage) { @@ -61,10 +62,10 @@ public record TaskContext(Network network, Actor actor) { } class TaskImpl implements Task { - private final Object template; + private final ResourceKey filter; - TaskImpl(final Object template) { - this.template = template; + TaskImpl(final ResourceKey filter) { + this.filter = filter; } @Override @@ -72,7 +73,7 @@ public boolean run(final TaskContext context) { if (transferStrategy == null) { return false; } - return transferStrategy.transfer(template, context.actor, context.network); + return transferStrategy.transfer(filter, context.actor, context.network); } } } diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/AbstractExporterTransferStrategy.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/ExporterTransferStrategyImpl.java similarity index 50% rename from refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/AbstractExporterTransferStrategy.java rename to refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/ExporterTransferStrategyImpl.java index 7aa3785b0..587f0201f 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/AbstractExporterTransferStrategy.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/ExporterTransferStrategyImpl.java @@ -3,61 +3,44 @@ import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; import com.refinedmods.refinedstorage2.api.network.node.exporter.ExporterTransferStrategy; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; import com.refinedmods.refinedstorage2.api.storage.TransferHelper; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import java.util.Collection; import java.util.Collections; -import javax.annotation.Nullable; -public abstract class AbstractExporterTransferStrategy implements ExporterTransferStrategy { - private final InsertableStorage destination; - private final StorageChannelType storageChannelType; +public class ExporterTransferStrategyImpl implements ExporterTransferStrategy { + private final InsertableStorage destination; private final long transferQuota; - protected AbstractExporterTransferStrategy(final InsertableStorage destination, - final StorageChannelType storageChannelType, - final long transferQuota) { + public ExporterTransferStrategyImpl(final InsertableStorage destination, final long transferQuota) { this.destination = destination; - this.storageChannelType = storageChannelType; this.transferQuota = transferQuota; } - @Nullable - protected abstract T tryConvert(Object resource); - /** * @param resource the resource to expand * @param storageChannel the storage channel belonging to the resource * @return the list of expanded resources, will be tried out in the order of the list. Can be empty. */ - protected Collection expand(final T resource, final StorageChannel storageChannel) { + protected Collection expand(final ResourceKey resource, final StorageChannel storageChannel) { return Collections.singletonList(resource); } @Override - public boolean transfer(final Object resource, final Actor actor, final Network network) { - final T converted = tryConvert(resource); - if (converted == null) { - return false; - } - return tryTransferConverted(converted, actor, network); - } - - private boolean tryTransferConverted(final T converted, final Actor actor, final Network network) { - final StorageChannel storageChannel = network.getComponent(StorageNetworkComponent.class) - .getStorageChannel(storageChannelType); - final Collection expanded = expand(converted, storageChannel); + public boolean transfer(final ResourceKey resource, final Actor actor, final Network network) { + final StorageChannel storageChannel = network.getComponent(StorageNetworkComponent.class); + final Collection expanded = expand(resource, storageChannel); return tryTransferExpanded(actor, storageChannel, expanded); } private boolean tryTransferExpanded(final Actor actor, - final StorageChannel storageChannel, - final Collection expanded) { - for (final T resource : expanded) { + final StorageChannel storageChannel, + final Collection expanded) { + for (final ResourceKey resource : expanded) { if (tryTransfer(actor, storageChannel, resource)) { return true; } @@ -65,7 +48,7 @@ private boolean tryTransferExpanded(final Actor actor, return false; } - private boolean tryTransfer(final Actor actor, final StorageChannel storageChannel, final T resource) { + private boolean tryTransfer(final Actor actor, final StorageChannel storageChannel, final ResourceKey resource) { final long transferred = TransferHelper.transfer( resource, transferQuota, diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/ExposedExternalStorage.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/ExposedExternalStorage.java index d30c56ba2..438534771 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/ExposedExternalStorage.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/ExposedExternalStorage.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage2.api.network.node.AbstractConfiguredProxyStorage; import com.refinedmods.refinedstorage2.api.network.node.StorageConfiguration; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.composite.CompositeAwareChild; import com.refinedmods.refinedstorage2.api.storage.composite.ConsumingStorage; @@ -19,23 +20,25 @@ import java.util.function.LongSupplier; import javax.annotation.Nullable; -public class ExposedExternalStorage extends AbstractConfiguredProxyStorage> - implements ConsumingStorage, CompositeAwareChild, TrackedStorage, ExternalStorageListener { - private final Set> parents = new HashSet<>(); - private final TrackedStorageRepository trackingRepository; +public class ExposedExternalStorage extends AbstractConfiguredProxyStorage + implements ConsumingStorage, CompositeAwareChild, TrackedStorage, ExternalStorageListener { + private final Set parents = new HashSet<>(); private final LongSupplier clock; + @Nullable + private TrackedStorageRepository trackingRepository; - ExposedExternalStorage(final StorageConfiguration config, - final TrackedStorageRepository trackingRepository, - final LongSupplier clock) { + ExposedExternalStorage(final StorageConfiguration config, final LongSupplier clock) { super(config); - this.trackingRepository = trackingRepository; this.clock = clock; } + void setTrackingRepository(final TrackedStorageRepository trackingRepository) { + this.trackingRepository = trackingRepository; + } + @Nullable - public ExternalStorageProvider getExternalStorageProvider() { - final ExternalStorage delegate = getUnsafeDelegate(); + public ExternalStorageProvider getExternalStorageProvider() { + final ExternalStorage delegate = getUnsafeDelegate(); if (delegate == null) { return null; } @@ -43,25 +46,25 @@ public ExternalStorageProvider getExternalStorageProvider() { } @Override - public void onAddedIntoComposite(final ParentComposite parentComposite) { + public void onAddedIntoComposite(final ParentComposite parentComposite) { parents.add(parentComposite); - final ExternalStorage delegate = getUnsafeDelegate(); + final ExternalStorage delegate = getUnsafeDelegate(); if (delegate != null) { delegate.onAddedIntoComposite(parentComposite); } } @Override - public void onRemovedFromComposite(final ParentComposite parentComposite) { + public void onRemovedFromComposite(final ParentComposite parentComposite) { parents.remove(parentComposite); - final ExternalStorage delegate = getUnsafeDelegate(); + final ExternalStorage delegate = getUnsafeDelegate(); if (delegate != null) { delegate.onRemovedFromComposite(parentComposite); } } @Override - public void setDelegate(final ExternalStorage newDelegate) { + public void setDelegate(final ExternalStorage newDelegate) { super.setDelegate(newDelegate); parents.forEach(parent -> { parent.onSourceAddedToChild(newDelegate); @@ -71,7 +74,7 @@ public void setDelegate(final ExternalStorage newDelegate) { @Override public void clearDelegate() { - final ExternalStorage delegate = getDelegate(); + final ExternalStorage delegate = getDelegate(); parents.forEach(parent -> { parent.onSourceRemovedFromChild(delegate); delegate.onRemovedFromComposite(parent); @@ -80,7 +83,7 @@ public void clearDelegate() { } public boolean detectChanges() { - final ExternalStorage delegate = getUnsafeDelegate(); + final ExternalStorage delegate = getUnsafeDelegate(); if (delegate == null) { return false; } @@ -88,13 +91,19 @@ public boolean detectChanges() { } @Override - public Optional findTrackedResourceByActorType(final T resource, + public Optional findTrackedResourceByActorType(final ResourceKey resource, final Class actorType) { + if (trackingRepository == null) { + return Optional.empty(); + } return trackingRepository.findTrackedResourceByActorType(resource, actorType); } @Override - public void beforeDetectChanges(final T resource, final Actor actor) { + public void beforeDetectChanges(final ResourceKey resource, final Actor actor) { + if (trackingRepository == null) { + return; + } trackingRepository.update(resource, actor, clock.getAsLong()); } } diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/ExternalStorageNetworkNode.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/ExternalStorageNetworkNode.java index 892b876b3..3b5298ffb 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/ExternalStorageNetworkNode.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/ExternalStorageNetworkNode.java @@ -4,51 +4,33 @@ import com.refinedmods.refinedstorage2.api.network.node.AbstractStorageNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.externalstorage.ExternalStorageProviderFactory; import com.refinedmods.refinedstorage2.api.storage.Storage; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.api.storage.external.ExternalStorage; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedStorageRepository; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Optional; -import java.util.Set; import java.util.function.LongSupplier; -import java.util.stream.Collectors; import javax.annotation.Nullable; public class ExternalStorageNetworkNode extends AbstractStorageNetworkNode implements StorageProvider { private final long energyUsage; - private Map, DynamicStorage> storages = Collections.emptyMap(); + private final ExposedExternalStorage storage; + @Nullable + private ExternalStorage externalStorage; - public ExternalStorageNetworkNode(final long energyUsage) { + public ExternalStorageNetworkNode(final long energyUsage, final LongSupplier clock) { this.energyUsage = energyUsage; + this.storage = new ExposedExternalStorage(this, clock); } - public void initialize(final Collection> storageChannelTypes, - final LongSupplier clock, - final TrackedStorageRepositoryProvider trackedStorageRepositoryProvider) { - this.storages = storageChannelTypes.stream().collect(Collectors.toUnmodifiableMap( - type -> type, - type -> new DynamicStorage<>(trackedStorageRepositoryProvider.getRepository(type), clock) - )); + public void setTrackingRepository(final TrackedStorageRepository trackingRepository) { + storage.setTrackingRepository(trackingRepository); } - @SuppressWarnings({"unchecked", "rawtypes"}) public void initialize(final ExternalStorageProviderFactory factory) { - storages.forEach((type, storage) -> { - storage.exposedStorage.tryClearDelegate(); - initialize(factory, (StorageChannelType) type, storage); - }); - } - - private void initialize(final ExternalStorageProviderFactory factory, - final StorageChannelType type, - final DynamicStorage dynamicStorage) { - factory.create(type).ifPresent(provider -> { - dynamicStorage.internalStorage = new ExternalStorage<>(provider, dynamicStorage.exposedStorage); + storage.tryClearDelegate(); + factory.create().ifPresent(provider -> { + this.externalStorage = new ExternalStorage(provider, storage); if (isActive()) { - dynamicStorage.setVisible(true); + setVisible(true); } }); } @@ -56,11 +38,11 @@ private void initialize(final ExternalStorageProviderFactory factory, @Override protected void onActiveChanged(final boolean newActive) { super.onActiveChanged(newActive); - storages.values().forEach(storage -> storage.setVisible(newActive)); + setVisible(newActive); } public boolean detectChanges() { - return storages.values().stream().anyMatch(storage -> storage.exposedStorage.detectChanges()); + return storage.detectChanges(); } @Override @@ -69,47 +51,18 @@ public long getEnergyUsage() { } @Override - protected Set> getRelevantStorageChannelTypes() { - return storages.keySet(); - } - - @Override - @SuppressWarnings("unchecked") - public Optional> getStorageForChannel(final StorageChannelType channelType) { - final DynamicStorage storage = storages.get(channelType); - if (storage == null) { - return Optional.empty(); - } - return Optional.of((Storage) storage.exposedStorage); + public Storage getStorage() { + return storage; } - private class DynamicStorage { - private final ExposedExternalStorage exposedStorage; - @Nullable - private ExternalStorage internalStorage; - - private DynamicStorage(final TrackedStorageRepository trackingRepository, - final LongSupplier clock) { - this.exposedStorage = new ExposedExternalStorage<>( - ExternalStorageNetworkNode.this, - trackingRepository, - clock - ); - } - - public void setVisible(final boolean visible) { - if (visible) { - tryMakeInternalStorageVisible(); - } else { - exposedStorage.tryClearDelegate(); - } - } - - private void tryMakeInternalStorageVisible() { - if (internalStorage == null) { + private void setVisible(final boolean visible) { + if (visible) { + if (externalStorage == null) { return; } - exposedStorage.setDelegate(internalStorage); + storage.setDelegate(externalStorage); + } else { + storage.tryClearDelegate(); } } } diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/TrackedStorageRepositoryProvider.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/TrackedStorageRepositoryProvider.java deleted file mode 100644 index 9532f0409..000000000 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/TrackedStorageRepositoryProvider.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.refinedmods.refinedstorage2.api.network.impl.node.externalstorage; - -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; -import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedStorageRepository; - -@FunctionalInterface -public interface TrackedStorageRepositoryProvider { - TrackedStorageRepository getRepository(StorageChannelType type); -} diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/InterfaceExportState.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/InterfaceExportState.java index e9b6f0def..17a48ff1a 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/InterfaceExportState.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/InterfaceExportState.java @@ -1,9 +1,8 @@ package com.refinedmods.refinedstorage2.api.network.impl.node.iface; import com.refinedmods.refinedstorage2.api.core.Action; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import java.util.Collection; import javax.annotation.Nullable; @@ -11,28 +10,27 @@ public interface InterfaceExportState { int getSlots(); - Collection expandExportCandidates(StorageChannel storageChannel, T resource); + Collection expandExportCandidates(StorageChannel storageChannel, ResourceKey resource); - boolean isExportedResourceValid(ResourceTemplate want, - ResourceTemplate got); + boolean isExportedResourceValid(ResourceKey want, ResourceKey got); @Nullable - ResourceTemplate getRequestedResource(int slotIndex); + ResourceKey getRequestedResource(int slotIndex); long getRequestedAmount(int slotIndex); @Nullable - ResourceTemplate getExportedResource(int slotIndex); + ResourceKey getExportedResource(int slotIndex); long getExportedAmount(int slotIndex); - void setExportSlot(int slotIndex, ResourceTemplate resource, long amount); + void setExportSlot(int slotIndex, ResourceKey resource, long amount); void shrinkExportedAmount(int slotIndex, long amount); void growExportedAmount(int slotIndex, long amount); - long insert(StorageChannelType storageChannelType, T resource, long amount, Action action); + long insert(ResourceKey resource, long amount, Action action); - long extract(T resource, long amount, Action action); + long extract(ResourceKey resource, long amount, Action action); } diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/InterfaceNetworkNode.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/InterfaceNetworkNode.java index b5a5ee6b0..732a0b3cd 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/InterfaceNetworkNode.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/InterfaceNetworkNode.java @@ -6,8 +6,8 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.iface.externalstorage.InterfaceExternalStorageProvider; import com.refinedmods.refinedstorage2.api.network.node.AbstractNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.NetworkNodeActor; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.api.storage.Storage; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; @@ -20,13 +20,13 @@ public class InterfaceNetworkNode extends AbstractNetworkNode { private final Actor actor = new NetworkNodeActor(this); @Nullable private InterfaceExportState exportState; - private ToLongFunction> transferQuotaProvider = resourceTemplate -> Long.MAX_VALUE; + private ToLongFunction transferQuotaProvider = resource -> Long.MAX_VALUE; public InterfaceNetworkNode(final long energyUsage) { this.energyUsage = energyUsage; } - public void setTransferQuotaProvider(final ToLongFunction> transferQuotaProvider) { + public void setTransferQuotaProvider(final ToLongFunction transferQuotaProvider) { this.transferQuotaProvider = transferQuotaProvider; } @@ -39,9 +39,9 @@ public boolean isActingAsExternalStorage() { ); } - private boolean isStorageAnExternalStorageProviderThatReferencesMe(final Storage storage) { - return storage instanceof ExposedExternalStorage proxy - && proxy.getExternalStorageProvider() instanceof InterfaceExternalStorageProvider interfaceProvider + private boolean isStorageAnExternalStorageProviderThatReferencesMe(final Storage storage) { + return storage instanceof ExposedExternalStorage proxy + && proxy.getExternalStorageProvider() instanceof InterfaceExternalStorageProvider interfaceProvider && interfaceProvider.getInterface() == this; } @@ -73,8 +73,8 @@ public void doWork() { private void doExport(final InterfaceExportState state, final int index, final StorageNetworkComponent storageComponent) { - final ResourceTemplate want = state.getRequestedResource(index); - final ResourceTemplate got = state.getExportedResource(index); + final ResourceKey want = state.getRequestedResource(index); + final ResourceKey got = state.getExportedResource(index); if (want == null && got != null) { clearExportedResource(state, index, got, storageComponent); } else if (want != null && got == null) { @@ -89,14 +89,13 @@ private void doExport(final InterfaceExportState state, } } - private void clearExportedResource(final InterfaceExportState state, - final int slot, - final ResourceTemplate got, - final StorageNetworkComponent storageComponent) { + private void clearExportedResource(final InterfaceExportState state, + final int slot, + final ResourceKey got, + final StorageChannel storageChannel) { final long currentAmount = state.getExportedAmount(slot); - final StorageChannel storageChannel = storageComponent.getStorageChannel(got.storageChannelType()); final long inserted = storageChannel.insert( - got.resource(), + got, Math.min(currentAmount, transferQuotaProvider.applyAsLong(got)), Action.EXECUTE, actor @@ -107,14 +106,13 @@ private void clearExportedResource(final InterfaceExportState state, state.shrinkExportedAmount(slot, inserted); } - private void doInitialExport(final InterfaceExportState state, - final int slot, - final ResourceTemplate want, - final StorageNetworkComponent storageComponent) { + private void doInitialExport(final InterfaceExportState state, + final int slot, + final ResourceKey want, + final StorageChannel storageChannel) { final long wantedAmount = state.getRequestedAmount(slot); - final StorageChannel storageChannel = storageComponent.getStorageChannel(want.storageChannelType()); - final Collection candidates = state.expandExportCandidates(storageChannel, want.resource()); - for (final T candidate : candidates) { + final Collection candidates = state.expandExportCandidates(storageChannel, want); + for (final ResourceKey candidate : candidates) { final long extracted = storageChannel.extract( candidate, Math.min(transferQuotaProvider.applyAsLong(want), wantedAmount), @@ -122,20 +120,16 @@ private void doInitialExport(final InterfaceExportState state, actor ); if (extracted > 0) { - state.setExportSlot( - slot, - new ResourceTemplate<>(candidate, want.storageChannelType()), - extracted - ); + state.setExportSlot(slot, candidate, extracted); break; } } } - private void doExportWithExistingResource(final InterfaceExportState state, - final int slot, - final ResourceTemplate got, - final StorageNetworkComponent storageComponent) { + private void doExportWithExistingResource(final InterfaceExportState state, + final int slot, + final ResourceKey got, + final StorageNetworkComponent storageComponent) { final long wantedAmount = state.getRequestedAmount(slot); final long currentAmount = state.getExportedAmount(slot); final long difference = wantedAmount - currentAmount; @@ -146,28 +140,26 @@ private void doExportWithExistingResource(final InterfaceExportState state, } } - private void exportAdditionalResources(final InterfaceExportState state, - final int slot, - final ResourceTemplate got, - final long amount, - final StorageNetworkComponent storageComponent) { + private void exportAdditionalResources(final InterfaceExportState state, + final int slot, + final ResourceKey got, + final long amount, + final StorageChannel storageChannel) { final long correctedAmount = Math.min(transferQuotaProvider.applyAsLong(got), amount); - final StorageChannel storageChannel = storageComponent.getStorageChannel(got.storageChannelType()); - final long extracted = storageChannel.extract(got.resource(), correctedAmount, Action.EXECUTE, actor); + final long extracted = storageChannel.extract(got, correctedAmount, Action.EXECUTE, actor); if (extracted == 0) { return; } state.growExportedAmount(slot, extracted); } - private void returnExportedResource(final InterfaceExportState state, - final int slot, - final ResourceTemplate got, - final long amount, - final StorageNetworkComponent storageComponent) { - final StorageChannel storageChannel = storageComponent.getStorageChannel(got.storageChannelType()); + private void returnExportedResource(final InterfaceExportState state, + final int slot, + final ResourceKey got, + final long amount, + final StorageChannel storageChannel) { final long correctedAmount = Math.min(transferQuotaProvider.applyAsLong(got), Math.abs(amount)); - final long inserted = storageChannel.insert(got.resource(), correctedAmount, Action.EXECUTE, actor); + final long inserted = storageChannel.insert(got, correctedAmount, Action.EXECUTE, actor); if (inserted == 0) { return; } diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/InterfaceExternalStorageProvider.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/InterfaceExternalStorageProvider.java index 5be8a6f6a..8c463256f 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/InterfaceExternalStorageProvider.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/InterfaceExternalStorageProvider.java @@ -5,7 +5,7 @@ import javax.annotation.Nullable; -public interface InterfaceExternalStorageProvider extends ExternalStorageProvider { +public interface InterfaceExternalStorageProvider extends ExternalStorageProvider { @Nullable InterfaceNetworkNode getInterface(); } diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/InterfaceExternalStorageProviderImpl.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/InterfaceExternalStorageProviderImpl.java index e69d0a337..1f1bb9c77 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/InterfaceExternalStorageProviderImpl.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/InterfaceExternalStorageProviderImpl.java @@ -5,27 +5,23 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.iface.InterfaceNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.NetworkNodeActor; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; -public class InterfaceExternalStorageProviderImpl implements InterfaceExternalStorageProvider { +public class InterfaceExternalStorageProviderImpl implements InterfaceExternalStorageProvider { private final InterfaceNetworkNode networkNode; - private final StorageChannelType storageChannelType; - public InterfaceExternalStorageProviderImpl(final InterfaceNetworkNode networkNode, - final StorageChannelType storageChannelType) { + public InterfaceExternalStorageProviderImpl(final InterfaceNetworkNode networkNode) { this.networkNode = networkNode; - this.storageChannelType = storageChannelType; } @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { if (isAnotherInterfaceActingAsExternalStorage(actor)) { return 0; } @@ -37,7 +33,7 @@ public long extract(final T resource, final long amount, final Action action, fi } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { if (isAnotherInterfaceActingAsExternalStorage(actor)) { return 0; } @@ -45,7 +41,7 @@ public long insert(final T resource, final long amount, final Action action, fin if (exportState == null) { return 0; } - return exportState.insert(storageChannelType, resource, amount, action); + return exportState.insert(resource, amount, action); } private boolean isAnotherInterfaceActingAsExternalStorage(final Actor actor) { @@ -55,26 +51,24 @@ private boolean isAnotherInterfaceActingAsExternalStorage(final Actor actor) { } @Override - @SuppressWarnings("unchecked") - public Iterator> iterator() { + public Iterator iterator() { final InterfaceExportState exportState = networkNode.getExportState(); if (exportState == null) { return Collections.emptyIterator(); } - final List> slots = new ArrayList<>(); + final List slots = new ArrayList<>(); for (int i = 0; i < exportState.getSlots(); ++i) { - final ResourceTemplate resource = exportState.getExportedResource(i); - if (resource == null || resource.storageChannelType() != storageChannelType) { + final ResourceKey resource = exportState.getExportedResource(i); + if (resource == null) { continue; } - slots.add(getResourceAmount((ResourceTemplate) resource, exportState.getExportedAmount(i))); + slots.add(getResourceAmount(resource, exportState.getExportedAmount(i))); } return slots.iterator(); } - private ResourceAmount getResourceAmount(final ResourceTemplate resource, - final long amount) { - return new ResourceAmount<>(resource.resource(), amount); + private ResourceAmount getResourceAmount(final ResourceKey resource, final long amount) { + return new ResourceAmount(resource, amount); } @Override diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/importer/CompositeImporterTransferStrategy.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/importer/CompositeImporterTransferStrategy.java index 38afbf871..35d6d9014 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/importer/CompositeImporterTransferStrategy.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/importer/CompositeImporterTransferStrategy.java @@ -1,8 +1,8 @@ package com.refinedmods.refinedstorage2.api.network.impl.node.importer; -import com.refinedmods.refinedstorage2.api.core.filter.Filter; import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.node.importer.ImporterTransferStrategy; +import com.refinedmods.refinedstorage2.api.resource.filter.Filter; import com.refinedmods.refinedstorage2.api.storage.Actor; import java.util.Collections; diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/importer/ImporterNetworkNode.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/importer/ImporterNetworkNode.java index ba74fd5c4..2491e8296 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/importer/ImporterNetworkNode.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/importer/ImporterNetworkNode.java @@ -1,10 +1,11 @@ package com.refinedmods.refinedstorage2.api.network.impl.node.importer; -import com.refinedmods.refinedstorage2.api.core.filter.Filter; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; import com.refinedmods.refinedstorage2.api.network.node.AbstractNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.NetworkNodeActor; import com.refinedmods.refinedstorage2.api.network.node.importer.ImporterTransferStrategy; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; +import com.refinedmods.refinedstorage2.api.resource.filter.Filter; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; import com.refinedmods.refinedstorage2.api.storage.Actor; import java.util.Set; @@ -43,12 +44,12 @@ public void setFilterMode(final FilterMode mode) { filter.setMode(mode); } - public void setNormalizer(final UnaryOperator normalizer) { + public void setNormalizer(final UnaryOperator normalizer) { filter.setNormalizer(normalizer); } - public void setFilterTemplates(final Set templates) { - filter.setTemplates(templates); + public void setFilters(final Set filters) { + filter.setFilters(filters); } public void setEnergyUsage(final long energyUsage) { diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/ExposedStorage.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/ExposedMultiStorage.java similarity index 71% rename from refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/ExposedStorage.java rename to refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/ExposedMultiStorage.java index 1cd63837d..76e1e2715 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/ExposedStorage.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/ExposedMultiStorage.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage2.api.network.node.AbstractImmutableConfiguredProxyStorage; import com.refinedmods.refinedstorage2.api.network.node.StorageConfiguration; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.Storage; @@ -14,10 +15,10 @@ import java.util.List; import java.util.Optional; -class ExposedStorage extends AbstractImmutableConfiguredProxyStorage> - implements CompositeStorage, CompositeAwareChild { - protected ExposedStorage(final StorageConfiguration config) { - super(config, new CompositeStorageImpl<>(new ResourceListImpl<>())); +class ExposedMultiStorage extends AbstractImmutableConfiguredProxyStorage + implements CompositeStorage, CompositeAwareChild { + protected ExposedMultiStorage(final StorageConfiguration config) { + super(config, new CompositeStorageImpl(new ResourceListImpl())); } @Override @@ -26,17 +27,17 @@ public void sortSources() { } @Override - public void addSource(final Storage source) { + public void addSource(final Storage source) { getDelegate().addSource(source); } @Override - public void removeSource(final Storage source) { + public void removeSource(final Storage source) { getDelegate().removeSource(source); } @Override - public List> getSources() { + public List getSources() { return getDelegate().getSources(); } @@ -46,18 +47,18 @@ public void clearSources() { } @Override - public Optional findTrackedResourceByActorType(final T resource, + public Optional findTrackedResourceByActorType(final ResourceKey resource, final Class actorType) { return getDelegate().findTrackedResourceByActorType(resource, actorType); } @Override - public void onAddedIntoComposite(final ParentComposite parentComposite) { + public void onAddedIntoComposite(final ParentComposite parentComposite) { getDelegate().onAddedIntoComposite(parentComposite); } @Override - public void onRemovedFromComposite(final ParentComposite parentComposite) { + public void onRemovedFromComposite(final ParentComposite parentComposite) { getDelegate().onRemovedFromComposite(parentComposite); } } diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/MultiStorageNetworkNode.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/MultiStorageNetworkNode.java index a2e90bb16..95704945c 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/MultiStorageNetworkNode.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/MultiStorageNetworkNode.java @@ -5,20 +5,13 @@ import com.refinedmods.refinedstorage2.api.storage.StateTrackedStorage; import com.refinedmods.refinedstorage2.api.storage.Storage; import com.refinedmods.refinedstorage2.api.storage.StorageState; -import com.refinedmods.refinedstorage2.api.storage.TypedStorage; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collection; import java.util.HashSet; import java.util.List; -import java.util.Map; import java.util.Objects; -import java.util.Optional; import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; import javax.annotation.Nullable; import org.slf4j.Logger; @@ -35,31 +28,17 @@ public class MultiStorageNetworkNode extends AbstractStorageNetworkNode implemen private final long energyUsage; private final long energyUsagePerStorage; - private final TypedStorage>[] cache; - private final Map, ExposedStorage> exposedStorages; + private final StateTrackedStorage[] cache; + private final ExposedMultiStorage storage; private int activeStorages; public MultiStorageNetworkNode(final long energyUsage, final long energyUsagePerStorage, - final Collection> storageChannelTypes, final int size) { this.energyUsage = energyUsage; this.energyUsagePerStorage = energyUsagePerStorage; - this.exposedStorages = createExposedStorages(storageChannelTypes); - this.cache = new TypedStorage[size]; - } - - private Map, ExposedStorage> createExposedStorages( - final Collection> storageChannelTypes - ) { - return storageChannelTypes.stream().collect(Collectors.toUnmodifiableMap( - Function.identity(), - this::createExposedStorage - )); - } - - private ExposedStorage createExposedStorage(final StorageChannelType type) { - return new ExposedStorage<>(this); + this.storage = new ExposedMultiStorage(this); + this.cache = new StateTrackedStorage[size]; } public void setProvider(final MultiStorageProvider provider) { @@ -85,36 +64,32 @@ public void onStorageChanged(final int index) { updateActiveStorageCount(); } - @SuppressWarnings({"rawtypes", "unchecked"}) private Set initializeStorage(final int index) { final Set results = new HashSet<>(); if (cache[index] != null) { - final StorageChannelType removedType = cache[index].storageChannelType(); - final ExposedStorage relevantComposite = exposedStorages.get(removedType); - results.add(new StorageChange(true, relevantComposite, cache[index].storage())); + results.add(new StorageChange(true, cache[index])); } if (provider != null) { provider.resolve(index).ifPresentOrElse(resolved -> { - cache[index] = (TypedStorage) StateTrackedStorage.of(resolved, listener); - final ExposedStorage relevantComposite = exposedStorages.get(resolved.storageChannelType()); - results.add(new StorageChange(false, relevantComposite, cache[index].storage())); + final StateTrackedStorage newStorage = new StateTrackedStorage(resolved, listener); + cache[index] = newStorage; + results.add(new StorageChange(false, newStorage)); }, () -> cache[index] = null); } return results; } - @SuppressWarnings({"unchecked", "rawtypes"}) private void processStorageChange(final StorageChange change) { if (!isActive()) { return; } if (change.removed) { - change.exposedStorage.removeSource((Storage) change.internalStorage); + storage.removeSource(change.storage); } else { - change.exposedStorage.addSource((Storage) change.internalStorage); + storage.addSource(change.storage); } } @@ -137,21 +112,15 @@ protected void onActiveChanged(final boolean newActive) { } private void enableAllStorages() { - exposedStorages.forEach(this::enableAllStoragesForChannel); - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - private void enableAllStoragesForChannel(final StorageChannelType type, - final ExposedStorage exposedStorage) { - for (final TypedStorage> internalStorage : cache) { - if (internalStorage != null && internalStorage.storageChannelType() == type) { - exposedStorage.addSource((StateTrackedStorage) internalStorage.storage()); + for (final StateTrackedStorage internalStorage : cache) { + if (internalStorage != null) { + storage.addSource(internalStorage); } } } private void disableAllStorages() { - exposedStorages.values().forEach(ExposedStorage::clearSources); + storage.clearSources(); } public void setListener(final StateTrackedStorage.Listener listener) { @@ -168,33 +137,21 @@ public int getSize() { } public StorageState getState(final int index) { - final var storage = cache[index]; - if (storage == null) { + final var cached = cache[index]; + if (cached == null) { return StorageState.NONE; } if (!isActive()) { return StorageState.INACTIVE; } - return storage.storage().getState(); + return cached.getState(); } @Override - protected Set> getRelevantStorageChannelTypes() { - return exposedStorages.keySet(); - } - - @Override - @SuppressWarnings("unchecked") - public Optional> getStorageForChannel(final StorageChannelType channelType) { - final ExposedStorage storage = exposedStorages.get(channelType); - if (storage != null) { - return Optional.of((Storage) storage); - } - return Optional.empty(); + public Storage getStorage() { + return storage; } - private record StorageChange(boolean removed, - ExposedStorage exposedStorage, - StateTrackedStorage internalStorage) { + private record StorageChange(boolean removed, StateTrackedStorage storage) { } } diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/MultiStorageProvider.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/MultiStorageProvider.java index 5b9049d52..8dd420fa1 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/MultiStorageProvider.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/MultiStorageProvider.java @@ -1,11 +1,10 @@ package com.refinedmods.refinedstorage2.api.network.impl.node.multistorage; import com.refinedmods.refinedstorage2.api.storage.Storage; -import com.refinedmods.refinedstorage2.api.storage.TypedStorage; import java.util.Optional; @FunctionalInterface public interface MultiStorageProvider { - Optional>> resolve(int index); + Optional resolve(int index); } diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/storage/ExposedStorage.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/storage/ExposedStorage.java index 1e2a40aa9..1724bba1c 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/storage/ExposedStorage.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/storage/ExposedStorage.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage2.api.network.node.AbstractConfiguredProxyStorage; import com.refinedmods.refinedstorage2.api.network.node.StorageConfiguration; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.Storage; import com.refinedmods.refinedstorage2.api.storage.composite.CompositeAwareChild; @@ -14,47 +15,47 @@ import java.util.Optional; import java.util.Set; -class ExposedStorage extends AbstractConfiguredProxyStorage> - implements TrackedStorage, CompositeAwareChild { - private final Set> parents = new HashSet<>(); +class ExposedStorage extends AbstractConfiguredProxyStorage + implements TrackedStorage, CompositeAwareChild { + private final Set parents = new HashSet<>(); ExposedStorage(final StorageConfiguration config) { super(config); } @Override - public Optional findTrackedResourceByActorType(final T resource, + public Optional findTrackedResourceByActorType(final ResourceKey resource, final Class actorType) { - return getUnsafeDelegate() instanceof TrackedStorage trackedStorage + return getUnsafeDelegate() instanceof TrackedStorage trackedStorage ? trackedStorage.findTrackedResourceByActorType(resource, actorType) : Optional.empty(); } @Override - public void onAddedIntoComposite(final ParentComposite parentComposite) { + public void onAddedIntoComposite(final ParentComposite parentComposite) { parents.add(parentComposite); } @Override - public void onRemovedFromComposite(final ParentComposite parentComposite) { + public void onRemovedFromComposite(final ParentComposite parentComposite) { parents.remove(parentComposite); } public long getCapacity() { - return getUnsafeDelegate() instanceof LimitedStorage limitedStorage + return getUnsafeDelegate() instanceof LimitedStorage limitedStorage ? limitedStorage.getCapacity() : 0L; } @Override - public void setDelegate(final Storage newDelegate) { + public void setDelegate(final Storage newDelegate) { super.setDelegate(newDelegate); parents.forEach(parent -> parent.onSourceAddedToChild(newDelegate)); } @Override public void clearDelegate() { - final Storage delegate = getDelegate(); + final Storage delegate = getDelegate(); parents.forEach(parent -> parent.onSourceRemovedFromChild(delegate)); super.clearDelegate(); } diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/storage/StorageNetworkNode.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/storage/StorageNetworkNode.java index 59ed41ad7..659ae9106 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/storage/StorageNetworkNode.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/node/storage/StorageNetworkNode.java @@ -3,31 +3,25 @@ import com.refinedmods.refinedstorage2.api.network.component.StorageProvider; import com.refinedmods.refinedstorage2.api.network.node.AbstractStorageNetworkNode; import com.refinedmods.refinedstorage2.api.storage.Storage; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; -import java.util.Optional; -import java.util.Set; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class StorageNetworkNode extends AbstractStorageNetworkNode implements StorageProvider { +public class StorageNetworkNode extends AbstractStorageNetworkNode implements StorageProvider { private static final Logger LOGGER = LoggerFactory.getLogger(StorageNetworkNode.class); private final long energyUsage; - private final StorageChannelType type; - private final ExposedStorage exposedStorage = new ExposedStorage<>(this); - + private final ExposedStorage storage = new ExposedStorage(this); @Nullable - private Storage internalStorage; + private Storage internalStorage; - public StorageNetworkNode(final long energyUsage, final StorageChannelType type) { + public StorageNetworkNode(final long energyUsage) { this.energyUsage = energyUsage; - this.type = type; } - public void setStorage(final Storage storage) { + public void setStorage(final Storage storage) { LOGGER.debug("Loading storage {}", storage); this.internalStorage = storage; } @@ -40,9 +34,9 @@ protected void onActiveChanged(final boolean newActive) { } LOGGER.debug("Storage activeness got changed to '{}', updating underlying storage", newActive); if (newActive) { - exposedStorage.setDelegate(internalStorage); + storage.setDelegate(internalStorage); } else { - exposedStorage.clearDelegate(); + storage.clearDelegate(); } } @@ -52,24 +46,15 @@ public long getEnergyUsage() { } public long getStored() { - return exposedStorage.getStored(); + return storage.getStored(); } public long getCapacity() { - return exposedStorage.getCapacity(); + return storage.getCapacity(); } @Override - protected Set> getRelevantStorageChannelTypes() { - return Set.of(type); - } - - @Override - @SuppressWarnings("unchecked") - public Optional> getStorageForChannel(final StorageChannelType channelType) { - if (channelType == this.type) { - return Optional.of((Storage) exposedStorage); - } - return Optional.empty(); + public Storage getStorage() { + return storage; } } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/PriorityNetworkBuilderImplTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/PriorityNetworkBuilderImplTest.java index a2adacb55..b6fb80561 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/PriorityNetworkBuilderImplTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/PriorityNetworkBuilderImplTest.java @@ -8,9 +8,9 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.grid.GridNetworkNode; import com.refinedmods.refinedstorage2.api.network.impl.node.storage.StorageNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import com.refinedmods.refinedstorage2.network.test.util.FakeActor; import java.util.function.Supplier; @@ -18,6 +18,8 @@ import org.junit.jupiter.api.Test; import org.mockito.InOrder; +import static com.refinedmods.refinedstorage2.api.network.impl.PriorityNetworkBuilderImplTest.MasterSlave.MASTER; +import static com.refinedmods.refinedstorage2.api.network.impl.PriorityNetworkBuilderImplTest.MasterSlave.SLAVE; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.inOrder; @@ -31,9 +33,9 @@ class PriorityNetworkBuilderImplTest extends AbstractNetworkBuilderImplTest { void shouldRespectPriorityWhenSplitting() { // Arrange final Network originalNetwork = new NetworkImpl(componentMapFactory); - final NetworkSide master = createNetworkSide("master", () -> originalNetwork); + final NetworkSide master = createNetworkSide(MASTER, () -> originalNetwork); final NetworkNodeContainer connector = createContainerWithNetwork(container -> originalNetwork); - final NetworkSide slave = createNetworkSide("slave", () -> originalNetwork); + final NetworkSide slave = createNetworkSide(SLAVE, () -> originalNetwork); clearInvocations(master.watcher); final ConnectionProvider connectionProvider = new FakeConnectionProvider() @@ -54,16 +56,14 @@ void shouldRespectPriorityWhenSplitting() { final InOrder inOrder = inOrder(slave.watcher); inOrder.verify(slave.watcher, times(1)).invalidate(); inOrder.verify(slave.watcher, times(1)).onChanged( - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - "slave", + SLAVE, 10L, null ); verifyNoMoreInteractions(slave.watcher); verify(master.watcher, times(1)).onChanged( - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - "slave", + SLAVE, -10L, null ); @@ -73,9 +73,9 @@ void shouldRespectPriorityWhenSplitting() { @Test void shouldRespectPriorityWhenMerging() { // Arrange - final NetworkSide master = createNetworkSide("master", () -> new NetworkImpl(componentMapFactory)); + final NetworkSide master = createNetworkSide(MASTER, () -> new NetworkImpl(componentMapFactory)); final NetworkNodeContainer connector = createContainer(); - final NetworkSide slave = createNetworkSide("slave", () -> new NetworkImpl(componentMapFactory)); + final NetworkSide slave = createNetworkSide(SLAVE, () -> new NetworkImpl(componentMapFactory)); final ConnectionProvider connectionProvider = new FakeConnectionProvider() .with(master.a, master.b, connector, slave.a, slave.b) @@ -92,38 +92,32 @@ void shouldRespectPriorityWhenMerging() { assertThat(slave.nodeA.getNetwork()).isSameAs(master.nodeA.getNetwork()); assertThat(slave.nodeB.getNetwork()).isSameAs(master.nodeA.getNetwork()); - final InOrder inOrder = inOrder(slave.watcher); - inOrder.verify(slave.watcher, times(1)).invalidate(); - inOrder.verify(slave.watcher).onChanged( - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - "slave", + verify(slave.watcher, times(1)).invalidate(); + verify(slave.watcher).onChanged( + SLAVE, 10L, null ); - inOrder.verify(slave.watcher).onChanged( - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - "master", + verify(slave.watcher).onChanged( + MASTER, 10L, null ); - inOrder.verifyNoMoreInteractions(); + verifyNoMoreInteractions(slave.watcher); verify(master.watcher, times(1)).onChanged( - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - "slave", + SLAVE, 10L, null ); verifyNoMoreInteractions(master.watcher); } - private NetworkSide createNetworkSide(final String name, final Supplier networkFactory) { - final StorageNetworkNode nodeA = new StorageNetworkNode<>( - 0, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE - ); - final InMemoryStorageImpl storage = new InMemoryStorageImpl<>(); - storage.insert(name, 10, Action.EXECUTE, FakeActor.INSTANCE); + private NetworkSide createNetworkSide(final MasterSlave side, + final Supplier networkFactory) { + final StorageNetworkNode nodeA = new StorageNetworkNode(0); + final InMemoryStorageImpl storage = new InMemoryStorageImpl(); + storage.insert(side, 10, Action.EXECUTE, FakeActor.INSTANCE); nodeA.setStorage(storage); final NetworkNodeContainer a = createContainerWithNetwork( nodeA, @@ -137,7 +131,7 @@ private NetworkSide createNetworkSide(final String name, final Supplier container -> a.getNode().getNetwork(), NetworkNodeContainerPriorities.GRID ); - final GridWatcher watcher = mock(GridWatcher.class, "watcher for " + name); + final GridWatcher watcher = mock(GridWatcher.class, "watcher for " + side.name()); nodeB.setActive(true); nodeB.addWatcher(watcher, EmptyActor.class); return new NetworkSide(a, nodeA, b, nodeB, watcher); @@ -145,10 +139,14 @@ private NetworkSide createNetworkSide(final String name, final Supplier private record NetworkSide( NetworkNodeContainer a, - StorageNetworkNode nodeA, + StorageNetworkNode nodeA, NetworkNodeContainer b, GridNetworkNode nodeB, GridWatcher watcher ) { } + + protected enum MasterSlave implements ResourceKey { + MASTER, SLAVE + } } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/component/StorageNetworkComponentImplTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/component/StorageNetworkComponentImplTest.java index 22b4d45a6..b8267db73 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/component/StorageNetworkComponentImplTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/component/StorageNetworkComponentImplTest.java @@ -8,7 +8,6 @@ import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; import com.refinedmods.refinedstorage2.api.storage.TrackedResourceAmount; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.api.storage.limited.LimitedStorageImpl; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedStorageImpl; @@ -21,30 +20,32 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; +import static com.refinedmods.refinedstorage2.network.test.TestResource.B; import static org.assertj.core.api.Assertions.assertThat; class StorageNetworkComponentImplTest { private StorageNetworkComponent sut; - private StorageNetworkNode storage1; + private StorageNetworkNode storage1; private NetworkNodeContainer storage1Container; - private StorageNetworkNode storage2; + private StorageNetworkNode storage2; private NetworkNodeContainer storage2Container; @BeforeEach void setUp() { - sut = new StorageNetworkComponentImpl(NetworkTestFixtures.STORAGE_CHANNEL_TYPES); + sut = new StorageNetworkComponentImpl(); - storage1 = new StorageNetworkNode<>(0, NetworkTestFixtures.STORAGE_CHANNEL_TYPE); + storage1 = new StorageNetworkNode(0); storage1.setNetwork(new NetworkImpl(NetworkTestFixtures.NETWORK_COMPONENT_MAP_FACTORY)); - storage1.setStorage(new LimitedStorageImpl<>(100)); + storage1.setStorage(new LimitedStorageImpl(100)); storage1.setActive(true); storage1Container = () -> storage1; - storage2 = new StorageNetworkNode<>(0, NetworkTestFixtures.STORAGE_CHANNEL_TYPE); + storage2 = new StorageNetworkNode(0); storage2.setNetwork(new NetworkImpl(NetworkTestFixtures.NETWORK_COMPONENT_MAP_FACTORY)); - storage2.setStorage(new LimitedStorageImpl<>(100)); + storage2.setStorage(new LimitedStorageImpl(100)); storage2.setActive(true); storage2Container = () -> storage2; } @@ -52,9 +53,7 @@ void setUp() { @Test void testInitialState() { // Act - final Collection> resources = sut - .getStorageChannel(NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - .getAll(); + final Collection resources = sut.getAll(); // Assert assertThat(resources).isEmpty(); @@ -62,36 +61,31 @@ void testInitialState() { @Test void shouldAddStorageSourceContainer() { - // Arrange - final StorageChannel storageChannel = sut.getStorageChannel(NetworkTestFixtures.STORAGE_CHANNEL_TYPE); - // Act - final long insertedPre = storageChannel.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long insertedPre = sut.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.onContainerAdded(storage1Container); - final long insertedPost = storageChannel.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long insertedPost = sut.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(insertedPre).isZero(); assertThat(insertedPost).isEqualTo(10); - assertThat(storageChannel.getAll()).isNotEmpty(); + assertThat(sut.getAll()).isNotEmpty(); } @Test void shouldRemoveStorageSourceContainer() { // Arrange - final StorageChannel storageChannel = sut.getStorageChannel(NetworkTestFixtures.STORAGE_CHANNEL_TYPE); - sut.onContainerAdded(storage1Container); sut.onContainerAdded(storage2Container); // Ensure that we fill our 2 containers. - storageChannel.insert("A", 200, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(A, 200, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final Collection> resourcesPre = new HashSet<>(storageChannel.getAll()); + final Collection resourcesPre = new HashSet<>(sut.getAll()); sut.onContainerRemoved(storage1Container); sut.onContainerRemoved(storage2Container); - final Collection> resourcesPost = storageChannel.getAll(); + final Collection resourcesPost = sut.getAll(); // Assert assertThat(resourcesPre).isNotEmpty(); @@ -104,12 +98,8 @@ void testHasSource() { sut.onContainerAdded(storage1Container); // Act - final boolean found = sut.hasSource( - s -> s == storage1.getStorageForChannel(NetworkTestFixtures.STORAGE_CHANNEL_TYPE).get() - ); - final boolean found2 = sut.hasSource( - s -> s == storage2.getStorageForChannel(NetworkTestFixtures.STORAGE_CHANNEL_TYPE).get() - ); + final boolean found = sut.hasSource(s -> s == storage1.getStorage()); + final boolean found2 = sut.hasSource(s -> s == storage2.getStorage()); // Assert assertThat(found).isTrue(); @@ -119,27 +109,23 @@ void testHasSource() { @Test void shouldRetrieveResources() { // Arrange - final StorageChannel storageChannel = sut.getStorageChannel(NetworkTestFixtures.STORAGE_CHANNEL_TYPE); sut.onContainerRemoved(storage1Container); sut.onContainerRemoved(storage2Container); - storageChannel.addSource(new TrackedStorageImpl<>(new LimitedStorageImpl<>(1000), () -> 2L)); - storageChannel.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("B", 200, Action.EXECUTE, EmptyActor.INSTANCE); + sut.addSource(new TrackedStorageImpl(new LimitedStorageImpl(1000), () -> 2L)); + sut.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(B, 200, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final List> resources = sut.getResources( - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - EmptyActor.class - ); + final List resources = sut.getResources(EmptyActor.class); // Assert - assertThat(resources).usingRecursiveFieldByFieldElementComparator().containsExactly( - new TrackedResourceAmount<>( - new ResourceAmount<>("A", 100), + assertThat(resources).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new TrackedResourceAmount( + new ResourceAmount(A, 100), new TrackedResource("Empty", 2L) ), - new TrackedResourceAmount<>( - new ResourceAmount<>("B", 200), + new TrackedResourceAmount( + new ResourceAmount(B, 200), new TrackedResource("Empty", 2L) ) ); diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/DetectorNetworkNodeTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/DetectorNetworkNodeTest.java index 51290862c..936654442 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/DetectorNetworkNodeTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/detector/DetectorNetworkNodeTest.java @@ -3,12 +3,10 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.network.test.AddNetworkNode; import com.refinedmods.refinedstorage2.network.test.InjectNetworkStorageChannel; import com.refinedmods.refinedstorage2.network.test.NetworkTest; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import com.refinedmods.refinedstorage2.network.test.SetupNetwork; import com.refinedmods.refinedstorage2.network.test.nodefactory.AbstractNetworkNodeFactory; @@ -21,6 +19,7 @@ import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.MethodSource; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; import static org.assertj.core.api.Assertions.assertThat; @NetworkTest @@ -34,15 +33,15 @@ class DetectorNetworkNodeTest { DetectorNetworkNode sut; @BeforeEach - void setUp(@InjectNetworkStorageChannel final StorageChannel storageChannel) { - storageChannel.addSource(new InMemoryStorageImpl<>()); + void setUp(@InjectNetworkStorageChannel final StorageChannel storageChannel) { + storageChannel.addSource(new InMemoryStorageImpl()); sut.setAmountStrategy(new DetectorAmountStrategyImpl()); } @Test void testWithoutNetwork() { // Act - sut.setFilterTemplate(new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE)); + sut.setConfiguredResource(A); sut.setNetwork(null); // Assert @@ -55,7 +54,7 @@ void testWithoutNetwork() { @Test void testWithoutActiveness() { // Act - sut.setFilterTemplate(new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE)); + sut.setConfiguredResource(A); sut.setActive(false); // Assert @@ -66,7 +65,7 @@ void testWithoutActiveness() { } @Test - void testWithoutTemplate() { + void testWithoutConfiguredResource() { // Assert assertThat(sut.isActivated()).isFalse(); assertThat(sut.getAmount()).isZero(); @@ -76,9 +75,9 @@ void testWithoutTemplate() { @ParameterizedTest @EnumSource(DetectorMode.class) - void testWithTemplateButWithoutResourceInNetwork(final DetectorMode mode) { + void testWithConfiguredResourceButWithoutResourceInNetwork(final DetectorMode mode) { // Arrange - sut.setFilterTemplate(new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE)); + sut.setConfiguredResource(A); sut.setMode(mode); // Act @@ -119,14 +118,14 @@ void testModes(final DetectorMode mode, final long comparisonAmount, final long amountInNetwork, final boolean expectedActivated, - @InjectNetworkStorageChannel final StorageChannel storageChannel) { + @InjectNetworkStorageChannel final StorageChannel storageChannel) { // Arrange - sut.setFilterTemplate(new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE)); + sut.setConfiguredResource(A); sut.setMode(mode); sut.setAmount(comparisonAmount); if (amountInNetwork > 0) { - storageChannel.insert("A", amountInNetwork, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(A, amountInNetwork, Action.EXECUTE, EmptyActor.INSTANCE); } // Act diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/AbstractExporterNetworkNodeTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/AbstractExporterNetworkNodeTest.java index a980e0879..3789625df 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/AbstractExporterNetworkNodeTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/AbstractExporterNetworkNodeTest.java @@ -15,15 +15,16 @@ import com.refinedmods.refinedstorage2.network.test.InjectNetworkEnergyComponent; import com.refinedmods.refinedstorage2.network.test.InjectNetworkStorageChannel; import com.refinedmods.refinedstorage2.network.test.NetworkTest; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import com.refinedmods.refinedstorage2.network.test.SetupNetwork; import java.util.List; -import javax.annotation.Nullable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; +import static com.refinedmods.refinedstorage2.network.test.TestResource.B; +import static com.refinedmods.refinedstorage2.network.test.TestResource.C; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @@ -52,30 +53,30 @@ void testInitialState() { @Test void shouldUseFirstSuccessfulStrategy( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new LimitedStorageImpl<>(100); + final Storage destination = new LimitedStorageImpl(100); sut.setTransferStrategy(new CompositeExporterTransferStrategy(List.of( createTransferStrategy(destination, 10), createTransferStrategy(destination, 10), createTransferStrategy(destination, 10) ))); - sut.setFilterTemplates(List.of("A")); + sut.setFilters(List.of(A)); // Act sut.doWork(); // Assert assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 90) + new ResourceAmount(A, 90) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); } @@ -99,16 +100,16 @@ void shouldNotTransferWithoutNetwork() { @Test void shouldNotTransferWithoutTaskExecutor( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("B", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(B, 100, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new InMemoryStorageImpl<>(); + final Storage destination = new InMemoryStorageImpl(); - sut.setFilterTemplates(List.of("A", "B")); + sut.setFilters(List.of(A, B)); sut.setTransferStrategy(createTransferStrategy(destination, 1)); sut.setTaskExecutor(null); @@ -116,94 +117,94 @@ void shouldNotTransferWithoutTaskExecutor( sut.doWork(); // Assert - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100), - new ResourceAmount<>("B", 100) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A, 100), + new ResourceAmount(B, 100) ); assertThat(destination.getAll()).isEmpty(); } @Test - void shouldNotTransferWithoutStrategy(@InjectNetworkStorageChannel final StorageChannel storageChannel) { + void shouldNotTransferWithoutStrategy(@InjectNetworkStorageChannel final StorageChannel storageChannel) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("B", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(B, 100, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new InMemoryStorageImpl<>(); + final Storage destination = new InMemoryStorageImpl(); - sut.setFilterTemplates(List.of("A", "B")); + sut.setFilters(List.of(A, B)); // Act sut.doWork(); // Assert - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100), - new ResourceAmount<>("B", 100) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A, 100), + new ResourceAmount(B, 100) ); assertThat(destination.getAll()).isEmpty(); } @Test - void shouldNotTransferIfInactive(@InjectNetworkStorageChannel final StorageChannel storageChannel) { + void shouldNotTransferIfInactive(@InjectNetworkStorageChannel final StorageChannel storageChannel) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("B", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(B, 100, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new InMemoryStorageImpl<>(); + final Storage destination = new InMemoryStorageImpl(); final ExporterTransferStrategy strategy = createTransferStrategy(destination, 1); sut.setTransferStrategy(strategy); - sut.setFilterTemplates(List.of("A", "B")); + sut.setFilters(List.of(A, B)); sut.setActive(false); // Act sut.doWork(); // Assert - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100), - new ResourceAmount<>("B", 100) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A, 100), + new ResourceAmount(B, 100) ); assertThat(destination.getAll()).isEmpty(); } @Test - void shouldNotTransferWithoutTemplates(@InjectNetworkStorageChannel final StorageChannel storageChannel) { + void shouldNotTransferWithoutFilters(@InjectNetworkStorageChannel final StorageChannel storageChannel) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("B", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(B, 100, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new InMemoryStorageImpl<>(); + final Storage destination = new InMemoryStorageImpl(); final ExporterTransferStrategy strategy = createTransferStrategy(destination, 1); sut.setTransferStrategy(strategy); - sut.setFilterTemplates(List.of()); + sut.setFilters(List.of()); // Act sut.doWork(); // Assert - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100), - new ResourceAmount<>("B", 100) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A, 100), + new ResourceAmount(B, 100) ); assertThat(destination.getAll()).isEmpty(); } @Test void shouldNotTransferIfNoResourcesAreAvailable( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - final Storage destination = new InMemoryStorageImpl<>(); + final Storage destination = new InMemoryStorageImpl(); final ExporterTransferStrategy strategy = createTransferStrategy(destination, 10); sut.setTransferStrategy(strategy); - sut.setFilterTemplates(List.of("A", "B")); + sut.setFilters(List.of(A, B)); // Act sut.doWork(); @@ -217,125 +218,110 @@ void shouldNotTransferIfNoResourcesAreAvailable( @Test void shouldTransferWithLimitedSpaceInDestination( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("B", 100, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("C", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(B, 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(C, 100, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new LimitedStorageImpl<>(5); - destination.insert("C", 1, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage destination = new LimitedStorageImpl(5); + destination.insert(C, 1, Action.EXECUTE, EmptyActor.INSTANCE); final ExporterTransferStrategy strategy = createTransferStrategy(destination, 10); sut.setTransferStrategy(strategy); - sut.setFilterTemplates(List.of("C")); - sut.setFilterTemplates(List.of("A", "B")); + sut.setFilters(List.of(C)); + sut.setFilters(List.of(A, B)); // Act & assert sut.doWork(); assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 96), - new ResourceAmount<>("B", 100), - new ResourceAmount<>("C", 100) + new ResourceAmount(A, 96), + new ResourceAmount(B, 100), + new ResourceAmount(C, 100) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 4), - new ResourceAmount<>("C", 1) + new ResourceAmount(A, 4), + new ResourceAmount(C, 1) ); sut.doWork(); assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 96), - new ResourceAmount<>("B", 100), - new ResourceAmount<>("C", 100) + new ResourceAmount(A, 96), + new ResourceAmount(B, 100), + new ResourceAmount(C, 100) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 4), - new ResourceAmount<>("C", 1) + new ResourceAmount(A, 4), + new ResourceAmount(C, 1) ); } @Test void shouldNotTransferIfThereIsNoSpaceInTheDestination( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("B", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(B, 100, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new LimitedStorageImpl<>(1); - destination.insert("C", 1, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage destination = new LimitedStorageImpl(1); + destination.insert(C, 1, Action.EXECUTE, EmptyActor.INSTANCE); final ExporterTransferStrategy strategy = createTransferStrategy(destination, 5); sut.setTransferStrategy(strategy); - sut.setFilterTemplates(List.of("A", "B")); + sut.setFilters(List.of(A, B)); // Act sut.doWork(); // Assert - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100), - new ResourceAmount<>("B", 100) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A, 100), + new ResourceAmount(B, 100) ); - assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("C", 1) + assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( + new ResourceAmount(C, 1) ); } @Test void shouldTransferSingleResourceEvenIfTransferQuotaHasNotBeenMet( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 6, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("B", 7, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 6, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(B, 7, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new InMemoryStorageImpl<>(); + final Storage destination = new InMemoryStorageImpl(); final ExporterTransferStrategy strategy = createTransferStrategy(destination, 10); sut.setTransferStrategy(strategy); - sut.setFilterTemplates(List.of("A", "B")); + sut.setFilters(List.of(A, B)); // Act sut.doWork(); // Assert assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("B", 7) + new ResourceAmount(B, 7) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 6) + new ResourceAmount(A, 6) ); } protected static ExporterTransferStrategy createTransferStrategy( - final InsertableStorage destination, + final InsertableStorage destination, final long transferQuota ) { - return new FakeAbstractExporterTransferStrategy(destination, transferQuota); - } - - private static class FakeAbstractExporterTransferStrategy extends AbstractExporterTransferStrategy { - private FakeAbstractExporterTransferStrategy( - final InsertableStorage destination, - final long transferQuota - ) { - super(destination, NetworkTestFixtures.STORAGE_CHANNEL_TYPE, transferQuota); - } - - @Nullable - @Override - protected String tryConvert(final Object resource) { - return resource instanceof String str ? str : null; - } + return new ExporterTransferStrategyImpl(destination, transferQuota); } } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/FirstAvailableExporterNetworkNodeTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/FirstAvailableExporterNetworkNodeTest.java index 4910fd991..4f94d158f 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/FirstAvailableExporterNetworkNodeTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/FirstAvailableExporterNetworkNodeTest.java @@ -6,6 +6,7 @@ import com.refinedmods.refinedstorage2.api.network.node.exporter.ExporterTransferStrategy; import com.refinedmods.refinedstorage2.api.network.node.task.TaskExecutor; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; @@ -19,6 +20,9 @@ import org.junit.jupiter.api.Test; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; +import static com.refinedmods.refinedstorage2.network.test.TestResource.B; +import static com.refinedmods.refinedstorage2.network.test.TestResource.C; import static org.assertj.core.api.Assertions.assertThat; class FirstAvailableExporterNetworkNodeTest extends AbstractExporterNetworkNodeTest { @@ -28,49 +32,49 @@ protected TaskExecutor createTaskExecutor() { } @Test - void shouldTransfer(@InjectNetworkStorageChannel final StorageChannel storageChannel) { + void shouldTransfer(@InjectNetworkStorageChannel final StorageChannel storageChannel) { // Arrange - storageChannel.addSource(new TrackedStorageImpl<>(new InMemoryStorageImpl<>(), () -> 1L)); - storageChannel.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("B", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new TrackedStorageImpl(new InMemoryStorageImpl(), () -> 1L)); + storageChannel.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(B, 100, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new InMemoryStorageImpl<>(); + final Storage destination = new InMemoryStorageImpl(); final ExporterTransferStrategy strategy = createTransferStrategy(destination, 1); sut.setTransferStrategy(strategy); - sut.setFilterTemplates(List.of("A")); + sut.setFilters(List.of(A)); // Act sut.doWork(); // Assert - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 99), - new ResourceAmount<>("B", 100) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A, 99), + new ResourceAmount(B, 100) ); - assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 1) + assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( + new ResourceAmount(A, 1) ); - assertThat(storageChannel.findTrackedResourceByActorType("A", NetworkNodeActor.class)) + assertThat(storageChannel.findTrackedResourceByActorType(A, NetworkNodeActor.class)) .get() .usingRecursiveComparison() .isEqualTo(new TrackedResource(ExporterNetworkNode.class.getName(), 1)); - assertThat(storageChannel.findTrackedResourceByActorType("B", NetworkNodeActor.class)).isEmpty(); + assertThat(storageChannel.findTrackedResourceByActorType(B, NetworkNodeActor.class)).isEmpty(); } @Test void shouldUseNextResourceIfFirstOneIsNotAvailableInSameCycle( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("B", 7, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(B, 7, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new InMemoryStorageImpl<>(); + final Storage destination = new InMemoryStorageImpl(); final ExporterTransferStrategy strategy = createTransferStrategy(destination, 10); sut.setTransferStrategy(strategy); - sut.setFilterTemplates(List.of("A", "B")); + sut.setFilters(List.of(A, B)); // Act sut.doWork(); @@ -78,24 +82,24 @@ void shouldUseNextResourceIfFirstOneIsNotAvailableInSameCycle( // Assert assertThat(storageChannel.getAll()).isEmpty(); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("B", 7) + new ResourceAmount(B, 7) ); } @Test void shouldUseNextResourceIfFirstOneIsNotAcceptedInSameCycle( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("B", 10, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("C", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(B, 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(C, 10, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new InMemoryStorageImpl<>() { + final Storage destination = new InMemoryStorageImpl() { @Override - public long insert(final String resource, final long amount, final Action action, final Actor actor) { - if ("A".equalsIgnoreCase(resource)) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { + if (A.equals(resource)) { return 0; } return super.insert(resource, amount, action, actor); @@ -104,37 +108,37 @@ public long insert(final String resource, final long amount, final Action action final ExporterTransferStrategy strategy = createTransferStrategy(destination, 20); sut.setTransferStrategy(strategy); - sut.setFilterTemplates(List.of("A", "B", "C")); + sut.setFilters(List.of(A, B, C)); // Act & assert sut.doWork(); assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 10), - new ResourceAmount<>("C", 10) + new ResourceAmount(A, 10), + new ResourceAmount(C, 10) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("B", 10) + new ResourceAmount(B, 10) ); sut.doWork(); assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("B", 10), - new ResourceAmount<>("C", 10) + new ResourceAmount(B, 10), + new ResourceAmount(C, 10) ); sut.doWork(); assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("B", 10), - new ResourceAmount<>("C", 10) + new ResourceAmount(B, 10), + new ResourceAmount(C, 10) ); } } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/RandomExporterNetworkNodeTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/RandomExporterNetworkNodeTest.java index af95cfcdb..fe2e90ddc 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/RandomExporterNetworkNodeTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/RandomExporterNetworkNodeTest.java @@ -15,6 +15,8 @@ import org.junit.jupiter.api.Test; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; +import static com.refinedmods.refinedstorage2.network.test.TestResource.B; import static org.assertj.core.api.Assertions.assertThat; class RandomExporterNetworkNodeTest extends AbstractExporterNetworkNodeTest { @@ -22,73 +24,73 @@ class RandomExporterNetworkNodeTest extends AbstractExporterNetworkNodeTest { protected TaskExecutor createTaskExecutor() { return new RandomTaskExecutor<>(list -> { list.clear(); - list.add(sut.new TaskImpl("A")); - list.add(sut.new TaskImpl("B")); + list.add(sut.new TaskImpl(A)); + list.add(sut.new TaskImpl(B)); }); } @Test - void shouldTransfer(@InjectNetworkStorageChannel final StorageChannel storageChannel) { + void shouldTransfer(@InjectNetworkStorageChannel final StorageChannel storageChannel) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("B", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(B, 100, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new InMemoryStorageImpl<>(); + final Storage destination = new InMemoryStorageImpl(); final ExporterTransferStrategy strategy = createTransferStrategy(destination, 5); sut.setTransferStrategy(strategy); - sut.setFilterTemplates(List.of("B", "A")); + sut.setFilters(List.of(B, A)); // Act & assert sut.doWork(); - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 95), - new ResourceAmount<>("B", 100) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A, 95), + new ResourceAmount(B, 100) ); - assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 5) + assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( + new ResourceAmount(A, 5) ); sut.doWork(); - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 90), - new ResourceAmount<>("B", 100) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A, 90), + new ResourceAmount(B, 100) ); - assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 10) + assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( + new ResourceAmount(A, 10) ); } @Test void shouldUseNextResourceIfFirstOneIsNotAvailableInSameCycle( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("B", 7, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(B, 7, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new InMemoryStorageImpl<>(); + final Storage destination = new InMemoryStorageImpl(); final ExporterTransferStrategy strategy = createTransferStrategy(destination, 10); sut.setTransferStrategy(strategy); - sut.setFilterTemplates(List.of("A", "B")); + sut.setFilters(List.of(A, B)); // Act & assert sut.doWork(); assertThat(storageChannel.getAll()).isEmpty(); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("B", 7) + new ResourceAmount(B, 7) ); sut.doWork(); assertThat(storageChannel.getAll()).isEmpty(); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("B", 7) + new ResourceAmount(B, 7) ); } } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/RoundRobinExporterNetworkNodeTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/RoundRobinExporterNetworkNodeTest.java index e8183fde4..278f6c6b3 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/RoundRobinExporterNetworkNodeTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/exporter/RoundRobinExporterNetworkNodeTest.java @@ -16,6 +16,10 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; +import static com.refinedmods.refinedstorage2.network.test.TestResource.B; +import static com.refinedmods.refinedstorage2.network.test.TestResource.C; +import static com.refinedmods.refinedstorage2.network.test.TestResource.D; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -37,53 +41,53 @@ protected TaskExecutor createTaskExecutor() { } @Test - void shouldTransfer(@InjectNetworkStorageChannel final StorageChannel storageChannel) { + void shouldTransfer(@InjectNetworkStorageChannel final StorageChannel storageChannel) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("B", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(B, 100, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new InMemoryStorageImpl<>(); + final Storage destination = new InMemoryStorageImpl(); final ExporterTransferStrategy strategy = createTransferStrategy(destination, 5); sut.setTransferStrategy(strategy); - sut.setFilterTemplates(List.of("A", "B")); + sut.setFilters(List.of(A, B)); // Act & assert sut.doWork(); - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 95), - new ResourceAmount<>("B", 100) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A, 95), + new ResourceAmount(B, 100) ); - assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 5) + assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( + new ResourceAmount(A, 5) ); verify(listener, times(1)).run(); sut.doWork(); - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 95), - new ResourceAmount<>("B", 95) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A, 95), + new ResourceAmount(B, 95) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 5), - new ResourceAmount<>("B", 5) + new ResourceAmount(A, 5), + new ResourceAmount(B, 5) ); verify(listener, times(2)).run(); sut.doWork(); - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 90), - new ResourceAmount<>("B", 95) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A, 90), + new ResourceAmount(B, 95) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 10), - new ResourceAmount<>("B", 5) + new ResourceAmount(A, 10), + new ResourceAmount(B, 5) ); verify(listener, times(3)).run(); @@ -92,11 +96,11 @@ void shouldTransfer(@InjectNetworkStorageChannel final StorageChannel st @Test void shouldNotTransferIfThereAreNoResourcesInSource() { // Arrange - final Storage destination = new InMemoryStorageImpl<>(); + final Storage destination = new InMemoryStorageImpl(); final ExporterTransferStrategy strategy = createTransferStrategy(destination, 5); sut.setTransferStrategy(strategy); - sut.setFilterTemplates(List.of("A", "B")); + sut.setFilters(List.of(A, B)); // Act & assert sut.doWork(); @@ -105,132 +109,132 @@ void shouldNotTransferIfThereAreNoResourcesInSource() { @Test void shouldUseNextResourceIfFirstOneIsNotAvailableInSameCycle( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("C", 8, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("D", 9, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(C, 8, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(D, 9, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new InMemoryStorageImpl<>(); + final Storage destination = new InMemoryStorageImpl(); final ExporterTransferStrategy strategy = createTransferStrategy(destination, 10); sut.setTransferStrategy(strategy); - sut.setFilterTemplates(List.of("A", "B", "C", "D")); + sut.setFilters(List.of(A, B, C, D)); // Act & assert sut.doWork(); assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("D", 9) + new ResourceAmount(D, 9) ); - assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("C", 8) + assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( + new ResourceAmount(C, 8) ); sut.doWork(); assertThat(storageChannel.getAll()).isEmpty(); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("C", 8), - new ResourceAmount<>("D", 9) + new ResourceAmount(C, 8), + new ResourceAmount(D, 9) ); sut.doWork(); assertThat(storageChannel.getAll()).isEmpty(); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("C", 8), - new ResourceAmount<>("D", 9) + new ResourceAmount(C, 8), + new ResourceAmount(D, 9) ); - storageChannel.insert("A", 1, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("B", 2, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(A, 1, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(B, 2, Action.EXECUTE, EmptyActor.INSTANCE); sut.doWork(); assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("B", 2) + new ResourceAmount(B, 2) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 1), - new ResourceAmount<>("C", 8), - new ResourceAmount<>("D", 9) + new ResourceAmount(A, 1), + new ResourceAmount(C, 8), + new ResourceAmount(D, 9) ); sut.doWork(); assertThat(storageChannel.getAll()).isEmpty(); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 1), - new ResourceAmount<>("B", 2), - new ResourceAmount<>("C", 8), - new ResourceAmount<>("D", 9) + new ResourceAmount(A, 1), + new ResourceAmount(B, 2), + new ResourceAmount(C, 8), + new ResourceAmount(D, 9) ); sut.doWork(); assertThat(storageChannel.getAll()).isEmpty(); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 1), - new ResourceAmount<>("B", 2), - new ResourceAmount<>("C", 8), - new ResourceAmount<>("D", 9) + new ResourceAmount(A, 1), + new ResourceAmount(B, 2), + new ResourceAmount(C, 8), + new ResourceAmount(D, 9) ); } @Test - void shouldResetRoundRobinStateAfterChangingTemplates( - @InjectNetworkStorageChannel final StorageChannel storageChannel + void shouldResetRoundRobinStateAfterChangingFilters( + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("B", 100, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("C", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(B, 100, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(C, 100, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage destination = new InMemoryStorageImpl<>(); + final Storage destination = new InMemoryStorageImpl(); final ExporterTransferStrategy strategy = createTransferStrategy(destination, 5); sut.setTransferStrategy(strategy); - sut.setFilterTemplates(List.of("A", "B", "C")); + sut.setFilters(List.of(A, B, C)); // Act & assert sut.doWork(); - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 95), - new ResourceAmount<>("B", 100), - new ResourceAmount<>("C", 100) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A, 95), + new ResourceAmount(B, 100), + new ResourceAmount(C, 100) ); - assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 5) + assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( + new ResourceAmount(A, 5) ); sut.doWork(); - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 95), - new ResourceAmount<>("B", 95), - new ResourceAmount<>("C", 100) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A, 95), + new ResourceAmount(B, 95), + new ResourceAmount(C, 100) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 5), - new ResourceAmount<>("B", 5) + new ResourceAmount(A, 5), + new ResourceAmount(B, 5) ); // Now C would be the next one, but we expect to go back to A. - sut.setFilterTemplates(List.of("A", "C")); + sut.setFilters(List.of(A, C)); sut.doWork(); - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 90), - new ResourceAmount<>("B", 95), - new ResourceAmount<>("C", 100) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A, 90), + new ResourceAmount(B, 95), + new ResourceAmount(C, 100) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 10), - new ResourceAmount<>("B", 5) + new ResourceAmount(A, 10), + new ResourceAmount(B, 5) ); } } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/ExternalStorageNetworkNodeTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/ExternalStorageNetworkNodeTest.java index 984394049..bc6bff232 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/ExternalStorageNetworkNodeTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/ExternalStorageNetworkNodeTest.java @@ -1,9 +1,9 @@ package com.refinedmods.refinedstorage2.api.network.impl.node.externalstorage; import com.refinedmods.refinedstorage2.api.core.Action; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; import com.refinedmods.refinedstorage2.api.storage.AccessMode; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; @@ -30,6 +30,9 @@ import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.ValueSource; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; +import static com.refinedmods.refinedstorage2.network.test.TestResource.B; +import static com.refinedmods.refinedstorage2.network.test.TestResource.C; import static com.refinedmods.refinedstorage2.network.test.nodefactory.AbstractNetworkNodeFactory.PROPERTY_ENERGY_USAGE; import static org.assertj.core.api.Assertions.assertThat; @@ -45,10 +48,10 @@ class ExternalStorageNetworkNodeTest { ExternalStorageNetworkNode sut; @Test - void testInitialState(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void testInitialState(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Act - final long inserted = networkStorage.insert("A", 10, Action.EXECUTE, FakeActor.INSTANCE); - final long extracted = networkStorage.extract("A", 10, Action.EXECUTE, FakeActor.INSTANCE); + final long inserted = networkStorage.insert(A, 10, Action.EXECUTE, FakeActor.INSTANCE); + final long extracted = networkStorage.extract(A, 10, Action.EXECUTE, FakeActor.INSTANCE); // Assert assertThat(inserted).isZero(); @@ -59,14 +62,14 @@ void testInitialState(@InjectNetworkStorageChannel final StorageChannel assertThat(sut.getFilterMode()).isEqualTo(FilterMode.BLOCK); assertThat(networkStorage.getAll()).isEmpty(); assertThat(networkStorage.getStored()).isZero(); - assertThat(networkStorage.findTrackedResourceByActorType("A", FakeActor.class)).isEmpty(); + assertThat(networkStorage.findTrackedResourceByActorType(A, FakeActor.class)).isEmpty(); } @Test - void shouldInitialize(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldInitialize(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage = new InMemoryStorageImpl<>(); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new InMemoryStorageImpl(); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); // Act sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); @@ -78,92 +81,92 @@ void shouldInitialize(@InjectNetworkStorageChannel final StorageChannel @Test void shouldBeAbleToInitializeMultipleTimes( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final Storage storage1 = new InMemoryStorageImpl<>(); - final ExternalStorageProvider provider1 = new StorageExternalStorageProvider<>(storage1); + final Storage storage1 = new InMemoryStorageImpl(); + final ExternalStorageProvider provider1 = new StorageExternalStorageProvider(storage1); - final Storage storage2 = new InMemoryStorageImpl<>(); - final ExternalStorageProvider provider2 = new StorageExternalStorageProvider<>(storage2); + final Storage storage2 = new InMemoryStorageImpl(); + final ExternalStorageProvider provider2 = new StorageExternalStorageProvider(storage2); // Act sut.initialize(new ExternalStorageProviderFactoryImpl(provider1)); - networkStorage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + networkStorage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.initialize(new ExternalStorageProviderFactoryImpl(provider2)); - networkStorage.insert("B", 1, Action.EXECUTE, EmptyActor.INSTANCE); + networkStorage.insert(B, 1, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("B", 1) + new ResourceAmount(B, 1) ); assertThat(networkStorage.getStored()).isEqualTo(1); assertThat(storage1.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(storage2.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("B", 1) + new ResourceAmount(B, 1) ); } @Test - void shouldInsert(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldInsert(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage = new InMemoryStorageImpl<>(); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new InMemoryStorageImpl(); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); // Act - final long inserted = networkStorage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted = networkStorage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted).isEqualTo(10); assertThat(storage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(networkStorage.getStored()).isEqualTo(10); } @Test - void shouldExtract(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldExtract(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage = new InMemoryStorageImpl<>(); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new InMemoryStorageImpl(); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); // Act - final long extracted = networkStorage.extract("A", 7, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = networkStorage.extract(A, 7, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(7); assertThat(storage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 3) + new ResourceAmount(A, 3) ); assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 3) + new ResourceAmount(A, 3) ); assertThat(networkStorage.getStored()).isEqualTo(3); } @Test - void shouldRespectAllowlistWhenInserting(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldRespectAllowlistWhenInserting(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange sut.setFilterMode(FilterMode.ALLOW); - sut.setFilterTemplates(Set.of("A", "B")); + sut.setFilters(Set.of(A, B)); - final Storage storage = new InMemoryStorageImpl<>(); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new InMemoryStorageImpl(); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); // Act - final long inserted1 = networkStorage.insert("A", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted2 = networkStorage.insert("B", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted3 = networkStorage.insert("C", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted1 = networkStorage.insert(A, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted2 = networkStorage.insert(B, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted3 = networkStorage.insert(C, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted1).isEqualTo(12); @@ -173,20 +176,20 @@ void shouldRespectAllowlistWhenInserting(@InjectNetworkStorageChannel final Stor @Test void shouldRespectEmptyAllowlistWhenInserting( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange sut.setFilterMode(FilterMode.ALLOW); - sut.setFilterTemplates(Set.of()); + sut.setFilters(Set.of()); - final Storage storage = new InMemoryStorageImpl<>(); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new InMemoryStorageImpl(); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); // Act - final long inserted1 = networkStorage.insert("A", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted2 = networkStorage.insert("B", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted3 = networkStorage.insert("C", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted1 = networkStorage.insert(A, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted2 = networkStorage.insert(B, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted3 = networkStorage.insert(C, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted1).isZero(); @@ -195,19 +198,19 @@ void shouldRespectEmptyAllowlistWhenInserting( } @Test - void shouldRespectBlocklistWhenInserting(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldRespectBlocklistWhenInserting(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange sut.setFilterMode(FilterMode.BLOCK); - sut.setFilterTemplates(Set.of("A", "B")); + sut.setFilters(Set.of(A, B)); - final Storage storage = new InMemoryStorageImpl<>(); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new InMemoryStorageImpl(); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); // Act - final long inserted1 = networkStorage.insert("A", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted2 = networkStorage.insert("B", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted3 = networkStorage.insert("C", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted1 = networkStorage.insert(A, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted2 = networkStorage.insert(B, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted3 = networkStorage.insert(C, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted1).isZero(); @@ -217,19 +220,19 @@ void shouldRespectBlocklistWhenInserting(@InjectNetworkStorageChannel final Stor @Test void shouldRespectEmptyBlocklistWhenInserting( - @InjectNetworkStorageChannel final StorageChannel networkStorage) { + @InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange sut.setFilterMode(FilterMode.BLOCK); - sut.setFilterTemplates(Set.of()); + sut.setFilters(Set.of()); - final Storage storage = new InMemoryStorageImpl<>(); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new InMemoryStorageImpl(); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); // Act - final long inserted1 = networkStorage.insert("A", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted2 = networkStorage.insert("B", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted3 = networkStorage.insert("C", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted1 = networkStorage.insert(A, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted2 = networkStorage.insert(B, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted3 = networkStorage.insert(C, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted1).isEqualTo(12); @@ -240,17 +243,17 @@ void shouldRespectEmptyBlocklistWhenInserting( @ParameterizedTest @EnumSource(AccessMode.class) void shouldRespectAccessModeWhenInserting(final AccessMode accessMode, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange sut.setAccessMode(accessMode); - final Storage storage = new InMemoryStorageImpl<>(); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new InMemoryStorageImpl(); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); // Act - final long inserted = networkStorage.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted = networkStorage.insert(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); // Assert switch (accessMode) { @@ -262,19 +265,19 @@ void shouldRespectAccessModeWhenInserting(final AccessMode accessMode, @ParameterizedTest @EnumSource(AccessMode.class) void shouldRespectAccessModeWhenExtracting(final AccessMode accessMode, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange sut.setAccessMode(accessMode); - final Storage storage = new InMemoryStorageImpl<>(); - storage.insert("A", 20, Action.EXECUTE, EmptyActor.INSTANCE); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new InMemoryStorageImpl(); + storage.insert(A, 20, Action.EXECUTE, EmptyActor.INSTANCE); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); // Act - final long extracted = networkStorage.extract("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = networkStorage.extract(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); // Assert switch (accessMode) { @@ -284,33 +287,33 @@ void shouldRespectAccessModeWhenExtracting(final AccessMode accessMode, } @Test - void shouldNotInsertWhenInactive(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldNotInsertWhenInactive(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage = new InMemoryStorageImpl<>(); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new InMemoryStorageImpl(); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); sut.setActive(false); // Act - final long inserted = networkStorage.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted = networkStorage.insert(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted).isZero(); } @Test - void shouldNotExtractWhenInactive(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldNotExtractWhenInactive(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage = new InMemoryStorageImpl<>(); - storage.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new InMemoryStorageImpl(); + storage.insert(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); sut.setActive(false); // Act - final long extracted = networkStorage.extract("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = networkStorage.extract(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(extracted).isZero(); @@ -318,15 +321,15 @@ void shouldNotExtractWhenInactive(@InjectNetworkStorageChannel final StorageChan @Test void shouldHideStorageContentsWhenInactive( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new LimitedStorageImpl(100); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); - networkStorage.insert("A", 50, Action.EXECUTE, EmptyActor.INSTANCE); - networkStorage.insert("B", 50, Action.EXECUTE, EmptyActor.INSTANCE); + networkStorage.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); + networkStorage.insert(B, 50, Action.EXECUTE, EmptyActor.INSTANCE); // Act sut.setActive(false); @@ -337,14 +340,14 @@ void shouldHideStorageContentsWhenInactive( } @Test - void shouldShowStorageContentsWhenActive(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldShowStorageContentsWhenActive(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new LimitedStorageImpl(100); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); - networkStorage.insert("A", 50, Action.EXECUTE, EmptyActor.INSTANCE); - networkStorage.insert("B", 50, Action.EXECUTE, EmptyActor.INSTANCE); + networkStorage.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); + networkStorage.insert(B, 50, Action.EXECUTE, EmptyActor.INSTANCE); sut.setActive(false); @@ -353,27 +356,27 @@ void shouldShowStorageContentsWhenActive(@InjectNetworkStorageChannel final Stor // Assert assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 50), - new ResourceAmount<>("B", 50) + new ResourceAmount(A, 50), + new ResourceAmount(B, 50) ); } @Test void shouldNoLongerShowOnNetworkWhenRemoved( - @InjectNetworkStorageChannel final StorageChannel networkStorage, + @InjectNetworkStorageChannel final StorageChannel networkStorage, @InjectNetwork final Network network ) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - storage.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new LimitedStorageImpl(100); + storage.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); // Act & assert network.removeContainer(() -> sut); assertThat(networkStorage.getAll()).isEmpty(); - storage.insert("B", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(B, 100, Action.EXECUTE, EmptyActor.INSTANCE); sut.detectChanges(); assertThat(networkStorage.getAll()).isEmpty(); @@ -381,15 +384,15 @@ void shouldNoLongerShowOnNetworkWhenRemoved( @Test void shouldNotifyNewNetworkAboutChangesWhenChangingNetworks( - @InjectNetworkStorageChannel final StorageChannel networkStorage, - @InjectNetworkStorageChannel(networkId = "other") final StorageChannel otherNetworkStorage, + @InjectNetworkStorageChannel final StorageChannel networkStorage, + @InjectNetworkStorageChannel(networkId = "other") final StorageChannel otherNetworkStorage, @InjectNetwork final Network network, @InjectNetwork("other") final Network otherNetwork ) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - storage.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new LimitedStorageImpl(100); + storage.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); // Act & assert @@ -402,7 +405,7 @@ void shouldNotifyNewNetworkAboutChangesWhenChangingNetworks( assertThat(networkStorage.getAll()).isEmpty(); // Now reinsert. - storage.insert("B", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(B, 100, Action.EXECUTE, EmptyActor.INSTANCE); sut.detectChanges(); // This is the desired state, the old parent should be cleaned up and not used. @@ -412,15 +415,15 @@ void shouldNotifyNewNetworkAboutChangesWhenChangingNetworks( @Test void shouldNoLongerNotifyOldNetworkAboutChangesWhenChangingNetworks( - @InjectNetworkStorageChannel final StorageChannel networkStorage, - @InjectNetworkStorageChannel(networkId = "other") final StorageChannel otherNetworkStorage, + @InjectNetworkStorageChannel final StorageChannel networkStorage, + @InjectNetworkStorageChannel(networkId = "other") final StorageChannel otherNetworkStorage, @InjectNetwork final Network network, @InjectNetwork("other") final Network otherNetwork ) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - storage.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new LimitedStorageImpl(100); + storage.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); // Act & assert @@ -437,7 +440,7 @@ void shouldNoLongerNotifyOldNetworkAboutChangesWhenChangingNetworks( sut.setActive(true); // Now reinsert. - storage.insert("B", 100, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(B, 100, Action.EXECUTE, EmptyActor.INSTANCE); sut.detectChanges(); // This is the desired state, the old parent should be cleaned up and not used. @@ -447,7 +450,7 @@ void shouldNoLongerNotifyOldNetworkAboutChangesWhenChangingNetworks( @Test void shouldNoLongerShowOnNetworkWhenRemovedWithoutInitializedStorage( - @InjectNetworkStorageChannel final StorageChannel networkStorage, + @InjectNetworkStorageChannel final StorageChannel networkStorage, @InjectNetwork final Network network ) { // Act @@ -462,12 +465,12 @@ void shouldNoLongerShowOnNetworkWhenRemovedWithoutInitializedStorage( @EnumSource(Action.class) void shouldTrackChangesWhenExtracting( final Action action, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new LimitedStorageImpl(100); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); final AtomicBoolean trackedResourceWasPresent = trackWhetherResourceHasChangedAndTrackedResourceIsAvailable( @@ -475,12 +478,12 @@ void shouldTrackChangesWhenExtracting( ); // Act - final long extracted = networkStorage.extract("A", 7, action, FakeActor.INSTANCE); + final long extracted = networkStorage.extract(A, 7, action, FakeActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(7); final Optional trackedResource = networkStorage.findTrackedResourceByActorType( - "A", + A, FakeActor.class ); if (action == Action.EXECUTE) { @@ -499,20 +502,20 @@ void shouldTrackChangesWhenExtracting( @EnumSource(Action.class) void shouldNotTrackChangesWhenExtractionFailed( final Action action, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new LimitedStorageImpl(100); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); // Act - final long extracted = networkStorage.extract("A", 7, action, FakeActor.INSTANCE); + final long extracted = networkStorage.extract(A, 7, action, FakeActor.INSTANCE); // Assert assertThat(extracted).isZero(); final Optional trackedResource = networkStorage.findTrackedResourceByActorType( - "A", + A, FakeActor.class ); assertThat(trackedResource).isEmpty(); @@ -522,11 +525,11 @@ void shouldNotTrackChangesWhenExtractionFailed( @EnumSource(Action.class) void shouldTrackChangesWhenInserting( final Action action, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new LimitedStorageImpl(100); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); final AtomicBoolean trackedResourceWasPresent = trackWhetherResourceHasChangedAndTrackedResourceIsAvailable( @@ -534,12 +537,12 @@ void shouldTrackChangesWhenInserting( ); // Act - final long inserted = networkStorage.insert("A", 10, action, FakeActor.INSTANCE); + final long inserted = networkStorage.insert(A, 10, action, FakeActor.INSTANCE); // Assert assertThat(inserted).isEqualTo(10); final Optional trackedResource = networkStorage.findTrackedResourceByActorType( - "A", + A, FakeActor.class ); if (action == Action.EXECUTE) { @@ -558,32 +561,32 @@ void shouldTrackChangesWhenInserting( @EnumSource(Action.class) void shouldNotTrackChangesWhenInsertionFailed( final Action action, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final Storage storage = new LimitedStorageImpl<>(0); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new LimitedStorageImpl(0); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); // Act - final long inserted = networkStorage.insert("A", 10, action, FakeActor.INSTANCE); + final long inserted = networkStorage.insert(A, 10, action, FakeActor.INSTANCE); // Assert assertThat(inserted).isZero(); final Optional trackedResource = networkStorage.findTrackedResourceByActorType( - "A", + A, FakeActor.class ); assertThat(trackedResource).isEmpty(); } private AtomicBoolean trackWhetherResourceHasChangedAndTrackedResourceIsAvailable( - final StorageChannel networkStorage + final StorageChannel networkStorage ) { final AtomicBoolean found = new AtomicBoolean(); networkStorage.addListener(change -> { - if (change.resourceAmount().getResource().equals("A")) { - found.set(networkStorage.findTrackedResourceByActorType("A", FakeActor.class).isPresent()); + if (change.resourceAmount().getResource().equals(A)) { + found.set(networkStorage.findTrackedResourceByActorType(A, FakeActor.class).isPresent()); } }); return found; @@ -599,24 +602,24 @@ void shouldNotDetectChangesWithoutConnectedStorage() { } @Test - void shouldDetectChanges(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldDetectChanges(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - final ExternalStorageProvider provider = new StorageExternalStorageProvider<>(storage); + final Storage storage = new LimitedStorageImpl(100); + final ExternalStorageProvider provider = new StorageExternalStorageProvider(storage); sut.initialize(new ExternalStorageProviderFactoryImpl(provider)); // Act - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); final boolean hasChanges1 = sut.detectChanges(); - networkStorage.insert("B", 1, Action.EXECUTE, EmptyActor.INSTANCE); + networkStorage.insert(B, 1, Action.EXECUTE, EmptyActor.INSTANCE); final boolean hasChanges2 = sut.detectChanges(); // Assert assertThat(hasChanges1).isTrue(); assertThat(hasChanges2).isFalse(); assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 10), - new ResourceAmount<>("B", 1) + new ResourceAmount(A, 10), + new ResourceAmount(B, 1) ); } @@ -628,14 +631,14 @@ class PriorityTest { @ParameterizedTest @ValueSource(booleans = {true, false}) void shouldRespectPriority(final boolean oneHasPriority, - @InjectNetworkStorageChannel final StorageChannel networkStorage) { + @InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage1 = new TrackedStorageImpl<>(new LimitedStorageImpl<>(100), () -> 0L); - final ExternalStorageProvider provider1 = new StorageExternalStorageProvider<>(storage1); + final Storage storage1 = new TrackedStorageImpl(new LimitedStorageImpl(100), () -> 0L); + final ExternalStorageProvider provider1 = new StorageExternalStorageProvider(storage1); sut.initialize(new ExternalStorageProviderFactoryImpl(provider1)); - final Storage storage2 = new TrackedStorageImpl<>(new LimitedStorageImpl<>(100), () -> 0L); - final ExternalStorageProvider provider2 = new StorageExternalStorageProvider<>(storage2); + final Storage storage2 = new TrackedStorageImpl(new LimitedStorageImpl(100), () -> 0L); + final ExternalStorageProvider provider2 = new StorageExternalStorageProvider(storage2); otherStorage.initialize(new ExternalStorageProviderFactoryImpl(provider2)); if (oneHasPriority) { @@ -647,7 +650,7 @@ void shouldRespectPriority(final boolean oneHasPriority, } // Act - networkStorage.insert("A", 1, Action.EXECUTE, EmptyActor.INSTANCE); + networkStorage.insert(A, 1, Action.EXECUTE, EmptyActor.INSTANCE); // Assert if (oneHasPriority) { diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/ExternalStorageProviderFactoryImpl.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/ExternalStorageProviderFactoryImpl.java index 9e5b233d3..ef9b2f787 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/ExternalStorageProviderFactoryImpl.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/ExternalStorageProviderFactoryImpl.java @@ -1,20 +1,14 @@ package com.refinedmods.refinedstorage2.api.network.impl.node.externalstorage; import com.refinedmods.refinedstorage2.api.network.node.externalstorage.ExternalStorageProviderFactory; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.api.storage.external.ExternalStorageProvider; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import java.util.Optional; -public record ExternalStorageProviderFactoryImpl(ExternalStorageProvider provider) +public record ExternalStorageProviderFactoryImpl(ExternalStorageProvider provider) implements ExternalStorageProviderFactory { @Override - @SuppressWarnings("unchecked") - public Optional> create(final StorageChannelType channelType) { - if (channelType == NetworkTestFixtures.STORAGE_CHANNEL_TYPE) { - return Optional.of((ExternalStorageProvider) provider); - } - return Optional.empty(); + public Optional create() { + return Optional.of(provider); } } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/StorageExternalStorageProvider.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/StorageExternalStorageProvider.java index 88a596e00..b3e79b8c3 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/StorageExternalStorageProvider.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/externalstorage/StorageExternalStorageProvider.java @@ -2,31 +2,32 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.Storage; import com.refinedmods.refinedstorage2.api.storage.external.ExternalStorageProvider; import java.util.Iterator; -public class StorageExternalStorageProvider implements ExternalStorageProvider { - private final Storage storage; +public class StorageExternalStorageProvider implements ExternalStorageProvider { + private final Storage storage; - public StorageExternalStorageProvider(final Storage storage) { + public StorageExternalStorageProvider(final Storage storage) { this.storage = storage; } @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return storage.extract(resource, amount, action, actor); } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return storage.insert(resource, amount, action, actor); } @Override - public Iterator> iterator() { + public Iterator iterator() { return storage.getAll().iterator(); } } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/grid/GridNetworkNodeTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/grid/GridNetworkNodeTest.java index 9a90acb90..c90aa1436 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/grid/GridNetworkNodeTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/grid/GridNetworkNodeTest.java @@ -3,6 +3,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.grid.watcher.GridWatcher; import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; @@ -14,7 +15,6 @@ import com.refinedmods.refinedstorage2.network.test.InjectNetwork; import com.refinedmods.refinedstorage2.network.test.InjectNetworkStorageChannel; import com.refinedmods.refinedstorage2.network.test.NetworkTest; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import com.refinedmods.refinedstorage2.network.test.SetupNetwork; import com.refinedmods.refinedstorage2.network.test.nodefactory.AbstractNetworkNodeFactory; import com.refinedmods.refinedstorage2.network.test.util.FakeActor; @@ -23,6 +23,10 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; +import static com.refinedmods.refinedstorage2.network.test.TestResource.B; +import static com.refinedmods.refinedstorage2.network.test.TestResource.C; +import static com.refinedmods.refinedstorage2.network.test.TestResource.D; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyLong; @@ -44,14 +48,14 @@ class GridNetworkNodeTest { @BeforeEach void setUp( - @InjectNetworkStorageChannel final StorageChannel storage, - @InjectNetworkStorageChannel(networkId = "other") final StorageChannel otherStorageChannel + @InjectNetworkStorageChannel final StorageChannel storage, + @InjectNetworkStorageChannel(networkId = "other") final StorageChannel otherStorageChannel ) { - storage.addSource(new TrackedStorageImpl<>(new LimitedStorageImpl<>(1000), () -> 2L)); - storage.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); - storage.insert("B", 200, Action.EXECUTE, EmptyActor.INSTANCE); + storage.addSource(new TrackedStorageImpl(new LimitedStorageImpl(1000), () -> 2L)); + storage.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(B, 200, Action.EXECUTE, EmptyActor.INSTANCE); - otherStorageChannel.addSource(new TrackedStorageImpl<>(new InMemoryStorageImpl<>(), () -> 3L)); + otherStorageChannel.addSource(new TrackedStorageImpl(new InMemoryStorageImpl(), () -> 3L)); } @Test @@ -81,29 +85,28 @@ void shouldNotifyWatchersOfActivenessChanges() { @Test void shouldNotifyWatchersOfStorageChanges( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange final GridWatcher watcher = mock(GridWatcher.class); sut.addWatcher(watcher, FakeActor.class); // Act - networkStorage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - networkStorage.insert("A", 1, Action.EXECUTE, FakeActor.INSTANCE); + networkStorage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + networkStorage.insert(A, 1, Action.EXECUTE, FakeActor.INSTANCE); sut.removeWatcher(watcher); - networkStorage.insert("A", 1, Action.EXECUTE, FakeActor.INSTANCE); + networkStorage.insert(A, 1, Action.EXECUTE, FakeActor.INSTANCE); // Assert - final ArgumentCaptor resources = ArgumentCaptor.forClass(String.class); + final ArgumentCaptor resources = ArgumentCaptor.forClass(ResourceKey.class); final ArgumentCaptor trackedResources = ArgumentCaptor.forClass(TrackedResource.class); verify(watcher, times(2)).onChanged( - eq(NetworkTestFixtures.STORAGE_CHANNEL_TYPE), resources.capture(), anyLong(), trackedResources.capture() ); - assertThat(resources.getAllValues()).containsExactly("A", "A"); + assertThat(resources.getAllValues()).containsExactly(A, A); assertThat(trackedResources.getAllValues()) .usingRecursiveFieldByFieldElementComparator() .containsExactly(null, new TrackedResource("Fake", 2)); @@ -138,36 +141,35 @@ void shouldNotBeAbleToAddDuplicateWatcher() { void shouldDetachWatchersFromOldNetworkAndReattachToNewNetwork( @InjectNetwork("other") final Network otherNetwork, @InjectNetwork final Network network, - @InjectNetworkStorageChannel final StorageChannel storageChannel, - @InjectNetworkStorageChannel(networkId = "other") final StorageChannel otherStorageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel, + @InjectNetworkStorageChannel(networkId = "other") final StorageChannel otherStorageChannel ) { // Arrange final GridWatcher watcher = mock(GridWatcher.class); sut.addWatcher(watcher, FakeActor.class); // Act - // this one shouldn't be ignored! - otherStorageChannel.insert("C", 10, Action.EXECUTE, FakeActor.INSTANCE); + // This one shouldn't be ignored! + otherStorageChannel.insert(C, 10, Action.EXECUTE, FakeActor.INSTANCE); sut.setNetwork(otherNetwork); network.removeContainer(() -> sut); otherNetwork.addContainer(() -> sut); // these one shouldn't be ignored either - otherStorageChannel.insert("A", 10, Action.EXECUTE, FakeActor.INSTANCE); - otherStorageChannel.insert("D", 10, Action.EXECUTE, EmptyActor.INSTANCE); + otherStorageChannel.insert(A, 10, Action.EXECUTE, FakeActor.INSTANCE); + otherStorageChannel.insert(D, 10, Action.EXECUTE, EmptyActor.INSTANCE); // these should be ignored - storageChannel.insert("B", 10, Action.EXECUTE, FakeActor.INSTANCE); - storageChannel.insert("D", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(B, 10, Action.EXECUTE, FakeActor.INSTANCE); + storageChannel.insert(D, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert verify(watcher, times(1)).invalidate(); final ArgumentCaptor trackedResources1 = ArgumentCaptor.forClass(TrackedResource.class); verify(watcher, times(1)).onChanged( - eq(NetworkTestFixtures.STORAGE_CHANNEL_TYPE), - eq("C"), + eq(C), eq(10L), trackedResources1.capture() ); @@ -177,8 +179,7 @@ void shouldDetachWatchersFromOldNetworkAndReattachToNewNetwork( final ArgumentCaptor trackedResources2 = ArgumentCaptor.forClass(TrackedResource.class); verify(watcher, times(1)).onChanged( - eq(NetworkTestFixtures.STORAGE_CHANNEL_TYPE), - eq("A"), + eq(A), eq(10L), trackedResources2.capture() ); @@ -187,8 +188,7 @@ void shouldDetachWatchersFromOldNetworkAndReattachToNewNetwork( .allMatch(t -> FakeActor.INSTANCE.getName().equals(t.getSourceName())); verify(watcher, times(1)).onChanged( - eq(NetworkTestFixtures.STORAGE_CHANNEL_TYPE), - eq("D"), + eq(D), eq(10L), isNull() ); diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/ClearSlotInterfaceNetworkNodeTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/ClearSlotInterfaceNetworkNodeTest.java index 77d212a9b..673d43a55 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/ClearSlotInterfaceNetworkNodeTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/ClearSlotInterfaceNetworkNodeTest.java @@ -2,18 +2,18 @@ import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.api.storage.limited.LimitedStorageImpl; import com.refinedmods.refinedstorage2.network.test.AddNetworkNode; import com.refinedmods.refinedstorage2.network.test.InjectNetworkStorageChannel; import com.refinedmods.refinedstorage2.network.test.NetworkTest; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import com.refinedmods.refinedstorage2.network.test.SetupNetwork; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; +import static com.refinedmods.refinedstorage2.network.test.TestResource.B; import static org.assertj.core.api.Assertions.assertThat; @NetworkTest @@ -34,55 +34,49 @@ void setUp() { @Test void shouldClearSlotWhenNoLongerRequestingAnything( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); + storageChannel.addSource(new InMemoryStorageImpl()); - exportState.setCurrentlyExported(1, "A", 7); - exportState.setCurrentlyExported(2, "B", 2); + exportState.setCurrentlyExported(1, A, 7); + exportState.setCurrentlyExported(2, B, 2); // Act & assert sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(5); assertThat(exportState.getExportedResource(2)).isNull(); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("A", 2), - new ResourceAmount<>("B", 2) + new ResourceAmount(A, 2), + new ResourceAmount(B, 2) ); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(3); assertThat(exportState.getExportedResource(2)).isNull(); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("A", 4), - new ResourceAmount<>("B", 2) + new ResourceAmount(A, 4), + new ResourceAmount(B, 2) ); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(1); assertThat(exportState.getExportedResource(2)).isNull(); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("A", 6), - new ResourceAmount<>("B", 2) + new ResourceAmount(A, 6), + new ResourceAmount(B, 2) ); sut.doWork(); @@ -92,8 +86,8 @@ void shouldClearSlotWhenNoLongerRequestingAnything( assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("A", 7), - new ResourceAmount<>("B", 2) + new ResourceAmount(A, 7), + new ResourceAmount(B, 2) ); sut.doWork(); @@ -105,72 +99,64 @@ void shouldClearSlotWhenNoLongerRequestingAnything( assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("A", 7), - new ResourceAmount<>("B", 2) + new ResourceAmount(A, 7), + new ResourceAmount(B, 2) ); } @Test void shouldClearSlotPartiallyWhenNoLongerRequestingAnythingButNetworkDoesNotHaveEnoughSpace( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new LimitedStorageImpl<>(3)); + storageChannel.addSource(new LimitedStorageImpl(3)); - exportState.setCurrentlyExported(1, "A", 7); + exportState.setCurrentlyExported(1, A, 7); // Act & assert sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(5); assertThat(exportState.getExportedResource(2)).isNull(); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 2)); + .containsExactly(new ResourceAmount(A, 2)); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(4); assertThat(exportState.getExportedResource(2)).isNull(); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 3)); + .containsExactly(new ResourceAmount(A, 3)); sut.doWork(); sut.doWork(); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(4); assertThat(exportState.getExportedResource(2)).isNull(); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 3)); + .containsExactly(new ResourceAmount(A, 3)); } @Test void shouldNotClearSlotWhenNoLongerRequestingAnythingAndNetworkDoesNotHaveEnoughSpace( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - exportState.setCurrentlyExported(1, "A", 7); + exportState.setCurrentlyExported(1, A, 7); // Act sut.doWork(); // Assert assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(7); assertThat(exportState.getExportedResource(2)).isNull(); diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/ExportToEmptySlotInterfaceNetworkNodeTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/ExportToEmptySlotInterfaceNetworkNodeTest.java index 97ff84814..7a41bd42b 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/ExportToEmptySlotInterfaceNetworkNodeTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/ExportToEmptySlotInterfaceNetworkNodeTest.java @@ -4,17 +4,19 @@ import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.network.test.AddNetworkNode; import com.refinedmods.refinedstorage2.network.test.InjectNetworkStorageChannel; import com.refinedmods.refinedstorage2.network.test.NetworkTest; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import com.refinedmods.refinedstorage2.network.test.SetupNetwork; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A_ALTERNATIVE; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A_ALTERNATIVE2; +import static com.refinedmods.refinedstorage2.network.test.TestResource.B; import static org.assertj.core.api.Assertions.assertThat; @NetworkTest @@ -35,11 +37,11 @@ void setUp() { @Test void shouldNotExportToEmptySlotWhenRequestedIsNotAvailable( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - exportState.setRequestedResource(1, "A", 1); - exportState.setRequestedResource(2, "B", 1); + exportState.setRequestedResource(1, A, 1); + exportState.setRequestedResource(2, B, 1); // Act sut.doWork(); @@ -53,13 +55,13 @@ void shouldNotExportToEmptySlotWhenRequestedIsNotAvailable( @Test void shouldExportToEmptySlotWhenRequestedIsNotEntirelyAvailable( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 2, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 2, Action.EXECUTE, EmptyActor.INSTANCE); - exportState.setRequestedResource(1, "A", 10); + exportState.setRequestedResource(1, A, 10); sut.setTransferQuotaProvider(resource -> 10); @@ -68,9 +70,7 @@ void shouldExportToEmptySlotWhenRequestedIsNotEntirelyAvailable( // Assert assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(2); assertThat(exportState.getExportedResource(2)).isNull(); @@ -79,91 +79,83 @@ void shouldExportToEmptySlotWhenRequestedIsNotEntirelyAvailable( @Test void shouldExportToEmptySlotWhenRequestedIsLessThanTransferQuota( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); - exportState.setRequestedResource(1, "A", 1); + exportState.setRequestedResource(1, A, 1); // Act sut.doWork(); // Assert assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(1); assertThat(exportState.getExportedResource(2)).isNull(); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 9)); + .containsExactly(new ResourceAmount(A, 9)); } @Test void shouldExportToEmptySlot( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("B", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(B, 10, Action.EXECUTE, EmptyActor.INSTANCE); - exportState.setRequestedResource(1, "A", 7); - exportState.setRequestedResource(2, "B", 2); + exportState.setRequestedResource(1, A, 7); + exportState.setRequestedResource(2, B, 2); // Act sut.doWork(); // Assert assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(2); - assertThat(exportState.getExportedResource(2)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("B", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(2)).isEqualTo(B); assertThat(exportState.getExportedAmount(2)).isEqualTo(2); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("A", 8), - new ResourceAmount<>("B", 8) + new ResourceAmount(A, 8), + new ResourceAmount(B, 8) ); } @Test void shouldExportResourceFuzzilyToEmptySlot( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A1", 10, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("A2", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A_ALTERNATIVE, 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(A_ALTERNATIVE2, 10, Action.EXECUTE, EmptyActor.INSTANCE); - exportState.setRequestedResource(1, "A", 10); + exportState.setRequestedResource(1, A, 10); // Act sut.doWork(); // Assert assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A1", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A_ALTERNATIVE); assertThat(exportState.getExportedAmount(1)).isEqualTo(2); assertThat(exportState.getExportedResource(2)).isNull(); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("A1", 8), - new ResourceAmount<>("A2", 10) + new ResourceAmount(A_ALTERNATIVE, 8), + new ResourceAmount(A_ALTERNATIVE2, 10) ); } } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/InterfaceExportStateImpl.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/InterfaceExportStateImpl.java index e0e5f9b1e..df0b48887 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/InterfaceExportStateImpl.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/InterfaceExportStateImpl.java @@ -2,10 +2,8 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import java.util.ArrayList; import java.util.Collection; @@ -15,17 +13,21 @@ import java.util.Map; import javax.annotation.Nullable; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A_ALTERNATIVE; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A_ALTERNATIVE2; + public class InterfaceExportStateImpl implements InterfaceExportState { - private final Map> requested = new HashMap<>(); - private final Map> current = new HashMap<>(); + private final Map requested = new HashMap<>(); + private final Map current = new HashMap<>(); private final int slots; public InterfaceExportStateImpl(final int slots) { this.slots = slots; } - public void setRequestedResource(final int index, final String resource, final long amount) { - requested.put(index, new ResourceAmount<>(resource, amount)); + public void setRequestedResource(final int index, final ResourceKey resource, final long amount) { + requested.put(index, new ResourceAmount(resource, amount)); } public void clearRequestedResources() { @@ -38,31 +40,31 @@ public int getSlots() { } @Override - @SuppressWarnings("unchecked") - public Collection expandExportCandidates(final StorageChannel storageChannel, final T resource) { - if ("A".equals(resource)) { - return (Collection) expandExportCandidates((StorageChannel) storageChannel); + public Collection expandExportCandidates(final StorageChannel storageChannel, + final ResourceKey resource) { + if (A.equals(resource)) { + return expandExportCandidates(storageChannel); } return Collections.singletonList(resource); } - private Collection expandExportCandidates(final StorageChannel storageChannel) { - final List candidates = new ArrayList<>(); - candidates.add("A"); - // simulate the behavior from FuzzyStorageChannel - if (storageChannel.get("A1").isPresent()) { - candidates.add("A1"); + private Collection expandExportCandidates(final StorageChannel storageChannel) { + final List candidates = new ArrayList<>(); + candidates.add(A); + // Simulate the behavior from FuzzyStorageChannel + if (storageChannel.get(A_ALTERNATIVE).isPresent()) { + candidates.add(A_ALTERNATIVE); } - if (storageChannel.get("A2").isPresent()) { - candidates.add("A2"); + if (storageChannel.get(A_ALTERNATIVE2).isPresent()) { + candidates.add(A_ALTERNATIVE2); } return candidates; } @Override - public boolean isExportedResourceValid(final ResourceTemplate want, final ResourceTemplate got) { - if ("A".equals(want.resource())) { - return ((String) got.resource()).startsWith("A"); + public boolean isExportedResourceValid(final ResourceKey want, final ResourceKey got) { + if (A.equals(want)) { + return got == A || got == A_ALTERNATIVE || got == A_ALTERNATIVE2; } return got.equals(want); } @@ -75,19 +77,19 @@ private void validateIndex(final int index) { @Nullable @Override - public ResourceTemplate getRequestedResource(final int slotIndex) { + public ResourceKey getRequestedResource(final int slotIndex) { validateIndex(slotIndex); - final ResourceAmount resourceAmount = requested.get(slotIndex); + final ResourceAmount resourceAmount = requested.get(slotIndex); if (resourceAmount == null) { return null; } - return new ResourceTemplate<>(resourceAmount.getResource(), NetworkTestFixtures.STORAGE_CHANNEL_TYPE); + return resourceAmount.getResource(); } @Override public long getRequestedAmount(final int slotIndex) { validateIndex(slotIndex); - final ResourceAmount resourceAmount = requested.get(slotIndex); + final ResourceAmount resourceAmount = requested.get(slotIndex); if (resourceAmount == null) { return 0L; } @@ -96,19 +98,19 @@ public long getRequestedAmount(final int slotIndex) { @Nullable @Override - public ResourceTemplate getExportedResource(final int slotIndex) { + public ResourceKey getExportedResource(final int slotIndex) { validateIndex(slotIndex); - final ResourceAmount resourceAmount = current.get(slotIndex); + final ResourceAmount resourceAmount = current.get(slotIndex); if (resourceAmount == null) { return null; } - return new ResourceTemplate<>(resourceAmount.getResource(), NetworkTestFixtures.STORAGE_CHANNEL_TYPE); + return resourceAmount.getResource(); } @Override public long getExportedAmount(final int slotIndex) { validateIndex(slotIndex); - final ResourceAmount resourceAmount = current.get(slotIndex); + final ResourceAmount resourceAmount = current.get(slotIndex); if (resourceAmount == null) { return 0L; } @@ -116,19 +118,19 @@ public long getExportedAmount(final int slotIndex) { } @Override - public void setExportSlot(final int slotIndex, final ResourceTemplate resource, final long amount) { + public void setExportSlot(final int slotIndex, final ResourceKey resource, final long amount) { validateIndex(slotIndex); - current.put(slotIndex, new ResourceAmount<>((String) resource.resource(), amount)); + current.put(slotIndex, new ResourceAmount(resource, amount)); } - public void setCurrentlyExported(final int index, final String resource, final long amount) { - setExportSlot(index, new ResourceTemplate<>(resource, NetworkTestFixtures.STORAGE_CHANNEL_TYPE), amount); + public void setCurrentlyExported(final int index, final ResourceKey resource, final long amount) { + setExportSlot(index, resource, amount); } @Override public void shrinkExportedAmount(final int slotIndex, final long amount) { validateIndex(slotIndex); - final ResourceAmount resourceAmount = this.current.get(slotIndex); + final ResourceAmount resourceAmount = this.current.get(slotIndex); if (resourceAmount.getAmount() - amount <= 0) { this.current.remove(slotIndex); } else { @@ -139,23 +141,16 @@ public void shrinkExportedAmount(final int slotIndex, final long amount) { @Override public void growExportedAmount(final int slotIndex, final long amount) { validateIndex(slotIndex); - final ResourceAmount resourceAmount = this.current.get(slotIndex); + final ResourceAmount resourceAmount = this.current.get(slotIndex); resourceAmount.increment(amount); } @Override - public long insert(final StorageChannelType storageChannelType, - final T resource, - final long amount, - final Action action) { + public long insert(final ResourceKey resource, final long amount, final Action action) { for (int i = 0; i < getSlots(); ++i) { if (getExportedResource(i) == null) { if (action == Action.EXECUTE) { - final ResourceTemplate template = new ResourceTemplate<>( - (String) resource, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE - ); - setExportSlot(i, template, amount); + setExportSlot(i, resource, amount); } return amount; } @@ -164,11 +159,11 @@ public long insert(final StorageChannelType storageChannelType, } @Override - public long extract(final T resource, final long amount, final Action action) { + public long extract(final ResourceKey resource, final long amount, final Action action) { long extracted = 0; for (int i = 0; i < getSlots(); ++i) { - final ResourceTemplate slot = getExportedResource(i); - if (slot != null && slot.resource().equals(resource)) { + final ResourceKey slot = getExportedResource(i); + if (slot != null && slot.equals(resource)) { final long maxAmount = Math.min(getExportedAmount(i), amount - extracted); extracted += maxAmount; if (action == Action.EXECUTE) { diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/InterfaceNetworkNodeTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/InterfaceNetworkNodeTest.java index 5affd2bc5..3e995a5ca 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/InterfaceNetworkNodeTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/InterfaceNetworkNodeTest.java @@ -5,18 +5,17 @@ import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.network.test.AddNetworkNode; import com.refinedmods.refinedstorage2.network.test.InjectNetworkEnergyComponent; import com.refinedmods.refinedstorage2.network.test.InjectNetworkStorageChannel; import com.refinedmods.refinedstorage2.network.test.NetworkTest; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import com.refinedmods.refinedstorage2.network.test.SetupNetwork; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; import static org.assertj.core.api.Assertions.assertThat; @NetworkTest @@ -47,23 +46,21 @@ void shouldExtractEnergy( @Test void shouldExportAllWithDefaultTransferQuota( - @InjectNetworkStorageChannel final StorageChannel storageChannel, + @InjectNetworkStorageChannel final StorageChannel storageChannel, @InjectNetworkEnergyComponent final EnergyNetworkComponent energy ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", Long.MAX_VALUE, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, Long.MAX_VALUE, Action.EXECUTE, EmptyActor.INSTANCE); - exportState.setRequestedResource(1, "A", Long.MAX_VALUE); + exportState.setRequestedResource(1, A, Long.MAX_VALUE); // Act sut.doWork(); // Assert assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(Long.MAX_VALUE); assertThat(storageChannel.getAll()).isEmpty(); assertThat(energy.getStored()).isEqualTo(1000 - 5); @@ -71,14 +68,14 @@ void shouldExportAllWithDefaultTransferQuota( @Test void shouldNotExportAnythingWithoutBeingActive( - @InjectNetworkStorageChannel final StorageChannel storageChannel, + @InjectNetworkStorageChannel final StorageChannel storageChannel, @InjectNetworkEnergyComponent final EnergyNetworkComponent energy ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); - exportState.setRequestedResource(1, "A", 1); + exportState.setRequestedResource(1, A, 1); sut.setActive(false); sut.setTransferQuotaProvider(resource -> 2); @@ -91,20 +88,20 @@ void shouldNotExportAnythingWithoutBeingActive( assertThat(exportState.getExportedResource(1)).isNull(); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 10)); + .containsExactly(new ResourceAmount(A, 10)); assertThat(energy.getStored()).isEqualTo(1000); } @Test void shouldNotExportAnythingWithoutNetwork( - @InjectNetworkStorageChannel final StorageChannel storageChannel, + @InjectNetworkStorageChannel final StorageChannel storageChannel, @InjectNetworkEnergyComponent final EnergyNetworkComponent energy ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); - exportState.setRequestedResource(1, "A", 1); + exportState.setRequestedResource(1, A, 1); sut.setNetwork(null); sut.setTransferQuotaProvider(resource -> 2); @@ -117,18 +114,18 @@ void shouldNotExportAnythingWithoutNetwork( assertThat(exportState.getExportedResource(1)).isNull(); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 10)); + .containsExactly(new ResourceAmount(A, 10)); assertThat(energy.getStored()).isEqualTo(1000); } @Test void shouldNotExportAnythingWithoutExportState( - @InjectNetworkStorageChannel final StorageChannel storageChannel, + @InjectNetworkStorageChannel final StorageChannel storageChannel, @InjectNetworkEnergyComponent final EnergyNetworkComponent energy ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.setExportState(null); sut.setTransferQuotaProvider(resource -> 2); @@ -141,7 +138,7 @@ void shouldNotExportAnythingWithoutExportState( assertThat(exportState.getExportedResource(1)).isNull(); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 10)); + .containsExactly(new ResourceAmount(A, 10)); assertThat(energy.getStored()).isEqualTo(1000 - 5); } } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/KeepExportingInterfaceNetworkNodeTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/KeepExportingInterfaceNetworkNodeTest.java index 3c2a105e3..78d1d5ace 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/KeepExportingInterfaceNetworkNodeTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/KeepExportingInterfaceNetworkNodeTest.java @@ -4,18 +4,20 @@ import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.api.storage.limited.LimitedStorageImpl; import com.refinedmods.refinedstorage2.network.test.AddNetworkNode; import com.refinedmods.refinedstorage2.network.test.InjectNetworkStorageChannel; import com.refinedmods.refinedstorage2.network.test.NetworkTest; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import com.refinedmods.refinedstorage2.network.test.SetupNetwork; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A_ALTERNATIVE; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A_ALTERNATIVE2; +import static com.refinedmods.refinedstorage2.network.test.TestResource.B; import static org.assertj.core.api.Assertions.assertThat; @NetworkTest @@ -36,114 +38,96 @@ void setUp() { @Test void shouldKeepExportingResourceUntilWantedAmountIsReached( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); - exportState.setRequestedResource(1, "A", 7); + exportState.setRequestedResource(1, A, 7); // Act & assert sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(2); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 8)); + .containsExactly(new ResourceAmount(A, 8)); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(4); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 6)); + .containsExactly(new ResourceAmount(A, 6)); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(6); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 4)); + .containsExactly(new ResourceAmount(A, 4)); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(7); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 3)); + .containsExactly(new ResourceAmount(A, 3)); sut.doWork(); sut.doWork(); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(7); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 3)); + .containsExactly(new ResourceAmount(A, 3)); } @Test void shouldKeepExportingResourceUntilWantedAmountIsReachedAndNetworkHasEnoughResources( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A", 7, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A, 7, Action.EXECUTE, EmptyActor.INSTANCE); - exportState.setRequestedResource(1, "A", 10); + exportState.setRequestedResource(1, A, 10); // Act & assert sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(2); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 5)); + .containsExactly(new ResourceAmount(A, 5)); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(4); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 3)); + .containsExactly(new ResourceAmount(A, 3)); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(6); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 1)); + .containsExactly(new ResourceAmount(A, 1)); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(7); assertThat(storageChannel.getAll()).isEmpty(); @@ -151,191 +135,167 @@ void shouldKeepExportingResourceUntilWantedAmountIsReachedAndNetworkHasEnoughRes sut.doWork(); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(7); assertThat(storageChannel.getAll()).isEmpty(); } @Test void shouldKeepExportingResourceFuzzilyUntilWantedAmountIsReached( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A1", 10, Action.EXECUTE, EmptyActor.INSTANCE); - storageChannel.insert("A2", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A_ALTERNATIVE, 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(A_ALTERNATIVE2, 10, Action.EXECUTE, EmptyActor.INSTANCE); - exportState.setRequestedResource(1, "A", 10); + exportState.setRequestedResource(1, A, 10); // Act & assert sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A1", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A_ALTERNATIVE); assertThat(exportState.getExportedAmount(1)).isEqualTo(2); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("A1", 8), - new ResourceAmount<>("A2", 10) + new ResourceAmount(A_ALTERNATIVE, 8), + new ResourceAmount(A_ALTERNATIVE2, 10) ); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A1", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A_ALTERNATIVE); assertThat(exportState.getExportedAmount(1)).isEqualTo(4); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("A1", 6), - new ResourceAmount<>("A2", 10) + new ResourceAmount(A_ALTERNATIVE, 6), + new ResourceAmount(A_ALTERNATIVE2, 10) ); } @Test void shouldKeepExportingResourceFuzzilyUntilWantedAmountIsReachedEvenIfTheResourceIsNoLongerAvailableInTheNetwork( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("A1", 1, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(A_ALTERNATIVE, 1, Action.EXECUTE, EmptyActor.INSTANCE); - exportState.setRequestedResource(1, "A", 1); + exportState.setRequestedResource(1, A, 1); // Act & assert sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A1", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A_ALTERNATIVE); assertThat(exportState.getExportedAmount(1)).isEqualTo(1); assertThat(storageChannel.getAll()).isEmpty(); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A1", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A_ALTERNATIVE); assertThat(exportState.getExportedAmount(1)).isEqualTo(1); assertThat(storageChannel.getAll()).isEmpty(); } @Test void shouldReturnResourceToNetworkUntilWantedAmountIsReached( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); + storageChannel.addSource(new InMemoryStorageImpl()); - exportState.setRequestedResource(1, "A", 7); - exportState.setCurrentlyExported(1, "A", 10); + exportState.setRequestedResource(1, A, 7); + exportState.setCurrentlyExported(1, A, 10); // Act & assert sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(8); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 2)); + .containsExactly(new ResourceAmount(A, 2)); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(7); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 3)); + .containsExactly(new ResourceAmount(A, 3)); sut.doWork(); sut.doWork(); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(7); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 3)); + .containsExactly(new ResourceAmount(A, 3)); } @Test void shouldReturnResourceToNetworkUntilWantedAmountIsReachedAndNetworkIsFull( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new LimitedStorageImpl<>(3)); + storageChannel.addSource(new LimitedStorageImpl(3)); - exportState.setRequestedResource(1, "A", 5); - exportState.setCurrentlyExported(1, "A", 10); + exportState.setRequestedResource(1, A, 5); + exportState.setCurrentlyExported(1, A, 10); // Act & assert sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(8); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 2)); + .containsExactly(new ResourceAmount(A, 2)); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(7); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 3)); + .containsExactly(new ResourceAmount(A, 3)); sut.doWork(); sut.doWork(); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(7); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() - .containsExactly(new ResourceAmount<>("A", 3)); + .containsExactly(new ResourceAmount(A, 3)); } @Test void shouldReturnResourceToNetworkAndExportOtherResourceIfSpecified( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - storageChannel.insert("B", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new InMemoryStorageImpl()); + storageChannel.insert(B, 10, Action.EXECUTE, EmptyActor.INSTANCE); - exportState.setRequestedResource(1, "B", 3); - exportState.setCurrentlyExported(1, "A", 3); + exportState.setRequestedResource(1, B, 3); + exportState.setCurrentlyExported(1, A, 3); // Act & assert sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(1); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("A", 2), - new ResourceAmount<>("B", 10) + new ResourceAmount(A, 2), + new ResourceAmount(B, 10) ); sut.doWork(); @@ -344,90 +304,80 @@ void shouldReturnResourceToNetworkAndExportOtherResourceIfSpecified( assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("A", 3), - new ResourceAmount<>("B", 10) + new ResourceAmount(A, 3), + new ResourceAmount(B, 10) ); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("B", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(B); assertThat(exportState.getExportedAmount(1)).isEqualTo(2); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("A", 3), - new ResourceAmount<>("B", 8) + new ResourceAmount(A, 3), + new ResourceAmount(B, 8) ); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("B", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(B); assertThat(exportState.getExportedAmount(1)).isEqualTo(3); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("A", 3), - new ResourceAmount<>("B", 7) + new ResourceAmount(A, 3), + new ResourceAmount(B, 7) ); sut.doWork(); sut.doWork(); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("B", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(B); assertThat(exportState.getExportedAmount(1)).isEqualTo(3); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("A", 3), - new ResourceAmount<>("B", 7) + new ResourceAmount(A, 3), + new ResourceAmount(B, 7) ); } @Test void shouldReturnResourceToNetworkAndExportOtherResourceIfSpecifiedUntilNetworkIsFull( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new LimitedStorageImpl<>(11)); - storageChannel.insert("B", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.addSource(new LimitedStorageImpl(11)); + storageChannel.insert(B, 10, Action.EXECUTE, EmptyActor.INSTANCE); - exportState.setRequestedResource(1, "B", 3); - exportState.setCurrentlyExported(1, "A", 3); + exportState.setRequestedResource(1, B, 3); + exportState.setCurrentlyExported(1, A, 3); // Act & assert sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(2); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("A", 1), - new ResourceAmount<>("B", 10) + new ResourceAmount(A, 1), + new ResourceAmount(B, 10) ); sut.doWork(); sut.doWork(); sut.doWork(); assertThat(exportState.getExportedResource(0)).isNull(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(2); assertThat(storageChannel.getAll()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( - new ResourceAmount<>("A", 1), - new ResourceAmount<>("B", 10) + new ResourceAmount(A, 1), + new ResourceAmount(B, 10) ); } } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/InterfaceExternalStorageProviderImplTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/InterfaceExternalStorageProviderImplTest.java index 4bb704278..3c4425d8e 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/InterfaceExternalStorageProviderImplTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/InterfaceExternalStorageProviderImplTest.java @@ -7,12 +7,10 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.iface.InterfaceNetworkNode; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.network.test.AddNetworkNode; import com.refinedmods.refinedstorage2.network.test.InjectNetworkStorageChannel; import com.refinedmods.refinedstorage2.network.test.NetworkTest; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import com.refinedmods.refinedstorage2.network.test.SetupNetwork; import org.junit.jupiter.api.BeforeEach; @@ -20,6 +18,8 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; +import static com.refinedmods.refinedstorage2.network.test.TestResource.B; import static org.assertj.core.api.Assertions.assertThat; @NetworkTest @@ -42,15 +42,14 @@ void setUp() { @Test void shouldExposeExportedResources( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - exportState.setCurrentlyExported(0, "A", 100); - exportState.setCurrentlyExported(8, "A", 1); + exportState.setCurrentlyExported(0, A, 100); + exportState.setCurrentlyExported(8, A, 1); - externalStorage.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl<>( - interfaceNetworkNode, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE + externalStorage.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl( + interfaceNetworkNode ))); // Act @@ -58,18 +57,17 @@ void shouldExposeExportedResources( // Assert assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 101) + new ResourceAmount(A, 101) ); } @Test void shouldNotExposeExportedResourceWithoutExportState( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - externalStorage.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl<>( - interfaceNetworkNodeWithoutExportState, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE + externalStorage.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl( + interfaceNetworkNodeWithoutExportState ))); // Act @@ -83,26 +81,23 @@ void shouldNotExposeExportedResourceWithoutExportState( @EnumSource(Action.class) void shouldInsertIntoInterface( final Action action, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - externalStorage.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl<>( - interfaceNetworkNode, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE + externalStorage.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl( + interfaceNetworkNode ))); // Act - final long inserted = networkStorage.insert("A", 10, action, EmptyActor.INSTANCE); + final long inserted = networkStorage.insert(A, 10, action, EmptyActor.INSTANCE); // Assert assertThat(inserted).isEqualTo(10); if (action == Action.EXECUTE) { assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) - ); - assertThat(exportState.getExportedResource(0)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) + new ResourceAmount(A, 10) ); + assertThat(exportState.getExportedResource(0)).isEqualTo(A); assertThat(exportState.getExportedAmount(0)).isEqualTo(10); } else { assertThat(networkStorage.getAll()).isEmpty(); @@ -115,17 +110,16 @@ void shouldInsertIntoInterface( @EnumSource(Action.class) void shouldNotInsertResourceWithoutExportState( final Action action, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - externalStorage.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl<>( - interfaceNetworkNodeWithoutExportState, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE + externalStorage.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl( + interfaceNetworkNodeWithoutExportState ))); externalStorage.detectChanges(); // Act - final long inserted = networkStorage.insert("A", 101, action, EmptyActor.INSTANCE); + final long inserted = networkStorage.insert(A, 101, action, EmptyActor.INSTANCE); // Assert assertThat(inserted).isZero(); @@ -136,19 +130,18 @@ void shouldNotInsertResourceWithoutExportState( @EnumSource(Action.class) void shouldExtractEntireResourceFromInterface( final Action action, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - exportState.setCurrentlyExported(0, "A", 50); - exportState.setCurrentlyExported(1, "A", 50); - externalStorage.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl<>( - interfaceNetworkNode, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE + exportState.setCurrentlyExported(0, A, 50); + exportState.setCurrentlyExported(1, A, 50); + externalStorage.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl( + interfaceNetworkNode ))); externalStorage.detectChanges(); // Act - final long extracted = networkStorage.extract("A", 101, action, EmptyActor.INSTANCE); + final long extracted = networkStorage.extract(A, 101, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(100); @@ -160,15 +153,11 @@ void shouldExtractEntireResourceFromInterface( assertThat(exportState.getExportedAmount(1)).isZero(); } else { assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100) - ); - assertThat(exportState.getExportedResource(0)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) + new ResourceAmount(A, 100) ); + assertThat(exportState.getExportedResource(0)).isEqualTo(A); assertThat(exportState.getExportedAmount(0)).isEqualTo(50); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(50); } } @@ -177,43 +166,36 @@ void shouldExtractEntireResourceFromInterface( @EnumSource(Action.class) void shouldExtractPartialResourceFromInterface( final Action action, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - exportState.setCurrentlyExported(0, "A", 50); - exportState.setCurrentlyExported(1, "A", 50); - externalStorage.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl<>( - interfaceNetworkNode, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE + exportState.setCurrentlyExported(0, A, 50); + exportState.setCurrentlyExported(1, A, 50); + externalStorage.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl( + interfaceNetworkNode ))); externalStorage.detectChanges(); // Act - final long extracted = networkStorage.extract("A", 51, action, EmptyActor.INSTANCE); + final long extracted = networkStorage.extract(A, 51, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(51); if (action == Action.EXECUTE) { assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 49) + new ResourceAmount(A, 49) ); assertThat(exportState.getExportedResource(0)).isNull(); assertThat(exportState.getExportedAmount(0)).isZero(); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(49); } else { assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100) - ); - assertThat(exportState.getExportedResource(0)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) + new ResourceAmount(A, 100) ); + assertThat(exportState.getExportedResource(0)).isEqualTo(A); assertThat(exportState.getExportedAmount(0)).isEqualTo(50); - assertThat(exportState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(1)).isEqualTo(A); assertThat(exportState.getExportedAmount(1)).isEqualTo(50); } } @@ -222,27 +204,24 @@ void shouldExtractPartialResourceFromInterface( @EnumSource(Action.class) void shouldNotExtractNonExistentResourceFromInterface( final Action action, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - exportState.setCurrentlyExported(0, "A", 50); - externalStorage.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl<>( - interfaceNetworkNode, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE + exportState.setCurrentlyExported(0, A, 50); + externalStorage.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl( + interfaceNetworkNode ))); externalStorage.detectChanges(); // Act - final long extracted = networkStorage.extract("B", 1, action, EmptyActor.INSTANCE); + final long extracted = networkStorage.extract(B, 1, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isZero(); assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 50) - ); - assertThat(exportState.getExportedResource(0)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) + new ResourceAmount(A, 50) ); + assertThat(exportState.getExportedResource(0)).isEqualTo(A); assertThat(exportState.getExportedAmount(0)).isEqualTo(50); } @@ -250,17 +229,16 @@ void shouldNotExtractNonExistentResourceFromInterface( @EnumSource(Action.class) void shouldNotExtractResourceWithoutExportState( final Action action, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - externalStorage.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl<>( - interfaceNetworkNodeWithoutExportState, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE + externalStorage.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl( + interfaceNetworkNodeWithoutExportState ))); externalStorage.detectChanges(); // Act - final long extracted = networkStorage.extract("A", 101, action, EmptyActor.INSTANCE); + final long extracted = networkStorage.extract(A, 101, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isZero(); diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/IoLoopInterfaceExternalStorageProviderImplTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/IoLoopInterfaceExternalStorageProviderImplTest.java index dd95af0ee..ace9aaf46 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/IoLoopInterfaceExternalStorageProviderImplTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/IoLoopInterfaceExternalStorageProviderImplTest.java @@ -10,25 +10,24 @@ import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.api.storage.Storage; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.network.test.AddNetworkNode; import com.refinedmods.refinedstorage2.network.test.InjectNetwork; import com.refinedmods.refinedstorage2.network.test.InjectNetworkStorageChannel; import com.refinedmods.refinedstorage2.network.test.NetworkTest; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import com.refinedmods.refinedstorage2.network.test.SetupNetwork; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; import static org.assertj.core.api.Assertions.assertThat; @NetworkTest @SetupNetwork class IoLoopInterfaceExternalStorageProviderImplTest { - Storage regularStorageInNetwork; + Storage regularStorageInNetwork; @AddNetworkNode InterfaceNetworkNode interfaceWithExternalStorage; @@ -46,48 +45,43 @@ class IoLoopInterfaceExternalStorageProviderImplTest { InterfaceNetworkNode regularInterface; InterfaceExportStateImpl regularInterfaceState; - // this has no usages, but it's useful to bring an external storage in the network ctx that has no delegate + // This has no usages, but it's useful to bring an external storage in the network context that has no delegate @AddNetworkNode + @SuppressWarnings("unused") ExternalStorageNetworkNode externalStorageWithoutConnection; @AddNetworkNode ExternalStorageNetworkNode externalStorageWithNonInterfaceConnection; @BeforeEach - void setUp(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void setUp(@InjectNetworkStorageChannel final StorageChannel networkStorage) { interfaceWithExternalStorageState = new InterfaceExportStateImpl(2); - interfaceWithExternalStorageState.setRequestedResource(1, "A", 10); + interfaceWithExternalStorageState.setRequestedResource(1, A, 10); interfaceWithExternalStorage.setExportState(interfaceWithExternalStorageState); interfaceWithExternalStorage.setTransferQuotaProvider(resource -> 100); externalStorageConnectionToInterface.initialize(new ExternalStorageProviderFactoryImpl( - new InterfaceExternalStorageProviderImpl<>( - interfaceWithExternalStorage, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE - ) + new InterfaceExternalStorageProviderImpl(interfaceWithExternalStorage) )); interfaceWithExternalStorageState2 = new InterfaceExportStateImpl(2); - interfaceWithExternalStorageState2.setRequestedResource(1, "A", 10); + interfaceWithExternalStorageState2.setRequestedResource(1, A, 10); interfaceWithExternalStorage2.setExportState(interfaceWithExternalStorageState2); interfaceWithExternalStorage2.setTransferQuotaProvider(resource -> 100); externalStorageConnectionToInterface2.initialize(new ExternalStorageProviderFactoryImpl( - new InterfaceExternalStorageProviderImpl<>( - interfaceWithExternalStorage2, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE - ) + new InterfaceExternalStorageProviderImpl(interfaceWithExternalStorage2) )); regularInterfaceState = new InterfaceExportStateImpl(2); - regularInterfaceState.setRequestedResource(1, "A", 10); + regularInterfaceState.setRequestedResource(1, A, 10); regularInterface.setExportState(regularInterfaceState); regularInterface.setTransferQuotaProvider(resource -> 100); - regularStorageInNetwork = new InMemoryStorageImpl<>(); - regularStorageInNetwork.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + regularStorageInNetwork = new InMemoryStorageImpl(); + regularStorageInNetwork.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); networkStorage.addSource(regularStorageInNetwork); externalStorageWithNonInterfaceConnection.initialize(new ExternalStorageProviderFactoryImpl( - new StorageExternalStorageProvider<>(new InMemoryStorageImpl<>()) + new StorageExternalStorageProvider(new InMemoryStorageImpl()) )); } @@ -98,14 +92,14 @@ void setUp(@InjectNetworkStorageChannel final StorageChannel networkStor // and would double count them because the External Storage update is later. @Test void shouldNotAllowInsertionByAnotherInterfaceIfThatInterfaceIsActingAsExternalStorage( - @InjectNetworkStorageChannel final StorageChannel networkStorage, + @InjectNetworkStorageChannel final StorageChannel networkStorage, @InjectNetwork final Network network ) { // Arrange networkStorage.removeSource(regularStorageInNetwork); network.removeContainer(() -> externalStorageWithNonInterfaceConnection); - interfaceWithExternalStorageState.setCurrentlyExported(0, "A", 15); + interfaceWithExternalStorageState.setCurrentlyExported(0, A, 15); interfaceWithExternalStorageState.clearRequestedResources(); // Act @@ -114,38 +108,34 @@ void shouldNotAllowInsertionByAnotherInterfaceIfThatInterfaceIsActingAsExternalS interfaceWithExternalStorage.doWork(); // Assert - assertThat(interfaceWithExternalStorageState.getExportedResource(0)) - .usingRecursiveComparison() - .isEqualTo(new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE)); + assertThat(interfaceWithExternalStorageState.getExportedResource(0)).isEqualTo(A); assertThat(interfaceWithExternalStorageState.getExportedAmount(0)).isEqualTo(15); assertThat(interfaceWithExternalStorageState2.getExportedResource(0)).isNull(); assertThat(interfaceWithExternalStorageState2.getExportedAmount(0)).isZero(); assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 15) + new ResourceAmount(A, 15) ); } @Test void shouldAllowInsertionByAnotherInterfaceIfThatInterfaceIsNotActingAsExternalStorage( - @InjectNetworkStorageChannel final StorageChannel networkStorage, + @InjectNetworkStorageChannel final StorageChannel networkStorage, @InjectNetwork final Network network ) { // Arrange networkStorage.removeSource(regularStorageInNetwork); network.removeContainer(() -> externalStorageWithNonInterfaceConnection); - regularInterfaceState.setCurrentlyExported(0, "A", 10); + regularInterfaceState.setCurrentlyExported(0, A, 10); regularInterfaceState.clearRequestedResources(); // Act regularInterface.doWork(); // Assert - assertThat(interfaceWithExternalStorageState.getExportedResource(0)) - .usingRecursiveComparison() - .isEqualTo(new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE)); + assertThat(interfaceWithExternalStorageState.getExportedResource(0)).isEqualTo(A); assertThat(interfaceWithExternalStorageState.getExportedAmount(0)).isEqualTo(10); assertThat(interfaceWithExternalStorageState2.getExportedResource(0)).isNull(); @@ -155,7 +145,7 @@ void shouldAllowInsertionByAnotherInterfaceIfThatInterfaceIsNotActingAsExternalS assertThat(regularInterfaceState.getExportedAmount(1)).isZero(); assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); } @@ -165,16 +155,14 @@ void shouldAllowInsertionByAnotherInterfaceIfThatInterfaceIsNotActingAsExternalS // isn't allowed as it would create an extraction loop causing the Interfaces to constantly steal from each other. @Test void shouldNotAllowExtractionRequestedByAnotherInterfaceIfThatInterfaceIsActingAsExternalStorage( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Act & assert interfaceWithExternalStorage.doWork(); externalStorageConnectionToInterface.detectChanges(); assertThat(interfaceWithExternalStorageState.getExportedResource(0)).isNull(); - assertThat(interfaceWithExternalStorageState.getExportedResource(1)) - .usingRecursiveComparison() - .isEqualTo(new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE)); + assertThat(interfaceWithExternalStorageState.getExportedResource(1)).isEqualTo(A); assertThat(interfaceWithExternalStorageState.getExportedAmount(1)).isEqualTo(10); assertThat(interfaceWithExternalStorageState2.getExportedResource(0)).isNull(); @@ -183,16 +171,14 @@ void shouldNotAllowExtractionRequestedByAnotherInterfaceIfThatInterfaceIsActingA assertThat(regularStorageInNetwork.getAll()).isEmpty(); assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); interfaceWithExternalStorage2.doWork(); externalStorageConnectionToInterface2.detectChanges(); assertThat(interfaceWithExternalStorageState.getExportedResource(0)).isNull(); - assertThat(interfaceWithExternalStorageState.getExportedResource(1)) - .usingRecursiveComparison() - .isEqualTo(new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE)); + assertThat(interfaceWithExternalStorageState.getExportedResource(1)).isEqualTo(A); assertThat(interfaceWithExternalStorageState.getExportedAmount(1)).isEqualTo(10); assertThat(interfaceWithExternalStorageState2.getExportedResource(0)).isNull(); @@ -201,22 +187,20 @@ void shouldNotAllowExtractionRequestedByAnotherInterfaceIfThatInterfaceIsActingA assertThat(regularStorageInNetwork.getAll()).isEmpty(); assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); } @Test void shouldAllowExtractionRequestedByAnotherInterfaceIfThatInterfaceIsNotActingAsExternalStorage( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Act & assert interfaceWithExternalStorage.doWork(); externalStorageConnectionToInterface.detectChanges(); assertThat(interfaceWithExternalStorageState.getExportedResource(0)).isNull(); - assertThat(interfaceWithExternalStorageState.getExportedResource(1)) - .usingRecursiveComparison() - .isEqualTo(new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE)); + assertThat(interfaceWithExternalStorageState.getExportedResource(1)).isEqualTo(A); assertThat(interfaceWithExternalStorageState.getExportedAmount(1)).isEqualTo(10); assertThat(regularInterfaceState.getExportedResource(0)).isNull(); @@ -225,7 +209,7 @@ void shouldAllowExtractionRequestedByAnotherInterfaceIfThatInterfaceIsNotActingA assertThat(regularStorageInNetwork.getAll()).isEmpty(); assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); regularInterface.doWork(); @@ -238,9 +222,7 @@ void shouldAllowExtractionRequestedByAnotherInterfaceIfThatInterfaceIsNotActingA assertThat(interfaceWithExternalStorageState.getExportedAmount(1)).isZero(); assertThat(regularInterfaceState.getExportedResource(0)).isNull(); - assertThat(regularInterfaceState.getExportedResource(1)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("A", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(regularInterfaceState.getExportedResource(1)).isEqualTo(A); assertThat(regularInterfaceState.getExportedAmount(1)).isEqualTo(10); assertThat(regularStorageInNetwork.getAll()).isEmpty(); diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/SelfIoInterfaceExternalStorageProviderImplTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/SelfIoInterfaceExternalStorageProviderImplTest.java index b8987f04e..1c73869e7 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/SelfIoInterfaceExternalStorageProviderImplTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/iface/externalstorage/SelfIoInterfaceExternalStorageProviderImplTest.java @@ -5,17 +5,16 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.iface.InterfaceExportStateImpl; import com.refinedmods.refinedstorage2.api.network.impl.node.iface.InterfaceNetworkNode; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.network.test.AddNetworkNode; import com.refinedmods.refinedstorage2.network.test.InjectNetworkStorageChannel; import com.refinedmods.refinedstorage2.network.test.NetworkTest; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import com.refinedmods.refinedstorage2.network.test.SetupNetwork; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static com.refinedmods.refinedstorage2.network.test.TestResource.B; import static org.assertj.core.api.Assertions.assertThat; @NetworkTest @@ -32,39 +31,34 @@ void setUp() { exportState = new InterfaceExportStateImpl(2); iface.setExportState(exportState); iface.setTransferQuotaProvider(resource -> 100); - connection.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl<>( - iface, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE - ))); + connection.initialize(new ExternalStorageProviderFactoryImpl(new InterfaceExternalStorageProviderImpl(iface))); } // We don't allow self-insertions and self-extractions for the same reasons mentioned in // IoLoopInterfaceExternalStorageProviderImplTest. @Test void shouldNotAllowSelfInsertionOrSelfExtraction( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange // this would try to do a self-insert as it's an unwanted resource. - exportState.setCurrentlyExported(0, "B", 15); + exportState.setCurrentlyExported(0, B, 15); // this would try to do a self-extract because we have the resource. - exportState.setRequestedResource(1, "B", 1); + exportState.setRequestedResource(1, B, 1); // Act iface.doWork(); connection.detectChanges(); // Assert - assertThat(exportState.getExportedResource(0)).usingRecursiveComparison().isEqualTo( - new ResourceTemplate<>("B", NetworkTestFixtures.STORAGE_CHANNEL_TYPE) - ); + assertThat(exportState.getExportedResource(0)).isEqualTo(B); assertThat(exportState.getExportedAmount(0)).isEqualTo(15); assertThat(exportState.getExportedResource(1)).isNull(); assertThat(exportState.getExportedAmount(1)).isZero(); assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("B", 15) + new ResourceAmount(B, 15) ); } } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/importer/FakeImporterSource.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/importer/FakeImporterSource.java index f2a27d932..8986a626d 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/importer/FakeImporterSource.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/importer/FakeImporterSource.java @@ -3,6 +3,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.network.node.importer.ImporterSource; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; @@ -12,36 +13,36 @@ import java.util.Iterator; import java.util.List; -public class FakeImporterSource implements ImporterSource { - private final List resources; - private final InMemoryStorageImpl storage = new InMemoryStorageImpl<>(); +public class FakeImporterSource implements ImporterSource { + private final List resources; + private final InMemoryStorageImpl storage = new InMemoryStorageImpl(); - public FakeImporterSource(final String... resources) { + public FakeImporterSource(final ResourceKey... resources) { this.resources = Arrays.stream(resources).toList(); } - public FakeImporterSource add(final String resource, final long amount) { + public FakeImporterSource add(final ResourceKey resource, final long amount) { storage.insert(resource, amount, Action.EXECUTE, EmptyActor.INSTANCE); return this; } @Override - public Iterator getResources() { + public Iterator getResources() { return resources.iterator(); } @Override - public long extract(final String resource, final long amount, final Action action, final Actor actor) { - // extract a maximum of 5 to ensure that we try to extract multiple times from different slots. + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { + // Extract a maximum of 5 to ensure that we try to extract multiple times from different slots. return storage.extract(resource, Math.min(amount, 5), action, actor); } - public Collection> getAll() { + public Collection getAll() { return storage.getAll(); } @Override - public long insert(final String resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return storage.insert(resource, amount, action, actor); } } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/importer/ImporterNetworkNodeTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/importer/ImporterNetworkNodeTest.java index e2006fc53..7357f5a38 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/importer/ImporterNetworkNodeTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/importer/ImporterNetworkNodeTest.java @@ -1,11 +1,12 @@ package com.refinedmods.refinedstorage2.api.network.impl.node.importer; import com.refinedmods.refinedstorage2.api.core.Action; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; import com.refinedmods.refinedstorage2.api.network.component.EnergyNetworkComponent; import com.refinedmods.refinedstorage2.api.network.node.importer.ImporterTransferStrategy; import com.refinedmods.refinedstorage2.api.network.node.importer.ImporterTransferStrategyImpl; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; @@ -15,7 +16,6 @@ import com.refinedmods.refinedstorage2.network.test.InjectNetworkEnergyComponent; import com.refinedmods.refinedstorage2.network.test.InjectNetworkStorageChannel; import com.refinedmods.refinedstorage2.network.test.NetworkTest; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import com.refinedmods.refinedstorage2.network.test.SetupNetwork; import java.util.List; @@ -24,6 +24,11 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A_ALTERNATIVE; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A_ALTERNATIVE2; +import static com.refinedmods.refinedstorage2.network.test.TestResource.B; +import static com.refinedmods.refinedstorage2.network.test.TestResource.C; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @@ -61,7 +66,7 @@ void shouldExtractEnergy( @Test void shouldNotWorkWithoutTransferStrategy( - @InjectNetworkStorageChannel final StorageChannel storageChannel, + @InjectNetworkStorageChannel final StorageChannel storageChannel, @InjectNetworkEnergyComponent final EnergyNetworkComponent energy ) { // Act @@ -81,20 +86,16 @@ void shouldNotWorkWithoutNetwork() { @Test void shouldNotWorkOrExtractEnergyWithoutBeingActive( - @InjectNetworkStorageChannel final StorageChannel storageChannel, + @InjectNetworkStorageChannel final StorageChannel storageChannel, @InjectNetworkEnergyComponent final EnergyNetworkComponent energy ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - - final FakeImporterSource source = new FakeImporterSource("A", "B") - .add("A", 100) - .add("B", 100); - final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 1 - ); + storageChannel.addSource(new InMemoryStorageImpl()); + + final FakeImporterSource source = new FakeImporterSource(A, B) + .add(A, 100) + .add(B, 100); + final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl(source, 1); sut.setTransferStrategy(strategy); sut.setActive(false); @@ -104,25 +105,21 @@ void shouldNotWorkOrExtractEnergyWithoutBeingActive( // Assert assertThat(storageChannel.getAll()).isEmpty(); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 100), - new ResourceAmount<>("B", 100) + new ResourceAmount(A, 100), + new ResourceAmount(B, 100) ); assertThat(energy.getStored()).isEqualTo(1000); } @Test - void testTransfer(@InjectNetworkStorageChannel final StorageChannel storageChannel) { + void testTransfer(@InjectNetworkStorageChannel final StorageChannel storageChannel) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - - final FakeImporterSource source = new FakeImporterSource("A", "B", "A") - .add("A", 100) - .add("B", 100); - final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 1 - ); + storageChannel.addSource(new InMemoryStorageImpl()); + + final FakeImporterSource source = new FakeImporterSource(A, B, A) + .add(A, 100) + .add(B, 100); + final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl(source, 1); sut.setTransferStrategy(strategy); // Act @@ -130,43 +127,31 @@ void testTransfer(@InjectNetworkStorageChannel final StorageChannel stor // Assert assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 1) + new ResourceAmount(A, 1) ); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 99), - new ResourceAmount<>("B", 100) + new ResourceAmount(A, 99), + new ResourceAmount(B, 100) ); } @Test void shouldUseFirstSuccessfulTransferStrategy( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); + storageChannel.addSource(new InMemoryStorageImpl()); final FakeImporterSource emptySource = new FakeImporterSource(); - final FakeImporterSource source = new FakeImporterSource("A", "B", "A") - .add("A", 100) - .add("B", 100); + final FakeImporterSource source = new FakeImporterSource(A, B, A) + .add(A, 100) + .add(B, 100); sut.setTransferStrategy(new CompositeImporterTransferStrategy(List.of( - new ImporterTransferStrategyImpl<>( - emptySource, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 1 - ), - new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 1 - ), - new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 1 - ) + new ImporterTransferStrategyImpl(emptySource, 1), + new ImporterTransferStrategyImpl(source, 1), + new ImporterTransferStrategyImpl(source, 1) ))); // Act @@ -174,30 +159,26 @@ void shouldUseFirstSuccessfulTransferStrategy( // Assert assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 1) + new ResourceAmount(A, 1) ); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 99), - new ResourceAmount<>("B", 100) + new ResourceAmount(A, 99), + new ResourceAmount(B, 100) ); } @Test void shouldNotTransferIfThereIsNoSpaceInTheNetwork( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new LimitedStorageImpl<>(100)); - storageChannel.insert("C", 100, Action.EXECUTE, EmptyActor.INSTANCE); - - final FakeImporterSource source = new FakeImporterSource("A", "B") - .add("A", 100) - .add("B", 100); - final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 1 - ); + storageChannel.addSource(new LimitedStorageImpl(100)); + storageChannel.insert(C, 100, Action.EXECUTE, EmptyActor.INSTANCE); + + final FakeImporterSource source = new FakeImporterSource(A, B) + .add(A, 100) + .add(B, 100); + final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl(source, 1); sut.setTransferStrategy(strategy); // Act @@ -205,29 +186,25 @@ void shouldNotTransferIfThereIsNoSpaceInTheNetwork( // Assert assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("C", 100) + new ResourceAmount(C, 100) ); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 100), - new ResourceAmount<>("B", 100) + new ResourceAmount(A, 100), + new ResourceAmount(B, 100) ); } @Test void testTransferDifferentResourceOverMultipleSlots( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - - final FakeImporterSource source = new FakeImporterSource("A", "B", "A", "B") - .add("A", 11) - .add("B", 6); - final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 10 - ); + storageChannel.addSource(new InMemoryStorageImpl()); + + final FakeImporterSource source = new FakeImporterSource(A, B, A, B) + .add(A, 11) + .add(B, 6); + final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl(source, 10); sut.setTransferStrategy(strategy); // Act @@ -235,30 +212,26 @@ void testTransferDifferentResourceOverMultipleSlots( // Assert assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 1), - new ResourceAmount<>("B", 6) + new ResourceAmount(A, 1), + new ResourceAmount(B, 6) ); } @Test void testTransferSameResourceOverMultipleSlots( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); + storageChannel.addSource(new InMemoryStorageImpl()); - final FakeImporterSource source = new FakeImporterSource("A", "A", "A", "B") - .add("A", 20) - .add("B", 5); + final FakeImporterSource source = new FakeImporterSource(A, A, A, B) + .add(A, 20) + .add(B, 5); - final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 10 - ); + final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl(source, 10); sut.setTransferStrategy(strategy); // Act @@ -266,37 +239,33 @@ void testTransferSameResourceOverMultipleSlots( // Assert assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 10), - new ResourceAmount<>("B", 5) + new ResourceAmount(A, 10), + new ResourceAmount(B, 5) ); } @Test void testTransferWhereResourceIsNotAccepted( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>() { + storageChannel.addSource(new InMemoryStorageImpl() { @Override - public long insert(final String resource, final long amount, final Action action, final Actor actor) { - if ("A".equals(resource)) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { + if (A.equals(resource)) { return 0; } return super.insert(resource, amount, action, actor); } }); - final FakeImporterSource source = new FakeImporterSource("A", "B", "B", "B") - .add("A", 8) - .add("B", 11); - final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 10 - ); + final FakeImporterSource source = new FakeImporterSource(A, B, B, B) + .add(A, 8) + .add(B, 11); + final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl(source, 10); sut.setTransferStrategy(strategy); // Act @@ -304,27 +273,23 @@ public long insert(final String resource, final long amount, final Action action // Assert assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("B", 10) + new ResourceAmount(B, 10) ); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 8), - new ResourceAmount<>("B", 1) + new ResourceAmount(A, 8), + new ResourceAmount(B, 1) ); } @Test void testTransferWithoutAnyResourcesInSource( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); + storageChannel.addSource(new InMemoryStorageImpl()); final FakeImporterSource source = new FakeImporterSource(); - final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 10 - ); + final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl(source, 10); sut.setTransferStrategy(strategy); // Act @@ -336,22 +301,18 @@ void testTransferWithoutAnyResourcesInSource( } @Test - void shouldRespectAllowlist(@InjectNetworkStorageChannel final StorageChannel storageChannel) { + void shouldRespectAllowlist(@InjectNetworkStorageChannel final StorageChannel storageChannel) { // Arrange sut.setFilterMode(FilterMode.ALLOW); - sut.setFilterTemplates(Set.of("A")); + sut.setFilters(Set.of(A)); - storageChannel.addSource(new InMemoryStorageImpl<>()); + storageChannel.addSource(new InMemoryStorageImpl()); - final FakeImporterSource source = new FakeImporterSource("B", "A") - .add("B", 10) - .add("A", 10); + final FakeImporterSource source = new FakeImporterSource(B, A) + .add(B, 10) + .add(A, 10); - final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 1 - ); + final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl(source, 1); sut.setTransferStrategy(strategy); // Act @@ -359,35 +320,36 @@ void shouldRespectAllowlist(@InjectNetworkStorageChannel final StorageChannel("A", 1) + new ResourceAmount(A, 1) ); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("B", 10), - new ResourceAmount<>("A", 9) + new ResourceAmount(B, 10), + new ResourceAmount(A, 9) ); } @Test void shouldRespectAllowlistWithNormalizer( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange sut.setFilterMode(FilterMode.ALLOW); - sut.setFilterTemplates(Set.of("A")); - sut.setNormalizer(value -> value instanceof String str && str.startsWith("A") ? "A" : value); + sut.setFilters(Set.of(A)); + sut.setNormalizer(resource -> { + if (resource == A_ALTERNATIVE || resource == A_ALTERNATIVE2) { + return A; + } + return resource; + }); - storageChannel.addSource(new InMemoryStorageImpl<>()); + storageChannel.addSource(new InMemoryStorageImpl()); - final FakeImporterSource source = new FakeImporterSource("B", "A1", "A2") - .add("B", 10) - .add("A1", 1) - .add("A2", 1); + final FakeImporterSource source = new FakeImporterSource(B, A_ALTERNATIVE, A_ALTERNATIVE2) + .add(B, 10) + .add(A_ALTERNATIVE, 1) + .add(A_ALTERNATIVE2, 1); - final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 10 - ); + final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl(source, 10); sut.setTransferStrategy(strategy); // Act @@ -396,32 +358,28 @@ void shouldRespectAllowlistWithNormalizer( // Assert assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A1", 1), - new ResourceAmount<>("A2", 1) + new ResourceAmount(A_ALTERNATIVE, 1), + new ResourceAmount(A_ALTERNATIVE2, 1) ); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("B", 10) + new ResourceAmount(B, 10) ); } @Test void shouldRespectAllowlistWithoutAlternative( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange sut.setFilterMode(FilterMode.ALLOW); - sut.setFilterTemplates(Set.of("A")); + sut.setFilters(Set.of(A)); - storageChannel.addSource(new InMemoryStorageImpl<>()); + storageChannel.addSource(new InMemoryStorageImpl()); - final FakeImporterSource source = new FakeImporterSource("B") - .add("B", 10); + final FakeImporterSource source = new FakeImporterSource(B) + .add(B, 10); - final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 1 - ); + final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl(source, 1); sut.setTransferStrategy(strategy); // Act @@ -430,27 +388,23 @@ void shouldRespectAllowlistWithoutAlternative( // Assert assertThat(storageChannel.getAll()).isEmpty(); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("B", 10) + new ResourceAmount(B, 10) ); } @Test - void shouldRespectEmptyAllowlist(@InjectNetworkStorageChannel final StorageChannel storageChannel) { + void shouldRespectEmptyAllowlist(@InjectNetworkStorageChannel final StorageChannel storageChannel) { // Arrange sut.setFilterMode(FilterMode.ALLOW); - sut.setFilterTemplates(Set.of()); + sut.setFilters(Set.of()); - storageChannel.addSource(new InMemoryStorageImpl<>()); + storageChannel.addSource(new InMemoryStorageImpl()); - final FakeImporterSource source = new FakeImporterSource("B", "A") - .add("B", 10) - .add("A", 10); + final FakeImporterSource source = new FakeImporterSource(B, A) + .add(B, 10) + .add(A, 10); - final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 1 - ); + final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl(source, 1); sut.setTransferStrategy(strategy); // Act @@ -459,28 +413,24 @@ void shouldRespectEmptyAllowlist(@InjectNetworkStorageChannel final StorageChann // Assert assertThat(storageChannel.getAll()).isEmpty(); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("B", 10), - new ResourceAmount<>("A", 10) + new ResourceAmount(B, 10), + new ResourceAmount(A, 10) ); } @Test - void shouldRespectBlocklist(@InjectNetworkStorageChannel final StorageChannel storageChannel) { + void shouldRespectBlocklist(@InjectNetworkStorageChannel final StorageChannel storageChannel) { // Arrange sut.setFilterMode(FilterMode.BLOCK); - sut.setFilterTemplates(Set.of("A")); + sut.setFilters(Set.of(A)); - storageChannel.addSource(new InMemoryStorageImpl<>()); + storageChannel.addSource(new InMemoryStorageImpl()); - final FakeImporterSource source = new FakeImporterSource("A", "B") - .add("A", 10) - .add("B", 10); + final FakeImporterSource source = new FakeImporterSource(A, B) + .add(A, 10) + .add(B, 10); - final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 1 - ); + final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl(source, 1); sut.setTransferStrategy(strategy); // Act @@ -488,32 +438,28 @@ void shouldRespectBlocklist(@InjectNetworkStorageChannel final StorageChannel("B", 1) + new ResourceAmount(B, 1) ); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 10), - new ResourceAmount<>("B", 9) + new ResourceAmount(A, 10), + new ResourceAmount(B, 9) ); } @Test void shouldRespectBlocklistWithoutAlternative( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel ) { // Arrange sut.setFilterMode(FilterMode.BLOCK); - sut.setFilterTemplates(Set.of("A")); + sut.setFilters(Set.of(A)); - storageChannel.addSource(new InMemoryStorageImpl<>()); + storageChannel.addSource(new InMemoryStorageImpl()); - final FakeImporterSource source = new FakeImporterSource("A") - .add("A", 10); + final FakeImporterSource source = new FakeImporterSource(A) + .add(A, 10); - final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 1 - ); + final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl(source, 1); sut.setTransferStrategy(strategy); // Act @@ -522,27 +468,23 @@ void shouldRespectBlocklistWithoutAlternative( // Assert assertThat(storageChannel.getAll()).isEmpty(); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); } @Test - void shouldRespectEmptyBlocklist(@InjectNetworkStorageChannel final StorageChannel storageChannel) { + void shouldRespectEmptyBlocklist(@InjectNetworkStorageChannel final StorageChannel storageChannel) { // Arrange sut.setFilterMode(FilterMode.BLOCK); - sut.setFilterTemplates(Set.of()); + sut.setFilters(Set.of()); - storageChannel.addSource(new InMemoryStorageImpl<>()); + storageChannel.addSource(new InMemoryStorageImpl()); - final FakeImporterSource source = new FakeImporterSource("A", "B") - .add("A", 10) - .add("B", 10); + final FakeImporterSource source = new FakeImporterSource(A, B) + .add(A, 10) + .add(B, 10); - final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 1 - ); + final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl(source, 1); sut.setTransferStrategy(strategy); // Act @@ -550,11 +492,11 @@ void shouldRespectEmptyBlocklist(@InjectNetworkStorageChannel final StorageChann // Assert assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 1) + new ResourceAmount(A, 1) ); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 9), - new ResourceAmount<>("B", 10) + new ResourceAmount(A, 9), + new ResourceAmount(B, 10) ); } } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/MultiStorageNetworkNodeTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/MultiStorageNetworkNodeTest.java index bc99e72c6..058500dea 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/MultiStorageNetworkNodeTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/MultiStorageNetworkNodeTest.java @@ -1,9 +1,9 @@ package com.refinedmods.refinedstorage2.api.network.impl.node.multistorage; import com.refinedmods.refinedstorage2.api.core.Action; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; import com.refinedmods.refinedstorage2.api.storage.AccessMode; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; @@ -30,6 +30,12 @@ import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.ValueSource; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A_ALTERNATIVE; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A_ALTERNATIVE2; +import static com.refinedmods.refinedstorage2.network.test.TestResource.B; +import static com.refinedmods.refinedstorage2.network.test.TestResource.B_ALTERNATIVE; +import static com.refinedmods.refinedstorage2.network.test.TestResource.C; import static com.refinedmods.refinedstorage2.network.test.nodefactory.AbstractNetworkNodeFactory.PROPERTY_ENERGY_USAGE; import static com.refinedmods.refinedstorage2.network.test.nodefactory.MultiStorageNetworkNodeFactory.PROPERTY_ENERGY_USAGE_PER_STORAGE; import static org.assertj.core.api.Assertions.assertThat; @@ -58,11 +64,11 @@ void setUp() { @Test void shouldInitializeButNotShowResourcesYet( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final Storage storage = new LimitedStorageImpl<>(10); - storage.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(10); + storage.insert(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(1, storage); // Act @@ -76,12 +82,12 @@ void shouldInitializeButNotShowResourcesYet( @Test void shouldInitializeAndShowResourcesAfterEnabling( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - storage.insert("A", 50, Action.EXECUTE, EmptyActor.INSTANCE); - storage.insert("B", 50, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(100); + storage.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(B, 50, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(1, storage); // Act @@ -90,24 +96,24 @@ void shouldInitializeAndShowResourcesAfterEnabling( // Assert assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 50), - new ResourceAmount<>("B", 50) + new ResourceAmount(A, 50), + new ResourceAmount(B, 50) ); } @Test void shouldInitializeMultipleTimes( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final Storage storage1 = new LimitedStorageImpl<>(10); - storage1.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage1 = new LimitedStorageImpl(10); + storage1.insert(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(8, storage1); sut.setProvider(provider); sut.setActive(true); - final Storage storage2 = new LimitedStorageImpl<>(10); - storage2.insert("B", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage2 = new LimitedStorageImpl(10); + storage2.insert(B, 5, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(8, storage2); // Act @@ -116,12 +122,12 @@ void shouldInitializeMultipleTimes( // Assert assertThat(sut.getEnergyUsage()).isEqualTo(BASE_USAGE + USAGE_PER_STORAGE); assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("B", 5) + new ResourceAmount(B, 5) ); } @Test - void testInitialState(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void testInitialState(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Assert assertThat(sut.getEnergyUsage()).isEqualTo(BASE_USAGE); assertThat(sut.getFilterMode()).isEqualTo(FilterMode.BLOCK); @@ -137,16 +143,16 @@ void testInitialState(@InjectNetworkStorageChannel final StorageChannel @ValueSource(booleans = {true, false}) void testState(final boolean active) { // Arrange - final Storage normalStorage = new LimitedStorageImpl<>(100); - normalStorage.insert("A", 74, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage normalStorage = new LimitedStorageImpl(100); + normalStorage.insert(A, 74, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage nearCapacityStorage = new LimitedStorageImpl<>(100); - nearCapacityStorage.insert("A", 75, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage nearCapacityStorage = new LimitedStorageImpl(100); + nearCapacityStorage.insert(A, 75, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage fullStorage = new LimitedStorageImpl<>(100); - fullStorage.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage fullStorage = new LimitedStorageImpl(100); + fullStorage.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage unlimitedStorage = new InMemoryStorageImpl<>(); + final Storage unlimitedStorage = new InMemoryStorageImpl(); provider.set(2, unlimitedStorage); provider.set(3, normalStorage); @@ -170,12 +176,12 @@ void testState(final boolean active) { } @Test - void shouldDetectNewStorage(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldDetectNewStorage(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange initializeAndActivate(); - final Storage storage = new LimitedStorageImpl<>(10); - storage.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(10); + storage.insert(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(8, storage); // Act @@ -184,52 +190,52 @@ void shouldDetectNewStorage(@InjectNetworkStorageChannel final StorageChannel("A", 5) + new ResourceAmount(A, 5) ); } @Test - void shouldDetectChangedStorage(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldDetectChangedStorage(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage originalStorage = new LimitedStorageImpl<>(10); - originalStorage.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage originalStorage = new LimitedStorageImpl(10); + originalStorage.insert(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(0, originalStorage); initializeAndActivate(); - final Storage replacedStorage = new LimitedStorageImpl<>(10); - replacedStorage.insert("B", 2, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage replacedStorage = new LimitedStorageImpl(10); + replacedStorage.insert(B, 2, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(0, replacedStorage); // Act - final Collection> preChanging = new HashSet<>(networkStorage.getAll()); + final Collection preChanging = new HashSet<>(networkStorage.getAll()); sut.onStorageChanged(0); - final Collection> postChanging = networkStorage.getAll(); + final Collection postChanging = networkStorage.getAll(); // Assert assertThat(sut.getEnergyUsage()).isEqualTo(BASE_USAGE + USAGE_PER_STORAGE); assertThat(preChanging).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 5) + new ResourceAmount(A, 5) ); assertThat(postChanging).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("B", 2) + new ResourceAmount(B, 2) ); assertThat(networkStorage.getStored()).isEqualTo(2L); } @Test - void shouldDetectRemovedStorage(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldDetectRemovedStorage(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage = new LimitedStorageImpl<>(10); - storage.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(10); + storage.insert(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(7, storage); initializeAndActivate(); provider.remove(7); // Act - final Collection> preRemoval = new HashSet<>(networkStorage.getAll()); + final Collection preRemoval = new HashSet<>(networkStorage.getAll()); sut.onStorageChanged(7); - final Collection> postRemoval = networkStorage.getAll(); + final Collection postRemoval = networkStorage.getAll(); // Assert assertThat(sut.getEnergyUsage()).isEqualTo(BASE_USAGE); @@ -253,20 +259,20 @@ void shouldNotDetectStorageChangeInInvalidIndex() { @Test void shouldNotUpdateNetworkStorageWhenChangingStorageWhenInactive( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - storage.insert("A", 50, Action.EXECUTE, EmptyActor.INSTANCE); - storage.insert("B", 50, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(100); + storage.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(B, 50, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(1, storage); initializeAndActivate(); // Act - final Collection> preInactiveness = new HashSet<>(networkStorage.getAll()); + final Collection preInactiveness = new HashSet<>(networkStorage.getAll()); sut.setActive(false); sut.onStorageChanged(1); - final Collection> postInactiveness = networkStorage.getAll(); + final Collection postInactiveness = networkStorage.getAll(); // Assert assertThat(preInactiveness).isNotEmpty(); @@ -276,46 +282,46 @@ void shouldNotUpdateNetworkStorageWhenChangingStorageWhenInactive( @Test void shouldHaveResourcesFromStoragePresentInNetwork( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - storage.insert("A", 50, Action.EXECUTE, EmptyActor.INSTANCE); - storage.insert("B", 50, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(100); + storage.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(B, 50, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(1, storage); initializeAndActivate(); // Act - final Collection> resources = networkStorage.getAll(); + final Collection resources = networkStorage.getAll(); final long stored = networkStorage.getStored(); // Assert assertThat(resources).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 50), - new ResourceAmount<>("B", 50) + new ResourceAmount(A, 50), + new ResourceAmount(B, 50) ); assertThat(stored).isEqualTo(100); } @Test - void shouldInsert(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldInsert(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage1 = new LimitedStorageImpl<>(100); + final Storage storage1 = new LimitedStorageImpl(100); provider.set(1, storage1); - final Storage storage2 = new LimitedStorageImpl<>(100); + final Storage storage2 = new LimitedStorageImpl(100); provider.set(2, storage2); - final Storage storage3 = new LimitedStorageImpl<>(100); + final Storage storage3 = new LimitedStorageImpl(100); provider.set(3, storage3); initializeAndActivate(); // Act - final long inserted1 = networkStorage.insert("A", 150, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted2 = networkStorage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted3 = networkStorage.insert("B", 300, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted1 = networkStorage.insert(A, 150, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted2 = networkStorage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted3 = networkStorage.insert(B, 300, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted1).isEqualTo(150); @@ -323,83 +329,83 @@ void shouldInsert(@InjectNetworkStorageChannel final StorageChannel netw assertThat(inserted3).isEqualTo(140); assertThat(storage1.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100) + new ResourceAmount(A, 100) ); assertThat(storage2.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 60), - new ResourceAmount<>("B", 40) + new ResourceAmount(A, 60), + new ResourceAmount(B, 40) ); assertThat(storage3.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("B", 100) + new ResourceAmount(B, 100) ); assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("B", 140), - new ResourceAmount<>("A", 160) + new ResourceAmount(B, 140), + new ResourceAmount(A, 160) ); assertThat(networkStorage.getStored()).isEqualTo(inserted1 + inserted2 + inserted3); } @Test - void shouldExtract(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldExtract(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage1 = new LimitedStorageImpl<>(100); - storage1.insert("A", 50, Action.EXECUTE, EmptyActor.INSTANCE); - storage1.insert("B", 50, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage1 = new LimitedStorageImpl(100); + storage1.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); + storage1.insert(B, 50, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(1, storage1); - final Storage storage2 = new LimitedStorageImpl<>(100); - storage2.insert("A", 50, Action.EXECUTE, EmptyActor.INSTANCE); - storage2.insert("B", 50, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage2 = new LimitedStorageImpl(100); + storage2.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); + storage2.insert(B, 50, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(2, storage2); - final Storage storage3 = new LimitedStorageImpl<>(100); - storage3.insert("C", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage3 = new LimitedStorageImpl(100); + storage3.insert(C, 10, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(3, storage3); initializeAndActivate(); // Act - final long extracted = networkStorage.extract("A", 85, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = networkStorage.extract(A, 85, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(85); assertThat(storage1.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("B", 50) + new ResourceAmount(B, 50) ); assertThat(storage2.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("B", 50), - new ResourceAmount<>("A", 15) + new ResourceAmount(B, 50), + new ResourceAmount(A, 15) ); assertThat(storage3.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("C", 10) + new ResourceAmount(C, 10) ); assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("B", 100), - new ResourceAmount<>("A", 15), - new ResourceAmount<>("C", 10) + new ResourceAmount(B, 100), + new ResourceAmount(A, 15), + new ResourceAmount(C, 10) ); assertThat(networkStorage.getStored()).isEqualTo(125); } @Test void shouldRespectAllowlistWhenInserting( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange sut.setFilterMode(FilterMode.ALLOW); - sut.setFilterTemplates(Set.of("A", "B")); + sut.setFilters(Set.of(A, B)); - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); provider.set(1, storage); initializeAndActivate(); // Act - final long inserted1 = networkStorage.insert("A", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted2 = networkStorage.insert("B", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted3 = networkStorage.insert("C", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted1 = networkStorage.insert(A, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted2 = networkStorage.insert(B, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted3 = networkStorage.insert(C, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted1).isEqualTo(12); @@ -409,28 +415,31 @@ void shouldRespectAllowlistWhenInserting( @Test void shouldRespectAllowlistWithNormalizerWhenInserting( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange sut.setFilterMode(FilterMode.ALLOW); - sut.setFilterTemplates(Set.of("A")); + sut.setFilters(Set.of(A)); sut.setNormalizer(resource -> { - if (resource instanceof String str) { - return str.substring(0, 1); + if (resource == A_ALTERNATIVE || resource == A_ALTERNATIVE2) { + return A; + } + if (resource == B_ALTERNATIVE) { + return B; } return resource; }); - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); provider.set(1, storage); initializeAndActivate(); // Act - final long inserted1 = networkStorage.insert("A", 1, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted2 = networkStorage.insert("A1", 1, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted3 = networkStorage.insert("A2", 1, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted4 = networkStorage.insert("B", 1, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted5 = networkStorage.insert("B1", 1, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted1 = networkStorage.insert(A, 1, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted2 = networkStorage.insert(A_ALTERNATIVE, 1, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted3 = networkStorage.insert(A_ALTERNATIVE2, 1, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted4 = networkStorage.insert(B, 1, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted5 = networkStorage.insert(B_ALTERNATIVE, 1, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted1).isEqualTo(1); @@ -442,20 +451,20 @@ void shouldRespectAllowlistWithNormalizerWhenInserting( @Test void shouldRespectEmptyAllowlistWhenInserting( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange sut.setFilterMode(FilterMode.ALLOW); - sut.setFilterTemplates(Set.of()); + sut.setFilters(Set.of()); - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); provider.set(1, storage); initializeAndActivate(); // Act - final long inserted1 = networkStorage.insert("A", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted2 = networkStorage.insert("B", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted3 = networkStorage.insert("C", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted1 = networkStorage.insert(A, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted2 = networkStorage.insert(B, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted3 = networkStorage.insert(C, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted1).isZero(); @@ -465,20 +474,20 @@ void shouldRespectEmptyAllowlistWhenInserting( @Test void shouldRespectBlocklistWhenInserting( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange sut.setFilterMode(FilterMode.BLOCK); - sut.setFilterTemplates(Set.of("A", "B")); + sut.setFilters(Set.of(A, B)); - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); provider.set(1, storage); initializeAndActivate(); // Act - final long inserted1 = networkStorage.insert("A", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted2 = networkStorage.insert("B", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted3 = networkStorage.insert("C", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted1 = networkStorage.insert(A, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted2 = networkStorage.insert(B, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted3 = networkStorage.insert(C, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted1).isZero(); @@ -488,20 +497,20 @@ void shouldRespectBlocklistWhenInserting( @Test void shouldRespectEmptyBlocklistWhenInserting( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange sut.setFilterMode(FilterMode.BLOCK); - sut.setFilterTemplates(Set.of()); + sut.setFilters(Set.of()); - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); provider.set(1, storage); initializeAndActivate(); // Act - final long inserted1 = networkStorage.insert("A", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted2 = networkStorage.insert("B", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted3 = networkStorage.insert("C", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted1 = networkStorage.insert(A, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted2 = networkStorage.insert(B, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted3 = networkStorage.insert(C, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted1).isEqualTo(12); @@ -513,17 +522,17 @@ void shouldRespectEmptyBlocklistWhenInserting( @EnumSource(AccessMode.class) void shouldRespectAccessModeWhenInserting( final AccessMode accessMode, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange sut.setAccessMode(accessMode); - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); provider.set(1, storage); initializeAndActivate(); // Act - final long inserted = networkStorage.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted = networkStorage.insert(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); // Assert switch (accessMode) { @@ -536,19 +545,19 @@ void shouldRespectAccessModeWhenInserting( @EnumSource(AccessMode.class) void shouldRespectAccessModeWhenExtracting( final AccessMode accessMode, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange sut.setAccessMode(accessMode); - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); provider.set(1, storage); initializeAndActivate(); - storage.insert("A", 20, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(A, 20, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final long extracted = networkStorage.extract("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = networkStorage.extract(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); // Assert switch (accessMode) { @@ -559,17 +568,17 @@ void shouldRespectAccessModeWhenExtracting( @Test void shouldNotAllowInsertsWhenInactive( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); provider.set(1, storage); initializeAndActivate(); sut.setActive(false); // Act - final long inserted = networkStorage.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted = networkStorage.insert(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted).isZero(); @@ -577,18 +586,18 @@ void shouldNotAllowInsertsWhenInactive( @Test void shouldNotAllowExtractsWhenInactive( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - storage.insert("A", 20, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(100); + storage.insert(A, 20, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(1, storage); initializeAndActivate(); sut.setActive(false); // Act - final long extracted = networkStorage.extract("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = networkStorage.extract(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(extracted).isZero(); @@ -596,19 +605,19 @@ void shouldNotAllowExtractsWhenInactive( @Test void shouldHideFromNetworkWhenInactive( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - storage.insert("A", 50, Action.EXECUTE, EmptyActor.INSTANCE); - storage.insert("B", 50, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(100); + storage.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(B, 50, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(1, storage); initializeAndActivate(); // Act - final Collection> preInactiveness = new HashSet<>(networkStorage.getAll()); + final Collection preInactiveness = new HashSet<>(networkStorage.getAll()); sut.setActive(false); - final Collection> postInactiveness = networkStorage.getAll(); + final Collection postInactiveness = networkStorage.getAll(); // Assert assertThat(preInactiveness).isNotEmpty(); @@ -617,31 +626,31 @@ void shouldHideFromNetworkWhenInactive( @Test void shouldNoLongerShowOnNetworkWhenRemoved( - @InjectNetworkStorageChannel final StorageChannel networkStorage, + @InjectNetworkStorageChannel final StorageChannel networkStorage, @InjectNetwork final Network network ) { // Arrange - final Storage storage1 = new LimitedStorageImpl<>(100); - storage1.insert("A", 50, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage1 = new LimitedStorageImpl(100); + storage1.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(1, storage1); initializeAndActivate(); // Act & assert - final Storage storage2 = new LimitedStorageImpl<>(100); - storage2.insert("B", 50, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage2 = new LimitedStorageImpl(100); + storage2.insert(B, 50, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(2, storage2); sut.onStorageChanged(2); assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 50), - new ResourceAmount<>("B", 50) + new ResourceAmount(A, 50), + new ResourceAmount(B, 50) ); network.removeContainer(() -> sut); assertThat(networkStorage.getAll()).isEmpty(); - final Storage storage3 = new LimitedStorageImpl<>(100); - storage3.insert("C", 50, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage3 = new LimitedStorageImpl(100); + storage3.insert(C, 50, Action.EXECUTE, EmptyActor.INSTANCE); provider.set(3, storage3); sut.onStorageChanged(3); @@ -649,34 +658,34 @@ void shouldNoLongerShowOnNetworkWhenRemoved( } @Test - void shouldTrackChanges(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldTrackChanges(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage = new TrackedStorageImpl<>(new LimitedStorageImpl<>(100), () -> 0L); + final Storage storage = new TrackedStorageImpl(new LimitedStorageImpl(100), () -> 0L); provider.set(1, storage); initializeAndActivate(); // Act - final long inserted = networkStorage.insert("A", 10, Action.EXECUTE, FakeActor.INSTANCE); + final long inserted = networkStorage.insert(A, 10, Action.EXECUTE, FakeActor.INSTANCE); // Assert assertThat(inserted).isEqualTo(10); - assertThat(networkStorage.findTrackedResourceByActorType("A", FakeActor.class)).isNotEmpty(); + assertThat(networkStorage.findTrackedResourceByActorType(A, FakeActor.class)).isNotEmpty(); } @Test void shouldNotifyListenerWhenStateChanges( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange final StateTrackedStorage.Listener listener = mock(StateTrackedStorage.Listener.class); sut.setListener(listener); - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); provider.set(1, storage); initializeAndActivate(); // Act - networkStorage.insert("A", 75, Action.EXECUTE, FakeActor.INSTANCE); + networkStorage.insert(A, 75, Action.EXECUTE, FakeActor.INSTANCE); // Assert verify(listener, times(1)).onStorageStateChanged(); diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/MultiStorageProviderImpl.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/MultiStorageProviderImpl.java index 551ce6891..09df89765 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/MultiStorageProviderImpl.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/MultiStorageProviderImpl.java @@ -1,26 +1,20 @@ package com.refinedmods.refinedstorage2.api.network.impl.node.multistorage; import com.refinedmods.refinedstorage2.api.storage.Storage; -import com.refinedmods.refinedstorage2.api.storage.TypedStorage; -import com.refinedmods.refinedstorage2.network.test.NetworkTestFixtures; import java.util.HashMap; import java.util.Map; import java.util.Optional; class MultiStorageProviderImpl implements MultiStorageProvider { - private final Map> storages = new HashMap<>(); + private final Map storages = new HashMap<>(); @Override - @SuppressWarnings({"unchecked", "rawtypes"}) - public Optional>> resolve(final int index) { - return (Optional) Optional.ofNullable(storages.get(index)).map(storage -> new TypedStorage<>( - storage, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE - )); + public Optional resolve(final int index) { + return Optional.ofNullable(storages.get(index)); } - public void set(final int index, final Storage storage) { + public void set(final int index, final Storage storage) { storages.put(index, storage); } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/PriorityMultiStorageNetworkNodeTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/PriorityMultiStorageNetworkNodeTest.java index 0b910d268..506be8cb3 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/PriorityMultiStorageNetworkNodeTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/multistorage/PriorityMultiStorageNetworkNodeTest.java @@ -14,6 +14,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; import static org.assertj.core.api.Assertions.assertThat; @NetworkTest @@ -36,16 +37,16 @@ void setUp() { @ValueSource(booleans = {true, false}) void shouldRespectPriority( final boolean multiStorageAHasPriority, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final Storage storage1 = new LimitedStorageImpl<>(100); + final Storage storage1 = new LimitedStorageImpl(100); final MultiStorageProviderImpl provider1 = new MultiStorageProviderImpl(); provider1.set(1, storage1); a.setProvider(provider1); a.setActive(true); - final Storage storage2 = new LimitedStorageImpl<>(100); + final Storage storage2 = new LimitedStorageImpl(100); final MultiStorageProviderImpl provider2 = new MultiStorageProviderImpl(); provider2.set(1, storage2); b.setProvider(provider2); @@ -60,7 +61,7 @@ void shouldRespectPriority( } // Act - networkStorage.insert("A", 1, Action.EXECUTE, EmptyActor.INSTANCE); + networkStorage.insert(A, 1, Action.EXECUTE, EmptyActor.INSTANCE); // Assert if (multiStorageAHasPriority) { diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/storage/StorageNetworkNodeTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/storage/StorageNetworkNodeTest.java index 799034908..f96e95348 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/storage/StorageNetworkNodeTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/node/storage/StorageNetworkNodeTest.java @@ -1,8 +1,8 @@ package com.refinedmods.refinedstorage2.api.network.impl.node.storage; import com.refinedmods.refinedstorage2.api.core.Action; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; import com.refinedmods.refinedstorage2.api.storage.AccessMode; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; import com.refinedmods.refinedstorage2.api.storage.Storage; @@ -24,6 +24,9 @@ import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.ValueSource; +import static com.refinedmods.refinedstorage2.network.test.TestResource.A; +import static com.refinedmods.refinedstorage2.network.test.TestResource.B; +import static com.refinedmods.refinedstorage2.network.test.TestResource.C; import static com.refinedmods.refinedstorage2.network.test.nodefactory.AbstractNetworkNodeFactory.PROPERTY_ENERGY_USAGE; import static org.assertj.core.api.Assertions.assertThat; @@ -35,13 +38,13 @@ class StorageNetworkNodeTest { @AddNetworkNode(properties = { @AddNetworkNode.Property(key = PROPERTY_ENERGY_USAGE, longValue = ENERGY_USAGE) }) - StorageNetworkNode sut; + StorageNetworkNode sut; @Test - void testInitialState(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void testInitialState(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Act - final long inserted = networkStorage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - final long extracted = networkStorage.extract("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted = networkStorage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = networkStorage.extract(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted).isZero(); @@ -57,10 +60,10 @@ void testInitialState(@InjectNetworkStorageChannel final StorageChannel } @Test - void shouldInitialize(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldInitialize(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final LimitedStorage limitedStorage = new LimitedStorageImpl<>(100); - limitedStorage.insert("A", 50, Action.EXECUTE, EmptyActor.INSTANCE); + final LimitedStorage limitedStorage = new LimitedStorageImpl(100); + limitedStorage.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); // Act activateStorage(limitedStorage); @@ -69,65 +72,65 @@ void shouldInitialize(@InjectNetworkStorageChannel final StorageChannel assertThat(sut.getStored()).isEqualTo(50L); assertThat(sut.getCapacity()).isEqualTo(100L); assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 50L) + new ResourceAmount(A, 50L) ); } @Test - void shouldInsert(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldInsert(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); activateStorage(storage); // Act - final long inserted = networkStorage.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted = networkStorage.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted).isEqualTo(100); assertThat(storage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100) + new ResourceAmount(A, 100) ); - assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 100) + assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( + new ResourceAmount(A, 100) ); } @Test - void shouldExtract(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldExtract(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage = new LimitedStorageImpl<>(200); - storage.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); - storage.insert("B", 50, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(200); + storage.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(B, 50, Action.EXECUTE, EmptyActor.INSTANCE); activateStorage(storage); // Act - final long extracted = networkStorage.extract("A", 30, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = networkStorage.extract(A, 30, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(30); assertThat(storage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 70), - new ResourceAmount<>("B", 50) + new ResourceAmount(A, 70), + new ResourceAmount(B, 50) ); assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 70), - new ResourceAmount<>("B", 50) + new ResourceAmount(A, 70), + new ResourceAmount(B, 50) ); } @Test - void shouldRespectAllowlistWhenInserting(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldRespectAllowlistWhenInserting(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange sut.setFilterMode(FilterMode.ALLOW); - sut.setFilterTemplates(Set.of("A", "B")); + sut.setFilters(Set.of(A, B)); - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); activateStorage(storage); // Act - final long inserted1 = networkStorage.insert("A", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted2 = networkStorage.insert("B", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted3 = networkStorage.insert("C", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted1 = networkStorage.insert(A, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted2 = networkStorage.insert(B, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted3 = networkStorage.insert(C, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted1).isEqualTo(12); @@ -137,18 +140,18 @@ void shouldRespectAllowlistWhenInserting(@InjectNetworkStorageChannel final Stor @Test void shouldRespectEmptyAllowlistWhenInserting( - @InjectNetworkStorageChannel final StorageChannel networkStorage) { + @InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange sut.setFilterMode(FilterMode.ALLOW); - sut.setFilterTemplates(Set.of()); + sut.setFilters(Set.of()); - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); activateStorage(storage); // Act - final long inserted1 = networkStorage.insert("A", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted2 = networkStorage.insert("B", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted3 = networkStorage.insert("C", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted1 = networkStorage.insert(A, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted2 = networkStorage.insert(B, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted3 = networkStorage.insert(C, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted1).isZero(); @@ -157,18 +160,18 @@ void shouldRespectEmptyAllowlistWhenInserting( } @Test - void shouldRespectBlocklistWhenInserting(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldRespectBlocklistWhenInserting(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange sut.setFilterMode(FilterMode.BLOCK); - sut.setFilterTemplates(Set.of("A", "B")); + sut.setFilters(Set.of(A, B)); - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); activateStorage(storage); // Act - final long inserted1 = networkStorage.insert("A", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted2 = networkStorage.insert("B", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted3 = networkStorage.insert("C", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted1 = networkStorage.insert(A, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted2 = networkStorage.insert(B, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted3 = networkStorage.insert(C, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted1).isZero(); @@ -178,18 +181,18 @@ void shouldRespectBlocklistWhenInserting(@InjectNetworkStorageChannel final Stor @Test void shouldRespectEmptyBlocklistWhenInserting( - @InjectNetworkStorageChannel final StorageChannel networkStorage) { + @InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange sut.setFilterMode(FilterMode.BLOCK); - sut.setFilterTemplates(Set.of()); + sut.setFilters(Set.of()); - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); activateStorage(storage); // Act - final long inserted1 = networkStorage.insert("A", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted2 = networkStorage.insert("B", 12, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted3 = networkStorage.insert("C", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted1 = networkStorage.insert(A, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted2 = networkStorage.insert(B, 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted3 = networkStorage.insert(C, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted1).isEqualTo(12); @@ -200,16 +203,16 @@ void shouldRespectEmptyBlocklistWhenInserting( @ParameterizedTest @EnumSource(AccessMode.class) void shouldRespectAccessModeWhenInserting(final AccessMode accessMode, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange sut.setAccessMode(accessMode); - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); activateStorage(storage); // Act - final long inserted = networkStorage.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted = networkStorage.insert(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); // Assert switch (accessMode) { @@ -221,17 +224,17 @@ void shouldRespectAccessModeWhenInserting(final AccessMode accessMode, @ParameterizedTest @EnumSource(AccessMode.class) void shouldRespectAccessModeWhenExtracting(final AccessMode accessMode, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange sut.setAccessMode(accessMode); - final Storage storage = new LimitedStorageImpl<>(100); - storage.insert("A", 20, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(100); + storage.insert(A, 20, Action.EXECUTE, EmptyActor.INSTANCE); activateStorage(storage); // Act - final long extracted = networkStorage.extract("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = networkStorage.extract(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); // Assert switch (accessMode) { @@ -241,29 +244,29 @@ void shouldRespectAccessModeWhenExtracting(final AccessMode accessMode, } @Test - void shouldNotInsertWhenInactive(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldNotInsertWhenInactive(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); activateStorage(storage); sut.setActive(false); // Act - final long inserted = networkStorage.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted = networkStorage.insert(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted).isZero(); } @Test - void shouldNotExtractWhenInactive(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldNotExtractWhenInactive(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); + final Storage storage = new LimitedStorageImpl(100); activateStorage(storage); sut.setActive(false); // Act - final long extracted = networkStorage.extract("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = networkStorage.extract(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(extracted).isZero(); @@ -271,12 +274,12 @@ void shouldNotExtractWhenInactive(@InjectNetworkStorageChannel final StorageChan @Test void shouldHideStorageContentsWhenInactive( - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - storage.insert("A", 50, Action.EXECUTE, EmptyActor.INSTANCE); - storage.insert("B", 50, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(100); + storage.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(B, 50, Action.EXECUTE, EmptyActor.INSTANCE); activateStorage(storage); // Act @@ -287,36 +290,36 @@ void shouldHideStorageContentsWhenInactive( } @Test - void shouldShowStorageContentsWhenActive(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldShowStorageContentsWhenActive(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - storage.insert("A", 50, Action.EXECUTE, EmptyActor.INSTANCE); - storage.insert("B", 50, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(100); + storage.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(B, 50, Action.EXECUTE, EmptyActor.INSTANCE); // Act activateStorage(storage); // Assert assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 50), - new ResourceAmount<>("B", 50) + new ResourceAmount(A, 50), + new ResourceAmount(B, 50) ); } @Test - void shouldTrackChanges(@InjectNetworkStorageChannel final StorageChannel networkStorage) { + void shouldTrackChanges(@InjectNetworkStorageChannel final StorageChannel networkStorage) { // Arrange - activateStorage(new TrackedStorageImpl<>(new LimitedStorageImpl<>(100), () -> 0L)); + activateStorage(new TrackedStorageImpl(new LimitedStorageImpl(100), () -> 0L)); // Act - final long inserted = networkStorage.insert("A", 10, Action.EXECUTE, FakeActor.INSTANCE); + final long inserted = networkStorage.insert(A, 10, Action.EXECUTE, FakeActor.INSTANCE); // Assert assertThat(inserted).isEqualTo(10); - assertThat(networkStorage.findTrackedResourceByActorType("A", FakeActor.class)).isNotEmpty(); + assertThat(networkStorage.findTrackedResourceByActorType(A, FakeActor.class)).isNotEmpty(); } - private void activateStorage(final Storage storage) { + private void activateStorage(final Storage storage) { sut.setStorage(storage); sut.setActive(true); } @@ -324,20 +327,20 @@ private void activateStorage(final Storage storage) { @Nested class PriorityTest { @AddNetworkNode - StorageNetworkNode otherStorage; + StorageNetworkNode otherStorage; @ParameterizedTest @ValueSource(booleans = {true, false}) void shouldRespectPriority( final boolean oneHasPriority, - @InjectNetworkStorageChannel final StorageChannel networkStorage + @InjectNetworkStorageChannel final StorageChannel networkStorage ) { // Arrange - final LimitedStorageImpl storage1 = new LimitedStorageImpl<>(100); + final LimitedStorageImpl storage1 = new LimitedStorageImpl(100); sut.setStorage(storage1); sut.setActive(true); - final LimitedStorageImpl storage2 = new LimitedStorageImpl<>(100); + final LimitedStorageImpl storage2 = new LimitedStorageImpl(100); otherStorage.setStorage(storage2); otherStorage.setActive(true); @@ -350,7 +353,7 @@ void shouldRespectPriority( } // Act - networkStorage.insert("A", 1, Action.EXECUTE, EmptyActor.INSTANCE); + networkStorage.insert(A, 1, Action.EXECUTE, EmptyActor.INSTANCE); // Assert if (oneHasPriority) { diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java index 6f3c71781..6cb41434e 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java @@ -5,6 +5,7 @@ import com.refinedmods.refinedstorage2.api.network.component.NetworkComponent; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.constructordestructor.ConstructorStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.constructordestructor.DestructorStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.exporter.ExporterTransferStrategyFactory; @@ -23,7 +24,6 @@ import com.refinedmods.refinedstorage2.platform.api.storage.StorageContainerItemHelper; import com.refinedmods.refinedstorage2.platform.api.storage.StorageRepository; import com.refinedmods.refinedstorage2.platform.api.storage.StorageType; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; import com.refinedmods.refinedstorage2.platform.api.storage.externalstorage.PlatformExternalStorageProviderFactory; import com.refinedmods.refinedstorage2.platform.api.storagemonitor.StorageMonitorExtractionStrategy; import com.refinedmods.refinedstorage2.platform.api.storagemonitor.StorageMonitorInsertionStrategy; @@ -33,10 +33,9 @@ import com.refinedmods.refinedstorage2.platform.api.support.network.bounditem.SlotReferenceFactory; import com.refinedmods.refinedstorage2.platform.api.support.network.bounditem.SlotReferenceProvider; import com.refinedmods.refinedstorage2.platform.api.support.registry.PlatformRegistry; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceFactory; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceRendering; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.api.upgrade.BuiltinUpgradeDestinations; import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; import com.refinedmods.refinedstorage2.platform.api.wirelesstransmitter.WirelessTransmitterRangeModifier; @@ -60,13 +59,13 @@ public interface PlatformApi { PlatformApi INSTANCE = new PlatformApiProxy(); - PlatformRegistry> getStorageTypeRegistry(); + PlatformRegistry getStorageTypeRegistry(); StorageRepository getStorageRepository(Level level); StorageContainerItemHelper getStorageContainerItemHelper(); - PlatformRegistry> getStorageChannelTypeRegistry(); + PlatformRegistry getResourceTypeRegistry(); PlatformRegistry getImporterTransferStrategyRegistry(); @@ -132,25 +131,21 @@ GridScrollingStrategy createGridScrollingStrategy(AbstractContainerMenu containe void addGridScrollingStrategyFactory(GridScrollingStrategyFactory scrollingStrategyFactory); - void addResourceFactory(ResourceFactory factory); + void addResourceFactory(ResourceFactory factory); - ResourceFactory getItemResourceFactory(); + ResourceFactory getItemResourceFactory(); - PlatformStorageChannelType getItemStorageChannelType(); + StorageType getItemStorageType(); - StorageType getItemStorageType(); + ResourceFactory getFluidResourceFactory(); - ResourceFactory getFluidResourceFactory(); + StorageType getFluidStorageType(); - PlatformStorageChannelType getFluidStorageChannelType(); + Set getAlternativeResourceFactories(); - StorageType getFluidStorageType(); + void registerResourceRendering(Class resourceClass, ResourceRendering rendering); - Set> getAlternativeResourceFactories(); - - void registerResourceRendering(Class resourceClass, ResourceRendering rendering); - - ResourceRendering getResourceRendering(T resource); + ResourceRendering getResourceRendering(ResourceKey resource); void registerIngredientConverter(IngredientConverter converter); diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java index de1375c99..1980886df 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java @@ -5,6 +5,7 @@ import com.refinedmods.refinedstorage2.api.network.component.NetworkComponent; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.constructordestructor.ConstructorStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.constructordestructor.DestructorStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.exporter.ExporterTransferStrategyFactory; @@ -23,7 +24,6 @@ import com.refinedmods.refinedstorage2.platform.api.storage.StorageContainerItemHelper; import com.refinedmods.refinedstorage2.platform.api.storage.StorageRepository; import com.refinedmods.refinedstorage2.platform.api.storage.StorageType; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; import com.refinedmods.refinedstorage2.platform.api.storage.externalstorage.PlatformExternalStorageProviderFactory; import com.refinedmods.refinedstorage2.platform.api.storagemonitor.StorageMonitorExtractionStrategy; import com.refinedmods.refinedstorage2.platform.api.storagemonitor.StorageMonitorInsertionStrategy; @@ -33,8 +33,6 @@ import com.refinedmods.refinedstorage2.platform.api.support.network.bounditem.SlotReferenceFactory; import com.refinedmods.refinedstorage2.platform.api.support.network.bounditem.SlotReferenceProvider; import com.refinedmods.refinedstorage2.platform.api.support.registry.PlatformRegistry; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceFactory; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceRendering; import com.refinedmods.refinedstorage2.platform.api.upgrade.BuiltinUpgradeDestinations; @@ -68,7 +66,7 @@ public void setDelegate(final PlatformApi delegate) { } @Override - public PlatformRegistry> getStorageTypeRegistry() { + public PlatformRegistry getStorageTypeRegistry() { return ensureLoaded().getStorageTypeRegistry(); } @@ -83,8 +81,8 @@ public StorageContainerItemHelper getStorageContainerItemHelper() { } @Override - public PlatformRegistry> getStorageChannelTypeRegistry() { - return ensureLoaded().getStorageChannelTypeRegistry(); + public PlatformRegistry getResourceTypeRegistry() { + return ensureLoaded().getResourceTypeRegistry(); } @Override @@ -241,52 +239,43 @@ public void addGridScrollingStrategyFactory(final GridScrollingStrategyFactory s } @Override - public void addResourceFactory(final ResourceFactory factory) { + public void addResourceFactory(final ResourceFactory factory) { ensureLoaded().addResourceFactory(factory); } @Override - public ResourceFactory getItemResourceFactory() { + public ResourceFactory getItemResourceFactory() { return ensureLoaded().getItemResourceFactory(); } @Override - public PlatformStorageChannelType getItemStorageChannelType() { - return ensureLoaded().getItemStorageChannelType(); - } - - @Override - public StorageType getItemStorageType() { + public StorageType getItemStorageType() { return ensureLoaded().getItemStorageType(); } @Override - public ResourceFactory getFluidResourceFactory() { + public ResourceFactory getFluidResourceFactory() { return ensureLoaded().getFluidResourceFactory(); } @Override - public PlatformStorageChannelType getFluidStorageChannelType() { - return ensureLoaded().getFluidStorageChannelType(); - } - - @Override - public StorageType getFluidStorageType() { + public StorageType getFluidStorageType() { return ensureLoaded().getFluidStorageType(); } @Override - public Set> getAlternativeResourceFactories() { + public Set getAlternativeResourceFactories() { return ensureLoaded().getAlternativeResourceFactories(); } @Override - public void registerResourceRendering(final Class resourceClass, final ResourceRendering rendering) { + public void registerResourceRendering(final Class resourceClass, + final ResourceRendering rendering) { ensureLoaded().registerResourceRendering(resourceClass, rendering); } @Override - public ResourceRendering getResourceRendering(final T resource) { + public ResourceRendering getResourceRendering(final ResourceKey resource) { return ensureLoaded().getResourceRendering(resource); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/constructordestructor/ConstructorStrategy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/constructordestructor/ConstructorStrategy.java index 2e51e0308..c5daaf2cc 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/constructordestructor/ConstructorStrategy.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/constructordestructor/ConstructorStrategy.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.platform.api.constructordestructor; import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import net.minecraft.world.entity.player.Player; @@ -9,5 +10,5 @@ @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.11") @FunctionalInterface public interface ConstructorStrategy { - boolean apply(Object resource, Actor actor, Player actingPlayer, Network network); + boolean apply(ResourceKey resource, Actor actor, Player actingPlayer, Network network); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/constructordestructor/DestructorStrategy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/constructordestructor/DestructorStrategy.java index 719dec17d..ffcb17fd9 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/constructordestructor/DestructorStrategy.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/constructordestructor/DestructorStrategy.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.api.constructordestructor; -import com.refinedmods.refinedstorage2.api.core.filter.Filter; import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.resource.filter.Filter; import com.refinedmods.refinedstorage2.api.storage.Actor; import java.util.function.Supplier; diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/exporter/AmountOverride.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/exporter/AmountOverride.java index 12cf11a6f..8f6b08f0b 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/exporter/AmountOverride.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/exporter/AmountOverride.java @@ -1,5 +1,7 @@ package com.refinedmods.refinedstorage2.platform.api.exporter; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; + import java.util.function.LongSupplier; import org.apiguardian.api.API; @@ -7,12 +9,7 @@ @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.12") @FunctionalInterface public interface AmountOverride { - AmountOverride NONE = new AmountOverride() { - @Override - public long overrideAmount(final T resource, final long amount, final LongSupplier currentAmount) { - return amount; - } - }; + AmountOverride NONE = (resource, amount, currentAmount) -> amount; /** * Modifies the requested amount to a new amount. @@ -20,8 +17,7 @@ public long overrideAmount(final T resource, final long amount, final LongSu * @param resource the resource * @param amount the original requested amount * @param currentAmount the current amount present in the source - * @param the resource type * @return the new requested amount, may be 0 */ - long overrideAmount(T resource, long amount, LongSupplier currentAmount); + long overrideAmount(ResourceKey resource, long amount, LongSupplier currentAmount); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/Grid.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/Grid.java index b0f6e96a4..c07944903 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/Grid.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/Grid.java @@ -5,9 +5,7 @@ import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.Storage; import com.refinedmods.refinedstorage2.api.storage.TrackedResourceAmount; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import java.util.List; @@ -19,11 +17,11 @@ public interface Grid { void removeWatcher(GridWatcher watcher); - Storage getItemStorage(); + Storage getItemStorage(); boolean isGridActive(); - List> getResources(StorageChannelType type, Class actorType); + List getResources(Class actorType); - GridOperations createOperations(PlatformStorageChannelType storageChannelType, Actor actor); + GridOperations createOperations(ResourceType resourceType, Actor actor); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/strategy/GridExtractionStrategy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/strategy/GridExtractionStrategy.java index 79531e4dc..b53bf0a1c 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/strategy/GridExtractionStrategy.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/strategy/GridExtractionStrategy.java @@ -1,16 +1,11 @@ package com.refinedmods.refinedstorage2.platform.api.grid.strategy; import com.refinedmods.refinedstorage2.api.grid.operations.GridExtractMode; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.6") public interface GridExtractionStrategy { - boolean onExtract( - PlatformStorageChannelType storageChannelType, - T resource, - GridExtractMode extractMode, - boolean cursor - ); + boolean onExtract(PlatformResourceKey resource, GridExtractMode extractMode, boolean cursor); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/strategy/GridScrollingStrategy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/strategy/GridScrollingStrategy.java index 2648e9424..a3d4adf96 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/strategy/GridScrollingStrategy.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/strategy/GridScrollingStrategy.java @@ -1,16 +1,11 @@ package com.refinedmods.refinedstorage2.platform.api.grid.strategy; import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollMode; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.6") public interface GridScrollingStrategy { - boolean onScroll( - PlatformStorageChannelType storageChannelType, - T resource, - GridScrollMode scrollMode, - int slotIndex - ); + boolean onScroll(PlatformResourceKey resource, GridScrollMode scrollMode, int slotIndex); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/view/AbstractPlatformGridResource.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/view/AbstractPlatformGridResource.java index 1cdf4b95f..5831a758c 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/view/AbstractPlatformGridResource.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/view/AbstractPlatformGridResource.java @@ -3,6 +3,7 @@ import com.refinedmods.refinedstorage2.api.grid.view.GridResourceAttributeKey; import com.refinedmods.refinedstorage2.api.grid.view.GridView; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import java.util.Collections; @@ -13,13 +14,13 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.3.0") -public abstract class AbstractPlatformGridResource implements PlatformGridResource { - protected final ResourceAmount resourceAmount; +public abstract class AbstractPlatformGridResource implements PlatformGridResource { + protected final ResourceAmount resourceAmount; private final String name; private final Map> attributes; private boolean zeroed; - protected AbstractPlatformGridResource(final ResourceAmount resourceAmount, + protected AbstractPlatformGridResource(final ResourceAmount resourceAmount, final String name, final Map> attributes) { this.resourceAmount = resourceAmount; @@ -27,7 +28,7 @@ protected AbstractPlatformGridResource(final ResourceAmount resourceAmount, this.attributes = attributes; } - public T getResource() { + public ResourceKey getResource() { return resourceAmount.getResource(); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/view/PlatformGridResource.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/view/PlatformGridResource.java index a469a88f8..abe4ff089 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/view/PlatformGridResource.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/grid/view/PlatformGridResource.java @@ -5,9 +5,11 @@ import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollMode; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridExtractionStrategy; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridScrollingStrategy; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import java.util.List; import java.util.Optional; +import javax.annotation.Nullable; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; @@ -37,4 +39,7 @@ void onScroll(GridScrollMode scrollMode, int getRegistryId(); List getExtractionHints(); + + @Nullable + PlatformResourceKey getUnderlyingResource(); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/recipemod/IngredientConverter.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/recipemod/IngredientConverter.java index 53934e2a0..aa2ff7e8a 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/recipemod/IngredientConverter.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/recipemod/IngredientConverter.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.api.recipemod; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import java.util.Optional; @@ -8,7 +8,7 @@ @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.5") public interface IngredientConverter { - Optional> convertToResource(Object ingredient); + Optional convertToResource(Object ingredient); - Optional convertToIngredient(Object resource); + Optional convertToIngredient(PlatformResourceKey resource); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/AbstractStorageContainerItem.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/AbstractStorageContainerItem.java index 0f16a19aa..b36966d29 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/AbstractStorageContainerItem.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/AbstractStorageContainerItem.java @@ -1,8 +1,6 @@ package com.refinedmods.refinedstorage2.platform.api.storage; import com.refinedmods.refinedstorage2.api.storage.Storage; -import com.refinedmods.refinedstorage2.api.storage.TypedStorage; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import java.util.List; @@ -23,23 +21,17 @@ // TODO: Immunity for despawning // TODO: Tags/ore dict in recipes @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.0") -public abstract class AbstractStorageContainerItem extends Item implements StorageContainerItem { +public abstract class AbstractStorageContainerItem extends Item implements StorageContainerItem { protected final StorageContainerItemHelper helper; - private final StorageChannelType type; - protected AbstractStorageContainerItem(final Properties properties, - final StorageChannelType type, - final StorageContainerItemHelper helper) { + protected AbstractStorageContainerItem(final Properties properties, final StorageContainerItemHelper helper) { super(properties); - this.type = type; this.helper = helper; } @Override - @SuppressWarnings({"unchecked", "rawtypes"}) - public Optional>> resolve(final StorageRepository storageRepository, - final ItemStack stack) { - return helper.resolve(storageRepository, stack).map(storage -> new TypedStorage(storage, type)); + public Optional resolve(final StorageRepository storageRepository, final ItemStack stack) { + return helper.resolve(storageRepository, stack); } @Override @@ -85,7 +77,7 @@ public void appendHoverText(final ItemStack stack, protected abstract String formatAmount(long amount); - protected abstract Storage createStorage(StorageRepository storageRepository); + protected abstract Storage createStorage(StorageRepository storageRepository); protected abstract ItemStack createPrimaryDisassemblyByproduct(int count); diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/SerializableStorage.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/SerializableStorage.java index 688eddd8b..801799a1e 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/SerializableStorage.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/SerializableStorage.java @@ -3,6 +3,6 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.4") -public interface SerializableStorage { - StorageType getType(); +public interface SerializableStorage { + StorageType getType(); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageContainerItem.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageContainerItem.java index a1bfd3958..b66fd0588 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageContainerItem.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageContainerItem.java @@ -1,7 +1,6 @@ package com.refinedmods.refinedstorage2.platform.api.storage; import com.refinedmods.refinedstorage2.api.storage.Storage; -import com.refinedmods.refinedstorage2.api.storage.TypedStorage; import java.util.Optional; @@ -10,7 +9,7 @@ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.0") public interface StorageContainerItem { - Optional>> resolve(StorageRepository storageRepository, ItemStack stack); + Optional resolve(StorageRepository storageRepository, ItemStack stack); Optional getInfo(StorageRepository storageRepository, ItemStack stack); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageContainerItemHelper.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageContainerItemHelper.java index 865fc0e98..b2577334b 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageContainerItemHelper.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageContainerItemHelper.java @@ -21,9 +21,9 @@ @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.5") public interface StorageContainerItemHelper { - Optional> resolve(StorageRepository storageRepository, ItemStack stack); + Optional resolve(StorageRepository storageRepository, ItemStack stack); - void set(StorageRepository storageRepository, ItemStack stack, Storage storage); + void set(StorageRepository storageRepository, ItemStack stack, Storage storage); Optional getInfo(StorageRepository storageRepository, ItemStack stack); diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageInfo.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageInfo.java index c9f7007b3..c5dd83fc3 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageInfo.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageInfo.java @@ -9,10 +9,10 @@ public record StorageInfo(long stored, long capacity) { public static final StorageInfo UNKNOWN = new StorageInfo(0, 0); - public static StorageInfo of(final Storage storage) { + public static StorageInfo of(final Storage storage) { return new StorageInfo( storage.getStored(), - storage instanceof LimitedStorage limitedStorage ? limitedStorage.getCapacity() : 0L + storage instanceof LimitedStorage limitedStorage ? limitedStorage.getCapacity() : 0L ); } } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageRepository.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageRepository.java index 015e6d478..163833237 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageRepository.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageRepository.java @@ -12,29 +12,26 @@ public interface StorageRepository { /** * Retrieves a storage by ID, if it exists. * - * @param id the id - * @param the resource type + * @param id the id * @return the storage, if present */ - Optional> get(UUID id); + Optional get(UUID id); /** * Sets a storage by ID. * * @param id the id * @param storage the storage - * @param the resource type */ - void set(UUID id, Storage storage); + void set(UUID id, Storage storage); /** * If the storage exists, and is empty, it will remove the storage from the repository. * - * @param id the id - * @param the resource type + * @param id the id * @return the removed storage, if it existed and was empty */ - Optional> removeIfEmpty(UUID id); + Optional removeIfEmpty(UUID id); /** * Retrieves info for a given storage ID. diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageType.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageType.java index 81091b40a..e1ddbbf85 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageType.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/StorageType.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage2.platform.api.storage; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Storage; import javax.annotation.Nullable; @@ -8,10 +9,12 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.4") -public interface StorageType { - Storage create(@Nullable Long capacity, Runnable listener); +public interface StorageType { + Storage create(@Nullable Long capacity, Runnable listener); - Storage fromTag(CompoundTag tag, Runnable listener); + Storage fromTag(CompoundTag tag, Runnable listener); - CompoundTag toTag(Storage storage); + CompoundTag toTag(Storage storage); + + boolean isAllowed(ResourceKey resource); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/channel/AbstractPlatformStorageChannelType.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/channel/AbstractPlatformStorageChannelType.java deleted file mode 100644 index d504d1e7c..000000000 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/channel/AbstractPlatformStorageChannelType.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.api.storage.channel; - -import com.refinedmods.refinedstorage2.api.core.CoreValidations; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; -import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; - -import java.util.function.BiConsumer; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.resources.ResourceLocation; -import org.apiguardian.api.API; - -@API(status = API.Status.STABLE, since = "2.0.0-milestone.2.4") -public abstract class AbstractPlatformStorageChannelType implements PlatformStorageChannelType { - private static final String TAG_CHANGED_BY = "cb"; - private static final String TAG_CHANGED_AT = "ca"; - - private final String name; - private final StorageChannelType delegate; - private final MutableComponent title; - private final ResourceLocation textureIdentifier; - private final int textureX; - private final int textureY; - - protected AbstractPlatformStorageChannelType(final String name, - final StorageChannelType delegate, - final MutableComponent title, - final ResourceLocation textureIdentifier, - final int textureX, - final int textureY) { - this.name = name; - this.delegate = CoreValidations.validateNotNull(delegate, "Delegate cannot be null"); - this.title = title; - this.textureIdentifier = textureIdentifier; - this.textureX = textureX; - this.textureY = textureY; - } - - @Override - public CompoundTag toTag(final T resource, final TrackedResource trackedResource) { - final CompoundTag tag = toTag(resource); - tag.putString(TAG_CHANGED_BY, trackedResource.getSourceName()); - tag.putLong(TAG_CHANGED_AT, trackedResource.getTime()); - return tag; - } - - @Override - public void fromTag(final CompoundTag tag, final BiConsumer acceptor) { - fromTag(tag).ifPresent(resource -> { - final String changedBy = tag.getString(TAG_CHANGED_BY); - final long changedAt = tag.getLong(TAG_CHANGED_AT); - acceptor.accept(resource, new TrackedResource(changedBy, changedAt)); - }); - } - - @Override - public StorageChannel create() { - return delegate.create(); - } - - @Override - public MutableComponent getTitle() { - return title; - } - - @Override - public ResourceLocation getTextureIdentifier() { - return textureIdentifier; - } - - @Override - public int getXTexture() { - return textureX; - } - - @Override - public int getYTexture() { - return textureY; - } - - @Override - public String toString() { - return name; - } -} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/channel/FuzzyStorageChannel.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/channel/FuzzyStorageChannel.java index 52d8663c1..f0f70efea 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/channel/FuzzyStorageChannel.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/channel/FuzzyStorageChannel.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.platform.api.storage.channel; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import java.util.Collection; @@ -8,6 +9,6 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.4") -public interface FuzzyStorageChannel extends StorageChannel { - Collection> getFuzzy(T resource); +public interface FuzzyStorageChannel extends StorageChannel { + Collection getFuzzy(ResourceKey resource); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/channel/FuzzyStorageChannelImpl.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/channel/FuzzyStorageChannelImpl.java deleted file mode 100644 index a8a11086a..000000000 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/channel/FuzzyStorageChannelImpl.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.api.storage.channel; - -import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelImpl; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FuzzyModeNormalizer; -import com.refinedmods.refinedstorage2.platform.api.support.resource.list.FuzzyResourceList; - -import java.util.Collection; - -import org.apiguardian.api.API; - -@API(status = API.Status.STABLE, since = "2.0.0-milestone.2.4") -public class FuzzyStorageChannelImpl> extends StorageChannelImpl - implements FuzzyStorageChannel { - private final FuzzyResourceList fuzzyList; - - public FuzzyStorageChannelImpl(final FuzzyResourceList fuzzyList) { - super(fuzzyList); - this.fuzzyList = fuzzyList; - } - - @Override - public Collection> getFuzzy(final T resource) { - return fuzzyList.getFuzzy(resource); - } -} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/channel/PlatformStorageChannelType.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/channel/PlatformStorageChannelType.java deleted file mode 100644 index 666e9d079..000000000 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/channel/PlatformStorageChannelType.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.api.storage.channel; - -import com.refinedmods.refinedstorage2.api.grid.operations.GridOperations; -import com.refinedmods.refinedstorage2.api.grid.view.GridResource; -import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.api.storage.Actor; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; -import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; - -import java.util.Optional; -import java.util.function.BiConsumer; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.resources.ResourceLocation; -import org.apiguardian.api.API; - -@API(status = API.Status.STABLE, since = "2.0.0-milestone.2.5") -public interface PlatformStorageChannelType extends StorageChannelType { - CompoundTag toTag(T resource); - - CompoundTag toTag(T resource, TrackedResource trackedResource); - - void fromTag(CompoundTag tag, BiConsumer acceptor); - - Optional fromTag(CompoundTag tag); - - void toBuffer(T resource, FriendlyByteBuf buf); - - T fromBuffer(FriendlyByteBuf buf); - - Optional toGridResource(ResourceAmount resourceAmount); - - boolean isGridResourceBelonging(GridResource gridResource); - - MutableComponent getTitle(); - - ResourceLocation getTextureIdentifier(); - - int getXTexture(); - - int getYTexture(); - - long normalizeAmount(double amount); - - double getDisplayAmount(long amount); - - long getInterfaceExportLimit(); - - default long getInterfaceExportLimit(T resource) { - return getInterfaceExportLimit(); - } - - GridOperations createGridOperations(StorageChannel storageChannel, Actor actor); -} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/externalstorage/PlatformExternalStorageProviderFactory.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/externalstorage/PlatformExternalStorageProviderFactory.java index 4ef0049f9..1a5d81545 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/externalstorage/PlatformExternalStorageProviderFactory.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storage/externalstorage/PlatformExternalStorageProviderFactory.java @@ -1,6 +1,5 @@ package com.refinedmods.refinedstorage2.platform.api.storage.externalstorage; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.api.storage.external.ExternalStorageProvider; import java.util.Optional; @@ -12,10 +11,7 @@ @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.4") public interface PlatformExternalStorageProviderFactory { - Optional> create(ServerLevel level, - BlockPos pos, - Direction direction, - StorageChannelType storageChannelType); + Optional create(ServerLevel level, BlockPos pos, Direction direction); default int getPriority() { return 0; diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storagemonitor/StorageMonitorExtractionStrategy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storagemonitor/StorageMonitorExtractionStrategy.java index 595d6df0e..bec67bec2 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storagemonitor/StorageMonitorExtractionStrategy.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storagemonitor/StorageMonitorExtractionStrategy.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.platform.api.storagemonitor; import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import net.minecraft.world.entity.player.Player; @@ -9,5 +10,5 @@ @API(status = API.Status.STABLE, since = "2.0.0-milestone.3.1") @FunctionalInterface public interface StorageMonitorExtractionStrategy { - boolean extract(Object resource, boolean fullStack, Player player, Actor actor, Network network); + boolean extract(ResourceKey resource, boolean fullStack, Player player, Actor actor, Network network); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storagemonitor/StorageMonitorInsertionStrategy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storagemonitor/StorageMonitorInsertionStrategy.java index 624bfb67a..81c609ed2 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storagemonitor/StorageMonitorInsertionStrategy.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/storagemonitor/StorageMonitorInsertionStrategy.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.platform.api.storagemonitor; import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import java.util.Optional; @@ -11,5 +12,5 @@ @API(status = API.Status.STABLE, since = "2.0.0-milestone.3.1") @FunctionalInterface public interface StorageMonitorInsertionStrategy { - Optional insert(Object configuredResource, ItemStack stack, Actor actor, Network network); + Optional insert(ResourceKey configuredResource, ItemStack stack, Actor actor, Network network); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/AbstractResourceType.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/AbstractResourceType.java new file mode 100644 index 000000000..e634d2443 --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/AbstractResourceType.java @@ -0,0 +1,51 @@ +package com.refinedmods.refinedstorage2.platform.api.support.resource; + +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.resources.ResourceLocation; +import org.apiguardian.api.API; + +@API(status = API.Status.STABLE, since = "2.0.0-milestone.2.4") +public abstract class AbstractResourceType implements ResourceType { + private final String name; + private final MutableComponent title; + private final ResourceLocation textureIdentifier; + private final int textureX; + private final int textureY; + + protected AbstractResourceType(final String name, + final MutableComponent title, + final ResourceLocation textureIdentifier, + final int textureX, + final int textureY) { + this.name = name; + this.title = title; + this.textureIdentifier = textureIdentifier; + this.textureX = textureX; + this.textureY = textureY; + } + + @Override + public MutableComponent getTitle() { + return title; + } + + @Override + public ResourceLocation getTextureIdentifier() { + return textureIdentifier; + } + + @Override + public int getXTexture() { + return textureX; + } + + @Override + public int getYTexture() { + return textureY; + } + + @Override + public String toString() { + return name; + } +} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/FuzzyModeNormalizer.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/FuzzyModeNormalizer.java index eb6bbc642..0411ca36a 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/FuzzyModeNormalizer.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/FuzzyModeNormalizer.java @@ -1,8 +1,10 @@ package com.refinedmods.refinedstorage2.platform.api.support.resource; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; + import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.3") -public interface FuzzyModeNormalizer { - T normalize(); +public interface FuzzyModeNormalizer { + ResourceKey normalize(); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/PlatformResourceKey.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/PlatformResourceKey.java new file mode 100644 index 000000000..b6987d6c6 --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/PlatformResourceKey.java @@ -0,0 +1,18 @@ +package com.refinedmods.refinedstorage2.platform.api.support.resource; + +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.FriendlyByteBuf; +import org.apiguardian.api.API; + +@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.4") +public interface PlatformResourceKey extends ResourceKey { + CompoundTag toTag(); + + void toBuffer(FriendlyByteBuf buf); + + long getInterfaceExportLimit(); + + ResourceType getResourceType(); +} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceAmountTemplate.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceAmountTemplate.java deleted file mode 100644 index b131d7d3a..000000000 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceAmountTemplate.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.api.support.resource; - -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; - -import java.util.Objects; - -import net.minecraft.world.item.ItemStack; -import org.apiguardian.api.API; - -/** - * A ResourceAmountTemplate is the combination of a {@link com.refinedmods.refinedstorage2.api.resource.ResourceAmount} - * and a {@link ResourceTemplate}. It identifies a resource, its storage channel type and an amount. - * Additionally, for performance reasons, it provides an {@link ItemStack} representation. - * - * @param the resource type - */ -@API(status = API.Status.STABLE, since = "2.0.0-milestone.2.13") -public class ResourceAmountTemplate { - private final ResourceTemplate resourceTemplate; - private final long amount; - private final ItemStack stackRepresentation; - - public ResourceAmountTemplate(final T resource, - final long amount, - final PlatformStorageChannelType storageChannelType) { - this.resourceTemplate = new ResourceTemplate<>(resource, storageChannelType); - this.amount = amount; - this.stackRepresentation = resource instanceof ItemResource itemResource - ? itemResource.toItemStack(amount) - : ItemStack.EMPTY; - } - - public T getResource() { - return resourceTemplate.resource(); - } - - public PlatformStorageChannelType getStorageChannelType() { - return (PlatformStorageChannelType) resourceTemplate.storageChannelType(); - } - - public long getAmount() { - return amount; - } - - public ResourceTemplate getResourceTemplate() { - return resourceTemplate; - } - - public ItemStack getStackRepresentation() { - return stackRepresentation; - } - - public ResourceAmountTemplate withAmount(final long newAmount) { - return new ResourceAmountTemplate<>( - resourceTemplate.resource(), - newAmount, - (PlatformStorageChannelType) resourceTemplate.storageChannelType() - ); - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - final ResourceAmountTemplate that = (ResourceAmountTemplate) o; - return Objects.equals(amount, that.amount) - && Objects.equals(resourceTemplate.resource(), that.resourceTemplate.resource()); - } - - @Override - public int hashCode() { - return Objects.hash(amount, resourceTemplate.resource()); - } -} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceContainer.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceContainer.java index c9f65c5f8..e1808bf11 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceContainer.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceContainer.java @@ -1,8 +1,8 @@ package com.refinedmods.refinedstorage2.platform.api.support.resource; import com.refinedmods.refinedstorage2.api.core.Action; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import java.util.List; import java.util.Set; @@ -25,7 +25,7 @@ public interface ResourceContainer { void change(int index, ItemStack stack, boolean tryAlternatives); - void set(int index, ResourceAmountTemplate resourceAmount); + void set(int index, ResourceAmount resourceAmount); long getAmount(int index); @@ -35,20 +35,29 @@ public interface ResourceContainer { void setAmount(int index, long amount); - long getMaxAmount(ResourceAmountTemplate resourceAmount); + long getMaxAmount(ResourceKey resource); - boolean isValid(T resource); + boolean isValid(ResourceKey resource); void remove(int index); int size(); + default boolean isEmpty(int index) { + return get(index) == null; + } + + @Nullable + ResourceAmount get(int index); + @Nullable - ResourceAmountTemplate get(int index); + PlatformResourceKey getResource(int index); + + ItemStack getStackRepresentation(int index); - Set getUniqueTemplates(); + Set getUniqueResources(); - List> getTemplates(); + List getResources(); void writeToUpdatePacket(FriendlyByteBuf buf); @@ -58,15 +67,15 @@ public interface ResourceContainer { void fromTag(CompoundTag tag); - ResourceFactory getPrimaryResourceFactory(); + ResourceFactory getPrimaryResourceFactory(); - Set> getAlternativeResourceFactories(); + Set getAlternativeResourceFactories(); Container toItemContainer(); - long insert(StorageChannelType storageChannelType, T resource, long amount, Action action); + long insert(ResourceKey resource, long amount, Action action); - long extract(T resource, long amount, Action action); + long extract(ResourceKey resource, long amount, Action action); ResourceContainer copy(); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceFactory.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceFactory.java index c1ac32c0c..5d37f2177 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceFactory.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceFactory.java @@ -1,13 +1,16 @@ package com.refinedmods.refinedstorage2.platform.api.support.resource; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; + import java.util.Optional; import net.minecraft.world.item.ItemStack; import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.13") -public interface ResourceFactory { - Optional> create(ItemStack stack); +public interface ResourceFactory { + Optional create(ItemStack stack); - boolean isValid(Object resource); + boolean isValid(ResourceKey resource); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceRendering.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceRendering.java index f85937be1..4485da524 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceRendering.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceRendering.java @@ -1,5 +1,7 @@ package com.refinedmods.refinedstorage2.platform.api.support.resource; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; + import java.util.List; import com.mojang.blaze3d.vertex.PoseStack; @@ -10,14 +12,14 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.13") -public interface ResourceRendering { +public interface ResourceRendering { String getDisplayedAmount(long amount, boolean withUnits); - Component getDisplayName(T resource); + Component getDisplayName(ResourceKey resource); - List getTooltip(T resource); + List getTooltip(ResourceKey resource); - void render(T resource, GuiGraphics graphics, int x, int y); + void render(ResourceKey resource, GuiGraphics graphics, int x, int y); - void render(T resource, PoseStack poseStack, MultiBufferSource renderTypeBuffer, int light, Level level); + void render(ResourceKey resource, PoseStack poseStack, MultiBufferSource renderTypeBuffer, int light, Level level); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceType.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceType.java new file mode 100644 index 000000000..ea0b7fde8 --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ResourceType.java @@ -0,0 +1,41 @@ +package com.refinedmods.refinedstorage2.platform.api.support.resource; + +import com.refinedmods.refinedstorage2.api.grid.operations.GridOperations; +import com.refinedmods.refinedstorage2.api.grid.view.GridResource; +import com.refinedmods.refinedstorage2.api.storage.Actor; +import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; + +import java.util.Optional; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.resources.ResourceLocation; +import org.apiguardian.api.API; + +@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.4") +public interface ResourceType { + Optional fromTag(CompoundTag tag); + + PlatformResourceKey fromBuffer(FriendlyByteBuf buf); + + MutableComponent getTitle(); + + ResourceLocation getTextureIdentifier(); + + int getXTexture(); + + int getYTexture(); + + long normalizeAmount(double amount); + + double getDisplayAmount(long amount); + + Optional toGridResource(PlatformResourceKey resource, long amount); + + boolean isGridResourceBelonging(GridResource gridResource); + + long getInterfaceExportLimit(); + + GridOperations createGridOperations(StorageChannel storageChannel, Actor actor); +} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/list/FuzzyResourceList.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/list/FuzzyResourceList.java index e624bbf1b..0884466cd 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/list/FuzzyResourceList.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/list/FuzzyResourceList.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.platform.api.support.resource.list; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; import com.refinedmods.refinedstorage2.platform.api.support.resource.FuzzyModeNormalizer; @@ -9,12 +10,12 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.4") -public interface FuzzyResourceList> extends ResourceList { +public interface FuzzyResourceList extends ResourceList { /** * Retrieves all resources that match the normalized variant from {@link FuzzyModeNormalizer}. * * @param resource the resource, doesn't matter if it's normalized or not * @return a list of fuzzy matched variants, or empty list if none found */ - Collection> getFuzzy(T resource); + Collection getFuzzy(ResourceKey resource); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/list/FuzzyResourceListImpl.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/list/FuzzyResourceListImpl.java deleted file mode 100644 index a19a293aa..000000000 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/list/FuzzyResourceListImpl.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.api.support.resource.list; - -import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.api.resource.list.AbstractProxyResourceList; -import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; -import com.refinedmods.refinedstorage2.api.resource.list.ResourceListOperationResult; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FuzzyModeNormalizer; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -import org.apiguardian.api.API; - -@API(status = API.Status.STABLE, since = "2.0.0-milestone.2.4") -public class FuzzyResourceListImpl> - extends AbstractProxyResourceList - implements FuzzyResourceList { - private final Map>> normalizedFuzzyMap = new HashMap<>(); - - public FuzzyResourceListImpl(final ResourceList delegate) { - super(delegate); - } - - @Override - public ResourceListOperationResult add(final T resource, final long amount) { - final ResourceListOperationResult result = super.add(resource, amount); - addToIndex(resource, result); - return result; - } - - private void addToIndex(final T resource, final ResourceListOperationResult result) { - normalizedFuzzyMap.computeIfAbsent(resource.normalize(), k -> new HashSet<>()).add(result.resourceAmount()); - } - - @Override - public Optional> remove(final T resource, final long amount) { - return super.remove(resource, amount) - .map(result -> { - if (!result.available()) { - removeFromIndex(resource, result); - } - return result; - }); - } - - private void removeFromIndex(final T resource, final ResourceListOperationResult result) { - final T normalized = resource.normalize(); - final Collection> index = normalizedFuzzyMap.get(normalized); - if (index == null) { - return; - } - index.remove(result.resourceAmount()); - if (index.isEmpty()) { - normalizedFuzzyMap.remove(normalized); - } - } - - @Override - public Collection> getFuzzy(final T resource) { - return normalizedFuzzyMap.getOrDefault(resource.normalize(), Collections.emptySet()); - } -} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractClientModInitializer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractClientModInitializer.java index 89068d786..87096e77e 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractClientModInitializer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractClientModInitializer.java @@ -1,8 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.constructordestructor.ConstructorScreen; import com.refinedmods.refinedstorage2.platform.common.constructordestructor.DestructorScreen; import com.refinedmods.refinedstorage2.platform.common.content.Items; @@ -27,7 +25,9 @@ import com.refinedmods.refinedstorage2.platform.common.storage.storageblock.FluidStorageBlockScreen; import com.refinedmods.refinedstorage2.platform.common.storage.storageblock.ItemStorageBlockScreen; import com.refinedmods.refinedstorage2.platform.common.storagemonitor.StorageMonitorScreen; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResourceRendering; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResourceRendering; import com.refinedmods.refinedstorage2.platform.common.upgrade.RegulatorUpgradeScreen; import com.refinedmods.refinedstorage2.platform.common.wirelesstransmitter.WirelessTransmitterScreen; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java index 61a9cbd57..637af1260 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java @@ -5,7 +5,6 @@ import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; import com.refinedmods.refinedstorage2.api.network.impl.component.EnergyNetworkComponentImpl; import com.refinedmods.refinedstorage2.api.network.impl.component.GraphNetworkComponentImpl; -import com.refinedmods.refinedstorage2.api.network.impl.component.StorageNetworkComponentImpl; import com.refinedmods.refinedstorage2.api.network.impl.node.SimpleNetworkNode; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.PlatformApiProxy; @@ -58,7 +57,6 @@ import com.refinedmods.refinedstorage2.platform.common.storage.FluidStorageType; import com.refinedmods.refinedstorage2.platform.common.storage.ItemStorageType; import com.refinedmods.refinedstorage2.platform.common.storage.StorageTypes; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import com.refinedmods.refinedstorage2.platform.common.storage.diskdrive.AbstractDiskDriveBlockEntity; import com.refinedmods.refinedstorage2.platform.common.storage.diskdrive.DiskDriveBlock; import com.refinedmods.refinedstorage2.platform.common.storage.diskdrive.DiskDriveContainerMenu; @@ -94,7 +92,9 @@ import com.refinedmods.refinedstorage2.platform.common.support.SimpleItem; import com.refinedmods.refinedstorage2.platform.common.support.energy.EnergyLootItemFunction; import com.refinedmods.refinedstorage2.platform.common.support.network.NetworkNodeContainerBlockEntityImpl; +import com.refinedmods.refinedstorage2.platform.common.support.network.component.PlatformStorageNetworkComponent; import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResourceFactory; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceTypes; import com.refinedmods.refinedstorage2.platform.common.upgrade.FortuneUpgradeItem; import com.refinedmods.refinedstorage2.platform.common.upgrade.RangeUpgradeItem; import com.refinedmods.refinedstorage2.platform.common.upgrade.RegulatorUpgradeContainerMenu; @@ -173,7 +173,7 @@ public abstract class AbstractModInitializer { protected final void initializePlatformApi() { ((PlatformApiProxy) PlatformApi.INSTANCE).setDelegate(new PlatformApiImpl()); registerAdditionalStorageTypes(); - registerAdditionalStorageChannelTypes(); + registerAdditionalResourceTypes(); registerAdditionalResourceFactories(); registerDestructorStrategyFactories(); registerConstructorStrategyFactories(); @@ -190,10 +190,10 @@ private void registerAdditionalStorageTypes() { ); } - private void registerAdditionalStorageChannelTypes() { - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().register( + private void registerAdditionalResourceTypes() { + PlatformApi.INSTANCE.getResourceTypeRegistry().register( createIdentifier(FLUID_REGISTRY_KEY), - StorageChannelTypes.FLUID + ResourceTypes.FLUID ); } @@ -238,9 +238,7 @@ private void registerNetworkComponents() { ); PlatformApi.INSTANCE.getNetworkComponentMapFactory().addFactory( StorageNetworkComponent.class, - network -> new StorageNetworkComponentImpl( - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().getAll() - ) + network -> new PlatformStorageNetworkComponent() ); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java index 54bdec5c8..61c22ab7e 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java @@ -91,11 +91,11 @@ interface GridEntry extends SimpleEnergyUsageEntry { void setSize(GridSize size); - Optional getStorageChannelType(); + Optional getResourceTypeId(); - void setStorageChannelType(ResourceLocation storageChannelTypeId); + void setResourceTypeId(ResourceLocation resourceTypeId); - void clearStorageChannelType(); + void clearResourceType(); } interface CraftingGridEntry extends SimpleEnergyUsageEntry { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Platform.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Platform.java index 6b4953556..132868491 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Platform.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Platform.java @@ -3,15 +3,14 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.grid.view.GridResourceFactory; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; -import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridInsertionStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.support.ClientToServerCommunications; import com.refinedmods.refinedstorage2.platform.common.support.ServerToClientCommunications; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.MenuOpener; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.TransferManager; import com.refinedmods.refinedstorage2.platform.common.support.render.FluidRenderer; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.List; import java.util.Optional; @@ -118,6 +117,6 @@ List processTooltipComponents( Optional getEnergyStorage(ItemStack stack); - record ContainedFluid(ItemStack remainderContainer, ResourceAmount fluid) { + record ContainedFluid(ItemStack remainderContainer, FluidResource fluid, long amount) { } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java index 4049dbff1..5eab2aa38 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java @@ -8,6 +8,7 @@ import com.refinedmods.refinedstorage2.api.network.impl.NetworkBuilderImpl; import com.refinedmods.refinedstorage2.api.network.impl.NetworkFactory; import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.constructordestructor.ConstructorStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.constructordestructor.DestructorStrategyFactory; @@ -27,7 +28,6 @@ import com.refinedmods.refinedstorage2.platform.api.storage.StorageContainerItemHelper; import com.refinedmods.refinedstorage2.platform.api.storage.StorageRepository; import com.refinedmods.refinedstorage2.platform.api.storage.StorageType; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; import com.refinedmods.refinedstorage2.platform.api.storage.externalstorage.PlatformExternalStorageProviderFactory; import com.refinedmods.refinedstorage2.platform.api.storagemonitor.StorageMonitorExtractionStrategy; import com.refinedmods.refinedstorage2.platform.api.storagemonitor.StorageMonitorInsertionStrategy; @@ -37,10 +37,9 @@ import com.refinedmods.refinedstorage2.platform.api.support.network.bounditem.SlotReferenceFactory; import com.refinedmods.refinedstorage2.platform.api.support.network.bounditem.SlotReferenceProvider; import com.refinedmods.refinedstorage2.platform.api.support.registry.PlatformRegistry; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceFactory; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceRendering; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.api.upgrade.BuiltinUpgradeDestinations; import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; import com.refinedmods.refinedstorage2.platform.api.wirelesstransmitter.WirelessTransmitterRangeModifier; @@ -57,7 +56,6 @@ import com.refinedmods.refinedstorage2.platform.common.storage.StorageContainerItemHelperImpl; import com.refinedmods.refinedstorage2.platform.common.storage.StorageRepositoryImpl; import com.refinedmods.refinedstorage2.platform.common.storage.StorageTypes; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import com.refinedmods.refinedstorage2.platform.common.storagemonitor.CompositeStorageMonitorExtractionStrategy; import com.refinedmods.refinedstorage2.platform.common.storagemonitor.CompositeStorageMonitorInsertionStrategy; import com.refinedmods.refinedstorage2.platform.common.support.energy.EnergyItemHelperImpl; @@ -71,6 +69,7 @@ import com.refinedmods.refinedstorage2.platform.common.support.registry.PlatformRegistryImpl; import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResourceFactory; import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResourceFactory; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceTypes; import com.refinedmods.refinedstorage2.platform.common.upgrade.BuiltinUpgradeDestinationsImpl; import com.refinedmods.refinedstorage2.platform.common.upgrade.UpgradeRegistryImpl; import com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil; @@ -116,10 +115,10 @@ public class PlatformApiImpl implements PlatformApi { new ComponentMapFactory<>(); private final NetworkBuilder networkBuilder = new NetworkBuilderImpl(new NetworkFactory(networkComponentMapFactory)); - private final PlatformRegistry> storageTypeRegistry = + private final PlatformRegistry storageTypeRegistry = new PlatformRegistryImpl<>(createIdentifier(ITEM_REGISTRY_KEY), StorageTypes.ITEM); - private final PlatformRegistry> storageChannelTypeRegistry = - new PlatformRegistryImpl<>(createIdentifier(ITEM_REGISTRY_KEY), StorageChannelTypes.ITEM); + private final PlatformRegistry resourceTypeRegistry = + new PlatformRegistryImpl<>(createIdentifier(ITEM_REGISTRY_KEY), ResourceTypes.ITEM); private final PlatformRegistry gridSynchronizerRegistry = new PlatformRegistryImpl<>(createIdentifier("off"), new NoopGridSynchronizer()); private final PlatformRegistry importerTransferStrategyRegistry = @@ -152,10 +151,10 @@ public class PlatformApiImpl implements PlatformApi { ); private final List gridExtractionStrategyFactories = new ArrayList<>(); private final List gridScrollingStrategyFactories = new ArrayList<>(); - private final ResourceFactory itemResourceFactory = new ItemResourceFactory(); - private final ResourceFactory fluidResourceFactory = new FluidResourceFactory(); - private final Set> resourceFactories = new HashSet<>(); - private final Map, ResourceRendering> resourceRenderingMap = new HashMap<>(); + private final ResourceFactory itemResourceFactory = new ItemResourceFactory(); + private final ResourceFactory fluidResourceFactory = new FluidResourceFactory(); + private final Set resourceFactories = new HashSet<>(); + private final Map, ResourceRendering> resourceRenderingMap = new HashMap<>(); private final CompositeWirelessTransmitterRangeModifier wirelessTransmitterRangeModifier = new CompositeWirelessTransmitterRangeModifier(); private final EnergyItemHelper energyItemHelper = new EnergyItemHelperImpl(); @@ -167,7 +166,7 @@ public class PlatformApiImpl implements PlatformApi { private final CompositeSlotReferenceProvider slotReferenceProvider = new CompositeSlotReferenceProvider(); @Override - public PlatformRegistry> getStorageTypeRegistry() { + public PlatformRegistry getStorageTypeRegistry() { return storageTypeRegistry; } @@ -201,8 +200,8 @@ private StorageRepositoryImpl createStorageRepository() { } @Override - public PlatformRegistry> getStorageChannelTypeRegistry() { - return storageChannelTypeRegistry; + public PlatformRegistry getResourceTypeRegistry() { + return resourceTypeRegistry; } @Override @@ -282,7 +281,7 @@ public PlatformRegistry getGridSynchronizerRegistry() { @Override public void writeGridScreenOpeningData(final Grid grid, final FriendlyByteBuf buf) { - AbstractGridContainerMenu.writeScreenOpeningData(storageChannelTypeRegistry, grid, buf); + AbstractGridContainerMenu.writeScreenOpeningData(grid, buf); } @Override @@ -384,54 +383,44 @@ public void addGridScrollingStrategyFactory(final GridScrollingStrategyFactory s } @Override - public void addResourceFactory(final ResourceFactory factory) { + public void addResourceFactory(final ResourceFactory factory) { resourceFactories.add(factory); } @Override - public ResourceFactory getItemResourceFactory() { + public ResourceFactory getItemResourceFactory() { return itemResourceFactory; } @Override - public PlatformStorageChannelType getItemStorageChannelType() { - return StorageChannelTypes.ITEM; - } - - @Override - public StorageType getItemStorageType() { + public StorageType getItemStorageType() { return StorageTypes.ITEM; } @Override - public ResourceFactory getFluidResourceFactory() { + public ResourceFactory getFluidResourceFactory() { return fluidResourceFactory; } @Override - public PlatformStorageChannelType getFluidStorageChannelType() { - return StorageChannelTypes.FLUID; - } - - @Override - public StorageType getFluidStorageType() { + public StorageType getFluidStorageType() { return StorageTypes.FLUID; } @Override - public Set> getAlternativeResourceFactories() { + public Set getAlternativeResourceFactories() { return resourceFactories; } @Override - public void registerResourceRendering(final Class resourceClass, final ResourceRendering rendering) { + public void registerResourceRendering(final Class resourceClass, + final ResourceRendering rendering) { resourceRenderingMap.put(resourceClass, rendering); } @Override - @SuppressWarnings("unchecked") - public ResourceRendering getResourceRendering(final T resource) { - return (ResourceRendering) resourceRenderingMap.get(resource.getClass()); + public ResourceRendering getResourceRendering(final ResourceKey resource) { + return resourceRenderingMap.get(resource.getClass()); } @Override diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformProxy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformProxy.java index 9ef09ac11..21da8eb65 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformProxy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformProxy.java @@ -4,13 +4,13 @@ import com.refinedmods.refinedstorage2.api.grid.view.GridResourceFactory; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridInsertionStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.support.ClientToServerCommunications; import com.refinedmods.refinedstorage2.platform.common.support.ServerToClientCommunications; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.MenuOpener; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.TransferManager; import com.refinedmods.refinedstorage2.platform.common.support.render.FluidRenderer; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.List; import java.util.Optional; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/AbstractItemConstructorStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/AbstractItemConstructorStrategy.java index fe58bd497..deaff8a3c 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/AbstractItemConstructorStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/AbstractItemConstructorStrategy.java @@ -3,11 +3,11 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.platform.api.constructordestructor.ConstructorStrategy; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -32,7 +32,7 @@ protected long getTransferAmount() { @Override public final boolean apply( - final Object resource, + final ResourceKey resource, final Actor actor, final Player actingPlayer, final Network network @@ -43,8 +43,7 @@ public final boolean apply( if (!(resource instanceof ItemResource itemResource)) { return false; } - final StorageChannel storageChannel = network.getComponent(StorageNetworkComponent.class) - .getStorageChannel(StorageChannelTypes.ITEM); + final StorageChannel storageChannel = network.getComponent(StorageNetworkComponent.class); final long amount = getTransferAmount(); final long extractedAmount = storageChannel.extract(itemResource, amount, Action.SIMULATE, actor); if (extractedAmount == 0) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/BlockBreakDestructorStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/BlockBreakDestructorStrategy.java index b5c9d79c2..0b15939a8 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/BlockBreakDestructorStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/BlockBreakDestructorStrategy.java @@ -1,15 +1,14 @@ package com.refinedmods.refinedstorage2.platform.common.constructordestructor; import com.refinedmods.refinedstorage2.api.core.Action; -import com.refinedmods.refinedstorage2.api.core.filter.Filter; import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; +import com.refinedmods.refinedstorage2.api.resource.filter.Filter; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.platform.api.constructordestructor.DestructorStrategy; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.Platform; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.List; import java.util.function.Supplier; @@ -75,10 +74,8 @@ public boolean apply(final Filter filter, return true; } - private static StorageChannel getStorageChannel(final Supplier network) { - return network.get() - .getComponent(StorageNetworkComponent.class) - .getStorageChannel(StorageChannelTypes.ITEM); + private static StorageChannel getStorageChannel(final Supplier network) { + return network.get().getComponent(StorageNetworkComponent.class); } private static boolean isFastExit(final BlockState blockState) { @@ -109,7 +106,7 @@ private boolean isAllowed( private boolean insertDrops( final Actor actor, final List drops, - final StorageChannel storage, + final StorageChannel storage, final Action action ) { for (final ItemStack drop : drops) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/CompositeConstructorStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/CompositeConstructorStrategy.java index 0b6ef3b36..f44b04900 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/CompositeConstructorStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/CompositeConstructorStrategy.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.constructordestructor; import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.platform.api.constructordestructor.ConstructorStrategy; @@ -17,7 +18,10 @@ class CompositeConstructorStrategy implements ConstructorStrategy { } @Override - public boolean apply(final Object resource, final Actor actor, final Player actingPlayer, final Network network) { + public boolean apply(final ResourceKey resource, + final Actor actor, + final Player actingPlayer, + final Network network) { for (final ConstructorStrategy strategy : strategies) { if (strategy.apply(resource, actor, actingPlayer, network)) { return true; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/CompositeDestructorStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/CompositeDestructorStrategy.java index 1bc13264c..ed8f3b332 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/CompositeDestructorStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/CompositeDestructorStrategy.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.constructordestructor; -import com.refinedmods.refinedstorage2.api.core.filter.Filter; import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.resource.filter.Filter; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.platform.api.constructordestructor.DestructorStrategy; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/ConstructorBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/ConstructorBlockEntity.java index 335595124..05e3eae2d 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/ConstructorBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/ConstructorBlockEntity.java @@ -5,6 +5,7 @@ import com.refinedmods.refinedstorage2.api.network.node.NetworkNodeActor; import com.refinedmods.refinedstorage2.api.network.node.task.Task; import com.refinedmods.refinedstorage2.api.network.node.task.TaskExecutor; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.constructordestructor.ConstructorStrategy; @@ -56,9 +57,9 @@ public ConstructorBlockEntity(final BlockPos pos, final BlockState state) { } @Override - protected void setFilterTemplates(final List templates) { + protected void setFilters(final List filters) { this.tasks.clear(); - this.tasks.addAll(templates.stream().map(TaskImpl::new).toList()); + this.tasks.addAll(filters.stream().map(TaskImpl::new).toList()); } @Override @@ -156,10 +157,10 @@ protected record TaskContext(Network network, Player player) { } private class TaskImpl implements Task { - private final Object template; + private final ResourceKey filter; - private TaskImpl(final Object template) { - this.template = template; + private TaskImpl(final ResourceKey filter) { + this.filter = filter; } @Override @@ -167,7 +168,7 @@ public boolean run(final TaskContext context) { if (strategy == null) { return false; } - strategy.apply(template, actor, context.player, context.network); + strategy.apply(filter, actor, context.player, context.network); return true; } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/DestructorBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/DestructorBlockEntity.java index 61ed09d6f..87441fbdc 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/DestructorBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/DestructorBlockEntity.java @@ -1,9 +1,9 @@ package com.refinedmods.refinedstorage2.platform.common.constructordestructor; -import com.refinedmods.refinedstorage2.api.core.filter.Filter; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; import com.refinedmods.refinedstorage2.api.network.impl.node.SimpleNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.NetworkNodeActor; +import com.refinedmods.refinedstorage2.api.resource.filter.Filter; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.constructordestructor.DestructorStrategy; @@ -54,10 +54,10 @@ public DestructorBlockEntity(final BlockPos pos, final BlockState state) { UpgradeDestinations.DESTRUCTOR ); this.actor = new NetworkNodeActor(getNode()); - this.filterWithFuzzyMode = FilterWithFuzzyMode.createAndListenForUniqueTemplates( + this.filterWithFuzzyMode = FilterWithFuzzyMode.createAndListenForUniqueFilters( ResourceContainerImpl.createForFilter(), this::setChanged, - filter::setTemplates + filter::setFilters ); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/DestructorContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/DestructorContainerMenu.java index 847c8af6e..ca122493d 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/DestructorContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/DestructorContainerMenu.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.constructordestructor; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceContainer; import com.refinedmods.refinedstorage2.platform.common.content.Menus; import com.refinedmods.refinedstorage2.platform.common.support.RedstoneMode; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/FluidBreakDestructorStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/FluidBreakDestructorStrategy.java index 5472817f0..74bdc3a7b 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/FluidBreakDestructorStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/FluidBreakDestructorStrategy.java @@ -1,15 +1,14 @@ package com.refinedmods.refinedstorage2.platform.common.constructordestructor; import com.refinedmods.refinedstorage2.api.core.Action; -import com.refinedmods.refinedstorage2.api.core.filter.Filter; import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; +import com.refinedmods.refinedstorage2.api.resource.filter.Filter; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.platform.api.constructordestructor.DestructorStrategy; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.common.Platform; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import java.util.function.Supplier; @@ -73,9 +72,7 @@ private boolean tryInsert(final Actor actor, return true; } - private StorageChannel getStorageChannel(final Supplier networkSupplier) { - return networkSupplier.get() - .getComponent(StorageNetworkComponent.class) - .getStorageChannel(StorageChannelTypes.FLUID); + private StorageChannel getStorageChannel(final Supplier networkSupplier) { + return networkSupplier.get().getComponent(StorageNetworkComponent.class); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/ItemDropConstructorStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/ItemDropConstructorStrategy.java index 74a92fa58..8f7d46595 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/ItemDropConstructorStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/ItemDropConstructorStrategy.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.constructordestructor; import com.refinedmods.refinedstorage2.api.storage.Actor; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/ItemPickupDestructorStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/ItemPickupDestructorStrategy.java index 5eb87f603..b010c19fc 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/ItemPickupDestructorStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/ItemPickupDestructorStrategy.java @@ -1,14 +1,13 @@ package com.refinedmods.refinedstorage2.platform.common.constructordestructor; import com.refinedmods.refinedstorage2.api.core.Action; -import com.refinedmods.refinedstorage2.api.core.filter.Filter; import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; +import com.refinedmods.refinedstorage2.api.resource.filter.Filter; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.platform.api.constructordestructor.DestructorStrategy; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.List; import java.util.function.Supplier; @@ -37,9 +36,7 @@ public boolean apply(final Filter filter, if (!level.isLoaded(pos)) { return false; } - final StorageChannel storageChannel = networkSupplier.get() - .getComponent(StorageNetworkComponent.class) - .getStorageChannel(StorageChannelTypes.ITEM); + final StorageChannel storageChannel = networkSupplier.get().getComponent(StorageNetworkComponent.class); final List items = level.getEntitiesOfClass(ItemEntity.class, new AABB(pos)); for (final ItemEntity itemEntity : items) { tryInsert(filter, actor, storageChannel, itemEntity); @@ -49,7 +46,7 @@ public boolean apply(final Filter filter, private void tryInsert(final Filter filter, final Actor actor, - final StorageChannel storageChannel, + final StorageChannel storageChannel, final ItemEntity itemEntity) { if (itemEntity.isRemoved()) { return; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/PlaceBlockConstructorStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/PlaceBlockConstructorStrategy.java index b2dd9717f..9a6820ead 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/PlaceBlockConstructorStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/PlaceBlockConstructorStrategy.java @@ -1,8 +1,8 @@ package com.refinedmods.refinedstorage2.platform.common.constructordestructor; import com.refinedmods.refinedstorage2.api.storage.Actor; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.Platform; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/PlaceFireworksConstructorStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/PlaceFireworksConstructorStrategy.java index 98a804750..7033f24be 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/PlaceFireworksConstructorStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/PlaceFireworksConstructorStrategy.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.constructordestructor; import com.refinedmods.refinedstorage2.api.storage.Actor; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/PlaceFluidConstructorStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/PlaceFluidConstructorStrategy.java index 3987a67e1..b44515091 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/PlaceFluidConstructorStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/constructordestructor/PlaceFluidConstructorStrategy.java @@ -3,12 +3,12 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.platform.api.constructordestructor.ConstructorStrategy; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.common.Platform; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -28,7 +28,7 @@ public PlaceFluidConstructorStrategy(final ServerLevel level, final BlockPos pos @Override public boolean apply( - final Object resource, + final ResourceKey resource, final Actor actor, final Player actingPlayer, final Network network @@ -39,8 +39,7 @@ public boolean apply( if (!(resource instanceof FluidResource fluidResource)) { return false; } - final StorageChannel storageChannel = network.getComponent(StorageNetworkComponent.class) - .getStorageChannel(StorageChannelTypes.FLUID); + final StorageChannel storageChannel = network.getComponent(StorageNetworkComponent.class); final long bucketAmount = Platform.INSTANCE.getBucketAmount(); final long extractedAmount = storageChannel.extract( fluidResource, diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/controller/AbstractControllerBlock.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/controller/AbstractControllerBlock.java index 7e5b47049..7acfa9e89 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/controller/AbstractControllerBlock.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/controller/AbstractControllerBlock.java @@ -33,10 +33,10 @@ public abstract class AbstractControllerBlock private final ControllerBlockEntityTicker ticker; private final DyeColor color; - public AbstractControllerBlock(final ControllerType type, - final MutableComponent name, - final ControllerBlockEntityTicker ticker, - final DyeColor color) { + protected AbstractControllerBlock(final ControllerType type, + final MutableComponent name, + final ControllerBlockEntityTicker ticker, + final DyeColor color) { super(BlockConstants.PROPERTIES); this.type = type; this.name = name; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/detector/DetectorBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/detector/DetectorBlockEntity.java index 1605f68dd..680e685a0 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/detector/DetectorBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/detector/DetectorBlockEntity.java @@ -5,7 +5,7 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.detector.DetectorMode; import com.refinedmods.refinedstorage2.api.network.impl.node.detector.DetectorNetworkNode; import com.refinedmods.refinedstorage2.platform.api.support.network.ConnectionSink; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceContainer; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; @@ -51,15 +51,13 @@ public DetectorBlockEntity(final BlockPos pos, final BlockState state) { Platform.INSTANCE.getConfig().getDetector().getEnergyUsage() )); final ResourceContainer resourceContainer = ResourceContainerImpl.createForFilter(1); - this.filter = FilterWithFuzzyMode.createAndListenForTemplates( + this.filter = FilterWithFuzzyMode.createAndListenForFilters( resourceContainer, () -> { propagateAmount(); setChanged(); }, - templates -> getNode().setFilterTemplate( - templates.isEmpty() ? null : templates.get(0) - ) + filters -> getNode().setConfiguredResource(filters.isEmpty() ? null : filters.get(0)) ); initialize(); } @@ -93,10 +91,10 @@ void setAmount(final double amount) { } private void propagateAmount() { - final ResourceAmountTemplate resourceAmount = filter.getFilterContainer().get(0); - final long normalizedAmount = resourceAmount == null + final PlatformResourceKey configuredResource = filter.getFilterContainer().getResource(0); + final long normalizedAmount = configuredResource == null ? (long) amount - : resourceAmount.getStorageChannelType().normalizeAmount(amount); + : configuredResource.getResourceType().normalizeAmount(amount); LOGGER.debug("Updating detector amount of {} normalized as {}", amount, normalizedAmount); getNode().setAmount(normalizedAmount); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/detector/FuzzyDetectorAmountStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/detector/FuzzyDetectorAmountStrategy.java index 9372be618..1a76fa7c2 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/detector/FuzzyDetectorAmountStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/detector/FuzzyDetectorAmountStrategy.java @@ -4,7 +4,7 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.detector.AbstractDetectorAmountStrategy; import com.refinedmods.refinedstorage2.api.network.impl.node.detector.DetectorAmountStrategy; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.platform.api.storage.channel.FuzzyStorageChannel; @@ -16,12 +16,12 @@ class FuzzyDetectorAmountStrategy extends AbstractDetectorAmountStrategy { } @Override - public long getAmount(final Network network, final ResourceTemplate template) { - final StorageChannel storageChannel = getStorageChannel(network, template); - if (!(storageChannel instanceof FuzzyStorageChannel fuzzyStorageChannel)) { - return fallback.getAmount(network, template); + public long getAmount(final Network network, final ResourceKey configuredResource) { + final StorageChannel storageChannel = getStorageChannel(network); + if (!(storageChannel instanceof FuzzyStorageChannel fuzzyStorageChannel)) { + return fallback.getAmount(network, configuredResource); } - return fuzzyStorageChannel.getFuzzy(template.resource()) + return fuzzyStorageChannel.getFuzzy(configuredResource) .stream() .mapToLong(ResourceAmount::getAmount) .sum(); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/exporter/ExporterBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/exporter/ExporterBlockEntity.java index 6c8f755dd..36bf2469d 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/exporter/ExporterBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/exporter/ExporterBlockEntity.java @@ -4,6 +4,7 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.exporter.ExporterNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.exporter.ExporterTransferStrategy; import com.refinedmods.refinedstorage2.api.network.node.task.TaskExecutor; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; import com.refinedmods.refinedstorage2.platform.api.exporter.ExporterTransferStrategyFactory; @@ -94,12 +95,12 @@ protected void setTaskExecutor(final TaskExecutor templates) { - getNode().setFilterTemplates(templates); + protected void setFilters(final List filters) { + getNode().setFilters(filters); } @Override - public long overrideAmount(final T resource, final long amount, final LongSupplier currentAmount) { + public long overrideAmount(final ResourceKey resource, final long amount, final LongSupplier currentAmount) { if (!upgradeContainer.has(Items.INSTANCE.getRegulatorUpgrade())) { return amount; } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/exporter/AbstractFuzzyExporterTransferStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/exporter/FuzzyExporterTransferStrategy.java similarity index 54% rename from refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/exporter/AbstractFuzzyExporterTransferStrategy.java rename to refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/exporter/FuzzyExporterTransferStrategy.java index b2ec80ad9..9e5bf078c 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/exporter/AbstractFuzzyExporterTransferStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/exporter/FuzzyExporterTransferStrategy.java @@ -1,27 +1,23 @@ package com.refinedmods.refinedstorage2.platform.common.exporter; -import com.refinedmods.refinedstorage2.api.network.impl.node.exporter.AbstractExporterTransferStrategy; +import com.refinedmods.refinedstorage2.api.network.impl.node.exporter.ExporterTransferStrategyImpl; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.platform.api.storage.channel.FuzzyStorageChannel; import java.util.Collection; import java.util.stream.Collectors; -public abstract class AbstractFuzzyExporterTransferStrategy extends AbstractExporterTransferStrategy { - protected AbstractFuzzyExporterTransferStrategy( - final InsertableStorage destination, - final StorageChannelType storageChannelType, - final long transferQuota - ) { - super(destination, storageChannelType, transferQuota); +public class FuzzyExporterTransferStrategy extends ExporterTransferStrategyImpl { + public FuzzyExporterTransferStrategy(final InsertableStorage destination, final long transferQuota) { + super(destination, transferQuota); } @Override - protected Collection expand(final T resource, final StorageChannel storageChannel) { - if (storageChannel instanceof FuzzyStorageChannel fuzzyStorageChannel) { + protected Collection expand(final ResourceKey resource, final StorageChannel storageChannel) { + if (storageChannel instanceof FuzzyStorageChannel fuzzyStorageChannel) { return fuzzyStorageChannel .getFuzzy(resource) .stream() diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/AbstractGridBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/AbstractGridBlockEntity.java index 7755daca2..51277a021 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/AbstractGridBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/AbstractGridBlockEntity.java @@ -9,12 +9,9 @@ import com.refinedmods.refinedstorage2.api.storage.Storage; import com.refinedmods.refinedstorage2.api.storage.TrackedResourceAmount; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.grid.Grid; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.support.AbstractDirectionalBlock; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.ExtendedMenuProvider; import com.refinedmods.refinedstorage2.platform.common.support.network.AbstractRedstoneModeNetworkNodeContainerBlockEntity; @@ -45,20 +42,18 @@ public void writeScreenOpeningData(final ServerPlayer player, final FriendlyByte } @Override - public List> getResources(final StorageChannelType type, - final Class actorType) { + public List getResources(final Class actorType) { return requireNonNull(getNode().getNetwork()) .getComponent(StorageNetworkComponent.class) - .getResources(type, actorType); + .getResources(actorType); } @Override - public GridOperations createOperations(final PlatformStorageChannelType storageChannelType, - final Actor actor) { - final StorageChannel storageChannel = requireNonNull(getNode().getNetwork()) - .getComponent(StorageNetworkComponent.class) - .getStorageChannel(storageChannelType); - return storageChannelType.createGridOperations(storageChannel, actor); + public GridOperations createOperations(final ResourceType resourceType, + final Actor actor) { + final StorageChannel storageChannel = requireNonNull(getNode().getNetwork()) + .getComponent(StorageNetworkComponent.class); + return resourceType.createGridOperations(storageChannel, actor); } @Override @@ -67,10 +62,8 @@ public boolean isGridActive() { } @Override - public Storage getItemStorage() { - return requireNonNull(getNode().getNetwork()) - .getComponent(StorageNetworkComponent.class) - .getStorageChannel(StorageChannelTypes.ITEM); + public Storage getItemStorage() { + return requireNonNull(getNode().getNetwork()).getComponent(StorageNetworkComponent.class); } @Override diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/AbstractGridContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/AbstractGridContainerMenu.java index ccc677826..bf2de122c 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/AbstractGridContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/AbstractGridContainerMenu.java @@ -10,8 +10,9 @@ import com.refinedmods.refinedstorage2.api.grid.view.GridViewBuilder; import com.refinedmods.refinedstorage2.api.grid.view.GridViewBuilderImpl; import com.refinedmods.refinedstorage2.api.grid.watcher.GridWatcher; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.TrackedResourceAmount; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.grid.Grid; @@ -22,8 +23,9 @@ import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridInsertionStrategy; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridScrollingStrategy; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; import com.refinedmods.refinedstorage2.platform.api.support.registry.PlatformRegistry; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.Config; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.grid.strategy.ClientGridExtractionStrategy; @@ -84,7 +86,7 @@ public abstract class AbstractGridContainerMenu extends AbstractBaseContainerMen private Runnable sizeChangedListener; private GridSynchronizer synchronizer; @Nullable - private PlatformStorageChannelType storageChannelTypeFilter; + private ResourceType resourceTypeFilter; private boolean autoSelected; private boolean active; @Nullable @@ -103,14 +105,14 @@ protected AbstractGridContainerMenu( this.active = buf.readBoolean(); final GridViewBuilder viewBuilder = createViewBuilder(); - final int amountOfStorageChannels = buf.readInt(); - for (int i = 0; i < amountOfStorageChannels; ++i) { - final ResourceLocation id = buf.readResourceLocation(); - final PlatformStorageChannelType storageChannelType = PlatformApi.INSTANCE - .getStorageChannelTypeRegistry() - .get(id) + final int resources = buf.readInt(); + for (int i = 0; i < resources; ++i) { + final ResourceLocation resourceTypeId = buf.readResourceLocation(); + final ResourceType resourceType = PlatformApi.INSTANCE + .getResourceTypeRegistry() + .get(resourceTypeId) .orElseThrow(); - readStorageChannelFromBuffer(storageChannelType, buf, viewBuilder); + readResource(resourceType, buf, viewBuilder); } this.view = viewBuilder.build(); this.view.setSortingDirection(Platform.INSTANCE.getConfig().getGrid().getSortingDirection()); @@ -118,7 +120,7 @@ protected AbstractGridContainerMenu( this.view.setFilterAndSort(filterStorageChannel()); this.synchronizer = loadSynchronizer(); - this.storageChannelTypeFilter = loadStorageChannelType(); + this.resourceTypeFilter = loadResourceType(); this.insertionStrategy = new ClientGridInsertionStrategy(); this.extractionStrategy = new ClientGridExtractionStrategy(); this.scrollingStrategy = new ClientGridScrollingStrategy(); @@ -147,27 +149,27 @@ private Predicate filterStorageChannel() { return gridResource -> Platform.INSTANCE .getConfig() .getGrid() - .getStorageChannelType() - .flatMap(storageChannelTypeId -> PlatformApi.INSTANCE - .getStorageChannelTypeRegistry() - .get(storageChannelTypeId) + .getResourceTypeId() + .flatMap(resourceTypeId -> PlatformApi.INSTANCE + .getResourceTypeRegistry() + .get(resourceTypeId) .map(type -> type.isGridResourceBelonging(gridResource)) ).orElse(true); } private static GridViewBuilder createViewBuilder() { return new GridViewBuilderImpl( - new CompositeGridResourceFactory(PlatformApi.INSTANCE.getStorageChannelTypeRegistry()), + new CompositeGridResourceFactory(PlatformApi.INSTANCE.getResourceTypeRegistry()), GridSortingTypes.NAME, GridSortingTypes.QUANTITY ); } - public void onResourceUpdate(final T template, - final long amount, - @Nullable final TrackedResource trackedResource) { - LOGGER.debug("{} got updated with {}", template, amount); - view.onChange(template, amount, trackedResource); + public void onResourceUpdate(final ResourceKey resource, + final long amount, + @Nullable final TrackedResource trackedResource) { + LOGGER.debug("{} got updated with {}", resource, amount); + view.onChange(resource, amount, trackedResource); } public void setSizeChangedListener(@Nullable final Runnable sizeChangedListener) { @@ -266,20 +268,18 @@ public void onActiveChanged(final boolean newActive) { } @Override - public void onChanged( - final StorageChannelType storageChannelType, - final T resource, + public void onChanged( + final ResourceKey resource, final long change, @Nullable final TrackedResource trackedResource ) { - if (!(storageChannelType instanceof PlatformStorageChannelType platformStorageChannelType)) { + if (!(resource instanceof PlatformResourceKey platformResource)) { return; } LOGGER.info("{} received a change of {} for {}", this, change, resource); Platform.INSTANCE.getServerToClientCommunications().sendGridUpdate( (ServerPlayer) playerInventory.player, - platformStorageChannelType, - resource, + platformResource, change, trackedResource ); @@ -341,12 +341,12 @@ private GridSynchronizer loadSynchronizer() { } @Nullable - private PlatformStorageChannelType loadStorageChannelType() { + private ResourceType loadResourceType() { return Platform.INSTANCE .getConfig() .getGrid() - .getStorageChannelType() - .flatMap(id -> PlatformApi.INSTANCE.getStorageChannelTypeRegistry().get(id)) + .getResourceTypeId() + .flatMap(id -> PlatformApi.INSTANCE.getResourceTypeRegistry().get(id)) .orElse(null); } @@ -355,8 +355,8 @@ public GridSynchronizer getSynchronizer() { } @Nullable - public PlatformStorageChannelType getStorageChannelType() { - return storageChannelTypeFilter; + public ResourceType getResourceType() { + return resourceTypeFilter; } public void toggleSynchronizer() { @@ -371,19 +371,18 @@ public void toggleSynchronizer() { this.synchronizer = newSynchronizer; } - public void toggleStorageChannelType() { - final PlatformRegistry> registry = - PlatformApi.INSTANCE.getStorageChannelTypeRegistry(); + public void toggleResourceType() { + final PlatformRegistry registry = PlatformApi.INSTANCE.getResourceTypeRegistry(); final Config.GridEntry config = Platform.INSTANCE.getConfig().getGrid(); - final PlatformStorageChannelType newStorageChannelType = storageChannelTypeFilter == null + final ResourceType newResourceType = resourceTypeFilter == null ? registry.getDefault() - : registry.nextOrNullIfLast(storageChannelTypeFilter); - if (newStorageChannelType == null) { - config.clearStorageChannelType(); + : registry.nextOrNullIfLast(resourceTypeFilter); + if (newResourceType == null) { + config.clearResourceType(); } else { - registry.getId(newStorageChannelType).ifPresent(config::setStorageChannelType); + registry.getId(newResourceType).ifPresent(config::setResourceTypeId); } - this.storageChannelTypeFilter = newStorageChannelType; + this.resourceTypeFilter = newResourceType; this.view.sort(); } @@ -399,31 +398,27 @@ public boolean onInsert(final GridInsertMode insertMode, final boolean tryAltern } @Override - public boolean onExtract(final PlatformStorageChannelType storageChannelType, - final T resource, - final GridExtractMode extractMode, - final boolean cursor) { + public boolean onExtract(final PlatformResourceKey resource, + final GridExtractMode extractMode, + final boolean cursor) { if (grid != null && !grid.isGridActive()) { return false; } if (extractionStrategy == null) { return false; } - return extractionStrategy.onExtract(storageChannelType, resource, extractMode, cursor); + return extractionStrategy.onExtract(resource, extractMode, cursor); } @Override - public boolean onScroll(final PlatformStorageChannelType storageChannelType, - final T resource, - final GridScrollMode scrollMode, - final int slotIndex) { + public boolean onScroll(final PlatformResourceKey resource, final GridScrollMode scrollMode, final int slotIndex) { if (grid != null && !grid.isGridActive()) { return false; } if (scrollingStrategy == null) { return false; } - return scrollingStrategy.onScroll(storageChannelType, resource, scrollMode, slotIndex); + return scrollingStrategy.onScroll(resource, scrollMode, slotIndex); } @Override @@ -446,50 +441,36 @@ protected boolean canTransferSlot(final Slot slot) { return true; } - private static void readStorageChannelFromBuffer(final PlatformStorageChannelType type, - final FriendlyByteBuf buf, - final GridViewBuilder viewBuilder) { - final int size = buf.readInt(); - for (int i = 0; i < size; ++i) { - final T resource = type.fromBuffer(buf); - final long amount = buf.readLong(); - final TrackedResource trackedResource = PacketUtil.readTrackedResource(buf); - viewBuilder.withResource(resource, amount, trackedResource); - } + private static void readResource(final ResourceType type, + final FriendlyByteBuf buf, + final GridViewBuilder viewBuilder) { + final ResourceKey resource = type.fromBuffer(buf); + final long amount = buf.readLong(); + final TrackedResource trackedResource = PacketUtil.readTrackedResource(buf); + viewBuilder.withResource(resource, amount, trackedResource); } public void onClear() { view.clear(); } - public static void writeScreenOpeningData(final PlatformRegistry> - storageChannelTypeRegistry, - final Grid grid, - final FriendlyByteBuf buf) { + public static void writeScreenOpeningData(final Grid grid, final FriendlyByteBuf buf) { buf.writeBoolean(grid.isGridActive()); - final List> types = storageChannelTypeRegistry.getAll(); - buf.writeInt(types.size()); - types.forEach(type -> writeStorageChannel(storageChannelTypeRegistry, type, grid, buf)); - } - - private static void writeStorageChannel( - final PlatformRegistry> storageChannelTypeRegistry, - final PlatformStorageChannelType storageChannelType, - final Grid grid, - final FriendlyByteBuf buf - ) { - final ResourceLocation id = storageChannelTypeRegistry.getId(storageChannelType).orElseThrow(); - buf.writeResourceLocation(id); - final List> resources = grid.getResources(storageChannelType, PlayerActor.class); + final List resources = grid.getResources(PlayerActor.class); buf.writeInt(resources.size()); - resources.forEach(resource -> writeGridResource(storageChannelType, resource, buf)); - } - - private static void writeGridResource(final PlatformStorageChannelType storageChannelType, - final TrackedResourceAmount resource, - final FriendlyByteBuf buf) { - storageChannelType.toBuffer(resource.resourceAmount().getResource(), buf); - buf.writeLong(resource.resourceAmount().getAmount()); - PacketUtil.writeTrackedResource(buf, resource.trackedResource()); + resources.forEach(resource -> writeGridResource(resource, buf)); + } + + private static void writeGridResource(final TrackedResourceAmount trackedResourceAmount, + final FriendlyByteBuf buf) { + final ResourceAmount resourceAmount = trackedResourceAmount.resourceAmount(); + final PlatformResourceKey resource = (PlatformResourceKey) resourceAmount.getResource(); + final ResourceType resourceType = resource.getResourceType(); + final ResourceLocation resourceTypeId = PlatformApi.INSTANCE.getResourceTypeRegistry().getId(resourceType) + .orElseThrow(); + buf.writeResourceLocation(resourceTypeId); + resource.toBuffer(buf); + buf.writeLong(resourceAmount.getAmount()); + PacketUtil.writeTrackedResource(buf, trackedResourceAmount.trackedResource()); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/ClientCraftingGridSource.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/ClientCraftingGridSource.java index 00e270207..79450c3f0 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/ClientCraftingGridSource.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/ClientCraftingGridSource.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.grid; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.Platform; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.List; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridBlockEntity.java index 91fe16574..bd48406f7 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridBlockEntity.java @@ -6,11 +6,10 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.grid.GridNetworkNode; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; import com.refinedmods.refinedstorage2.platform.common.content.ContentNames; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.util.ContainerUtil; import java.util.Optional; @@ -137,10 +136,8 @@ Optional getNetwork() { return Optional.ofNullable(node.getNetwork()); } - Optional> getStorageChannel() { - return getNetwork().map(network -> network - .getComponent(StorageNetworkComponent.class) - .getStorageChannel(StorageChannelTypes.ITEM)); + Optional getStorageChannel() { + return getNetwork().map(network -> network.getComponent(StorageNetworkComponent.class)); } ItemStack insert(final ItemStack stack, final Player player) { @@ -149,7 +146,7 @@ ItemStack insert(final ItemStack stack, final Player player) { private ItemStack doInsert(final ItemStack stack, final Player player, - final StorageChannel storageChannel) { + final StorageChannel storageChannel) { final long inserted = storageChannel.insert( ItemResource.ofItemStack(stack), stack.getCount(), diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridContainerMenu.java index 1c9b31ba5..43ea346da 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridContainerMenu.java @@ -2,13 +2,13 @@ import com.refinedmods.refinedstorage2.api.grid.view.GridResource; import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.content.Menus; import com.refinedmods.refinedstorage2.platform.common.grid.view.ItemGridResource; import com.refinedmods.refinedstorage2.platform.common.support.RedstoneMode; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.ClientProperty; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.PropertyTypes; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.ServerProperty; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.ArrayList; import java.util.HashSet; @@ -116,14 +116,14 @@ public void clear(final boolean toPlayerInventory) { source.clearMatrix(player, toPlayerInventory); } - public ResourceList getAvailableListForRecipeTransfer() { - final ResourceList available = getView().copyBackingList(); + public ResourceList getAvailableListForRecipeTransfer() { + final ResourceList available = getView().copyBackingList(); addContainerToList(source.getCraftingMatrix(), available); addContainerToList(player.getInventory(), available); return available; } - private void addContainerToList(final Container container, final ResourceList available) { + private void addContainerToList(final Container container, final ResourceList available) { for (int i = 0; i < container.getContainerSize(); ++i) { final ItemStack stack = container.getItem(i); if (stack.isEmpty()) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridRefillContext.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridRefillContext.java index 58cf18369..0ac8d7728 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridRefillContext.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridRefillContext.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.grid; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import net.minecraft.world.entity.player.Player; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridRefillContextImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridRefillContextImpl.java index e3461da2a..2f71301fb 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridRefillContextImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridRefillContextImpl.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.grid; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import net.minecraft.world.entity.player.Player; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridResultSlot.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridResultSlot.java index 59495bcf2..70d19a96c 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridResultSlot.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridResultSlot.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.grid; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.Platform; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.List; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridSource.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridSource.java index 9b463fa97..4616d26da 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridSource.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridSource.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.grid; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.List; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridSourceImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridSourceImpl.java index f98f16e78..b6a27e6dc 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridSourceImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/CraftingGridSourceImpl.java @@ -4,8 +4,7 @@ import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; import com.refinedmods.refinedstorage2.api.resource.list.ResourceListImpl; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.Comparator; import java.util.List; @@ -89,7 +88,7 @@ public void transferRecipe(final Player player, final List> r if (!clearMatrix(player, clearToPlayerInventory)) { return; } - final ResourceList available = createCombinedPlayerInventoryAndNetworkList(player); + final ResourceList available = createCombinedPlayerInventoryAndNetworkList(player); final Comparator sorter = sortByHighestAvailableFirst(available); for (int i = 0; i < getCraftingMatrix().getContainerSize(); ++i) { if (i > recipe.size() || recipe.get(i) == null) { @@ -126,21 +125,20 @@ private boolean extractFromPlayerInventory(final Player player, final ItemResour return false; } - private ResourceList createCombinedPlayerInventoryAndNetworkList(final Player player) { - final ResourceList list = new ResourceListImpl<>(); + private ResourceList createCombinedPlayerInventoryAndNetworkList(final Player player) { + final ResourceList list = new ResourceListImpl(); addNetworkItemsIntoList(list); addPlayerInventoryItemsIntoList(player, list); return list; } - private void addNetworkItemsIntoList(final ResourceList list) { + private void addNetworkItemsIntoList(final ResourceList list) { blockEntity.getNetwork().ifPresent(network -> network.getComponent(StorageNetworkComponent.class) - .getStorageChannel(StorageChannelTypes.ITEM) .getAll() .forEach(list::add)); } - private void addPlayerInventoryItemsIntoList(final Player player, final ResourceList list) { + private void addPlayerInventoryItemsIntoList(final Player player, final ResourceList list) { for (int i = 0; i < player.getInventory().getContainerSize(); ++i) { final ItemStack playerInventoryStack = player.getInventory().getItem(i); if (playerInventoryStack.isEmpty()) { @@ -150,11 +148,11 @@ private void addPlayerInventoryItemsIntoList(final Player player, final Resource } } - private Comparator sortByHighestAvailableFirst(final ResourceList available) { + private Comparator sortByHighestAvailableFirst(final ResourceList available) { return Comparator.comparingLong(resource -> getAvailableAmount(available, resource)).reversed(); } - private long getAvailableAmount(final ResourceList available, final ItemResource resource) { + private long getAvailableAmount(final ResourceList available, final ItemResource resource) { return available.get(resource).map(ResourceAmount::getAmount).orElse(0L); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/SnapshotCraftingGridRefillContext.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/SnapshotCraftingGridRefillContext.java index 63a260e41..be6b8ac63 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/SnapshotCraftingGridRefillContext.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/SnapshotCraftingGridRefillContext.java @@ -5,7 +5,7 @@ import com.refinedmods.refinedstorage2.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; @@ -13,8 +13,8 @@ class SnapshotCraftingGridRefillContext implements CraftingGridRefillContext { private final PlayerActor playerActor; private final CraftingGridBlockEntity blockEntity; - private final ResourceList available = new ResourceListImpl<>(); - private final ResourceList used = new ResourceListImpl<>(); + private final ResourceList available = new ResourceListImpl(); + private final ResourceList used = new ResourceListImpl(); SnapshotCraftingGridRefillContext( final Player player, @@ -35,7 +35,7 @@ private void addAvailableItems(final CraftingMatrix craftingMatrix) { } private void addAvailableItem(final CraftingMatrix craftingMatrix, - final StorageChannel storageChannel, + final StorageChannel storageChannel, final int craftingMatrixSlotIndex) { final ItemStack craftingMatrixStack = craftingMatrix.getItem(craftingMatrixSlotIndex); if (craftingMatrixStack.isEmpty()) { @@ -44,7 +44,7 @@ private void addAvailableItem(final CraftingMatrix craftingMatrix, addAvailableItem(storageChannel, craftingMatrixStack); } - private void addAvailableItem(final StorageChannel storageChannel, + private void addAvailableItem(final StorageChannel storageChannel, final ItemStack craftingMatrixStack) { final ItemResource craftingMatrixResource = ItemResource.ofItemStack(craftingMatrixStack); // a single resource can occur multiple times in a recipe, only add it once @@ -70,7 +70,7 @@ public void close() { blockEntity.getStorageChannel().ifPresent(this::extractUsedItems); } - private void extractUsedItems(final StorageChannel storageChannel) { + private void extractUsedItems(final StorageChannel storageChannel) { used.getAll().forEach(u -> storageChannel.extract(u.getResource(), u.getAmount(), Action.EXECUTE, playerActor)); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/WirelessGrid.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/WirelessGrid.java index 0f129178f..4389dadac 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/WirelessGrid.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/WirelessGrid.java @@ -11,13 +11,10 @@ import com.refinedmods.refinedstorage2.api.storage.NoopStorage; import com.refinedmods.refinedstorage2.api.storage.Storage; import com.refinedmods.refinedstorage2.api.storage.TrackedResourceAmount; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.platform.api.grid.Grid; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; import com.refinedmods.refinedstorage2.platform.api.support.network.bounditem.NetworkBoundItemSession; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.Platform; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import java.util.Collections; import java.util.List; @@ -54,9 +51,8 @@ public void removeWatcher(final GridWatcher watcher) { } @Override - public Storage getItemStorage() { - return getStorage().map(storage -> (Storage) storage.getStorageChannel(StorageChannelTypes.ITEM)) - .orElseGet(NoopStorage::new); + public Storage getItemStorage() { + return getStorage().map(Storage.class::cast).orElseGet(NoopStorage::new); } @Override @@ -68,18 +64,16 @@ public boolean isGridActive() { } @Override - public List> getResources(final StorageChannelType type, - final Class actorType) { - return getStorage().map(storage -> storage.getResources(type, actorType)).orElse(Collections.emptyList()); + public List getResources(final Class actorType) { + return getStorage().map(storage -> storage.getResources(actorType)).orElse(Collections.emptyList()); } @Override - public GridOperations createOperations(final PlatformStorageChannelType storageChannelType, - final Actor actor) { + public GridOperations createOperations(final ResourceType resourceType, + final Actor actor) { return getStorage() - .map(storage -> storage.getStorageChannel(storageChannelType)) - .map(storageChannel -> storageChannelType.createGridOperations(storageChannel, actor)) - .map(gridOperations -> (GridOperations) new WirelessGridOperations<>(gridOperations, session, watchers)) + .map(storageChannel -> resourceType.createGridOperations(storageChannel, actor)) + .map(gridOperations -> (GridOperations) new WirelessGridOperations(gridOperations, session, watchers)) .orElseGet(NoopGridOperations::new); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/WirelessGridItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/WirelessGridItem.java index d1a538ee6..7aac3acad 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/WirelessGridItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/WirelessGridItem.java @@ -14,15 +14,12 @@ import net.minecraft.world.item.ItemStack; public class WirelessGridItem extends AbstractNetworkBoundEnergyItem { - private final boolean creative; - - public WirelessGridItem(final boolean creative) { + public WirelessGridItem() { super( new Item.Properties().stacksTo(1), PlatformApi.INSTANCE.getEnergyItemHelper(), PlatformApi.INSTANCE.getNetworkBoundItemHelper() ); - this.creative = creative; } public EnergyStorage createEnergyStorage(final ItemStack stack) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/WirelessGridOperations.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/WirelessGridOperations.java index 96bab64cd..2f2ee0c44 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/WirelessGridOperations.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/WirelessGridOperations.java @@ -4,17 +4,18 @@ import com.refinedmods.refinedstorage2.api.grid.operations.GridInsertMode; import com.refinedmods.refinedstorage2.api.grid.operations.GridOperations; import com.refinedmods.refinedstorage2.api.grid.watcher.GridWatcherManager; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.ExtractableStorage; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; import com.refinedmods.refinedstorage2.platform.api.support.network.bounditem.NetworkBoundItemSession; import com.refinedmods.refinedstorage2.platform.common.Platform; -class WirelessGridOperations implements GridOperations { - private final GridOperations delegate; +class WirelessGridOperations implements GridOperations { + private final GridOperations delegate; private final NetworkBoundItemSession session; private final GridWatcherManager watchers; - WirelessGridOperations(final GridOperations delegate, + WirelessGridOperations(final GridOperations delegate, final NetworkBoundItemSession session, final GridWatcherManager watchers) { this.delegate = delegate; @@ -23,9 +24,9 @@ class WirelessGridOperations implements GridOperations { } @Override - public boolean extract(final T resource, + public boolean extract(final ResourceKey resource, final GridExtractMode extractMode, - final InsertableStorage destination) { + final InsertableStorage destination) { final boolean success = delegate.extract(resource, extractMode, destination); if (success) { drain(Platform.INSTANCE.getConfig().getWirelessGrid().getExtractEnergyUsage()); @@ -34,9 +35,9 @@ public boolean extract(final T resource, } @Override - public boolean insert(final T resource, + public boolean insert(final ResourceKey resource, final GridInsertMode insertMode, - final ExtractableStorage source) { + final ExtractableStorage source) { final boolean success = delegate.insert(resource, insertMode, source); if (success) { drain(Platform.INSTANCE.getConfig().getWirelessGrid().getInsertEnergyUsage()); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/screen/AbstractGridScreen.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/screen/AbstractGridScreen.java index 4ac595f8d..bcee47e1c 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/screen/AbstractGridScreen.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/screen/AbstractGridScreen.java @@ -10,14 +10,14 @@ import com.refinedmods.refinedstorage2.platform.api.grid.GridSynchronizer; import com.refinedmods.refinedstorage2.platform.api.grid.view.PlatformGridResource; import com.refinedmods.refinedstorage2.platform.api.support.registry.PlatformRegistry; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.grid.AbstractGridContainerMenu; import com.refinedmods.refinedstorage2.platform.common.grid.view.ItemGridResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import com.refinedmods.refinedstorage2.platform.common.support.AbstractBaseScreen; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.DisabledSlot; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.PropertyTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.support.tooltip.SmallTextClientTooltipComponent; import com.refinedmods.refinedstorage2.platform.common.support.widget.History; import com.refinedmods.refinedstorage2.platform.common.support.widget.RedstoneModeSideButtonWidget; @@ -120,7 +120,7 @@ protected void init() { addSideButton(new SortingTypeSideButtonWidget(getMenu())); addSideButton(new SizeSideButtonWidget(getMenu())); addSideButton(new AutoSelectedSideButtonWidget(getMenu())); - addSideButton(new StorageChannelTypeSideButtonWidget(getMenu())); + addSideButton(new ResourceTypeSideButtonWidget(getMenu())); final PlatformRegistry synchronizers = PlatformApi.INSTANCE.getGridSynchronizerRegistry(); if (!synchronizers.isEmpty()) { @@ -343,9 +343,9 @@ protected void renderTooltip(final GuiGraphics graphics, final int x, final int } private void renderOverStorageAreaTooltip(final GuiGraphics graphics, final int x, final int y) { - final GridResource resource = getCurrentGridResource(); + final PlatformGridResource resource = getCurrentGridResource(); if (resource != null) { - renderHoveredResourceTooltip(graphics, x, y, resource); + renderHoveredResourceTooltip(graphics, x, y, menu.getView(), resource); return; } final ItemStack carried = getMenu().getCarried(); @@ -356,16 +356,6 @@ private void renderOverStorageAreaTooltip(final GuiGraphics graphics, final int Platform.INSTANCE.renderTooltip(graphics, hints, x, y); } - private void renderHoveredResourceTooltip(final GuiGraphics graphics, - final int mouseX, - final int mouseY, - final GridResource resource) { - if (!(resource instanceof PlatformGridResource platformResource)) { - return; - } - renderHoveredResourceTooltip(graphics, mouseX, mouseY, getMenu().getView(), platformResource); - } - private void renderHoveredResourceTooltip(final GuiGraphics graphics, final int mouseX, final int mouseY, @@ -428,9 +418,8 @@ private boolean isModifiedJustNow(final LastModified lastModified) { && lastModified.amount() <= MODIFIED_JUST_NOW_MAX_SECONDS; } - @Nullable - public GridResource getCurrentGridResource() { + public PlatformGridResource getCurrentGridResource() { if (currentGridSlotIndex < 0) { return null; } @@ -438,7 +427,13 @@ public GridResource getCurrentGridResource() { if (currentGridSlotIndex >= viewList.size()) { return null; } - return viewList.get(currentGridSlotIndex); + return (PlatformGridResource) viewList.get(currentGridSlotIndex); + } + + @Nullable + public PlatformResourceKey getCurrentResource() { + final PlatformGridResource resource = getCurrentGridResource(); + return resource != null ? resource.getUnderlyingResource() : null; } @Override @@ -459,7 +454,7 @@ public boolean mouseClicked(final double mouseX, final double mouseY, final int } final ItemStack carriedStack = getMenu().getCarried(); - final GridResource resource = getCurrentGridResource(); + final PlatformGridResource resource = getCurrentGridResource(); if (resource != null && carriedStack.isEmpty()) { mouseClickedInGrid(clickedButton, resource); @@ -483,14 +478,12 @@ private void mouseClickedInGrid(final int clickedButton) { getMenu().onInsert(mode, tryAlternatives); } - protected void mouseClickedInGrid(final int clickedButton, final GridResource resource) { - if (resource instanceof PlatformGridResource platformGridResource) { - platformGridResource.onExtract( - getExtractMode(clickedButton), - shouldExtractToCursor(), - getMenu() - ); - } + protected void mouseClickedInGrid(final int clickedButton, final PlatformGridResource resource) { + resource.onExtract( + getExtractMode(clickedButton), + shouldExtractToCursor(), + getMenu() + ); } private static GridExtractMode getExtractMode(final int clickedButton) { @@ -522,7 +515,7 @@ public boolean mouseScrolled(final double x, final double y, final double z, fin final boolean up = delta > 0; if (isOverStorageArea((int) x, (int) y)) { - final GridResource resource = getCurrentGridResource(); + final PlatformGridResource resource = getCurrentGridResource(); if (resource != null) { mouseScrolledInGrid(up, resource); } @@ -546,24 +539,16 @@ private void mouseScrolledInInventory(final boolean up, final ItemStack stack, f if (scrollMode == null) { return; } - getMenu().onScroll( - StorageChannelTypes.ITEM, - ItemResource.ofItemStack(stack), - scrollMode, - slotIndex - ); + getMenu().onScroll(ItemResource.ofItemStack(stack), scrollMode, slotIndex); } - private void mouseScrolledInGrid(final boolean up, final GridResource resource) { + private void mouseScrolledInGrid(final boolean up, final PlatformGridResource resource) { getMenu().getView().setPreventSorting(true); final GridScrollMode scrollMode = getScrollModeWhenScrollingOnGridArea(up); if (scrollMode == null) { return; } - if (!(resource instanceof PlatformGridResource platformGridResource)) { - return; - } - platformGridResource.onScroll(scrollMode, getMenu()); + resource.onScroll(scrollMode, getMenu()); } @Nullable diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/screen/StorageChannelTypeSideButtonWidget.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/screen/ResourceTypeSideButtonWidget.java similarity index 56% rename from refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/screen/StorageChannelTypeSideButtonWidget.java rename to refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/screen/ResourceTypeSideButtonWidget.java index 9b07d055f..bfa23ab2a 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/screen/StorageChannelTypeSideButtonWidget.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/screen/ResourceTypeSideButtonWidget.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.grid.screen; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.grid.AbstractGridContainerMenu; import com.refinedmods.refinedstorage2.platform.common.support.TextureIds; import com.refinedmods.refinedstorage2.platform.common.support.widget.AbstractSideButtonWidget; @@ -11,29 +11,29 @@ import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; -class StorageChannelTypeSideButtonWidget extends AbstractSideButtonWidget { - private static final MutableComponent TITLE = createTranslation("gui", "grid.storage_channel_type"); - private static final MutableComponent SUBTEXT_ALL = createTranslation("gui", "grid.storage_channel_type.all"); - private static final Component HELP = createTranslation("gui", "grid.storage_channel_type.help"); +class ResourceTypeSideButtonWidget extends AbstractSideButtonWidget { + private static final MutableComponent TITLE = createTranslation("gui", "grid.resource_type"); + private static final MutableComponent SUBTEXT_ALL = createTranslation("gui", "grid.resource_type.all"); + private static final Component HELP = createTranslation("gui", "grid.resource_type.help"); private final AbstractGridContainerMenu menu; - StorageChannelTypeSideButtonWidget(final AbstractGridContainerMenu menu) { + ResourceTypeSideButtonWidget(final AbstractGridContainerMenu menu) { super(createPressAction(menu)); this.menu = menu; } private static OnPress createPressAction(final AbstractGridContainerMenu menu) { - return btn -> menu.toggleStorageChannelType(); + return btn -> menu.toggleResourceType(); } @Override protected ResourceLocation getTextureIdentifier() { - final PlatformStorageChannelType storageChannelType = menu.getStorageChannelType(); - if (storageChannelType == null) { + final ResourceType resourceType = menu.getResourceType(); + if (resourceType == null) { return TextureIds.ICONS; } - return storageChannelType.getTextureIdentifier(); + return resourceType.getTextureIdentifier(); } @Override @@ -43,11 +43,11 @@ protected MutableComponent getTitle() { @Override protected MutableComponent getSubText() { - final PlatformStorageChannelType storageChannelType = menu.getStorageChannelType(); - if (storageChannelType == null) { + final ResourceType resourceType = menu.getResourceType(); + if (resourceType == null) { return SUBTEXT_ALL; } - return storageChannelType.getTitle(); + return resourceType.getTitle(); } @Override @@ -57,19 +57,19 @@ protected Component getHelpText() { @Override protected int getXTexture() { - final PlatformStorageChannelType storageChannelType = menu.getStorageChannelType(); - if (storageChannelType == null) { + final ResourceType resourceType = menu.getResourceType(); + if (resourceType == null) { return 32; } - return storageChannelType.getXTexture(); + return resourceType.getXTexture(); } @Override protected int getYTexture() { - final PlatformStorageChannelType storageChannelType = menu.getStorageChannelType(); - if (storageChannelType == null) { + final ResourceType resourceType = menu.getResourceType(); + if (resourceType == null) { return 128; } - return storageChannelType.getYTexture(); + return resourceType.getYTexture(); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/screen/hint/FluidGridInsertionHint.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/screen/hint/FluidGridInsertionHint.java index df3771a15..b2868a52d 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/screen/hint/FluidGridInsertionHint.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/screen/hint/FluidGridInsertionHint.java @@ -23,11 +23,11 @@ private MouseWithIconClientTooltipComponent createComponent(final Platform.Conta graphics.pose(), x, y, - result.fluid().getResource() + result.fluid() ), - result.fluid().getAmount() == Platform.INSTANCE.getBucketAmount() + result.amount() == Platform.INSTANCE.getBucketAmount() ? null - : FluidResourceRendering.format(result.fluid().getAmount()) + : FluidResourceRendering.format(result.amount()) ); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/strategy/ClientGridExtractionStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/strategy/ClientGridExtractionStrategy.java index 4c0dd60f7..a4f8d6e6f 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/strategy/ClientGridExtractionStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/strategy/ClientGridExtractionStrategy.java @@ -2,21 +2,15 @@ import com.refinedmods.refinedstorage2.api.grid.operations.GridExtractMode; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridExtractionStrategy; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.Platform; public class ClientGridExtractionStrategy implements GridExtractionStrategy { @Override - public boolean onExtract(final PlatformStorageChannelType storageChannelType, - final T resource, - final GridExtractMode extractMode, - final boolean cursor) { - Platform.INSTANCE.getClientToServerCommunications().sendGridExtract( - storageChannelType, - resource, - extractMode, - cursor - ); + public boolean onExtract(final PlatformResourceKey resource, + final GridExtractMode extractMode, + final boolean cursor) { + Platform.INSTANCE.getClientToServerCommunications().sendGridExtract(resource, extractMode, cursor); return true; } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/strategy/ClientGridScrollingStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/strategy/ClientGridScrollingStrategy.java index 4596a90c0..c3f1dbdda 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/strategy/ClientGridScrollingStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/strategy/ClientGridScrollingStrategy.java @@ -2,21 +2,13 @@ import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollMode; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridScrollingStrategy; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.Platform; public class ClientGridScrollingStrategy implements GridScrollingStrategy { @Override - public boolean onScroll(final PlatformStorageChannelType storageChannelType, - final T resource, - final GridScrollMode scrollMode, - final int slotIndex) { - Platform.INSTANCE.getClientToServerCommunications().sendGridScroll( - storageChannelType, - resource, - scrollMode, - slotIndex - ); + public boolean onScroll(final PlatformResourceKey resource, final GridScrollMode scrollMode, final int slotIndex) { + Platform.INSTANCE.getClientToServerCommunications().sendGridScroll(resource, scrollMode, slotIndex); return true; } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/strategy/CompositeGridExtractionStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/strategy/CompositeGridExtractionStrategy.java index fe3f068a7..4a3a1ba12 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/strategy/CompositeGridExtractionStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/strategy/CompositeGridExtractionStrategy.java @@ -2,7 +2,7 @@ import com.refinedmods.refinedstorage2.api.grid.operations.GridExtractMode; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridExtractionStrategy; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import java.util.Collections; import java.util.List; @@ -15,12 +15,11 @@ public CompositeGridExtractionStrategy(final List strate } @Override - public boolean onExtract(final PlatformStorageChannelType storageChannelType, - final T resource, - final GridExtractMode extractMode, - final boolean cursor) { + public boolean onExtract(final PlatformResourceKey resource, + final GridExtractMode extractMode, + final boolean cursor) { for (final GridExtractionStrategy strategy : strategies) { - if (strategy.onExtract(storageChannelType, resource, extractMode, cursor)) { + if (strategy.onExtract(resource, extractMode, cursor)) { return true; } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/strategy/CompositeGridScrollingStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/strategy/CompositeGridScrollingStrategy.java index 51ba457d8..73bdfb5e4 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/strategy/CompositeGridScrollingStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/strategy/CompositeGridScrollingStrategy.java @@ -2,7 +2,7 @@ import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollMode; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridScrollingStrategy; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import java.util.Collections; import java.util.List; @@ -15,12 +15,9 @@ public CompositeGridScrollingStrategy(final List strategi } @Override - public boolean onScroll(final PlatformStorageChannelType storageChannelType, - final T resource, - final GridScrollMode scrollMode, - final int slotIndex) { + public boolean onScroll(final PlatformResourceKey resource, final GridScrollMode scrollMode, final int slotIndex) { for (final GridScrollingStrategy strategy : strategies) { - if (strategy.onScroll(storageChannelType, resource, scrollMode, slotIndex)) { + if (strategy.onScroll(resource, scrollMode, slotIndex)) { return true; } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/AbstractFluidGridResourceFactory.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/AbstractFluidGridResourceFactory.java index cfc6399ba..d2fde502b 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/AbstractFluidGridResourceFactory.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/AbstractFluidGridResourceFactory.java @@ -3,7 +3,7 @@ import com.refinedmods.refinedstorage2.api.grid.view.GridResource; import com.refinedmods.refinedstorage2.api.grid.view.GridResourceFactory; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import java.util.Optional; import java.util.Set; @@ -15,8 +15,7 @@ public abstract class AbstractFluidGridResourceFactory implements GridResourceFactory { @Override - @SuppressWarnings("unchecked") - public Optional apply(final ResourceAmount resourceAmount) { + public Optional apply(final ResourceAmount resourceAmount) { if (!(resourceAmount.getResource() instanceof FluidResource fluidResource)) { return Optional.empty(); } @@ -26,7 +25,7 @@ public Optional apply(final ResourceAmount resourceAmount) { final Set tags = getTags(fluidResource.fluid()); final String tooltip = getTooltip(fluidResource); return Optional.of(new FluidGridResource( - (ResourceAmount) resourceAmount, + resourceAmount, name, modId, modName, diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/AbstractItemGridResourceFactory.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/AbstractItemGridResourceFactory.java index 8adcd47c3..19fb2e107 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/AbstractItemGridResourceFactory.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/AbstractItemGridResourceFactory.java @@ -3,7 +3,7 @@ import com.refinedmods.refinedstorage2.api.grid.view.GridResource; import com.refinedmods.refinedstorage2.api.grid.view.GridResourceFactory; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.Optional; import java.util.Set; @@ -18,8 +18,7 @@ public abstract class AbstractItemGridResourceFactory implements GridResourceFactory { @Override - @SuppressWarnings("unchecked") - public Optional apply(final ResourceAmount resourceAmount) { + public Optional apply(final ResourceAmount resourceAmount) { if (!(resourceAmount.getResource() instanceof ItemResource itemResource)) { return Optional.empty(); } @@ -31,7 +30,7 @@ public Optional apply(final ResourceAmount resourceAmount) { final Set tags = getTags(item); final String tooltip = getTooltip(itemStack); return Optional.of(new ItemGridResource( - (ResourceAmount) resourceAmount, + resourceAmount, itemStack, name, modId, diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/CompositeGridResourceFactory.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/CompositeGridResourceFactory.java index 90526370b..566afc85a 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/CompositeGridResourceFactory.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/CompositeGridResourceFactory.java @@ -3,25 +3,27 @@ import com.refinedmods.refinedstorage2.api.grid.view.GridResource; import com.refinedmods.refinedstorage2.api.grid.view.GridResourceFactory; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; import com.refinedmods.refinedstorage2.platform.api.support.registry.PlatformRegistry; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import java.util.Optional; public class CompositeGridResourceFactory implements GridResourceFactory { - private final PlatformRegistry> storageChannelTypeRegistry; + private final PlatformRegistry resourceTypeRegistry; - public CompositeGridResourceFactory( - final PlatformRegistry> storageChannelTypeRegistry - ) { - this.storageChannelTypeRegistry = storageChannelTypeRegistry; + public CompositeGridResourceFactory(final PlatformRegistry resourceTypeRegistry) { + this.resourceTypeRegistry = resourceTypeRegistry; } @Override - public Optional apply(final ResourceAmount resourceAmount) { - return storageChannelTypeRegistry.getAll() + public Optional apply(final ResourceAmount resourceAmount) { + if (!(resourceAmount.getResource() instanceof PlatformResourceKey platformResource)) { + return Optional.empty(); + } + return resourceTypeRegistry.getAll() .stream() - .flatMap(type -> type.toGridResource(resourceAmount).stream()) + .flatMap(type -> type.toGridResource(platformResource, resourceAmount.getAmount()).stream()) .findFirst(); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/FluidGridResource.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/FluidGridResource.java index 0e1986d59..a50d2e9b3 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/FluidGridResource.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/FluidGridResource.java @@ -7,9 +7,9 @@ import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridExtractionStrategy; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridScrollingStrategy; import com.refinedmods.refinedstorage2.platform.api.grid.view.AbstractPlatformGridResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.Platform; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResourceRendering; import com.refinedmods.refinedstorage2.platform.common.support.tooltip.MouseWithIconClientTooltipComponent; @@ -17,6 +17,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; +import javax.annotation.Nullable; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; @@ -24,11 +25,11 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.inventory.tooltip.TooltipComponent; -public class FluidGridResource extends AbstractPlatformGridResource { +public class FluidGridResource extends AbstractPlatformGridResource { private final FluidResource fluidResource; private final int id; - public FluidGridResource(final ResourceAmount resourceAmount, + public FluidGridResource(final ResourceAmount resourceAmount, final String name, final String modId, final String modName, @@ -40,8 +41,8 @@ public FluidGridResource(final ResourceAmount resourceAmount, GridResourceAttributeKeys.TAGS, tags, GridResourceAttributeKeys.TOOLTIP, Set.of(tooltip) )); - this.id = BuiltInRegistries.FLUID.getId(resourceAmount.getResource().fluid()); - this.fluidResource = resourceAmount.getResource(); + this.fluidResource = (FluidResource) resourceAmount.getResource(); + this.id = BuiltInRegistries.FLUID.getId(fluidResource.fluid()); } @Override @@ -60,16 +61,17 @@ public List getExtractionHints() { ).stream().toList(); } + @Nullable + @Override + public PlatformResourceKey getUnderlyingResource() { + return fluidResource; + } + @Override public void onExtract(final GridExtractMode extractMode, final boolean cursor, final GridExtractionStrategy extractionStrategy) { - extractionStrategy.onExtract( - StorageChannelTypes.FLUID, - fluidResource, - extractMode, - cursor - ); + extractionStrategy.onExtract(fluidResource, extractMode, cursor); } @Override diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/ItemGridResource.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/ItemGridResource.java index df3aaafce..4d0108900 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/ItemGridResource.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/grid/view/ItemGridResource.java @@ -8,14 +8,15 @@ import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridScrollingStrategy; import com.refinedmods.refinedstorage2.platform.api.grid.view.AbstractPlatformGridResource; import com.refinedmods.refinedstorage2.platform.api.support.AmountFormatting; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.support.tooltip.MouseWithIconClientTooltipComponent; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import javax.annotation.Nullable; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; @@ -27,11 +28,12 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -public class ItemGridResource extends AbstractPlatformGridResource { +public class ItemGridResource extends AbstractPlatformGridResource { private final int id; private final ItemStack itemStack; + private final ItemResource itemResource; - public ItemGridResource(final ResourceAmount resourceAmount, + public ItemGridResource(final ResourceAmount resourceAmount, final ItemStack itemStack, final String name, final String modId, @@ -44,7 +46,8 @@ public ItemGridResource(final ResourceAmount resourceAmount, GridResourceAttributeKeys.TAGS, tags, GridResourceAttributeKeys.TOOLTIP, Set.of(tooltip) )); - this.id = Item.getId(resourceAmount.getResource().item()); + this.itemResource = (ItemResource) resourceAmount.getResource(); + this.id = Item.getId(itemResource.item()); this.itemStack = itemStack; } @@ -52,8 +55,10 @@ public ItemStack getItemStack() { return itemStack; } - public ItemStack copyItemStack() { - return itemStack.copyWithCount(1); + @Nullable + @Override + public PlatformResourceKey getUnderlyingResource() { + return itemResource; } @Override @@ -83,22 +88,12 @@ public List getExtractionHints() { public void onExtract(final GridExtractMode extractMode, final boolean cursor, final GridExtractionStrategy extractionStrategy) { - extractionStrategy.onExtract( - StorageChannelTypes.ITEM, - resourceAmount.getResource(), - extractMode, - cursor - ); + extractionStrategy.onExtract(itemResource, extractMode, cursor); } @Override public void onScroll(final GridScrollMode scrollMode, final GridScrollingStrategy scrollingStrategy) { - scrollingStrategy.onScroll( - StorageChannelTypes.ITEM, - resourceAmount.getResource(), - scrollMode, - -1 - ); + scrollingStrategy.onScroll(itemResource, scrollMode, -1); } @Override diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/iface/ExportedResourcesContainer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/iface/ExportedResourcesContainer.java index 98606646e..256291e54 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/iface/ExportedResourcesContainer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/iface/ExportedResourcesContainer.java @@ -2,13 +2,11 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.iface.InterfaceExportState; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.storage.channel.FuzzyStorageChannel; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; import com.refinedmods.refinedstorage2.platform.api.support.resource.FuzzyModeNormalizer; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceContainerType; import com.refinedmods.refinedstorage2.platform.common.support.FilterWithFuzzyMode; import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceContainerImpl; @@ -38,11 +36,12 @@ public int getSlots() { } @Override - public Collection expandExportCandidates(final StorageChannel storageChannel, final T resource) { + public Collection expandExportCandidates(final StorageChannel storageChannel, + final ResourceKey resource) { if (!filter.isFuzzyMode()) { return Collections.singletonList(resource); } - if (!(storageChannel instanceof FuzzyStorageChannel fuzzyStorageChannel)) { + if (!(storageChannel instanceof FuzzyStorageChannel fuzzyStorageChannel)) { return Collections.singletonList(resource); } return fuzzyStorageChannel @@ -53,50 +52,37 @@ public Collection expandExportCandidates(final StorageChannel storageC } @Override - public boolean isExportedResourceValid(final ResourceTemplate want, final ResourceTemplate got) { + public boolean isExportedResourceValid(final ResourceKey want, final ResourceKey got) { if (!filter.isFuzzyMode()) { return got.equals(want); } - final B normalizedGot = normalize(got.resource()); - final A normalizedWant = normalize(want.resource()); + final ResourceKey normalizedGot = normalize(got); + final ResourceKey normalizedWant = normalize(want); return normalizedGot.equals(normalizedWant); } - @SuppressWarnings("unchecked") - private T normalize(final T value) { - if (value instanceof FuzzyModeNormalizer normalizer) { - return (T) normalizer.normalize(); + private ResourceKey normalize(final ResourceKey resource) { + if (resource instanceof FuzzyModeNormalizer normalizer) { + return normalizer.normalize(); } - return value; + return resource; } @Nullable @Override - public ResourceTemplate getRequestedResource(final int slotIndex) { - final ResourceAmountTemplate resourceAmount = filter.getFilterContainer().get(slotIndex); - if (resourceAmount == null) { - return null; - } - return resourceAmount.getResourceTemplate(); + public ResourceKey getRequestedResource(final int slotIndex) { + return filter.getFilterContainer().getResource(slotIndex); } @Override public long getRequestedAmount(final int slotIndex) { - final ResourceAmountTemplate resourceAmount = filter.getFilterContainer().get(slotIndex); - if (resourceAmount == null) { - return 0; - } - return resourceAmount.getAmount(); + return filter.getFilterContainer().getAmount(slotIndex); } @Nullable @Override - public ResourceTemplate getExportedResource(final int slotIndex) { - final ResourceAmountTemplate resourceAmount = get(slotIndex); - if (resourceAmount == null) { - return null; - } - return resourceAmount.getResourceTemplate(); + public ResourceKey getExportedResource(final int slotIndex) { + return getResource(slotIndex); } @Override @@ -105,12 +91,8 @@ public long getExportedAmount(final int slotIndex) { } @Override - public void setExportSlot(final int slotIndex, final ResourceTemplate resource, final long amount) { - set(slotIndex, new ResourceAmountTemplate<>( - resource.resource(), - amount, - (PlatformStorageChannelType) resource.storageChannelType() - )); + public void setExportSlot(final int slotIndex, final ResourceKey resource, final long amount) { + set(slotIndex, new ResourceAmount(resource, amount)); } @Override diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/iface/InterfaceBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/iface/InterfaceBlockEntity.java index e171acba6..87ec873b6 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/iface/InterfaceBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/iface/InterfaceBlockEntity.java @@ -3,10 +3,9 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.iface.InterfaceNetworkNode; import com.refinedmods.refinedstorage2.api.network.impl.node.iface.externalstorage.InterfaceExternalStorageProvider; import com.refinedmods.refinedstorage2.api.network.impl.node.iface.externalstorage.InterfaceExternalStorageProviderImpl; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceContainer; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceContainerType; import com.refinedmods.refinedstorage2.platform.common.Platform; @@ -18,8 +17,6 @@ import com.refinedmods.refinedstorage2.platform.common.support.network.AbstractRedstoneModeNetworkNodeContainerBlockEntity; import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceContainerImpl; -import java.util.HashMap; -import java.util.Map; import javax.annotation.Nullable; import net.minecraft.core.BlockPos; @@ -44,8 +41,7 @@ public class InterfaceBlockEntity private final FilterWithFuzzyMode filter; private final ExportedResourcesContainer exportedResources; private final Container exportedResourcesAsContainer; - private final Map, InterfaceExternalStorageProvider> externalStorageProviders = - new HashMap<>(); + private final InterfaceExternalStorageProvider externalStorageProvider; public InterfaceBlockEntity(final BlockPos pos, final BlockState state) { super( @@ -60,25 +56,7 @@ public InterfaceBlockEntity(final BlockPos pos, final BlockState state) { this.exportedResources.setListener(this::setChanged); getNode().setExportState(exportedResources); this.exportedResourcesAsContainer = exportedResources.toItemContainer(); - addExternalStorageProviders(); - } - - private void addExternalStorageProviders() { - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().getAll().forEach( - storageChannelType -> externalStorageProviders.put( - storageChannelType, - createExternalStorageProvider(storageChannelType) - ) - ); - } - - private InterfaceExternalStorageProviderImpl createExternalStorageProvider( - final PlatformStorageChannelType storageChannelType - ) { - return new InterfaceExternalStorageProviderImpl<>( - getNode(), - storageChannelType - ); + this.externalStorageProvider = new InterfaceExternalStorageProviderImpl(getNode()); } static ResourceContainer createFilterContainer() { @@ -95,9 +73,9 @@ static ExportedResourcesContainer createExportedResourcesContainer(final FilterW return new ExportedResourcesContainer(EXPORT_SLOTS, filter); } - static long getTransferQuota(final ResourceTemplate resourceTemplate) { - if (resourceTemplate.storageChannelType() instanceof PlatformStorageChannelType storageChannelType) { - return storageChannelType.getInterfaceExportLimit(resourceTemplate.resource()); + static long getTransferQuota(final ResourceKey resource) { + if (resource instanceof PlatformResourceKey platformResource) { + return platformResource.getInterfaceExportLimit(); } return 0; } @@ -177,8 +155,7 @@ public NonNullList getDrops() { return drops; } - @SuppressWarnings("unchecked") - InterfaceExternalStorageProvider getExternalStorageProvider(final StorageChannelType storageChannelType) { - return (InterfaceExternalStorageProvider) externalStorageProviders.get(storageChannelType); + InterfaceExternalStorageProvider getExternalStorageProvider() { + return externalStorageProvider; } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/iface/InterfacePlatformExternalStorageProviderFactory.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/iface/InterfacePlatformExternalStorageProviderFactory.java index 0cc89388b..16969e1a6 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/iface/InterfacePlatformExternalStorageProviderFactory.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/iface/InterfacePlatformExternalStorageProviderFactory.java @@ -1,6 +1,5 @@ package com.refinedmods.refinedstorage2.platform.common.iface; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.api.storage.external.ExternalStorageProvider; import com.refinedmods.refinedstorage2.platform.api.storage.externalstorage.PlatformExternalStorageProviderFactory; @@ -12,14 +11,13 @@ public class InterfacePlatformExternalStorageProviderFactory implements PlatformExternalStorageProviderFactory { @Override - public Optional> create(final ServerLevel level, - final BlockPos pos, - final Direction direction, - final StorageChannelType storageChannelType) { + public Optional create(final ServerLevel level, + final BlockPos pos, + final Direction direction) { if (!(level.getBlockEntity(pos) instanceof InterfaceBlockEntity)) { return Optional.empty(); } - return Optional.of(new InterfaceProxyExternalStorageProvider<>(level, pos, storageChannelType)); + return Optional.of(new InterfaceProxyExternalStorageProvider(level, pos)); } @Override diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/iface/InterfaceProxyExternalStorageProvider.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/iface/InterfaceProxyExternalStorageProvider.java index 0459cdd26..329681e7c 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/iface/InterfaceProxyExternalStorageProvider.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/iface/InterfaceProxyExternalStorageProvider.java @@ -4,8 +4,8 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.iface.InterfaceNetworkNode; import com.refinedmods.refinedstorage2.api.network.impl.node.iface.externalstorage.InterfaceExternalStorageProvider; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.platform.api.support.network.AbstractNetworkNodeContainerBlockEntity; import java.util.Collections; @@ -16,17 +16,13 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; -class InterfaceProxyExternalStorageProvider implements InterfaceExternalStorageProvider { +class InterfaceProxyExternalStorageProvider implements InterfaceExternalStorageProvider { private final Level level; private final BlockPos pos; - private final StorageChannelType storageChannelType; - InterfaceProxyExternalStorageProvider(final Level level, - final BlockPos pos, - final StorageChannelType storageChannelType) { + InterfaceProxyExternalStorageProvider(final Level level, final BlockPos pos) { this.level = level; this.pos = pos; - this.storageChannelType = storageChannelType; } private Optional tryGetInterface() { @@ -36,22 +32,22 @@ private Optional tryGetInterface() { return Optional.empty(); } - private Optional> tryGetProvider() { - return tryGetInterface().map(iface -> iface.getExternalStorageProvider(storageChannelType)); + private Optional tryGetProvider() { + return tryGetInterface().map(InterfaceBlockEntity::getExternalStorageProvider); } @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return tryGetProvider().map(provider -> provider.extract(resource, amount, action, actor)).orElse(0L); } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return tryGetProvider().map(provider -> provider.insert(resource, amount, action, actor)).orElse(0L); } @Override - public Iterator> iterator() { + public Iterator iterator() { return tryGetProvider().map(InterfaceExternalStorageProvider::iterator).orElse(Collections.emptyIterator()); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/importer/ImporterBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/importer/ImporterBlockEntity.java index 3a1a6be11..0662ab826 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/importer/ImporterBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/importer/ImporterBlockEntity.java @@ -1,9 +1,10 @@ package com.refinedmods.refinedstorage2.platform.common.importer; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; import com.refinedmods.refinedstorage2.api.network.impl.node.importer.CompositeImporterTransferStrategy; import com.refinedmods.refinedstorage2.api.network.impl.node.importer.ImporterNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.importer.ImporterTransferStrategy; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; import com.refinedmods.refinedstorage2.platform.api.importer.ImporterTransferStrategyFactory; @@ -54,10 +55,10 @@ public ImporterBlockEntity(final BlockPos pos, final BlockState state) { new ImporterNetworkNode(0), UpgradeDestinations.IMPORTER ); - this.filter = FilterWithFuzzyMode.createAndListenForUniqueTemplates( + this.filter = FilterWithFuzzyMode.createAndListenForUniqueFilters( ResourceContainerImpl.createForFilter(), this::setChanged, - templates -> getNode().setFilterTemplates(templates) + filters -> getNode().setFilters(filters) ); getNode().setNormalizer(filter.createNormalizer()); } @@ -137,9 +138,9 @@ public AbstractContainerMenu createMenu(final int syncId, final Inventory invent } @Override - public long overrideAmount(final T resource, - final long amount, - final LongSupplier currentAmount) { + public long overrideAmount(final ResourceKey resource, + final long amount, + final LongSupplier currentAmount) { if (!upgradeContainer.has(Items.INSTANCE.getRegulatorUpgrade())) { return amount; } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/importer/ImporterContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/importer/ImporterContainerMenu.java index dbe7f9abc..fefe5d2fc 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/importer/ImporterContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/importer/ImporterContainerMenu.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.importer; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceContainer; import com.refinedmods.refinedstorage2.platform.common.content.Menus; import com.refinedmods.refinedstorage2.platform.common.support.RedstoneMode; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/CompositeIngredientConverter.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/CompositeIngredientConverter.java index 5e266022a..fec6421ed 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/CompositeIngredientConverter.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/CompositeIngredientConverter.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.recipemod; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import java.util.Collection; import java.util.HashSet; @@ -11,14 +11,14 @@ public class CompositeIngredientConverter implements IngredientConverter { private final Collection converters = new HashSet<>(); @Override - public Optional> convertToResource(final Object ingredient) { + public Optional convertToResource(final Object ingredient) { return converters.stream() .flatMap(converter -> converter.convertToResource(ingredient).stream()) .findFirst(); } @Override - public Optional convertToIngredient(final Object resource) { + public Optional convertToIngredient(final PlatformResourceKey resource) { return converters.stream() .flatMap(converter -> converter.convertToIngredient(resource).stream()) .findFirst(); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/CraftingGridRecipeTransferHandler.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/CraftingGridRecipeTransferHandler.java index be8f2ae6a..e377b7a27 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/CraftingGridRecipeTransferHandler.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/CraftingGridRecipeTransferHandler.java @@ -1,9 +1,9 @@ package com.refinedmods.refinedstorage2.platform.common.recipemod.jei; import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.content.Menus; import com.refinedmods.refinedstorage2.platform.common.grid.CraftingGridContainerMenu; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.List; import java.util.Optional; @@ -52,7 +52,7 @@ public IRecipeTransferError transferRecipe(final CraftingGridContainerMenu conta doTransfer(recipeSlots, containerMenu); return null; } - final ResourceList available = containerMenu.getAvailableListForRecipeTransfer(); + final ResourceList available = containerMenu.getAvailableListForRecipeTransfer(); final List missingSlots = findMissingSlots(recipeSlots, available); return missingSlots.isEmpty() ? null : new MissingItemRecipeTransferError(missingSlots); } @@ -62,8 +62,7 @@ private void doTransfer(final IRecipeSlotsView recipeSlots, final CraftingGridCo containerMenu.transferRecipe(inputs); } - private List findMissingSlots(final IRecipeSlotsView recipeSlots, - final ResourceList available) { + private List findMissingSlots(final IRecipeSlotsView recipeSlots, final ResourceList available) { return recipeSlots.getSlotViews(RecipeIngredientRole.INPUT).stream().filter(slotView -> { if (slotView.isEmpty()) { return false; @@ -72,7 +71,7 @@ private List findMissingSlots(final IRecipeSlotsView recipeSlot }).toList(); } - private boolean isAvailable(final ResourceList available, final IRecipeSlotView slotView) { + private boolean isAvailable(final ResourceList available, final IRecipeSlotView slotView) { final List possibilities = slotView.getItemStacks().toList(); for (final ItemStack possibility : possibilities) { final ItemResource possibilityResource = ItemResource.ofItemStack(possibility); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/GhostIngredientHandler.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/GhostIngredientHandler.java index 3fc979898..df62f1a8e 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/GhostIngredientHandler.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/GhostIngredientHandler.java @@ -1,8 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.recipemod.jei; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.support.AbstractBaseScreen; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.AbstractResourceContainerMenu; @@ -40,7 +39,7 @@ private List> getTargets(final AbstractBaseScreen screen, final List> targets = new ArrayList<>(); ingredientConverter.convertToResource(ingredient).ifPresent(resource -> { for (final ResourceSlot slot : menu.getResourceSlots()) { - if (slot.isFilter() && slot.isValid(resource.resource())) { + if (slot.isFilter() && slot.isValid(resource)) { final Rect2i bounds = getBounds(screen, slot); targets.add(new TargetImpl<>(bounds, slot.index)); } @@ -77,10 +76,9 @@ public void accept(final I ingredient) { ingredientConverter.convertToResource(ingredient).ifPresent(this::accept); } - private void accept(final ResourceTemplate resource) { + private void accept(final PlatformResourceKey resource) { Platform.INSTANCE.getClientToServerCommunications().sendResourceFilterSlotChange( - (PlatformStorageChannelType) resource.storageChannelType(), - resource.resource(), + resource, slotIndex ); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/GridGuiContainerHandler.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/GridGuiContainerHandler.java index 8c7963508..a11f0ce02 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/GridGuiContainerHandler.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/GridGuiContainerHandler.java @@ -1,7 +1,8 @@ package com.refinedmods.refinedstorage2.platform.common.recipemod.jei; -import com.refinedmods.refinedstorage2.api.grid.view.GridResource; +import com.refinedmods.refinedstorage2.platform.api.grid.view.PlatformGridResource; import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.grid.screen.AbstractGridScreen; import java.util.Optional; @@ -27,13 +28,17 @@ public Optional> getClickableIngredientUnderMouse( final double mouseX, final double mouseY ) { - final GridResource resource = screen.getCurrentGridResource(); + final PlatformGridResource resource = screen.getCurrentGridResource(); if (resource == null) { return Optional.empty(); } - return converter - .convertToIngredient(resource) - .flatMap(ingredient -> convertToClickableIngredient(mouseX, mouseY, ingredient)); + final PlatformResourceKey underlyingResource = resource.getUnderlyingResource(); + if (underlyingResource == null) { + return Optional.empty(); + } + return converter.convertToIngredient(underlyingResource).flatMap( + ingredient -> convertToClickableIngredient(mouseX, mouseY, ingredient) + ); } private Optional> convertToClickableIngredient(final double x, diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/GridResourceIngredientConverter.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/GridResourceIngredientConverter.java deleted file mode 100644 index 3cde9afa4..000000000 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/GridResourceIngredientConverter.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.common.recipemod.jei; - -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; -import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; -import com.refinedmods.refinedstorage2.platform.common.grid.view.FluidGridResource; -import com.refinedmods.refinedstorage2.platform.common.grid.view.ItemGridResource; - -import java.util.Optional; - -import mezz.jei.api.helpers.IPlatformFluidHelper; - -class GridResourceIngredientConverter implements IngredientConverter { - private final IPlatformFluidHelper fluidHelper; - - GridResourceIngredientConverter(final IPlatformFluidHelper fluidHelper) { - this.fluidHelper = fluidHelper; - } - - @Override - public Optional> convertToResource(final Object ingredient) { - return Optional.empty(); - } - - @Override - public Optional convertToIngredient(final Object resource) { - if (resource instanceof ItemGridResource itemGridResource) { - return Optional.of(itemGridResource.copyItemStack()); - } - if (resource instanceof FluidGridResource fluidGridResource) { - return Optional.of(fluidHelper.create( - fluidGridResource.getResource().fluid(), - fluidHelper.bucketVolume(), - fluidGridResource.getResource().tag() - )); - } - return Optional.empty(); - } -} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/IngredientConvertImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/IngredientConvertImpl.java new file mode 100644 index 000000000..c9bcc7efd --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/IngredientConvertImpl.java @@ -0,0 +1,47 @@ +package com.refinedmods.refinedstorage2.platform.common.recipemod.jei; + +import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.common.Platform; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; + +import java.util.Optional; + +import mezz.jei.api.helpers.IPlatformFluidHelper; +import net.minecraft.world.item.ItemStack; + +class IngredientConvertImpl implements IngredientConverter { + private final IPlatformFluidHelper fluidHelper; + + IngredientConvertImpl(final IPlatformFluidHelper fluidHelper) { + this.fluidHelper = fluidHelper; + } + + @Override + public Optional convertToResource(final Object ingredient) { + final var fluid = Platform.INSTANCE.convertJeiIngredientToFluid(ingredient); + if (fluid.isPresent()) { + return fluid.map(f -> f); + } + if (ingredient instanceof ItemStack itemStack) { + return Optional.of(ItemResource.ofItemStack(itemStack)); + } + return Optional.empty(); + } + + @Override + public Optional convertToIngredient(final PlatformResourceKey resource) { + if (resource instanceof ItemResource itemResource) { + return Optional.of(itemResource.toItemStack()); + } + if (resource instanceof FluidResource fluidResource) { + return Optional.of(fluidHelper.create( + fluidResource.fluid(), + fluidHelper.bucketVolume(), + fluidResource.tag() + )); + } + return Optional.empty(); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/RefinedStorageJeiModPlugin.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/RefinedStorageJeiModPlugin.java index 7c322fa83..767208eb4 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/RefinedStorageJeiModPlugin.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/RefinedStorageJeiModPlugin.java @@ -87,7 +87,6 @@ private void registerGridSynchronizers() { } private void registerIngredientConverters(final IPlatformFluidHelper fluidHelper) { - PlatformApi.INSTANCE.registerIngredientConverter(new GridResourceIngredientConverter(fluidHelper)); - PlatformApi.INSTANCE.registerIngredientConverter(new ResourceIngredientConverter(fluidHelper)); + PlatformApi.INSTANCE.registerIngredientConverter(new IngredientConvertImpl(fluidHelper)); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/ResourceGuiContainerHandler.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/ResourceGuiContainerHandler.java index 5a45963ce..a6dc2c7c1 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/ResourceGuiContainerHandler.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/ResourceGuiContainerHandler.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.recipemod.jei; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.support.AbstractBaseScreen; import java.util.Optional; @@ -32,11 +32,11 @@ public Optional> getClickableIngredientUnderMouse( return convertToIngredient(baseScreen.getHoveredResource()).flatMap(this::convertToClickableIngredient); } - public Optional convertToIngredient(@Nullable final ResourceTemplate resourceTemplate) { - if (resourceTemplate == null) { + public Optional convertToIngredient(@Nullable final PlatformResourceKey resource) { + if (resource == null) { return Optional.empty(); } - return converter.convertToIngredient(resourceTemplate); + return converter.convertToIngredient(resource); } private Optional> convertToClickableIngredient(final Object ingredient) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/ResourceIngredientConverter.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/ResourceIngredientConverter.java deleted file mode 100644 index c4b6fd31d..000000000 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/recipemod/jei/ResourceIngredientConverter.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.common.recipemod.jei; - -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; -import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.Platform; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; - -import java.util.Optional; - -import mezz.jei.api.helpers.IPlatformFluidHelper; -import net.minecraft.world.item.ItemStack; - -class ResourceIngredientConverter implements IngredientConverter { - private final IPlatformFluidHelper fluidHelper; - - ResourceIngredientConverter(final IPlatformFluidHelper fluidHelper) { - this.fluidHelper = fluidHelper; - } - - @Override - public Optional> convertToResource(final Object ingredient) { - final var fluid = Platform.INSTANCE.convertJeiIngredientToFluid(ingredient); - if (fluid.isPresent()) { - return fluid.map(fluidResource -> new ResourceTemplate<>( - fluidResource, - StorageChannelTypes.FLUID - )); - } - if (ingredient instanceof ItemStack itemStack) { - return Optional.of(new ResourceTemplate<>( - ItemResource.ofItemStack(itemStack), - StorageChannelTypes.ITEM - )); - } - return Optional.empty(); - } - - @Override - public Optional convertToIngredient(final Object resource) { - if (!(resource instanceof ResourceTemplate resourceTemplate)) { - return Optional.empty(); - } - if (resourceTemplate.resource() instanceof ItemResource itemResource) { - return Optional.of(itemResource.toItemStack()); - } - if (resourceTemplate.resource() instanceof FluidResource fluidResource) { - return Optional.of(fluidHelper.create( - fluidResource.fluid(), - fluidHelper.bucketVolume(), - fluidResource.tag() - )); - } - return Optional.empty(); - } -} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/AbstractStorageContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/AbstractStorageContainerMenu.java index b453684b8..05621e42d 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/AbstractStorageContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/AbstractStorageContainerMenu.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.storage; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; import com.refinedmods.refinedstorage2.api.storage.AccessMode; import com.refinedmods.refinedstorage2.platform.common.support.RedstoneMode; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.AbstractResourceContainerMenu; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/BucketPlayerInventoryInsertableStorage.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/BucketPlayerInventoryInsertableStorage.java index a1f5a397b..e4a2fab44 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/BucketPlayerInventoryInsertableStorage.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/BucketPlayerInventoryInsertableStorage.java @@ -1,27 +1,28 @@ package com.refinedmods.refinedstorage2.platform.common.storage; import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; import com.refinedmods.refinedstorage2.api.storage.Storage; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.Platform; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; -public class BucketPlayerInventoryInsertableStorage implements InsertableStorage { +public class BucketPlayerInventoryInsertableStorage implements InsertableStorage { private static final ItemStack EMPTY_BUCKET_STACK = new ItemStack(Items.BUCKET); private static final ItemResource EMPTY_BUCKET_RESOURCE = ItemResource.ofItemStack(EMPTY_BUCKET_STACK); private final Inventory playerInventory; - private final Storage emptyBucketStorage; + private final Storage emptyBucketStorage; private final boolean mayDropFilledBucket; public BucketPlayerInventoryInsertableStorage(final Inventory playerInventory, - final Storage emptyBucketStorage, + final Storage emptyBucketStorage, final boolean mayDropFilledBucket) { this.playerInventory = playerInventory; this.emptyBucketStorage = emptyBucketStorage; @@ -29,11 +30,14 @@ public BucketPlayerInventoryInsertableStorage(final Inventory playerInventory, } @Override - public long insert(final FluidResource resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { + if (!(resource instanceof FluidResource fluidResource)) { + return 0; + } if (amount != Platform.INSTANCE.getBucketAmount()) { return 0; } - return Platform.INSTANCE.convertToBucket(resource).map( + return Platform.INSTANCE.convertToBucket(fluidResource).map( filledBucketStack -> insert(filledBucketStack, amount, action, actor) ).orElse(0L); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/ClientStorageRepository.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/ClientStorageRepository.java index fb446db0b..899217fcc 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/ClientStorageRepository.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/ClientStorageRepository.java @@ -30,17 +30,17 @@ public ClientStorageRepository(final Consumer storageInfoRequestAcceptor) } @Override - public Optional> get(final UUID id) { + public Optional get(final UUID id) { throw new UnsupportedOperationException(); } @Override - public void set(final UUID id, final Storage storage) { + public void set(final UUID id, final Storage storage) { throw new UnsupportedOperationException(); } @Override - public Optional> removeIfEmpty(final UUID id) { + public Optional removeIfEmpty(final UUID id) { throw new UnsupportedOperationException(); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/DiskInventory.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/DiskInventory.java index 77c2014ec..5db389b00 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/DiskInventory.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/DiskInventory.java @@ -3,7 +3,6 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.multistorage.MultiStorageProvider; import com.refinedmods.refinedstorage2.api.storage.Storage; import com.refinedmods.refinedstorage2.api.storage.StorageState; -import com.refinedmods.refinedstorage2.api.storage.TypedStorage; import com.refinedmods.refinedstorage2.platform.api.storage.StorageContainerItem; import com.refinedmods.refinedstorage2.platform.api.storage.StorageRepository; @@ -54,7 +53,7 @@ public void setItem(final int slot, final ItemStack stack) { } @Override - public Optional>> resolve(final int index) { + public Optional resolve(final int index) { if (storageRepository == null) { return Optional.empty(); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/FluidStorageType.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/FluidStorageType.java index 6822e780f..ddfff6b69 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/FluidStorageType.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/FluidStorageType.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.storage; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; import com.refinedmods.refinedstorage2.api.storage.Storage; import com.refinedmods.refinedstorage2.api.storage.limited.LimitedStorage; @@ -11,8 +12,9 @@ import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedStorageRepository; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; import com.refinedmods.refinedstorage2.platform.api.storage.StorageType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.common.Platform; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceTypes; import javax.annotation.Nullable; @@ -20,9 +22,10 @@ import net.minecraft.nbt.ListTag; import net.minecraft.nbt.Tag; -public class FluidStorageType implements StorageType { +public class FluidStorageType implements StorageType { private static final String TAG_CAPACITY = "cap"; private static final String TAG_STACKS = "stacks"; + private static final String TAG_AMOUNT = "amount"; private static final String TAG_CHANGED_BY = "cb"; private static final String TAG_CHANGED_AT = "ca"; @@ -30,21 +33,21 @@ public class FluidStorageType implements StorageType { } @Override - public Storage create(@Nullable final Long capacity, final Runnable listener) { + public Storage create(@Nullable final Long capacity, final Runnable listener) { return innerCreate(capacity, listener); } @Override - public Storage fromTag(final CompoundTag tag, final Runnable listener) { - final PlatformStorage storage = innerCreate( + public Storage fromTag(final CompoundTag tag, final Runnable listener) { + final PlatformStorage storage = innerCreate( tag.contains(TAG_CAPACITY) ? tag.getLong(TAG_CAPACITY) : null, listener ); final ListTag stacks = tag.getList(TAG_STACKS, Tag.TAG_COMPOUND); for (final Tag stackTag : stacks) { - FluidResource.fromTagWithAmount((CompoundTag) stackTag).ifPresent(resourceAmount -> storage.load( - resourceAmount.getResource(), - resourceAmount.getAmount(), + ResourceTypes.FLUID.fromTag((CompoundTag) stackTag).ifPresent(resource -> storage.load( + resource, + ((CompoundTag) stackTag).getLong(TAG_AMOUNT), ((CompoundTag) stackTag).getString(TAG_CHANGED_BY), ((CompoundTag) stackTag).getLong(TAG_CHANGED_AT) )); @@ -52,26 +55,26 @@ public Storage fromTag(final CompoundTag tag, final Runnable list return storage; } - private PlatformStorage innerCreate(@Nullable final Long capacity, final Runnable listener) { - final TrackedStorageRepository trackingRepository = new InMemoryTrackedStorageRepository<>(); + private PlatformStorage innerCreate(@Nullable final Long capacity, final Runnable listener) { + final TrackedStorageRepository trackingRepository = new InMemoryTrackedStorageRepository(); if (capacity != null) { - final LimitedStorageImpl delegate = new LimitedStorageImpl<>( - new TrackedStorageImpl<>( - new InMemoryStorageImpl<>(), + final LimitedStorageImpl delegate = new LimitedStorageImpl( + new TrackedStorageImpl( + new InMemoryStorageImpl(), trackingRepository, System::currentTimeMillis ), capacity ); - return new LimitedPlatformStorage<>( + return new LimitedPlatformStorage( delegate, StorageTypes.FLUID, trackingRepository, listener ); } - return new PlatformStorage<>( - new TrackedStorageImpl<>(new InMemoryStorageImpl<>(), trackingRepository, System::currentTimeMillis), + return new PlatformStorage( + new TrackedStorageImpl(new InMemoryStorageImpl(), trackingRepository, System::currentTimeMillis), StorageTypes.FLUID, trackingRepository, listener @@ -79,23 +82,26 @@ private PlatformStorage innerCreate(@Nullable final Long capacity } @Override - public CompoundTag toTag(final Storage storage) { + public CompoundTag toTag(final Storage storage) { final CompoundTag tag = new CompoundTag(); - if (storage instanceof LimitedStorage limitedStorage) { + if (storage instanceof LimitedStorage limitedStorage) { tag.putLong(TAG_CAPACITY, limitedStorage.getCapacity()); } final ListTag stacks = new ListTag(); - for (final ResourceAmount resourceAmount : storage.getAll()) { + for (final ResourceAmount resourceAmount : storage.getAll()) { stacks.add(toTag(storage, resourceAmount)); } tag.put(TAG_STACKS, stacks); return tag; } - private CompoundTag toTag(final Storage storage, - final ResourceAmount resourceAmount) { - final CompoundTag tag = FluidResource.toTagWithAmount(resourceAmount); - if (storage instanceof TrackedStorage trackedStorage) { + private CompoundTag toTag(final Storage storage, final ResourceAmount resourceAmount) { + if (!(resourceAmount.getResource() instanceof FluidResource fluidResource)) { + throw new UnsupportedOperationException(); + } + final CompoundTag tag = fluidResource.toTag(); + tag.putLong(TAG_AMOUNT, resourceAmount.getAmount()); + if (storage instanceof TrackedStorage trackedStorage) { trackedStorage .findTrackedResourceByActorType(resourceAmount.getResource(), PlayerActor.class) .ifPresent(trackedResource -> { @@ -106,6 +112,11 @@ private CompoundTag toTag(final Storage storage, return tag; } + @Override + public boolean isAllowed(final ResourceKey resource) { + return resource instanceof FluidResource; + } + public enum Variant { SIXTY_FOUR_B("64b", 64L), TWO_HUNDRED_FIFTY_SIX_B("256b", 256L), diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/ItemStorageType.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/ItemStorageType.java index fbf747c35..8f9d78c15 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/ItemStorageType.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/ItemStorageType.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.storage; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; import com.refinedmods.refinedstorage2.api.storage.Storage; import com.refinedmods.refinedstorage2.api.storage.limited.LimitedStorage; @@ -11,7 +12,8 @@ import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedStorageRepository; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; import com.refinedmods.refinedstorage2.platform.api.storage.StorageType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceTypes; import javax.annotation.Nullable; @@ -19,9 +21,10 @@ import net.minecraft.nbt.ListTag; import net.minecraft.nbt.Tag; -public class ItemStorageType implements StorageType { +public class ItemStorageType implements StorageType { private static final String TAG_CAPACITY = "cap"; private static final String TAG_STACKS = "stacks"; + private static final String TAG_AMOUNT = "amount"; private static final String TAG_CHANGED_BY = "cb"; private static final String TAG_CHANGED_AT = "ca"; @@ -29,21 +32,21 @@ public class ItemStorageType implements StorageType { } @Override - public Storage create(@Nullable final Long capacity, final Runnable listener) { + public Storage create(@Nullable final Long capacity, final Runnable listener) { return innerCreate(capacity, listener); } @Override - public Storage fromTag(final CompoundTag tag, final Runnable listener) { - final PlatformStorage storage = innerCreate( + public Storage fromTag(final CompoundTag tag, final Runnable listener) { + final PlatformStorage storage = innerCreate( tag.contains(TAG_CAPACITY) ? tag.getLong(TAG_CAPACITY) : null, listener ); final ListTag stacks = tag.getList(TAG_STACKS, Tag.TAG_COMPOUND); for (final Tag stackTag : stacks) { - ItemResource.fromTagWithAmount((CompoundTag) stackTag).ifPresent(resourceAmount -> storage.load( - resourceAmount.getResource(), - resourceAmount.getAmount(), + ResourceTypes.ITEM.fromTag((CompoundTag) stackTag).ifPresent(resource -> storage.load( + resource, + ((CompoundTag) stackTag).getLong(TAG_AMOUNT), ((CompoundTag) stackTag).getString(TAG_CHANGED_BY), ((CompoundTag) stackTag).getLong(TAG_CHANGED_AT) )); @@ -51,26 +54,26 @@ public Storage fromTag(final CompoundTag tag, final Runnable liste return storage; } - private PlatformStorage innerCreate(@Nullable final Long capacity, final Runnable listener) { - final TrackedStorageRepository trackingRepository = new InMemoryTrackedStorageRepository<>(); + private PlatformStorage innerCreate(@Nullable final Long capacity, final Runnable listener) { + final TrackedStorageRepository trackingRepository = new InMemoryTrackedStorageRepository(); if (capacity != null) { - final LimitedStorageImpl delegate = new LimitedStorageImpl<>( - new TrackedStorageImpl<>( - new InMemoryStorageImpl<>(), + final LimitedStorageImpl delegate = new LimitedStorageImpl( + new TrackedStorageImpl( + new InMemoryStorageImpl(), trackingRepository, System::currentTimeMillis ), capacity ); - return new LimitedPlatformStorage<>( + return new LimitedPlatformStorage( delegate, StorageTypes.ITEM, trackingRepository, listener ); } - return new PlatformStorage<>( - new TrackedStorageImpl<>(new InMemoryStorageImpl<>(), trackingRepository, System::currentTimeMillis), + return new PlatformStorage( + new TrackedStorageImpl(new InMemoryStorageImpl(), trackingRepository, System::currentTimeMillis), StorageTypes.ITEM, trackingRepository, listener @@ -78,22 +81,26 @@ private PlatformStorage innerCreate(@Nullable final Long capacity, } @Override - public CompoundTag toTag(final Storage storage) { + public CompoundTag toTag(final Storage storage) { final CompoundTag tag = new CompoundTag(); - if (storage instanceof LimitedStorage limitedStorage) { + if (storage instanceof LimitedStorage limitedStorage) { tag.putLong(TAG_CAPACITY, limitedStorage.getCapacity()); } final ListTag stacks = new ListTag(); - for (final ResourceAmount resourceAmount : storage.getAll()) { + for (final ResourceAmount resourceAmount : storage.getAll()) { stacks.add(toTag(storage, resourceAmount)); } tag.put(TAG_STACKS, stacks); return tag; } - private CompoundTag toTag(final Storage storage, final ResourceAmount resourceAmount) { - final CompoundTag tag = ItemResource.toTagWithAmount(resourceAmount); - if (storage instanceof TrackedStorage trackedStorage) { + private CompoundTag toTag(final Storage storage, final ResourceAmount resourceAmount) { + if (!(resourceAmount.getResource() instanceof ItemResource itemResource)) { + throw new UnsupportedOperationException(); + } + final CompoundTag tag = itemResource.toTag(); + tag.putLong(TAG_AMOUNT, resourceAmount.getAmount()); + if (storage instanceof TrackedStorage trackedStorage) { trackedStorage .findTrackedResourceByActorType(resourceAmount.getResource(), PlayerActor.class) .ifPresent(trackedResource -> { @@ -104,6 +111,11 @@ private CompoundTag toTag(final Storage storage, final ResourceAmo return tag; } + @Override + public boolean isAllowed(final ResourceKey resource) { + return resource instanceof ItemResource; + } + public enum Variant { ONE_K("1k", 1024L), FOUR_K("4k", 1024 * 4L), diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/LimitedPlatformStorage.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/LimitedPlatformStorage.java index 763883d98..72f5fc8e5 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/LimitedPlatformStorage.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/LimitedPlatformStorage.java @@ -5,12 +5,12 @@ import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedStorageRepository; import com.refinedmods.refinedstorage2.platform.api.storage.StorageType; -class LimitedPlatformStorage extends PlatformStorage implements LimitedStorage { - private final LimitedStorageImpl limitedStorage; +class LimitedPlatformStorage extends PlatformStorage implements LimitedStorage { + private final LimitedStorageImpl limitedStorage; - LimitedPlatformStorage(final LimitedStorageImpl delegate, - final StorageType type, - final TrackedStorageRepository trackingRepository, + LimitedPlatformStorage(final LimitedStorageImpl delegate, + final StorageType type, + final TrackedStorageRepository trackingRepository, final Runnable listener) { super(delegate, type, trackingRepository, listener); this.limitedStorage = delegate; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/PlatformStorage.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/PlatformStorage.java index 33594de43..1ac6a7184 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/PlatformStorage.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/PlatformStorage.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.storage; import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.AbstractProxyStorage; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; @@ -15,14 +16,14 @@ import java.util.Optional; import javax.annotation.Nullable; -class PlatformStorage extends AbstractProxyStorage implements SerializableStorage, TrackedStorage { - private final StorageType type; - private final TrackedStorageRepository trackingRepository; +class PlatformStorage extends AbstractProxyStorage implements SerializableStorage, TrackedStorage { + private final StorageType type; + private final TrackedStorageRepository trackingRepository; private final Runnable listener; - PlatformStorage(final Storage delegate, - final StorageType type, - final TrackedStorageRepository trackingRepository, + PlatformStorage(final Storage delegate, + final StorageType type, + final TrackedStorageRepository trackingRepository, final Runnable listener) { super(delegate); this.type = type; @@ -30,7 +31,10 @@ class PlatformStorage extends AbstractProxyStorage implements Serializable this.listener = listener; } - void load(final T resource, final long amount, @Nullable final String changedBy, final long changedAt) { + void load(final ResourceKey resource, final long amount, @Nullable final String changedBy, final long changedAt) { + if (!type.isAllowed(resource)) { + return; + } super.insert(resource, amount, Action.EXECUTE, EmptyActor.INSTANCE); if (changedBy != null && !changedBy.isBlank()) { trackingRepository.update(resource, new PlayerActor(changedBy), changedAt); @@ -38,7 +42,10 @@ void load(final T resource, final long amount, @Nullable final String changedBy, } @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { + if (!type.isAllowed(resource)) { + return 0; + } final long extracted = super.extract(resource, amount, action, actor); if (extracted > 0 && action == Action.EXECUTE) { listener.run(); @@ -47,7 +54,10 @@ public long extract(final T resource, final long amount, final Action action, fi } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { + if (!type.isAllowed(resource)) { + return 0; + } final long inserted = super.insert(resource, amount, action, actor); if (inserted > 0 && action == Action.EXECUTE) { listener.run(); @@ -56,12 +66,12 @@ public long insert(final T resource, final long amount, final Action action, fin } @Override - public StorageType getType() { + public StorageType getType() { return type; } @Override - public Optional findTrackedResourceByActorType(final T resource, + public Optional findTrackedResourceByActorType(final ResourceKey resource, final Class actorType) { return trackingRepository.findTrackedResourceByActorType(resource, actorType); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageConfigurationContainer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageConfigurationContainer.java index 723141478..26b181f58 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageConfigurationContainer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageConfigurationContainer.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.storage; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; import com.refinedmods.refinedstorage2.api.storage.AccessMode; import com.refinedmods.refinedstorage2.platform.common.support.RedstoneMode; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageConfigurationContainerImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageConfigurationContainerImpl.java index 883d6afd6..b74a9f2ca 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageConfigurationContainerImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageConfigurationContainerImpl.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.storage; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; import com.refinedmods.refinedstorage2.api.network.node.StorageConfiguration; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; import com.refinedmods.refinedstorage2.api.storage.AccessMode; import com.refinedmods.refinedstorage2.platform.common.support.FilterModeSettings; import com.refinedmods.refinedstorage2.platform.common.support.FilterWithFuzzyMode; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageContainerItemHelperImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageContainerItemHelperImpl.java index cd9cd5916..2be618047 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageContainerItemHelperImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageContainerItemHelperImpl.java @@ -42,12 +42,12 @@ public class StorageContainerItemHelperImpl implements StorageContainerItemHelpe private final Set diskModels = new HashSet<>(); @Override - public Optional> resolve(final StorageRepository storageRepository, final ItemStack stack) { + public Optional resolve(final StorageRepository storageRepository, final ItemStack stack) { return getId(stack).flatMap(storageRepository::get); } @Override - public void set(final StorageRepository storageRepository, final ItemStack stack, final Storage storage) { + public void set(final StorageRepository storageRepository, final ItemStack stack, final Storage storage) { final UUID id = UUID.randomUUID(); setId(stack, id); storageRepository.set(id, storage); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageRepositoryImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageRepositoryImpl.java index c08e6d259..6d25b7163 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageRepositoryImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageRepositoryImpl.java @@ -31,28 +31,27 @@ public class StorageRepositoryImpl extends SavedData implements StorageRepositor private static final String TAG_STORAGE_TYPE = "type"; private static final String TAG_STORAGE_DATA = "data"; - private final Map> entries = new HashMap<>(); - private final PlatformRegistry> storageTypeRegistry; + private final Map entries = new HashMap<>(); + private final PlatformRegistry storageTypeRegistry; - public StorageRepositoryImpl(final PlatformRegistry> storageTypeRegistry) { + public StorageRepositoryImpl(final PlatformRegistry storageTypeRegistry) { this.storageTypeRegistry = storageTypeRegistry; } @Override - @SuppressWarnings("unchecked") - public Optional> get(final UUID id) { - return Optional.ofNullable((Storage) entries.get(id)); + public Optional get(final UUID id) { + return Optional.ofNullable(entries.get(id)); } @Override - public void set(final UUID id, final Storage storage) { + public void set(final UUID id, final Storage storage) { setSilently(id, storage); setDirty(); } - private void setSilently(final UUID id, final Storage storage) { + private void setSilently(final UUID id, final Storage storage) { CoreValidations.validateNotNull(storage, "Storage must not be null"); - if (!(storage instanceof SerializableStorage)) { + if (!(storage instanceof SerializableStorage)) { throw new IllegalArgumentException("Storage is not serializable"); } CoreValidations.validateNotNull(id, "ID must not be null"); @@ -63,8 +62,8 @@ private void setSilently(final UUID id, final Storage storage) { } @Override - public Optional> removeIfEmpty(final UUID id) { - return this.get(id).map(storage -> { + public Optional removeIfEmpty(final UUID id) { + return get(id).map(storage -> { if (storage.getStored() == 0) { entries.remove(id); setDirty(); @@ -101,10 +100,9 @@ public void read(final CompoundTag tag) { } @Override - @SuppressWarnings({"unchecked", "rawtypes"}) public CompoundTag save(final CompoundTag tag) { final ListTag storageList = new ListTag(); - for (final Map.Entry> entry : entries.entrySet()) { + for (final Map.Entry entry : entries.entrySet()) { if (entry.getValue() instanceof SerializableStorage serializableStorage) { storageList.add(convertStorageToTag(entry.getKey(), entry.getValue(), serializableStorage)); } else { @@ -115,8 +113,9 @@ public CompoundTag save(final CompoundTag tag) { return tag; } - private Tag convertStorageToTag(final UUID id, final Storage storage, - final SerializableStorage serializableStorage) { + private Tag convertStorageToTag(final UUID id, + final Storage storage, + final SerializableStorage serializableStorage) { final ResourceLocation typeIdentifier = storageTypeRegistry .getId(serializableStorage.getType()) .orElseThrow(() -> new RuntimeException("Storage type is not registered")); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageTypes.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageTypes.java index 98cf8a896..3bbc695ff 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageTypes.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageTypes.java @@ -1,12 +1,10 @@ package com.refinedmods.refinedstorage2.platform.common.storage; import com.refinedmods.refinedstorage2.platform.api.storage.StorageType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; public final class StorageTypes { - public static final StorageType ITEM = new ItemStorageType(); - public static final StorageType FLUID = new FluidStorageType(); + public static final StorageType ITEM = new ItemStorageType(); + public static final StorageType FLUID = new FluidStorageType(); private StorageTypes() { } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/channel/StorageChannelTypes.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/channel/StorageChannelTypes.java deleted file mode 100644 index 01e9179c3..000000000 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/channel/StorageChannelTypes.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.common.storage.channel; - -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; - -public final class StorageChannelTypes { - public static final PlatformStorageChannelType ITEM = new ItemStorageChannelType(); - public static final PlatformStorageChannelType FLUID = new FluidStorageChannelType(); - - private StorageChannelTypes() { - } -} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/diskdrive/AbstractDiskDriveBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/diskdrive/AbstractDiskDriveBlockEntity.java index 6ed95037b..964534919 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/diskdrive/AbstractDiskDriveBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/diskdrive/AbstractDiskDriveBlockEntity.java @@ -58,14 +58,13 @@ protected AbstractDiskDriveBlockEntity(final BlockPos pos, final BlockState stat super(BlockEntities.INSTANCE.getDiskDrive(), pos, state, new MultiStorageNetworkNode( Platform.INSTANCE.getConfig().getDiskDrive().getEnergyUsage(), Platform.INSTANCE.getConfig().getDiskDrive().getEnergyUsagePerDisk(), - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().getAll(), AMOUNT_OF_DISKS )); this.diskInventory = new DiskInventory((inventory, slot) -> onDiskChanged(slot), getNode().getSize()); - this.filter = FilterWithFuzzyMode.createAndListenForUniqueTemplates( + this.filter = FilterWithFuzzyMode.createAndListenForUniqueFilters( ResourceContainerImpl.createForFilter(), this::setChanged, - templates -> getNode().setFilterTemplates(templates) + filters -> getNode().setFilters(filters) ); this.configContainer = new StorageConfigurationContainerImpl( getNode(), diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/externalstorage/ExternalStorageBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/externalstorage/ExternalStorageBlockEntity.java index 027a31103..52af23de1 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/externalstorage/ExternalStorageBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/externalstorage/ExternalStorageBlockEntity.java @@ -1,9 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.storage.externalstorage; import com.refinedmods.refinedstorage2.api.network.impl.node.externalstorage.ExternalStorageNetworkNode; -import com.refinedmods.refinedstorage2.api.network.node.externalstorage.ExternalStorageProviderFactory; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; -import com.refinedmods.refinedstorage2.api.storage.external.ExternalStorageProvider; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; @@ -15,7 +12,6 @@ import com.refinedmods.refinedstorage2.platform.common.support.network.AbstractRedstoneModeNetworkNodeContainerBlockEntity; import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceContainerImpl; -import java.util.Optional; import javax.annotation.Nullable; import net.minecraft.core.BlockPos; @@ -41,29 +37,23 @@ public class ExternalStorageBlockEntity private final FilterWithFuzzyMode filter; private final StorageConfigurationContainerImpl configContainer; - private final ExternalStorageTrackedStorageRepositoryProvider trackedStorageRepositoryProvider; + private final ExternalStorageTrackedStorageRepository trackedStorageRepository = + new ExternalStorageTrackedStorageRepository(this::setChanged); private final ExternalStorageWorkRate workRate = new ExternalStorageWorkRate(); private boolean initialized; public ExternalStorageBlockEntity(final BlockPos pos, final BlockState state) { super(BlockEntities.INSTANCE.getExternalStorage(), pos, state, new ExternalStorageNetworkNode( - Platform.INSTANCE.getConfig().getExternalStorage().getEnergyUsage() + Platform.INSTANCE.getConfig().getExternalStorage().getEnergyUsage(), + System::currentTimeMillis )); - this.filter = FilterWithFuzzyMode.createAndListenForUniqueTemplates( + this.filter = FilterWithFuzzyMode.createAndListenForUniqueFilters( ResourceContainerImpl.createForFilter(), this::setChanged, - templates -> getNode().setFilterTemplates(templates) - ); - this.trackedStorageRepositoryProvider = new ExternalStorageTrackedStorageRepositoryProvider( - PlatformApi.INSTANCE.getStorageChannelTypeRegistry(), - this::setChanged + filters -> getNode().setFilters(filters) ); getNode().setNormalizer(filter.createNormalizer()); - getNode().initialize( - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().getAll(), - System::currentTimeMillis, - trackedStorageRepositoryProvider - ); + getNode().setTrackingRepository(trackedStorageRepository); this.configContainer = new StorageConfigurationContainerImpl( getNode(), filter, @@ -98,18 +88,14 @@ void loadStorage(final ServerLevel serverLevel) { if (direction == null) { return; } - getNode().initialize(new ExternalStorageProviderFactory() { - @Override - public Optional> create(final StorageChannelType channelType) { - final Direction incomingDirection = direction.getOpposite(); - final BlockPos sourcePosition = worldPosition.relative(direction); - return PlatformApi.INSTANCE - .getExternalStorageProviderFactories() - .stream() - .flatMap(factory -> factory.create(serverLevel, sourcePosition, incomingDirection, channelType) - .stream()) - .findFirst(); - } + getNode().initialize(() -> { + final Direction incomingDirection = direction.getOpposite(); + final BlockPos sourcePosition = worldPosition.relative(direction); + return PlatformApi.INSTANCE + .getExternalStorageProviderFactories() + .stream() + .flatMap(factory -> factory.create(serverLevel, sourcePosition, incomingDirection).stream()) + .findFirst(); }); } @@ -130,7 +116,7 @@ public void doWork() { @Override public void saveAdditional(final CompoundTag tag) { super.saveAdditional(tag); - tag.put(TAG_TRACKED_RESOURCES, trackedStorageRepositoryProvider.toTag()); + tag.put(TAG_TRACKED_RESOURCES, trackedStorageRepository.toTag()); } @Override @@ -143,7 +129,7 @@ public void writeConfiguration(final CompoundTag tag) { @Override public void load(final CompoundTag tag) { super.load(tag); - trackedStorageRepositoryProvider.fromTag(tag.getList(TAG_TRACKED_RESOURCES, Tag.TAG_COMPOUND)); + trackedStorageRepository.fromTag(tag.getList(TAG_TRACKED_RESOURCES, Tag.TAG_COMPOUND)); } @Override @@ -168,7 +154,7 @@ public Component getDisplayName() { public AbstractContainerMenu createMenu(final int syncId, final Inventory inventory, final Player player) { return new ExternalStorageContainerMenu(syncId, player, filter.getFilterContainer(), configContainer); } - + @Override protected boolean doesBlockStateChangeWarrantNetworkNodeUpdate(final BlockState oldBlockState, final BlockState newBlockState) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/externalstorage/ExternalStorageTrackedStorageRepository.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/externalstorage/ExternalStorageTrackedStorageRepository.java index 8ae59bcad..9661cc923 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/externalstorage/ExternalStorageTrackedStorageRepository.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/externalstorage/ExternalStorageTrackedStorageRepository.java @@ -1,28 +1,34 @@ package com.refinedmods.refinedstorage2.platform.common.storage.externalstorage; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.tracked.InMemoryTrackedStorageRepository; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import java.util.Collections; import java.util.Map; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; +import net.minecraft.resources.ResourceLocation; + +class ExternalStorageTrackedStorageRepository extends InMemoryTrackedStorageRepository { + private static final String TAG_MODIFIED_BY = "mb"; + private static final String TAG_MODIFIED_AT = "ma"; + private static final String TAG_RESOURCE_TYPE = "rt"; -class ExternalStorageTrackedStorageRepository extends InMemoryTrackedStorageRepository { - private final PlatformStorageChannelType type; private final Runnable listener; - ExternalStorageTrackedStorageRepository(final Runnable listener, final PlatformStorageChannelType type) { + ExternalStorageTrackedStorageRepository(final Runnable listener) { this.listener = listener; - this.type = type; } @Override - public void update(final T resource, final Actor actor, final long time) { + public void update(final ResourceKey resource, final Actor actor, final long time) { super.update(resource, actor, time); listener.run(); } @@ -30,25 +36,43 @@ public void update(final T resource, final Actor actor, final long time) { ListTag toTag() { final ListTag items = new ListTag(); getPersistentTrackedResources().forEach((resource, trackedResource) -> { - final CompoundTag tag = type.toTag(resource, trackedResource); - items.add(tag); + if (!(resource instanceof PlatformResourceKey platformResource)) { + return; + } + final ResourceType resourceType = platformResource.getResourceType(); + PlatformApi.INSTANCE.getResourceTypeRegistry().getId(resourceType).ifPresent(id -> { + final CompoundTag tag = platformResource.toTag(); + tag.putString(TAG_MODIFIED_BY, trackedResource.getSourceName()); + tag.putLong(TAG_MODIFIED_AT, trackedResource.getTime()); + tag.putString(TAG_RESOURCE_TYPE, id.toString()); + items.add(tag); + }); }); return items; } void fromTag(final ListTag items) { - items.forEach(tag -> type.fromTag( - (CompoundTag) tag, - // call super here to avoid marking dirty. - (resource, trackedResource) -> super.update( - resource, - new PlayerActor(trackedResource.getSourceName()), - trackedResource.getTime() - ) - )); + items.forEach(tag -> { + final ResourceLocation resourceTypeId = new ResourceLocation( + ((CompoundTag) tag).getString(TAG_RESOURCE_TYPE) + ); + fromTag((CompoundTag) tag, resourceTypeId); + }); + } + + private void fromTag(final CompoundTag tag, final ResourceLocation resourceTypeId) { + PlatformApi.INSTANCE.getResourceTypeRegistry() + .get(resourceTypeId) + .flatMap(resourceType -> resourceType.fromTag(tag)) + .ifPresent(resource -> { + final String modifiedBy = tag.getString(TAG_MODIFIED_BY); + final long modifiedAt = tag.getLong(TAG_MODIFIED_AT); + // Call super here to avoid marking dirty. + super.update(resource, new PlayerActor(modifiedBy), modifiedAt); + }); } - private Map getPersistentTrackedResources() { + private Map getPersistentTrackedResources() { return trackedResourcesByActorType.getOrDefault( PlayerActor.class, Collections.emptyMap() diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/externalstorage/ExternalStorageTrackedStorageRepositoryProvider.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/externalstorage/ExternalStorageTrackedStorageRepositoryProvider.java deleted file mode 100644 index 01f051694..000000000 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/externalstorage/ExternalStorageTrackedStorageRepositoryProvider.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.common.storage.externalstorage; - -import com.refinedmods.refinedstorage2.api.network.impl.node.externalstorage.TrackedStorageRepositoryProvider; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; -import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedStorageRepository; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.registry.PlatformRegistry; - -import java.util.HashMap; -import java.util.Map; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.Tag; -import net.minecraft.resources.ResourceLocation; - -class ExternalStorageTrackedStorageRepositoryProvider implements TrackedStorageRepositoryProvider { - private static final String TAG_TYPE = "type"; - private static final String TAG_ITEMS = "items"; - - private final PlatformRegistry> storageChannelTypeRegistry; - private final Map, ExternalStorageTrackedStorageRepository> repositoryMap - = new HashMap<>(); - - ExternalStorageTrackedStorageRepositoryProvider( - final PlatformRegistry> storageChannelTypeRegistry, - final Runnable listener - ) { - this.storageChannelTypeRegistry = storageChannelTypeRegistry; - storageChannelTypeRegistry.getAll().forEach(type -> repositoryMap.put( - type, - new ExternalStorageTrackedStorageRepository<>(listener, type) - )); - } - - ListTag toTag() { - final ListTag items = new ListTag(); - repositoryMap.forEach((type, repo) -> storageChannelTypeRegistry.getId(type) - .ifPresent(id -> items.add(toTag(repo, id)))); - return items; - } - - private CompoundTag toTag(final ExternalStorageTrackedStorageRepository repo, - final ResourceLocation id) { - final CompoundTag tag = new CompoundTag(); - tag.putString(TAG_TYPE, id.toString()); - tag.put(TAG_ITEMS, repo.toTag()); - return tag; - } - - void fromTag(final ListTag tag) { - tag.forEach(item -> { - final String id = ((CompoundTag) item).getString(TAG_TYPE); - storageChannelTypeRegistry.get(new ResourceLocation(id)).ifPresent( - type -> repositoryMap.get(type).fromTag(((CompoundTag) item).getList(TAG_ITEMS, Tag.TAG_COMPOUND)) - ); - }); - } - - @Override - @SuppressWarnings("unchecked") - public TrackedStorageRepository getRepository(final StorageChannelType type) { - return (TrackedStorageRepository) repositoryMap.get((PlatformStorageChannelType) type); - } -} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/portablegrid/PortableGrid.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/portablegrid/PortableGrid.java index 6c8859166..9b0fbd3d0 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/portablegrid/PortableGrid.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/portablegrid/PortableGrid.java @@ -3,7 +3,6 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.grid.operations.GridOperations; import com.refinedmods.refinedstorage2.api.grid.operations.NoopGridOperations; -import com.refinedmods.refinedstorage2.api.grid.watcher.GridStorageChannelProvider; import com.refinedmods.refinedstorage2.api.grid.watcher.GridWatcher; import com.refinedmods.refinedstorage2.api.grid.watcher.GridWatcherManager; import com.refinedmods.refinedstorage2.api.grid.watcher.GridWatcherManagerImpl; @@ -15,26 +14,22 @@ import com.refinedmods.refinedstorage2.api.storage.StorageState; import com.refinedmods.refinedstorage2.api.storage.TrackedResourceAmount; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.platform.api.grid.Grid; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.storage.DiskInventory; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import java.util.Collections; import java.util.List; -import java.util.Set; import javax.annotation.Nullable; -class PortableGrid implements Grid, GridStorageChannelProvider { +class PortableGrid implements Grid { private final EnergyStorage energyStorage; private final DiskInventory diskInventory; private final GridWatcherManager watchers = new GridWatcherManagerImpl(); private final StateTrackedStorage.Listener diskListener; @Nullable - private PortableGridStorage storage; + private PortableGridStorage storage; PortableGrid(final EnergyStorage energyStorage, final DiskInventory diskInventory, @@ -45,12 +40,16 @@ class PortableGrid implements Grid, GridStorageChannelProvider { } void updateStorage() { - watchers.detachAll(this); + if (storage != null) { + watchers.detachAll(storage.getStorageChannel()); + } + this.storage = diskInventory.resolve(0) - .map(diskStorage -> StateTrackedStorage.of(diskStorage, diskListener)) + .map(diskStorage -> new StateTrackedStorage(diskStorage, diskListener)) .map(PortableGridStorage::new) .orElse(null); - watchers.attachAll(this); + + watchers.attachAll(getStorageChannel()); } void activeChanged(final boolean active) { @@ -70,21 +69,25 @@ StorageState getStorageState() { @Override public void addWatcher(final GridWatcher watcher, final Class actorType) { energyStorage.extract(Platform.INSTANCE.getConfig().getPortableGrid().getOpenEnergyUsage(), Action.EXECUTE); - watchers.addWatcher(watcher, actorType, this); + watchers.addWatcher(watcher, actorType, getStorageChannel()); } @Override public void removeWatcher(final GridWatcher watcher) { - watchers.removeWatcher(watcher, this); + watchers.removeWatcher(watcher, getStorageChannel()); + } + + @Nullable + private StorageChannel getStorageChannel() { + return storage != null ? storage.getStorageChannel() : null; } @Override - @SuppressWarnings("unchecked") - public Storage getItemStorage() { - if (storage == null || storage.getStorageChannelType() != StorageChannelTypes.ITEM) { - return new NoopStorage<>(); + public Storage getItemStorage() { + if (storage == null) { + return new NoopStorage(); } - return (Storage) storage.getStorageChannel(); + return storage.getStorageChannel(); } @Override @@ -93,42 +96,25 @@ public boolean isGridActive() { } @Override - @SuppressWarnings("unchecked") - public List> getResources(final StorageChannelType type, - final Class actorType) { - if (storage == null || storage.getStorageChannelType() != type) { + public List getResources(final Class actorType) { + if (storage == null) { return Collections.emptyList(); } - final StorageChannel casted = (StorageChannel) storage.getStorageChannel(); - return casted.getAll().stream().map(resource -> new TrackedResourceAmount<>( + final StorageChannel storageChannel = storage.getStorageChannel(); + return storageChannel.getAll().stream().map(resource -> new TrackedResourceAmount( resource, - casted.findTrackedResourceByActorType(resource.getResource(), actorType).orElse(null) + storageChannel.findTrackedResourceByActorType(resource.getResource(), actorType).orElse(null) )).toList(); } @Override - @SuppressWarnings("unchecked") - public GridOperations createOperations(final PlatformStorageChannelType storageChannelType, - final Actor actor) { - if (storage == null || storage.getStorageChannelType() != storageChannelType) { - return new NoopGridOperations<>(); - } - final StorageChannel casted = (StorageChannel) storage.getStorageChannel(); - final GridOperations operations = storageChannelType.createGridOperations(casted, actor); - return new PortableGridOperations<>(operations, energyStorage); - } - - @Override - public Set> getStorageChannelTypes() { - return storage == null ? Collections.emptySet() : Set.of(storage.getStorageChannelType()); - } - - @Override - @SuppressWarnings("unchecked") - public StorageChannel getStorageChannel(final StorageChannelType type) { - if (storage == null || type != storage.getStorageChannelType()) { - throw new IllegalArgumentException(); + public GridOperations createOperations(final ResourceType resourceType, + final Actor actor) { + if (storage == null) { + return new NoopGridOperations(); } - return (StorageChannel) storage.getStorageChannel(); + final StorageChannel storageChannel = this.storage.getStorageChannel(); + final GridOperations operations = resourceType.createGridOperations(storageChannel, actor); + return new PortableGridOperations(operations, energyStorage); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/portablegrid/PortableGridOperations.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/portablegrid/PortableGridOperations.java index 196f95fdb..8184c3f22 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/portablegrid/PortableGridOperations.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/portablegrid/PortableGridOperations.java @@ -5,23 +5,24 @@ import com.refinedmods.refinedstorage2.api.grid.operations.GridInsertMode; import com.refinedmods.refinedstorage2.api.grid.operations.GridOperations; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.ExtractableStorage; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; import com.refinedmods.refinedstorage2.platform.common.Platform; -class PortableGridOperations implements GridOperations { - private final GridOperations delegate; +class PortableGridOperations implements GridOperations { + private final GridOperations delegate; private final EnergyStorage energyStorage; - PortableGridOperations(final GridOperations delegate, final EnergyStorage energyStorage) { + PortableGridOperations(final GridOperations delegate, final EnergyStorage energyStorage) { this.delegate = delegate; this.energyStorage = energyStorage; } @Override - public boolean extract(final T resource, + public boolean extract(final ResourceKey resource, final GridExtractMode extractMode, - final InsertableStorage destination) { + final InsertableStorage destination) { if (delegate.extract(resource, extractMode, destination)) { energyStorage.extract( Platform.INSTANCE.getConfig().getPortableGrid().getExtractEnergyUsage(), @@ -33,9 +34,9 @@ public boolean extract(final T resource, } @Override - public boolean insert(final T resource, + public boolean insert(final ResourceKey resource, final GridInsertMode insertMode, - final ExtractableStorage source) { + final ExtractableStorage source) { if (delegate.insert(resource, insertMode, source)) { energyStorage.extract( Platform.INSTANCE.getConfig().getPortableGrid().getInsertEnergyUsage(), diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/portablegrid/PortableGridStorage.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/portablegrid/PortableGridStorage.java index e2bb1c486..aef54033c 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/portablegrid/PortableGridStorage.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/portablegrid/PortableGridStorage.java @@ -2,30 +2,24 @@ import com.refinedmods.refinedstorage2.api.storage.StateTrackedStorage; import com.refinedmods.refinedstorage2.api.storage.StorageState; -import com.refinedmods.refinedstorage2.api.storage.TypedStorage; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelImpl; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; -class PortableGridStorage { - private final StorageChannel storageChannel; - private final TypedStorage> diskStorage; +class PortableGridStorage { + private final StorageChannel storageChannel; + private final StateTrackedStorage diskStorage; - PortableGridStorage(final TypedStorage> diskStorage) { - this.storageChannel = new StorageChannelImpl<>(); + PortableGridStorage(final StateTrackedStorage diskStorage) { + this.storageChannel = new StorageChannelImpl(); this.diskStorage = diskStorage; - this.storageChannel.addSource(diskStorage.storage()); - } - - StorageChannelType getStorageChannelType() { - return diskStorage.storageChannelType(); + this.storageChannel.addSource(diskStorage); } StorageState getState() { - return diskStorage.storage().getState(); + return diskStorage.getState(); } - StorageChannel getStorageChannel() { + StorageChannel getStorageChannel() { return storageChannel; } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/AbstractStorageBlock.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/AbstractStorageBlock.java index 517bad963..0051252d3 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/AbstractStorageBlock.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/AbstractStorageBlock.java @@ -12,7 +12,7 @@ import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -abstract class AbstractStorageBlock> extends AbstractBaseBlock +abstract class AbstractStorageBlock extends AbstractBaseBlock implements EntityBlock { private final AbstractBlockEntityTicker ticker; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/AbstractStorageBlockBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/AbstractStorageBlockBlockEntity.java index 09d3016f0..2415a1c8d 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/AbstractStorageBlockBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/AbstractStorageBlockBlockEntity.java @@ -27,8 +27,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -abstract class AbstractStorageBlockBlockEntity - extends AbstractRedstoneModeNetworkNodeContainerBlockEntity> +abstract class AbstractStorageBlockBlockEntity + extends AbstractRedstoneModeNetworkNodeContainerBlockEntity implements ExtendedMenuProvider, ItemTransferableStorageBlockEntity { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractStorageBlockBlockEntity.class); @@ -43,13 +43,13 @@ abstract class AbstractStorageBlockBlockEntity protected AbstractStorageBlockBlockEntity(final BlockEntityType type, final BlockPos pos, final BlockState state, - final StorageNetworkNode node, - final ResourceFactory resourceFactory) { + final StorageNetworkNode node, + final ResourceFactory resourceFactory) { super(type, pos, state, node); - this.filter = FilterWithFuzzyMode.createAndListenForUniqueTemplates( + this.filter = FilterWithFuzzyMode.createAndListenForUniqueFilters( ResourceContainerImpl.createForFilter(resourceFactory), this::setChanged, - templates -> getNode().setFilterTemplates(templates) + filters -> getNode().setFilters(filters) ); this.configContainer = new StorageConfigurationContainerImpl( getNode(), @@ -61,10 +61,9 @@ protected AbstractStorageBlockBlockEntity(final BlockEntityType type, getNode().setNormalizer(filter.createNormalizer()); } - protected abstract Storage createStorage(Runnable listener); + protected abstract Storage createStorage(Runnable listener); @Override - @SuppressWarnings("unchecked") public void setLevel(final Level level) { super.setLevel(level); if (level.isClientSide()) { @@ -79,13 +78,13 @@ public void setLevel(final Level level) { // (#setLevel(Level) -> #modifyStorageAfterAlreadyInitialized(UUID)). // In both cases listed above we need to clean up the storage we create here. storageId = UUID.randomUUID(); - final Storage storage = createStorage(storageRepository::markAsChanged); + final Storage storage = createStorage(storageRepository::markAsChanged); storageRepository.set(storageId, storage); getNode().setStorage(storage); } else { // The existing block entity got loaded in the level (#load(CompoundTag) -> #setLevel(Level)). storageRepository.get(storageId).ifPresentOrElse( - storage -> getNode().setStorage((Storage) storage), + storage -> getNode().setStorage(storage), () -> LOGGER.warn("Storage {} could not be resolved", storageId) ); } @@ -126,7 +125,6 @@ public void readConfiguration(final CompoundTag tag) { filter.load(tag); } - @SuppressWarnings("unchecked") private void cleanupUnneededInitialStorageAndReinitialize(final UUID actualStorageId) { // We got placed through NBT (#setLevel(Level) -> #load(CompoundTag)), or, // we got placed with an existing storage ID (#setLevel(Level) -> modifyStorageAfterAlreadyInitialized(UUID)). @@ -138,7 +136,7 @@ private void cleanupUnneededInitialStorageAndReinitialize(final UUID actualStora () -> LOGGER.warn("Unneeded storage {} could not be removed", storageId) ); storageRepository.get(actualStorageId).ifPresentOrElse( - storage -> getNode().setStorage((Storage) storage), + storage -> getNode().setStorage(storage), () -> LOGGER.warn("Actual storage ID {} could not be resolved!", actualStorageId) ); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/AbstractStorageBlockContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/AbstractStorageBlockContainerMenu.java index a3cd05fa1..68dbf8fdd 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/AbstractStorageBlockContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/AbstractStorageBlockContainerMenu.java @@ -23,11 +23,11 @@ public abstract class AbstractStorageBlockContainerMenu extends AbstractStorageC private long stored; private long capacity; - protected AbstractStorageBlockContainerMenu(final MenuType type, - final int syncId, - final Player player, - final FriendlyByteBuf buf, - final ResourceFactory resourceFactory) { + protected AbstractStorageBlockContainerMenu(final MenuType type, + final int syncId, + final Player player, + final FriendlyByteBuf buf, + final ResourceFactory resourceFactory) { super(type, syncId); this.stored = buf.readLong(); this.capacity = buf.readLong(); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/FluidStorageBlockBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/FluidStorageBlockBlockEntity.java index b80290bcd..412d4d87a 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/FluidStorageBlockBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/FluidStorageBlockBlockEntity.java @@ -3,12 +3,10 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.storage.StorageNetworkNode; import com.refinedmods.refinedstorage2.api.storage.Storage; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; import com.refinedmods.refinedstorage2.platform.common.storage.FluidStorageType; import com.refinedmods.refinedstorage2.platform.common.storage.StorageTypes; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; @@ -19,7 +17,7 @@ import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; -public class FluidStorageBlockBlockEntity extends AbstractStorageBlockBlockEntity { +public class FluidStorageBlockBlockEntity extends AbstractStorageBlockBlockEntity { private final FluidStorageType.Variant variant; private final Component displayName; @@ -30,7 +28,7 @@ public FluidStorageBlockBlockEntity(final BlockPos pos, BlockEntities.INSTANCE.getFluidStorageBlock(variant), pos, state, - new StorageNetworkNode<>(getEnergyUsage(variant), StorageChannelTypes.FLUID), + new StorageNetworkNode(getEnergyUsage(variant)), PlatformApi.INSTANCE.getFluidResourceFactory() ); this.variant = variant; @@ -52,7 +50,7 @@ private static long getEnergyUsage(final FluidStorageType.Variant variant) { } @Override - protected Storage createStorage(final Runnable listener) { + protected Storage createStorage(final Runnable listener) { return StorageTypes.FLUID.create(variant.getCapacity(), listener); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/ItemStorageBlockBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/ItemStorageBlockBlockEntity.java index f77c3642c..397d572ba 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/ItemStorageBlockBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storageblock/ItemStorageBlockBlockEntity.java @@ -3,12 +3,10 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.storage.StorageNetworkNode; import com.refinedmods.refinedstorage2.api.storage.Storage; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; import com.refinedmods.refinedstorage2.platform.common.storage.ItemStorageType; import com.refinedmods.refinedstorage2.platform.common.storage.StorageTypes; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; @@ -19,7 +17,7 @@ import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; -public class ItemStorageBlockBlockEntity extends AbstractStorageBlockBlockEntity { +public class ItemStorageBlockBlockEntity extends AbstractStorageBlockBlockEntity { private final ItemStorageType.Variant variant; private final Component displayName; @@ -30,7 +28,7 @@ public ItemStorageBlockBlockEntity(final BlockPos pos, BlockEntities.INSTANCE.getItemStorageBlock(variant), pos, state, - new StorageNetworkNode<>(getEnergyUsage(variant), StorageChannelTypes.ITEM), + new StorageNetworkNode(getEnergyUsage(variant)), PlatformApi.INSTANCE.getItemResourceFactory() ); this.variant = variant; @@ -48,7 +46,7 @@ private static long getEnergyUsage(final ItemStorageType.Variant variant) { } @Override - protected Storage createStorage(final Runnable listener) { + protected Storage createStorage(final Runnable listener) { return StorageTypes.ITEM.create(variant.getCapacity(), listener); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storagedisk/FluidStorageDiskItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storagedisk/FluidStorageDiskItem.java index c385d496a..ebc6260a9 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storagedisk/FluidStorageDiskItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storagedisk/FluidStorageDiskItem.java @@ -4,11 +4,9 @@ import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.storage.AbstractStorageContainerItem; import com.refinedmods.refinedstorage2.platform.api.storage.StorageRepository; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.common.content.Items; import com.refinedmods.refinedstorage2.platform.common.storage.FluidStorageType; import com.refinedmods.refinedstorage2.platform.common.storage.StorageTypes; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResourceRendering; import javax.annotation.Nullable; @@ -16,13 +14,12 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -public class FluidStorageDiskItem extends AbstractStorageContainerItem { +public class FluidStorageDiskItem extends AbstractStorageContainerItem { private final FluidStorageType.Variant variant; public FluidStorageDiskItem(final FluidStorageType.Variant variant) { super( new Item.Properties().stacksTo(1).fireResistant(), - StorageChannelTypes.FLUID, PlatformApi.INSTANCE.getStorageContainerItemHelper() ); this.variant = variant; @@ -39,7 +36,7 @@ protected String formatAmount(final long amount) { } @Override - protected Storage createStorage(final StorageRepository storageRepository) { + protected Storage createStorage(final StorageRepository storageRepository) { return StorageTypes.FLUID.create(variant.getCapacity(), storageRepository::markAsChanged); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storagedisk/ItemStorageDiskItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storagedisk/ItemStorageDiskItem.java index f2d696c56..d2aec853b 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storagedisk/ItemStorageDiskItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/storagedisk/ItemStorageDiskItem.java @@ -5,24 +5,21 @@ import com.refinedmods.refinedstorage2.platform.api.storage.AbstractStorageContainerItem; import com.refinedmods.refinedstorage2.platform.api.storage.StorageRepository; import com.refinedmods.refinedstorage2.platform.api.support.AmountFormatting; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.content.Items; import com.refinedmods.refinedstorage2.platform.common.storage.ItemStorageType; import com.refinedmods.refinedstorage2.platform.common.storage.StorageTypes; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import javax.annotation.Nullable; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -public class ItemStorageDiskItem extends AbstractStorageContainerItem { +public class ItemStorageDiskItem extends AbstractStorageContainerItem { private final ItemStorageType.Variant variant; public ItemStorageDiskItem(final ItemStorageType.Variant variant) { super( new Item.Properties().stacksTo(1).fireResistant(), - StorageChannelTypes.ITEM, PlatformApi.INSTANCE.getStorageContainerItemHelper() ); this.variant = variant; @@ -39,7 +36,7 @@ protected String formatAmount(final long amount) { } @Override - protected Storage createStorage(final StorageRepository storageRepository) { + protected Storage createStorage(final StorageRepository storageRepository) { return StorageTypes.ITEM.create(variant.getCapacity(), storageRepository::markAsChanged); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/CompositeStorageMonitorExtractionStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/CompositeStorageMonitorExtractionStrategy.java index 05367d735..521a8a8b3 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/CompositeStorageMonitorExtractionStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/CompositeStorageMonitorExtractionStrategy.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.storagemonitor; import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.platform.api.storagemonitor.StorageMonitorExtractionStrategy; @@ -17,7 +18,7 @@ public void addStrategy(final StorageMonitorExtractionStrategy strategy) { } @Override - public boolean extract(final Object resource, + public boolean extract(final ResourceKey resource, final boolean fullStack, final Player player, final Actor actor, diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/CompositeStorageMonitorInsertionStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/CompositeStorageMonitorInsertionStrategy.java index 31e9c8f30..8236527d8 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/CompositeStorageMonitorInsertionStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/CompositeStorageMonitorInsertionStrategy.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.storagemonitor; import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.platform.api.storagemonitor.StorageMonitorInsertionStrategy; @@ -19,7 +20,7 @@ public void addStrategy(final StorageMonitorInsertionStrategy strategy) { @Override public Optional insert( - final Object configuredResource, + final ResourceKey configuredResource, final ItemStack stack, final Actor actor, final Network network diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/FluidStorageMonitorExtractionStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/FluidStorageMonitorExtractionStrategy.java index 77d48a9df..87329091f 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/FluidStorageMonitorExtractionStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/FluidStorageMonitorExtractionStrategy.java @@ -2,20 +2,20 @@ import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.TransferHelper; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.platform.api.storagemonitor.StorageMonitorExtractionStrategy; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.storage.BucketPlayerInventoryInsertableStorage; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import net.minecraft.world.entity.player.Player; public class FluidStorageMonitorExtractionStrategy implements StorageMonitorExtractionStrategy { @Override - public boolean extract(final Object resource, + public boolean extract(final ResourceKey resource, final boolean fullStack, final Player player, final Actor actor, @@ -25,11 +25,10 @@ public boolean extract(final Object resource, } final BucketPlayerInventoryInsertableStorage target = new BucketPlayerInventoryInsertableStorage( player.getInventory(), - network.getComponent(StorageNetworkComponent.class).getStorageChannel(StorageChannelTypes.ITEM), + network.getComponent(StorageNetworkComponent.class), true ); - final StorageChannel source = network.getComponent(StorageNetworkComponent.class) - .getStorageChannel(StorageChannelTypes.FLUID); + final StorageChannel source = network.getComponent(StorageNetworkComponent.class); return TransferHelper.transfer( fluidResource, Platform.INSTANCE.getBucketAmount(), diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/FluidStorageMonitorInsertionStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/FluidStorageMonitorInsertionStrategy.java index 3f7319673..1c428973b 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/FluidStorageMonitorInsertionStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/FluidStorageMonitorInsertionStrategy.java @@ -3,13 +3,12 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; -import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.platform.api.storagemonitor.StorageMonitorInsertionStrategy; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.common.Platform; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import java.util.Optional; import javax.annotation.Nullable; @@ -19,7 +18,7 @@ public class FluidStorageMonitorInsertionStrategy implements StorageMonitorInsertionStrategy { @Override public Optional insert( - final Object configuredResource, + final ResourceKey configuredResource, final ItemStack stack, final Actor actor, final Network network @@ -27,8 +26,7 @@ public Optional insert( if (!(configuredResource instanceof FluidResource configuredFluidResource)) { return Optional.empty(); } - final StorageChannel fluidStorageChannel = network.getComponent(StorageNetworkComponent.class) - .getStorageChannel(StorageChannelTypes.FLUID); + final StorageChannel fluidStorageChannel = network.getComponent(StorageNetworkComponent.class); return Platform.INSTANCE.getContainedFluid(stack) .map(extracted -> tryInsert(actor, configuredFluidResource, extracted, fluidStorageChannel)) .map(extracted -> doInsert(actor, extracted, fluidStorageChannel)); @@ -38,28 +36,26 @@ public Optional insert( private Platform.ContainedFluid tryInsert(final Actor actor, final FluidResource configuredResource, final Platform.ContainedFluid result, - final StorageChannel storageChannel) { - final ResourceAmount fluid = result.fluid(); - if (!fluid.getResource().equals(configuredResource)) { + final StorageChannel storageChannel) { + if (!result.fluid().equals(configuredResource)) { return null; } final long insertedSimulated = storageChannel.insert( - fluid.getResource(), - fluid.getAmount(), + result.fluid(), + result.amount(), Action.SIMULATE, actor ); - final boolean insertedSuccessfully = insertedSimulated == fluid.getAmount(); + final boolean insertedSuccessfully = insertedSimulated == result.amount(); return insertedSuccessfully ? result : null; } private ItemStack doInsert(final Actor actor, final Platform.ContainedFluid extracted, - final StorageChannel storageChannel) { - final ResourceAmount fluid = extracted.fluid(); + final StorageChannel storageChannel) { storageChannel.insert( - fluid.getResource(), - fluid.getAmount(), + extracted.fluid(), + extracted.amount(), Action.EXECUTE, actor ); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/ItemStorageMonitorExtractionStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/ItemStorageMonitorExtractionStrategy.java index 0cf8a8c9a..3c3a48991 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/ItemStorageMonitorExtractionStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/ItemStorageMonitorExtractionStrategy.java @@ -3,17 +3,17 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.platform.api.storagemonitor.StorageMonitorExtractionStrategy; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; public class ItemStorageMonitorExtractionStrategy implements StorageMonitorExtractionStrategy { @Override - public boolean extract(final Object resource, + public boolean extract(final ResourceKey resource, final boolean fullStack, final Player player, final Actor actor, @@ -21,9 +21,12 @@ public boolean extract(final Object resource, if (!(resource instanceof ItemResource itemResource)) { return false; } - final long extracted = network.getComponent(StorageNetworkComponent.class) - .getStorageChannel(StorageChannelTypes.ITEM) - .extract(itemResource, fullStack ? itemResource.item().getMaxStackSize() : 1, Action.EXECUTE, actor); + final long extracted = network.getComponent(StorageNetworkComponent.class).extract( + itemResource, + fullStack ? itemResource.item().getMaxStackSize() : 1, + Action.EXECUTE, + actor + ); if (extracted > 0) { final ItemStack stack = itemResource.toItemStack(extracted); if (!player.getInventory().add(stack)) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/ItemStorageMonitorInsertionStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/ItemStorageMonitorInsertionStrategy.java index 82ccb5cca..2eb65b710 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/ItemStorageMonitorInsertionStrategy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/ItemStorageMonitorInsertionStrategy.java @@ -3,10 +3,10 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.platform.api.storagemonitor.StorageMonitorInsertionStrategy; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.Optional; @@ -14,7 +14,7 @@ public class ItemStorageMonitorInsertionStrategy implements StorageMonitorInsertionStrategy { @Override - public Optional insert(final Object configuredResource, + public Optional insert(final ResourceKey configuredResource, final ItemStack stack, final Actor actor, final Network network) { @@ -25,9 +25,12 @@ public Optional insert(final Object configuredResource, if (!configuredItemResource.equals(resource)) { return Optional.empty(); } - final long inserted = network.getComponent(StorageNetworkComponent.class) - .getStorageChannel(StorageChannelTypes.ITEM) - .insert(resource, stack.getCount(), Action.EXECUTE, actor); + final long inserted = network.getComponent(StorageNetworkComponent.class).insert( + resource, + stack.getCount(), + Action.EXECUTE, + actor + ); final long remainder = stack.getCount() - inserted; if (remainder > 0) { return Optional.of(resource.toItemStack(remainder)); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/StorageMonitorBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/StorageMonitorBlockEntity.java index 72f365509..9e76ff199 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/StorageMonitorBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/StorageMonitorBlockEntity.java @@ -4,12 +4,11 @@ import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; import com.refinedmods.refinedstorage2.api.network.impl.node.SimpleNetworkNode; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; import com.refinedmods.refinedstorage2.platform.api.storage.channel.FuzzyStorageChannel; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceContainer; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; @@ -18,6 +17,7 @@ import com.refinedmods.refinedstorage2.platform.common.support.FilterWithFuzzyMode; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.ExtendedMenuProvider; import com.refinedmods.refinedstorage2.platform.common.support.network.AbstractRedstoneModeNetworkNodeContainerBlockEntity; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceContainerImpl; import javax.annotation.Nullable; @@ -86,24 +86,23 @@ private void trySendDisplayUpdate(final Level level) { } private long getAmount() { - final ResourceAmountTemplate template = filter.getFilterContainer().get(0); - if (template == null) { + final ResourceKey configuredResource = getConfiguredResource(); + if (configuredResource == null) { return 0; } final Network network = getNode().getNetwork(); if (network == null) { return 0; } - return getAmount(network, template); + return getAmount(network, configuredResource); } - private long getAmount(final Network network, final ResourceAmountTemplate template) { - final StorageChannel storageChannel = network.getComponent(StorageNetworkComponent.class) - .getStorageChannel(template.getStorageChannelType()); - if (!filter.isFuzzyMode() || !(storageChannel instanceof FuzzyStorageChannel fuzzyStorageChannel)) { - return storageChannel.get(template.getResource()).map(ResourceAmount::getAmount).orElse(0L); + private long getAmount(final Network network, final ResourceKey configuredResource) { + final StorageChannel storageChannel = network.getComponent(StorageNetworkComponent.class); + if (!filter.isFuzzyMode() || !(storageChannel instanceof FuzzyStorageChannel fuzzyStorageChannel)) { + return storageChannel.get(configuredResource).map(ResourceAmount::getAmount).orElse(0L); } - return fuzzyStorageChannel.getFuzzy(template.getResource()).stream().mapToLong(ResourceAmount::getAmount).sum(); + return fuzzyStorageChannel.getFuzzy(configuredResource).stream().mapToLong(ResourceAmount::getAmount).sum(); } public void extract(final Player player) { @@ -114,21 +113,21 @@ public void extract(final Player player) { if (network == null) { return; } - final ResourceAmountTemplate template = getFilteredResource(); - if (template == null) { + final ResourceKey configuredResource = getConfiguredResource(); + if (configuredResource == null) { return; } - extract(level, player, template.getResource(), network); + doExtract(level, player, configuredResource, network); } - private void extract( + private void doExtract( final Level level, final Player player, - final T template, + final ResourceKey configuredResource, final Network network ) { final boolean success = PlatformApi.INSTANCE.getStorageMonitorExtractionStrategy().extract( - template, + configuredResource, !player.isShiftKeyDown(), player, new PlayerActor(player), @@ -159,26 +158,26 @@ private boolean doInsert(final Player player, final InteractionHand hand) { if (network == null) { return false; } - final ResourceAmountTemplate template = getFilteredResource(); - if (template == null) { + final ResourceKey configuredResource = getConfiguredResource(); + if (configuredResource == null) { return false; } final ItemStack heldStack = player.getItemInHand(hand); if (heldStack.isEmpty()) { return doInsertAll(player); } - return doInsert(player, hand, heldStack, template.getResource(), network); + return doInsert(player, hand, heldStack, configuredResource, network); } - private boolean doInsert( + private boolean doInsert( final Player player, final InteractionHand hand, final ItemStack heldStack, - final T template, + final ResourceKey configuredResource, final Network network ) { return PlatformApi.INSTANCE.getStorageMonitorInsertionStrategy().insert( - template, + configuredResource, heldStack, new PlayerActor(player), network @@ -200,22 +199,22 @@ private boolean doInsertAll(final Player player, final ItemResource lastInserted if (network == null) { return false; } - final ResourceAmountTemplate template = getFilteredResource(); - if (template == null) { + final ResourceKey configuredResource = getConfiguredResource(); + if (configuredResource == null) { return false; } boolean success = false; for (int i = 0; i < player.getInventory().getContainerSize(); ++i) { - success |= tryInsertSlot(player, lastInsertedItem, i, template.getResource(), network); + success |= tryInsertSlot(player, lastInsertedItem, i, configuredResource, network); } return success; } - private boolean tryInsertSlot( + private boolean tryInsertSlot( final Player player, final ItemResource lastInsertedItem, final int inventorySlotIndex, - final T template, + final ResourceKey configuredResource, final Network network ) { final ItemStack slot = player.getInventory().getItem(inventorySlotIndex); @@ -227,7 +226,7 @@ private boolean tryInsertSlot( return false; } return PlatformApi.INSTANCE.getStorageMonitorInsertionStrategy().insert( - template, + configuredResource, slot, new PlayerActor(player), network @@ -246,8 +245,8 @@ public void setFuzzyMode(final boolean fuzzyMode) { } @Nullable - public ResourceAmountTemplate getFilteredResource() { - return filter.getFilterContainer().get(0); + public ResourceKey getConfiguredResource() { + return filter.getFilterContainer().getResource(0); } public long getCurrentAmount() { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/StorageMonitorBlockEntityRenderer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/StorageMonitorBlockEntityRenderer.java index dfc29ce40..0a24f4ef0 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/StorageMonitorBlockEntityRenderer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/StorageMonitorBlockEntityRenderer.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.storagemonitor; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceRendering; import com.refinedmods.refinedstorage2.platform.common.support.direction.BiDirection; import com.refinedmods.refinedstorage2.platform.common.support.direction.BiDirectionType; @@ -41,8 +41,8 @@ public void render(final StorageMonitorBlockEntity blockEntity, if (!blockEntity.isCurrentlyActive()) { return; } - final ResourceAmountTemplate template = blockEntity.getFilteredResource(); - if (template == null) { + final ResourceKey resource = blockEntity.getConfiguredResource(); + if (resource == null) { return; } doRender( @@ -50,20 +50,18 @@ public void render(final StorageMonitorBlockEntity blockEntity, poseStack, vertexConsumers, direction, - template, + resource, blockEntity.getCurrentAmount() ); } - private void doRender(final Level level, - final PoseStack poseStack, - final MultiBufferSource vertexConsumers, - final BiDirection direction, - final ResourceAmountTemplate template, - final long amount) { - final ResourceRendering resourceRendering = PlatformApi.INSTANCE.getResourceRendering( - template.getResource() - ); + private void doRender(final Level level, + final PoseStack poseStack, + final MultiBufferSource vertexConsumers, + final BiDirection direction, + final ResourceKey resource, + final long amount) { + final ResourceRendering resourceRendering = PlatformApi.INSTANCE.getResourceRendering(resource); doRender( poseStack, vertexConsumers, @@ -71,17 +69,17 @@ private void doRender(final Level level, resourceRendering.getDisplayedAmount(amount, false), level, resourceRendering, - template.getResource() + resource ); } - private void doRender(final PoseStack poseStack, - final MultiBufferSource renderTypeBuffer, - final Quaternionf rotation, - final String amount, - final Level level, - final ResourceRendering resourceRendering, - final T resource) { + private void doRender(final PoseStack poseStack, + final MultiBufferSource renderTypeBuffer, + final Quaternionf rotation, + final String amount, + final Level level, + final ResourceRendering resourceRendering, + final ResourceKey resource) { poseStack.pushPose(); poseStack.translate(0.5, 0.5, 0.5); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/StorageMonitorInsertTracker.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/StorageMonitorInsertTracker.java index 61deefca7..7fa430dfe 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/StorageMonitorInsertTracker.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storagemonitor/StorageMonitorInsertTracker.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.storagemonitor; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.HashMap; import java.util.Map; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/AbstractBaseScreen.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/AbstractBaseScreen.java index 02575acb7..cfc317897 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/AbstractBaseScreen.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/AbstractBaseScreen.java @@ -1,8 +1,8 @@ package com.refinedmods.refinedstorage2.platform.common.support; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceFactory; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceRendering; import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeMapping; @@ -20,7 +20,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.Objects; import java.util.stream.Collectors; import javax.annotation.Nullable; @@ -37,6 +36,7 @@ import net.minecraft.world.item.ItemStack; import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslationAsHeading; +import static java.util.Objects.requireNonNullElse; public abstract class AbstractBaseScreen extends AbstractContainerScreen { private static final SmallTextClientTooltipComponent CLICK_TO_CLEAR = new SmallTextClientTooltipComponent( @@ -102,44 +102,44 @@ protected final void renderResourceSlots(final GuiGraphics graphics) { } private void tryRenderResourceSlot(final GuiGraphics graphics, final ResourceSlot slot) { - final ResourceAmountTemplate resourceAmount = slot.getResourceAmount(); - if (resourceAmount == null) { + final ResourceKey resource = slot.getResource(); + if (resource == null) { return; } renderResourceSlot( graphics, leftPos + slot.x, topPos + slot.y, - resourceAmount, + resource, + slot.getAmount(), slot.shouldRenderAmount() ); } - private void renderResourceSlot(final GuiGraphics graphics, - final int x, - final int y, - final ResourceAmountTemplate resourceAmount, - final boolean renderAmount) { - final ResourceRendering rendering = PlatformApi.INSTANCE.getResourceRendering( - resourceAmount.getResource() - ); - rendering.render(resourceAmount.getResource(), graphics, x, y); + private void renderResourceSlot(final GuiGraphics graphics, + final int x, + final int y, + final ResourceKey resource, + final long amount, + final boolean renderAmount) { + final ResourceRendering rendering = PlatformApi.INSTANCE.getResourceRendering(resource); + rendering.render(resource, graphics, x, y); if (renderAmount) { - renderResourceSlotAmount(graphics, x, y, resourceAmount.getAmount(), rendering); + renderResourceSlotAmount(graphics, x, y, amount, rendering); } } - private void renderResourceSlotAmount(final GuiGraphics graphics, - final int x, - final int y, - final long amount, - final ResourceRendering rendering) { + private void renderResourceSlotAmount(final GuiGraphics graphics, + final int x, + final int y, + final long amount, + final ResourceRendering rendering) { renderAmount( graphics, x, y, rendering.getDisplayedAmount(amount, true), - Objects.requireNonNullElse(ChatFormatting.WHITE.getColor(), 15), + requireNonNullElse(ChatFormatting.WHITE.getColor(), 15), true ); } @@ -207,11 +207,11 @@ private List getUpgradeTooltip(final ItemStack carried, } public List getResourceTooltip(final ItemStack carried, final ResourceSlot resourceSlot) { - final ResourceAmountTemplate resourceAmount = resourceSlot.getResourceAmount(); - if (resourceAmount == null) { + final ResourceKey resource = resourceSlot.getResource(); + if (resource == null) { return getTooltipForEmptySlot(carried, resourceSlot); } - return getTooltipForResource(resourceAmount, resourceSlot); + return getTooltipForResource(resource, resourceSlot); } private List getTooltipForEmptySlot(final ItemStack carried, @@ -239,7 +239,7 @@ private List getResourceSlotHelpTooltip(final ItemStack null ) )); - for (final ResourceFactory alternativeResourceFactory : resourceSlot.getAlternativeResourceFactories()) { + for (final ResourceFactory alternativeResourceFactory : resourceSlot.getAlternativeResourceFactories()) { final var result = alternativeResourceFactory.create(carried); result.ifPresent(alternativeResourceInstance -> lines.add(new MouseWithIconClientTooltipComponent( MouseWithIconClientTooltipComponent.Type.RIGHT, @@ -250,15 +250,15 @@ private List getResourceSlotHelpTooltip(final ItemStack return lines; } - public static MouseWithIconClientTooltipComponent.IconRenderer getResourceRendering(final T resource) { + public static MouseWithIconClientTooltipComponent.IconRenderer getResourceRendering(final ResourceKey resource) { return (graphics, x, y) -> PlatformApi.INSTANCE.getResourceRendering(resource).render(resource, graphics, x, y); } - private List getTooltipForResource(final ResourceAmountTemplate resourceAmount, - final ResourceSlot resourceSlot) { + private List getTooltipForResource(final ResourceKey resource, + final ResourceSlot resourceSlot) { final List tooltip = PlatformApi.INSTANCE - .getResourceRendering(resourceAmount.getResource()) - .getTooltip(resourceAmount.getResource()) + .getResourceRendering(resource) + .getTooltip(resource) .stream() .map(Component::getVisualOrderText) .map(ClientTooltipComponent::create) @@ -284,7 +284,7 @@ && getMenu() instanceof AbstractResourceContainerMenu containerMenu) { } private boolean tryOpenResourceAmountScreen(final ResourceSlot slot) { - final boolean isFilterSlot = slot.getResourceAmount() != null; + final boolean isFilterSlot = slot.getResource() != null; final boolean canModifyAmount = isFilterSlot && slot.canModifyAmount(); final boolean isNotTryingToRemoveFilter = !hasShiftDown(); final boolean isNotCarryingItem = getMenu().getCarried().isEmpty(); @@ -297,10 +297,11 @@ private boolean tryOpenResourceAmountScreen(final ResourceSlot slot) { } @Nullable - public ResourceTemplate getHoveredResource() { - return hoveredSlot instanceof ResourceSlot resourceSlot && resourceSlot.getResourceAmount() != null - ? resourceSlot.getResourceAmount().getResourceTemplate() - : null; + public PlatformResourceKey getHoveredResource() { + if (hoveredSlot instanceof ResourceSlot resourceSlot) { + return resourceSlot.getResource(); + } + return null; } public int getLeftPos() { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/ClientToServerCommunications.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/ClientToServerCommunications.java index a16489164..5aeca9c19 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/ClientToServerCommunications.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/ClientToServerCommunications.java @@ -3,24 +3,18 @@ import com.refinedmods.refinedstorage2.api.grid.operations.GridExtractMode; import com.refinedmods.refinedstorage2.api.grid.operations.GridInsertMode; import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollMode; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; import com.refinedmods.refinedstorage2.platform.api.support.network.bounditem.SlotReference; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.PropertyType; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.List; import java.util.UUID; public interface ClientToServerCommunications { - void sendGridExtract(PlatformStorageChannelType storageChannelType, - T resource, - GridExtractMode mode, - boolean cursor); + void sendGridExtract(PlatformResourceKey resource, GridExtractMode mode, boolean cursor); - void sendGridScroll(PlatformStorageChannelType storageChannelType, - T resource, - GridScrollMode mode, - int slotIndex); + void sendGridScroll(PlatformResourceKey resource, GridScrollMode mode, int slotIndex); void sendGridInsert(GridInsertMode mode, boolean tryAlternatives); @@ -34,7 +28,7 @@ void sendGridScroll(PlatformStorageChannelType storageChannelType, void sendResourceSlotChange(int slotIndex, boolean tryAlternatives); - void sendResourceFilterSlotChange(PlatformStorageChannelType storageChannelType, T resource, int slotIndex); + void sendResourceFilterSlotChange(PlatformResourceKey resource, int slotIndex); void sendResourceSlotAmountChange(int slotIndex, long amount); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/FilterModeSettings.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/FilterModeSettings.java index c63f1141e..a545b0fcb 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/FilterModeSettings.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/FilterModeSettings.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.support; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; public class FilterModeSettings { private static final int BLOCK = 0; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/FilterWithFuzzyMode.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/FilterWithFuzzyMode.java index 0b43296d7..8008773f9 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/FilterWithFuzzyMode.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/FilterWithFuzzyMode.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.support; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.support.resource.FuzzyModeNormalizer; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceContainer; @@ -20,20 +20,20 @@ public final class FilterWithFuzzyMode { @Nullable private final Runnable listener; @Nullable - private final Consumer> uniqueTemplateListener; + private final Consumer> uniqueFilterListener; @Nullable - private final Consumer>> templateListener; + private final Consumer> filterListener; private boolean fuzzyMode; private FilterWithFuzzyMode(final ResourceContainer filterContainer, @Nullable final Runnable listener, - @Nullable final Consumer> uniqueTemplateListener, - @Nullable final Consumer>> templateListener) { + @Nullable final Consumer> uniqueFilterListener, + @Nullable final Consumer> filterListener) { this.filterContainer = filterContainer; this.listener = listener; - this.uniqueTemplateListener = uniqueTemplateListener; - this.templateListener = templateListener; + this.uniqueFilterListener = uniqueFilterListener; + this.filterListener = filterListener; this.filterContainer.setListener(this::filterContainerChanged); } @@ -54,7 +54,7 @@ public boolean isFuzzyMode() { public void setFuzzyMode(final boolean fuzzyMode) { this.fuzzyMode = fuzzyMode; - // We need to reload the templates as the normalizer will give different outputs now. + // We need to reload the filters as the normalizer will give different outputs now. notifyListeners(); if (listener != null) { listener.run(); @@ -72,11 +72,11 @@ public void load(final CompoundTag tag) { } private void notifyListeners() { - if (uniqueTemplateListener != null) { - uniqueTemplateListener.accept(filterContainer.getUniqueTemplates()); + if (uniqueFilterListener != null) { + uniqueFilterListener.accept(filterContainer.getUniqueResources()); } - if (templateListener != null) { - templateListener.accept(filterContainer.getTemplates()); + if (filterListener != null) { + filterListener.accept(filterContainer.getResources()); } } @@ -85,12 +85,12 @@ public void save(final CompoundTag tag) { tag.put(TAG_RESOURCE_FILTER, filterContainer.toTag()); } - public UnaryOperator createNormalizer() { + public UnaryOperator createNormalizer() { return value -> { if (!fuzzyMode) { return value; } - if (value instanceof FuzzyModeNormalizer normalizer) { + if (value instanceof FuzzyModeNormalizer normalizer) { return normalizer.normalize(); } return value; @@ -102,19 +102,19 @@ public static FilterWithFuzzyMode create(final ResourceContainer resourceContain return new FilterWithFuzzyMode(resourceContainer, listener, null, null); } - public static FilterWithFuzzyMode createAndListenForTemplates( + public static FilterWithFuzzyMode createAndListenForFilters( final ResourceContainer resourceContainer, final Runnable listener, - final Consumer>> templateListener + final Consumer> filterListener ) { - return new FilterWithFuzzyMode(resourceContainer, listener, null, templateListener); + return new FilterWithFuzzyMode(resourceContainer, listener, null, filterListener); } - public static FilterWithFuzzyMode createAndListenForUniqueTemplates( + public static FilterWithFuzzyMode createAndListenForUniqueFilters( final ResourceContainer resourceContainer, final Runnable listener, - final Consumer> templateListener + final Consumer> filterListener ) { - return new FilterWithFuzzyMode(resourceContainer, listener, templateListener, null); + return new FilterWithFuzzyMode(resourceContainer, listener, filterListener, null); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/ServerToClientCommunications.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/ServerToClientCommunications.java index 8eeb6223a..ac865be62 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/ServerToClientCommunications.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/ServerToClientCommunications.java @@ -1,9 +1,9 @@ package com.refinedmods.refinedstorage2.platform.common.support; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import com.refinedmods.refinedstorage2.platform.api.storage.StorageInfo; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.networking.NetworkTransmitterStatus; import java.util.UUID; @@ -18,17 +18,16 @@ public interface ServerToClientCommunications { void sendGridActiveness(ServerPlayer player, boolean active); - void sendGridUpdate(ServerPlayer player, - PlatformStorageChannelType storageChannelType, - T resource, - long change, - @Nullable TrackedResource trackedResource); + void sendGridUpdate(ServerPlayer player, + PlatformResourceKey resource, + long change, + @Nullable TrackedResource trackedResource); void sendGridClear(ServerPlayer player); - void sendResourceSlotUpdate(ServerPlayer player, - @Nullable ResourceAmountTemplate resourceAmount, - int slotIndex); + void sendResourceSlotUpdate(ServerPlayer player, + @Nullable ResourceAmount resourceAmount, + int slotIndex); void sendStorageInfoResponse(ServerPlayer player, UUID id, StorageInfo storageInfo); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/containermenu/AbstractResourceContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/containermenu/AbstractResourceContainerMenu.java index 6d8018e6a..a979f3513 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/containermenu/AbstractResourceContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/containermenu/AbstractResourceContainerMenu.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.support.containermenu; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.support.AbstractBaseContainerMenu; @@ -47,16 +47,12 @@ private Optional getResourceSlot(final int slotIndex) { return Optional.empty(); } - public void handleResourceSlotUpdate(final int slotIndex, - @Nullable final ResourceAmountTemplate resourceAmount) { + public void handleResourceSlotUpdate(final int slotIndex, @Nullable final ResourceAmount resourceAmount) { getResourceSlot(slotIndex).ifPresent(slot -> slot.change(resourceAmount)); } - - public void handleResourceFilterSlotUpdate(final int slotIndex, - final PlatformStorageChannelType storageChannelType, - final T resource) { - getResourceSlot(slotIndex).ifPresent(slot -> slot.setFilter(storageChannelType, resource)); + public void handleResourceFilterSlotUpdate(final int slotIndex, final PlatformResourceKey resource) { + getResourceSlot(slotIndex).ifPresent(slot -> slot.setFilter(resource)); } public void handleResourceSlotChange(final int slotIndex, final boolean tryAlternatives) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/containermenu/PropertyTypes.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/containermenu/PropertyTypes.java index 11c6f1aad..f7f227a72 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/containermenu/PropertyTypes.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/containermenu/PropertyTypes.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.support.containermenu; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; import com.refinedmods.refinedstorage2.platform.common.support.FilterModeSettings; import com.refinedmods.refinedstorage2.platform.common.support.RedstoneMode; import com.refinedmods.refinedstorage2.platform.common.support.RedstoneModeSettings; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/containermenu/ResourceSlot.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/containermenu/ResourceSlot.java index 4cbacd608..2bf95a802 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/containermenu/ResourceSlot.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/containermenu/ResourceSlot.java @@ -1,7 +1,8 @@ package com.refinedmods.refinedstorage2.platform.common.support.containermenu; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceContainer; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceContainerType; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceFactory; @@ -28,7 +29,7 @@ public class ResourceSlot extends Slot { private final ResourceContainer resourceContainer; private final Component helpText; @Nullable - private ResourceAmountTemplate cachedResource; + private ResourceAmount cachedResource; public ResourceSlot(final ResourceContainer resourceContainer, final int index, @@ -92,19 +93,27 @@ public boolean isDisabled() { } @Nullable - public ResourceAmountTemplate getResourceAmount() { - return resourceContainer.get(getContainerSlot()); + public PlatformResourceKey getResource() { + return resourceContainer.getResource(getContainerSlot()); + } + + public long getAmount() { + return resourceContainer.getAmount(getContainerSlot()); + } + + private ItemStack getStackRepresentation() { + return resourceContainer.getStackRepresentation(getContainerSlot()); } public boolean isEmpty() { - return getResourceAmount() == null; + return resourceContainer.isEmpty(getContainerSlot()); } public void change(final ItemStack stack, final boolean tryAlternatives) { resourceContainer.change(getContainerSlot(), stack, tryAlternatives); } - public void change(@Nullable final ResourceAmountTemplate instance) { + public void change(@Nullable final ResourceAmount instance) { if (instance == null) { resourceContainer.remove(getContainerSlot()); } else { @@ -112,18 +121,17 @@ public void change(@Nullable final ResourceAmountTemplate instance) { } } - public void setFilter(final PlatformStorageChannelType storageChannelType, final T resource) { + public void setFilter(final PlatformResourceKey resource) { if (!isFilter() || !isValid(resource)) { return; } - resourceContainer.set(getContainerSlot(), new ResourceAmountTemplate<>( + resourceContainer.set(getContainerSlot(), new ResourceAmount( resource, - storageChannelType.normalizeAmount(1D), - storageChannelType + resource.getResourceType().normalizeAmount(1D) )); } - public boolean isValid(final T resource) { + public boolean isValid(final ResourceKey resource) { return resourceContainer.isValid(resource); } @@ -143,32 +151,29 @@ public void changeAmount(final long amount) { } public void changeAmountOnClient(final double amount) { - final ResourceAmountTemplate resourceAmount = getResourceAmount(); - if (resourceAmount == null) { + final PlatformResourceKey resource = getResource(); + if (resource == null) { return; } - final long normalizedAmount = resourceAmount.getStorageChannelType().normalizeAmount(amount); + final long normalizedAmount = resource.getResourceType().normalizeAmount(amount); Platform.INSTANCE.getClientToServerCommunications().sendResourceSlotAmountChange(index, normalizedAmount); } public boolean contains(final ItemStack stack) { - final ResourceAmountTemplate resourceAmount = getResourceAmount(); - return resourceAmount != null && ItemStack.matches(stack, resourceAmount.getStackRepresentation()); + return ItemStack.matches(stack, getStackRepresentation()); } public void broadcastChanges(final Player player) { - final ResourceAmountTemplate resourceAmount = getResourceAmount(); - if (!Objects.equals(resourceAmount, cachedResource)) { + final ResourceAmount currentResourceAmount = resourceContainer.get(getContainerSlot()); + if (!Objects.equals(currentResourceAmount, cachedResource)) { LOGGER.debug("Resource slot {} has changed", getContainerSlot()); - this.cachedResource = resourceAmount; - broadcastChange((ServerPlayer) player, resourceAmount); + this.cachedResource = currentResourceAmount; + broadcastChange((ServerPlayer) player, currentResourceAmount); } } - private void broadcastChange(final ServerPlayer player, - @Nullable final ResourceAmountTemplate contents) { - Platform.INSTANCE.getServerToClientCommunications() - .sendResourceSlotUpdate(player, contents, index); + private void broadcastChange(final ServerPlayer player, @Nullable final ResourceAmount contents) { + Platform.INSTANCE.getServerToClientCommunications().sendResourceSlotUpdate(player, contents, index); } public void readFromUpdatePacket(final FriendlyByteBuf buf) { @@ -186,30 +191,30 @@ public boolean mayPlace(final ItemStack stack) { } public double getDisplayAmount() { - final ResourceAmountTemplate resourceAmount = getResourceAmount(); - if (resourceAmount == null) { + final PlatformResourceKey resource = getResource(); + if (resource == null) { return 0; } - return resourceAmount.getStorageChannelType().getDisplayAmount(resourceAmount.getAmount()); + return resource.getResourceType().getDisplayAmount(getAmount()); } public double getMaxAmountWhenModifying() { - final ResourceAmountTemplate resourceAmount = getResourceAmount(); - if (resourceAmount == null) { + final ResourceKey resource = getResource(); + if (resource == null) { return 0; } - return resourceContainer.getMaxAmount(resourceAmount); + return resourceContainer.getMaxAmount(resource); } public Component getHelpText() { return helpText; } - public ResourceFactory getPrimaryResourceFactory() { + public ResourceFactory getPrimaryResourceFactory() { return resourceContainer.getPrimaryResourceFactory(); } - public Set> getAlternativeResourceFactories() { + public Set getAlternativeResourceFactories() { return resourceContainer.getAlternativeResourceFactories(); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/network/AbstractSchedulingNetworkNodeContainerBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/network/AbstractSchedulingNetworkNodeContainerBlockEntity.java index 2de3e849b..069b38d6f 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/network/AbstractSchedulingNetworkNodeContainerBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/network/AbstractSchedulingNetworkNodeContainerBlockEntity.java @@ -2,7 +2,7 @@ import com.refinedmods.refinedstorage2.api.network.node.AbstractNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.task.TaskExecutor; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.common.support.FilterWithFuzzyMode; import com.refinedmods.refinedstorage2.platform.common.support.SchedulingMode; import com.refinedmods.refinedstorage2.platform.common.support.SchedulingModeType; @@ -11,7 +11,6 @@ import com.refinedmods.refinedstorage2.platform.common.upgrade.UpgradeDestinations; import java.util.List; -import java.util.stream.Collectors; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; @@ -36,12 +35,10 @@ protected AbstractSchedulingNetworkNodeContainerBlockEntity( ) { super(type, pos, state, node, destination); this.schedulingMode = new SchedulingMode<>(this::setChanged, this::setTaskExecutor); - this.filter = FilterWithFuzzyMode.createAndListenForTemplates( + this.filter = FilterWithFuzzyMode.createAndListenForFilters( ResourceContainerImpl.createForFilter(), this::setChanged, - templates -> setFilterTemplates( - templates.stream().map(ResourceTemplate::resource).collect(Collectors.toList()) - ) + this::setFilters ); } @@ -85,5 +82,5 @@ public void writeScreenOpeningData(final ServerPlayer player, final FriendlyByte protected abstract void setTaskExecutor(TaskExecutor taskExecutor); - protected abstract void setFilterTemplates(List templates); + protected abstract void setFilters(List filters); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/network/bounditem/CompositeSlotReferenceProvider.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/network/bounditem/CompositeSlotReferenceProvider.java index c955c5157..cce62b3f4 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/network/bounditem/CompositeSlotReferenceProvider.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/network/bounditem/CompositeSlotReferenceProvider.java @@ -7,7 +7,6 @@ import java.util.List; import java.util.Optional; import java.util.Set; -import java.util.stream.Collectors; import net.minecraft.ChatFormatting; import net.minecraft.world.entity.player.Player; @@ -26,7 +25,7 @@ public void addProvider(final SlotReferenceProvider provider) { @Override public List find(final Player player, final Set validItems) { - return providers.stream().flatMap(p -> p.find(player, validItems).stream()).collect(Collectors.toList()); + return providers.stream().flatMap(p -> p.find(player, validItems).stream()).toList(); } public Optional findForUse(final Player player, diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/network/component/PlatformStorageNetworkComponent.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/network/component/PlatformStorageNetworkComponent.java new file mode 100644 index 000000000..2dc393e0e --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/network/component/PlatformStorageNetworkComponent.java @@ -0,0 +1,29 @@ +package com.refinedmods.refinedstorage2.platform.common.support.network.component; + +import com.refinedmods.refinedstorage2.api.network.impl.component.StorageNetworkComponentImpl; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; +import com.refinedmods.refinedstorage2.api.resource.list.ResourceListImpl; +import com.refinedmods.refinedstorage2.platform.api.storage.channel.FuzzyStorageChannel; +import com.refinedmods.refinedstorage2.platform.api.support.resource.list.FuzzyResourceList; +import com.refinedmods.refinedstorage2.platform.common.support.resource.list.FuzzyResourceListImpl; + +import java.util.Collection; + +public class PlatformStorageNetworkComponent extends StorageNetworkComponentImpl implements FuzzyStorageChannel { + private final FuzzyResourceList fuzzyResourceList; + + public PlatformStorageNetworkComponent() { + this(new FuzzyResourceListImpl(new ResourceListImpl())); + } + + private PlatformStorageNetworkComponent(final FuzzyResourceList fuzzyResourceList) { + super(fuzzyResourceList); + this.fuzzyResourceList = fuzzyResourceList; + } + + @Override + public Collection getFuzzy(final ResourceKey resource) { + return fuzzyResourceList.getFuzzy(resource); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/network/component/package-info.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/network/component/package-info.java new file mode 100644 index 000000000..4f36cc79b --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/network/component/package-info.java @@ -0,0 +1,7 @@ +@ParametersAreNonnullByDefault +@FieldsAndMethodsAreNonnullByDefault +package com.refinedmods.refinedstorage2.platform.common.support.network.component; + +import com.refinedmods.refinedstorage2.api.core.FieldsAndMethodsAreNonnullByDefault; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/render/FluidRenderer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/render/FluidRenderer.java index e5d76bc35..34773c624 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/render/FluidRenderer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/render/FluidRenderer.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.support.render; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import java.util.List; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/AbstractResourceContainerContainerAdapter.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/AbstractResourceContainerContainerAdapter.java index 7714f7600..b1cc8437f 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/AbstractResourceContainerContainerAdapter.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/AbstractResourceContainerContainerAdapter.java @@ -1,9 +1,8 @@ package com.refinedmods.refinedstorage2.platform.common.support.resource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceContainer; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; @@ -24,7 +23,7 @@ public int getContainerSize() { @Override public boolean isEmpty() { for (int i = 0; i < container.size(); ++i) { - if (container.get(i) != null) { + if (!container.isEmpty(i)) { return false; } } @@ -33,18 +32,14 @@ public boolean isEmpty() { @Override public ItemStack getItem(final int slotIndex) { - final ResourceAmountTemplate resourceAmount = container.get(slotIndex); - if (resourceAmount != null) { - return resourceAmount.getStackRepresentation(); - } - return ItemStack.EMPTY; + return container.getStackRepresentation(slotIndex); } @Override public ItemStack removeItem(final int slotIndex, final int amount) { - final ResourceAmountTemplate resourceAmount = container.get(slotIndex); - if (resourceAmount != null && resourceAmount.getResource() instanceof ItemResource itemResource) { - final long maxRemove = Math.min(amount, resourceAmount.getAmount()); + final ResourceKey resource = container.getResource(slotIndex); + if (resource instanceof ItemResource itemResource) { + final long maxRemove = Math.min(amount, container.getAmount(slotIndex)); container.shrink(slotIndex, maxRemove); return itemResource.toItemStack(maxRemove); } @@ -53,10 +48,10 @@ public ItemStack removeItem(final int slotIndex, final int amount) { @Override public ItemStack removeItemNoUpdate(final int slotIndex) { - final ResourceAmountTemplate resourceAmount = container.get(slotIndex); - if (resourceAmount != null && resourceAmount.getResource() instanceof ItemResource itemResource) { + final ResourceKey resource = container.getResource(slotIndex); + if (resource instanceof ItemResource itemResource) { final ItemStack stack = itemResource.toItemStack(); - final long maxRemove = Math.min(stack.getMaxStackSize(), resourceAmount.getAmount()); + final long maxRemove = Math.min(stack.getMaxStackSize(), container.getAmount(slotIndex)); container.shrink(slotIndex, maxRemove); return stack.copyWithCount((int) maxRemove); } @@ -65,22 +60,21 @@ public ItemStack removeItemNoUpdate(final int slotIndex) { @Override public boolean canPlaceItem(final int slot, final ItemStack stack) { - return container.get(slot) == null; + return container.isEmpty(slot); } @Override public void setItem(final int slotIndex, final ItemStack itemStack) { - final ResourceAmountTemplate resourceAmount = container.get(slotIndex); + final ResourceKey resource = container.getResource(slotIndex); if (itemStack.isEmpty()) { - if (resourceAmount != null && resourceAmount.getStorageChannelType() == StorageChannelTypes.ITEM) { + if (resource instanceof ItemResource) { container.remove(slotIndex); } return; } - container.set(slotIndex, new ResourceAmountTemplate<>( + container.set(slotIndex, new ResourceAmount( ItemResource.ofItemStack(itemStack), - itemStack.getCount(), - StorageChannelTypes.ITEM + itemStack.getCount() )); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/FluidResource.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResource.java similarity index 51% rename from refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/FluidResource.java rename to refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResource.java index 36dd326a3..7d1095013 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/FluidResource.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResource.java @@ -1,23 +1,27 @@ -package com.refinedmods.refinedstorage2.platform.api.support.resource; +package com.refinedmods.refinedstorage2.platform.common.support.resource; import com.refinedmods.refinedstorage2.api.core.CoreValidations; -import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.FuzzyModeNormalizer; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import java.util.Optional; import javax.annotation.Nullable; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.Fluids; import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.0") -public record FluidResource(Fluid fluid, @Nullable CompoundTag tag) implements FuzzyModeNormalizer { +public record FluidResource(Fluid fluid, @Nullable CompoundTag tag) + implements PlatformResourceKey, FuzzyModeNormalizer { private static final String TAG_TAG = "tag"; private static final String TAG_ID = "id"; - private static final String TAG_AMOUNT = "amount"; public FluidResource(final Fluid fluid, @Nullable final CompoundTag tag) { this.fluid = CoreValidations.validateNotNull(fluid, "Fluid must not be null"); @@ -25,26 +29,11 @@ public FluidResource(final Fluid fluid, @Nullable final CompoundTag tag) { } @Override - public FluidResource normalize() { + public ResourceKey normalize() { return new FluidResource(fluid, null); } - public static CompoundTag toTag(final FluidResource fluidResource) { - final CompoundTag tag = new CompoundTag(); - if (fluidResource.tag() != null) { - tag.put(TAG_TAG, fluidResource.tag()); - } - tag.putString(TAG_ID, BuiltInRegistries.FLUID.getKey(fluidResource.fluid()).toString()); - return tag; - } - - public static CompoundTag toTagWithAmount(final ResourceAmount resourceAmount) { - final CompoundTag tag = toTag(resourceAmount.getResource()); - tag.putLong(TAG_AMOUNT, resourceAmount.getAmount()); - return tag; - } - - public static Optional fromTag(final CompoundTag tag) { + static Optional fromTag(final CompoundTag tag) { final ResourceLocation id = new ResourceLocation(tag.getString(TAG_ID)); final Fluid fluid = BuiltInRegistries.FLUID.get(id); if (fluid == Fluids.EMPTY) { @@ -54,7 +43,29 @@ public static Optional fromTag(final CompoundTag tag) { return Optional.of(new FluidResource(fluid, itemTag)); } - public static Optional> fromTagWithAmount(final CompoundTag tag) { - return fromTag(tag).map(fluidResource -> new ResourceAmount<>(fluidResource, tag.getLong(TAG_AMOUNT))); + @Override + public CompoundTag toTag() { + final CompoundTag nbt = new CompoundTag(); + if (tag != null) { + nbt.put(TAG_TAG, tag); + } + nbt.putString(TAG_ID, BuiltInRegistries.FLUID.getKey(fluid).toString()); + return nbt; + } + + @Override + public void toBuffer(final FriendlyByteBuf buf) { + buf.writeVarInt(BuiltInRegistries.FLUID.getId(fluid)); + buf.writeNbt(tag); + } + + @Override + public long getInterfaceExportLimit() { + return ResourceTypes.FLUID.getInterfaceExportLimit(); + } + + @Override + public ResourceType getResourceType() { + return ResourceTypes.FLUID; } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceFactory.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceFactory.java index 499231e91..a6e829864 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceFactory.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceFactory.java @@ -1,27 +1,25 @@ package com.refinedmods.refinedstorage2.platform.common.support.resource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceFactory; import com.refinedmods.refinedstorage2.platform.common.Platform; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import java.util.Optional; import net.minecraft.world.item.ItemStack; -public class FluidResourceFactory implements ResourceFactory { +public class FluidResourceFactory implements ResourceFactory { @Override - public Optional> create(final ItemStack stack) { - return Platform.INSTANCE.getContainedFluid(stack).map(result -> new ResourceAmountTemplate<>( - result.fluid().getResource(), - Platform.INSTANCE.getBucketAmount(), - StorageChannelTypes.FLUID + public Optional create(final ItemStack stack) { + return Platform.INSTANCE.getContainedFluid(stack).map(result -> new ResourceAmount( + result.fluid(), + Platform.INSTANCE.getBucketAmount() )); } @Override - public boolean isValid(final Object resource) { + public boolean isValid(final ResourceKey resource) { return resource instanceof FluidResource; } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceRendering.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceRendering.java index d9df74755..82fb68926 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceRendering.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceRendering.java @@ -1,12 +1,13 @@ package com.refinedmods.refinedstorage2.platform.common.support.resource; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.support.AmountFormatting; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceRendering; import com.refinedmods.refinedstorage2.platform.common.Platform; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; +import java.util.Collections; import java.util.List; import java.util.Locale; @@ -16,7 +17,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.level.Level; -public class FluidResourceRendering implements ResourceRendering { +public class FluidResourceRendering implements ResourceRendering { private static final DecimalFormat LESS_THAN_1_BUCKET_FORMATTER = new DecimalFormat("0.#", DecimalFormatSymbols.getInstance(Locale.US)); private static final DecimalFormat FORMATTER = @@ -31,27 +32,39 @@ public String getDisplayedAmount(final long amount, final boolean withUnits) { } @Override - public Component getDisplayName(final FluidResource resource) { - return Platform.INSTANCE.getFluidRenderer().getDisplayName(resource); + public Component getDisplayName(final ResourceKey resource) { + if (!(resource instanceof FluidResource fluidResource)) { + return Component.empty(); + } + return Platform.INSTANCE.getFluidRenderer().getDisplayName(fluidResource); } @Override - public List getTooltip(final FluidResource resource) { - return Platform.INSTANCE.getFluidRenderer().getTooltip(resource); + public List getTooltip(final ResourceKey resource) { + if (!(resource instanceof FluidResource fluidResource)) { + return Collections.emptyList(); + } + return Platform.INSTANCE.getFluidRenderer().getTooltip(fluidResource); } @Override - public void render(final FluidResource resource, final GuiGraphics graphics, final int x, final int y) { - Platform.INSTANCE.getFluidRenderer().render(graphics.pose(), x, y, resource); + public void render(final ResourceKey resource, final GuiGraphics graphics, final int x, final int y) { + if (!(resource instanceof FluidResource fluidResource)) { + return; + } + Platform.INSTANCE.getFluidRenderer().render(graphics.pose(), x, y, fluidResource); } @Override - public void render(final FluidResource resource, + public void render(final ResourceKey resource, final PoseStack poseStack, final MultiBufferSource renderTypeBuffer, final int light, final Level level) { - Platform.INSTANCE.getFluidRenderer().render(poseStack, renderTypeBuffer, light, resource); + if (!(resource instanceof FluidResource fluidResource)) { + return; + } + Platform.INSTANCE.getFluidRenderer().render(poseStack, renderTypeBuffer, light, fluidResource); } public static String formatWithUnits(final long droplets) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/channel/FluidStorageChannelType.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceType.java similarity index 54% rename from refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/channel/FluidStorageChannelType.java rename to refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceType.java index e6a324666..a727aab96 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/channel/FluidStorageChannelType.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceType.java @@ -1,18 +1,13 @@ -package com.refinedmods.refinedstorage2.platform.common.storage.channel; +package com.refinedmods.refinedstorage2.platform.common.support.resource; import com.refinedmods.refinedstorage2.api.grid.operations.GridOperations; import com.refinedmods.refinedstorage2.api.grid.operations.GridOperationsImpl; import com.refinedmods.refinedstorage2.api.grid.view.GridResource; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; -import com.refinedmods.refinedstorage2.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.AbstractPlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.FuzzyStorageChannelImpl; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.list.FuzzyResourceList; -import com.refinedmods.refinedstorage2.platform.api.support.resource.list.FuzzyResourceListImpl; +import com.refinedmods.refinedstorage2.platform.api.support.resource.AbstractResourceType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.grid.view.FluidGridResource; import com.refinedmods.refinedstorage2.platform.common.support.TextureIds; @@ -25,16 +20,11 @@ import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; -class FluidStorageChannelType extends AbstractPlatformStorageChannelType { - FluidStorageChannelType() { +class FluidResourceType extends AbstractResourceType { + FluidResourceType() { super( "FLUID", - () -> { - final ResourceList list = new ResourceListImpl<>(); - final FuzzyResourceList fuzzyList = new FuzzyResourceListImpl<>(list); - return new FuzzyStorageChannelImpl<>(fuzzyList); - }, - createTranslation("misc", "storage_channel_type.fluid"), + createTranslation("misc", "resource_type.fluid"), TextureIds.ICONS, 16, 128 @@ -42,18 +32,13 @@ class FluidStorageChannelType extends AbstractPlatformStorageChannelType toGridResource(final ResourceAmount resourceAmount) { - return Platform.INSTANCE.getFluidGridResourceFactory().apply(resourceAmount); + public Optional toGridResource(final PlatformResourceKey resource, final long amount) { + return Platform.INSTANCE.getFluidGridResourceFactory().apply(new ResourceAmount(resource, amount)); } @Override @@ -77,9 +62,8 @@ public long getInterfaceExportLimit() { } @Override - public GridOperations createGridOperations(final StorageChannel storageChannel, - final Actor actor) { - return new GridOperationsImpl<>( + public GridOperations createGridOperations(final StorageChannel storageChannel, final Actor actor) { + return new GridOperationsImpl( storageChannel, actor, fluidResource -> Long.MAX_VALUE, @@ -88,12 +72,7 @@ public GridOperations createGridOperations(final StorageChannel fromTag(final CompoundTag tag) { + public Optional fromTag(final CompoundTag tag) { return FluidResource.fromTag(tag); } } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ItemResource.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResource.java similarity index 63% rename from refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ItemResource.java rename to refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResource.java index 558390206..261c97128 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ItemResource.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResource.java @@ -1,13 +1,17 @@ -package com.refinedmods.refinedstorage2.platform.api.support.resource; +package com.refinedmods.refinedstorage2.platform.common.support.resource; import com.refinedmods.refinedstorage2.api.core.CoreValidations; -import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.FuzzyModeNormalizer; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import java.util.Optional; import javax.annotation.Nullable; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; @@ -17,12 +21,11 @@ import org.slf4j.LoggerFactory; @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.0") -public record ItemResource(Item item, @Nullable CompoundTag tag) implements FuzzyModeNormalizer { +public record ItemResource(Item item, @Nullable CompoundTag tag) implements PlatformResourceKey, FuzzyModeNormalizer { private static final Logger LOGGER = LoggerFactory.getLogger(ItemResource.class); private static final String TAG_TAG = "tag"; private static final String TAG_ID = "id"; - private static final String TAG_AMOUNT = "amount"; public ItemResource(final Item item, @Nullable final CompoundTag tag) { this.item = CoreValidations.validateNotNull(item, "Item must not be null"); @@ -45,30 +48,41 @@ public ItemStack toItemStack(final long amount) { } @Override - public ItemResource normalize() { + public ResourceKey normalize() { return new ItemResource(item, null); } - public static ItemResource ofItemStack(final ItemStack itemStack) { - return new ItemResource(itemStack.getItem(), itemStack.getTag()); + @Override + public CompoundTag toTag() { + final CompoundTag nbt = new CompoundTag(); + if (this.tag != null) { + nbt.put(TAG_TAG, this.tag); + } + nbt.putString(TAG_ID, BuiltInRegistries.ITEM.getKey(item).toString()); + return nbt; } - public static CompoundTag toTag(final ItemResource itemResource) { - final CompoundTag tag = new CompoundTag(); - if (itemResource.tag() != null) { - tag.put(TAG_TAG, itemResource.tag()); - } - tag.putString(TAG_ID, BuiltInRegistries.ITEM.getKey(itemResource.item()).toString()); - return tag; + @Override + public void toBuffer(final FriendlyByteBuf buf) { + buf.writeVarInt(Item.getId(item)); + buf.writeNbt(tag); + } + + @Override + public long getInterfaceExportLimit() { + return item.getMaxStackSize(); + } + + @Override + public ResourceType getResourceType() { + return ResourceTypes.ITEM; } - public static CompoundTag toTagWithAmount(final ResourceAmount resourceAmount) { - final CompoundTag tag = toTag(resourceAmount.getResource()); - tag.putLong(TAG_AMOUNT, resourceAmount.getAmount()); - return tag; + public static ItemResource ofItemStack(final ItemStack itemStack) { + return new ItemResource(itemStack.getItem(), itemStack.getTag()); } - public static Optional fromTag(final CompoundTag tag) { + static Optional fromTag(final CompoundTag tag) { final ResourceLocation id = new ResourceLocation(tag.getString(TAG_ID)); final Item item = BuiltInRegistries.ITEM.get(id); if (item == Items.AIR) { @@ -77,8 +91,4 @@ public static Optional fromTag(final CompoundTag tag) { final CompoundTag itemTag = tag.contains(TAG_TAG) ? tag.getCompound(TAG_TAG) : null; return Optional.of(new ItemResource(item, itemTag)); } - - public static Optional> fromTagWithAmount(final CompoundTag tag) { - return fromTag(tag).map(itemResource -> new ResourceAmount<>(itemResource, tag.getLong(TAG_AMOUNT))); - } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResourceFactory.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResourceFactory.java index f7c354427..56143b94a 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResourceFactory.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResourceFactory.java @@ -1,29 +1,24 @@ package com.refinedmods.refinedstorage2.platform.common.support.resource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceFactory; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import java.util.Optional; import net.minecraft.world.item.ItemStack; -public class ItemResourceFactory implements ResourceFactory { +public class ItemResourceFactory implements ResourceFactory { @Override - public Optional> create(final ItemStack stack) { + public Optional create(final ItemStack stack) { if (stack.isEmpty()) { return Optional.empty(); } - return Optional.of(new ResourceAmountTemplate<>( - ItemResource.ofItemStack(stack), - stack.getCount(), - StorageChannelTypes.ITEM - )); + return Optional.of(new ResourceAmount(ItemResource.ofItemStack(stack), stack.getCount())); } @Override - public boolean isValid(final Object resource) { + public boolean isValid(final ResourceKey resource) { return resource instanceof ItemResource; } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResourceRendering.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResourceRendering.java index ed35746d4..86c143b66 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResourceRendering.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResourceRendering.java @@ -1,9 +1,10 @@ package com.refinedmods.refinedstorage2.platform.common.support.resource; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.support.AmountFormatting; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceRendering; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -21,7 +22,7 @@ import net.minecraft.world.level.Level; import org.joml.Matrix4f; -public class ItemResourceRendering implements ResourceRendering { +public class ItemResourceRendering implements ResourceRendering { public static final Matrix4f IN_WORLD_SCALE = new Matrix4f().scale(0.3F, 0.3F, 0.001f); private final Map stackCache = new HashMap<>(); @@ -41,33 +42,45 @@ public String getDisplayedAmount(final long amount, final boolean withUnits) { } @Override - public Component getDisplayName(final ItemResource resource) { - return getStack(resource).getHoverName(); + public Component getDisplayName(final ResourceKey resource) { + if (!(resource instanceof ItemResource itemResource)) { + return Component.empty(); + } + return getStack(itemResource).getHoverName(); } @Override - public List getTooltip(final ItemResource resource) { + public List getTooltip(final ResourceKey resource) { + if (!(resource instanceof ItemResource itemResource)) { + return Collections.emptyList(); + } final Minecraft minecraft = Minecraft.getInstance(); - return getStack(resource).getTooltipLines( + return getStack(itemResource).getTooltipLines( minecraft.player, minecraft.options.advancedItemTooltips ? TooltipFlag.ADVANCED : TooltipFlag.NORMAL ); } @Override - public void render(final ItemResource resource, final GuiGraphics graphics, final int x, final int y) { - final ItemStack stack = getStack(resource); + public void render(final ResourceKey resource, final GuiGraphics graphics, final int x, final int y) { + if (!(resource instanceof ItemResource itemResource)) { + return; + } + final ItemStack stack = getStack(itemResource); graphics.renderItem(stack, x, y); graphics.renderItemDecorations(Minecraft.getInstance().font, stack, x, y); } @Override - public void render(final ItemResource resource, + public void render(final ResourceKey resource, final PoseStack poseStack, final MultiBufferSource renderTypeBuffer, final int light, final Level level) { - final ItemStack itemStack = getStack(resource); + if (!(resource instanceof ItemResource itemResource)) { + return; + } + final ItemStack itemStack = getStack(itemResource); poseStack.mulPoseMatrix(IN_WORLD_SCALE); poseStack.last().normal().rotateX(Mth.DEG_TO_RAD * -45f); Minecraft.getInstance().getItemRenderer().renderStatic( diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/channel/ItemStorageChannelType.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResourceType.java similarity index 50% rename from refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/channel/ItemStorageChannelType.java rename to refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResourceType.java index 909c14bce..656b32158 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/channel/ItemStorageChannelType.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResourceType.java @@ -1,18 +1,13 @@ -package com.refinedmods.refinedstorage2.platform.common.storage.channel; +package com.refinedmods.refinedstorage2.platform.common.support.resource; import com.refinedmods.refinedstorage2.api.grid.operations.GridOperations; import com.refinedmods.refinedstorage2.api.grid.operations.GridOperationsImpl; import com.refinedmods.refinedstorage2.api.grid.view.GridResource; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; -import com.refinedmods.refinedstorage2.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.AbstractPlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.FuzzyStorageChannelImpl; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.list.FuzzyResourceList; -import com.refinedmods.refinedstorage2.platform.api.support.resource.list.FuzzyResourceListImpl; +import com.refinedmods.refinedstorage2.platform.api.support.resource.AbstractResourceType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.grid.view.ItemGridResource; import com.refinedmods.refinedstorage2.platform.common.support.TextureIds; @@ -25,35 +20,25 @@ import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; -class ItemStorageChannelType extends AbstractPlatformStorageChannelType { - ItemStorageChannelType() { +class ItemResourceType extends AbstractResourceType { + ItemResourceType() { super( "ITEM", - () -> { - final ResourceList list = new ResourceListImpl<>(); - final FuzzyResourceList fuzzyList = new FuzzyResourceListImpl<>(list); - return new FuzzyStorageChannelImpl<>(fuzzyList); - }, - createTranslation("misc", "storage_channel_type.item"), + createTranslation("misc", "resource_type.item"), TextureIds.ICONS, 0, 128 ); } - @Override - public void toBuffer(final ItemResource resource, final FriendlyByteBuf buf) { - PacketUtil.writeItemResource(buf, resource); - } - @Override public ItemResource fromBuffer(final FriendlyByteBuf buf) { return PacketUtil.readItemResource(buf); } @Override - public Optional toGridResource(final ResourceAmount resourceAmount) { - return Platform.INSTANCE.getItemGridResourceFactory().apply(resourceAmount); + public Optional toGridResource(final PlatformResourceKey resource, final long amount) { + return Platform.INSTANCE.getItemGridResourceFactory().apply(new ResourceAmount(resource, amount)); } @Override @@ -77,32 +62,17 @@ public long getInterfaceExportLimit() { } @Override - @SuppressWarnings("deprecation") - public long getInterfaceExportLimit(final ItemResource resource) { - return resource.item().getMaxStackSize(); - } - - @Override - @SuppressWarnings("deprecation") - public GridOperations createGridOperations( - final StorageChannel storageChannel, - final Actor actor - ) { - return new GridOperationsImpl<>( + public GridOperations createGridOperations(final StorageChannel storageChannel, final Actor actor) { + return new GridOperationsImpl( storageChannel, actor, - itemResource -> itemResource.item().getMaxStackSize(), + resource -> resource instanceof ItemResource itemResource ? itemResource.item().getMaxStackSize() : 0, 1 ); } @Override - public CompoundTag toTag(final ItemResource resource) { - return ItemResource.toTag(resource); - } - - @Override - public Optional fromTag(final CompoundTag tag) { + public Optional fromTag(final CompoundTag tag) { return ItemResource.fromTag(tag); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ResourceContainerImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ResourceContainerImpl.java index 1c2113b26..f58be8381 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ResourceContainerImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ResourceContainerImpl.java @@ -2,14 +2,14 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.core.CoreValidations; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceContainer; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceContainerType; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceFactory; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.util.MathUtil; import java.util.ArrayList; @@ -27,21 +27,21 @@ import net.minecraft.world.item.ItemStack; public class ResourceContainerImpl implements ResourceContainer { - private final ResourceAmountTemplate[] slots; + private final ResourceContainerSlot[] slots; private final ResourceContainerType type; - private final ToLongFunction> maxAmountProvider; - private final ResourceFactory primaryResourceFactory; - private final Set> alternativeResourceFactories; + private final ToLongFunction maxAmountProvider; + private final ResourceFactory primaryResourceFactory; + private final Set alternativeResourceFactories; @Nullable private Runnable listener; public ResourceContainerImpl(final int size, final ResourceContainerType type, - final ToLongFunction> maxAmountProvider, - final ResourceFactory primaryResourceFactory, - final Set> alternativeResourceFactories) { - this.slots = new ResourceAmountTemplate[size]; + final ToLongFunction maxAmountProvider, + final ResourceFactory primaryResourceFactory, + final Set alternativeResourceFactories) { + this.slots = new ResourceContainerSlot[size]; this.type = type; this.maxAmountProvider = maxAmountProvider; this.primaryResourceFactory = primaryResourceFactory; @@ -61,7 +61,7 @@ public void setListener(@Nullable final Runnable listener) { @Override public void change(final int index, final ItemStack stack, final boolean tryAlternatives) { if (tryAlternatives) { - for (final ResourceFactory resourceFactory : alternativeResourceFactories) { + for (final ResourceFactory resourceFactory : alternativeResourceFactories) { final var result = resourceFactory.create(stack); if (result.isPresent()) { set(index, result.get()); @@ -76,21 +76,21 @@ public void change(final int index, final ItemStack stack, final boolean tryAlte } @Override - public void set(final int index, final ResourceAmountTemplate resourceAmount) { + public void set(final int index, final ResourceAmount resourceAmount) { setSilently(index, resourceAmount); changed(); } - private void setSilently(final int index, final ResourceAmountTemplate resourceAmount) { - slots[index] = resourceAmount; + private void setSilently(final int index, final ResourceAmount resourceAmount) { + slots[index] = new ResourceContainerSlot(resourceAmount); } @Override - public boolean isValid(final T resource) { + public boolean isValid(final ResourceKey resource) { if (primaryResourceFactory.isValid(resource)) { return true; } - for (final ResourceFactory resourceFactory : alternativeResourceFactories) { + for (final ResourceFactory resourceFactory : alternativeResourceFactories) { if (resourceFactory.isValid(resource)) { return true; } @@ -100,11 +100,11 @@ public boolean isValid(final T resource) { @Override public long getAmount(final int index) { - final ResourceAmountTemplate resourceAmount = slots[index]; - if (resourceAmount == null) { + final ResourceContainerSlot slot = slots[index]; + if (slot == null) { return 0; } - return resourceAmount.getAmount(); + return slot.getResourceAmount().getAmount(); } @Override @@ -121,22 +121,22 @@ public void shrink(final int index, final long amount) { @Override public void setAmount(final int index, final long amount) { - final ResourceAmountTemplate resourceAmount = slots[index]; - if (resourceAmount == null) { + final ResourceContainerSlot slot = slots[index]; + if (slot == null) { return; } - final long newAmount = MathUtil.clamp(amount, 0, getMaxAmount(resourceAmount)); + final long newAmount = MathUtil.clamp(amount, 0, getMaxAmount(slot.getResourceAmount().getResource())); if (newAmount == 0) { remove(index); } else { - slots[index] = resourceAmount.withAmount(newAmount); + slots[index] = slot.withAmount(newAmount); } changed(); } @Override - public long getMaxAmount(final ResourceAmountTemplate resourceAmount) { - return maxAmountProvider.applyAsLong(resourceAmount.getResourceTemplate()); + public long getMaxAmount(final ResourceKey resource) { + return maxAmountProvider.applyAsLong(resource); } @Override @@ -156,39 +156,62 @@ public int size() { @Override @Nullable - public ResourceAmountTemplate get(final int index) { - return slots[index]; + public ResourceAmount get(final int index) { + final ResourceContainerSlot slot = slots[index]; + if (slot == null) { + return null; + } + return slot.getResourceAmount(); + } + + @Nullable + @Override + public PlatformResourceKey getResource(final int index) { + final ResourceContainerSlot slot = slots[index]; + if (slot == null) { + return null; + } + return slot.getPlatformResource(); + } + + @Override + public ItemStack getStackRepresentation(final int index) { + final ResourceContainerSlot slot = slots[index]; + if (slot == null) { + return ItemStack.EMPTY; + } + return slot.getStackRepresentation(); } @Override - public Set getUniqueTemplates() { - final Set result = new HashSet<>(); + public Set getUniqueResources() { + final Set result = new HashSet<>(); for (int i = 0; i < size(); ++i) { - final ResourceAmountTemplate resourceAmount = slots[i]; - if (resourceAmount == null) { + final ResourceContainerSlot slot = slots[i]; + if (slot == null) { continue; } - result.add(resourceAmount.getResourceTemplate().resource()); + result.add(slot.getResourceAmount().getResource()); } return result; } @Override - public List> getTemplates() { - final List> result = new ArrayList<>(); + public List getResources() { + final List result = new ArrayList<>(); for (int i = 0; i < size(); ++i) { - final ResourceAmountTemplate resourceAmount = slots[i]; - if (resourceAmount == null) { + final ResourceContainerSlot slot = slots[i]; + if (slot == null) { continue; } - result.add(resourceAmount.getResourceTemplate()); + result.add(slot.getResourceAmount().getResource()); } return result; } @Override public void writeToUpdatePacket(final FriendlyByteBuf buf) { - for (final ResourceAmountTemplate slot : slots) { + for (final ResourceContainerSlot slot : slots) { if (slot == null) { buf.writeBoolean(false); continue; @@ -197,13 +220,13 @@ public void writeToUpdatePacket(final FriendlyByteBuf buf) { } } - private void writeToUpdatePacket(final FriendlyByteBuf buf, final ResourceAmountTemplate resourceAmount) { - final PlatformStorageChannelType storageChannelType = resourceAmount.getStorageChannelType(); - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().getId(storageChannelType).ifPresentOrElse(id -> { + private void writeToUpdatePacket(final FriendlyByteBuf buf, final ResourceContainerSlot slot) { + final ResourceType resourceType = slot.getResourceType(); + PlatformApi.INSTANCE.getResourceTypeRegistry().getId(resourceType).ifPresentOrElse(id -> { buf.writeBoolean(true); buf.writeResourceLocation(id); - storageChannelType.toBuffer(resourceAmount.getResource(), buf); - buf.writeLong(resourceAmount.getAmount()); + slot.getPlatformResource().toBuffer(buf); + buf.writeLong(slot.getAmount()); }, () -> buf.writeBoolean(false)); } @@ -215,24 +238,24 @@ public void readFromUpdatePacket(final int index, final FriendlyByteBuf buf) { return; } final ResourceLocation id = buf.readResourceLocation(); - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().get(id).ifPresent( - storageChannelType -> readFromUpdatePacket(index, buf, storageChannelType) + PlatformApi.INSTANCE.getResourceTypeRegistry().get(id).ifPresent( + resourceType -> readFromUpdatePacket(index, buf, resourceType) ); } - private void readFromUpdatePacket(final int index, - final FriendlyByteBuf buf, - final PlatformStorageChannelType storageChannelType) { - final T resource = storageChannelType.fromBuffer(buf); + private void readFromUpdatePacket(final int index, + final FriendlyByteBuf buf, + final ResourceType resourceType) { + final ResourceKey resource = resourceType.fromBuffer(buf); final long amount = buf.readLong(); - setSilently(index, new ResourceAmountTemplate<>(resource, amount, storageChannelType)); + setSilently(index, new ResourceAmount(resource, amount)); } @Override public CompoundTag toTag() { final CompoundTag tag = new CompoundTag(); for (int i = 0; i < size(); ++i) { - final ResourceAmountTemplate resourceAmount = slots[i]; + final ResourceContainerSlot resourceAmount = slots[i]; if (resourceAmount == null) { continue; } @@ -241,24 +264,23 @@ public CompoundTag toTag() { return tag; } - private void addToTag(final CompoundTag tag, - final int index, - final ResourceAmountTemplate resourceAmount) { - final PlatformStorageChannelType storageChannelType = resourceAmount.getStorageChannelType(); - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().getId(storageChannelType).ifPresent( - storageChannelTypeId -> addToTag(tag, index, resourceAmount, storageChannelType, storageChannelTypeId) + private void addToTag(final CompoundTag tag, + final int index, + final ResourceContainerSlot resourceAmount) { + final ResourceType resourceType = resourceAmount.getResourceType(); + PlatformApi.INSTANCE.getResourceTypeRegistry().getId(resourceType).ifPresent( + resourceTypeId -> addToTag(tag, index, resourceAmount, resourceTypeId) ); } - private void addToTag(final CompoundTag tag, - final int index, - final ResourceAmountTemplate resourceAmount, - final PlatformStorageChannelType storageChannelType, - final ResourceLocation storageChannelTypeId) { + private void addToTag(final CompoundTag tag, + final int index, + final ResourceContainerSlot slot, + final ResourceLocation resourceTypeId) { final CompoundTag serialized = new CompoundTag(); - serialized.putString("t", storageChannelTypeId.toString()); - serialized.put("v", storageChannelType.toTag(resourceAmount.getResource())); - serialized.putLong("a", resourceAmount.getAmount()); + serialized.putString("t", resourceTypeId.toString()); + serialized.put("v", slot.getPlatformResource().toTag()); + serialized.putLong("a", slot.getAmount()); tag.put("s" + index, serialized); } @@ -276,29 +298,27 @@ public void fromTag(final CompoundTag tag) { } private void fromTag(final int index, final CompoundTag tag) { - final ResourceLocation storageChannelTypeId = new ResourceLocation(tag.getString("t")); - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().get(storageChannelTypeId).ifPresent( - storageChannelType -> fromTag(index, tag, storageChannelType) + final ResourceLocation resourceTypeId = new ResourceLocation(tag.getString("t")); + PlatformApi.INSTANCE.getResourceTypeRegistry().get(resourceTypeId).ifPresent( + resourceType -> fromTag(index, tag, resourceType) ); } - private void fromTag(final int index, - final CompoundTag tag, - final PlatformStorageChannelType storageChannelType) { + private void fromTag(final int index, final CompoundTag tag, final ResourceType resourceType) { final long amount = tag.getLong("a"); - storageChannelType.fromTag(tag.getCompound("v")).ifPresent(resource -> setSilently( + resourceType.fromTag(tag.getCompound("v")).ifPresent(resource -> setSilently( index, - new ResourceAmountTemplate<>(resource, amount, storageChannelType) + new ResourceAmount(resource, amount) )); } @Override - public ResourceFactory getPrimaryResourceFactory() { + public ResourceFactory getPrimaryResourceFactory() { return primaryResourceFactory; } @Override - public Set> getAlternativeResourceFactories() { + public Set getAlternativeResourceFactories() { return alternativeResourceFactories; } @@ -322,26 +342,22 @@ public void setChanged() { } @Override - public long insert(final StorageChannelType storageChannelType, - final T resource, - final long amount, - final Action action) { - if (!(storageChannelType instanceof PlatformStorageChannelType platformStorageChannelType)) { - return 0; + public long insert(final ResourceKey resource, final long amount, final Action action) { + if (!(resource instanceof PlatformResourceKey platformResource)) { + return 0L; } long remainder = amount; for (int i = 0; i < size(); ++i) { - final ResourceAmountTemplate existing = get(i); - if (existing == null) { - remainder -= insertIntoEmptySlot(i, resource, action, platformStorageChannelType, remainder); - } else if (existing.getResource().equals(resource)) { + final ResourceAmount slot = get(i); + if (slot == null) { + remainder -= insertIntoEmptySlot(i, platformResource, action, remainder); + } else if (slot.getResource().equals(resource)) { remainder -= insertIntoExistingSlot( i, - platformStorageChannelType, - resource, + platformResource, action, remainder, - existing + slot ); } if (remainder == 0) { @@ -351,29 +367,23 @@ public long insert(final StorageChannelType storageChannelType, return amount - remainder; } - private long insertIntoEmptySlot(final int slotIndex, - final T resource, - final Action action, - final PlatformStorageChannelType platformStorageChannelType, - final long amount) { - final long inserted = Math.min(platformStorageChannelType.getInterfaceExportLimit(resource), amount); + private long insertIntoEmptySlot(final int slotIndex, + final PlatformResourceKey resource, + final Action action, + final long amount) { + final long inserted = Math.min(resource.getInterfaceExportLimit(), amount); if (action == Action.EXECUTE) { - set(slotIndex, new ResourceAmountTemplate<>( - resource, - inserted, - platformStorageChannelType - )); + set(slotIndex, new ResourceAmount(resource, inserted)); } return inserted; } - private long insertIntoExistingSlot(final int slotIndex, - final PlatformStorageChannelType storageChannelType, - final T resource, - final Action action, - final long amount, - final ResourceAmountTemplate existing) { - final long spaceRemaining = storageChannelType.getInterfaceExportLimit(resource) - existing.getAmount(); + private long insertIntoExistingSlot(final int slotIndex, + final PlatformResourceKey resource, + final Action action, + final long amount, + final ResourceAmount existing) { + final long spaceRemaining = resource.getInterfaceExportLimit() - existing.getAmount(); final long inserted = Math.min(spaceRemaining, amount); if (action == Action.EXECUTE) { grow(slotIndex, inserted); @@ -382,15 +392,15 @@ private long insertIntoExistingSlot(final int slotIndex, } @Override - public long extract(final T resource, final long amount, final Action action) { + public long extract(final ResourceKey resource, final long amount, final Action action) { long extracted = 0; for (int i = 0; i < size(); ++i) { - final ResourceAmountTemplate slot = get(i); - if (slot == null || !resource.equals(slot.getResource())) { + final ResourceAmount slotContents = get(i); + if (slotContents == null || !resource.equals(slotContents.getResource())) { continue; } final long stillNeeded = amount - extracted; - final long toExtract = Math.min(slot.getAmount(), stillNeeded); + final long toExtract = Math.min(slotContents.getAmount(), stillNeeded); if (action == Action.EXECUTE) { shrink(i, toExtract); } @@ -409,9 +419,9 @@ public ResourceContainer copy() { alternativeResourceFactories ); for (int i = 0; i < size(); ++i) { - final ResourceAmountTemplate resourceAmount = get(i); - if (resourceAmount != null) { - copy.set(i, resourceAmount); + final ResourceAmount slotContents = get(i); + if (slotContents != null) { + copy.set(i, slotContents); } } return copy; @@ -435,7 +445,7 @@ public static ResourceContainer createForFilter(final int size, final ResourceCo ); } - public static ResourceContainer createForFilter(final ResourceFactory resourceFactory) { + public static ResourceContainer createForFilter(final ResourceFactory resourceFactory) { return new ResourceContainerImpl( 9, ResourceContainerType.FILTER, diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ResourceContainerSlot.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ResourceContainerSlot.java new file mode 100644 index 000000000..fcb7efd05 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ResourceContainerSlot.java @@ -0,0 +1,62 @@ +package com.refinedmods.refinedstorage2.platform.common.support.resource; + +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; + +import java.util.Objects; + +import net.minecraft.world.item.ItemStack; + +class ResourceContainerSlot { + private final ResourceAmount resourceAmount; + private final ItemStack stackRepresentation; + + ResourceContainerSlot(final ResourceAmount resourceAmount) { + this.resourceAmount = resourceAmount; + this.stackRepresentation = resourceAmount.getResource() instanceof ItemResource itemResource + ? itemResource.toItemStack(resourceAmount.getAmount()) + : ItemStack.EMPTY; + } + + long getAmount() { + return resourceAmount.getAmount(); + } + + ResourceAmount getResourceAmount() { + return resourceAmount; + } + + PlatformResourceKey getPlatformResource() { + return (PlatformResourceKey) resourceAmount.getResource(); + } + + ResourceType getResourceType() { + return getPlatformResource().getResourceType(); + } + + ItemStack getStackRepresentation() { + return stackRepresentation; + } + + ResourceContainerSlot withAmount(final long newAmount) { + return new ResourceContainerSlot(new ResourceAmount(resourceAmount.getResource(), newAmount)); + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + final ResourceContainerSlot that = (ResourceContainerSlot) o; + return Objects.equals(resourceAmount, that.resourceAmount); + } + + @Override + public int hashCode() { + return Objects.hash(resourceAmount); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ResourceTypes.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ResourceTypes.java new file mode 100644 index 000000000..2b572aa99 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ResourceTypes.java @@ -0,0 +1,11 @@ +package com.refinedmods.refinedstorage2.platform.common.support.resource; + +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; + +public final class ResourceTypes { + public static final ResourceType ITEM = new ItemResourceType(); + public static final ResourceType FLUID = new FluidResourceType(); + + private ResourceTypes() { + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/list/FuzzyResourceListImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/list/FuzzyResourceListImpl.java new file mode 100644 index 000000000..9c62ba6f3 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/list/FuzzyResourceListImpl.java @@ -0,0 +1,75 @@ +package com.refinedmods.refinedstorage2.platform.common.support.resource.list; + +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; +import com.refinedmods.refinedstorage2.api.resource.list.AbstractProxyResourceList; +import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; +import com.refinedmods.refinedstorage2.api.resource.list.ResourceListOperationResult; +import com.refinedmods.refinedstorage2.platform.api.support.resource.FuzzyModeNormalizer; +import com.refinedmods.refinedstorage2.platform.api.support.resource.list.FuzzyResourceList; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import org.apiguardian.api.API; + +@API(status = API.Status.STABLE, since = "2.0.0-milestone.2.4") +public class FuzzyResourceListImpl extends AbstractProxyResourceList implements FuzzyResourceList { + private final Map> normalizedFuzzyMap = new HashMap<>(); + + public FuzzyResourceListImpl(final ResourceList delegate) { + super(delegate); + } + + @Override + public ResourceListOperationResult add(final ResourceKey resource, final long amount) { + final ResourceListOperationResult result = super.add(resource, amount); + addToIndex(resource, result); + return result; + } + + private void addToIndex(final ResourceKey resource, final ResourceListOperationResult result) { + if (resource instanceof FuzzyModeNormalizer normalizer) { + normalizedFuzzyMap.computeIfAbsent(normalizer.normalize(), k -> new HashSet<>()) + .add(result.resourceAmount()); + } + } + + @Override + public Optional remove(final ResourceKey resource, final long amount) { + return super.remove(resource, amount).map(result -> { + if (!result.available()) { + removeFromIndex(resource, result); + } + return result; + }); + } + + private void removeFromIndex(final ResourceKey resource, final ResourceListOperationResult result) { + if (!(resource instanceof FuzzyModeNormalizer normalizer)) { + return; + } + final ResourceKey normalized = normalizer.normalize(); + final Collection index = normalizedFuzzyMap.get(normalized); + if (index == null) { + return; + } + index.remove(result.resourceAmount()); + if (index.isEmpty()) { + normalizedFuzzyMap.remove(normalized); + } + } + + @Override + public Collection getFuzzy(final ResourceKey resource) { + if (resource instanceof FuzzyModeNormalizer normalizer) { + return normalizedFuzzyMap.getOrDefault(normalizer.normalize(), Collections.emptySet()); + } + return normalizedFuzzyMap.getOrDefault(resource, Collections.emptySet()); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/channel/package-info.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/list/package-info.java similarity index 72% rename from refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/channel/package-info.java rename to refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/list/package-info.java index 72cbfb5b1..1491d8830 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/storage/channel/package-info.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/resource/list/package-info.java @@ -1,6 +1,6 @@ @ParametersAreNonnullByDefault @FieldsAndMethodsAreNonnullByDefault -package com.refinedmods.refinedstorage2.platform.common.storage.channel; +package com.refinedmods.refinedstorage2.platform.common.support.resource.list; import com.refinedmods.refinedstorage2.api.core.FieldsAndMethodsAreNonnullByDefault; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/tooltip/ResourceClientTooltipComponent.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/tooltip/ResourceClientTooltipComponent.java index bac724911..79b983225 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/tooltip/ResourceClientTooltipComponent.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/tooltip/ResourceClientTooltipComponent.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.support.tooltip; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceRendering; import java.util.Objects; @@ -12,11 +12,11 @@ import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; import net.minecraft.network.chat.Component; -public class ResourceClientTooltipComponent implements ClientTooltipComponent { - private final ResourceAmountTemplate resourceAmount; +public class ResourceClientTooltipComponent implements ClientTooltipComponent { + private final ResourceAmount resourceAmount; private final Component name; - public ResourceClientTooltipComponent(final ResourceAmountTemplate resourceAmount) { + public ResourceClientTooltipComponent(final ResourceAmount resourceAmount) { this.resourceAmount = resourceAmount; this.name = getNameWithAmount(resourceAmount); } @@ -48,8 +48,8 @@ public void renderImage(final Font font, final int x, final int y, final GuiGrap ); } - private static Component getNameWithAmount(final ResourceAmountTemplate resourceAmount) { - final ResourceRendering rendering = PlatformApi.INSTANCE.getResourceRendering( + private static Component getNameWithAmount(final ResourceAmount resourceAmount) { + final ResourceRendering rendering = PlatformApi.INSTANCE.getResourceRendering( resourceAmount.getResource() ); final String amount = rendering.getDisplayedAmount(resourceAmount.getAmount(), true); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/widget/FilterModeSideButtonWidget.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/widget/FilterModeSideButtonWidget.java index fc79a5875..c007cc350 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/widget/FilterModeSideButtonWidget.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/support/widget/FilterModeSideButtonWidget.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.support.widget; -import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; +import com.refinedmods.refinedstorage2.api.resource.filter.FilterMode; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.ClientProperty; import net.minecraft.network.chat.Component; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/upgrade/RegulatorUpgradeItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/upgrade/RegulatorUpgradeItem.java index 4bf0d3aa9..dfa3e843d 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/upgrade/RegulatorUpgradeItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/upgrade/RegulatorUpgradeItem.java @@ -1,8 +1,10 @@ package com.refinedmods.refinedstorage2.platform.common.upgrade; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.support.network.bounditem.SlotReference; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceContainer; import com.refinedmods.refinedstorage2.platform.api.upgrade.AbstractUpgradeItem; import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; @@ -58,19 +60,19 @@ public InteractionResultHolder use(final Level level, final Player pl @Override public Optional getTooltipImage(final ItemStack stack) { - return Optional.of(new RegulatorTooltipComponent<>(HELP, getFilteredResource(stack))); + return Optional.of(new RegulatorTooltipComponent(HELP, getConfiguredResource(stack))); } @Nullable - private ResourceAmountTemplate getFilteredResource(final ItemStack stack) { + private ResourceAmount getConfiguredResource(final ItemStack stack) { final ResourceContainer container = getResourceFilterContainer(stack); - final ResourceAmountTemplate resourceAmount = container.get(0); - if (resourceAmount == null) { + final PlatformResourceKey resource = container.getResource(0); + if (resource == null) { return null; } final double amount = getAmount(stack); - final long normalizedAmount = resourceAmount.getStorageChannelType().normalizeAmount(amount); - return resourceAmount.withAmount(normalizedAmount); + final long normalizedAmount = resource.getResourceType().normalizeAmount(amount); + return new ResourceAmount(resource, normalizedAmount); } public double getAmount(final ItemStack stack) { @@ -96,23 +98,23 @@ public long getEnergyUsage() { return Platform.INSTANCE.getConfig().getUpgrade().getRegulatorUpgradeEnergyUsage(); } - public OptionalLong getDesiredAmount(final ItemStack stack, final Object resource) { + public OptionalLong getDesiredAmount(final ItemStack stack, final ResourceKey resource) { final ResourceContainer container = getResourceFilterContainer(stack); - final ResourceAmountTemplate filteredResource = container.get(0); - if (filteredResource == null) { + final PlatformResourceKey configuredResource = container.getResource(0); + if (configuredResource == null) { return OptionalLong.empty(); } - final boolean same = filteredResource.getResource().equals(resource); + final boolean same = configuredResource.equals(resource); if (!same) { return OptionalLong.empty(); } final double amount = getAmount(stack); - final long normalizedAmount = filteredResource.getStorageChannelType().normalizeAmount(amount); + final long normalizedAmount = configuredResource.getResourceType().normalizeAmount(amount); return OptionalLong.of(normalizedAmount); } - public record RegulatorTooltipComponent(Component helpText, - @Nullable ResourceAmountTemplate filteredResource) + public record RegulatorTooltipComponent(Component helpText, + @Nullable ResourceAmount configuredResource) implements TooltipComponent { } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/upgrade/UpgradeContainer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/upgrade/UpgradeContainer.java index d7c0833fe..9cd9caaf9 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/upgrade/UpgradeContainer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/upgrade/UpgradeContainer.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.upgrade; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeDestination; import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeItem; import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeMapping; @@ -66,7 +67,7 @@ public Set getAllowedUpgrades() { return registry.getByDestination(destination); } - public OptionalLong getRegulatedAmount(final T resource) { + public OptionalLong getRegulatedAmount(final ResourceKey resource) { return IntStream.range(0, getContainerSize()) .mapToObj(this::getItem) .filter(stack -> stack.getItem() instanceof RegulatorUpgradeItem) diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/util/PacketUtil.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/util/PacketUtil.java index 791d2e55c..bd04f3482 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/util/PacketUtil.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/util/PacketUtil.java @@ -1,8 +1,9 @@ package com.refinedmods.refinedstorage2.platform.common.util; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import javax.annotation.Nullable; @@ -15,23 +16,13 @@ public final class PacketUtil { private PacketUtil() { } - public static void writeItemResource(final FriendlyByteBuf buf, final ItemResource itemResource) { - buf.writeVarInt(Item.getId(itemResource.item())); - buf.writeNbt(itemResource.tag()); - } - public static ItemResource readItemResource(final FriendlyByteBuf buf) { final int id = buf.readVarInt(); final CompoundTag nbt = buf.readNbt(); return new ItemResource(Item.byId(id), nbt); } - public static void writeFluidResource(final FriendlyByteBuf buf, final FluidResource itemResource) { - buf.writeVarInt(BuiltInRegistries.FLUID.getId(itemResource.fluid())); - buf.writeNbt(itemResource.tag()); - } - - public static FluidResource readFluidResource(final FriendlyByteBuf buf) { + public static PlatformResourceKey readFluidResource(final FriendlyByteBuf buf) { final int id = buf.readVarInt(); final CompoundTag nbt = buf.readNbt(); return new FluidResource(BuiltInRegistries.FLUID.byId(id), nbt); diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json index aca94c00e..08acc2fcb 100644 --- a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json @@ -66,9 +66,9 @@ "gui.refinedstorage2.grid.synchronizer.rei.help": "Sync the search box text to the REI filter.", "gui.refinedstorage2.grid.synchronizer.rei.two_way": "REI two-way", "gui.refinedstorage2.grid.synchronizer.rei.two_way.help": "Sync the search box text to the JEI filter, and the JEI filter to the search box text.", - "gui.refinedstorage2.grid.storage_channel_type": "Storage channel", - "gui.refinedstorage2.grid.storage_channel_type.all": "All", - "gui.refinedstorage2.grid.storage_channel_type.help": "Filter resources from a specific storage channel.", + "gui.refinedstorage2.grid.resource_type": "Resource type", + "gui.refinedstorage2.grid.resource_type.all": "All", + "gui.refinedstorage2.grid.resource_type.help": "Filter specific resource types.", "gui.refinedstorage2.crafting_grid.move.network": "Move items to network", "gui.refinedstorage2.crafting_grid.move.inventory": "Move items to inventory", "gui.refinedstorage2.detector.mode": "Mode", @@ -232,8 +232,8 @@ "misc.refinedstorage2.last_modified.weeks": "Last modified %d weeks ago by %s", "misc.refinedstorage2.last_modified.year": "Last modified %d year ago by %s", "misc.refinedstorage2.last_modified.years": "Last modified %d years ago by %s", - "misc.refinedstorage2.storage_channel_type.item": "Item", - "misc.refinedstorage2.storage_channel_type.fluid": "Fluid", + "misc.refinedstorage2.resource_type.item": "Item", + "misc.refinedstorage2.resource_type.fluid": "Fluid", "misc.refinedstorage2.press_shift_for_help": "Press SHIFT for help", "key.refinedstorage2.focus_search_bar": "Focus search bar", "key.refinedstorage2.clear_crafting_grid_matrix_to_network": "Clear Crafting Grid matrix to network", @@ -254,7 +254,7 @@ "text.autoconfig.refinedstorage2.option.grid.smoothScrolling": "Smooth scrolling", "text.autoconfig.refinedstorage2.option.grid.autoSelected": "Auto selected search box", "text.autoconfig.refinedstorage2.option.grid.synchronizer": "Synchronizer", - "text.autoconfig.refinedstorage2.option.grid.storageChannelType": "Storage channel", + "text.autoconfig.refinedstorage2.option.grid.resourceTypeId": "Resource type", "text.autoconfig.refinedstorage2.option.grid.sortingDirection": "Sorting direction", "text.autoconfig.refinedstorage2.option.grid.sortingType": "Sorting type", "text.autoconfig.refinedstorage2.option.grid.size": "Size", diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/zh_cn.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/zh_cn.json index 80ba42bdc..d226f265b 100644 --- a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/zh_cn.json +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/zh_cn.json @@ -64,9 +64,9 @@ "gui.refinedstorage2.grid.synchronizer.rei.help": "将搜索框文本同步到 REI 过滤器。", "gui.refinedstorage2.grid.synchronizer.rei.two_way": "REI 双向", "gui.refinedstorage2.grid.synchronizer.rei.two_way.help": "将搜索框文本同步到 JEI 过滤器,并将 JEI 过滤器同步到搜索框文本。", - "gui.refinedstorage2.grid.storage_channel_type": "存储通道", - "gui.refinedstorage2.grid.storage_channel_type.all": "全部", - "gui.refinedstorage2.grid.storage_channel_type.help": "从特定的存储通道中过滤资源。", + "gui.refinedstorage2.grid.resource_type": "存储通道", + "gui.refinedstorage2.grid.resource_type.all": "全部", + "gui.refinedstorage2.grid.resource_type.help": "从特定的存储通道中过滤资源。", "gui.refinedstorage2.crafting_grid.move.network": "将物品移动到网络。", "gui.refinedstorage2.crafting_grid.move.inventory": "将物品移动到物品栏。", "gui.refinedstorage2.detector.mode": "模式", @@ -230,8 +230,8 @@ "misc.refinedstorage2.last_modified.weeks": "%d 周前由 %s 修改", "misc.refinedstorage2.last_modified.year": "%d 年前由 %s 修改", "misc.refinedstorage2.last_modified.years": "%d 年前由 %s 修改", - "misc.refinedstorage2.storage_channel_type.item": "物品", - "misc.refinedstorage2.storage_channel_type.fluid": "流体", + "misc.refinedstorage2.resource_type.item": "物品", + "misc.refinedstorage2.resource_type.fluid": "流体", "misc.refinedstorage2.press_shift_for_help": "按下 SHIFT 获取帮助", "key.refinedstorage2.focus_search_bar": "聚焦搜索栏", "key.refinedstorage2.clear_crafting_grid_matrix_to_network": "清除制作终端矩阵到网络", @@ -252,7 +252,7 @@ "text.autoconfig.refinedstorage2.option.grid.smoothScrolling": "平滑滚动", "text.autoconfig.refinedstorage2.option.grid.autoSelected": "自动选择搜索框", "text.autoconfig.refinedstorage2.option.grid.synchronizer": "同步器", - "text.autoconfig.refinedstorage2.option.grid.storageChannelType": "存储通道类型", + "text.autoconfig.refinedstorage2.option.grid.resourceTypeId": "存储通道类型", "text.autoconfig.refinedstorage2.option.grid.sortingDirection": "排序方向", "text.autoconfig.refinedstorage2.option.grid.sortingType": "排序类型", "text.autoconfig.refinedstorage2.option.grid.size": "大小", diff --git a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/PlatformTestFixtures.java b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/PlatformTestFixtures.java index e617e9d33..84b25d394 100644 --- a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/PlatformTestFixtures.java +++ b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/PlatformTestFixtures.java @@ -8,7 +8,7 @@ import net.minecraft.resources.ResourceLocation; public final class PlatformTestFixtures { - public static final PlatformRegistry> STORAGE_TYPE_REGISTRY = new PlatformRegistryImpl<>( + public static final PlatformRegistry STORAGE_TYPE_REGISTRY = new PlatformRegistryImpl<>( new ResourceLocation("item"), StorageTypes.ITEM ); diff --git a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/TestPlatform.java b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/TestPlatform.java index 9dc2cf9c9..5f1e86fef 100644 --- a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/TestPlatform.java +++ b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/TestPlatform.java @@ -4,13 +4,13 @@ import com.refinedmods.refinedstorage2.api.grid.view.GridResourceFactory; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridInsertionStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.support.ClientToServerCommunications; import com.refinedmods.refinedstorage2.platform.common.support.ServerToClientCommunications; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.MenuOpener; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.TransferManager; import com.refinedmods.refinedstorage2.platform.common.support.render.FluidRenderer; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.List; import java.util.Optional; diff --git a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/grid/GridSortingTypesTest.java b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/grid/GridSortingTypesTest.java index 6a3c64e86..5257a4a34 100644 --- a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/grid/GridSortingTypesTest.java +++ b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/grid/GridSortingTypesTest.java @@ -7,8 +7,8 @@ import com.refinedmods.refinedstorage2.api.grid.view.GridViewBuilder; import com.refinedmods.refinedstorage2.api.grid.view.GridViewBuilderImpl; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.grid.view.AbstractItemGridResourceFactory; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.test.SetupMinecraft; import java.util.Comparator; diff --git a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/FluidStorageTypeTest.java b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/FluidStorageTypeTest.java index 88a44c6bf..dfbfd1832 100644 --- a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/FluidStorageTypeTest.java +++ b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/FluidStorageTypeTest.java @@ -13,8 +13,8 @@ import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedStorageImpl; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; import com.refinedmods.refinedstorage2.platform.api.storage.StorageType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.common.SimpleListener; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.test.SetupMinecraft; import net.minecraft.nbt.CompoundTag; @@ -27,7 +27,7 @@ @SetupMinecraft class FluidStorageTypeTest { - StorageType sut = StorageTypes.FLUID; + StorageType sut = StorageTypes.FLUID; SimpleListener listener; @BeforeEach @@ -38,9 +38,9 @@ void setUp() { @Test void shouldSerializeAndDeserializeRegularStorage() { // Arrange - final InMemoryTrackedStorageRepository tracker = new InMemoryTrackedStorageRepository<>(); - final Storage storage = new PlatformStorage<>( - new TrackedStorageImpl<>(new InMemoryStorageImpl<>(), tracker, () -> 123L), + final InMemoryTrackedStorageRepository tracker = new InMemoryTrackedStorageRepository(); + final Storage storage = new PlatformStorage( + new TrackedStorageImpl(new InMemoryStorageImpl(), tracker, () -> 123L), StorageTypes.FLUID, tracker, () -> { @@ -52,20 +52,20 @@ void shouldSerializeAndDeserializeRegularStorage() { // Act final CompoundTag serialized = sut.toTag(storage); - final Storage deserialized = sut.fromTag(serialized, listener); + final Storage deserialized = sut.fromTag(serialized, listener); // Assert assertThat(listener.isChanged()).isFalse(); assertThat(deserialized).isInstanceOf(PlatformStorage.class); assertThat(deserialized.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>(new FluidResource(Fluids.WATER, createDummyTag()), 10), - new ResourceAmount<>(new FluidResource(Fluids.LAVA, null), 15) + new ResourceAmount(new FluidResource(Fluids.WATER, createDummyTag()), 10), + new ResourceAmount(new FluidResource(Fluids.LAVA, null), 15) ); - assertThat(((TrackedStorage) deserialized).findTrackedResourceByActorType( + assertThat(((TrackedStorage) deserialized).findTrackedResourceByActorType( new FluidResource(Fluids.WATER, createDummyTag()), PlayerActor.class )).get().usingRecursiveComparison().isEqualTo(new TrackedResource("A", 123)); - assertThat(((TrackedStorage) deserialized).findTrackedResourceByActorType( + assertThat(((TrackedStorage) deserialized).findTrackedResourceByActorType( new FluidResource(Fluids.LAVA, null), PlayerActor.class )).isEmpty(); @@ -74,9 +74,9 @@ void shouldSerializeAndDeserializeRegularStorage() { @Test void shouldCallListenerOnDeserializedStorage() { // Arrange - final InMemoryTrackedStorageRepository tracker = new InMemoryTrackedStorageRepository<>(); - final Storage storage = new PlatformStorage<>( - new TrackedStorageImpl<>(new InMemoryStorageImpl<>(), tracker, () -> 123L), + final InMemoryTrackedStorageRepository tracker = new InMemoryTrackedStorageRepository(); + final Storage storage = new PlatformStorage( + new TrackedStorageImpl(new InMemoryStorageImpl(), tracker, () -> 123L), StorageTypes.FLUID, tracker, () -> { @@ -85,7 +85,7 @@ void shouldCallListenerOnDeserializedStorage() { storage.insert(new FluidResource(Fluids.WATER, null), 15, Action.EXECUTE, EmptyActor.INSTANCE); final CompoundTag serialized = sut.toTag(storage); - final Storage deserialized = sut.fromTag(serialized, listener); + final Storage deserialized = sut.fromTag(serialized, listener); // Act final boolean preInsert = listener.isChanged(); @@ -100,10 +100,10 @@ void shouldCallListenerOnDeserializedStorage() { @Test void shouldSerializeLimitedStorage() { // Arrange - final InMemoryTrackedStorageRepository tracker = new InMemoryTrackedStorageRepository<>(); - final Storage storage = new LimitedPlatformStorage<>( - new LimitedStorageImpl<>( - new TrackedStorageImpl<>(new InMemoryStorageImpl<>(), tracker, () -> 123L), + final InMemoryTrackedStorageRepository tracker = new InMemoryTrackedStorageRepository(); + final Storage storage = new LimitedPlatformStorage( + new LimitedStorageImpl( + new TrackedStorageImpl(new InMemoryStorageImpl(), tracker, () -> 123L), 100 ), StorageTypes.FLUID, @@ -117,21 +117,21 @@ void shouldSerializeLimitedStorage() { // Act final CompoundTag serialized = sut.toTag(storage); - final Storage deserialized = sut.fromTag(serialized, listener); + final Storage deserialized = sut.fromTag(serialized, listener); // Assert assertThat(listener.isChanged()).isFalse(); assertThat(deserialized).isInstanceOf(LimitedStorage.class); - assertThat(((LimitedStorage) deserialized).getCapacity()).isEqualTo(100); + assertThat(((LimitedStorage) deserialized).getCapacity()).isEqualTo(100); assertThat(deserialized.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>(new FluidResource(Fluids.WATER, createDummyTag()), 10), - new ResourceAmount<>(new FluidResource(Fluids.LAVA, null), 15) + new ResourceAmount(new FluidResource(Fluids.WATER, createDummyTag()), 10), + new ResourceAmount(new FluidResource(Fluids.LAVA, null), 15) ); - assertThat(((TrackedStorage) deserialized).findTrackedResourceByActorType( + assertThat(((TrackedStorage) deserialized).findTrackedResourceByActorType( new FluidResource(Fluids.WATER, createDummyTag()), PlayerActor.class )).get().usingRecursiveComparison().isEqualTo(new TrackedResource("A", 123)); - assertThat(((TrackedStorage) deserialized).findTrackedResourceByActorType( + assertThat(((TrackedStorage) deserialized).findTrackedResourceByActorType( new FluidResource(Fluids.LAVA, null), PlayerActor.class )).isEmpty(); diff --git a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/ItemStorageTypeTest.java b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/ItemStorageTypeTest.java index 79fcf3529..dbf632236 100644 --- a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/ItemStorageTypeTest.java +++ b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/ItemStorageTypeTest.java @@ -13,8 +13,8 @@ import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedStorageImpl; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; import com.refinedmods.refinedstorage2.platform.api.storage.StorageType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.SimpleListener; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.test.SetupMinecraft; import net.minecraft.nbt.CompoundTag; @@ -27,7 +27,7 @@ @SetupMinecraft class ItemStorageTypeTest { - StorageType sut = StorageTypes.ITEM; + StorageType sut = StorageTypes.ITEM; SimpleListener listener; @BeforeEach @@ -38,9 +38,9 @@ void setUp() { @Test void shouldSerializeAndDeserializeRegularStorage() { // Arrange - final InMemoryTrackedStorageRepository tracker = new InMemoryTrackedStorageRepository<>(); - final Storage storage = new PlatformStorage<>( - new TrackedStorageImpl<>(new InMemoryStorageImpl<>(), tracker, () -> 123L), + final InMemoryTrackedStorageRepository tracker = new InMemoryTrackedStorageRepository(); + final Storage storage = new PlatformStorage( + new TrackedStorageImpl(new InMemoryStorageImpl(), tracker, () -> 123L), StorageTypes.ITEM, tracker, () -> { @@ -52,20 +52,20 @@ void shouldSerializeAndDeserializeRegularStorage() { // Act final CompoundTag serialized = sut.toTag(storage); - final Storage deserialized = sut.fromTag(serialized, listener); + final Storage deserialized = sut.fromTag(serialized, listener); // Assert assertThat(listener.isChanged()).isFalse(); assertThat(deserialized).isInstanceOf(PlatformStorage.class); assertThat(deserialized.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>(new ItemResource(Items.DIRT, createDummyTag()), 10), - new ResourceAmount<>(new ItemResource(Items.GLASS, null), 15) + new ResourceAmount(new ItemResource(Items.DIRT, createDummyTag()), 10), + new ResourceAmount(new ItemResource(Items.GLASS, null), 15) ); - assertThat(((TrackedStorage) deserialized).findTrackedResourceByActorType( + assertThat(((TrackedStorage) deserialized).findTrackedResourceByActorType( new ItemResource(Items.DIRT, createDummyTag()), PlayerActor.class )).get().usingRecursiveComparison().isEqualTo(new TrackedResource("A", 123)); - assertThat(((TrackedStorage) deserialized).findTrackedResourceByActorType( + assertThat(((TrackedStorage) deserialized).findTrackedResourceByActorType( new ItemResource(Items.GLASS, null), PlayerActor.class )).isEmpty(); @@ -74,9 +74,9 @@ void shouldSerializeAndDeserializeRegularStorage() { @Test void shouldCallListenerOnDeserializedStorage() { // Arrange - final InMemoryTrackedStorageRepository tracker = new InMemoryTrackedStorageRepository<>(); - final Storage storage = new PlatformStorage<>( - new TrackedStorageImpl<>(new InMemoryStorageImpl<>(), tracker, () -> 123L), + final InMemoryTrackedStorageRepository tracker = new InMemoryTrackedStorageRepository(); + final Storage storage = new PlatformStorage( + new TrackedStorageImpl(new InMemoryStorageImpl(), tracker, () -> 123L), StorageTypes.ITEM, tracker, () -> { @@ -85,7 +85,7 @@ void shouldCallListenerOnDeserializedStorage() { storage.insert(new ItemResource(Items.GLASS, null), 15, Action.EXECUTE, EmptyActor.INSTANCE); final CompoundTag serialized = sut.toTag(storage); - final Storage deserialized = sut.fromTag(serialized, listener); + final Storage deserialized = sut.fromTag(serialized, listener); // Act final boolean preInsert = listener.isChanged(); @@ -100,9 +100,9 @@ void shouldCallListenerOnDeserializedStorage() { @Test void shouldSerializeLimitedStorage() { // Arrange - final InMemoryTrackedStorageRepository tracker = new InMemoryTrackedStorageRepository<>(); - final Storage storage = new LimitedPlatformStorage<>( - new LimitedStorageImpl<>(new TrackedStorageImpl<>(new InMemoryStorageImpl<>(), tracker, () -> 123L), 100), + final InMemoryTrackedStorageRepository tracker = new InMemoryTrackedStorageRepository(); + final Storage storage = new LimitedPlatformStorage( + new LimitedStorageImpl(new TrackedStorageImpl(new InMemoryStorageImpl(), tracker, () -> 123L), 100), StorageTypes.ITEM, tracker, () -> { @@ -114,21 +114,21 @@ void shouldSerializeLimitedStorage() { // Act final CompoundTag serialized = sut.toTag(storage); - final Storage deserialized = sut.fromTag(serialized, listener); + final Storage deserialized = sut.fromTag(serialized, listener); // Assert assertThat(listener.isChanged()).isFalse(); assertThat(deserialized).isInstanceOf(LimitedStorage.class); - assertThat(((LimitedStorage) deserialized).getCapacity()).isEqualTo(100); + assertThat(((LimitedStorage) deserialized).getCapacity()).isEqualTo(100); assertThat(deserialized.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>(new ItemResource(Items.DIRT, createDummyTag()), 10), - new ResourceAmount<>(new ItemResource(Items.GLASS, null), 15) + new ResourceAmount(new ItemResource(Items.DIRT, createDummyTag()), 10), + new ResourceAmount(new ItemResource(Items.GLASS, null), 15) ); - assertThat(((TrackedStorage) deserialized).findTrackedResourceByActorType( + assertThat(((TrackedStorage) deserialized).findTrackedResourceByActorType( new ItemResource(Items.DIRT, createDummyTag()), PlayerActor.class )).get().usingRecursiveComparison().isEqualTo(new TrackedResource("A", 123)); - assertThat(((TrackedStorage) deserialized).findTrackedResourceByActorType( + assertThat(((TrackedStorage) deserialized).findTrackedResourceByActorType( new ItemResource(Items.GLASS, null), PlayerActor.class )).isEmpty(); diff --git a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/LimitedPlatformStorageTest.java b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/LimitedPlatformStorageTest.java index 13558e964..a50f08e15 100644 --- a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/LimitedPlatformStorageTest.java +++ b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/LimitedPlatformStorageTest.java @@ -3,7 +3,6 @@ import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; import com.refinedmods.refinedstorage2.api.storage.limited.LimitedStorage; import com.refinedmods.refinedstorage2.api.storage.limited.LimitedStorageImpl; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -11,13 +10,13 @@ import static org.assertj.core.api.Assertions.assertThat; class LimitedPlatformStorageTest { - LimitedPlatformStorage sut; + LimitedPlatformStorage sut; @BeforeEach @SuppressWarnings("ConstantConditions") void setUp() { - final LimitedStorageImpl delegate = new LimitedStorageImpl<>(new InMemoryStorageImpl<>(), 100); - sut = new LimitedPlatformStorage<>(delegate, StorageTypes.ITEM, null, null); + final LimitedStorageImpl delegate = new LimitedStorageImpl(new InMemoryStorageImpl(), 100); + sut = new LimitedPlatformStorage(delegate, StorageTypes.ITEM, null, null); } @Test diff --git a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/PlatformStorageTest.java b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/PlatformStorageTest.java index 530a6dd3e..d86c9a56a 100644 --- a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/PlatformStorageTest.java +++ b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/PlatformStorageTest.java @@ -10,8 +10,8 @@ import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedStorageImpl; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedStorageRepository; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.SimpleListener; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.test.SetupMinecraft; import net.minecraft.world.item.Items; @@ -24,20 +24,19 @@ @SetupMinecraft class PlatformStorageTest { - PlatformStorage sut; + PlatformStorage sut; SimpleListener listener; @BeforeEach void setUp() { - final TrackedStorageRepository trackedStorageRepository = - new InMemoryTrackedStorageRepository<>(); - final TrackedStorageImpl delegate = new TrackedStorageImpl<>( - new LimitedStorageImpl<>(new InMemoryStorageImpl<>(), 100), + final TrackedStorageRepository trackedStorageRepository = new InMemoryTrackedStorageRepository(); + final TrackedStorageImpl delegate = new TrackedStorageImpl( + new LimitedStorageImpl(new InMemoryStorageImpl(), 100), trackedStorageRepository, () -> 0L ); listener = new SimpleListener(); - sut = new PlatformStorage<>(delegate, StorageTypes.ITEM, trackedStorageRepository, listener); + sut = new PlatformStorage(delegate, StorageTypes.ITEM, trackedStorageRepository, listener); } @Test @@ -56,9 +55,9 @@ void shouldLoadAndUpdateTrackedResources() { // Assert assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>(new ItemResource(Items.DIRT, null), 10), - new ResourceAmount<>(new ItemResource(Items.GLASS, null), 20), - new ResourceAmount<>(new ItemResource(Items.STONE, null), 30) + new ResourceAmount(new ItemResource(Items.DIRT, null), 10), + new ResourceAmount(new ItemResource(Items.GLASS, null), 20), + new ResourceAmount(new ItemResource(Items.STONE, null), 30) ); assertThat(sut.findTrackedResourceByActorType(new ItemResource(Items.DIRT, null), PlayerActor.class)) .get() @@ -83,7 +82,7 @@ void shouldInsert(final Action action) { if (action == Action.EXECUTE) { assertThat(listener.getChanges()).isEqualTo(2); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>(new ItemResource(Items.DIRT, null), 100) + new ResourceAmount(new ItemResource(Items.DIRT, null), 100) ); assertThat(sut.findTrackedResourceByActorType(new ItemResource(Items.DIRT, null), PlayerActor.class)) .get() diff --git a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageRepositoryImplTest.java b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageRepositoryImplTest.java index 38b516789..7ed352c33 100644 --- a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageRepositoryImplTest.java +++ b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/storage/StorageRepositoryImplTest.java @@ -12,8 +12,8 @@ import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedStorageImpl; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; import com.refinedmods.refinedstorage2.platform.api.storage.StorageInfo; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.PlatformTestFixtures; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.test.SetupMinecraft; import java.util.Optional; @@ -38,20 +38,20 @@ void setUp() { sut = new StorageRepositoryImpl(PlatformTestFixtures.STORAGE_TYPE_REGISTRY); } - private PlatformStorage createSerializableStorage(final Storage storage) { - if (storage instanceof LimitedStorageImpl limitedStorage) { - return new LimitedPlatformStorage<>( + private PlatformStorage createSerializableStorage(final Storage storage) { + if (storage instanceof LimitedStorageImpl limitedStorage) { + return new LimitedPlatformStorage( limitedStorage, StorageTypes.ITEM, - new InMemoryTrackedStorageRepository<>(), + new InMemoryTrackedStorageRepository(), () -> { } ); } - return new PlatformStorage<>( + return new PlatformStorage( storage, StorageTypes.ITEM, - new InMemoryTrackedStorageRepository<>(), + new InMemoryTrackedStorageRepository(), () -> { } ); @@ -73,14 +73,14 @@ void shouldNotRetrieveNonExistentStorage() { void shouldBeAbleToSetAndRetrieveStorage() { // Arrange final UUID id = UUID.randomUUID(); - final Storage storage = createSerializableStorage(new InMemoryStorageImpl<>()); + final Storage storage = createSerializableStorage(new InMemoryStorageImpl()); storage.insert(new ItemResource(Items.DIRT, null), 10, Action.EXECUTE, EmptyActor.INSTANCE); // Act sut.set(id, storage); // Assert - assertThat(sut.get(id)).containsSame(storage); + assertThat(sut.get(id)).containsSame(storage); assertThat(sut.isDirty()).isTrue(); assertThat(sut.getInfo(id)).usingRecursiveComparison().isEqualTo(new StorageInfo(10, 0)); } @@ -89,10 +89,10 @@ void shouldBeAbleToSetAndRetrieveStorage() { void shouldNotBeAbleToSetStorageWithExistingId() { // Arrange final UUID id = UUID.randomUUID(); - sut.set(id, createSerializableStorage(new InMemoryStorageImpl<>())); + sut.set(id, createSerializableStorage(new InMemoryStorageImpl())); // Act - final Executable action = () -> sut.set(id, createSerializableStorage(new InMemoryStorageImpl<>())); + final Executable action = () -> sut.set(id, createSerializableStorage(new InMemoryStorageImpl())); // Assert assertThrows(IllegalArgumentException.class, action); @@ -102,7 +102,7 @@ void shouldNotBeAbleToSetStorageWithExistingId() { void shouldNotBeAbleToSetUnserializableStorage() { // Arrange final UUID id = UUID.randomUUID(); - final InMemoryStorageImpl storage = new InMemoryStorageImpl<>(); + final InMemoryStorageImpl storage = new InMemoryStorageImpl(); // Act & assert assertThrows(IllegalArgumentException.class, () -> sut.set(id, storage)); @@ -112,7 +112,7 @@ void shouldNotBeAbleToSetUnserializableStorage() { @SuppressWarnings("ConstantConditions") void shouldNotBeAbleToSetWithInvalidId() { // Arrange - final Storage storage = createSerializableStorage(new InMemoryStorageImpl<>()); + final Storage storage = createSerializableStorage(new InMemoryStorageImpl()); // Act & assert assertThrows(NullPointerException.class, () -> sut.set(null, storage)); @@ -132,12 +132,12 @@ void shouldNotBeAbleToSetWithInvalidStorage() { void shouldRemoveIfEmpty() { // Arrange final UUID id = UUID.randomUUID(); - final Storage storage = createSerializableStorage(new InMemoryStorageImpl<>()); + final Storage storage = createSerializableStorage(new InMemoryStorageImpl()); sut.set(id, storage); sut.setDirty(false); // Act - final Optional> result = sut.removeIfEmpty(id); + final Optional result = sut.removeIfEmpty(id); // Assert assertThat(result).get().isEqualTo(storage); @@ -149,13 +149,13 @@ void shouldRemoveIfEmpty() { void shouldNotRemoveIfEmptyIfNotEmpty() { // Arrange final UUID id = UUID.randomUUID(); - final Storage storage = createSerializableStorage(new InMemoryStorageImpl<>()); + final Storage storage = createSerializableStorage(new InMemoryStorageImpl()); storage.insert(new ItemResource(Items.DIRT, null), 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.set(id, storage); sut.setDirty(false); // Act - final Optional> result = sut.removeIfEmpty(id); + final Optional result = sut.removeIfEmpty(id); // Assert assertThat(result).isEmpty(); @@ -166,7 +166,7 @@ void shouldNotRemoveIfEmptyIfNotEmpty() { @Test void shouldNotRemoveIfEmptyIfNotExists() { // Act - final Optional> disassembled = sut.removeIfEmpty(UUID.randomUUID()); + final Optional disassembled = sut.removeIfEmpty(UUID.randomUUID()); // Assert assertThat(disassembled).isEmpty(); @@ -186,7 +186,7 @@ void shouldBeDirtyWhenMarkedAsChanged() { void shouldRetrieveInfoFromLimitedStorage() { // Arrange final UUID id = UUID.randomUUID(); - final Storage storage = createSerializableStorage(new LimitedStorageImpl<>(10)); + final Storage storage = createSerializableStorage(new LimitedStorageImpl(10)); storage.insert(new ItemResource(Items.DIRT, null), 5, Action.EXECUTE, EmptyActor.INSTANCE); // Act @@ -203,7 +203,7 @@ void shouldRetrieveInfoFromLimitedStorage() { void shouldRetrieveInfoFromRegularStorage() { // Arrange final UUID id = UUID.randomUUID(); - final Storage storage = createSerializableStorage(new InMemoryStorageImpl<>()); + final Storage storage = createSerializableStorage(new InMemoryStorageImpl()); storage.insert(new ItemResource(Items.DIRT, null), 5, Action.EXECUTE, EmptyActor.INSTANCE); // Act @@ -227,20 +227,19 @@ void shouldRetrieveInfoFromNonExistentStorage() { } @Test - @SuppressWarnings({"unchecked", "rawtypes"}) void shouldSerializeAndDeserialize() { // Arrange - final InMemoryTrackedStorageRepository repository = new InMemoryTrackedStorageRepository<>(); - final PlatformStorage a = new PlatformStorage<>( - new TrackedStorageImpl<>(new InMemoryStorageImpl<>(), repository, () -> 123L), + final InMemoryTrackedStorageRepository repository = new InMemoryTrackedStorageRepository(); + final PlatformStorage a = new PlatformStorage( + new TrackedStorageImpl(new InMemoryStorageImpl(), repository, () -> 123L), StorageTypes.ITEM, repository, sut::markAsChanged ); - final PlatformStorage b = new LimitedPlatformStorage<>( - new LimitedStorageImpl<>(new InMemoryStorageImpl<>(), 100), + final PlatformStorage b = new LimitedPlatformStorage( + new LimitedStorageImpl(new InMemoryStorageImpl(), 100), StorageTypes.ITEM, - new InMemoryTrackedStorageRepository<>(), + new InMemoryTrackedStorageRepository(), sut::markAsChanged ); @@ -266,7 +265,7 @@ void shouldSerializeAndDeserialize() { .get() .isInstanceOf(PlatformStorage.class); assertThat(sut.get(aId).get().getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>(new ItemResource(Items.DIRT, createDummyTag()), 10) + new ResourceAmount(new ItemResource(Items.DIRT, createDummyTag()), 10) ); assertThat(((TrackedStorage) sut.get(aId).get()).findTrackedResourceByActorType( new ItemResource(Items.DIRT, createDummyTag()), PlayerActor.class)) @@ -276,7 +275,7 @@ void shouldSerializeAndDeserialize() { assertThat(sut.get(bId)).get().isInstanceOf(LimitedPlatformStorage.class); assertThat(((LimitedPlatformStorage) sut.get(bId).get()).getCapacity()).isEqualTo(100); assertThat(sut.get(bId).get().getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>(new ItemResource(Items.GLASS, null), 20) + new ResourceAmount(new ItemResource(Items.GLASS, null), 20) ); } } diff --git a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceRenderingTest.java b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceRenderingTest.java index 20b210dd4..ac09a1cd5 100644 --- a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceRenderingTest.java +++ b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceRenderingTest.java @@ -8,7 +8,7 @@ import static org.assertj.core.api.Assertions.assertThat; -public class FluidResourceRenderingTest { +class FluidResourceRenderingTest { private static final long BUCKET_AMOUNT = 1000; @BeforeAll diff --git a/refinedstorage2-platform-api/src/test/java/com/refinedmods/refinedstorage2/platform/api/support/resource/FluidResourceTest.java b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceTest.java similarity index 61% rename from refinedstorage2-platform-api/src/test/java/com/refinedmods/refinedstorage2/platform/api/support/resource/FluidResourceTest.java rename to refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceTest.java index e57fe1687..1df545f93 100644 --- a/refinedstorage2-platform-api/src/test/java/com/refinedmods/refinedstorage2/platform/api/support/resource/FluidResourceTest.java +++ b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/support/resource/FluidResourceTest.java @@ -1,6 +1,7 @@ -package com.refinedmods.refinedstorage2.platform.api.support.resource; +package com.refinedmods.refinedstorage2.platform.common.support.resource; -import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.test.SetupMinecraft; import java.util.Optional; @@ -33,39 +34,22 @@ void testSerialization(final boolean hasTag) { final FluidResource fluidResource = new FluidResource(Fluids.WATER, fluidTag); // Act - final CompoundTag serialized = FluidResource.toTag(fluidResource); - final Optional deserialized = FluidResource.fromTag(serialized); + final CompoundTag serialized = fluidResource.toTag(); + final Optional deserialized = FluidResource.fromTag(serialized); // Assert assertThat(deserialized).isPresent().contains(fluidResource); } - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void testSerializationWithAmount(final boolean hasTag) { - // Arrange - final CompoundTag fluidTag = hasTag ? createDummyTag() : null; - final FluidResource fluidResource = new FluidResource(Fluids.WATER, fluidTag); - final ResourceAmount resourceAmount = new ResourceAmount<>(fluidResource, 10); - - // Act - final CompoundTag serialized = FluidResource.toTagWithAmount(resourceAmount); - final Optional> deserialized = FluidResource.fromTagWithAmount(serialized); - - // Assert - assertThat(deserialized).isPresent(); - assertThat(deserialized.get()).usingRecursiveComparison().isEqualTo(resourceAmount); - } - @Test void testDeserializationWithInvalidFluid() { // Arrange final FluidResource fluidResource = new FluidResource(Fluids.WATER, null); - final CompoundTag serialized = FluidResource.toTag(fluidResource); + final CompoundTag serialized = fluidResource.toTag(); serialized.putString("id", "minecraft:non_existent"); // Act - final Optional deserialized = FluidResource.fromTag(serialized); + final Optional deserialized = FluidResource.fromTag(serialized); // Assert assertThat(deserialized).isEmpty(); @@ -79,11 +63,10 @@ void testNormalization(final boolean hasTag) { final FluidResource fluidResource = new FluidResource(Fluids.WATER, fluidTag); // Act - final FluidResource normalized = fluidResource.normalize(); + final ResourceKey normalized = fluidResource.normalize(); // Assert - assertThat(normalized.fluid()).isEqualTo(Fluids.WATER); - assertThat(normalized.tag()).isNull(); + assertThat(normalized).usingRecursiveComparison().isEqualTo(new FluidResource(Fluids.WATER, null)); } @Test diff --git a/refinedstorage2-platform-api/src/test/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ItemResourceTest.java b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResourceTest.java similarity index 65% rename from refinedstorage2-platform-api/src/test/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ItemResourceTest.java rename to refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResourceTest.java index 47dbf56ff..0d95f19a5 100644 --- a/refinedstorage2-platform-api/src/test/java/com/refinedmods/refinedstorage2/platform/api/support/resource/ItemResourceTest.java +++ b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/support/resource/ItemResourceTest.java @@ -1,6 +1,7 @@ -package com.refinedmods.refinedstorage2.platform.api.support.resource; +package com.refinedmods.refinedstorage2.platform.common.support.resource; -import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.test.SetupMinecraft; import java.util.Optional; @@ -35,39 +36,22 @@ void testSerialization(final boolean hasTag) { final ItemResource itemResource = new ItemResource(Items.DIRT, itemTag); // Act - final CompoundTag serialized = ItemResource.toTag(itemResource); - final Optional deserialized = ItemResource.fromTag(serialized); + final CompoundTag serialized = itemResource.toTag(); + final Optional deserialized = ItemResource.fromTag(serialized); // Assert assertThat(deserialized).isPresent().contains(itemResource); } - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void testSerializationWithAmount(final boolean hasTag) { - // Arrange - final CompoundTag itemTag = hasTag ? createDummyTag() : null; - final ItemResource itemResource = new ItemResource(Items.DIRT, itemTag); - final ResourceAmount resourceAmount = new ResourceAmount<>(itemResource, 10); - - // Act - final CompoundTag serialized = ItemResource.toTagWithAmount(resourceAmount); - final Optional> deserialized = ItemResource.fromTagWithAmount(serialized); - - // Assert - assertThat(deserialized).isPresent(); - assertThat(deserialized.get()).usingRecursiveComparison().isEqualTo(resourceAmount); - } - @Test void testDeserializationWithInvalidItem() { // Arrange final ItemResource itemResource = new ItemResource(Items.DIRT, null); - final CompoundTag serialized = ItemResource.toTag(itemResource); + final CompoundTag serialized = itemResource.toTag(); serialized.putString("id", "minecraft:non_existent"); // Act - final Optional deserialized = ItemResource.fromTag(serialized); + final Optional deserialized = ItemResource.fromTag(serialized); // Assert assertThat(deserialized).isEmpty(); @@ -97,11 +81,10 @@ void testNormalization(final boolean hasTag) { final ItemResource itemResource = new ItemResource(Items.DIRT, itemTag); // Act - final ItemResource normalized = itemResource.normalize(); + final ResourceKey normalized = itemResource.normalize(); // Assert - assertThat(normalized.item()).isEqualTo(Items.DIRT); - assertThat(normalized.tag()).isNull(); + assertThat(normalized).usingRecursiveComparison().isEqualTo(new ItemResource(Items.DIRT, null)); } @Test diff --git a/refinedstorage2-platform-api/src/test/java/com/refinedmods/refinedstorage2/platform/api/support/resource/list/FuzzyResourceListImplTest.java b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/support/resource/list/FuzzyResourceListImplTest.java similarity index 52% rename from refinedstorage2-platform-api/src/test/java/com/refinedmods/refinedstorage2/platform/api/support/resource/list/FuzzyResourceListImplTest.java rename to refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/support/resource/list/FuzzyResourceListImplTest.java index 54873b215..77b523331 100644 --- a/refinedstorage2-platform-api/src/test/java/com/refinedmods/refinedstorage2/platform/api/support/resource/list/FuzzyResourceListImplTest.java +++ b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/support/resource/list/FuzzyResourceListImplTest.java @@ -1,8 +1,9 @@ -package com.refinedmods.refinedstorage2.platform.api.support.resource.list; +package com.refinedmods.refinedstorage2.platform.common.support.resource.list; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.api.resource.list.ResourceListImpl; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.api.support.resource.list.FuzzyResourceList; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.test.SetupMinecraft; import java.util.Collection; @@ -23,11 +24,11 @@ class FuzzyResourceListImplTest { private static final ItemResource DUMMY_D = new ItemResource(Items.GLASS, null); private static final ItemResource DUMMY_E = new ItemResource(Items.DARK_OAK_DOOR, null); - FuzzyResourceList sut; + FuzzyResourceList sut; @BeforeEach void setUp() { - sut = new FuzzyResourceListImpl(new ResourceListImpl<>()); + sut = new FuzzyResourceListImpl(new ResourceListImpl()); } @Test @@ -45,42 +46,42 @@ void testRetrievingFuzzy() { sut.add(DUMMY_D, 15); // Act - final Optional> strictA = sut.get(DUMMY_A); - final Optional> strictB = sut.get(DUMMY_B); - final Optional> strictC = sut.get(DUMMY_C); - final Optional> strictD = sut.get(DUMMY_D); - final Optional> strictE = sut.get(DUMMY_E); - - final Collection> fuzzyA = sut.getFuzzy(DUMMY_A); - final Collection> fuzzyB = sut.getFuzzy(DUMMY_B); - final Collection> fuzzyC = sut.getFuzzy(DUMMY_C); - final Collection> fuzzyD = sut.getFuzzy(DUMMY_D); - final Collection> fuzzyE = sut.getFuzzy(DUMMY_E); + final Optional strictA = sut.get(DUMMY_A); + final Optional strictB = sut.get(DUMMY_B); + final Optional strictC = sut.get(DUMMY_C); + final Optional strictD = sut.get(DUMMY_D); + final Optional strictE = sut.get(DUMMY_E); + + final Collection fuzzyA = sut.getFuzzy(DUMMY_A); + final Collection fuzzyB = sut.getFuzzy(DUMMY_B); + final Collection fuzzyC = sut.getFuzzy(DUMMY_C); + final Collection fuzzyD = sut.getFuzzy(DUMMY_D); + final Collection fuzzyE = sut.getFuzzy(DUMMY_E); // Assert - assertThat(strictA).get().usingRecursiveComparison().isEqualTo(new ResourceAmount<>(DUMMY_A, 1)); - assertThat(strictB).get().usingRecursiveComparison().isEqualTo(new ResourceAmount<>(DUMMY_B, 15)); - assertThat(strictC).get().usingRecursiveComparison().isEqualTo(new ResourceAmount<>(DUMMY_C, 20)); - assertThat(strictD).get().usingRecursiveComparison().isEqualTo(new ResourceAmount<>(DUMMY_D, 25)); + assertThat(strictA).get().usingRecursiveComparison().isEqualTo(new ResourceAmount(DUMMY_A, 1)); + assertThat(strictB).get().usingRecursiveComparison().isEqualTo(new ResourceAmount(DUMMY_B, 15)); + assertThat(strictC).get().usingRecursiveComparison().isEqualTo(new ResourceAmount(DUMMY_C, 20)); + assertThat(strictD).get().usingRecursiveComparison().isEqualTo(new ResourceAmount(DUMMY_D, 25)); assertThat(strictE).isNotPresent(); assertThat(fuzzyA).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>(DUMMY_A, 1), - new ResourceAmount<>(DUMMY_B, 15), - new ResourceAmount<>(DUMMY_C, 20) + new ResourceAmount(DUMMY_A, 1), + new ResourceAmount(DUMMY_B, 15), + new ResourceAmount(DUMMY_C, 20) ); assertThat(fuzzyB).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>(DUMMY_A, 1), - new ResourceAmount<>(DUMMY_B, 15), - new ResourceAmount<>(DUMMY_C, 20) + new ResourceAmount(DUMMY_A, 1), + new ResourceAmount(DUMMY_B, 15), + new ResourceAmount(DUMMY_C, 20) ); assertThat(fuzzyC).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>(DUMMY_A, 1), - new ResourceAmount<>(DUMMY_B, 15), - new ResourceAmount<>(DUMMY_C, 20) + new ResourceAmount(DUMMY_A, 1), + new ResourceAmount(DUMMY_B, 15), + new ResourceAmount(DUMMY_C, 20) ); assertThat(fuzzyD).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>(DUMMY_D, 25) + new ResourceAmount(DUMMY_D, 25) ); assertThat(fuzzyE).isEmpty(); } @@ -102,30 +103,30 @@ void shouldRemoveEntireResourceFromFuzzyIndexAfterRemoval() { sut.add(DUMMY_D, 15); // Act - final Optional> strictA = sut.get(DUMMY_A); - final Optional> strictB = sut.get(DUMMY_B); - final Optional> strictC = sut.get(DUMMY_C); - final Optional> strictD = sut.get(DUMMY_D); - final Optional> strictE = sut.get(DUMMY_E); - - final Collection> fuzzyA = sut.getFuzzy(DUMMY_A); - final Collection> fuzzyB = sut.getFuzzy(DUMMY_B); - final Collection> fuzzyC = sut.getFuzzy(DUMMY_C); - final Collection> fuzzyD = sut.getFuzzy(DUMMY_D); - final Collection> fuzzyE = sut.getFuzzy(DUMMY_E); + final Optional strictA = sut.get(DUMMY_A); + final Optional strictB = sut.get(DUMMY_B); + final Optional strictC = sut.get(DUMMY_C); + final Optional strictD = sut.get(DUMMY_D); + final Optional strictE = sut.get(DUMMY_E); + + final Collection fuzzyA = sut.getFuzzy(DUMMY_A); + final Collection fuzzyB = sut.getFuzzy(DUMMY_B); + final Collection fuzzyC = sut.getFuzzy(DUMMY_C); + final Collection fuzzyD = sut.getFuzzy(DUMMY_D); + final Collection fuzzyE = sut.getFuzzy(DUMMY_E); // Assert assertThat(strictA).isNotPresent(); assertThat(strictB).isNotPresent(); assertThat(strictC).isNotPresent(); - assertThat(strictD).get().usingRecursiveComparison().isEqualTo(new ResourceAmount<>(DUMMY_D, 25)); + assertThat(strictD).get().usingRecursiveComparison().isEqualTo(new ResourceAmount(DUMMY_D, 25)); assertThat(strictE).isNotPresent(); assertThat(fuzzyA).isEmpty(); assertThat(fuzzyB).isEmpty(); assertThat(fuzzyC).isEmpty(); assertThat(fuzzyD).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>(DUMMY_D, 25) + new ResourceAmount(DUMMY_D, 25) ); assertThat(fuzzyE).isEmpty(); } @@ -145,39 +146,39 @@ void shouldRemoveSingleResourceFromFuzzyIndexAfterRemoval() { sut.add(DUMMY_D, 15); // Act - final Optional> strictA = sut.get(DUMMY_A); - final Optional> strictB = sut.get(DUMMY_B); - final Optional> strictC = sut.get(DUMMY_C); - final Optional> strictD = sut.get(DUMMY_D); - final Optional> strictE = sut.get(DUMMY_E); - - final Collection> fuzzyA = sut.getFuzzy(DUMMY_A); - final Collection> fuzzyB = sut.getFuzzy(DUMMY_B); - final Collection> fuzzyC = sut.getFuzzy(DUMMY_C); - final Collection> fuzzyD = sut.getFuzzy(DUMMY_D); - final Collection> fuzzyE = sut.getFuzzy(DUMMY_E); + final Optional strictA = sut.get(DUMMY_A); + final Optional strictB = sut.get(DUMMY_B); + final Optional strictC = sut.get(DUMMY_C); + final Optional strictD = sut.get(DUMMY_D); + final Optional strictE = sut.get(DUMMY_E); + + final Collection fuzzyA = sut.getFuzzy(DUMMY_A); + final Collection fuzzyB = sut.getFuzzy(DUMMY_B); + final Collection fuzzyC = sut.getFuzzy(DUMMY_C); + final Collection fuzzyD = sut.getFuzzy(DUMMY_D); + final Collection fuzzyE = sut.getFuzzy(DUMMY_E); // Assert assertThat(strictA).isNotPresent(); - assertThat(strictB).get().usingRecursiveComparison().isEqualTo(new ResourceAmount<>(DUMMY_B, 15)); - assertThat(strictC).get().usingRecursiveComparison().isEqualTo(new ResourceAmount<>(DUMMY_C, 20)); - assertThat(strictD).get().usingRecursiveComparison().isEqualTo(new ResourceAmount<>(DUMMY_D, 25)); + assertThat(strictB).get().usingRecursiveComparison().isEqualTo(new ResourceAmount(DUMMY_B, 15)); + assertThat(strictC).get().usingRecursiveComparison().isEqualTo(new ResourceAmount(DUMMY_C, 20)); + assertThat(strictD).get().usingRecursiveComparison().isEqualTo(new ResourceAmount(DUMMY_D, 25)); assertThat(strictE).isNotPresent(); assertThat(fuzzyA).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>(DUMMY_B, 15), - new ResourceAmount<>(DUMMY_C, 20) + new ResourceAmount(DUMMY_B, 15), + new ResourceAmount(DUMMY_C, 20) ); assertThat(fuzzyB).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>(DUMMY_B, 15), - new ResourceAmount<>(DUMMY_C, 20) + new ResourceAmount(DUMMY_B, 15), + new ResourceAmount(DUMMY_C, 20) ); assertThat(fuzzyC).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>(DUMMY_B, 15), - new ResourceAmount<>(DUMMY_C, 20) + new ResourceAmount(DUMMY_B, 15), + new ResourceAmount(DUMMY_C, 20) ); assertThat(fuzzyD).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>(DUMMY_D, 25) + new ResourceAmount(DUMMY_D, 25) ); assertThat(fuzzyE).isEmpty(); } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java index 8e919c6e7..18eac2b73 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java @@ -1,8 +1,8 @@ package com.refinedmods.refinedstorage2.platform.fabric; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.support.HelpTooltipComponent; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; import com.refinedmods.refinedstorage2.platform.api.upgrade.AbstractUpgradeItem; import com.refinedmods.refinedstorage2.platform.common.AbstractClientModInitializer; import com.refinedmods.refinedstorage2.platform.common.configurationcard.ConfigurationCardItemPropertyFunction; @@ -339,22 +339,22 @@ private void registerCustomTooltips() { if (data instanceof HelpTooltipComponent component) { return HelpClientTooltipComponent.create(component.text()); } - if (data instanceof RegulatorUpgradeItem.RegulatorTooltipComponent component) { + if (data instanceof RegulatorUpgradeItem.RegulatorTooltipComponent component) { final ClientTooltipComponent help = HelpClientTooltipComponent.create(component.helpText()); - return component.filteredResource() == null + return component.configuredResource() == null ? help - : createRegulatorUpgradeClientTooltipComponent(component.filteredResource(), help); + : createRegulatorUpgradeClientTooltipComponent(component.configuredResource(), help); } return null; }); } - private CompositeClientTooltipComponent createRegulatorUpgradeClientTooltipComponent( - final ResourceAmountTemplate filteredResource, + private CompositeClientTooltipComponent createRegulatorUpgradeClientTooltipComponent( + final ResourceAmount configuredResource, final ClientTooltipComponent help ) { return new CompositeClientTooltipComponent(List.of( - new ResourceClientTooltipComponent<>(filteredResource), + new ResourceClientTooltipComponent(configuredResource), help )); } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ConfigImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ConfigImpl.java index d6d95a1c5..a35756902 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ConfigImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ConfigImpl.java @@ -217,7 +217,7 @@ private static class GridEntryImpl implements GridEntry { private String synchronizer = ""; - private String storageChannelType = ""; + private String resourceTypeId = ""; private GridSortingDirection sortingDirection = GridSortingDirection.ASCENDING; @@ -325,22 +325,22 @@ public void setSize(final GridSize size) { } @Override - public Optional getStorageChannelType() { - if (storageChannelType == null || storageChannelType.trim().isBlank()) { + public Optional getResourceTypeId() { + if (resourceTypeId == null || resourceTypeId.trim().isBlank()) { return Optional.empty(); } - return Optional.of(storageChannelType).map(ResourceLocation::new); + return Optional.of(resourceTypeId).map(ResourceLocation::new); } @Override - public void setStorageChannelType(final ResourceLocation storageChannelTypeId) { - this.storageChannelType = storageChannelTypeId.toString(); + public void setResourceTypeId(final ResourceLocation resourceTypeId) { + this.resourceTypeId = resourceTypeId.toString(); save(); } @Override - public void clearStorageChannelType() { - this.storageChannelType = ""; + public void clearResourceType() { + this.resourceTypeId = ""; save(); } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java index 2a39d003a..93908e0ec 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java @@ -1,8 +1,6 @@ package com.refinedmods.refinedstorage2.platform.fabric; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.AbstractModInitializer; import com.refinedmods.refinedstorage2.platform.common.PlatformProxy; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; @@ -15,12 +13,13 @@ import com.refinedmods.refinedstorage2.platform.common.grid.WirelessGridItem; import com.refinedmods.refinedstorage2.platform.common.iface.InterfaceBlockEntity; import com.refinedmods.refinedstorage2.platform.common.iface.InterfacePlatformExternalStorageProviderFactory; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import com.refinedmods.refinedstorage2.platform.common.storage.diskdrive.AbstractDiskDriveBlockEntity; import com.refinedmods.refinedstorage2.platform.common.storage.portablegrid.PortableGridBlockItem; import com.refinedmods.refinedstorage2.platform.common.storage.portablegrid.PortableGridType; import com.refinedmods.refinedstorage2.platform.common.support.AbstractBaseBlock; import com.refinedmods.refinedstorage2.platform.common.support.packet.PacketIds; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.upgrade.RegulatorUpgradeItem; import com.refinedmods.refinedstorage2.platform.common.util.ServerEventQueue; import com.refinedmods.refinedstorage2.platform.fabric.exporter.FabricStorageExporterTransferStrategyFactory; @@ -52,7 +51,6 @@ import java.util.Arrays; import java.util.HashSet; -import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; @@ -133,9 +131,9 @@ private void registerImporterTransferStrategyFactories() { createIdentifier("item"), new FabricStorageImporterTransferStrategyFactory<>( ItemStorage.SIDED, - StorageChannelTypes.ITEM, VariantUtil::ofItemVariant, - VariantUtil::toItemVariant, + resource -> resource instanceof ItemResource itemResource + ? VariantUtil.toItemVariant(itemResource) : null, 1 ) ); @@ -143,9 +141,9 @@ private void registerImporterTransferStrategyFactories() { createIdentifier("fluid"), new FabricStorageImporterTransferStrategyFactory<>( FluidStorage.SIDED, - StorageChannelTypes.FLUID, VariantUtil::ofFluidVariant, - VariantUtil::toFluidVariant, + resource -> resource instanceof FluidResource fluidResource + ? VariantUtil.toFluidVariant(fluidResource) : null, FluidConstants.BUCKET ) ); @@ -156,11 +154,8 @@ private void registerExporterTransferStrategyFactories() { createIdentifier("item"), new FabricStorageExporterTransferStrategyFactory<>( ItemStorage.SIDED, - StorageChannelTypes.ITEM, resource -> resource instanceof ItemResource itemResource - ? Optional.of(itemResource) - : Optional.empty(), - VariantUtil::toItemVariant, + ? VariantUtil.toItemVariant(itemResource) : null, 1 ) ); @@ -168,11 +163,8 @@ private void registerExporterTransferStrategyFactories() { createIdentifier("fluid"), new FabricStorageExporterTransferStrategyFactory<>( FluidStorage.SIDED, - StorageChannelTypes.FLUID, resource -> resource instanceof FluidResource fluidResource - ? Optional.of(fluidResource) - : Optional.empty(), - VariantUtil::toFluidVariant, + ? VariantUtil.toFluidVariant(fluidResource) : null, FluidConstants.BUCKET ) ); @@ -182,17 +174,17 @@ private void registerExternalStorageProviderFactories() { PlatformApi.INSTANCE.addExternalStorageProviderFactory(new InterfacePlatformExternalStorageProviderFactory()); PlatformApi.INSTANCE.addExternalStorageProviderFactory( new FabricStoragePlatformExternalStorageProviderFactory<>( - StorageChannelTypes.ITEM, ItemStorage.SIDED, VariantUtil::ofItemVariant, - VariantUtil::toItemVariant + resource -> resource instanceof ItemResource itemResource + ? VariantUtil.toItemVariant(itemResource) : null )); PlatformApi.INSTANCE.addExternalStorageProviderFactory( new FabricStoragePlatformExternalStorageProviderFactory<>( - StorageChannelTypes.FLUID, FluidStorage.SIDED, VariantUtil::ofFluidVariant, - VariantUtil::toFluidVariant + resource -> resource instanceof FluidResource fluidResource + ? VariantUtil.toFluidVariant(fluidResource) : null )); } @@ -214,7 +206,7 @@ public boolean allowNbtUpdateAnimation(final Player player, return AbstractModInitializer.allowNbtUpdateAnimation(oldStack, newStack); } }, - () -> new WirelessGridItem(false) { + () -> new WirelessGridItem() { @Override public boolean allowNbtUpdateAnimation(final Player player, final InteractionHand hand, @@ -223,7 +215,7 @@ public boolean allowNbtUpdateAnimation(final Player player, return AbstractModInitializer.allowNbtUpdateAnimation(oldStack, newStack); } }, - () -> new WirelessGridItem(true) { + () -> new WirelessGridItem() { @Override public boolean allowNbtUpdateAnimation(final Player player, final InteractionHand hand, @@ -314,7 +306,6 @@ private void registerPackets() { ServerPlayNetworking.registerGlobalReceiver(PacketIds.USE_NETWORK_BOUND_ITEM, new UseNetworkBoundItemPacket()); } - @SuppressWarnings("checkstyle:Indentation") private void registerSidedHandlers() { registerItemStorage( AbstractDiskDriveBlockEntity.class::isInstance, diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/PlatformImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/PlatformImpl.java index b604fe442..6757008a1 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/PlatformImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/PlatformImpl.java @@ -3,12 +3,11 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.grid.view.GridResourceFactory; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; -import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.AbstractPlatform; import com.refinedmods.refinedstorage2.platform.common.Config; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.TransferManager; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.util.CustomBlockPlaceContext; import com.refinedmods.refinedstorage2.platform.fabric.grid.strategy.ItemGridInsertionStrategy; import com.refinedmods.refinedstorage2.platform.fabric.grid.view.FabricFluidGridResourceFactory; @@ -160,7 +159,8 @@ public Optional getContainedFluid(final ItemStack stack) { } return Optional.of(new ContainedFluid( interceptingStorage.getStack(), - new ResourceAmount<>(ofFluidVariant(extracted.resource()), extracted.amount()) + ofFluidVariant(extracted.resource()), + extracted.amount() )); } } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/exporter/FabricStorageExporterTransferStrategyFactory.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/exporter/FabricStorageExporterTransferStrategyFactory.java index ed5f49a3b..1e07454d2 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/exporter/FabricStorageExporterTransferStrategyFactory.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/exporter/FabricStorageExporterTransferStrategyFactory.java @@ -1,18 +1,16 @@ package com.refinedmods.refinedstorage2.platform.fabric.exporter; -import com.refinedmods.refinedstorage2.api.network.impl.node.exporter.AbstractExporterTransferStrategy; +import com.refinedmods.refinedstorage2.api.network.impl.node.exporter.ExporterTransferStrategyImpl; import com.refinedmods.refinedstorage2.api.network.node.exporter.ExporterTransferStrategy; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; import com.refinedmods.refinedstorage2.platform.api.exporter.ExporterTransferStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeState; import com.refinedmods.refinedstorage2.platform.common.content.Items; -import com.refinedmods.refinedstorage2.platform.common.exporter.AbstractFuzzyExporterTransferStrategy; +import com.refinedmods.refinedstorage2.platform.common.exporter.FuzzyExporterTransferStrategy; import com.refinedmods.refinedstorage2.platform.fabric.storage.FabricStorageInsertableStorage; -import java.util.Optional; import java.util.function.Function; -import javax.annotation.Nullable; import net.fabricmc.fabric.api.lookup.v1.block.BlockApiLookup; import net.fabricmc.fabric.api.transfer.v1.storage.Storage; @@ -20,21 +18,15 @@ import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; -public class FabricStorageExporterTransferStrategyFactory implements ExporterTransferStrategyFactory { - private final BlockApiLookup, Direction> lookup; - private final StorageChannelType storageChannelType; - private final Function toPlatformMapper; - private final Function> mapper; +public class FabricStorageExporterTransferStrategyFactory implements ExporterTransferStrategyFactory { + private final BlockApiLookup, Direction> lookup; + private final Function toPlatformMapper; private final long singleAmount; - public FabricStorageExporterTransferStrategyFactory(final BlockApiLookup, Direction> lookup, - final StorageChannelType storageChannelType, - final Function> mapper, - final Function toPlatformMapper, + public FabricStorageExporterTransferStrategyFactory(final BlockApiLookup, Direction> lookup, + final Function toPlatformMapper, final long singleAmount) { this.lookup = lookup; - this.storageChannelType = storageChannelType; - this.mapper = mapper; this.toPlatformMapper = toPlatformMapper; this.singleAmount = singleAmount; } @@ -46,7 +38,7 @@ public ExporterTransferStrategy create(final ServerLevel level, final UpgradeState upgradeState, final AmountOverride amountOverride, final boolean fuzzyMode) { - final FabricStorageInsertableStorage insertTarget = new FabricStorageInsertableStorage<>( + final FabricStorageInsertableStorage insertTarget = new FabricStorageInsertableStorage<>( lookup, toPlatformMapper, level, @@ -60,25 +52,12 @@ public ExporterTransferStrategy create(final ServerLevel level, return create(fuzzyMode, insertTarget, transferQuota); } - private AbstractExporterTransferStrategy create(final boolean fuzzyMode, - final FabricStorageInsertableStorage insertTarget, - final long transferQuota) { + private ExporterTransferStrategyImpl create(final boolean fuzzyMode, + final FabricStorageInsertableStorage insertTarget, + final long transferQuota) { if (fuzzyMode) { - return new AbstractFuzzyExporterTransferStrategy<>(insertTarget, storageChannelType, transferQuota) { - @Nullable - @Override - protected T tryConvert(final Object resource) { - return mapper.apply(resource).orElse(null); - } - }; + return new FuzzyExporterTransferStrategy(insertTarget, transferQuota); } - - return new AbstractExporterTransferStrategy<>(insertTarget, storageChannelType, transferQuota) { - @Nullable - @Override - protected T tryConvert(final Object resource) { - return mapper.apply(resource).orElse(null); - } - }; + return new ExporterTransferStrategyImpl(insertTarget, transferQuota); } } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/FluidGridExtractionStrategy.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/FluidGridExtractionStrategy.java index 1537bfc34..ea2616144 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/FluidGridExtractionStrategy.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/FluidGridExtractionStrategy.java @@ -8,10 +8,10 @@ import com.refinedmods.refinedstorage2.platform.api.grid.Grid; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridExtractionStrategy; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceTypes; import com.refinedmods.refinedstorage2.platform.fabric.util.SimpleSingleStackStorage; import net.fabricmc.fabric.api.transfer.v1.context.ContainerItemContext; @@ -30,25 +30,24 @@ public class FluidGridExtractionStrategy implements GridExtractionStrategy { private static final ItemVariant BUCKET_ITEM_VARIANT = ItemVariant.of(Items.BUCKET); private static final ItemResource BUCKET_ITEM_RESOURCE = new ItemResource(Items.BUCKET, null); - private final GridOperations gridOperations; + private final GridOperations gridOperations; private final PlayerInventoryStorage playerInventoryStorage; private final net.fabricmc.fabric.api.transfer.v1.storage.Storage playerCursorStorage; - private final Storage itemStorage; + private final Storage itemStorage; public FluidGridExtractionStrategy(final AbstractContainerMenu containerMenu, final Player player, final Grid grid) { - this.gridOperations = grid.createOperations(StorageChannelTypes.FLUID, new PlayerActor(player)); + this.gridOperations = grid.createOperations(ResourceTypes.FLUID, new PlayerActor(player)); this.playerInventoryStorage = PlayerInventoryStorage.of(player.getInventory()); this.playerCursorStorage = PlayerInventoryStorage.getCursorStorage(containerMenu); this.itemStorage = grid.getItemStorage(); } @Override - public boolean onExtract(final PlatformStorageChannelType storageChannelType, - final T resource, - final GridExtractMode extractMode, - final boolean cursor) { + public boolean onExtract(final PlatformResourceKey resource, + final GridExtractMode extractMode, + final boolean cursor) { if (resource instanceof FluidResource fluidResource) { final boolean bucketInInventory = hasBucketInInventory(); final boolean bucketInStorageChannel = hasBucketInStorage(); @@ -74,8 +73,11 @@ private void extractWithBucketInStorage(final FluidResource fluidResource, return; } gridOperations.extract(fluidResource, mode, (resource, amount, action, source) -> { + if (!(resource instanceof FluidResource fluidResource2)) { + return 0; + } try (Transaction tx = Transaction.openOuter()) { - final long inserted = destination.insert(toFluidVariant(resource), amount, tx); + final long inserted = destination.insert(toFluidVariant(fluidResource2), amount, tx); final boolean couldInsertBucket = insertResultingBucketIntoInventory(interceptingStorage, cursor, tx); if (!couldInsertBucket) { return 0; @@ -103,8 +105,11 @@ private void extractWithBucketInInventory(final FluidResource fluidResource, return; } gridOperations.extract(fluidResource, mode, (resource, amount, action, source) -> { + if (!(resource instanceof FluidResource fluidResource2)) { + return 0; + } try (Transaction innerTx = tx.openNested()) { - final long inserted = dest.insert(toFluidVariant(resource), amount, innerTx); + final long inserted = dest.insert(toFluidVariant(fluidResource2), amount, innerTx); final boolean couldInsertBucket = insertResultingBucketIntoInventory( interceptingStorage, cursor, diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/FluidGridInsertionStrategy.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/FluidGridInsertionStrategy.java index 13139cb8f..a02c50bcb 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/FluidGridInsertionStrategy.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/FluidGridInsertionStrategy.java @@ -6,8 +6,8 @@ import com.refinedmods.refinedstorage2.platform.api.grid.Grid; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridInsertionStrategy; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceTypes; import javax.annotation.Nullable; @@ -28,7 +28,7 @@ public class FluidGridInsertionStrategy implements GridInsertionStrategy { private final AbstractContainerMenu containerMenu; - private final GridOperations gridOperations; + private final GridOperations gridOperations; private final Player player; private final PlayerInventoryStorage playerInventoryStorage; @@ -36,7 +36,7 @@ public FluidGridInsertionStrategy(final AbstractContainerMenu containerMenu, final Player player, final Grid grid) { this.containerMenu = containerMenu; - this.gridOperations = grid.createOperations(StorageChannelTypes.FLUID, new PlayerActor(player)); + this.gridOperations = grid.createOperations(ResourceTypes.FLUID, new PlayerActor(player)); this.player = player; this.playerInventoryStorage = PlayerInventoryStorage.of(player.getInventory()); } @@ -53,7 +53,10 @@ public boolean onInsert(final GridInsertMode insertMode, final boolean tryAltern } final FluidResource fluidResource = ofFluidVariant(extractableResource); gridOperations.insert(fluidResource, insertMode, (resource, amount, action, source) -> { - final FluidVariant fluidVariant = toFluidVariant(resource); + if (!(resource instanceof FluidResource fluidResource2)) { + return 0; + } + final FluidVariant fluidVariant = toFluidVariant(fluidResource2); try (Transaction tx = Transaction.openOuter()) { final long extracted = cursorStorage.extract(fluidVariant, amount, tx); if (action == Action.EXECUTE) { @@ -92,7 +95,10 @@ public boolean onTransfer(final int slotIndex) { } final FluidResource fluidResource = ofFluidVariant(extractableResource); gridOperations.insert(fluidResource, GridInsertMode.ENTIRE_RESOURCE, (resource, amount, action, source) -> { - final FluidVariant fluidVariant = toFluidVariant(resource); + if (!(resource instanceof FluidResource fluidResource2)) { + return 0; + } + final FluidVariant fluidVariant = toFluidVariant(fluidResource2); try (Transaction tx = Transaction.openOuter()) { final long extracted = fluidSlotStorage.extract(fluidVariant, amount, tx); if (action == Action.EXECUTE) { diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/ItemGridExtractionStrategy.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/ItemGridExtractionStrategy.java index b77050ac4..b40f135fa 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/ItemGridExtractionStrategy.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/ItemGridExtractionStrategy.java @@ -6,9 +6,9 @@ import com.refinedmods.refinedstorage2.platform.api.grid.Grid; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridExtractionStrategy; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceTypes; import net.fabricmc.fabric.api.transfer.v1.item.ItemVariant; import net.fabricmc.fabric.api.transfer.v1.item.PlayerInventoryStorage; @@ -21,26 +21,28 @@ import static com.refinedmods.refinedstorage2.platform.fabric.support.resource.VariantUtil.toItemVariant; public class ItemGridExtractionStrategy implements GridExtractionStrategy { - private final GridOperations gridOperations; + private final GridOperations gridOperations; private final PlayerInventoryStorage playerInventoryStorage; private final SingleSlotStorage playerCursorStorage; public ItemGridExtractionStrategy(final AbstractContainerMenu containerMenu, final Player player, final Grid grid) { - this.gridOperations = grid.createOperations(StorageChannelTypes.ITEM, new PlayerActor(player)); + this.gridOperations = grid.createOperations(ResourceTypes.ITEM, new PlayerActor(player)); this.playerInventoryStorage = PlayerInventoryStorage.of(player.getInventory()); this.playerCursorStorage = PlayerInventoryStorage.getCursorStorage(containerMenu); } @Override - public boolean onExtract(final PlatformStorageChannelType storageChannelType, - final T resource, - final GridExtractMode extractMode, - final boolean cursor) { + public boolean onExtract(final PlatformResourceKey resource, + final GridExtractMode extractMode, + final boolean cursor) { if (resource instanceof ItemResource itemResource) { gridOperations.extract(itemResource, extractMode, (r, amount, action, source) -> { - final ItemVariant itemVariant = toItemVariant(r); + if (!(r instanceof ItemResource itemResource2)) { + return 0; + } + final ItemVariant itemVariant = toItemVariant(itemResource2); try (Transaction tx = Transaction.openOuter()) { final long inserted = insert(itemVariant, amount, tx, cursor); if (action == Action.EXECUTE) { diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/ItemGridInsertionStrategy.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/ItemGridInsertionStrategy.java index ac9dfce0e..1632bea91 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/ItemGridInsertionStrategy.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/ItemGridInsertionStrategy.java @@ -6,8 +6,8 @@ import com.refinedmods.refinedstorage2.platform.api.grid.Grid; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridInsertionStrategy; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceTypes; import net.fabricmc.fabric.api.transfer.v1.item.InventoryStorage; import net.fabricmc.fabric.api.transfer.v1.item.ItemVariant; @@ -25,14 +25,14 @@ public class ItemGridInsertionStrategy implements GridInsertionStrategy { private final AbstractContainerMenu containerMenu; - private final GridOperations gridOperations; + private final GridOperations gridOperations; private final SingleSlotStorage playerCursorStorage; public ItemGridInsertionStrategy(final AbstractContainerMenu containerMenu, final Player player, final Grid grid) { this.containerMenu = containerMenu; - this.gridOperations = grid.createOperations(StorageChannelTypes.ITEM, new PlayerActor(player)); + this.gridOperations = grid.createOperations(ResourceTypes.ITEM, new PlayerActor(player)); this.playerCursorStorage = PlayerInventoryStorage.getCursorStorage(containerMenu); } @@ -44,8 +44,11 @@ public boolean onInsert(final GridInsertMode insertMode, final boolean tryAltern } final ItemResource itemResource = new ItemResource(carried.getItem(), carried.getTag()); gridOperations.insert(itemResource, insertMode, (resource, amount, action, source) -> { + if (!(resource instanceof ItemResource itemResource2)) { + return 0; + } try (Transaction tx = Transaction.openOuter()) { - final ItemVariant itemVariant = toItemVariant(resource); + final ItemVariant itemVariant = toItemVariant(itemResource2); final long extracted = playerCursorStorage.extract(itemVariant, amount, tx); if (action == Action.EXECUTE) { tx.commit(); @@ -67,8 +70,11 @@ public boolean onTransfer(final int slotIndex) { } final ItemResource itemResource = ofItemVariant(itemVariantInSlot); gridOperations.insert(itemResource, GridInsertMode.ENTIRE_RESOURCE, (resource, amount, action, source) -> { + if (!(resource instanceof ItemResource itemResource2)) { + return 0; + } try (Transaction tx = Transaction.openOuter()) { - final ItemVariant itemVariant = toItemVariant(resource); + final ItemVariant itemVariant = toItemVariant(itemResource2); final long extracted = storage.extract(itemVariant, amount, tx); if (action == Action.EXECUTE) { tx.commit(); diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/ItemGridScrollingStrategy.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/ItemGridScrollingStrategy.java index 7bfec47f0..7d51b15b0 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/ItemGridScrollingStrategy.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/strategy/ItemGridScrollingStrategy.java @@ -8,9 +8,9 @@ import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollMode; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridScrollingStrategy; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceTypes; import net.fabricmc.fabric.api.transfer.v1.item.ItemVariant; import net.fabricmc.fabric.api.transfer.v1.item.PlayerInventoryStorage; @@ -23,25 +23,20 @@ import static com.refinedmods.refinedstorage2.platform.fabric.support.resource.VariantUtil.toItemVariant; public class ItemGridScrollingStrategy implements GridScrollingStrategy { - private final GridOperations gridOperations; + private final GridOperations gridOperations; private final PlayerInventoryStorage playerInventoryStorage; private final SingleSlotStorage playerCursorStorage; public ItemGridScrollingStrategy(final AbstractContainerMenu containerMenu, final Player player, final Grid grid) { - this.gridOperations = grid.createOperations(StorageChannelTypes.ITEM, new PlayerActor(player)); + this.gridOperations = grid.createOperations(ResourceTypes.ITEM, new PlayerActor(player)); this.playerInventoryStorage = PlayerInventoryStorage.of(player.getInventory()); this.playerCursorStorage = PlayerInventoryStorage.getCursorStorage(containerMenu); } @Override - public boolean onScroll( - final PlatformStorageChannelType storageChannelType, - final T resource, - final GridScrollMode scrollMode, - final int slotIndex - ) { + public boolean onScroll(final PlatformResourceKey resource, final GridScrollMode scrollMode, final int slotIndex) { if (resource instanceof ItemResource itemResource) { final Storage playerStorage = slotIndex >= 0 ? playerInventoryStorage.getSlot(slotIndex) @@ -59,8 +54,11 @@ public boolean onScroll( private void handleInventoryToGridScroll(final ItemResource itemResource, final Storage sourceStorage) { gridOperations.insert(itemResource, GridInsertMode.SINGLE_RESOURCE, (resource, amount, action, source) -> { + if (!(resource instanceof ItemResource itemResource2)) { + return 0; + } try (Transaction tx = Transaction.openOuter()) { - final ItemVariant itemVariant = toItemVariant(resource); + final ItemVariant itemVariant = toItemVariant(itemResource2); final long extracted = sourceStorage.extract(itemVariant, amount, tx); if (action == Action.EXECUTE) { tx.commit(); @@ -73,7 +71,10 @@ private void handleInventoryToGridScroll(final ItemResource itemResource, private void handleGridToInventoryScroll(final ItemResource itemResource, final Storage destinationStorage) { gridOperations.extract(itemResource, GridExtractMode.SINGLE_RESOURCE, (resource, amount, action, source) -> { - final ItemVariant itemVariant = toItemVariant(resource); + if (!(resource instanceof ItemResource itemResource2)) { + return 0; + } + final ItemVariant itemVariant = toItemVariant(itemResource2); try (Transaction tx = Transaction.openOuter()) { final long inserted = destinationStorage.insert(itemVariant, amount, tx); if (action == Action.EXECUTE) { diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/view/FabricFluidGridResourceFactory.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/view/FabricFluidGridResourceFactory.java index 7312ea82d..21eb541e1 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/view/FabricFluidGridResourceFactory.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/grid/view/FabricFluidGridResourceFactory.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.fabric.grid.view; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.common.grid.view.AbstractFluidGridResourceFactory; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import java.util.stream.Collectors; diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/importer/FabricStorageImporterSource.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/importer/FabricStorageImporterSource.java index bc34bcad1..aea89b31c 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/importer/FabricStorageImporterSource.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/importer/FabricStorageImporterSource.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.network.node.importer.ImporterSource; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; import com.refinedmods.refinedstorage2.platform.fabric.storage.FabricStorageExtractableStorage; @@ -22,16 +23,16 @@ import static com.google.common.collect.Iterators.filter; import static com.google.common.collect.Iterators.transform; -class FabricStorageImporterSource implements ImporterSource { - private final BlockApiCache, Direction> cache; - private final Function fromPlatformMapper; - private final FabricStorageInsertableStorage insertTarget; - private final FabricStorageExtractableStorage extractTarget; +class FabricStorageImporterSource implements ImporterSource { + private final BlockApiCache, Direction> cache; + private final Function fromPlatformMapper; + private final FabricStorageInsertableStorage insertTarget; + private final FabricStorageExtractableStorage extractTarget; private final Direction direction; - FabricStorageImporterSource(final BlockApiLookup, Direction> lookup, - final Function fromPlatformMapper, - final Function toPlatformMapper, + FabricStorageImporterSource(final BlockApiLookup, Direction> lookup, + final Function fromPlatformMapper, + final Function toPlatformMapper, final ServerLevel serverLevel, final BlockPos pos, final Direction direction, @@ -58,12 +59,12 @@ class FabricStorageImporterSource implements ImporterSource { } @Override - public Iterator getResources() { - final Storage

storage = cache.find(direction); + public Iterator getResources() { + final Storage storage = cache.find(direction); if (storage == null) { return Collections.emptyListIterator(); } - final Iterator> iterator = storage.iterator(); + final Iterator> iterator = storage.iterator(); return transform( filter(iterator, storageView -> !storageView.isResourceBlank()), storageView -> fromPlatformMapper.apply(storageView.getResource()) @@ -71,12 +72,12 @@ public Iterator getResources() { } @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return extractTarget.extract(resource, amount, action, actor); } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return insertTarget.insert(resource, amount, action, actor); } } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/importer/FabricStorageImporterTransferStrategyFactory.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/importer/FabricStorageImporterTransferStrategyFactory.java index 4d3ad81be..0d0dd8a1d 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/importer/FabricStorageImporterTransferStrategyFactory.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/importer/FabricStorageImporterTransferStrategyFactory.java @@ -3,7 +3,7 @@ import com.refinedmods.refinedstorage2.api.network.node.importer.ImporterSource; import com.refinedmods.refinedstorage2.api.network.node.importer.ImporterTransferStrategy; import com.refinedmods.refinedstorage2.api.network.node.importer.ImporterTransferStrategyImpl; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; import com.refinedmods.refinedstorage2.platform.api.importer.ImporterTransferStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeState; @@ -17,20 +17,17 @@ import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; -public class FabricStorageImporterTransferStrategyFactory implements ImporterTransferStrategyFactory { +public class FabricStorageImporterTransferStrategyFactory

implements ImporterTransferStrategyFactory { private final BlockApiLookup, Direction> lookup; - private final StorageChannelType storageChannelType; - private final Function fromPlatformMapper; - private final Function toPlatformMapper; + private final Function fromPlatformMapper; + private final Function toPlatformMapper; private final long singleAmount; public FabricStorageImporterTransferStrategyFactory(final BlockApiLookup, Direction> lookup, - final StorageChannelType storageChannelType, - final Function fromPlatformMapper, - final Function toPlatformMapper, + final Function fromPlatformMapper, + final Function toPlatformMapper, final long singleAmount) { this.lookup = lookup; - this.storageChannelType = storageChannelType; this.fromPlatformMapper = fromPlatformMapper; this.toPlatformMapper = toPlatformMapper; this.singleAmount = singleAmount; @@ -42,7 +39,7 @@ public ImporterTransferStrategy create(final ServerLevel level, final Direction direction, final UpgradeState upgradeState, final AmountOverride amountOverride) { - final ImporterSource source = new FabricStorageImporterSource<>( + final ImporterSource source = new FabricStorageImporterSource<>( lookup, fromPlatformMapper, toPlatformMapper, @@ -51,10 +48,9 @@ public ImporterTransferStrategy create(final ServerLevel level, direction, amountOverride ); - return new ImporterTransferStrategyImpl<>( - source, - storageChannelType, - upgradeState.has(Items.INSTANCE.getStackUpgrade()) ? singleAmount * 64 : singleAmount - ); + final long transferQuota = upgradeState.has(Items.INSTANCE.getStackUpgrade()) + ? singleAmount * 64 + : singleAmount; + return new ImporterTransferStrategyImpl(source, transferQuota); } } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/ClientToServerCommunicationsImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/ClientToServerCommunicationsImpl.java index d208274f4..064d16ddb 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/ClientToServerCommunicationsImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/ClientToServerCommunicationsImpl.java @@ -4,13 +4,13 @@ import com.refinedmods.refinedstorage2.api.grid.operations.GridInsertMode; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollMode; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; import com.refinedmods.refinedstorage2.platform.api.support.network.bounditem.SlotReference; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.support.ClientToServerCommunications; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.PropertyType; import com.refinedmods.refinedstorage2.platform.common.support.packet.PacketIds; -import com.refinedmods.refinedstorage2.platform.common.util.PacketUtil; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.List; import java.util.UUID; @@ -23,33 +23,29 @@ public class ClientToServerCommunicationsImpl implements ClientToServerCommunications { @Override - public void sendGridExtract(final PlatformStorageChannelType storageChannelType, - final T resource, - final GridExtractMode mode, - final boolean cursor) { - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().getId(storageChannelType).ifPresent(id -> sendToServer( + public void sendGridExtract(final PlatformResourceKey resource, final GridExtractMode mode, final boolean cursor) { + final ResourceType resourceType = resource.getResourceType(); + PlatformApi.INSTANCE.getResourceTypeRegistry().getId(resourceType).ifPresent(id -> sendToServer( PacketIds.GRID_EXTRACT, buf -> { buf.writeResourceLocation(id); GridExtractPacket.writeMode(buf, mode); buf.writeBoolean(cursor); - storageChannelType.toBuffer(resource, buf); + resource.toBuffer(buf); } )); } @Override - public void sendGridScroll(final PlatformStorageChannelType storageChannelType, - final T resource, - final GridScrollMode mode, - final int slotIndex) { - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().getId(storageChannelType).ifPresent(id -> sendToServer( + public void sendGridScroll(final PlatformResourceKey resource, final GridScrollMode mode, final int slotIndex) { + final ResourceType resourceType = resource.getResourceType(); + PlatformApi.INSTANCE.getResourceTypeRegistry().getId(resourceType).ifPresent(id -> sendToServer( PacketIds.GRID_SCROLL, buf -> { buf.writeResourceLocation(id); GridScrollPacket.writeMode(buf, mode); buf.writeInt(slotIndex); - storageChannelType.toBuffer(resource, buf); + resource.toBuffer(buf); } )); } @@ -74,7 +70,7 @@ public void sendCraftingGridRecipeTransfer(final List> recipe for (final List slotPossibilities : recipe) { buf.writeInt(slotPossibilities.size()); for (final ItemResource slotPossibility : slotPossibilities) { - PacketUtil.writeItemResource(buf, slotPossibility); + slotPossibility.toBuffer(buf); } } }); @@ -101,16 +97,14 @@ public void sendResourceSlotChange(final int slotIndex, final boolean tryAlterna }); } - @Override - public void sendResourceFilterSlotChange(final PlatformStorageChannelType storageChannelType, - final T resource, - final int slotIndex) { - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().getId(storageChannelType) + public void sendResourceFilterSlotChange(final PlatformResourceKey resource, final int slotIndex) { + final ResourceType resourceType = resource.getResourceType(); + PlatformApi.INSTANCE.getResourceTypeRegistry().getId(resourceType) .ifPresent(id -> sendToServer(PacketIds.RESOURCE_FILTER_SLOT_CHANGE, buf -> { buf.writeInt(slotIndex); buf.writeResourceLocation(id); - storageChannelType.toBuffer(resource, buf); + resource.toBuffer(buf); })); } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/CraftingGridRecipeTransferPacket.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/CraftingGridRecipeTransferPacket.java index 40e57730e..4efffd0da 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/CraftingGridRecipeTransferPacket.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/CraftingGridRecipeTransferPacket.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.fabric.packet.c2s; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.grid.CraftingGridContainerMenu; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.util.PacketUtil; import java.util.ArrayList; diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/GridExtractPacket.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/GridExtractPacket.java index b548b2eaa..da105453e 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/GridExtractPacket.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/GridExtractPacket.java @@ -3,7 +3,8 @@ import com.refinedmods.refinedstorage2.api.grid.operations.GridExtractMode; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridExtractionStrategy; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import net.fabricmc.fabric.api.networking.v1.PacketSender; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; @@ -23,21 +24,21 @@ public void receive(final MinecraftServer server, final FriendlyByteBuf buf, final PacketSender responseSender) { final ResourceLocation id = buf.readResourceLocation(); - PlatformApi.INSTANCE.getStorageChannelTypeRegistry() + PlatformApi.INSTANCE.getResourceTypeRegistry() .get(id) .ifPresent(type -> handle(type, buf, player, server)); } - private void handle(final PlatformStorageChannelType type, - final FriendlyByteBuf buf, - final Player player, - final MinecraftServer server) { + private void handle(final ResourceType type, + final FriendlyByteBuf buf, + final Player player, + final MinecraftServer server) { final AbstractContainerMenu menu = player.containerMenu; if (menu instanceof GridExtractionStrategy strategy) { final GridExtractMode mode = getMode(buf.readByte()); final boolean cursor = buf.readBoolean(); - final T resource = type.fromBuffer(buf); - server.execute(() -> strategy.onExtract(type, resource, mode, cursor)); + final PlatformResourceKey resource = type.fromBuffer(buf); + server.execute(() -> strategy.onExtract(resource, mode, cursor)); } } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/GridScrollPacket.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/GridScrollPacket.java index c67e5d2f1..81bb55218 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/GridScrollPacket.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/GridScrollPacket.java @@ -3,7 +3,8 @@ import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollMode; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridScrollingStrategy; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import net.fabricmc.fabric.api.networking.v1.PacketSender; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; @@ -23,21 +24,21 @@ public void receive(final MinecraftServer server, final FriendlyByteBuf buf, final PacketSender responseSender) { final ResourceLocation id = buf.readResourceLocation(); - PlatformApi.INSTANCE.getStorageChannelTypeRegistry() + PlatformApi.INSTANCE.getResourceTypeRegistry() .get(id) .ifPresent(type -> handle(type, buf, player, server)); } - private void handle(final PlatformStorageChannelType type, - final FriendlyByteBuf buf, - final Player player, - final MinecraftServer server) { + private void handle(final ResourceType type, + final FriendlyByteBuf buf, + final Player player, + final MinecraftServer server) { final AbstractContainerMenu menu = player.containerMenu; if (menu instanceof GridScrollingStrategy strategy) { final GridScrollMode mode = getMode(buf.readByte()); final int slotIndex = buf.readInt(); - final T resource = type.fromBuffer(buf); - server.execute(() -> strategy.onScroll(type, resource, mode, slotIndex)); + final PlatformResourceKey resource = type.fromBuffer(buf); + server.execute(() -> strategy.onScroll(resource, mode, slotIndex)); } } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/ResourceFilterSlotChangePacket.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/ResourceFilterSlotChangePacket.java index 3e1329cf1..eb56e7747 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/ResourceFilterSlotChangePacket.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/ResourceFilterSlotChangePacket.java @@ -1,7 +1,8 @@ package com.refinedmods.refinedstorage2.platform.fabric.packet.c2s; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.AbstractResourceContainerMenu; import net.fabricmc.fabric.api.networking.v1.PacketSender; @@ -20,21 +21,21 @@ public void receive(final MinecraftServer server, final FriendlyByteBuf buf, final PacketSender responseSender) { final int slotIndex = buf.readInt(); - final ResourceLocation storageChannelTypeId = buf.readResourceLocation(); - PlatformApi.INSTANCE.getStorageChannelTypeRegistry() - .get(storageChannelTypeId) - .ifPresent(storageChannelType -> handle(storageChannelType, buf, server, slotIndex, player)); + final ResourceLocation resourceTypeId = buf.readResourceLocation(); + PlatformApi.INSTANCE.getResourceTypeRegistry() + .get(resourceTypeId) + .ifPresent(resourceType -> handle(resourceType, buf, server, slotIndex, player)); } - private void handle(final PlatformStorageChannelType storageChannelType, - final FriendlyByteBuf buf, - final MinecraftServer server, - final int slotIndex, - final ServerPlayer serverPlayer) { - final T resource = storageChannelType.fromBuffer(buf); + private void handle(final ResourceType resourceType, + final FriendlyByteBuf buf, + final MinecraftServer server, + final int slotIndex, + final ServerPlayer serverPlayer) { + final PlatformResourceKey resource = resourceType.fromBuffer(buf); server.execute(() -> { if (serverPlayer.containerMenu instanceof AbstractResourceContainerMenu containerMenu) { - containerMenu.handleResourceFilterSlotUpdate(slotIndex, storageChannelType, resource); + containerMenu.handleResourceFilterSlotUpdate(slotIndex, resource); } }); } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/s2c/GridUpdatePacket.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/s2c/GridUpdatePacket.java index 7b0dfcab5..87e6a12e3 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/s2c/GridUpdatePacket.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/s2c/GridUpdatePacket.java @@ -1,8 +1,9 @@ package com.refinedmods.refinedstorage2.platform.fabric.packet.s2c; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.grid.AbstractGridContainerMenu; import com.refinedmods.refinedstorage2.platform.common.util.PacketUtil; @@ -20,13 +21,13 @@ public void receive(final Minecraft client, final FriendlyByteBuf buf, final PacketSender responseSender) { final ResourceLocation id = buf.readResourceLocation(); - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().get(id).ifPresent(type -> handle(type, buf, client)); + PlatformApi.INSTANCE.getResourceTypeRegistry().get(id).ifPresent(type -> handle(type, buf, client)); } - private void handle(final PlatformStorageChannelType type, - final FriendlyByteBuf buf, - final Minecraft client) { - final T resource = type.fromBuffer(buf); + private void handle(final ResourceType type, + final FriendlyByteBuf buf, + final Minecraft client) { + final ResourceKey resource = type.fromBuffer(buf); final long amount = buf.readLong(); final TrackedResource trackedResource = PacketUtil.readTrackedResource(buf); if (client.player.containerMenu instanceof AbstractGridContainerMenu containerMenu) { diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/s2c/ResourceSlotUpdatePacket.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/s2c/ResourceSlotUpdatePacket.java index 572eb8a41..19569352a 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/s2c/ResourceSlotUpdatePacket.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/s2c/ResourceSlotUpdatePacket.java @@ -1,8 +1,9 @@ package com.refinedmods.refinedstorage2.platform.fabric.packet.s2c; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.AbstractResourceContainerMenu; import java.util.function.Consumer; @@ -24,7 +25,7 @@ public void receive(final Minecraft client, final boolean present = buf.readBoolean(); if (present) { final ResourceLocation id = buf.readResourceLocation(); - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().get(id).ifPresent( + PlatformApi.INSTANCE.getResourceTypeRegistry().get(id).ifPresent( type -> handle(type, buf, client, slotIndex) ); } else { @@ -32,16 +33,15 @@ public void receive(final Minecraft client, } } - private void handle(final PlatformStorageChannelType type, - final FriendlyByteBuf buf, - final Minecraft client, - final int slotIndex) { - final T resource = type.fromBuffer(buf); + private void handle(final ResourceType type, + final FriendlyByteBuf buf, + final Minecraft client, + final int slotIndex) { + final ResourceKey resource = type.fromBuffer(buf); final long amount = buf.readLong(); - handle(client, containerMenu -> containerMenu.handleResourceSlotUpdate(slotIndex, new ResourceAmountTemplate<>( + handle(client, containerMenu -> containerMenu.handleResourceSlotUpdate(slotIndex, new ResourceAmount( resource, - amount, - type + amount ))); } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/s2c/ServerToClientCommunicationsImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/s2c/ServerToClientCommunicationsImpl.java index 35cc62353..19c2f4644 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/s2c/ServerToClientCommunicationsImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/s2c/ServerToClientCommunicationsImpl.java @@ -1,10 +1,11 @@ package com.refinedmods.refinedstorage2.platform.fabric.packet.s2c; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.storage.StorageInfo; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.networking.NetworkTransmitterStatus; import com.refinedmods.refinedstorage2.platform.common.support.ServerToClientCommunications; import com.refinedmods.refinedstorage2.platform.common.support.packet.PacketIds; @@ -40,17 +41,17 @@ public void sendGridActiveness(final ServerPlayer player, final boolean active) } @Override - public void sendGridUpdate(final ServerPlayer player, - final PlatformStorageChannelType storageChannelType, - final T resource, - final long change, - @Nullable final TrackedResource trackedResource) { - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().getId(storageChannelType).ifPresent(id -> sendToPlayer( + public void sendGridUpdate(final ServerPlayer player, + final PlatformResourceKey resource, + final long change, + @Nullable final TrackedResource trackedResource) { + final ResourceType resourceType = resource.getResourceType(); + PlatformApi.INSTANCE.getResourceTypeRegistry().getId(resourceType).ifPresent(id -> sendToPlayer( player, PacketIds.GRID_UPDATE, buf -> { buf.writeResourceLocation(id); - storageChannelType.toBuffer(resource, buf); + resource.toBuffer(buf); buf.writeLong(change); PacketUtil.writeTrackedResource(buf, trackedResource); } @@ -64,32 +65,28 @@ public void sendGridClear(final ServerPlayer player) { } @Override - public void sendResourceSlotUpdate(final ServerPlayer player, - @Nullable final ResourceAmountTemplate resourceAmount, - final int slotIndex) { + public void sendResourceSlotUpdate(final ServerPlayer player, + @Nullable final ResourceAmount resourceAmount, + final int slotIndex) { sendToPlayer(player, PacketIds.RESOURCE_SLOT_UPDATE, buf -> { buf.writeInt(slotIndex); - if (resourceAmount != null) { - sendResourceSlotUpdate( - resourceAmount.getStorageChannelType(), - resourceAmount.getResource(), - resourceAmount.getAmount(), - buf - ); + if (resourceAmount != null + && resourceAmount.getResource() instanceof PlatformResourceKey platformResource) { + sendResourceSlotUpdate(platformResource, resourceAmount.getAmount(), buf); } else { buf.writeBoolean(false); } }); } - private void sendResourceSlotUpdate(final PlatformStorageChannelType storageChannelType, - final T resource, - final long amount, - final FriendlyByteBuf buf) { - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().getId(storageChannelType).ifPresentOrElse(id -> { + private void sendResourceSlotUpdate(final PlatformResourceKey resource, + final long amount, + final FriendlyByteBuf buf) { + final ResourceType resourceType = resource.getResourceType(); + PlatformApi.INSTANCE.getResourceTypeRegistry().getId(resourceType).ifPresentOrElse(id -> { buf.writeBoolean(true); buf.writeResourceLocation(id); - storageChannelType.toBuffer(resource, buf); + resource.toBuffer(buf); buf.writeLong(amount); }, () -> buf.writeBoolean(false)); } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/CraftingGridTransferHandler.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/CraftingGridTransferHandler.java index 9f79443da..3b8878195 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/CraftingGridTransferHandler.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/CraftingGridTransferHandler.java @@ -1,8 +1,8 @@ package com.refinedmods.refinedstorage2.platform.fabric.recipemod.rei; import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.grid.CraftingGridContainerMenu; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.awt.Color; import java.util.List; @@ -38,7 +38,7 @@ public Result handle(final Context context) { doTransfer(ingredients, containerMenu); return Result.createSuccessful().blocksFurtherHandling(); } - final ResourceList available = containerMenu.getAvailableListForRecipeTransfer(); + final ResourceList available = containerMenu.getAvailableListForRecipeTransfer(); final MissingIngredients missingIngredients = findMissingIngredients(ingredients, available); if (missingIngredients.isEmpty()) { return Result.createSuccessful().blocksFurtherHandling(); @@ -56,7 +56,7 @@ private void doTransfer(final List ingredients, final CraftingG } private MissingIngredients findMissingIngredients(final List ingredients, - final ResourceList available) { + final ResourceList available) { final MissingIngredients missingIngredients = new MissingIngredients(); for (int i = 0; i < ingredients.size(); ++i) { final EntryIngredient ingredient = ingredients.get(i); @@ -70,7 +70,7 @@ private MissingIngredients findMissingIngredients(final List in return missingIngredients; } - private boolean isAvailable(final ResourceList available, final EntryIngredient ingredient) { + private boolean isAvailable(final ResourceList available, final EntryIngredient ingredient) { final List possibilities = convertIngredientToItemStacks(ingredient); for (final ItemStack possibility : possibilities) { final ItemResource possibilityResource = ItemResource.ofItemStack(possibility); diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/DraggableStackVisitorImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/DraggableStackVisitorImpl.java index 2158f1bbf..f8dd525f8 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/DraggableStackVisitorImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/DraggableStackVisitorImpl.java @@ -1,8 +1,7 @@ package com.refinedmods.refinedstorage2.platform.fabric.recipemod.rei; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.support.AbstractBaseScreen; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.AbstractResourceContainerMenu; @@ -38,7 +37,7 @@ public Stream getDraggableAcceptingBounds( final List bounds = new ArrayList<>(); ingredientConverter.convertToResource(value).ifPresent(resource -> { for (final ResourceSlot slot : menu.getResourceSlots()) { - if (slot.isFilter() && slot.isValid(resource.resource())) { + if (slot.isFilter() && slot.isValid(resource)) { bounds.add(BoundsProvider.ofRectangle(toRectangle(screen, slot))); } } @@ -55,26 +54,22 @@ public DraggedAcceptorResult acceptDraggedStack( final var menu = screen.getMenu(); final Object value = stack.getStack().getValue(); return ingredientConverter.convertToResource(value) - .map(resourceTemplate -> accept(context, menu, screen, resourceTemplate)) + .map(resource -> accept(context, menu, screen, resource)) .orElse(DraggedAcceptorResult.PASS); } - private DraggedAcceptorResult accept( + private DraggedAcceptorResult accept( final DraggingContext> context, final AbstractResourceContainerMenu menu, final AbstractBaseScreen screen, - final ResourceTemplate resource + final PlatformResourceKey resource ) { for (final ResourceSlot slot : menu.getResourceSlots()) { final Rectangle slotBounds = toRectangle(screen, slot); if (!slotBounds.contains(context.getCurrentPosition())) { continue; } - Platform.INSTANCE.getClientToServerCommunications().sendResourceFilterSlotChange( - (PlatformStorageChannelType) resource.storageChannelType(), - resource.resource(), - slot.index - ); + Platform.INSTANCE.getClientToServerCommunications().sendResourceFilterSlotChange(resource, slot.index); return DraggedAcceptorResult.ACCEPTED; } return DraggedAcceptorResult.PASS; diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/GridFocusedStackProvider.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/GridFocusedStackProvider.java index 0809e36cd..4ce3cb754 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/GridFocusedStackProvider.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/GridFocusedStackProvider.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.fabric.recipemod.rei; -import com.refinedmods.refinedstorage2.api.grid.view.GridResource; import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.grid.screen.AbstractGridScreen; import dev.architectury.event.CompoundEventResult; @@ -22,7 +22,7 @@ public CompoundEventResult> provide(final Screen screen, final Poi if (!(screen instanceof AbstractGridScreen gridScreen)) { return CompoundEventResult.pass(); } - final GridResource resource = gridScreen.getCurrentGridResource(); + final PlatformResourceKey resource = gridScreen.getCurrentResource(); if (resource == null) { return CompoundEventResult.pass(); } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/GridResourceIngredientConverter.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/GridResourceIngredientConverter.java deleted file mode 100644 index f55b41a25..000000000 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/GridResourceIngredientConverter.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.fabric.recipemod.rei; - -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; -import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; -import com.refinedmods.refinedstorage2.platform.common.grid.view.FluidGridResource; -import com.refinedmods.refinedstorage2.platform.common.grid.view.ItemGridResource; - -import java.util.Optional; - -import dev.architectury.fluid.FluidStack; -import me.shedaniel.rei.api.common.util.EntryStacks; - -class GridResourceIngredientConverter implements IngredientConverter { - @Override - public Optional> convertToResource(final Object ingredient) { - return Optional.empty(); - } - - @Override - public Optional convertToIngredient(final Object resource) { - if (resource instanceof ItemGridResource itemGridResource) { - return Optional.of(EntryStacks.of(itemGridResource.copyItemStack())); - } - if (resource instanceof FluidGridResource fluidGridResource) { - final FluidStack fluidStack = FluidStack.create( - fluidGridResource.getResource().fluid(), - FluidStack.bucketAmount(), - fluidGridResource.getResource().tag() - ); - return Optional.of(EntryStacks.of(fluidStack)); - } - return Optional.empty(); - } -} diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/IngredientConverterImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/IngredientConverterImpl.java new file mode 100644 index 000000000..454255833 --- /dev/null +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/IngredientConverterImpl.java @@ -0,0 +1,41 @@ +package com.refinedmods.refinedstorage2.platform.fabric.recipemod.rei; + +import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; + +import java.util.Optional; + +import dev.architectury.fluid.FluidStack; +import me.shedaniel.rei.api.common.util.EntryStacks; +import net.minecraft.world.item.ItemStack; + +class IngredientConverterImpl implements IngredientConverter { + @Override + public Optional convertToResource(final Object ingredient) { + if (ingredient instanceof FluidStack fluidStack) { + return Optional.of(new FluidResource(fluidStack.getFluid(), fluidStack.getTag())); + } + if (ingredient instanceof ItemStack itemStack) { + return Optional.of(ItemResource.ofItemStack(itemStack)); + } + return Optional.empty(); + } + + @Override + public Optional convertToIngredient(final PlatformResourceKey resource) { + if (resource instanceof ItemResource itemResource) { + return Optional.of(EntryStacks.of(itemResource.toItemStack())); + } + if (resource instanceof FluidResource fluidResource) { + final FluidStack fluidStack = FluidStack.create( + fluidResource.fluid(), + FluidStack.bucketAmount(), + fluidResource.tag() + ); + return Optional.of(EntryStacks.of(fluidStack)); + } + return Optional.empty(); + } +} diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/RefinedStorageREIClientPlugin.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/RefinedStorageREIClientPlugin.java index 5e52837ab..466e8260d 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/RefinedStorageREIClientPlugin.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/RefinedStorageREIClientPlugin.java @@ -11,7 +11,6 @@ import com.refinedmods.refinedstorage2.platform.common.support.AbstractBaseScreen; import java.util.function.Supplier; -import java.util.stream.Collectors; import me.shedaniel.rei.api.client.plugins.REIClientPlugin; import me.shedaniel.rei.api.client.registry.entry.CollapsibleEntryRegistry; @@ -46,8 +45,7 @@ public void registerTransferHandlers(final TransferHandlerRegistry registry) { } public static void registerIngredientConverters() { - PlatformApi.INSTANCE.registerIngredientConverter(new GridResourceIngredientConverter()); - PlatformApi.INSTANCE.registerIngredientConverter(new ResourceIngredientConverter()); + PlatformApi.INSTANCE.registerIngredientConverter(new IngredientConverterImpl()); } @Override @@ -76,7 +74,7 @@ public void registerCollapsibleEntries(final CollapsibleEntryRegistry registry) .map(Supplier::get) .map(ControllerBlockItem::createAtEnergyCapacity) .map(EntryStacks::of) - .collect(Collectors.toList()) + .toList() ); groupItems( registry, diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/ResourceFocusedStackProvider.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/ResourceFocusedStackProvider.java index e1d68f656..b69667c36 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/ResourceFocusedStackProvider.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/ResourceFocusedStackProvider.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.fabric.recipemod.rei; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.support.AbstractBaseScreen; import dev.architectury.event.CompoundEventResult; @@ -22,7 +22,7 @@ public CompoundEventResult> provide(final Screen screen, final Poi if (!(screen instanceof AbstractBaseScreen baseScreen)) { return CompoundEventResult.pass(); } - final ResourceTemplate hoveredResource = baseScreen.getHoveredResource(); + final PlatformResourceKey hoveredResource = baseScreen.getHoveredResource(); if (hoveredResource == null) { return CompoundEventResult.pass(); } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/ResourceIngredientConverter.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/ResourceIngredientConverter.java deleted file mode 100644 index 4e6debd8c..000000000 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/recipemod/rei/ResourceIngredientConverter.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.fabric.recipemod.rei; - -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; -import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; - -import java.util.Optional; - -import dev.architectury.fluid.FluidStack; -import me.shedaniel.rei.api.common.util.EntryStacks; -import net.minecraft.world.item.ItemStack; - -class ResourceIngredientConverter implements IngredientConverter { - @Override - public Optional> convertToResource(final Object ingredient) { - if (ingredient instanceof FluidStack fluidStack) { - return Optional.of(new ResourceTemplate<>( - new FluidResource(fluidStack.getFluid(), fluidStack.getTag()), - StorageChannelTypes.FLUID - )); - } - if (ingredient instanceof ItemStack itemStack) { - return Optional.of(new ResourceTemplate<>( - ItemResource.ofItemStack(itemStack), - StorageChannelTypes.ITEM - )); - } - return Optional.empty(); - } - - @Override - public Optional convertToIngredient(final Object resource) { - if (!(resource instanceof ResourceTemplate resourceTemplate)) { - return Optional.empty(); - } - if (resourceTemplate.resource() instanceof ItemResource itemResource) { - return Optional.of(EntryStacks.of(itemResource.toItemStack())); - } - if (resourceTemplate.resource() instanceof FluidResource fluidResource) { - final FluidStack fluidStack = FluidStack.create( - fluidResource.fluid(), - FluidStack.bucketAmount(), - fluidResource.tag() - ); - return Optional.of(EntryStacks.of(fluidStack)); - } - return Optional.empty(); - } -} diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/storage/FabricStorageExtractableStorage.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/storage/FabricStorageExtractableStorage.java index d5f1f3b25..086ff1250 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/storage/FabricStorageExtractableStorage.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/storage/FabricStorageExtractableStorage.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.platform.fabric.storage; import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.ExtractableStorage; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; @@ -15,14 +16,14 @@ import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; -public class FabricStorageExtractableStorage implements ExtractableStorage { +public class FabricStorageExtractableStorage

implements ExtractableStorage { private final BlockApiCache, Direction> cache; - private final Function toPlatformMapper; + private final Function toPlatformMapper; private final Direction direction; private final AmountOverride amountOverride; public FabricStorageExtractableStorage(final BlockApiLookup, Direction> lookup, - final Function toPlatformMapper, + final Function toPlatformMapper, final ServerLevel serverLevel, final BlockPos pos, final Direction direction, @@ -34,7 +35,7 @@ public FabricStorageExtractableStorage(final BlockApiLookup, Directio } @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { final Storage

storage = cache.find(direction); if (storage == null) { return 0L; @@ -51,7 +52,10 @@ public long extract(final T resource, final long amount, final Action action, fi return doExtract(resource, correctedAmount, action, storage); } - private long doExtract(final T resource, final long amount, final Action action, final Storage

storage) { + private long doExtract(final ResourceKey resource, + final long amount, + final Action action, + final Storage

storage) { try (Transaction tx = Transaction.openOuter()) { final long extract = storage.extract(toPlatformMapper.apply(resource), amount, tx); if (action == Action.EXECUTE) { diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/storage/FabricStorageInsertableStorage.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/storage/FabricStorageInsertableStorage.java index e9bbcf948..36ec5c2e4 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/storage/FabricStorageInsertableStorage.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/storage/FabricStorageInsertableStorage.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.platform.fabric.storage; import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; @@ -15,14 +16,14 @@ import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; -public class FabricStorageInsertableStorage implements InsertableStorage { - private final BlockApiCache, Direction> cache; - private final Function toPlatformMapper; +public class FabricStorageInsertableStorage implements InsertableStorage { + private final BlockApiCache, Direction> cache; + private final Function toPlatformMapper; private final Direction direction; private final AmountOverride amountOverride; - public FabricStorageInsertableStorage(final BlockApiLookup, Direction> lookup, - final Function toPlatformMapper, + public FabricStorageInsertableStorage(final BlockApiLookup, Direction> lookup, + final Function toPlatformMapper, final ServerLevel serverLevel, final BlockPos pos, final Direction direction, @@ -34,12 +35,12 @@ public FabricStorageInsertableStorage(final BlockApiLookup, Direction } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { - final Storage

storage = cache.find(direction); + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { + final Storage storage = cache.find(direction); if (storage == null) { return 0; } - final P platformResource = toPlatformMapper.apply(resource); + final T platformResource = toPlatformMapper.apply(resource); final long correctedAmount = amountOverride.overrideAmount( resource, amount, @@ -51,7 +52,7 @@ public long insert(final T resource, final long amount, final Action action, fin return doInsert(platformResource, correctedAmount, action, storage); } - private long doInsert(final P platformResource, final long amount, final Action action, final Storage

storage) { + private long doInsert(final T platformResource, final long amount, final Action action, final Storage storage) { try (Transaction tx = Transaction.openOuter()) { final long inserted = storage.insert(platformResource, amount, tx); if (action == Action.EXECUTE) { diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/storage/externalstorage/FabricStorageExternalStorageProvider.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/storage/externalstorage/FabricStorageExternalStorageProvider.java index 442949035..7b074823b 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/storage/externalstorage/FabricStorageExternalStorageProvider.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/storage/externalstorage/FabricStorageExternalStorageProvider.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.external.ExternalStorageProvider; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; @@ -23,16 +24,16 @@ import static com.google.common.collect.Iterators.filter; import static com.google.common.collect.Iterators.transform; -class FabricStorageExternalStorageProvider implements ExternalStorageProvider { +class FabricStorageExternalStorageProvider

implements ExternalStorageProvider { private final BlockApiCache, Direction> cache; - private final Function fromPlatformMapper; - private final FabricStorageExtractableStorage extractTarget; - private final FabricStorageInsertableStorage insertTarget; + private final Function fromPlatformMapper; + private final FabricStorageExtractableStorage

extractTarget; + private final FabricStorageInsertableStorage

insertTarget; private final Direction direction; FabricStorageExternalStorageProvider(final BlockApiLookup, Direction> lookup, - final Function fromPlatformMapper, - final Function toPlatformMapper, + final Function fromPlatformMapper, + final Function toPlatformMapper, final ServerLevel serverLevel, final BlockPos pos, final Direction direction) { @@ -58,17 +59,17 @@ class FabricStorageExternalStorageProvider implements ExternalStorageProvi } @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return extractTarget.extract(resource, amount, action, actor); } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return insertTarget.insert(resource, amount, action, actor); } @Override - public Iterator> iterator() { + public Iterator iterator() { final Storage

storage = cache.find(direction); if (storage == null) { return Collections.emptyListIterator(); @@ -76,7 +77,7 @@ public Iterator> iterator() { final Iterator> iterator = storage.iterator(); return transform( filter(iterator, storageView -> !storageView.isResourceBlank() && storageView.getAmount() > 0), - storageView -> new ResourceAmount<>( + storageView -> new ResourceAmount( fromPlatformMapper.apply(storageView.getResource()), storageView.getAmount() ) diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/storage/externalstorage/FabricStoragePlatformExternalStorageProviderFactory.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/storage/externalstorage/FabricStoragePlatformExternalStorageProviderFactory.java index 658d676dd..7c55e17ed 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/storage/externalstorage/FabricStoragePlatformExternalStorageProviderFactory.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/storage/externalstorage/FabricStoragePlatformExternalStorageProviderFactory.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.fabric.storage.externalstorage; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.external.ExternalStorageProvider; import com.refinedmods.refinedstorage2.platform.api.storage.externalstorage.PlatformExternalStorageProviderFactory; @@ -13,33 +13,25 @@ import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; -public class FabricStoragePlatformExternalStorageProviderFactory +public class FabricStoragePlatformExternalStorageProviderFactory implements PlatformExternalStorageProviderFactory { - private final StorageChannelType theStorageChannelType; - private final BlockApiLookup, Direction> lookup; - private final Function fromPlatformMapper; - private final Function toPlatformMapper; + private final BlockApiLookup, Direction> lookup; + private final Function fromPlatformMapper; + private final Function toPlatformMapper; - public FabricStoragePlatformExternalStorageProviderFactory(final StorageChannelType storageChannelType, - final BlockApiLookup, Direction> lookup, - final Function fromPlatformMapper, - final Function toPlatformMapper) { - this.theStorageChannelType = storageChannelType; + public FabricStoragePlatformExternalStorageProviderFactory(final BlockApiLookup, Direction> lookup, + final Function fromPlatformMapper, + final Function toPlatformMapper) { this.lookup = lookup; this.fromPlatformMapper = fromPlatformMapper; this.toPlatformMapper = toPlatformMapper; } @Override - @SuppressWarnings("unchecked") - public Optional> create(final ServerLevel level, - final BlockPos pos, - final Direction direction, - final StorageChannelType storageChannelType) { - if (storageChannelType != theStorageChannelType) { - return Optional.empty(); - } - return Optional.of((ExternalStorageProvider) new FabricStorageExternalStorageProvider<>( + public Optional create(final ServerLevel level, + final BlockPos pos, + final Direction direction) { + return Optional.of(new FabricStorageExternalStorageProvider<>( lookup, fromPlatformMapper, toPlatformMapper, diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/support/render/FluidVariantFluidRenderer.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/support/render/FluidVariantFluidRenderer.java index 063b62e4b..a63ca4f1c 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/support/render/FluidVariantFluidRenderer.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/support/render/FluidVariantFluidRenderer.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.fabric.support.render; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.common.support.render.AbstractFluidRenderer; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.fabric.support.resource.VariantUtil; import java.util.HashMap; diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/support/resource/ResourceContainerFluidStorageAdapter.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/support/resource/ResourceContainerFluidStorageAdapter.java index 24fdc375e..396a3875d 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/support/resource/ResourceContainerFluidStorageAdapter.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/support/resource/ResourceContainerFluidStorageAdapter.java @@ -1,10 +1,11 @@ package com.refinedmods.refinedstorage2.platform.fabric.support.resource; import com.refinedmods.refinedstorage2.api.core.Action; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceContainer; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import java.util.ArrayList; import java.util.Iterator; @@ -32,21 +33,11 @@ public ResourceContainerFluidStorageAdapter(final ResourceContainer resourceCont public long insert(final FluidVariant fluidVariant, final long maxAmount, final TransactionContext transaction) { StoragePreconditions.notBlankNotNegative(fluidVariant, maxAmount); final FluidResource fluidResource = ofFluidVariant(fluidVariant); - final long insertedSimulated = resourceContainer.insert( - StorageChannelTypes.FLUID, - fluidResource, - maxAmount, - Action.SIMULATE - ); + final long insertedSimulated = resourceContainer.insert(fluidResource, maxAmount, Action.SIMULATE); if (insertedSimulated > 0) { updateSnapshots(transaction); } - return resourceContainer.insert( - StorageChannelTypes.FLUID, - fluidResource, - maxAmount, - Action.EXECUTE - ); + return resourceContainer.insert(fluidResource, maxAmount, Action.EXECUTE); } @Override @@ -77,7 +68,7 @@ protected ResourceContainer createSnapshot() { @Override protected void readSnapshot(final ResourceContainer snapshot) { for (int i = 0; i < snapshot.size(); ++i) { - final ResourceAmountTemplate snapshotSlot = snapshot.get(i); + final ResourceAmount snapshotSlot = snapshot.get(i); if (snapshotSlot == null) { resourceContainer.remove(i); } else { @@ -95,13 +86,13 @@ private StorageViewImpl(final int index) { @Override public long extract(final FluidVariant resource, final long maxAmount, final TransactionContext transaction) { - final ResourceAmountTemplate slot = resourceContainer.get(index); - if (slot == null - || !(slot.getResource() instanceof FluidResource fluidResource) + final ResourceAmount resourceAmount = resourceContainer.get(index); + if (resourceAmount == null + || !(resourceAmount.getResource() instanceof FluidResource fluidResource) || !resource.equals(toFluidVariant(fluidResource))) { return 0; } - final long extracted = Math.min(maxAmount, slot.getAmount()); + final long extracted = Math.min(maxAmount, resourceAmount.getAmount()); if (extracted > 0) { updateSnapshots(transaction); } @@ -111,13 +102,13 @@ public long extract(final FluidVariant resource, final long maxAmount, final Tra @Override public boolean isResourceBlank() { - return resourceContainer.get(index) == null; + return resourceContainer.isEmpty(index); } @Override public FluidVariant getResource() { - final ResourceAmountTemplate slot = resourceContainer.get(index); - if (slot == null || !(slot.getResource() instanceof FluidResource fluidResource)) { + final PlatformResourceKey resource = resourceContainer.getResource(index); + if (!(resource instanceof FluidResource fluidResource)) { return FluidVariant.blank(); } return toFluidVariant(fluidResource); @@ -125,20 +116,16 @@ public FluidVariant getResource() { @Override public long getAmount() { - final ResourceAmountTemplate slot = resourceContainer.get(index); - if (slot == null) { - return 0; - } - return slot.getAmount(); + return resourceContainer.getAmount(index); } @Override public long getCapacity() { - final ResourceAmountTemplate slot = resourceContainer.get(index); - if (slot == null) { + final ResourceKey resource = resourceContainer.getResource(index); + if (resource == null) { return 0; } - return resourceContainer.getMaxAmount(slot); + return resourceContainer.getMaxAmount(resource); } } } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/support/resource/VariantUtil.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/support/resource/VariantUtil.java index 2713c50e9..fa5c3b2f9 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/support/resource/VariantUtil.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/support/resource/VariantUtil.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.fabric.support.resource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import net.fabricmc.fabric.api.transfer.v1.fluid.FluidVariant; import net.fabricmc.fabric.api.transfer.v1.item.ItemVariant; diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ClientModInitializer.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ClientModInitializer.java index 9c36c3628..90c5f8129 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ClientModInitializer.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ClientModInitializer.java @@ -1,8 +1,8 @@ package com.refinedmods.refinedstorage2.platform.forge; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.support.HelpTooltipComponent; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; import com.refinedmods.refinedstorage2.platform.api.upgrade.AbstractUpgradeItem; import com.refinedmods.refinedstorage2.platform.common.AbstractClientModInitializer; import com.refinedmods.refinedstorage2.platform.common.configurationcard.ConfigurationCardItemPropertyFunction; @@ -194,7 +194,6 @@ private static void registerReiGridSynchronizers() { } @SubscribeEvent - @SuppressWarnings("unchecked") public static void onRegisterTooltipFactories(final RegisterClientTooltipComponentFactoriesEvent e) { e.register( AbstractUpgradeItem.UpgradeDestinationTooltipComponent.class, @@ -208,19 +207,19 @@ public static void onRegisterTooltipFactories(final RegisterClientTooltipCompone RegulatorUpgradeItem.RegulatorTooltipComponent.class, component -> { final ClientTooltipComponent help = HelpClientTooltipComponent.create(component.helpText()); - return component.filteredResource() == null + return component.configuredResource() == null ? help - : createRegulatorUpgradeClientTooltipComponent(component.filteredResource(), help); + : createRegulatorUpgradeClientTooltipComponent(component.configuredResource(), help); } ); } - private static CompositeClientTooltipComponent createRegulatorUpgradeClientTooltipComponent( - final ResourceAmountTemplate filteredResource, + private static CompositeClientTooltipComponent createRegulatorUpgradeClientTooltipComponent( + final ResourceAmount configuredResource, final ClientTooltipComponent help ) { return new CompositeClientTooltipComponent(List.of( - new ResourceClientTooltipComponent<>(filteredResource), + new ResourceClientTooltipComponent(configuredResource), help )); } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java index 10348249b..3055b0a68 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java @@ -258,7 +258,7 @@ private class GridEntryImpl implements GridEntry { private final ModConfigSpec.BooleanValue smoothScrolling; private final ModConfigSpec.BooleanValue autoSelected; private final ModConfigSpec.ConfigValue synchronizer; - private final ModConfigSpec.ConfigValue storageChannelType; + private final ModConfigSpec.ConfigValue resourceType; private final ModConfigSpec.EnumValue sortingDirection; private final ModConfigSpec.EnumValue sortingType; private final ModConfigSpec.EnumValue size; @@ -292,9 +292,9 @@ private class GridEntryImpl implements GridEntry { synchronizer = builder .comment("The synchronization type of the Grid search box") .define("synchronizer", ""); - storageChannelType = builder - .comment("The storage channel type to be shown") - .define("storageChannelType", ""); + resourceType = builder + .comment("The resource type to be shown") + .define("resourceType", ""); sortingDirection = builder .comment("The sorting direction") .defineEnum("sortingDirection", GridSortingDirection.ASCENDING); @@ -401,21 +401,21 @@ public void setSize(final GridSize size) { } @Override - public Optional getStorageChannelType() { - if (storageChannelType == null || storageChannelType.get().trim().isBlank()) { + public Optional getResourceTypeId() { + if (resourceType == null || resourceType.get().trim().isBlank()) { return Optional.empty(); } - return Optional.of(storageChannelType.get()).map(ResourceLocation::new); + return Optional.of(resourceType.get()).map(ResourceLocation::new); } @Override - public void setStorageChannelType(final ResourceLocation storageChannelTypeId) { - this.storageChannelType.set(storageChannelTypeId.toString()); + public void setResourceTypeId(final ResourceLocation resourceTypeId) { + this.resourceType.set(resourceTypeId.toString()); } @Override - public void clearStorageChannelType() { - this.storageChannelType.set(""); + public void clearResourceType() { + this.resourceType.set(""); } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java index fa72d378f..a1edc8856 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java @@ -214,7 +214,7 @@ public boolean shouldCauseReequipAnimation(final ItemStack oldStack, return AbstractModInitializer.allowNbtUpdateAnimation(oldStack, newStack); } }, - () -> new WirelessGridItem(false) { + () -> new WirelessGridItem() { @Override public boolean shouldCauseReequipAnimation(final ItemStack oldStack, final ItemStack newStack, @@ -222,7 +222,7 @@ public boolean shouldCauseReequipAnimation(final ItemStack oldStack, return AbstractModInitializer.allowNbtUpdateAnimation(oldStack, newStack); } }, - () -> new WirelessGridItem(true) { + () -> new WirelessGridItem() { @Override public boolean shouldCauseReequipAnimation(final ItemStack oldStack, final ItemStack newStack, diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/PlatformImpl.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/PlatformImpl.java index 7384eed48..7c7f53d80 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/PlatformImpl.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/PlatformImpl.java @@ -3,12 +3,11 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.grid.view.GridResourceFactory; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; -import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.AbstractPlatform; import com.refinedmods.refinedstorage2.platform.common.Config; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.TransferManager; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.util.CustomBlockPlaceContext; import com.refinedmods.refinedstorage2.platform.forge.grid.strategy.ItemGridInsertionStrategy; import com.refinedmods.refinedstorage2.platform.forge.grid.view.ForgeFluidGridResourceFactory; @@ -152,9 +151,11 @@ public Optional getContainedFluid(final ItemStack stack) { if (!result.isSuccess() || tank.isEmpty()) { return Optional.empty(); } + final FluidResource fluidResource = ofFluidStack(tank.getFluid()); return Optional.of(new ContainedFluid( result.getResult(), - new ResourceAmount<>(ofFluidStack(tank.getFluid()), tank.getFluidAmount()) + fluidResource, + tank.getFluidAmount() )); } @@ -204,6 +205,7 @@ public ItemStack getCloneItemStack(final BlockState state, } @Override + @SuppressWarnings("DataFlowIssue") // NeoForge allows null public NonNullList getRemainingCraftingItems(final Player player, final CraftingRecipe craftingRecipe, final CraftingContainer container) { diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/BlockStateProvider.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/BlockStateProviderImpl.java similarity index 98% rename from refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/BlockStateProvider.java rename to refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/BlockStateProviderImpl.java index de698c113..cdf847283 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/BlockStateProvider.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/BlockStateProviderImpl.java @@ -26,6 +26,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.BooleanProperty; +import net.neoforged.neoforge.client.model.generators.BlockStateProvider; import net.neoforged.neoforge.client.model.generators.ConfiguredModel; import net.neoforged.neoforge.client.model.generators.ModelFile; import net.neoforged.neoforge.client.model.generators.MultiPartBlockStateBuilder; @@ -34,7 +35,7 @@ import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.MOD_ID; import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createIdentifier; -public class BlockStateProvider extends net.neoforged.neoforge.client.model.generators.BlockStateProvider { +public class BlockStateProviderImpl extends BlockStateProvider { private static final Map PROPERTY_BY_DIRECTION = new EnumMap<>(Map.of( Direction.NORTH, CableBlockSupport.NORTH, Direction.EAST, CableBlockSupport.EAST, @@ -46,7 +47,7 @@ public class BlockStateProvider extends net.neoforged.neoforge.client.model.gene private final ExistingFileHelper existingFileHelper; - public BlockStateProvider(final PackOutput output, final ExistingFileHelper existingFileHelper) { + public BlockStateProviderImpl(final PackOutput output, final ExistingFileHelper existingFileHelper) { super(output, MOD_ID, existingFileHelper); this.existingFileHelper = existingFileHelper; } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/DataGenerators.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/DataGenerators.java index 995129786..8d1cb10f1 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/DataGenerators.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/DataGenerators.java @@ -41,7 +41,7 @@ private static void registerBlockStateProviders(final DataGenerator generator, final ExistingFileHelper existingFileHelper) { final PackGenerator mainPack = generator.getVanillaPack(true); - mainPack.addProvider(output -> new BlockStateProvider(output, existingFileHelper)); + mainPack.addProvider(output -> new BlockStateProviderImpl(output, existingFileHelper)); } private static void registerBlockModelProviders(final DataGenerator generator, @@ -55,7 +55,7 @@ private static void registerItemModelProviders(final DataGenerator generator, final ExistingFileHelper existingFileHelper) { final PackGenerator mainPack = generator.getVanillaPack(true); - mainPack.addProvider(output -> new ItemModelProvider(output, existingFileHelper)); + mainPack.addProvider(output -> new ItemModelProviderImpl(output, existingFileHelper)); } private static void registerLootTableProviders(final DataGenerator generator) { diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/ItemModelProvider.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/ItemModelProviderImpl.java similarity index 97% rename from refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/ItemModelProvider.java rename to refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/ItemModelProviderImpl.java index 77c648389..56bfdf157 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/ItemModelProvider.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/ItemModelProviderImpl.java @@ -14,17 +14,18 @@ import net.minecraft.data.PackOutput; import net.minecraft.resources.ResourceLocation; +import net.neoforged.neoforge.client.model.generators.ItemModelProvider; import net.neoforged.neoforge.client.model.generators.ModelFile; import net.neoforged.neoforge.common.data.ExistingFileHelper; import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.MOD_ID; import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createIdentifier; -public class ItemModelProvider extends net.neoforged.neoforge.client.model.generators.ItemModelProvider { +public class ItemModelProviderImpl extends ItemModelProvider { private static final String CUTOUT_TEXTURE_KEY = "cutout"; private static final String CABLE_TEXTURE_KEY = "cable"; - public ItemModelProvider(final PackOutput output, final ExistingFileHelper existingFileHelper) { + public ItemModelProviderImpl(final PackOutput output, final ExistingFileHelper existingFileHelper) { super(output, MOD_ID, existingFileHelper); } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/exporter/FluidHandlerExporterTransferStrategyFactory.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/exporter/FluidHandlerExporterTransferStrategyFactory.java index 95e8e6649..f9f457d80 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/exporter/FluidHandlerExporterTransferStrategyFactory.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/exporter/FluidHandlerExporterTransferStrategyFactory.java @@ -1,21 +1,17 @@ package com.refinedmods.refinedstorage2.platform.forge.exporter; -import com.refinedmods.refinedstorage2.api.network.impl.node.exporter.AbstractExporterTransferStrategy; +import com.refinedmods.refinedstorage2.api.network.impl.node.exporter.ExporterTransferStrategyImpl; import com.refinedmods.refinedstorage2.api.network.node.exporter.ExporterTransferStrategy; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; import com.refinedmods.refinedstorage2.platform.api.exporter.ExporterTransferStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeState; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.content.Items; -import com.refinedmods.refinedstorage2.platform.common.exporter.AbstractFuzzyExporterTransferStrategy; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.exporter.FuzzyExporterTransferStrategy; import com.refinedmods.refinedstorage2.platform.forge.storage.CapabilityCache; import com.refinedmods.refinedstorage2.platform.forge.storage.CapabilityCacheImpl; import com.refinedmods.refinedstorage2.platform.forge.storage.FluidHandlerInsertableStorage; -import javax.annotation.Nullable; - import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; @@ -36,20 +32,8 @@ public ExporterTransferStrategy create(final ServerLevel level, final long transferQuota = (upgradeState.has(Items.INSTANCE.getStackUpgrade()) ? 64 : 1) * Platform.INSTANCE.getBucketAmount(); if (fuzzyMode) { - return new AbstractFuzzyExporterTransferStrategy<>(destination, StorageChannelTypes.FLUID, transferQuota) { - @Nullable - @Override - protected FluidResource tryConvert(final Object resource) { - return resource instanceof FluidResource fluidResource ? fluidResource : null; - } - }; + return new FuzzyExporterTransferStrategy(destination, transferQuota); } - return new AbstractExporterTransferStrategy<>(destination, StorageChannelTypes.FLUID, transferQuota) { - @Nullable - @Override - protected FluidResource tryConvert(final Object resource) { - return resource instanceof FluidResource fluidResource ? fluidResource : null; - } - }; + return new ExporterTransferStrategyImpl(destination, transferQuota); } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/exporter/ItemHandlerExporterTransferStrategyFactory.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/exporter/ItemHandlerExporterTransferStrategyFactory.java index cbf67a051..1c170b677 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/exporter/ItemHandlerExporterTransferStrategyFactory.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/exporter/ItemHandlerExporterTransferStrategyFactory.java @@ -1,19 +1,15 @@ package com.refinedmods.refinedstorage2.platform.forge.exporter; -import com.refinedmods.refinedstorage2.api.network.impl.node.exporter.AbstractExporterTransferStrategy; +import com.refinedmods.refinedstorage2.api.network.impl.node.exporter.ExporterTransferStrategyImpl; import com.refinedmods.refinedstorage2.api.network.node.exporter.ExporterTransferStrategy; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; import com.refinedmods.refinedstorage2.platform.api.exporter.ExporterTransferStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeState; import com.refinedmods.refinedstorage2.platform.common.content.Items; -import com.refinedmods.refinedstorage2.platform.common.exporter.AbstractFuzzyExporterTransferStrategy; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.exporter.FuzzyExporterTransferStrategy; import com.refinedmods.refinedstorage2.platform.forge.storage.CapabilityCacheImpl; import com.refinedmods.refinedstorage2.platform.forge.storage.ItemHandlerInsertableStorage; -import javax.annotation.Nullable; - import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; @@ -30,20 +26,8 @@ public ExporterTransferStrategy create(final ServerLevel level, final ItemHandlerInsertableStorage destination = new ItemHandlerInsertableStorage(coordinates, amountOverride); final int transferQuota = upgradeState.has(Items.INSTANCE.getStackUpgrade()) ? 64 : 1; if (fuzzyMode) { - return new AbstractFuzzyExporterTransferStrategy<>(destination, StorageChannelTypes.ITEM, transferQuota) { - @Nullable - @Override - protected ItemResource tryConvert(final Object resource) { - return resource instanceof ItemResource itemResource ? itemResource : null; - } - }; + return new FuzzyExporterTransferStrategy(destination, transferQuota); } - return new AbstractExporterTransferStrategy<>(destination, StorageChannelTypes.ITEM, transferQuota) { - @Nullable - @Override - protected ItemResource tryConvert(final Object resource) { - return resource instanceof ItemResource itemResource ? itemResource : null; - } - }; + return new ExporterTransferStrategyImpl(destination, transferQuota); } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/FluidGridExtractionStrategy.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/FluidGridExtractionStrategy.java index a35a2310a..0e716b99a 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/FluidGridExtractionStrategy.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/FluidGridExtractionStrategy.java @@ -9,10 +9,10 @@ import com.refinedmods.refinedstorage2.platform.api.grid.Grid; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridExtractionStrategy; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceTypes; import javax.annotation.Nullable; @@ -33,24 +33,23 @@ public class FluidGridExtractionStrategy implements GridExtractionStrategy { private static final ItemResource BUCKET_ITEM_RESOURCE = new ItemResource(Items.BUCKET, null); private final AbstractContainerMenu menu; - private final GridOperations gridOperations; + private final GridOperations gridOperations; private final PlayerMainInvWrapper playerInventoryStorage; - private final Storage itemStorage; + private final Storage itemStorage; public FluidGridExtractionStrategy(final AbstractContainerMenu containerMenu, final Player player, final Grid grid) { this.menu = containerMenu; - this.gridOperations = grid.createOperations(StorageChannelTypes.FLUID, new PlayerActor(player)); + this.gridOperations = grid.createOperations(ResourceTypes.FLUID, new PlayerActor(player)); this.playerInventoryStorage = new PlayerMainInvWrapper(player.getInventory()); this.itemStorage = grid.getItemStorage(); } @Override - public boolean onExtract(final PlatformStorageChannelType storageChannelType, - final T resource, - final GridExtractMode extractMode, - final boolean cursor) { + public boolean onExtract(final PlatformResourceKey resource, + final GridExtractMode extractMode, + final boolean cursor) { if (resource instanceof FluidResource fluidResource) { final boolean bucketInInventory = hasBucketInInventory(); final boolean bucketInStorageChannel = hasBucketInStorage(); @@ -78,7 +77,10 @@ private void extract(final FluidResource fluidResource, return; // shouldn't happen } gridOperations.extract(fluidResource, mode, (resource, amount, action, source) -> { - final int inserted = destination.fill(toFluidStack(resource, amount), toFluidAction(action)); + if (!(resource instanceof FluidResource fluidResource2)) { + return 0; + } + final int inserted = destination.fill(toFluidStack(fluidResource2, amount), toFluidAction(action)); if (action == Action.EXECUTE) { extractSourceBucket(bucketFromInventory, source); if (!insertResultingBucket(cursor, destination)) { diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/FluidGridInsertionStrategy.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/FluidGridInsertionStrategy.java index 8e9e32db0..65bd05106 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/FluidGridInsertionStrategy.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/FluidGridInsertionStrategy.java @@ -6,8 +6,8 @@ import com.refinedmods.refinedstorage2.platform.api.grid.Grid; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridInsertionStrategy; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceTypes; import javax.annotation.Nullable; @@ -24,11 +24,11 @@ public class FluidGridInsertionStrategy implements GridInsertionStrategy { private final AbstractContainerMenu menu; - private final GridOperations gridOperations; + private final GridOperations gridOperations; public FluidGridInsertionStrategy(final AbstractContainerMenu menu, final Player player, final Grid grid) { this.menu = menu; - this.gridOperations = grid.createOperations(StorageChannelTypes.FLUID, new PlayerActor(player)); + this.gridOperations = grid.createOperations(ResourceTypes.FLUID, new PlayerActor(player)); } @Override @@ -43,7 +43,13 @@ public boolean onInsert(final GridInsertMode insertMode, final boolean tryAltern } final FluidResource fluidResource = ofFluidStack(extractableResource); gridOperations.insert(fluidResource, insertMode, (resource, amount, action, source) -> { - final FluidStack toDrain = toFluidStack(resource, amount == Long.MAX_VALUE ? Integer.MAX_VALUE : amount); + if (!(resource instanceof FluidResource fluidResource2)) { + return 0; + } + final FluidStack toDrain = toFluidStack( + fluidResource2, + amount == Long.MAX_VALUE ? Integer.MAX_VALUE : amount + ); final FluidStack drained = cursorStorage.drain(toDrain, toFluidAction(action)); if (action == Action.EXECUTE) { menu.setCarried(cursorStorage.getContainer()); diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/ItemGridExtractionStrategy.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/ItemGridExtractionStrategy.java index ddc7ee399..fc691d78a 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/ItemGridExtractionStrategy.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/ItemGridExtractionStrategy.java @@ -6,9 +6,9 @@ import com.refinedmods.refinedstorage2.platform.api.grid.Grid; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridExtractionStrategy; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceTypes; import com.refinedmods.refinedstorage2.platform.forge.storage.CapabilityCache; import com.refinedmods.refinedstorage2.platform.forge.storage.ItemHandlerInsertableStorage; @@ -18,23 +18,22 @@ import net.neoforged.neoforge.items.wrapper.PlayerMainInvWrapper; public class ItemGridExtractionStrategy implements GridExtractionStrategy { - private final GridOperations gridOperations; + private final GridOperations gridOperations; private final PlayerMainInvWrapper playerInventoryStorage; private final CursorItemHandler playerCursorItemHandler; public ItemGridExtractionStrategy(final AbstractContainerMenu containerMenu, final Player player, final Grid grid) { - this.gridOperations = grid.createOperations(StorageChannelTypes.ITEM, new PlayerActor(player)); + this.gridOperations = grid.createOperations(ResourceTypes.ITEM, new PlayerActor(player)); this.playerInventoryStorage = new PlayerMainInvWrapper(player.getInventory()); this.playerCursorItemHandler = new CursorItemHandler(containerMenu); } @Override - public boolean onExtract(final PlatformStorageChannelType storageChannelType, - final T resource, - final GridExtractMode extractMode, - final boolean cursor) { + public boolean onExtract(final PlatformResourceKey resource, + final GridExtractMode extractMode, + final boolean cursor) { if (resource instanceof ItemResource itemResource) { final IItemHandler handler = cursor ? playerCursorItemHandler : playerInventoryStorage; gridOperations.extract( diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/ItemGridInsertionStrategy.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/ItemGridInsertionStrategy.java index 4869a801b..732d2adee 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/ItemGridInsertionStrategy.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/ItemGridInsertionStrategy.java @@ -6,8 +6,8 @@ import com.refinedmods.refinedstorage2.platform.api.grid.Grid; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridInsertionStrategy; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceTypes; import com.refinedmods.refinedstorage2.platform.forge.storage.CapabilityCache; import com.refinedmods.refinedstorage2.platform.forge.storage.ItemHandlerExtractableStorage; @@ -18,18 +18,18 @@ import net.neoforged.neoforge.items.wrapper.InvWrapper; import net.neoforged.neoforge.items.wrapper.RangedWrapper; -import static com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource.ofItemStack; +import static com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource.ofItemStack; public class ItemGridInsertionStrategy implements GridInsertionStrategy { private final AbstractContainerMenu containerMenu; - private final GridOperations gridOperations; + private final GridOperations gridOperations; private final CursorItemHandler playerCursorItemHandler; public ItemGridInsertionStrategy(final AbstractContainerMenu containerMenu, final Player player, final Grid grid) { this.containerMenu = containerMenu; - this.gridOperations = grid.createOperations(StorageChannelTypes.ITEM, new PlayerActor(player)); + this.gridOperations = grid.createOperations(ResourceTypes.ITEM, new PlayerActor(player)); this.playerCursorItemHandler = new CursorItemHandler(containerMenu); } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/ItemGridScrollingStrategy.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/ItemGridScrollingStrategy.java index 9f35497d5..2b5b88169 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/ItemGridScrollingStrategy.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/strategy/ItemGridScrollingStrategy.java @@ -8,9 +8,9 @@ import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollMode; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridScrollingStrategy; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceTypes; import com.refinedmods.refinedstorage2.platform.forge.storage.CapabilityCache; import com.refinedmods.refinedstorage2.platform.forge.storage.ItemHandlerExtractableStorage; import com.refinedmods.refinedstorage2.platform.forge.storage.ItemHandlerInsertableStorage; @@ -24,7 +24,7 @@ import net.neoforged.neoforge.items.wrapper.RangedWrapper; public class ItemGridScrollingStrategy implements GridScrollingStrategy { - private final GridOperations gridOperations; + private final GridOperations gridOperations; private final Inventory playerInventory; private final PlayerMainInvWrapper playerInventoryStorage; private final CursorItemHandler playerCursorItemHandler; @@ -32,17 +32,14 @@ public class ItemGridScrollingStrategy implements GridScrollingStrategy { public ItemGridScrollingStrategy(final AbstractContainerMenu containerMenu, final Player player, final Grid grid) { - this.gridOperations = grid.createOperations(StorageChannelTypes.ITEM, new PlayerActor(player)); + this.gridOperations = grid.createOperations(ResourceTypes.ITEM, new PlayerActor(player)); this.playerInventory = player.getInventory(); this.playerInventoryStorage = new PlayerMainInvWrapper(playerInventory); this.playerCursorItemHandler = new CursorItemHandler(containerMenu); } @Override - public boolean onScroll(final PlatformStorageChannelType storageChannelType, - final T resource, - final GridScrollMode scrollMode, - final int slotIndex) { + public boolean onScroll(final PlatformResourceKey resource, final GridScrollMode scrollMode, final int slotIndex) { if (resource instanceof ItemResource itemResource) { final IItemHandler playerStorage = slotIndex >= 0 ? new RangedWrapper(new InvWrapper(playerInventory), slotIndex, slotIndex + 1) diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/view/ForgeFluidGridResourceFactory.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/view/ForgeFluidGridResourceFactory.java index 82e5e732f..1ab14c5d6 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/view/ForgeFluidGridResourceFactory.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/grid/view/ForgeFluidGridResourceFactory.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.forge.grid.view; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.common.grid.view.AbstractFluidGridResourceFactory; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import net.neoforged.fml.ModList; import net.neoforged.neoforge.fluids.FluidType; diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/importer/FluidHandlerImporterSource.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/importer/FluidHandlerImporterSource.java index a6d0f31e1..100f74a83 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/importer/FluidHandlerImporterSource.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/importer/FluidHandlerImporterSource.java @@ -2,21 +2,21 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.network.node.importer.ImporterSource; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.ExtractableStorage; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.forge.storage.CapabilityCache; import com.refinedmods.refinedstorage2.platform.forge.storage.FluidHandlerExtractableStorage; import com.refinedmods.refinedstorage2.platform.forge.storage.FluidHandlerInsertableStorage; import java.util.Iterator; -class FluidHandlerImporterSource implements ImporterSource { +class FluidHandlerImporterSource implements ImporterSource { private final CapabilityCache capabilityCache; - private final InsertableStorage insertTarget; - private final ExtractableStorage extractTarget; + private final InsertableStorage insertTarget; + private final ExtractableStorage extractTarget; FluidHandlerImporterSource(final CapabilityCache capabilityCache, final AmountOverride amountOverride) { @@ -26,17 +26,17 @@ class FluidHandlerImporterSource implements ImporterSource { } @Override - public Iterator getResources() { + public Iterator getResources() { return capabilityCache.getFluidIterator(); } @Override - public long extract(final FluidResource resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return extractTarget.extract(resource, amount, action, actor); } @Override - public long insert(final FluidResource resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return insertTarget.insert(resource, amount, action, actor); } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/importer/FluidHandlerImporterTransferStrategyFactory.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/importer/FluidHandlerImporterTransferStrategyFactory.java index 9c40b2a51..7b3fafa52 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/importer/FluidHandlerImporterTransferStrategyFactory.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/importer/FluidHandlerImporterTransferStrategyFactory.java @@ -5,10 +5,8 @@ import com.refinedmods.refinedstorage2.api.network.node.importer.ImporterTransferStrategyImpl; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; import com.refinedmods.refinedstorage2.platform.api.importer.ImporterTransferStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeState; import com.refinedmods.refinedstorage2.platform.common.content.Items; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import com.refinedmods.refinedstorage2.platform.forge.storage.CapabilityCacheImpl; import net.minecraft.core.BlockPos; @@ -23,7 +21,7 @@ public ImporterTransferStrategy create(final ServerLevel level, final Direction direction, final UpgradeState upgradeState, final AmountOverride amountOverride) { - final ImporterSource source = new FluidHandlerImporterSource(new CapabilityCacheImpl( + final ImporterSource source = new FluidHandlerImporterSource(new CapabilityCacheImpl( level, pos, direction @@ -31,6 +29,6 @@ public ImporterTransferStrategy create(final ServerLevel level, final int transferQuota = upgradeState.has(Items.INSTANCE.getStackUpgrade()) ? FluidType.BUCKET_VOLUME * 64 : FluidType.BUCKET_VOLUME; - return new ImporterTransferStrategyImpl<>(source, StorageChannelTypes.FLUID, transferQuota); + return new ImporterTransferStrategyImpl(source, transferQuota); } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/importer/ItemHandlerImporterSource.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/importer/ItemHandlerImporterSource.java index fc311e115..663b79b63 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/importer/ItemHandlerImporterSource.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/importer/ItemHandlerImporterSource.java @@ -2,21 +2,21 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.network.node.importer.ImporterSource; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.ExtractableStorage; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.forge.storage.CapabilityCache; import com.refinedmods.refinedstorage2.platform.forge.storage.ItemHandlerExtractableStorage; import com.refinedmods.refinedstorage2.platform.forge.storage.ItemHandlerInsertableStorage; import java.util.Iterator; -class ItemHandlerImporterSource implements ImporterSource { +class ItemHandlerImporterSource implements ImporterSource { private final CapabilityCache capabilityCache; - private final InsertableStorage insertTarget; - private final ExtractableStorage extractTarget; + private final InsertableStorage insertTarget; + private final ExtractableStorage extractTarget; ItemHandlerImporterSource(final CapabilityCache capabilityCache, final AmountOverride amountOverride) { @@ -26,17 +26,17 @@ class ItemHandlerImporterSource implements ImporterSource { } @Override - public Iterator getResources() { + public Iterator getResources() { return capabilityCache.getItemIterator(); } @Override - public long extract(final ItemResource resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return extractTarget.extract(resource, amount, action, actor); } @Override - public long insert(final ItemResource resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return insertTarget.insert(resource, amount, action, actor); } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/importer/ItemHandlerImporterTransferStrategyFactory.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/importer/ItemHandlerImporterTransferStrategyFactory.java index a1f0a946a..64570d9fc 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/importer/ItemHandlerImporterTransferStrategyFactory.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/importer/ItemHandlerImporterTransferStrategyFactory.java @@ -5,10 +5,8 @@ import com.refinedmods.refinedstorage2.api.network.node.importer.ImporterTransferStrategyImpl; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; import com.refinedmods.refinedstorage2.platform.api.importer.ImporterTransferStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeState; import com.refinedmods.refinedstorage2.platform.common.content.Items; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import com.refinedmods.refinedstorage2.platform.forge.storage.CapabilityCacheImpl; import net.minecraft.core.BlockPos; @@ -22,12 +20,12 @@ public ImporterTransferStrategy create(final ServerLevel level, final Direction direction, final UpgradeState upgradeState, final AmountOverride amountOverride) { - final ImporterSource source = new ItemHandlerImporterSource(new CapabilityCacheImpl( + final ImporterSource source = new ItemHandlerImporterSource(new CapabilityCacheImpl( level, pos, direction ), amountOverride); final int transferQuota = upgradeState.has(Items.INSTANCE.getStackUpgrade()) ? 64 : 1; - return new ImporterTransferStrategyImpl<>(source, StorageChannelTypes.ITEM, transferQuota); + return new ImporterTransferStrategyImpl(source, transferQuota); } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/CraftingGridTransferHandler.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/CraftingGridTransferHandler.java index 57ceed741..5c54da32e 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/CraftingGridTransferHandler.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/CraftingGridTransferHandler.java @@ -1,8 +1,8 @@ package com.refinedmods.refinedstorage2.platform.forge.recipemod.rei; import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.grid.CraftingGridContainerMenu; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.awt.Color; import java.util.List; @@ -38,7 +38,7 @@ public Result handle(final Context context) { doTransfer(ingredients, containerMenu); return Result.createSuccessful().blocksFurtherHandling(); } - final ResourceList available = containerMenu.getAvailableListForRecipeTransfer(); + final ResourceList available = containerMenu.getAvailableListForRecipeTransfer(); final MissingIngredients missingIngredients = findMissingIngredients(ingredients, available); if (missingIngredients.isEmpty()) { return Result.createSuccessful().blocksFurtherHandling(); @@ -56,7 +56,7 @@ private void doTransfer(final List ingredients, final CraftingG } private MissingIngredients findMissingIngredients(final List ingredients, - final ResourceList available) { + final ResourceList available) { final MissingIngredients missingIngredients = new MissingIngredients(); for (int i = 0; i < ingredients.size(); ++i) { final EntryIngredient ingredient = ingredients.get(i); @@ -70,7 +70,7 @@ private MissingIngredients findMissingIngredients(final List in return missingIngredients; } - private boolean isAvailable(final ResourceList available, final EntryIngredient ingredient) { + private boolean isAvailable(final ResourceList available, final EntryIngredient ingredient) { final List possibilities = convertIngredientToItemStacks(ingredient); for (final ItemStack possibility : possibilities) { final ItemResource possibilityResource = ItemResource.ofItemStack(possibility); diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/DraggableStackVisitorImpl.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/DraggableStackVisitorImpl.java index 58f4215b4..bd3ed0f80 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/DraggableStackVisitorImpl.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/DraggableStackVisitorImpl.java @@ -1,8 +1,7 @@ package com.refinedmods.refinedstorage2.platform.forge.recipemod.rei; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.support.AbstractBaseScreen; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.AbstractResourceContainerMenu; @@ -38,7 +37,7 @@ public Stream getDraggableAcceptingBounds( final List bounds = new ArrayList<>(); ingredientConverter.convertToResource(value).ifPresent(resource -> { for (final ResourceSlot slot : menu.getResourceSlots()) { - if (slot.isFilter() && slot.isValid(resource.resource())) { + if (slot.isFilter() && slot.isValid(resource)) { bounds.add(BoundsProvider.ofRectangle(toRectangle(screen, slot))); } } @@ -55,26 +54,22 @@ public DraggedAcceptorResult acceptDraggedStack( final var menu = screen.getMenu(); final Object value = stack.getStack().getValue(); return ingredientConverter.convertToResource(value) - .map(resourceTemplate -> accept(context, menu, screen, resourceTemplate)) + .map(resource -> accept(context, menu, screen, resource)) .orElse(DraggedAcceptorResult.PASS); } - private DraggedAcceptorResult accept( + private DraggedAcceptorResult accept( final DraggingContext> context, final AbstractResourceContainerMenu menu, final AbstractBaseScreen screen, - final ResourceTemplate resource + final PlatformResourceKey resource ) { for (final ResourceSlot slot : menu.getResourceSlots()) { final Rectangle slotBounds = toRectangle(screen, slot); if (!slotBounds.contains(context.getCurrentPosition())) { continue; } - Platform.INSTANCE.getClientToServerCommunications().sendResourceFilterSlotChange( - (PlatformStorageChannelType) resource.storageChannelType(), - resource.resource(), - slot.index - ); + Platform.INSTANCE.getClientToServerCommunications().sendResourceFilterSlotChange(resource, slot.index); return DraggedAcceptorResult.ACCEPTED; } return DraggedAcceptorResult.PASS; diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/GridFocusedStackProvider.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/GridFocusedStackProvider.java index 0ed91efad..baa9f3989 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/GridFocusedStackProvider.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/GridFocusedStackProvider.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.forge.recipemod.rei; -import com.refinedmods.refinedstorage2.api.grid.view.GridResource; import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.grid.screen.AbstractGridScreen; import dev.architectury.event.CompoundEventResult; @@ -22,11 +22,11 @@ public CompoundEventResult> provide(final Screen screen, final Poi if (!(screen instanceof AbstractGridScreen gridScreen)) { return CompoundEventResult.pass(); } - final GridResource resource = gridScreen.getCurrentGridResource(); - if (resource == null) { + final PlatformResourceKey underlyingResource = gridScreen.getCurrentResource(); + if (underlyingResource == null) { return CompoundEventResult.pass(); } - final Object converted = converter.convertToIngredient(resource).orElse(null); + final Object converted = converter.convertToIngredient(underlyingResource).orElse(null); if (converted instanceof EntryStack stack) { return CompoundEventResult.interruptTrue(stack); } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/GridResourceIngredientConverter.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/GridResourceIngredientConverter.java deleted file mode 100644 index e83e1b518..000000000 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/GridResourceIngredientConverter.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.forge.recipemod.rei; - -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; -import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; -import com.refinedmods.refinedstorage2.platform.common.grid.view.FluidGridResource; -import com.refinedmods.refinedstorage2.platform.common.grid.view.ItemGridResource; - -import java.util.Optional; - -import dev.architectury.fluid.FluidStack; -import me.shedaniel.rei.api.common.util.EntryStacks; - -class GridResourceIngredientConverter implements IngredientConverter { - @Override - public Optional> convertToResource(final Object ingredient) { - return Optional.empty(); - } - - @Override - public Optional convertToIngredient(final Object resource) { - if (resource instanceof ItemGridResource itemGridResource) { - return Optional.of(EntryStacks.of(itemGridResource.copyItemStack())); - } - if (resource instanceof FluidGridResource fluidGridResource) { - final FluidStack fluidStack = FluidStack.create( - fluidGridResource.getResource().fluid(), - FluidStack.bucketAmount(), - fluidGridResource.getResource().tag() - ); - return Optional.of(EntryStacks.of(fluidStack)); - } - return Optional.empty(); - } -} diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/IngredientConverterImpl.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/IngredientConverterImpl.java new file mode 100644 index 000000000..1adb1d641 --- /dev/null +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/IngredientConverterImpl.java @@ -0,0 +1,41 @@ +package com.refinedmods.refinedstorage2.platform.forge.recipemod.rei; + +import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; + +import java.util.Optional; + +import dev.architectury.fluid.FluidStack; +import me.shedaniel.rei.api.common.util.EntryStacks; +import net.minecraft.world.item.ItemStack; + +class IngredientConverterImpl implements IngredientConverter { + @Override + public Optional convertToResource(final Object ingredient) { + if (ingredient instanceof FluidStack fluidStack) { + return Optional.of(new FluidResource(fluidStack.getFluid(), fluidStack.getTag())); + } + if (ingredient instanceof ItemStack itemStack) { + return Optional.of(ItemResource.ofItemStack(itemStack)); + } + return Optional.empty(); + } + + @Override + public Optional convertToIngredient(final PlatformResourceKey resource) { + if (resource instanceof ItemResource itemResource) { + return Optional.of(EntryStacks.of(itemResource.toItemStack())); + } + if (resource instanceof FluidResource fluidResource) { + final FluidStack fluidStack = FluidStack.create( + fluidResource.fluid(), + FluidStack.bucketAmount(), + fluidResource.tag() + ); + return Optional.of(EntryStacks.of(fluidStack)); + } + return Optional.empty(); + } +} diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/RefinedStorageREIClientPlugin.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/RefinedStorageREIClientPlugin.java index a9f815312..1e73e5325 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/RefinedStorageREIClientPlugin.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/RefinedStorageREIClientPlugin.java @@ -11,7 +11,6 @@ import com.refinedmods.refinedstorage2.platform.common.support.AbstractBaseScreen; import java.util.function.Supplier; -import java.util.stream.Collectors; import me.shedaniel.rei.api.client.plugins.REIClientPlugin; import me.shedaniel.rei.api.client.registry.entry.CollapsibleEntryRegistry; @@ -40,8 +39,7 @@ public void registerScreens(final ScreenRegistry registry) { } public static void registerIngredientConverters() { - PlatformApi.INSTANCE.registerIngredientConverter(new GridResourceIngredientConverter()); - PlatformApi.INSTANCE.registerIngredientConverter(new ResourceIngredientConverter()); + PlatformApi.INSTANCE.registerIngredientConverter(new IngredientConverterImpl()); } @Override @@ -74,7 +72,7 @@ public void registerCollapsibleEntries(final CollapsibleEntryRegistry registry) .map(Supplier::get) .map(ControllerBlockItem::createAtEnergyCapacity) .map(EntryStacks::of) - .collect(Collectors.toList()) + .toList() ); groupItems( registry, diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/ResourceFocusedStackProvider.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/ResourceFocusedStackProvider.java index cb2e21ade..6ee58c9e3 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/ResourceFocusedStackProvider.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/ResourceFocusedStackProvider.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.forge.recipemod.rei; -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.support.AbstractBaseScreen; import dev.architectury.event.CompoundEventResult; @@ -22,7 +22,7 @@ public CompoundEventResult> provide(final Screen screen, final Poi if (!(screen instanceof AbstractBaseScreen baseScreen)) { return CompoundEventResult.pass(); } - final ResourceTemplate hoveredResource = baseScreen.getHoveredResource(); + final PlatformResourceKey hoveredResource = baseScreen.getHoveredResource(); if (hoveredResource == null) { return CompoundEventResult.pass(); } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/ResourceIngredientConverter.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/ResourceIngredientConverter.java deleted file mode 100644 index ce2273584..000000000 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/recipemod/rei/ResourceIngredientConverter.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.forge.recipemod.rei; - -import com.refinedmods.refinedstorage2.api.storage.ResourceTemplate; -import com.refinedmods.refinedstorage2.platform.api.recipemod.IngredientConverter; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; - -import java.util.Optional; - -import dev.architectury.fluid.FluidStack; -import me.shedaniel.rei.api.common.util.EntryStacks; -import net.minecraft.world.item.ItemStack; - -class ResourceIngredientConverter implements IngredientConverter { - @Override - public Optional> convertToResource(final Object ingredient) { - if (ingredient instanceof FluidStack fluidStack) { - return Optional.of(new ResourceTemplate<>( - new FluidResource(fluidStack.getFluid(), fluidStack.getTag()), - StorageChannelTypes.FLUID - )); - } - if (ingredient instanceof ItemStack itemStack) { - return Optional.of(new ResourceTemplate<>( - ItemResource.ofItemStack(itemStack), - StorageChannelTypes.ITEM - )); - } - return Optional.empty(); - } - - @Override - public Optional convertToIngredient(final Object resource) { - if (!(resource instanceof ResourceTemplate resourceTemplate)) { - return Optional.empty(); - } - if (resourceTemplate.resource() instanceof ItemResource itemResource) { - return Optional.of(EntryStacks.of(itemResource.toItemStack())); - } - if (resourceTemplate.resource() instanceof FluidResource fluidResource) { - final FluidStack fluidStack = FluidStack.create( - fluidResource.fluid(), - FluidStack.bucketAmount(), - fluidResource.tag() - ); - return Optional.of(EntryStacks.of(fluidStack)); - } - return Optional.empty(); - } -} diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/CapabilityCache.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/CapabilityCache.java index 4cbdd7e04..28f7ed94c 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/CapabilityCache.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/CapabilityCache.java @@ -1,8 +1,7 @@ package com.refinedmods.refinedstorage2.platform.forge.storage; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import java.util.Collections; import java.util.Iterator; @@ -15,7 +14,7 @@ import net.neoforged.neoforge.fluids.capability.IFluidHandler; import net.neoforged.neoforge.items.IItemHandler; -import static com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource.ofItemStack; +import static com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource.ofItemStack; import static com.refinedmods.refinedstorage2.platform.forge.support.resource.VariantUtil.ofFluidStack; public interface CapabilityCache { @@ -23,13 +22,13 @@ default Optional getItemHandler() { return Optional.empty(); } - default Iterator getItemIterator() { - return getItemHandler().map(handler -> (Iterator) new AbstractIterator() { + default Iterator getItemIterator() { + return getItemHandler().map(handler -> (Iterator) new AbstractIterator() { private int index; @Nullable @Override - protected ItemResource computeNext() { + protected ResourceKey computeNext() { if (index > handler.getSlots()) { return endOfData(); } @@ -45,14 +44,14 @@ protected ItemResource computeNext() { }).orElse(Collections.emptyListIterator()); } - default Iterator> getItemAmountIterator() { + default Iterator getItemAmountIterator() { return getItemHandler().map( - handler -> (Iterator>) new AbstractIterator>() { + handler -> (Iterator) new AbstractIterator() { private int index; @Nullable @Override - protected ResourceAmount computeNext() { + protected ResourceAmount computeNext() { if (index > handler.getSlots()) { return endOfData(); } @@ -60,7 +59,7 @@ protected ResourceAmount computeNext() { final ItemStack slot = handler.getStackInSlot(index); if (!slot.isEmpty()) { index++; - return new ResourceAmount<>(ofItemStack(slot), slot.getCount()); + return new ResourceAmount(ofItemStack(slot), slot.getCount()); } } return endOfData(); @@ -73,13 +72,13 @@ default Optional getFluidHandler() { return Optional.empty(); } - default Iterator getFluidIterator() { - return getFluidHandler().map(handler -> (Iterator) new AbstractIterator() { + default Iterator getFluidIterator() { + return getFluidHandler().map(handler -> (Iterator) new AbstractIterator() { private int index; @Nullable @Override - protected FluidResource computeNext() { + protected ResourceKey computeNext() { if (index > handler.getTanks()) { return endOfData(); } @@ -95,14 +94,14 @@ protected FluidResource computeNext() { }).orElse(Collections.emptyListIterator()); } - default Iterator> getFluidAmountIterator() { + default Iterator getFluidAmountIterator() { return getFluidHandler().map( - handler -> (Iterator>) new AbstractIterator>() { + handler -> (Iterator) new AbstractIterator() { private int index; @Nullable @Override - protected ResourceAmount computeNext() { + protected ResourceAmount computeNext() { if (index > handler.getTanks()) { return endOfData(); } @@ -110,7 +109,7 @@ protected ResourceAmount computeNext() { final FluidStack slot = handler.getFluidInTank(index); if (!slot.isEmpty()) { index++; - return new ResourceAmount<>(ofFluidStack(slot), slot.getAmount()); + return new ResourceAmount(ofFluidStack(slot), slot.getAmount()); } } return endOfData(); diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/FluidHandlerExtractableStorage.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/FluidHandlerExtractableStorage.java index 76cb7c3ee..cfe13b84d 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/FluidHandlerExtractableStorage.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/FluidHandlerExtractableStorage.java @@ -1,17 +1,18 @@ package com.refinedmods.refinedstorage2.platform.forge.storage; import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.ExtractableStorage; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import net.neoforged.neoforge.fluids.FluidStack; import static com.refinedmods.refinedstorage2.platform.forge.support.resource.VariantUtil.toFluidAction; import static com.refinedmods.refinedstorage2.platform.forge.support.resource.VariantUtil.toFluidStack; -public class FluidHandlerExtractableStorage implements ExtractableStorage { +public class FluidHandlerExtractableStorage implements ExtractableStorage { private final CapabilityCache capabilityCache; private final AmountOverride amountOverride; @@ -22,17 +23,20 @@ public FluidHandlerExtractableStorage(final CapabilityCache capabilityCache, } @Override - public long extract(final FluidResource resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { + if (!(resource instanceof FluidResource fluidResource)) { + return 0; + } return capabilityCache.getFluidHandler().map(fluidHandler -> { final long correctedAmount = amountOverride.overrideAmount( resource, amount, - () -> ForgeHandlerUtil.getCurrentAmount(fluidHandler, resource) + () -> ForgeHandlerUtil.getCurrentAmount(fluidHandler, fluidResource) ); if (correctedAmount == 0) { return 0L; } - final FluidStack toExtractStack = toFluidStack(resource, correctedAmount); + final FluidStack toExtractStack = toFluidStack(fluidResource, correctedAmount); return (long) fluidHandler.drain(toExtractStack, toFluidAction(action)).getAmount(); }).orElse(0L); } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/FluidHandlerInsertableStorage.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/FluidHandlerInsertableStorage.java index 016d59d48..35ad156c2 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/FluidHandlerInsertableStorage.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/FluidHandlerInsertableStorage.java @@ -1,10 +1,11 @@ package com.refinedmods.refinedstorage2.platform.forge.storage; import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import net.neoforged.neoforge.fluids.FluidStack; import net.neoforged.neoforge.fluids.capability.IFluidHandler; @@ -12,7 +13,7 @@ import static com.refinedmods.refinedstorage2.platform.forge.support.resource.VariantUtil.toFluidAction; import static com.refinedmods.refinedstorage2.platform.forge.support.resource.VariantUtil.toFluidStack; -public class FluidHandlerInsertableStorage implements InsertableStorage { +public class FluidHandlerInsertableStorage implements InsertableStorage { private final CapabilityCache capabilityCache; private final AmountOverride amountOverride; @@ -23,21 +24,21 @@ public FluidHandlerInsertableStorage(final CapabilityCache capabilityCache, } @Override - public long insert(final FluidResource resource, final long amount, final Action action, final Actor actor) { - return capabilityCache - .getFluidHandler() - .map(fluidHandler -> { - final long correctedAmount = amountOverride.overrideAmount( - resource, - amount, - () -> ForgeHandlerUtil.getCurrentAmount(fluidHandler, resource) - ); - if (correctedAmount == 0) { - return 0L; - } - return doInsert(resource, correctedAmount, action, fluidHandler); - }) - .orElse(0L); + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { + if (!(resource instanceof FluidResource fluidResource)) { + return 0; + } + return capabilityCache.getFluidHandler().map(fluidHandler -> { + final long correctedAmount = amountOverride.overrideAmount( + fluidResource, + amount, + () -> ForgeHandlerUtil.getCurrentAmount(fluidHandler, fluidResource) + ); + if (correctedAmount == 0) { + return 0L; + } + return doInsert(fluidResource, correctedAmount, action, fluidHandler); + }).orElse(0L); } private long doInsert(final FluidResource resource, diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/ForgeHandlerUtil.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/ForgeHandlerUtil.java index 93e7bc03c..3b0b27fb3 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/ForgeHandlerUtil.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/ForgeHandlerUtil.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.forge.storage; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import net.minecraft.world.item.ItemStack; import net.neoforged.neoforge.fluids.FluidStack; diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/ItemHandlerExtractableStorage.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/ItemHandlerExtractableStorage.java index a27d8b68d..41756c205 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/ItemHandlerExtractableStorage.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/ItemHandlerExtractableStorage.java @@ -1,15 +1,16 @@ package com.refinedmods.refinedstorage2.platform.forge.storage; import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.ExtractableStorage; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import net.minecraft.world.item.ItemStack; import net.neoforged.neoforge.items.IItemHandler; -public class ItemHandlerExtractableStorage implements ExtractableStorage { +public class ItemHandlerExtractableStorage implements ExtractableStorage { private final CapabilityCache capabilityCache; private final AmountOverride amountOverride; @@ -20,9 +21,12 @@ public ItemHandlerExtractableStorage(final CapabilityCache capabilityCache, } @Override - public long extract(final ItemResource resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { + if (!(resource instanceof ItemResource itemResource)) { + return 0L; + } return capabilityCache.getItemHandler().map(itemHandler -> { - final ItemStack toExtractStack = resource.toItemStack(amount); + final ItemStack toExtractStack = itemResource.toItemStack(amount); final long correctedAmount = amountOverride.overrideAmount( resource, amount, diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/ItemHandlerInsertableStorage.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/ItemHandlerInsertableStorage.java index 3ddfeb57f..fe34d4d41 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/ItemHandlerInsertableStorage.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/ItemHandlerInsertableStorage.java @@ -1,16 +1,17 @@ package com.refinedmods.refinedstorage2.platform.forge.storage; import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import net.minecraft.world.item.ItemStack; import net.neoforged.neoforge.items.IItemHandler; import net.neoforged.neoforge.items.ItemHandlerHelper; -public class ItemHandlerInsertableStorage implements InsertableStorage { +public class ItemHandlerInsertableStorage implements InsertableStorage { private final CapabilityCache capabilityCache; private final AmountOverride amountOverride; @@ -21,19 +22,22 @@ public ItemHandlerInsertableStorage(final CapabilityCache capabilityCache, } @Override - public long insert(final ItemResource resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { + if (!(resource instanceof ItemResource itemResource)) { + return 0L; + } return capabilityCache .getItemHandler() .map(itemHandler -> { final long correctedAmount = amountOverride.overrideAmount( resource, amount, - () -> ForgeHandlerUtil.getCurrentAmount(itemHandler, resource.toItemStack()) + () -> ForgeHandlerUtil.getCurrentAmount(itemHandler, itemResource.toItemStack()) ); if (correctedAmount == 0) { return 0L; } - return doInsert(resource, correctedAmount, action, itemHandler); + return doInsert(itemResource, correctedAmount, action, itemHandler); }) .orElse(0L); } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/externalstorage/FluidHandlerExternalStorageProvider.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/externalstorage/FluidHandlerExternalStorageProvider.java index 5ab10b892..c91f7cc4e 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/externalstorage/FluidHandlerExternalStorageProvider.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/externalstorage/FluidHandlerExternalStorageProvider.java @@ -2,22 +2,22 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.ExtractableStorage; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; import com.refinedmods.refinedstorage2.api.storage.external.ExternalStorageProvider; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.forge.storage.CapabilityCache; import com.refinedmods.refinedstorage2.platform.forge.storage.FluidHandlerExtractableStorage; import com.refinedmods.refinedstorage2.platform.forge.storage.FluidHandlerInsertableStorage; import java.util.Iterator; -class FluidHandlerExternalStorageProvider implements ExternalStorageProvider { +class FluidHandlerExternalStorageProvider implements ExternalStorageProvider { private final CapabilityCache capabilityCache; - private final InsertableStorage insertTarget; - private final ExtractableStorage extractTarget; + private final InsertableStorage insertTarget; + private final ExtractableStorage extractTarget; FluidHandlerExternalStorageProvider(final CapabilityCache capabilityCache) { this.capabilityCache = capabilityCache; @@ -26,17 +26,17 @@ class FluidHandlerExternalStorageProvider implements ExternalStorageProvider> iterator() { + public Iterator iterator() { return capabilityCache.getFluidAmountIterator(); } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/externalstorage/FluidHandlerPlatformExternalStorageProviderFactory.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/externalstorage/FluidHandlerPlatformExternalStorageProviderFactory.java index e8f31713c..b5ad12fed 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/externalstorage/FluidHandlerPlatformExternalStorageProviderFactory.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/externalstorage/FluidHandlerPlatformExternalStorageProviderFactory.java @@ -1,9 +1,7 @@ package com.refinedmods.refinedstorage2.platform.forge.storage.externalstorage; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.api.storage.external.ExternalStorageProvider; import com.refinedmods.refinedstorage2.platform.api.storage.externalstorage.PlatformExternalStorageProviderFactory; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import com.refinedmods.refinedstorage2.platform.forge.storage.CapabilityCacheImpl; import java.util.Optional; @@ -14,16 +12,9 @@ public class FluidHandlerPlatformExternalStorageProviderFactory implements PlatformExternalStorageProviderFactory { @Override - @SuppressWarnings("unchecked") - public Optional> create(final ServerLevel level, - final BlockPos pos, - final Direction direction, - final StorageChannelType storageChannelType) { - if (storageChannelType != StorageChannelTypes.FLUID) { - return Optional.empty(); - } - return Optional.of((ExternalStorageProvider) new FluidHandlerExternalStorageProvider( - new CapabilityCacheImpl(level, pos, direction) - )); + public Optional create(final ServerLevel level, + final BlockPos pos, + final Direction direction) { + return Optional.of(new FluidHandlerExternalStorageProvider(new CapabilityCacheImpl(level, pos, direction))); } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/externalstorage/ItemHandlerExternalStorageProvider.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/externalstorage/ItemHandlerExternalStorageProvider.java index 8085c54a9..42913da59 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/externalstorage/ItemHandlerExternalStorageProvider.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/externalstorage/ItemHandlerExternalStorageProvider.java @@ -2,22 +2,22 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.ExtractableStorage; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; import com.refinedmods.refinedstorage2.api.storage.external.ExternalStorageProvider; import com.refinedmods.refinedstorage2.platform.api.exporter.AmountOverride; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.forge.storage.CapabilityCache; import com.refinedmods.refinedstorage2.platform.forge.storage.ItemHandlerExtractableStorage; import com.refinedmods.refinedstorage2.platform.forge.storage.ItemHandlerInsertableStorage; import java.util.Iterator; -class ItemHandlerExternalStorageProvider implements ExternalStorageProvider { +class ItemHandlerExternalStorageProvider implements ExternalStorageProvider { private final CapabilityCache capabilityCache; - private final InsertableStorage insertTarget; - private final ExtractableStorage extractTarget; + private final InsertableStorage insertTarget; + private final ExtractableStorage extractTarget; ItemHandlerExternalStorageProvider(final CapabilityCache capabilityCache) { this.capabilityCache = capabilityCache; @@ -26,17 +26,17 @@ class ItemHandlerExternalStorageProvider implements ExternalStorageProvider> iterator() { + public Iterator iterator() { return capabilityCache.getItemAmountIterator(); } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/externalstorage/ItemHandlerPlatformExternalStorageProviderFactory.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/externalstorage/ItemHandlerPlatformExternalStorageProviderFactory.java index 0a19e2c7f..cf1fa0c57 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/externalstorage/ItemHandlerPlatformExternalStorageProviderFactory.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/storage/externalstorage/ItemHandlerPlatformExternalStorageProviderFactory.java @@ -1,9 +1,7 @@ package com.refinedmods.refinedstorage2.platform.forge.storage.externalstorage; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.api.storage.external.ExternalStorageProvider; import com.refinedmods.refinedstorage2.platform.api.storage.externalstorage.PlatformExternalStorageProviderFactory; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; import com.refinedmods.refinedstorage2.platform.forge.storage.CapabilityCacheImpl; import java.util.Optional; @@ -14,16 +12,9 @@ public class ItemHandlerPlatformExternalStorageProviderFactory implements PlatformExternalStorageProviderFactory { @Override - @SuppressWarnings("unchecked") - public Optional> create(final ServerLevel level, - final BlockPos pos, - final Direction direction, - final StorageChannelType storageChannelType) { - if (storageChannelType != StorageChannelTypes.ITEM) { - return Optional.empty(); - } - return Optional.of((ExternalStorageProvider) new ItemHandlerExternalStorageProvider( - new CapabilityCacheImpl(level, pos, direction) - )); + public Optional create(final ServerLevel level, + final BlockPos pos, + final Direction direction) { + return Optional.of(new ItemHandlerExternalStorageProvider(new CapabilityCacheImpl(level, pos, direction))); } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/ClientToServerCommunicationsImpl.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/ClientToServerCommunicationsImpl.java index e321fab45..7554e91d4 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/ClientToServerCommunicationsImpl.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/ClientToServerCommunicationsImpl.java @@ -4,11 +4,12 @@ import com.refinedmods.refinedstorage2.api.grid.operations.GridInsertMode; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollMode; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; import com.refinedmods.refinedstorage2.platform.api.support.network.bounditem.SlotReference; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.support.ClientToServerCommunications; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.PropertyType; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import java.util.List; import java.util.UUID; @@ -22,13 +23,13 @@ private void sendPacket(final CustomPacketPayload packet) { } @Override - public void sendGridExtract(final PlatformStorageChannelType storageChannelType, - final T resource, - final GridExtractMode mode, - final boolean cursor) { - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().getId(storageChannelType) - .ifPresent(id -> sendPacket(new GridExtractPacket<>( - storageChannelType, + public void sendGridExtract(final PlatformResourceKey resource, + final GridExtractMode mode, + final boolean cursor) { + final ResourceType resourceType = resource.getResourceType(); + PlatformApi.INSTANCE.getResourceTypeRegistry().getId(resourceType) + .ifPresent(id -> sendPacket(new GridExtractPacket( + resourceType, id, resource, mode, @@ -37,14 +38,14 @@ public void sendGridExtract(final PlatformStorageChannelType storageChann } @Override - public void sendGridScroll(final PlatformStorageChannelType storageChannelType, - final T resource, - final GridScrollMode mode, - final int slotIndex) { - PlatformApi.INSTANCE.getStorageChannelTypeRegistry() - .getId(storageChannelType) - .ifPresent(id -> sendPacket(new GridScrollPacket<>( - storageChannelType, + public void sendGridScroll(final PlatformResourceKey resource, + final GridScrollMode mode, + final int slotIndex) { + final ResourceType resourceType = resource.getResourceType(); + PlatformApi.INSTANCE.getResourceTypeRegistry() + .getId(resourceType) + .ifPresent(id -> sendPacket(new GridScrollPacket( + resourceType, id, resource, mode, @@ -83,14 +84,13 @@ public void sendResourceSlotChange(final int slotIndex, final boolean tryAlterna } @Override - public void sendResourceFilterSlotChange(final PlatformStorageChannelType storageChannelType, - final T resource, - final int slotIndex) { - PlatformApi.INSTANCE.getStorageChannelTypeRegistry().getId(storageChannelType).ifPresent( - id -> sendPacket(new ResourceFilterSlotChangePacket<>( + public void sendResourceFilterSlotChange(final PlatformResourceKey resource, final int slotIndex) { + final ResourceType resourceType = resource.getResourceType(); + PlatformApi.INSTANCE.getResourceTypeRegistry().getId(resourceType).ifPresent( + id -> sendPacket(new ResourceFilterSlotChangePacket( slotIndex, resource, - storageChannelType, + resourceType, id )) ); diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/CraftingGridRecipeTransferPacket.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/CraftingGridRecipeTransferPacket.java index 45289443c..6fcd9799b 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/CraftingGridRecipeTransferPacket.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/CraftingGridRecipeTransferPacket.java @@ -1,8 +1,8 @@ package com.refinedmods.refinedstorage2.platform.forge.support.packet.c2s; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.grid.CraftingGridContainerMenu; import com.refinedmods.refinedstorage2.platform.common.support.packet.PacketIds; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.util.PacketUtil; import java.util.ArrayList; @@ -34,7 +34,7 @@ public void write(final FriendlyByteBuf buf) { for (final List slotPossibilities : recipe) { buf.writeInt(slotPossibilities.size()); for (final ItemResource slotPossibility : slotPossibilities) { - PacketUtil.writeItemResource(buf, slotPossibility); + slotPossibility.toBuffer(buf); } } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/GridExtractPacket.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/GridExtractPacket.java index 605e15e03..7bee58044 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/GridExtractPacket.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/GridExtractPacket.java @@ -3,7 +3,8 @@ import com.refinedmods.refinedstorage2.api.grid.operations.GridExtractMode; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridExtractionStrategy; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.support.packet.PacketIds; import net.minecraft.network.FriendlyByteBuf; @@ -11,41 +12,35 @@ import net.minecraft.resources.ResourceLocation; import net.neoforged.neoforge.network.handling.PlayPayloadContext; -public record GridExtractPacket( - PlatformStorageChannelType storageChannelType, - ResourceLocation storageChannelTypeId, - T resource, +public record GridExtractPacket( + ResourceType resourceType, + ResourceLocation resourceTypeId, + PlatformResourceKey resource, GridExtractMode mode, boolean cursor ) implements CustomPacketPayload { - @SuppressWarnings("unchecked") - public static GridExtractPacket decode(final FriendlyByteBuf buf) { - final ResourceLocation storageChannelTypeId = buf.readResourceLocation(); - final PlatformStorageChannelType storageChannelType = PlatformApi.INSTANCE - .getStorageChannelTypeRegistry() - .get(storageChannelTypeId) + public static GridExtractPacket decode(final FriendlyByteBuf buf) { + final ResourceLocation resourceTypeId = buf.readResourceLocation(); + final ResourceType resourceType = PlatformApi.INSTANCE + .getResourceTypeRegistry() + .get(resourceTypeId) .orElseThrow(); final GridExtractMode mode = getMode(buf.readByte()); final boolean cursor = buf.readBoolean(); - final Object resource = storageChannelType.fromBuffer(buf); - return new GridExtractPacket<>( - (PlatformStorageChannelType) storageChannelType, - storageChannelTypeId, + final PlatformResourceKey resource = resourceType.fromBuffer(buf); + return new GridExtractPacket( + resourceType, + resourceTypeId, resource, mode, cursor ); } - public static void handle(final GridExtractPacket packet, final PlayPayloadContext ctx) { + public static void handle(final GridExtractPacket packet, final PlayPayloadContext ctx) { ctx.player().ifPresent(player -> ctx.workHandler().submitAsync(() -> { if (player.containerMenu instanceof GridExtractionStrategy strategy) { - strategy.onExtract( - packet.storageChannelType, - packet.resource, - packet.mode, - packet.cursor - ); + strategy.onExtract(packet.resource, packet.mode, packet.cursor); } })); } @@ -67,10 +62,10 @@ public static void writeMode(final FriendlyByteBuf buf, final GridExtractMode mo @Override public void write(final FriendlyByteBuf buf) { - buf.writeResourceLocation(storageChannelTypeId); + buf.writeResourceLocation(resourceTypeId); writeMode(buf, mode); buf.writeBoolean(cursor); - storageChannelType.toBuffer(resource, buf); + resource.toBuffer(buf); } @Override diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/GridScrollPacket.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/GridScrollPacket.java index 36c24612f..5c4ee0e9a 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/GridScrollPacket.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/GridScrollPacket.java @@ -3,7 +3,8 @@ import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollMode; import com.refinedmods.refinedstorage2.platform.api.grid.strategy.GridScrollingStrategy; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.support.packet.PacketIds; import net.minecraft.network.FriendlyByteBuf; @@ -11,41 +12,35 @@ import net.minecraft.resources.ResourceLocation; import net.neoforged.neoforge.network.handling.PlayPayloadContext; -public record GridScrollPacket( - PlatformStorageChannelType storageChannelType, - ResourceLocation storageChannelTypeId, - T resource, +public record GridScrollPacket( + ResourceType resourceType, + ResourceLocation resourceTypeId, + PlatformResourceKey resource, GridScrollMode mode, int slotIndex ) implements CustomPacketPayload { - @SuppressWarnings("unchecked") - public static GridScrollPacket decode(final FriendlyByteBuf buf) { - final ResourceLocation storageChannelTypeId = buf.readResourceLocation(); - final PlatformStorageChannelType storageChannelType = PlatformApi.INSTANCE - .getStorageChannelTypeRegistry() - .get(storageChannelTypeId) + public static GridScrollPacket decode(final FriendlyByteBuf buf) { + final ResourceLocation resourceTypeId = buf.readResourceLocation(); + final ResourceType resourceType = PlatformApi.INSTANCE + .getResourceTypeRegistry() + .get(resourceTypeId) .orElseThrow(); final GridScrollMode mode = getMode(buf.readByte()); final int slotIndex = buf.readInt(); - final Object resource = storageChannelType.fromBuffer(buf); - return new GridScrollPacket<>( - (PlatformStorageChannelType) storageChannelType, - storageChannelTypeId, + final PlatformResourceKey resource = resourceType.fromBuffer(buf); + return new GridScrollPacket( + resourceType, + resourceTypeId, resource, mode, slotIndex ); } - public static void handle(final GridScrollPacket packet, final PlayPayloadContext ctx) { + public static void handle(final GridScrollPacket packet, final PlayPayloadContext ctx) { ctx.player().ifPresent(player -> ctx.workHandler().submitAsync(() -> { if (player.containerMenu instanceof GridScrollingStrategy strategy) { - strategy.onScroll( - packet.storageChannelType, - packet.resource, - packet.mode, - packet.slotIndex - ); + strategy.onScroll(packet.resource, packet.mode, packet.slotIndex); } })); } @@ -69,10 +64,10 @@ private static void writeMode(final FriendlyByteBuf buf, final GridScrollMode mo @Override public void write(final FriendlyByteBuf buf) { - buf.writeResourceLocation(storageChannelTypeId); + buf.writeResourceLocation(resourceTypeId); writeMode(buf, mode); buf.writeInt(slotIndex); - storageChannelType.toBuffer(resource, buf); + resource.toBuffer(buf); } @Override diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/ResourceFilterSlotChangePacket.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/ResourceFilterSlotChangePacket.java index 9619b428d..fc73cf246 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/ResourceFilterSlotChangePacket.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/c2s/ResourceFilterSlotChangePacket.java @@ -1,11 +1,11 @@ package com.refinedmods.refinedstorage2.platform.forge.support.packet.c2s; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.AbstractResourceContainerMenu; import com.refinedmods.refinedstorage2.platform.common.support.packet.PacketIds; -import java.util.Objects; import javax.annotation.Nullable; import net.minecraft.network.FriendlyByteBuf; @@ -13,40 +13,38 @@ import net.minecraft.resources.ResourceLocation; import net.neoforged.neoforge.network.handling.PlayPayloadContext; -public record ResourceFilterSlotChangePacket( +import static java.util.Objects.requireNonNull; + +public record ResourceFilterSlotChangePacket( int slotIndex, @Nullable - T resource, + PlatformResourceKey resource, @Nullable - PlatformStorageChannelType storageChannelType, + ResourceType resourceType, @Nullable - ResourceLocation storageChannelTypeId + ResourceLocation resourceTypeId ) implements CustomPacketPayload { - public static ResourceFilterSlotChangePacket decode(final FriendlyByteBuf buf) { + public static ResourceFilterSlotChangePacket decode(final FriendlyByteBuf buf) { final int slotIndex = buf.readInt(); - final ResourceLocation storageChannelTypeId = buf.readResourceLocation(); - return PlatformApi.INSTANCE.getStorageChannelTypeRegistry().get(storageChannelTypeId) - .map(storageChannelType -> decode(buf, slotIndex, storageChannelType, storageChannelTypeId)) - .orElseGet(() -> new ResourceFilterSlotChangePacket<>(slotIndex, null, null, storageChannelTypeId)); + final ResourceLocation resourceTypeId = buf.readResourceLocation(); + return PlatformApi.INSTANCE.getResourceTypeRegistry().get(resourceTypeId) + .map(resourceType -> decode(buf, slotIndex, resourceType, resourceTypeId)) + .orElseGet(() -> new ResourceFilterSlotChangePacket(slotIndex, null, null, resourceTypeId)); } - private static ResourceFilterSlotChangePacket decode(final FriendlyByteBuf buf, - final int slotIndex, - final PlatformStorageChannelType type, - final ResourceLocation typeId) { - final T resource = type.fromBuffer(buf); - return new ResourceFilterSlotChangePacket<>(slotIndex, resource, type, typeId); + private static ResourceFilterSlotChangePacket decode(final FriendlyByteBuf buf, + final int slotIndex, + final ResourceType type, + final ResourceLocation typeId) { + final PlatformResourceKey resource = type.fromBuffer(buf); + return new ResourceFilterSlotChangePacket(slotIndex, resource, type, typeId); } - public static void handle(final ResourceFilterSlotChangePacket packet, - final PlayPayloadContext ctx) { + public static void handle(final ResourceFilterSlotChangePacket packet, + final PlayPayloadContext ctx) { ctx.player().ifPresent(player -> ctx.workHandler().submitAsync(() -> { if (player.containerMenu instanceof AbstractResourceContainerMenu containerMenu) { - containerMenu.handleResourceFilterSlotUpdate( - packet.slotIndex, - Objects.requireNonNull(packet.storageChannelType), - Objects.requireNonNull(packet.resource) - ); + containerMenu.handleResourceFilterSlotUpdate(packet.slotIndex, requireNonNull(packet.resource)); } })); } @@ -54,8 +52,8 @@ public static void handle(final ResourceFilterSlotChangePacket packet, @Override public void write(final FriendlyByteBuf buf) { buf.writeInt(slotIndex); - buf.writeResourceLocation(Objects.requireNonNull(storageChannelTypeId)); - Objects.requireNonNull(storageChannelType).toBuffer(Objects.requireNonNull(resource), buf); + buf.writeResourceLocation(requireNonNull(resourceTypeId)); + requireNonNull(resource).toBuffer(buf); } @Override diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/s2c/GridUpdatePacket.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/s2c/GridUpdatePacket.java index eacf93ea4..95257c1fd 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/s2c/GridUpdatePacket.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/s2c/GridUpdatePacket.java @@ -2,7 +2,8 @@ import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.grid.AbstractGridContainerMenu; import com.refinedmods.refinedstorage2.platform.common.support.packet.PacketIds; import com.refinedmods.refinedstorage2.platform.common.util.PacketUtil; @@ -14,31 +15,30 @@ import net.minecraft.resources.ResourceLocation; import net.neoforged.neoforge.network.handling.PlayPayloadContext; -public record GridUpdatePacket(PlatformStorageChannelType storageChannelType, - ResourceLocation storageChannelTypeId, - T resource, - long amount, - @Nullable TrackedResource trackedResource) implements CustomPacketPayload { - @SuppressWarnings("unchecked") - public static GridUpdatePacket decode(final FriendlyByteBuf buf) { - final ResourceLocation storageChannelTypeId = buf.readResourceLocation(); - final PlatformStorageChannelType storageChannelType = PlatformApi.INSTANCE - .getStorageChannelTypeRegistry() - .get(storageChannelTypeId) +public record GridUpdatePacket( + ResourceLocation resourceTypeId, + PlatformResourceKey resource, + long amount, + @Nullable TrackedResource trackedResource +) implements CustomPacketPayload { + public static GridUpdatePacket decode(final FriendlyByteBuf buf) { + final ResourceLocation resourceTypeId = buf.readResourceLocation(); + final ResourceType resourceType = PlatformApi.INSTANCE + .getResourceTypeRegistry() + .get(resourceTypeId) .orElseThrow(); - final Object resource = storageChannelType.fromBuffer(buf); + final PlatformResourceKey resource = resourceType.fromBuffer(buf); final long amount = buf.readLong(); final TrackedResource trackedResource = PacketUtil.readTrackedResource(buf); - return new GridUpdatePacket<>( - (PlatformStorageChannelType) storageChannelType, - storageChannelTypeId, + return new GridUpdatePacket( + resourceTypeId, resource, amount, trackedResource ); } - public static void handle(final GridUpdatePacket packet, final PlayPayloadContext ctx) { + public static void handle(final GridUpdatePacket packet, final PlayPayloadContext ctx) { ctx.player().ifPresent(player -> ctx.workHandler().submitAsync(() -> { if (player.containerMenu instanceof AbstractGridContainerMenu containerMenu) { containerMenu.onResourceUpdate(packet.resource, packet.amount, packet.trackedResource); @@ -48,8 +48,8 @@ public static void handle(final GridUpdatePacket packet, final PlayPayloa @Override public void write(final FriendlyByteBuf buf) { - buf.writeResourceLocation(storageChannelTypeId); - storageChannelType.toBuffer(resource, buf); + buf.writeResourceLocation(resourceTypeId); + resource.toBuffer(buf); buf.writeLong(amount); PacketUtil.writeTrackedResource(buf, trackedResource); } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/s2c/ResourceSlotUpdatePacket.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/s2c/ResourceSlotUpdatePacket.java index 2b0f5d91d..be78e9d68 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/s2c/ResourceSlotUpdatePacket.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/s2c/ResourceSlotUpdatePacket.java @@ -1,8 +1,9 @@ package com.refinedmods.refinedstorage2.platform.forge.support.packet.s2c; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceType; import com.refinedmods.refinedstorage2.platform.common.support.containermenu.AbstractResourceContainerMenu; import com.refinedmods.refinedstorage2.platform.common.support.packet.PacketIds; @@ -13,33 +14,33 @@ import net.minecraft.resources.ResourceLocation; import net.neoforged.neoforge.network.handling.PlayPayloadContext; -public record ResourceSlotUpdatePacket(int slotIndex, - @Nullable ResourceAmountTemplate resourceAmount, - @Nullable ResourceLocation storageChannelTypeId) - implements CustomPacketPayload { - public static ResourceSlotUpdatePacket decode(final FriendlyByteBuf buf) { +public record ResourceSlotUpdatePacket( + int slotIndex, + @Nullable ResourceAmount resourceAmount, + @Nullable ResourceLocation resourceTypeId +) implements CustomPacketPayload { + public static ResourceSlotUpdatePacket decode(final FriendlyByteBuf buf) { final int slotIndex = buf.readInt(); final boolean present = buf.readBoolean(); if (!present) { - return new ResourceSlotUpdatePacket<>(slotIndex, null, null); + return new ResourceSlotUpdatePacket(slotIndex, null, null); } - final ResourceLocation storageChannelTypeId = buf.readResourceLocation(); - return PlatformApi.INSTANCE.getStorageChannelTypeRegistry().get(storageChannelTypeId).map( - storageChannelType -> decode(buf, slotIndex, storageChannelType) - ).orElseGet(() -> new ResourceSlotUpdatePacket<>(slotIndex, null, null)); + final ResourceLocation resourceTypeId = buf.readResourceLocation(); + return PlatformApi.INSTANCE.getResourceTypeRegistry().get(resourceTypeId).map( + resourceType -> decode(buf, slotIndex, resourceType) + ).orElseGet(() -> new ResourceSlotUpdatePacket(slotIndex, null, null)); } - private static ResourceSlotUpdatePacket decode(final FriendlyByteBuf buf, - final int slotIndex, - final PlatformStorageChannelType type) { - final T resource = type.fromBuffer(buf); + private static ResourceSlotUpdatePacket decode(final FriendlyByteBuf buf, + final int slotIndex, + final ResourceType type) { + final PlatformResourceKey resource = type.fromBuffer(buf); final long amount = buf.readLong(); - final ResourceAmountTemplate resourceAmount = new ResourceAmountTemplate<>(resource, amount, type); - return new ResourceSlotUpdatePacket<>(slotIndex, resourceAmount, null); + return new ResourceSlotUpdatePacket(slotIndex, new ResourceAmount(resource, amount), null); } - public static void handle(final ResourceSlotUpdatePacket packet, - final PlayPayloadContext ctx) { + public static void handle(final ResourceSlotUpdatePacket packet, + final PlayPayloadContext ctx) { ctx.player().ifPresent(player -> ctx.workHandler().submitAsync(() -> { if (player.containerMenu instanceof AbstractResourceContainerMenu containerMenu) { containerMenu.handleResourceSlotUpdate(packet.slotIndex, packet.resourceAmount); @@ -50,11 +51,11 @@ public static void handle(final ResourceSlotUpdatePacket packet, @Override public void write(final FriendlyByteBuf buf) { buf.writeInt(slotIndex); - final boolean present = resourceAmount != null && storageChannelTypeId != null; + final boolean present = resourceAmount != null && resourceTypeId != null; buf.writeBoolean(present); if (present) { - buf.writeResourceLocation(storageChannelTypeId); - resourceAmount.getStorageChannelType().toBuffer(resourceAmount.getResource(), buf); + buf.writeResourceLocation(resourceTypeId); + ((PlatformResourceKey) resourceAmount.getResource()).toBuffer(buf); buf.writeLong(resourceAmount.getAmount()); } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/s2c/ServerToClientCommunicationsImpl.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/s2c/ServerToClientCommunicationsImpl.java index 00595fd82..572261c2c 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/s2c/ServerToClientCommunicationsImpl.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/packet/s2c/ServerToClientCommunicationsImpl.java @@ -1,10 +1,10 @@ package com.refinedmods.refinedstorage2.platform.forge.support.packet.s2c; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.storage.StorageInfo; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.platform.api.support.resource.PlatformResourceKey; import com.refinedmods.refinedstorage2.platform.common.networking.NetworkTransmitterStatus; import com.refinedmods.refinedstorage2.platform.common.support.ServerToClientCommunications; @@ -36,16 +36,12 @@ public void sendGridActiveness(final ServerPlayer player, final boolean active) } @Override - public void sendGridUpdate(final ServerPlayer player, - final PlatformStorageChannelType storageChannelType, - final T resource, - final long change, - @Nullable final TrackedResource trackedResource) { - PlatformApi.INSTANCE - .getStorageChannelTypeRegistry() - .getId(storageChannelType) - .ifPresent(id -> sendToPlayer(player, new GridUpdatePacket<>( - storageChannelType, + public void sendGridUpdate(final ServerPlayer player, + final PlatformResourceKey resource, + final long change, + @Nullable final TrackedResource trackedResource) { + PlatformApi.INSTANCE.getResourceTypeRegistry().getId(resource.getResourceType()) + .ifPresent(id -> sendToPlayer(player, new GridUpdatePacket( id, resource, change, @@ -59,19 +55,18 @@ public void sendGridClear(final ServerPlayer player) { } @Override - public void sendResourceSlotUpdate(final ServerPlayer player, - @Nullable final ResourceAmountTemplate resourceAmount, - final int slotIndex) { - if (resourceAmount != null) { - PlatformApi.INSTANCE.getStorageChannelTypeRegistry() - .getId(resourceAmount.getStorageChannelType()) - .ifPresent(id -> sendToPlayer(player, new ResourceSlotUpdatePacket<>( + public void sendResourceSlotUpdate(final ServerPlayer player, + @Nullable final ResourceAmount resourceAmount, + final int slotIndex) { + if (resourceAmount != null && resourceAmount.getResource() instanceof PlatformResourceKey platformResource) { + PlatformApi.INSTANCE.getResourceTypeRegistry().getId(platformResource.getResourceType()) + .ifPresent(id -> sendToPlayer(player, new ResourceSlotUpdatePacket( slotIndex, resourceAmount, id ))); } else { - sendToPlayer(player, new ResourceSlotUpdatePacket<>( + sendToPlayer(player, new ResourceSlotUpdatePacket( slotIndex, null, null diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/render/FluidStackFluidRenderer.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/render/FluidStackFluidRenderer.java index 4cd49fde3..84df21784 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/render/FluidStackFluidRenderer.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/render/FluidStackFluidRenderer.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.forge.support.render; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.common.support.render.AbstractFluidRenderer; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import java.util.Collections; import java.util.HashMap; diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/resource/ResourceContainerFluidHandlerAdapter.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/resource/ResourceContainerFluidHandlerAdapter.java index 1fedece10..de24cbc94 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/resource/ResourceContainerFluidHandlerAdapter.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/resource/ResourceContainerFluidHandlerAdapter.java @@ -1,9 +1,10 @@ package com.refinedmods.refinedstorage2.platform.forge.support.resource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.platform.api.support.resource.ResourceContainer; -import com.refinedmods.refinedstorage2.platform.common.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.ResourceTypes; import javax.annotation.Nullable; @@ -28,7 +29,7 @@ public int getTanks() { @Override public FluidStack getFluidInTank(final int tank) { - final ResourceAmountTemplate resourceAmount = container.get(tank); + final ResourceAmount resourceAmount = container.get(tank); if (resourceAmount == null || !(resourceAmount.getResource() instanceof FluidResource fluidResource)) { return FluidStack.EMPTY; } @@ -37,9 +38,9 @@ public FluidStack getFluidInTank(final int tank) { @Override public int getTankCapacity(final int tank) { - final ResourceAmountTemplate resourceAmount = container.get(tank); - if (resourceAmount == null || resourceAmount.getResource() instanceof FluidResource) { - return (int) StorageChannelTypes.FLUID.getInterfaceExportLimit(); + final ResourceKey resource = container.getResource(tank); + if (resource == null || resource instanceof FluidResource) { + return (int) ResourceTypes.FLUID.getInterfaceExportLimit(); } return 0; } @@ -51,12 +52,7 @@ public boolean isFluidValid(final int tank, final FluidStack stack) { @Override public int fill(final FluidStack resource, final FluidAction action) { - return (int) container.insert( - StorageChannelTypes.FLUID, - ofFluidStack(resource), - resource.getAmount(), - toAction(action) - ); + return (int) container.insert(ofFluidStack(resource), resource.getAmount(), toAction(action)); } @Override @@ -85,8 +81,8 @@ public FluidStack drain(final int maxDrain, final FluidAction action) { @Nullable private FluidResource findExtractableFluidResource() { for (int i = 0; i < container.size(); ++i) { - final ResourceAmountTemplate resourceAmount = container.get(i); - if (resourceAmount == null || !(resourceAmount.getResource() instanceof FluidResource fluidResource)) { + final ResourceKey resource = container.getResource(i); + if (!(resource instanceof FluidResource fluidResource)) { continue; } return fluidResource; diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/resource/VariantUtil.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/resource/VariantUtil.java index 0a3cd6f8a..27367bae7 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/resource/VariantUtil.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/support/resource/VariantUtil.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.forge.support.resource; import com.refinedmods.refinedstorage2.api.core.Action; -import com.refinedmods.refinedstorage2.platform.api.support.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.support.resource.FluidResource; import java.util.Objects; diff --git a/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/ResourceAmount.java b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/ResourceAmount.java index 636102d7b..d6227df99 100644 --- a/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/ResourceAmount.java +++ b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/ResourceAmount.java @@ -5,27 +5,25 @@ import org.apiguardian.api.API; /** - * A class representing a resource of an arbitrary type, and a corresponding amount. + * A class representing a resource and a corresponding amount. * The resource cannot be mutated but the amount can be modified. - * - * @param the type of resource */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") -public final class ResourceAmount { - private final T resource; +public final class ResourceAmount { + private final ResourceKey resource; private long amount; /** * @param resource the resource, must be non-null * @param amount the amount, must be larger than 0 */ - public ResourceAmount(final T resource, final long amount) { + public ResourceAmount(final ResourceKey resource, final long amount) { validate(resource, amount); this.resource = resource; this.amount = amount; } - public T getResource() { + public ResourceKey getResource() { return resource; } @@ -66,7 +64,7 @@ public String toString() { + '}'; } - public static void validate(final T resource, final long amount) { + public static void validate(final ResourceKey resource, final long amount) { CoreValidations.validateLargerThanZero(amount, "Amount must be larger than 0"); CoreValidations.validateNotNull(resource, "Resource must not be null"); } diff --git a/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/ResourceKey.java b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/ResourceKey.java new file mode 100644 index 000000000..daebbc4e5 --- /dev/null +++ b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/ResourceKey.java @@ -0,0 +1,7 @@ +package com.refinedmods.refinedstorage2.api.resource; + +import org.apiguardian.api.API; + +@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.4") +public interface ResourceKey { +} diff --git a/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/filter/Filter.java b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/filter/Filter.java new file mode 100644 index 000000000..fd0dbb8b4 --- /dev/null +++ b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/filter/Filter.java @@ -0,0 +1,42 @@ +package com.refinedmods.refinedstorage2.api.resource.filter; + +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; + +import java.util.HashSet; +import java.util.Set; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +import org.apiguardian.api.API; + +@API(status = API.Status.STABLE, since = "2.0.0-milestone.1.0") +public class Filter { + private final Set filters = new HashSet<>(); + private FilterMode mode = FilterMode.BLOCK; + private UnaryOperator normalizer = value -> value; + + public FilterMode getMode() { + return mode; + } + + public void setNormalizer(final UnaryOperator normalizer) { + this.normalizer = normalizer; + } + + public void setMode(final FilterMode mode) { + this.mode = mode; + } + + public boolean isAllowed(final ResourceKey resource) { + final ResourceKey normalized = normalizer.apply(resource); + return switch (mode) { + case ALLOW -> filters.contains(normalized); + case BLOCK -> !filters.contains(normalized); + }; + } + + public void setFilters(final Set filters) { + this.filters.clear(); + this.filters.addAll(filters.stream().map(normalizer).collect(Collectors.toSet())); + } +} diff --git a/refinedstorage2-core-api/src/main/java/com/refinedmods/refinedstorage2/api/core/filter/FilterMode.java b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/filter/FilterMode.java similarity index 70% rename from refinedstorage2-core-api/src/main/java/com/refinedmods/refinedstorage2/api/core/filter/FilterMode.java rename to refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/filter/FilterMode.java index 88f9de115..fd2a97fc0 100644 --- a/refinedstorage2-core-api/src/main/java/com/refinedmods/refinedstorage2/api/core/filter/FilterMode.java +++ b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/filter/FilterMode.java @@ -1,4 +1,4 @@ -package com.refinedmods.refinedstorage2.api.core.filter; +package com.refinedmods.refinedstorage2.api.resource.filter; import org.apiguardian.api.API; diff --git a/refinedstorage2-core-api/src/main/java/com/refinedmods/refinedstorage2/api/core/filter/package-info.java b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/filter/package-info.java similarity index 77% rename from refinedstorage2-core-api/src/main/java/com/refinedmods/refinedstorage2/api/core/filter/package-info.java rename to refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/filter/package-info.java index 9c8b39430..a28d22e92 100644 --- a/refinedstorage2-core-api/src/main/java/com/refinedmods/refinedstorage2/api/core/filter/package-info.java +++ b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/filter/package-info.java @@ -1,6 +1,6 @@ @ParametersAreNonnullByDefault @FieldsAndMethodsAreNonnullByDefault -package com.refinedmods.refinedstorage2.api.core.filter; +package com.refinedmods.refinedstorage2.api.resource.filter; import com.refinedmods.refinedstorage2.api.core.FieldsAndMethodsAreNonnullByDefault; diff --git a/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/AbstractProxyResourceList.java b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/AbstractProxyResourceList.java index 0d78f05ee..745642248 100644 --- a/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/AbstractProxyResourceList.java +++ b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/AbstractProxyResourceList.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.api.resource.list; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import java.util.Collection; import java.util.Optional; @@ -9,34 +10,32 @@ /** * This is a utility class to easily decorate a {@link ResourceList}. - * - * @param the type of resource */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") -public abstract class AbstractProxyResourceList implements ResourceList { - private final ResourceList delegate; +public abstract class AbstractProxyResourceList implements ResourceList { + private final ResourceList delegate; - protected AbstractProxyResourceList(final ResourceList delegate) { + protected AbstractProxyResourceList(final ResourceList delegate) { this.delegate = delegate; } @Override - public ResourceListOperationResult add(final T resource, final long amount) { + public ResourceListOperationResult add(final ResourceKey resource, final long amount) { return delegate.add(resource, amount); } @Override - public Optional> remove(final T resource, final long amount) { + public Optional remove(final ResourceKey resource, final long amount) { return delegate.remove(resource, amount); } @Override - public Optional> get(final T resource) { + public Optional get(final ResourceKey resource) { return delegate.get(resource); } @Override - public Collection> getAll() { + public Collection getAll() { return delegate.getAll(); } diff --git a/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/ResourceList.java b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/ResourceList.java index 3077e3d7f..da1b6ee06 100644 --- a/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/ResourceList.java +++ b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/ResourceList.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.api.resource.list; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import java.util.Collection; import java.util.Optional; @@ -10,11 +11,9 @@ /** * Represents a list of a resource of an arbitrary type. * A basic implementation of this class can be found in {@link ResourceListImpl}. - * - * @param the type of resource */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") -public interface ResourceList { +public interface ResourceList { /** * Adds a given resource to the list. * @@ -22,16 +21,16 @@ public interface ResourceList { * @param amount the amount, must be larger than 0 * @return the result of the operation */ - ResourceListOperationResult add(T resource, long amount); + ResourceListOperationResult add(ResourceKey resource, long amount); /** * Adds a given resource to the list. - * Shorthand for {@link #add(Object, long)}. + * Shorthand for {@link #add(ResourceKey, long)}. * * @param resourceAmount the resource and the amount * @return the result of the operation */ - default ResourceListOperationResult add(ResourceAmount resourceAmount) { + default ResourceListOperationResult add(ResourceAmount resourceAmount) { return add(resourceAmount.getResource(), resourceAmount.getAmount()); } @@ -43,17 +42,17 @@ default ResourceListOperationResult add(ResourceAmount resourceAmount) { * @param amount the amount, must be larger than 0 * @return a result if the removal operation was successful, otherwise an empty {@link Optional} */ - Optional> remove(T resource, long amount); + Optional remove(ResourceKey resource, long amount); /** * Removes an amount of a certain resource in the list. * If the amount reaches 0 due to this removal, the resource is removed from the list. - * Shorthand for {@link #remove(Object, long)}. + * Shorthand for {@link #remove(ResourceKey, long)}. * * @param resourceAmount the resource and the amount * @return a result if the removal operation was successful, otherwise an empty {@link Optional} */ - default Optional> remove(ResourceAmount resourceAmount) { + default Optional remove(ResourceAmount resourceAmount) { return remove(resourceAmount.getResource(), resourceAmount.getAmount()); } @@ -63,14 +62,14 @@ default Optional> remove(ResourceAmount resour * @param resource the resource * @return the resource amount if it's present in the list, otherwise an empty {@link Optional} */ - Optional> get(T resource); + Optional get(ResourceKey resource); /** * Retrieves all resources and their amounts from the list. * * @return a list of resource amounts */ - Collection> getAll(); + Collection getAll(); /** * Clears the list. diff --git a/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/ResourceListImpl.java b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/ResourceListImpl.java index 0c90d1275..24929b0fd 100644 --- a/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/ResourceListImpl.java +++ b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/ResourceListImpl.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.api.resource.list; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import java.util.Collection; import java.util.HashMap; @@ -11,17 +12,14 @@ /** * An implementation of a {@link ResourceList} that stores the resource entries in a {@link HashMap}. - * This resource list implementation relies on {@link Object#equals(Object)} and {@link Object#hashCode()}. - * - * @param the type of resource */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") -public class ResourceListImpl implements ResourceList { - private final Map> entries = new HashMap<>(); +public class ResourceListImpl implements ResourceList { + private final Map entries = new HashMap<>(); @Override - public ResourceListOperationResult add(final T resource, final long amount) { - final ResourceAmount existing = entries.get(resource); + public ResourceListOperationResult add(final ResourceKey resource, final long amount) { + final ResourceAmount existing = entries.get(resource); if (existing != null) { return addToExisting(existing, amount); } else { @@ -29,23 +27,23 @@ public ResourceListOperationResult add(final T resource, final long amount) { } } - private ResourceListOperationResult addToExisting(final ResourceAmount resourceAmount, final long amount) { + private ResourceListOperationResult addToExisting(final ResourceAmount resourceAmount, final long amount) { resourceAmount.increment(amount); - return new ResourceListOperationResult<>(resourceAmount, amount, true); + return new ResourceListOperationResult(resourceAmount, amount, true); } - private ResourceListOperationResult addNew(final T resource, final long amount) { - final ResourceAmount resourceAmount = new ResourceAmount<>(resource, amount); + private ResourceListOperationResult addNew(final ResourceKey resource, final long amount) { + final ResourceAmount resourceAmount = new ResourceAmount(resource, amount); entries.put(resource, resourceAmount); - return new ResourceListOperationResult<>(resourceAmount, amount, true); + return new ResourceListOperationResult(resourceAmount, amount, true); } @Override - public Optional> remove(final T resource, final long amount) { + public Optional remove(final ResourceKey resource, final long amount) { ResourceAmount.validate(resource, amount); - final ResourceAmount existing = entries.get(resource); + final ResourceAmount existing = entries.get(resource); if (existing != null) { if (existing.getAmount() - amount <= 0) { return removeCompletely(existing); @@ -57,17 +55,17 @@ public Optional> remove(final T resource, final l return Optional.empty(); } - private Optional> removePartly(final long amount, - final ResourceAmount resourceAmount) { + private Optional removePartly(final long amount, + final ResourceAmount resourceAmount) { resourceAmount.decrement(amount); - return Optional.of(new ResourceListOperationResult<>(resourceAmount, -amount, true)); + return Optional.of(new ResourceListOperationResult(resourceAmount, -amount, true)); } - private Optional> removeCompletely(final ResourceAmount resourceAmount) { + private Optional removeCompletely(final ResourceAmount resourceAmount) { entries.remove(resourceAmount.getResource()); - return Optional.of(new ResourceListOperationResult<>( + return Optional.of(new ResourceListOperationResult( resourceAmount, -resourceAmount.getAmount(), false @@ -75,12 +73,12 @@ private Optional> removeCompletely(final Resource } @Override - public Optional> get(final T resource) { + public Optional get(final ResourceKey resource) { return Optional.ofNullable(entries.get(resource)); } @Override - public Collection> getAll() { + public Collection getAll() { return entries.values(); } diff --git a/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/ResourceListOperationResult.java b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/ResourceListOperationResult.java index c6aa484a9..d4c860f00 100644 --- a/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/ResourceListOperationResult.java +++ b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/ResourceListOperationResult.java @@ -7,11 +7,10 @@ /** * Represents the result of an operation in a {@link ResourceList}. * - * @param the type of resource * @param resourceAmount the current resource amount in the list * @param change the delta caused by the operation * @param available whether this resource is still available in the list, or if it was removed */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") -public record ResourceListOperationResult(ResourceAmount resourceAmount, long change, boolean available) { +public record ResourceListOperationResult(ResourceAmount resourceAmount, long change, boolean available) { } diff --git a/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/listenable/ListenableResourceList.java b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/listenable/ListenableResourceList.java index 3523e4c1f..2f304d530 100644 --- a/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/listenable/ListenableResourceList.java +++ b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/listenable/ListenableResourceList.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage2.api.resource.list.listenable; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.resource.list.AbstractProxyResourceList; import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; import com.refinedmods.refinedstorage2.api.resource.list.ResourceListOperationResult; @@ -15,38 +16,39 @@ * Can easily be used with an existing list by passing it in the constructor. * The {@link ResourceListListener#onChanged(ResourceListOperationResult)} method is only called when the change * is being performed through this list, not the delegate list. - * - * @param the resource */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") -public class ListenableResourceList extends AbstractProxyResourceList { - private final Set> listeners = new HashSet<>(); +public class ListenableResourceList extends AbstractProxyResourceList { + private final Set listeners = new HashSet<>(); - public ListenableResourceList(final ResourceList delegate) { + public ListenableResourceList(final ResourceList delegate) { super(delegate); } @Override - public ResourceListOperationResult add(final T resource, final long amount) { - final ResourceListOperationResult result = super.add(resource, amount); - listeners.forEach(listener -> listener.onChanged(result)); + public ResourceListOperationResult add(final ResourceKey resource, final long amount) { + final ResourceListOperationResult result = super.add(resource, amount); + notifyListeners(result); return result; } @Override - public Optional> remove(final T resource, final long amount) { - return super.remove(resource, amount) - .map(result -> { - listeners.forEach(listener -> listener.onChanged(result)); - return result; - }); + public Optional remove(final ResourceKey resource, final long amount) { + return super.remove(resource, amount).map(result -> { + notifyListeners(result); + return result; + }); + } + + private void notifyListeners(final ResourceListOperationResult result) { + listeners.forEach(listener -> listener.onChanged(result)); } - public void addListener(final ResourceListListener listener) { + public void addListener(final ResourceListListener listener) { listeners.add(listener); } - public void removeListener(final ResourceListListener listener) { + public void removeListener(final ResourceListListener listener) { listeners.remove(listener); } } diff --git a/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/listenable/ResourceListListener.java b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/listenable/ResourceListListener.java index fb4b790bf..825ee53ef 100644 --- a/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/listenable/ResourceListListener.java +++ b/refinedstorage2-resource-api/src/main/java/com/refinedmods/refinedstorage2/api/resource/list/listenable/ResourceListListener.java @@ -6,16 +6,14 @@ /** * A listener for resource list operations. Can be used on a {@link ListenableResourceList}. - * - * @param the type of resource */ @FunctionalInterface @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") -public interface ResourceListListener { +public interface ResourceListListener { /** * Called when a list operation has occurred. * * @param change the change */ - void onChanged(ResourceListOperationResult change); + void onChanged(ResourceListOperationResult change); } diff --git a/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/ResourceAmountTest.java b/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/ResourceAmountTest.java index 505ea9000..0802abbbb 100644 --- a/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/ResourceAmountTest.java +++ b/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/ResourceAmountTest.java @@ -9,31 +9,31 @@ class ResourceAmountTest { @Test void testValidResource() { // Act - final ResourceAmount resourceAmount = new ResourceAmount<>("A", 1); + final ResourceAmount resourceAmount = new ResourceAmount(TestResource.A, 1); // Assert assertThat(resourceAmount.getAmount()).isEqualTo(1); - assertThat(resourceAmount.getResource()).isEqualTo("A"); + assertThat(resourceAmount.getResource()).isEqualTo(TestResource.A); } @Test @SuppressWarnings("ConstantConditions") void testInvalidResource() { // Act & assert - assertThrows(NullPointerException.class, () -> new ResourceAmount<>(null, 1)); + assertThrows(NullPointerException.class, () -> new ResourceAmount(null, 1)); } @Test void testInvalidAmount() { // Act & assert - assertThrows(IllegalArgumentException.class, () -> new ResourceAmount<>("A", 0)); - assertThrows(IllegalArgumentException.class, () -> new ResourceAmount<>("A", -1)); + assertThrows(IllegalArgumentException.class, () -> new ResourceAmount(TestResource.A, 0)); + assertThrows(IllegalArgumentException.class, () -> new ResourceAmount(TestResource.A, -1)); } @Test void shouldNotIncrementZeroOrNegativeAmount() { // Arrange - final ResourceAmount sut = new ResourceAmount<>("A", 1); + final ResourceAmount sut = new ResourceAmount(TestResource.A, 1); // Act & assert assertThrows(IllegalArgumentException.class, () -> sut.increment(0)); @@ -43,7 +43,7 @@ void shouldNotIncrementZeroOrNegativeAmount() { @Test void shouldNotDecrementZeroOrNegativeAmount() { // Arrange - final ResourceAmount sut = new ResourceAmount<>("A", 3); + final ResourceAmount sut = new ResourceAmount(TestResource.A, 3); // Act & assert assertThrows(IllegalArgumentException.class, () -> sut.decrement(0)); @@ -53,7 +53,7 @@ void shouldNotDecrementZeroOrNegativeAmount() { @Test void shouldNotDecrementLeadingToZeroAmount() { // Arrange - final ResourceAmount sut = new ResourceAmount<>("A", 3); + final ResourceAmount sut = new ResourceAmount(TestResource.A, 3); // Act & assert assertThrows(IllegalArgumentException.class, () -> sut.decrement(3)); @@ -62,7 +62,7 @@ void shouldNotDecrementLeadingToZeroAmount() { @Test void shouldIncrement() { // Arrange - final ResourceAmount sut = new ResourceAmount<>("A", 3); + final ResourceAmount sut = new ResourceAmount(TestResource.A, 3); // Act sut.increment(2); @@ -74,7 +74,7 @@ void shouldIncrement() { @Test void shouldDecrement() { // Arrange - final ResourceAmount sut = new ResourceAmount<>("A", 3); + final ResourceAmount sut = new ResourceAmount(TestResource.A, 3); // Act sut.decrement(2); @@ -86,7 +86,7 @@ void shouldDecrement() { @Test void testToString() { // Arrange - final ResourceAmount sut = new ResourceAmount<>("A", 3); + final ResourceAmount sut = new ResourceAmount(TestResource.A, 3); // Act & assert assertThat(sut).hasToString( diff --git a/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/TestResource.java b/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/TestResource.java new file mode 100644 index 000000000..9673135e4 --- /dev/null +++ b/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/TestResource.java @@ -0,0 +1,7 @@ +package com.refinedmods.refinedstorage2.api.resource; + +public enum TestResource implements ResourceKey { + A, + B, + C +} diff --git a/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/filter/FilterTest.java b/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/filter/FilterTest.java new file mode 100644 index 000000000..232edb367 --- /dev/null +++ b/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/filter/FilterTest.java @@ -0,0 +1,142 @@ +package com.refinedmods.refinedstorage2.api.resource.filter; + +import java.util.Set; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static com.refinedmods.refinedstorage2.api.resource.TestResource.A; +import static com.refinedmods.refinedstorage2.api.resource.TestResource.B; +import static com.refinedmods.refinedstorage2.api.resource.TestResource.C; +import static org.assertj.core.api.Assertions.assertThat; + +class FilterTest { + private Filter sut; + + @BeforeEach + void setUp() { + sut = new Filter(); + } + + @Test + void testDefaults() { + // Assert + assertThat(sut.getMode()).isEqualTo(FilterMode.BLOCK); + } + + @Test + void testEmptyBlocklistShouldAllowAll() { + // Act + final boolean allowed = sut.isAllowed(A); + + // Assert + assertThat(allowed).isTrue(); + } + + @Test + void testEmptyAllowlistAllowsNone() { + // Arrange + sut.setMode(FilterMode.ALLOW); + + // Act + final boolean allowed = sut.isAllowed(A); + + // Assert + assertThat(allowed).isFalse(); + } + + @Test + void testAllowlist() { + // Arrange + sut.setMode(FilterMode.ALLOW); + sut.setFilters(Set.of(A, B)); + + // Act + final boolean allowsDirt = sut.isAllowed(A); + final boolean allowsStone = sut.isAllowed(B); + final boolean allowsSponge = sut.isAllowed(C); + + // Assert + assertThat(allowsDirt).isTrue(); + assertThat(allowsStone).isTrue(); + assertThat(allowsSponge).isFalse(); + } + + @Test + void testBlocklist() { + // Arrange + sut.setFilters(Set.of(A, B)); + + // Act + final boolean allowsDirt = sut.isAllowed(A); + final boolean allowsStone = sut.isAllowed(B); + final boolean allowsSponge = sut.isAllowed(C); + + // Assert + assertThat(allowsDirt).isFalse(); + assertThat(allowsStone).isFalse(); + assertThat(allowsSponge).isTrue(); + } + + @Test + void shouldBeAbleToModifyFilters() { + // Arrange + sut.setFilters(Set.of(B)); + + final boolean allowsDirt = sut.isAllowed(A); + final boolean allowsStone = sut.isAllowed(B); + final boolean allowsSponge = sut.isAllowed(C); + + // Act + sut.setFilters(Set.of(A, C)); + + final boolean allowsDirtAfter = sut.isAllowed(A); + final boolean allowsStoneAfter = sut.isAllowed(B); + final boolean allowsSpongeAfter = sut.isAllowed(C); + + // Assert + assertThat(allowsDirt).isTrue(); + assertThat(allowsStone).isFalse(); + assertThat(allowsSponge).isTrue(); + + assertThat(allowsDirtAfter).isFalse(); + assertThat(allowsStoneAfter).isTrue(); + assertThat(allowsSpongeAfter).isFalse(); + } + + @Test + void testAllowlistNormalizer() { + // Arrange + sut.setNormalizer(resource -> { + if (resource == A) { + return B; + } + return resource; + }); + sut.setMode(FilterMode.ALLOW); + sut.setFilters(Set.of(A)); + + // Act & assert + assertThat(sut.isAllowed(A)).isTrue(); + assertThat(sut.isAllowed(B)).isTrue(); + assertThat(sut.isAllowed(C)).isFalse(); + } + + @Test + void testBlocklistNormalizer() { + // Arrange + sut.setNormalizer(resource -> { + if (resource == A) { + return B; + } + return resource; + }); + sut.setMode(FilterMode.BLOCK); + sut.setFilters(Set.of(A)); + + // Act & assert + assertThat(sut.isAllowed(A)).isFalse(); + assertThat(sut.isAllowed(B)).isFalse(); + assertThat(sut.isAllowed(C)).isTrue(); + } +} diff --git a/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/list/AbstractResourceListTest.java b/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/list/AbstractResourceListTest.java index 36927cec5..111ba83c8 100644 --- a/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/list/AbstractResourceListTest.java +++ b/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/list/AbstractResourceListTest.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.api.resource.list; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.TestResource; import java.util.ArrayList; import java.util.Collection; @@ -14,95 +15,95 @@ import static org.junit.jupiter.api.Assertions.assertThrows; abstract class AbstractResourceListTest { - private ResourceList list; + private ResourceList list; @BeforeEach void setUp() { list = createList(); } - protected abstract ResourceList createList(); + protected abstract ResourceList createList(); @Test void shouldAddNewResource() { // Act - final ResourceListOperationResult result = list.add("A", 10); + final ResourceListOperationResult result = list.add(TestResource.A, 10); // Assert assertThat(result.change()).isEqualTo(10); assertThat(result.resourceAmount().getAmount()).isEqualTo(10); - assertThat(result.resourceAmount().getResource()).isEqualTo("A"); + assertThat(result.resourceAmount().getResource()).isEqualTo(TestResource.A); assertThat(result.available()).isTrue(); assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(TestResource.A, 10) ); } @Test void shouldAddNewResourceWithResourceAmountDirectly() { // Act - final ResourceListOperationResult result = list.add(new ResourceAmount<>("A", 10)); + final ResourceListOperationResult result = list.add(new ResourceAmount(TestResource.A, 10)); // Assert assertThat(result.change()).isEqualTo(10); assertThat(result.resourceAmount().getAmount()).isEqualTo(10); - assertThat(result.resourceAmount().getResource()).isEqualTo("A"); + assertThat(result.resourceAmount().getResource()).isEqualTo(TestResource.A); assertThat(result.available()).isTrue(); assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(TestResource.A, 10) ); } @Test void shouldAddMultipleOfSameResource() { // Act - final ResourceListOperationResult result1 = list.add("A", 10); - final ResourceListOperationResult result2 = list.add("A", 5); + final ResourceListOperationResult result1 = list.add(TestResource.A, 10); + final ResourceListOperationResult result2 = list.add(TestResource.A, 5); // Assert assertThat(result1.change()).isEqualTo(10); assertThat(result1.resourceAmount().getAmount()).isEqualTo(15); - assertThat(result1.resourceAmount().getResource()).isEqualTo("A"); + assertThat(result1.resourceAmount().getResource()).isEqualTo(TestResource.A); assertThat(result1.available()).isTrue(); assertThat(result2.change()).isEqualTo(5); assertThat(result1.resourceAmount().getAmount()).isEqualTo(15); - assertThat(result1.resourceAmount().getResource()).isEqualTo("A"); + assertThat(result1.resourceAmount().getResource()).isEqualTo(TestResource.A); assertThat(result2.available()).isTrue(); assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 15) + new ResourceAmount(TestResource.A, 15) ); } @Test void shouldAddMultipleOfDifferentResources() { // Act - final ResourceListOperationResult result1 = list.add("A", 10); - final ResourceListOperationResult result2 = list.add("A", 5); - final ResourceListOperationResult result3 = list.add("B", 3); + final ResourceListOperationResult result1 = list.add(TestResource.A, 10); + final ResourceListOperationResult result2 = list.add(TestResource.A, 5); + final ResourceListOperationResult result3 = list.add(TestResource.B, 3); // Assert assertThat(result1.change()).isEqualTo(10); assertThat(result1.resourceAmount().getAmount()).isEqualTo(15); - assertThat(result1.resourceAmount().getResource()).isEqualTo("A"); + assertThat(result1.resourceAmount().getResource()).isEqualTo(TestResource.A); assertThat(result1.available()).isTrue(); assertThat(result2.change()).isEqualTo(5); assertThat(result2.resourceAmount().getAmount()).isEqualTo(15); - assertThat(result2.resourceAmount().getResource()).isEqualTo("A"); + assertThat(result2.resourceAmount().getResource()).isEqualTo(TestResource.A); assertThat(result2.available()).isTrue(); assertThat(result3.change()).isEqualTo(3); assertThat(result3.resourceAmount().getAmount()).isEqualTo(3); - assertThat(result3.resourceAmount().getResource()).isEqualTo("B"); + assertThat(result3.resourceAmount().getResource()).isEqualTo(TestResource.B); assertThat(result3.available()).isTrue(); assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 15), - new ResourceAmount<>("B", 3) + new ResourceAmount(TestResource.A, 15), + new ResourceAmount(TestResource.B, 3) ); } @@ -110,8 +111,8 @@ void shouldAddMultipleOfDifferentResources() { @SuppressWarnings("ConstantConditions") void shouldNotAddInvalidResourceOrAmount() { // Act - final Executable action1 = () -> list.add("A", 0); - final Executable action2 = () -> list.add("A", -1); + final Executable action1 = () -> list.add(TestResource.A, 0); + final Executable action2 = () -> list.add(TestResource.A, -1); final Executable action3 = () -> list.add(null, 1); // Assert @@ -123,7 +124,7 @@ void shouldNotAddInvalidResourceOrAmount() { @Test void shouldNotRemoveResourceWhenItIsNotAvailable() { // Act - final Optional> result = list.remove("A", 10); + final Optional result = list.remove(TestResource.A, 10); // Assert assertThat(result).isEmpty(); @@ -132,34 +133,34 @@ void shouldNotRemoveResourceWhenItIsNotAvailable() { @Test void shouldRemoveResourcePartly() { // Arrange - list.add("A", 20); - list.add("B", 6); + list.add(TestResource.A, 20); + list.add(TestResource.B, 6); // Act - final Optional> result2 = list.remove("A", 5); + final Optional result2 = list.remove(TestResource.A, 5); // Assert assertThat(result2).isPresent(); assertThat(result2.get().change()).isEqualTo(-5); assertThat(result2.get().resourceAmount().getAmount()).isEqualTo(15); - assertThat(result2.get().resourceAmount().getResource()).isEqualTo("A"); + assertThat(result2.get().resourceAmount().getResource()).isEqualTo(TestResource.A); assertThat(result2.get().available()).isTrue(); assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 15), - new ResourceAmount<>("B", 6) + new ResourceAmount(TestResource.A, 15), + new ResourceAmount(TestResource.B, 6) ); } @Test void shouldRemoveResourcePartlyWithResourceAmountDirectly() { // Arrange - list.add("A", 20); - list.add("B", 6); + list.add(TestResource.A, 20); + list.add(TestResource.B, 6); // Act - final Optional> result2 = list.remove(new ResourceAmount<>( - "A", + final Optional result2 = list.remove(new ResourceAmount( + TestResource.A, 5 )); @@ -167,45 +168,45 @@ void shouldRemoveResourcePartlyWithResourceAmountDirectly() { assertThat(result2).isPresent(); assertThat(result2.get().change()).isEqualTo(-5); assertThat(result2.get().resourceAmount().getAmount()).isEqualTo(15); - assertThat(result2.get().resourceAmount().getResource()).isEqualTo("A"); + assertThat(result2.get().resourceAmount().getResource()).isEqualTo(TestResource.A); assertThat(result2.get().available()).isTrue(); assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 15), - new ResourceAmount<>("B", 6) + new ResourceAmount(TestResource.A, 15), + new ResourceAmount(TestResource.B, 6) ); } @Test void shouldRemoveResourceCompletely() { // Arrange - list.add("A", 20); - list.add("B", 6); + list.add(TestResource.A, 20); + list.add(TestResource.B, 6); // Act - final Optional> result2 = list.remove("A", 20); + final Optional result2 = list.remove(TestResource.A, 20); // Assert assertThat(result2).isPresent(); assertThat(result2.get().change()).isEqualTo(-20); assertThat(result2.get().resourceAmount().getAmount()).isEqualTo(20); - assertThat(result2.get().resourceAmount().getResource()).isEqualTo("A"); + assertThat(result2.get().resourceAmount().getResource()).isEqualTo(TestResource.A); assertThat(result2.get().available()).isFalse(); assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("B", 6) + new ResourceAmount(TestResource.B, 6) ); } @Test void shouldRemoveResourceCompletelyWithResourceAmountDirectly() { // Arrange - list.add("A", 20); - list.add("B", 6); + list.add(TestResource.A, 20); + list.add(TestResource.B, 6); // Act - final Optional> result2 = list.remove(new ResourceAmount<>( - "A", + final Optional result2 = list.remove(new ResourceAmount( + TestResource.A, 20 )); @@ -213,32 +214,32 @@ void shouldRemoveResourceCompletelyWithResourceAmountDirectly() { assertThat(result2).isPresent(); assertThat(result2.get().change()).isEqualTo(-20); assertThat(result2.get().resourceAmount().getAmount()).isEqualTo(20); - assertThat(result2.get().resourceAmount().getResource()).isEqualTo("A"); + assertThat(result2.get().resourceAmount().getResource()).isEqualTo(TestResource.A); assertThat(result2.get().available()).isFalse(); assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("B", 6) + new ResourceAmount(TestResource.B, 6) ); } @Test void shouldNotRemoveResourceWithMoreThanIsAvailable() { // Arrange - list.add("A", 20); - list.add("B", 6); + list.add(TestResource.A, 20); + list.add(TestResource.B, 6); // Act - final Optional> result2 = list.remove("A", 21); + final Optional result2 = list.remove(TestResource.A, 21); // Assert assertThat(result2).isPresent(); assertThat(result2.get().change()).isEqualTo(-20); assertThat(result2.get().resourceAmount().getAmount()).isEqualTo(20); - assertThat(result2.get().resourceAmount().getResource()).isEqualTo("A"); + assertThat(result2.get().resourceAmount().getResource()).isEqualTo(TestResource.A); assertThat(result2.get().available()).isFalse(); assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("B", 6) + new ResourceAmount(TestResource.B, 6) ); } @@ -246,8 +247,8 @@ void shouldNotRemoveResourceWithMoreThanIsAvailable() { @SuppressWarnings("ConstantConditions") void shouldNotRemoveInvalidResourceOrAmount() { // Act - final Executable action1 = () -> list.remove("A", 0); - final Executable action2 = () -> list.remove("A", -1); + final Executable action1 = () -> list.remove(TestResource.A, 0); + final Executable action2 = () -> list.remove(TestResource.A, -1); final Executable action3 = () -> list.remove(null, 1); // Assert @@ -259,40 +260,40 @@ void shouldNotRemoveInvalidResourceOrAmount() { @Test void shouldBeAbleToRetrieveByResourceAfterAdding() { // Arrange - list.add("A", 6); + list.add(TestResource.A, 6); // Act - final Optional> resourceAmount = list.get("A"); + final Optional resourceAmount = list.get(TestResource.A); // Assert assertThat(resourceAmount).isPresent(); - assertThat(resourceAmount.get().getResource()).isEqualTo("A"); + assertThat(resourceAmount.get().getResource()).isEqualTo(TestResource.A); assertThat(resourceAmount.get().getAmount()).isEqualTo(6); } @Test void shouldStillBeAbleToRetrieveByResourceWhenRemovingPartly() { // Arrange - list.add("A", 10); - list.remove("A", 3); + list.add(TestResource.A, 10); + list.remove(TestResource.A, 3); // Act - final Optional> resourceAmount = list.get("A"); + final Optional resourceAmount = list.get(TestResource.A); // Assert assertThat(resourceAmount).isPresent(); - assertThat(resourceAmount.get().getResource()).isEqualTo("A"); + assertThat(resourceAmount.get().getResource()).isEqualTo(TestResource.A); assertThat(resourceAmount.get().getAmount()).isEqualTo(7); } @Test void shouldNotBeAbleToRetrieveByResourceWhenRemovingCompletely() { // Arrange - list.add("A", 10); - list.remove("A", 10); + list.add(TestResource.A, 10); + list.remove(TestResource.A, 10); // Act - final Optional> resourceAmount = list.get("A"); + final Optional resourceAmount = list.get(TestResource.A); // Assert assertThat(resourceAmount).isNotPresent(); @@ -301,16 +302,16 @@ void shouldNotBeAbleToRetrieveByResourceWhenRemovingCompletely() { @Test void shouldClearList() { // Arrange - list.add("A", 10); - list.add("B", 5); + list.add(TestResource.A, 10); + list.add(TestResource.B, 5); - final Collection> contentsBeforeClear = new ArrayList<>(list.getAll()); + final Collection contentsBeforeClear = new ArrayList<>(list.getAll()); // Act list.clear(); // Assert - final Collection> contentsAfterClear = list.getAll(); + final Collection contentsAfterClear = list.getAll(); assertThat(contentsBeforeClear).hasSize(2); assertThat(contentsAfterClear).isEmpty(); diff --git a/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/list/ProxyResourceListTest.java b/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/list/ProxyResourceListTest.java index 15b962f08..527621ddd 100644 --- a/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/list/ProxyResourceListTest.java +++ b/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/list/ProxyResourceListTest.java @@ -2,8 +2,8 @@ class ProxyResourceListTest extends AbstractResourceListTest { @Override - protected ResourceList createList() { - return new AbstractProxyResourceList<>(new ResourceListImpl<>()) { + protected ResourceList createList() { + return new AbstractProxyResourceList(new ResourceListImpl()) { }; } } diff --git a/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/list/ResourceListImplTest.java b/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/list/ResourceListImplTest.java index 6bea6fbe5..fd971ee0d 100644 --- a/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/list/ResourceListImplTest.java +++ b/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/list/ResourceListImplTest.java @@ -2,7 +2,7 @@ class ResourceListImplTest extends AbstractResourceListTest { @Override - protected ResourceList createList() { - return new ResourceListImpl<>(); + protected ResourceList createList() { + return new ResourceListImpl(); } } diff --git a/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/list/listenable/ListenableResourceListTest.java b/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/list/listenable/ListenableResourceListTest.java index c7fc98868..ada286c3a 100644 --- a/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/list/listenable/ListenableResourceListTest.java +++ b/refinedstorage2-resource-api/src/test/java/com/refinedmods/refinedstorage2/api/resource/list/listenable/ListenableResourceListTest.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage2.api.resource.list.listenable; +import com.refinedmods.refinedstorage2.api.resource.TestResource; import com.refinedmods.refinedstorage2.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage2.api.resource.list.ResourceListOperationResult; @@ -13,15 +14,15 @@ import static org.assertj.core.api.Assertions.assertThat; class ListenableResourceListTest { - private FakeResourceListListener listener; - private ResourceListImpl list; - private ListenableResourceList sut; + private FakeResourceListListener listener; + private ResourceListImpl list; + private ListenableResourceList sut; @BeforeEach void setUp() { - listener = new FakeResourceListListener<>(); - list = new ResourceListImpl<>(); - sut = new ListenableResourceList<>(list); + listener = new FakeResourceListListener(); + list = new ResourceListImpl(); + sut = new ListenableResourceList(list); } @Test @@ -30,12 +31,12 @@ void shouldCallListenerWhenAdding() { sut.addListener(listener); // Act - final ResourceListOperationResult result = sut.add("A", 10); + final ResourceListOperationResult result = sut.add(TestResource.A, 10); // Assert assertThat(result.change()).isEqualTo(10); assertThat(result.resourceAmount().getAmount()).isEqualTo(10); - assertThat(result.resourceAmount().getResource()).isEqualTo("A"); + assertThat(result.resourceAmount().getResource()).isEqualTo(TestResource.A); assertThat(result.available()).isTrue(); assertThat(listener.changes).hasSize(1); } @@ -43,12 +44,12 @@ void shouldCallListenerWhenAdding() { @Test void shouldNotCallListenerWhenAddingWithoutListener() { // Act - final ResourceListOperationResult result = sut.add("A", 10); + final ResourceListOperationResult result = sut.add(TestResource.A, 10); // Assert assertThat(result.change()).isEqualTo(10); assertThat(result.resourceAmount().getAmount()).isEqualTo(10); - assertThat(result.resourceAmount().getResource()).isEqualTo("A"); + assertThat(result.resourceAmount().getResource()).isEqualTo(TestResource.A); assertThat(result.available()).isTrue(); assertThat(listener.changes).isEmpty(); } @@ -57,16 +58,16 @@ void shouldNotCallListenerWhenAddingWithoutListener() { void shouldCallListenerWhenRemoving() { // Arrange sut.addListener(listener); - sut.add("A", 10); + sut.add(TestResource.A, 10); // Act - final Optional> result = sut.remove("A", 10); + final Optional result = sut.remove(TestResource.A, 10); // Assert assertThat(result).isPresent(); assertThat(result.get().change()).isEqualTo(-10); assertThat(result.get().resourceAmount().getAmount()).isEqualTo(10); - assertThat(result.get().resourceAmount().getResource()).isEqualTo("A"); + assertThat(result.get().resourceAmount().getResource()).isEqualTo(TestResource.A); assertThat(result.get().available()).isFalse(); assertThat(listener.changes).hasSize(2); } @@ -74,16 +75,16 @@ void shouldCallListenerWhenRemoving() { @Test void shouldNotCallListenerWhenRemovingWithoutListener() { // Arrange - sut.add("A", 10); + sut.add(TestResource.A, 10); // Act - final Optional> result = sut.remove("A", 10); + final Optional result = sut.remove(TestResource.A, 10); // Assert assertThat(result).isPresent(); assertThat(result.get().change()).isEqualTo(-10); assertThat(result.get().resourceAmount().getAmount()).isEqualTo(10); - assertThat(result.get().resourceAmount().getResource()).isEqualTo("A"); + assertThat(result.get().resourceAmount().getResource()).isEqualTo(TestResource.A); assertThat(result.get().available()).isFalse(); assertThat(listener.changes).isEmpty(); } @@ -92,10 +93,10 @@ void shouldNotCallListenerWhenRemovingWithoutListener() { void shouldNotCallListenerWhenRemovingWithoutResult() { // Arrange sut.addListener(listener); - sut.add("A", 10); + sut.add(TestResource.A, 10); // Act - final Optional> result = sut.remove("B", 10); + final Optional result = sut.remove(TestResource.B, 10); // Assert assertThat(result).isEmpty(); @@ -108,7 +109,7 @@ void shouldNotCallListenerWhenModifyingListDirectly() { sut.addListener(listener); // Act - list.add("A", 10); + list.add(TestResource.A, 10); // Assert assertThat(listener.changes).isEmpty(); @@ -118,21 +119,21 @@ void shouldNotCallListenerWhenModifyingListDirectly() { void shouldBeAbleToRemoveListener() { // Arrange sut.addListener(listener); - sut.add("A", 10); + sut.add(TestResource.A, 10); // Act sut.removeListener(listener); - sut.add("A", 10); + sut.add(TestResource.A, 10); // Assert assertThat(listener.changes).hasSize(1); } - private static class FakeResourceListListener implements ResourceListListener { - private final List> changes = new ArrayList<>(); + private static class FakeResourceListListener implements ResourceListListener { + private final List changes = new ArrayList<>(); @Override - public void onChanged(final ResourceListOperationResult change) { + public void onChanged(final ResourceListOperationResult change) { changes.add(change); } } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/AbstractProxyStorage.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/AbstractProxyStorage.java index 50112b5f1..984ee77ea 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/AbstractProxyStorage.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/AbstractProxyStorage.java @@ -3,6 +3,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.core.CoreValidations; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import java.util.Collection; @@ -10,33 +11,31 @@ /** * This is a utility class to easily decorate a {@link Storage}. - * - * @param the type of resource */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") -public abstract class AbstractProxyStorage implements Storage { - protected final Storage delegate; +public abstract class AbstractProxyStorage implements Storage { + protected final Storage delegate; /** * @param delegate the storage to delegate operations to, may not be null */ - protected AbstractProxyStorage(final Storage delegate) { + protected AbstractProxyStorage(final Storage delegate) { CoreValidations.validateNotNull(delegate, "Delegate must not be null"); this.delegate = delegate; } @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return delegate.extract(resource, amount, action, actor); } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return delegate.insert(resource, amount, action, actor); } @Override - public Collection> getAll() { + public Collection getAll() { return delegate.getAll(); } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/ExtractableStorage.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/ExtractableStorage.java index 3aa43a79a..dbde6a734 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/ExtractableStorage.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/ExtractableStorage.java @@ -1,16 +1,15 @@ package com.refinedmods.refinedstorage2.api.storage; import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import org.apiguardian.api.API; /** * Represents a storage that can be extracted from. - * - * @param the type of resource */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") -public interface ExtractableStorage { +public interface ExtractableStorage { /** * Extracts a resource from a storage. * @@ -20,5 +19,5 @@ public interface ExtractableStorage { * @param actor the source * @return the amount extracted */ - long extract(T resource, long amount, Action action, Actor actor); + long extract(ResourceKey resource, long amount, Action action, Actor actor); } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/InMemoryStorageImpl.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/InMemoryStorageImpl.java index 16627aed0..d03e7aa85 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/InMemoryStorageImpl.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/InMemoryStorageImpl.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; import com.refinedmods.refinedstorage2.api.resource.list.ResourceListImpl; @@ -11,16 +12,14 @@ /** * An implementation of a {@link Storage} which has an in-memory resource list as a backing list. - * - * @param the type of resource */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.0") -public class InMemoryStorageImpl implements Storage { - private final ResourceList list = new ResourceListImpl<>(); +public class InMemoryStorageImpl implements Storage { + private final ResourceList list = new ResourceListImpl(); private long stored; @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { ResourceAmount.validate(resource, amount); return list.get(resource).map(resourceAmount -> { @@ -32,7 +31,7 @@ public long extract(final T resource, final long amount, final Action action, fi }).orElse(0L); } - private long doExtract(final T resource, final long amount, final Action action) { + private long doExtract(final ResourceKey resource, final long amount, final Action action) { if (action == Action.EXECUTE) { list.remove(resource, amount); stored -= amount; @@ -41,7 +40,7 @@ private long doExtract(final T resource, final long amount, final Action action) } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { ResourceAmount.validate(resource, amount); if (action == Action.EXECUTE) { stored += amount; @@ -51,7 +50,7 @@ public long insert(final T resource, final long amount, final Action action, fin } @Override - public Collection> getAll() { + public Collection getAll() { return list.getAll(); } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/InsertableStorage.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/InsertableStorage.java index d3f7d00a7..df1519dc8 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/InsertableStorage.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/InsertableStorage.java @@ -1,16 +1,15 @@ package com.refinedmods.refinedstorage2.api.storage; import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import org.apiguardian.api.API; /** * Represents a storage that can be inserted into. - * - * @param the type of resource */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") -public interface InsertableStorage { +public interface InsertableStorage { /** * Inserts a resource into a storage. * @@ -20,5 +19,5 @@ public interface InsertableStorage { * @param actor the source * @return the amount inserted */ - long insert(T resource, long amount, Action action, Actor actor); + long insert(ResourceKey resource, long amount, Action action, Actor actor); } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/NoopStorage.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/NoopStorage.java index 91236852c..b72527b03 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/NoopStorage.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/NoopStorage.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import java.util.Collection; import java.util.Collections; @@ -9,19 +10,19 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.3.3") -public class NoopStorage implements Storage { +public class NoopStorage implements Storage { @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return 0; } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return 0; } @Override - public Collection> getAll() { + public Collection getAll() { return Collections.emptyList(); } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/ResourceTemplate.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/ResourceTemplate.java deleted file mode 100644 index 45cb1e79f..000000000 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/ResourceTemplate.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.refinedmods.refinedstorage2.api.storage; - -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; - -import org.apiguardian.api.API; - -/** - * A resource template adds storage channel information to a resource. - * - * @param resource the resource - * @param storageChannelType the storage channel type - * @param the resource type - */ -@API(status = API.Status.STABLE, since = "2.0.0-milestone.2.13") -public record ResourceTemplate(T resource, StorageChannelType storageChannelType) { -} diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/StateTrackedStorage.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/StateTrackedStorage.java index 4c902eff7..7b4fd4401 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/StateTrackedStorage.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/StateTrackedStorage.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.limited.LimitedStorage; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedStorage; @@ -10,15 +11,15 @@ import java.util.Optional; import javax.annotation.Nullable; -public class StateTrackedStorage implements TrackedStorage { +public class StateTrackedStorage implements TrackedStorage { private static final double NEAR_CAPACITY_THRESHOLD = .75; - private final Storage delegate; + private final Storage delegate; @Nullable private final Listener listener; private StorageState state; - public StateTrackedStorage(final Storage delegate, @Nullable final Listener listener) { + public StateTrackedStorage(final Storage delegate, @Nullable final Listener listener) { this.delegate = delegate; this.listener = listener; this.state = computeState(); @@ -29,7 +30,7 @@ public StorageState getState() { } private StorageState computeState() { - if (delegate instanceof LimitedStorage limitedStorage) { + if (delegate instanceof LimitedStorage limitedStorage) { return computeState(limitedStorage.getCapacity(), delegate.getStored()); } return StorageState.NORMAL; @@ -60,7 +61,7 @@ private void notifyListener() { } @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { final long extracted = delegate.extract(resource, amount, action, actor); if (extracted > 0 && action == Action.EXECUTE) { checkStateChanged(); @@ -69,7 +70,7 @@ public long extract(final T resource, final long amount, final Action action, fi } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { final long inserted = delegate.insert(resource, amount, action, actor); if (inserted > 0 && action == Action.EXECUTE) { checkStateChanged(); @@ -78,7 +79,7 @@ public long insert(final T resource, final long amount, final Action action, fin } @Override - public Collection> getAll() { + public Collection getAll() { return delegate.getAll(); } @@ -88,23 +89,13 @@ public long getStored() { } @Override - public Optional findTrackedResourceByActorType(final T resource, + public Optional findTrackedResourceByActorType(final ResourceKey resource, final Class actorType) { - return delegate instanceof TrackedStorage trackedStorage + return delegate instanceof TrackedStorage trackedStorage ? trackedStorage.findTrackedResourceByActorType(resource, actorType) : Optional.empty(); } - public static TypedStorage> of( - final TypedStorage> delegate, - @Nullable final Listener listener - ) { - return new TypedStorage<>( - new StateTrackedStorage<>(delegate.storage(), listener), - delegate.storageChannelType() - ); - } - @FunctionalInterface public interface Listener { void onStorageStateChanged(); diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/Storage.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/Storage.java index 59273acd2..f561a613b 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/Storage.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/Storage.java @@ -4,9 +4,7 @@ /** * Represents a storage that can be inserted into, extracted and read from. - * - * @param the type of resource */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") -public interface Storage extends StorageView, InsertableStorage, ExtractableStorage { +public interface Storage extends StorageView, InsertableStorage, ExtractableStorage { } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/StorageView.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/StorageView.java index 9f3c01c30..810caed76 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/StorageView.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/StorageView.java @@ -8,15 +8,13 @@ /** * Represents a storage where the contents can be retrieved. - * - * @param the type of resource */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") -public interface StorageView { +public interface StorageView { /** * @return a list of resource amounts */ - Collection> getAll(); + Collection getAll(); /** * @return the amount stored diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/TrackedResourceAmount.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/TrackedResourceAmount.java index 9ceaee775..0aca3dbc5 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/TrackedResourceAmount.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/TrackedResourceAmount.java @@ -8,5 +8,5 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.3.0") -public record TrackedResourceAmount(ResourceAmount resourceAmount, @Nullable TrackedResource trackedResource) { +public record TrackedResourceAmount(ResourceAmount resourceAmount, @Nullable TrackedResource trackedResource) { } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/TransferHelper.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/TransferHelper.java index 6a501a3c0..0cbcf5ad2 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/TransferHelper.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/TransferHelper.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.api.storage; import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import javax.annotation.Nullable; @@ -29,15 +30,14 @@ private TransferHelper() { * @param source the source to extract from * @param destination the destination to insert to * @param fallback the fallback to insert leftovers in - * @param the resource type * @return the amount transferred */ - public static long transfer(final T resource, - final long amount, - final Actor actor, - final ExtractableStorage source, - final InsertableStorage destination, - @Nullable final InsertableStorage fallback) { + public static long transfer(final ResourceKey resource, + final long amount, + final Actor actor, + final ExtractableStorage source, + final InsertableStorage destination, + @Nullable final InsertableStorage fallback) { final long extractedSimulated = source.extract(resource, amount, Action.SIMULATE, actor); if (extractedSimulated == 0) { return 0; @@ -64,10 +64,10 @@ public static long transfer(final T resource, return inserted; } - private static void handleLeftover(final T resource, - final Actor actor, - final InsertableStorage fallback, - final long leftover) { + private static void handleLeftover(final ResourceKey resource, + final Actor actor, + final InsertableStorage fallback, + final long leftover) { final long leftoverInserted = fallback.insert(resource, leftover, Action.EXECUTE, actor); final long leftoverNotInserted = leftover - leftoverInserted; if (leftoverNotInserted > 0) { diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/TypedStorage.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/TypedStorage.java deleted file mode 100644 index 37d6a3be3..000000000 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/TypedStorage.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.refinedmods.refinedstorage2.api.storage; - -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; - -public record TypedStorage>(S storage, StorageChannelType storageChannelType) { -} diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/channel/StorageChannel.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/channel/StorageChannel.java index 82918cc65..29299d15c 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/channel/StorageChannel.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/channel/StorageChannel.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.api.storage.channel; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.resource.list.listenable.ResourceListListener; import com.refinedmods.refinedstorage2.api.storage.Storage; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedStorage; @@ -11,33 +12,31 @@ import org.apiguardian.api.API; /** - * A storage channel is the entry-point for various storage operations for a given resource type. + * A storage channel is the entry-point for various storage operations. * It acts as a storage, and is usually backed by a * {@link com.refinedmods.refinedstorage2.api.storage.composite.CompositeStorage}. - * - * @param the type of resource */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.0") -public interface StorageChannel extends Storage, TrackedStorage { +public interface StorageChannel extends Storage, TrackedStorage { /** * Adds a listener to the storage channel. * * @param listener the listener */ - void addListener(ResourceListListener listener); + void addListener(ResourceListListener listener); /** * Removes a listener from the storage channel. * * @param listener the listener */ - void removeListener(ResourceListListener listener); + void removeListener(ResourceListListener listener); /** * @param resource the resource to retrieve * @return the resource amount for the given resource, if present */ - Optional> get(T resource); + Optional get(ResourceKey resource); /** * Sorts the sources in the backing storage. @@ -49,14 +48,14 @@ public interface StorageChannel extends Storage, TrackedStorage { * * @param source the source */ - void addSource(Storage source); + void addSource(Storage source); /** * Removes a source from the channel. * * @param source the source */ - void removeSource(Storage source); + void removeSource(Storage source); /** * Checks if a source is present. @@ -64,5 +63,5 @@ public interface StorageChannel extends Storage, TrackedStorage { * @param matcher a predicate * @return whether the predicate matched */ - boolean hasSource(Predicate> matcher); + boolean hasSource(Predicate matcher); } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/channel/StorageChannelImpl.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/channel/StorageChannelImpl.java index 464ad2cd3..6639d851d 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/channel/StorageChannelImpl.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/channel/StorageChannelImpl.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; import com.refinedmods.refinedstorage2.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage2.api.resource.list.listenable.ListenableResourceList; @@ -19,17 +20,17 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.0") -public class StorageChannelImpl implements StorageChannel { - private final ListenableResourceList list; - private final CompositeStorage storage; +public class StorageChannelImpl implements StorageChannel { + private final ListenableResourceList list; + private final CompositeStorage storage; public StorageChannelImpl() { - this(new ResourceListImpl<>()); + this(new ResourceListImpl()); } - public StorageChannelImpl(final ResourceList list) { - this.list = new ListenableResourceList<>(list); - this.storage = new CompositeStorageImpl<>(this.list); + public StorageChannelImpl(final ResourceList list) { + this.list = new ListenableResourceList(list); + this.storage = new CompositeStorageImpl(this.list); } @Override @@ -38,47 +39,47 @@ public void sortSources() { } @Override - public void addSource(final Storage source) { + public void addSource(final Storage source) { storage.addSource(source); } @Override - public void removeSource(final Storage source) { + public void removeSource(final Storage source) { storage.removeSource(source); } @Override - public boolean hasSource(final Predicate> matcher) { + public boolean hasSource(final Predicate matcher) { return storage.getSources().stream().anyMatch(matcher); } @Override - public void addListener(final ResourceListListener listener) { + public void addListener(final ResourceListListener listener) { list.addListener(listener); } @Override - public void removeListener(final ResourceListListener listener) { + public void removeListener(final ResourceListListener listener) { list.removeListener(listener); } @Override - public Optional> get(final T resource) { + public Optional get(final ResourceKey resource) { return list.get(resource); } @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return storage.extract(resource, amount, action, actor); } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return storage.insert(resource, amount, action, actor); } @Override - public Collection> getAll() { + public Collection getAll() { return storage.getAll(); } @@ -88,7 +89,7 @@ public long getStored() { } @Override - public Optional findTrackedResourceByActorType(final T resource, + public Optional findTrackedResourceByActorType(final ResourceKey resource, final Class actorType) { return storage.findTrackedResourceByActorType(resource, actorType); } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/channel/StorageChannelType.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/channel/StorageChannelType.java deleted file mode 100644 index 17dce15c1..000000000 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/channel/StorageChannelType.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.refinedmods.refinedstorage2.api.storage.channel; - -import org.apiguardian.api.API; - -@API(status = API.Status.STABLE, since = "2.0.0-milestone.1.0") -@FunctionalInterface -public interface StorageChannelType { - StorageChannel create(); -} diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/CompositeAwareChild.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/CompositeAwareChild.java index dd3940548..9f77de1ef 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/CompositeAwareChild.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/CompositeAwareChild.java @@ -8,22 +8,20 @@ * Implement this on storages that need to be aware of the fact that they are contained in a {@link CompositeStorage}. * Typically, this is needed so that storages that dynamically modify their underlying storage sources, can propagate * the changes to the parent composite list. - * - * @param the type of resource */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.4") -public interface CompositeAwareChild extends Storage { +public interface CompositeAwareChild extends Storage { /** * Called by a {@link CompositeStorage} when this {@link CompositeAwareChild} is added into the composite storage. * * @param parentComposite the composite storage that this {@link CompositeAwareChild} is contained in */ - void onAddedIntoComposite(ParentComposite parentComposite); + void onAddedIntoComposite(ParentComposite parentComposite); /** * Called by a {@link CompositeStorage} when this {@link CompositeAwareChild} is removed from the composite storage. * * @param parentComposite the composite storage that this {@link CompositeAwareChild} is/was contained in */ - void onRemovedFromComposite(ParentComposite parentComposite); + void onRemovedFromComposite(ParentComposite parentComposite); } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/CompositeStorage.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/CompositeStorage.java index a71815c01..63cf41f57 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/CompositeStorage.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/CompositeStorage.java @@ -9,11 +9,9 @@ /** * This represents a single storage that can be backed by multiple storages. - * - * @param the type of resource */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.0") -public interface CompositeStorage extends Storage, TrackedStorage { +public interface CompositeStorage extends Storage, TrackedStorage { /** * Sorts storages that implement {@link Priority}. */ @@ -24,19 +22,19 @@ public interface CompositeStorage extends Storage, TrackedStorage { * * @param source the source */ - void addSource(Storage source); + void addSource(Storage source); /** * Removes a source and resorts them. * * @param source the source */ - void removeSource(Storage source); + void removeSource(Storage source); /** * @return an unmodifiable source list */ - List> getSources(); + List getSources(); /** * Clears all sources. diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/CompositeStorageImpl.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/CompositeStorageImpl.java index 67cb1338d..fb46c3af7 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/CompositeStorageImpl.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/CompositeStorageImpl.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.Storage; @@ -21,19 +22,17 @@ /** * An implementation of {@link CompositeStorage} that can be contained into other {@link CompositeStorage}s. - * - * @param the type of resource */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.0") -public class CompositeStorageImpl implements CompositeStorage, CompositeAwareChild, ParentComposite { - private final List> sources = new ArrayList<>(); - private final ResourceList list; - private final Set> parentComposites = new HashSet<>(); +public class CompositeStorageImpl implements CompositeStorage, CompositeAwareChild, ParentComposite { + private final List sources = new ArrayList<>(); + private final ResourceList list; + private final Set parentComposites = new HashSet<>(); /** * @param list the backing list of this composite storage, used to retrieve a view of the sources */ - public CompositeStorageImpl(final ResourceList list) { + public CompositeStorageImpl(final ResourceList list) { this.list = list; } @@ -43,43 +42,43 @@ public void sortSources() { } @Override - public void addSource(final Storage source) { + public void addSource(final Storage source) { sources.add(source); sortSources(); addContentOfSourceToList(source); parentComposites.forEach(parentComposite -> parentComposite.onSourceAddedToChild(source)); - if (source instanceof CompositeAwareChild compositeAwareChild) { + if (source instanceof CompositeAwareChild compositeAwareChild) { compositeAwareChild.onAddedIntoComposite(this); } } @Override - public void removeSource(final Storage source) { + public void removeSource(final Storage source) { sources.remove(source); // Re-sort isn't necessary, since they are ordered when added. removeContentOfSourceFromList(source); parentComposites.forEach(parentComposite -> parentComposite.onSourceRemovedFromChild(source)); - if (source instanceof CompositeAwareChild compositeAwareChild) { + if (source instanceof CompositeAwareChild compositeAwareChild) { compositeAwareChild.onRemovedFromComposite(this); } } @Override - public List> getSources() { + public List getSources() { return Collections.unmodifiableList(sources); } @Override public void clearSources() { - final Set> oldSources = new HashSet<>(sources); + final Set oldSources = new HashSet<>(sources); oldSources.forEach(this::removeSource); } @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { long remaining = amount; long toRemoveFromList = 0; - for (final Storage source : sources) { + for (final Storage source : sources) { final long extractedFromSource = source.extract(resource, remaining, action, actor); if (!(source instanceof ConsumingStorage)) { toRemoveFromList += extractedFromSource; @@ -97,10 +96,10 @@ public long extract(final T resource, final long amount, final Action action, fi } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { long inserted = 0; long toInsertIntoList = 0; - for (final Storage source : sources) { + for (final Storage source : sources) { final long insertedIntoSource = source.insert(resource, amount - inserted, action, actor); if (!(source instanceof ConsumingStorage)) { toInsertIntoList += insertedIntoSource; @@ -117,7 +116,7 @@ public long insert(final T resource, final long amount, final Action action, fin } @Override - public Collection> getAll() { + public Collection getAll() { return list.getAll(); } @@ -127,51 +126,51 @@ public long getStored() { } @Override - public Optional findTrackedResourceByActorType(final T resource, + public Optional findTrackedResourceByActorType(final ResourceKey resource, final Class actorType) { return sources .stream() .filter(TrackedStorage.class::isInstance) - .map(storage -> (TrackedStorage) storage) + .map(TrackedStorage.class::cast) .flatMap(storage -> storage.findTrackedResourceByActorType(resource, actorType).stream()) .max(Comparator.comparingLong(TrackedResource::getTime)); } @Override - public void onAddedIntoComposite(final ParentComposite parentComposite) { + public void onAddedIntoComposite(final ParentComposite parentComposite) { parentComposites.add(parentComposite); } @Override - public void onRemovedFromComposite(final ParentComposite parentComposite) { + public void onRemovedFromComposite(final ParentComposite parentComposite) { parentComposites.remove(parentComposite); } @Override - public void onSourceAddedToChild(final Storage source) { + public void onSourceAddedToChild(final Storage source) { addContentOfSourceToList(source); } @Override - public void onSourceRemovedFromChild(final Storage source) { + public void onSourceRemovedFromChild(final Storage source) { removeContentOfSourceFromList(source); } @Override - public void addToCache(final T resource, final long amount) { + public void addToCache(final ResourceKey resource, final long amount) { list.add(resource, amount); } @Override - public void removeFromCache(final T resource, final long amount) { + public void removeFromCache(final ResourceKey resource, final long amount) { list.remove(resource, amount); } - private void addContentOfSourceToList(final Storage source) { + private void addContentOfSourceToList(final Storage source) { source.getAll().forEach(list::add); } - private void removeContentOfSourceFromList(final Storage source) { + private void removeContentOfSourceFromList(final Storage source) { source.getAll().forEach(resourceAmount -> list.remove( resourceAmount.getResource(), resourceAmount.getAmount() diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/ConsumingStorage.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/ConsumingStorage.java index d6b8a1ad2..284f9ca7f 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/ConsumingStorage.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/ConsumingStorage.java @@ -8,5 +8,5 @@ * A consuming storage is a storage that won't cause changes to be propagated in the {@link CompositeStorage} cache. */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.4") -public interface ConsumingStorage extends Storage { +public interface ConsumingStorage extends Storage { } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/ParentComposite.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/ParentComposite.java index 481bea8db..2e6847945 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/ParentComposite.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/ParentComposite.java @@ -1,23 +1,22 @@ package com.refinedmods.refinedstorage2.api.storage.composite; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Storage; import org.apiguardian.api.API; /** * Represents the parent storage that a {@link CompositeAwareChild} can use to propagate changes to. - * - * @param the type of resource */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.4") -public interface ParentComposite { +public interface ParentComposite { /** * Called by the {@link CompositeAwareChild} to notify to this parent composite storage * that a source has been added. * * @param source the source */ - void onSourceAddedToChild(Storage source); + void onSourceAddedToChild(Storage source); /** * Called by the {@link CompositeAwareChild} to notify to this parent composite storage @@ -25,7 +24,7 @@ public interface ParentComposite { * * @param source the source */ - void onSourceRemovedFromChild(Storage source); + void onSourceRemovedFromChild(Storage source); /** * Adds a resource to the composite storage cache. @@ -34,7 +33,7 @@ public interface ParentComposite { * @param resource the resource * @param amount the amount */ - void addToCache(T resource, long amount); + void addToCache(ResourceKey resource, long amount); /** * Removes a resource from the composite storage cache. @@ -43,5 +42,5 @@ public interface ParentComposite { * @param resource the resource * @param amount the amount */ - void removeFromCache(T resource, long amount); + void removeFromCache(ResourceKey resource, long amount); } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/PrioritizedStorageComparator.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/PrioritizedStorageComparator.java index 7da1af28c..c5c3bb988 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/PrioritizedStorageComparator.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/composite/PrioritizedStorageComparator.java @@ -4,10 +4,10 @@ import java.util.Comparator; -class PrioritizedStorageComparator implements Comparator> { - static final Comparator> INSTANCE = new PrioritizedStorageComparator(); +class PrioritizedStorageComparator implements Comparator { + static final Comparator INSTANCE = new PrioritizedStorageComparator(); - private static int getPriority(final Storage storage) { + private static int getPriority(final Storage storage) { if (storage instanceof Priority priority) { return priority.getPriority(); } @@ -15,7 +15,7 @@ private static int getPriority(final Storage storage) { } @Override - public int compare(final Storage a, final Storage b) { + public int compare(final Storage a, final Storage b) { return Integer.compare(getPriority(b), getPriority(a)); } } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorage.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorage.java index 7a935be1e..6195eb7fe 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorage.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorage.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.resource.list.ResourceList; import com.refinedmods.refinedstorage2.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage2.api.storage.Actor; @@ -17,23 +18,23 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.4") -public class ExternalStorage implements ConsumingStorage, CompositeAwareChild { - private final ExternalStorageProvider provider; - private final Set> parents = new HashSet<>(); - private final ResourceList cache = new ResourceListImpl<>(); - private final ExternalStorageListener listener; +public class ExternalStorage implements ConsumingStorage, CompositeAwareChild { + private final ExternalStorageProvider provider; + private final Set parents = new HashSet<>(); + private final ResourceList cache = new ResourceListImpl(); + private final ExternalStorageListener listener; - public ExternalStorage(final ExternalStorageProvider provider, final ExternalStorageListener listener) { + public ExternalStorage(final ExternalStorageProvider provider, final ExternalStorageListener listener) { this.provider = provider; this.listener = listener; } - public ExternalStorageProvider getProvider() { + public ExternalStorageProvider getProvider() { return provider; } @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { final long extracted = provider.extract(resource, amount, action, actor); if (action == Action.EXECUTE && extracted > 0) { listener.beforeDetectChanges(resource, actor); @@ -43,7 +44,7 @@ public long extract(final T resource, final long amount, final Action action, fi } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { final long inserted = provider.insert(resource, amount, action, actor); if (action == Action.EXECUTE && inserted > 0) { listener.beforeDetectChanges(resource, actor); @@ -53,16 +54,16 @@ public long insert(final T resource, final long amount, final Action action, fin } public boolean detectChanges() { - final ResourceList updatedCache = buildCache(); + final ResourceList updatedCache = buildCache(); boolean hasChanges = detectCompleteRemovals(updatedCache); hasChanges |= detectAdditionsAndPartialRemovals(updatedCache); return hasChanges; } - private boolean detectCompleteRemovals(final ResourceList updatedCache) { - final Set> removedInUpdatedCache = new HashSet<>(); - for (final ResourceAmount inOldCache : cache.getAll()) { - final Optional> inUpdatedCache = updatedCache.get(inOldCache.getResource()); + private boolean detectCompleteRemovals(final ResourceList updatedCache) { + final Set removedInUpdatedCache = new HashSet<>(); + for (final ResourceAmount inOldCache : cache.getAll()) { + final Optional inUpdatedCache = updatedCache.get(inOldCache.getResource()); if (inUpdatedCache.isEmpty()) { removedInUpdatedCache.add(inOldCache); } @@ -71,10 +72,10 @@ private boolean detectCompleteRemovals(final ResourceList updatedCache) { return !removedInUpdatedCache.isEmpty(); } - private boolean detectAdditionsAndPartialRemovals(final ResourceList updatedCache) { + private boolean detectAdditionsAndPartialRemovals(final ResourceList updatedCache) { boolean hasChanges = false; - for (final ResourceAmount inUpdatedCache : updatedCache.getAll()) { - final Optional> inOldCache = cache.get(inUpdatedCache.getResource()); + for (final ResourceAmount inUpdatedCache : updatedCache.getAll()) { + final Optional inOldCache = cache.get(inUpdatedCache.getResource()); final boolean doesNotExistInOldCache = inOldCache.isEmpty(); if (doesNotExistInOldCache) { addToCache(inUpdatedCache.getResource(), inUpdatedCache.getAmount()); @@ -86,9 +87,9 @@ private boolean detectAdditionsAndPartialRemovals(final ResourceList updatedC return hasChanges; } - private boolean detectPotentialDifference(final ResourceAmount inUpdatedCache, - final ResourceAmount inOldCache) { - final T resource = inUpdatedCache.getResource(); + private boolean detectPotentialDifference(final ResourceAmount inUpdatedCache, + final ResourceAmount inOldCache) { + final ResourceKey resource = inUpdatedCache.getResource(); final long diff = inUpdatedCache.getAmount() - inOldCache.getAmount(); if (diff > 0) { addToCache(resource, diff); @@ -100,24 +101,24 @@ private boolean detectPotentialDifference(final ResourceAmount inUpdatedCache return false; } - private void addToCache(final T resource, final long amount) { + private void addToCache(final ResourceKey resource, final long amount) { cache.add(resource, amount); parents.forEach(parent -> parent.addToCache(resource, amount)); } - private void removeFromCache(final T resource, final long amount) { + private void removeFromCache(final ResourceKey resource, final long amount) { cache.remove(resource, amount); parents.forEach(parent -> parent.removeFromCache(resource, amount)); } - private ResourceList buildCache() { - final ResourceList list = new ResourceListImpl<>(); + private ResourceList buildCache() { + final ResourceList list = new ResourceListImpl(); provider.iterator().forEachRemaining(list::add); return list; } @Override - public Collection> getAll() { + public Collection getAll() { return cache.getAll(); } @@ -127,12 +128,12 @@ public long getStored() { } @Override - public void onAddedIntoComposite(final ParentComposite parentComposite) { + public void onAddedIntoComposite(final ParentComposite parentComposite) { parents.add(parentComposite); } @Override - public void onRemovedFromComposite(final ParentComposite parentComposite) { + public void onRemovedFromComposite(final ParentComposite parentComposite) { parents.remove(parentComposite); } } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorageListener.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorageListener.java index 411b7bd01..3752d38fc 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorageListener.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorageListener.java @@ -1,10 +1,11 @@ package com.refinedmods.refinedstorage2.api.storage.external; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.5") -public interface ExternalStorageListener { - void beforeDetectChanges(T resource, Actor actor); +public interface ExternalStorageListener { + void beforeDetectChanges(ResourceKey resource, Actor actor); } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorageProvider.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorageProvider.java index a5af0f99c..dbd2ff8a1 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorageProvider.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorageProvider.java @@ -9,6 +9,6 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.4") -public interface ExternalStorageProvider extends InsertableStorage, ExtractableStorage { - Iterator> iterator(); +public interface ExternalStorageProvider extends InsertableStorage, ExtractableStorage { + Iterator iterator(); } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/limited/LimitedStorage.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/limited/LimitedStorage.java index 8c60dc195..2463d2aef 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/limited/LimitedStorage.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/limited/LimitedStorage.java @@ -5,6 +5,6 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.4") -public interface LimitedStorage extends Storage { +public interface LimitedStorage extends Storage { long getCapacity(); } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/limited/LimitedStorageImpl.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/limited/LimitedStorageImpl.java index 59b157f1b..340d5ee20 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/limited/LimitedStorageImpl.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/limited/LimitedStorageImpl.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.core.CoreValidations; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.AbstractProxyStorage; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; @@ -12,19 +13,18 @@ /** * This class can decorate any other {@link Storage} to add a capacity to it. - * {@link InsertableStorage#insert(Object, long, Action, Actor)} operations will respect this capacity. - * - * @param the type of resource + * {@link InsertableStorage#insert(com.refinedmods.refinedstorage2.api.resource.ResourceKey, long, Action, Actor)} + * operations will respect this capacity. */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") -public class LimitedStorageImpl extends AbstractProxyStorage implements LimitedStorage { +public class LimitedStorageImpl extends AbstractProxyStorage implements LimitedStorage { private final long capacity; /** * @param delegate the storage that is being decorated * @param capacity the capacity, must be 0 or larger than 0 */ - public LimitedStorageImpl(final Storage delegate, final long capacity) { + public LimitedStorageImpl(final Storage delegate, final long capacity) { super(delegate); this.capacity = CoreValidations.validateNotNegative(capacity, "Capacity cannot be negative"); } @@ -35,11 +35,11 @@ public LimitedStorageImpl(final Storage delegate, final long capacity) { * @param capacity the capacity, must be 0 or larger than 0 */ public LimitedStorageImpl(final long capacity) { - this(new InMemoryStorageImpl<>(), capacity); + this(new InMemoryStorageImpl(), capacity); } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { final long spaceRemaining = capacity - delegate.getStored(); if (spaceRemaining == 0) { return 0; diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/tracked/InMemoryTrackedStorageRepository.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/tracked/InMemoryTrackedStorageRepository.java index 63003c7b2..b9e6712bf 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/tracked/InMemoryTrackedStorageRepository.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/tracked/InMemoryTrackedStorageRepository.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage2.api.storage.tracked; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import java.util.HashMap; @@ -9,12 +10,13 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.4") -public class InMemoryTrackedStorageRepository implements TrackedStorageRepository { - protected final Map, Map> trackedResourcesByActorType = new HashMap<>(); +public class InMemoryTrackedStorageRepository implements TrackedStorageRepository { + protected final Map, Map> trackedResourcesByActorType = + new HashMap<>(); @Override - public void update(final T resource, final Actor actor, final long time) { - final Map resourceMap = trackedResourcesByActorType.computeIfAbsent( + public void update(final ResourceKey resource, final Actor actor, final long time) { + final Map resourceMap = trackedResourcesByActorType.computeIfAbsent( actor.getClass(), k -> new HashMap<>() ); @@ -27,9 +29,9 @@ public void update(final T resource, final Actor actor, final long time) { } @Override - public Optional findTrackedResourceByActorType(final T resource, + public Optional findTrackedResourceByActorType(final ResourceKey resource, final Class actorType) { - final Map resources = trackedResourcesByActorType.get(actorType); + final Map resources = trackedResourcesByActorType.get(actorType); if (resources != null) { return Optional.ofNullable(resources.get(resource)); } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/tracked/TrackedStorage.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/tracked/TrackedStorage.java index 154a8672e..7467bad00 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/tracked/TrackedStorage.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/tracked/TrackedStorage.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage2.api.storage.tracked; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.Storage; @@ -11,7 +12,7 @@ * A storage that is able to track resources being modified. */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.4") -public interface TrackedStorage extends Storage { +public interface TrackedStorage extends Storage { /** * Finds the tracked resource by actor type. * @@ -19,5 +20,5 @@ public interface TrackedStorage extends Storage { * @param actorType the actor type * @return the tracked resource modified by the given actor type, if present */ - Optional findTrackedResourceByActorType(T resource, Class actorType); + Optional findTrackedResourceByActorType(ResourceKey resource, Class actorType); } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/tracked/TrackedStorageImpl.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/tracked/TrackedStorageImpl.java index 7c63fe148..600ccd349 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/tracked/TrackedStorageImpl.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/tracked/TrackedStorageImpl.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.core.CoreValidations; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.AbstractProxyStorage; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.Storage; @@ -12,8 +13,8 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.4") -public class TrackedStorageImpl extends AbstractProxyStorage implements TrackedStorage { - private final TrackedStorageRepository repository; +public class TrackedStorageImpl extends AbstractProxyStorage implements TrackedStorage { + private final TrackedStorageRepository repository; private final LongSupplier clock; /** @@ -22,8 +23,8 @@ public class TrackedStorageImpl extends AbstractProxyStorage implements Tr * @param delegate the storage that is being decorated * @param clock a supplier for unix timestamps */ - public TrackedStorageImpl(final Storage delegate, final LongSupplier clock) { - this(delegate, new InMemoryTrackedStorageRepository<>(), clock); + public TrackedStorageImpl(final Storage delegate, final LongSupplier clock) { + this(delegate, new InMemoryTrackedStorageRepository(), clock); } /** @@ -31,8 +32,8 @@ public TrackedStorageImpl(final Storage delegate, final LongSupplier clock) { * @param repository a repository for persisting and retrieving tracked resources * @param clock a supplier for unix timestamps */ - public TrackedStorageImpl(final Storage delegate, - final TrackedStorageRepository repository, + public TrackedStorageImpl(final Storage delegate, + final TrackedStorageRepository repository, final LongSupplier clock) { super(delegate); this.repository = repository; @@ -40,7 +41,7 @@ public TrackedStorageImpl(final Storage delegate, } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { CoreValidations.validateNotNull(actor, "Source must not be null"); final long inserted = super.insert(resource, amount, action, actor); if (inserted > 0 && action == Action.EXECUTE) { @@ -50,7 +51,7 @@ public long insert(final T resource, final long amount, final Action action, fin } @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { CoreValidations.validateNotNull(actor, "Source must not be null"); final long extracted = super.extract(resource, amount, action, actor); if (extracted > 0 && action == Action.EXECUTE) { @@ -60,7 +61,7 @@ public long extract(final T resource, final long amount, final Action action, fi } @Override - public Optional findTrackedResourceByActorType(final T resource, + public Optional findTrackedResourceByActorType(final ResourceKey resource, final Class actorType) { return repository.findTrackedResourceByActorType(resource, actorType); } diff --git a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/tracked/TrackedStorageRepository.java b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/tracked/TrackedStorageRepository.java index b26359ec0..9f3948b9d 100644 --- a/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/tracked/TrackedStorageRepository.java +++ b/refinedstorage2-storage-api/src/main/java/com/refinedmods/refinedstorage2/api/storage/tracked/TrackedStorageRepository.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage2.api.storage.tracked; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import java.util.Optional; @@ -7,8 +8,8 @@ import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.4") -public interface TrackedStorageRepository { - void update(T resource, Actor actor, long time); +public interface TrackedStorageRepository { + void update(ResourceKey resource, Actor actor, long time); - Optional findTrackedResourceByActorType(T resource, Class actorType); + Optional findTrackedResourceByActorType(ResourceKey resource, Class actorType); } diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/ActorCapturingStorage.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/ActorCapturingStorage.java index d78c137c3..2f57ce190 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/ActorCapturingStorage.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/ActorCapturingStorage.java @@ -1,25 +1,26 @@ package com.refinedmods.refinedstorage2.api.storage; import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import java.util.ArrayList; import java.util.List; -public class ActorCapturingStorage extends AbstractProxyStorage { +public class ActorCapturingStorage extends AbstractProxyStorage { private final List actors = new ArrayList<>(); - public ActorCapturingStorage(final Storage delegate) { + public ActorCapturingStorage(final Storage delegate) { super(delegate); } @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { actors.add(actor); return super.extract(resource, amount, action, actor); } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { actors.add(actor); return super.insert(resource, amount, action, actor); } diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/InMemoryStorageImplTest.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/InMemoryStorageImplTest.java index d3323316a..7103ad9a9 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/InMemoryStorageImplTest.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/InMemoryStorageImplTest.java @@ -12,20 +12,20 @@ import static org.junit.jupiter.api.Assertions.assertThrows; class InMemoryStorageImplTest { - private final Storage sut = new InMemoryStorageImpl<>(); + private final Storage sut = new InMemoryStorageImpl(); @ParameterizedTest @EnumSource(Action.class) void shouldInsertResource(final Action action) { // Act - final long inserted = sut.insert("A", 64, action, EmptyActor.INSTANCE); + final long inserted = sut.insert(TestResource.A, 64, action, EmptyActor.INSTANCE); // Assert assertThat(inserted).isEqualTo(64); if (action == Action.EXECUTE) { assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 64) + new ResourceAmount(TestResource.A, 64) ); assertThat(sut.getStored()).isEqualTo(64); } else { @@ -38,8 +38,8 @@ void shouldInsertResource(final Action action) { @SuppressWarnings("ConstantConditions") void shouldNotInsertInvalidResourceOrAmount() { // Act - final Executable action1 = () -> sut.insert("A", 0, Action.EXECUTE, EmptyActor.INSTANCE); - final Executable action2 = () -> sut.insert("A", -1, Action.EXECUTE, EmptyActor.INSTANCE); + final Executable action1 = () -> sut.insert(TestResource.A, 0, Action.EXECUTE, EmptyActor.INSTANCE); + final Executable action2 = () -> sut.insert(TestResource.A, -1, Action.EXECUTE, EmptyActor.INSTANCE); final Executable action3 = () -> sut.insert(null, 1, Action.EXECUTE, EmptyActor.INSTANCE); // Assert @@ -51,7 +51,7 @@ void shouldNotInsertInvalidResourceOrAmount() { @Test void shouldNotExtractNonexistentResource() { // Act - final long extracted = sut.extract("A", 1, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = sut.extract(TestResource.A, 1, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(extracted).isZero(); @@ -62,22 +62,22 @@ void shouldNotExtractNonexistentResource() { @EnumSource(Action.class) void shouldExtractResourcePartly(final Action action) { // Arrange - sut.insert("A", 32, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(TestResource.A, 32, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final long extracted = sut.extract("A", 2, action, EmptyActor.INSTANCE); + final long extracted = sut.extract(TestResource.A, 2, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(2); if (action == Action.EXECUTE) { assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 30) + new ResourceAmount(TestResource.A, 30) ); assertThat(sut.getStored()).isEqualTo(30); } else { assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 32) + new ResourceAmount(TestResource.A, 32) ); assertThat(sut.getStored()).isEqualTo(32); } @@ -87,10 +87,10 @@ void shouldExtractResourcePartly(final Action action) { @EnumSource(Action.class) void shouldExtractResourceCompletely(final Action action) { // Arrange - sut.insert("A", 32, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(TestResource.A, 32, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final long extracted = sut.extract("A", 32, action, EmptyActor.INSTANCE); + final long extracted = sut.extract(TestResource.A, 32, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(32); @@ -100,7 +100,7 @@ void shouldExtractResourceCompletely(final Action action) { assertThat(sut.getStored()).isZero(); } else { assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 32) + new ResourceAmount(TestResource.A, 32) ); assertThat(sut.getStored()).isEqualTo(32); } @@ -110,10 +110,10 @@ void shouldExtractResourceCompletely(final Action action) { @EnumSource(Action.class) void shouldNotExtractMoreThanIsAvailable(final Action action) { // Arrange - sut.insert("A", 32, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(TestResource.A, 32, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final long extracted = sut.extract("A", 33, action, EmptyActor.INSTANCE); + final long extracted = sut.extract(TestResource.A, 33, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(32); @@ -123,7 +123,7 @@ void shouldNotExtractMoreThanIsAvailable(final Action action) { assertThat(sut.getStored()).isZero(); } else { assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 32) + new ResourceAmount(TestResource.A, 32) ); assertThat(sut.getStored()).isEqualTo(32); } @@ -133,8 +133,8 @@ void shouldNotExtractMoreThanIsAvailable(final Action action) { @Test void shouldNotExtractInvalidResourceOrAmount() { // Act - final Executable action1 = () -> sut.extract("A", 0, Action.EXECUTE, EmptyActor.INSTANCE); - final Executable action2 = () -> sut.extract("A", -1, Action.EXECUTE, EmptyActor.INSTANCE); + final Executable action1 = () -> sut.extract(TestResource.A, 0, Action.EXECUTE, EmptyActor.INSTANCE); + final Executable action2 = () -> sut.extract(TestResource.A, -1, Action.EXECUTE, EmptyActor.INSTANCE); final Executable action3 = () -> sut.extract(null, 1, Action.EXECUTE, EmptyActor.INSTANCE); // Assert diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/LimitedStorageImplTest.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/LimitedStorageImplTest.java index a68828971..15463034e 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/LimitedStorageImplTest.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/LimitedStorageImplTest.java @@ -14,29 +14,29 @@ import static org.junit.jupiter.api.Assertions.assertThrows; class LimitedStorageImplTest { - private ActorCapturingStorage backed; - private LimitedStorageImpl sut; + private ActorCapturingStorage backed; + private LimitedStorageImpl sut; private final Actor actor = () -> "Custom"; @BeforeEach void setUp() { - backed = new ActorCapturingStorage<>(new InMemoryStorageImpl<>()); - sut = new LimitedStorageImpl<>(backed, 100); + backed = new ActorCapturingStorage(new InMemoryStorageImpl()); + sut = new LimitedStorageImpl(backed, 100); } @Test void testNegativeCapacity() { // Act & assert - assertThrows(IllegalArgumentException.class, () -> new LimitedStorageImpl<>(backed, -1)); + assertThrows(IllegalArgumentException.class, () -> new LimitedStorageImpl(backed, -1)); } @Test void testZeroCapacity() { // Arrange - sut = new LimitedStorageImpl<>(backed, 0); + sut = new LimitedStorageImpl(backed, 0); // Act - final long inserted = sut.insert("A", 1, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted = sut.insert(TestResource.A, 1, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted).isZero(); @@ -47,14 +47,14 @@ void testZeroCapacity() { @EnumSource(Action.class) void shouldInsertResourceCompletely(final Action action) { // Act - final long inserted = sut.insert("A", 100, action, actor); + final long inserted = sut.insert(TestResource.A, 100, action, actor); // Assert assertThat(inserted).isEqualTo(100); if (action == Action.EXECUTE) { assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 100) + new ResourceAmount(TestResource.A, 100) ); assertThat(sut.getStored()).isEqualTo(100); } else { @@ -69,8 +69,8 @@ void shouldInsertResourceCompletely(final Action action) { @EnumSource(Action.class) void shouldInsertResourcePartly(final Action action) { // Act - final long inserted1 = sut.insert("A", 60, Action.EXECUTE, actor); - final long inserted2 = sut.insert("B", 45, action, actor); + final long inserted1 = sut.insert(TestResource.A, 60, Action.EXECUTE, actor); + final long inserted2 = sut.insert(TestResource.B, 45, action, actor); // Assert assertThat(inserted1).isEqualTo(60); @@ -78,13 +78,13 @@ void shouldInsertResourcePartly(final Action action) { if (action == Action.EXECUTE) { assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 60), - new ResourceAmount<>("B", 40) + new ResourceAmount(TestResource.A, 60), + new ResourceAmount(TestResource.B, 40) ); assertThat(sut.getStored()).isEqualTo(100); } else { assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 60) + new ResourceAmount(TestResource.A, 60) ); assertThat(sut.getStored()).isEqualTo(60); } @@ -96,8 +96,8 @@ void shouldInsertResourcePartly(final Action action) { @EnumSource(Action.class) void shouldNotInsertResourceWhenStorageAlreadyReachedCapacity(final Action action) { // Act - final long inserted1 = sut.insert("A", 100, Action.EXECUTE, actor); - final long inserted2 = sut.insert("A", 101, action, actor); + final long inserted1 = sut.insert(TestResource.A, 100, Action.EXECUTE, actor); + final long inserted2 = sut.insert(TestResource.A, 101, action, actor); // Assert assertThat(inserted1).isEqualTo(100); @@ -113,8 +113,8 @@ void shouldNotInsertResourceWhenStorageAlreadyReachedCapacity(final Action actio @SuppressWarnings("ConstantConditions") void shouldNotInsertInvalidResourceOrAmount(final Action action) { // Act - final Executable action1 = () -> sut.insert("A", 0, action, EmptyActor.INSTANCE); - final Executable action2 = () -> sut.insert("A", -1, action, EmptyActor.INSTANCE); + final Executable action1 = () -> sut.insert(TestResource.A, 0, action, EmptyActor.INSTANCE); + final Executable action2 = () -> sut.insert(TestResource.A, -1, action, EmptyActor.INSTANCE); final Executable action3 = () -> sut.insert(null, 1, action, EmptyActor.INSTANCE); // Assert @@ -126,10 +126,10 @@ void shouldNotInsertInvalidResourceOrAmount(final Action action) { @Test void shouldExtractResource() { // Arrange - sut.insert("A", 100, Action.EXECUTE, actor); + sut.insert(TestResource.A, 100, Action.EXECUTE, actor); // Act - final long extracted = sut.extract("A", 101, Action.EXECUTE, actor); + final long extracted = sut.extract(TestResource.A, 101, Action.EXECUTE, actor); // Assert assertThat(extracted).isEqualTo(100); diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/ProxyStorageTest.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/ProxyStorageTest.java index e05808589..347df9139 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/ProxyStorageTest.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/ProxyStorageTest.java @@ -12,14 +12,14 @@ import static org.junit.jupiter.api.Assertions.assertThrows; class ProxyStorageTest { - private ActorCapturingStorage backed; - private AbstractProxyStorage sut; + private ActorCapturingStorage backed; + private AbstractProxyStorage sut; private final Actor actor = () -> "Custom source"; @BeforeEach void setUp() { - backed = new ActorCapturingStorage<>(new InMemoryStorageImpl<>()); - sut = new AbstractProxyStorage<>(backed) { + backed = new ActorCapturingStorage(new InMemoryStorageImpl()); + sut = new AbstractProxyStorage(backed) { }; } @@ -27,25 +27,25 @@ void setUp() { @SuppressWarnings("ConstantConditions") void testInvalidParent() { // Act & assert - assertThrows(NullPointerException.class, () -> new AbstractProxyStorage(null) { + assertThrows(NullPointerException.class, () -> new AbstractProxyStorage(null) { }); } @Test void shouldRetrieveAll() { // Arrange - sut.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(TestResource.A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Act & assert assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(TestResource.A, 10) ); } @Test void shouldRetrieveStoredAmount() { // Arrange - sut.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(TestResource.A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Act & assert assertThat(sut.getStored()).isEqualTo(10); @@ -55,12 +55,12 @@ void shouldRetrieveStoredAmount() { @EnumSource(Action.class) void shouldInsert(final Action action) { // Act - sut.insert("A", 10, action, actor); + sut.insert(TestResource.A, 10, action, actor); // Assert if (action == Action.EXECUTE) { assertThat(backed.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(TestResource.A, 10) ); } else { assertThat(backed.getAll()).isEmpty(); @@ -72,20 +72,20 @@ void shouldInsert(final Action action) { @EnumSource(Action.class) void shouldExtract(final Action action) { // Arrange - backed.insert("A", 10, Action.EXECUTE, actor); + backed.insert(TestResource.A, 10, Action.EXECUTE, actor); // Act - final long extracted = sut.extract("A", 3, action, actor); + final long extracted = sut.extract(TestResource.A, 3, action, actor); // Assert assertThat(extracted).isEqualTo(3); if (action == Action.EXECUTE) { assertThat(backed.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 7) + new ResourceAmount(TestResource.A, 7) ); } else { assertThat(backed.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(TestResource.A, 10) ); } assertThat(backed.getActors()).containsExactly(actor, actor); diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/StateTrackedStorageTest.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/StateTrackedStorageTest.java index 4815bcc67..594b42135 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/StateTrackedStorageTest.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/StateTrackedStorageTest.java @@ -26,9 +26,9 @@ class StateTrackedStorageTest { void testStates(final long amount, final StorageState expectedState) { // Arrange final StateTrackedStorage.Listener listener = mock(StateTrackedStorage.Listener.class); - final Storage underlyingStorage = new LimitedStorageImpl<>(100); - underlyingStorage.insert("A", amount, Action.EXECUTE, EmptyActor.INSTANCE); - final StateTrackedStorage sut = new StateTrackedStorage<>(underlyingStorage, listener); + final Storage underlyingStorage = new LimitedStorageImpl(100); + underlyingStorage.insert(TestResource.A, amount, Action.EXECUTE, EmptyActor.INSTANCE); + final StateTrackedStorage sut = new StateTrackedStorage(underlyingStorage, listener); // Act final StorageState state = sut.getState(); @@ -51,9 +51,9 @@ private static Stream states() { void shouldSetInitialState() { // Arrange final StateTrackedStorage.Listener listener = mock(StateTrackedStorage.Listener.class); - final Storage underlyingStorage = new InMemoryStorageImpl<>(); - underlyingStorage.insert("A", 75, Action.EXECUTE, EmptyActor.INSTANCE); - final StateTrackedStorage sut = new StateTrackedStorage<>(underlyingStorage, listener); + final Storage underlyingStorage = new InMemoryStorageImpl(); + underlyingStorage.insert(TestResource.A, 75, Action.EXECUTE, EmptyActor.INSTANCE); + final StateTrackedStorage sut = new StateTrackedStorage(underlyingStorage, listener); // Act final StorageState state = sut.getState(); @@ -62,7 +62,7 @@ void shouldSetInitialState() { verify(listener, never()).onStorageStateChanged(); assertThat(state).isEqualTo(StorageState.NORMAL); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 75) + new ResourceAmount(TestResource.A, 75) ); assertThat(sut.getStored()).isEqualTo(75); } @@ -72,9 +72,9 @@ void shouldSetInitialState() { void shouldSetInitialStateForLimitedStorage() { // Arrange final StateTrackedStorage.Listener listener = mock(StateTrackedStorage.Listener.class); - final Storage underlyingStorage = new LimitedStorageImpl<>(100); - underlyingStorage.insert("A", 75, Action.EXECUTE, EmptyActor.INSTANCE); - final StateTrackedStorage sut = new StateTrackedStorage<>(underlyingStorage, listener); + final Storage underlyingStorage = new LimitedStorageImpl(100); + underlyingStorage.insert(TestResource.A, 75, Action.EXECUTE, EmptyActor.INSTANCE); + final StateTrackedStorage sut = new StateTrackedStorage(underlyingStorage, listener); // Act final StorageState state = sut.getState(); @@ -87,17 +87,17 @@ void shouldSetInitialStateForLimitedStorage() { @Test void shouldUseStorageTracking() { // Arrange - final Storage underlyingStorage = new TrackedStorageImpl<>( - new LimitedStorageImpl<>(100), + final Storage underlyingStorage = new TrackedStorageImpl( + new LimitedStorageImpl(100), () -> 0L ); - final StateTrackedStorage sut = new StateTrackedStorage<>(underlyingStorage, null); + final StateTrackedStorage sut = new StateTrackedStorage(underlyingStorage, null); // Act - sut.insert("A", 75, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(TestResource.A, 75, Action.EXECUTE, EmptyActor.INSTANCE); // Assert - assertThat(sut.findTrackedResourceByActorType("A", EmptyActor.class)).isNotEmpty(); + assertThat(sut.findTrackedResourceByActorType(TestResource.A, EmptyActor.class)).isNotEmpty(); } @ParameterizedTest @@ -105,19 +105,19 @@ void shouldUseStorageTracking() { void shouldCallStateChangeListenerWhenExtracting(final Action action) { // Arrange final StateTrackedStorage.Listener listener = mock(StateTrackedStorage.Listener.class); - final Storage underlyingStorage = new LimitedStorageImpl<>(100); - underlyingStorage.insert("A", 75, Action.EXECUTE, EmptyActor.INSTANCE); - final StateTrackedStorage sut = new StateTrackedStorage<>(underlyingStorage, listener); + final Storage underlyingStorage = new LimitedStorageImpl(100); + underlyingStorage.insert(TestResource.A, 75, Action.EXECUTE, EmptyActor.INSTANCE); + final StateTrackedStorage sut = new StateTrackedStorage(underlyingStorage, listener); // Act - final long extracted = sut.extract("A", 1, action, EmptyActor.INSTANCE); - sut.extract("A", 1, action, EmptyActor.INSTANCE); + final long extracted = sut.extract(TestResource.A, 1, action, EmptyActor.INSTANCE); + sut.extract(TestResource.A, 1, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(1); final VerificationMode expectedTimes = action == Action.EXECUTE ? times(1) : never(); verify(listener, expectedTimes).onStorageStateChanged(); - assertThat(sut.findTrackedResourceByActorType("A", EmptyActor.class)).isEmpty(); + assertThat(sut.findTrackedResourceByActorType(TestResource.A, EmptyActor.class)).isEmpty(); } @ParameterizedTest @@ -125,13 +125,13 @@ void shouldCallStateChangeListenerWhenExtracting(final Action action) { void shouldCallStateChangeListenerWhenInserting(final Action action) { // Arrange final StateTrackedStorage.Listener listener = mock(StateTrackedStorage.Listener.class); - final Storage underlyingStorage = new LimitedStorageImpl<>(100); - underlyingStorage.insert("A", 74, Action.EXECUTE, EmptyActor.INSTANCE); - final StateTrackedStorage sut = new StateTrackedStorage<>(underlyingStorage, listener); + final Storage underlyingStorage = new LimitedStorageImpl(100); + underlyingStorage.insert(TestResource.A, 74, Action.EXECUTE, EmptyActor.INSTANCE); + final StateTrackedStorage sut = new StateTrackedStorage(underlyingStorage, listener); // Act - final long inserted = sut.insert("A", 1, action, EmptyActor.INSTANCE); - sut.insert("A", 1, action, EmptyActor.INSTANCE); + final long inserted = sut.insert(TestResource.A, 1, action, EmptyActor.INSTANCE); + sut.insert(TestResource.A, 1, action, EmptyActor.INSTANCE); // Assert assertThat(inserted).isEqualTo(1); @@ -144,12 +144,12 @@ void shouldCallStateChangeListenerWhenInserting(final Action action) { void shouldNotCallStateChangeListenerWhenUnnecessaryOnExtracting(final Action action) { // Arrange final StateTrackedStorage.Listener listener = mock(StateTrackedStorage.Listener.class); - final Storage underlyingStorage = new LimitedStorageImpl<>(100); - underlyingStorage.insert("A", 76, Action.EXECUTE, EmptyActor.INSTANCE); - final StateTrackedStorage sut = new StateTrackedStorage<>(underlyingStorage, listener); + final Storage underlyingStorage = new LimitedStorageImpl(100); + underlyingStorage.insert(TestResource.A, 76, Action.EXECUTE, EmptyActor.INSTANCE); + final StateTrackedStorage sut = new StateTrackedStorage(underlyingStorage, listener); // Act - sut.extract("A", 1, action, EmptyActor.INSTANCE); + sut.extract(TestResource.A, 1, action, EmptyActor.INSTANCE); // Assert verify(listener, never()).onStorageStateChanged(); @@ -160,11 +160,11 @@ void shouldNotCallStateChangeListenerWhenUnnecessaryOnExtracting(final Action ac void shouldNotCallStateChangeListenerWhenUnnecessaryOnInserting(final Action action) { // Arrange final StateTrackedStorage.Listener listener = mock(StateTrackedStorage.Listener.class); - final Storage underlyingStorage = new LimitedStorageImpl<>(100); - final StateTrackedStorage sut = new StateTrackedStorage<>(underlyingStorage, listener); + final Storage underlyingStorage = new LimitedStorageImpl(100); + final StateTrackedStorage sut = new StateTrackedStorage(underlyingStorage, listener); // Act - sut.insert("A", 74, action, EmptyActor.INSTANCE); + sut.insert(TestResource.A, 74, action, EmptyActor.INSTANCE); // Assert verify(listener, never()).onStorageStateChanged(); diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/TestResource.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/TestResource.java new file mode 100644 index 000000000..8b36a05e5 --- /dev/null +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/TestResource.java @@ -0,0 +1,9 @@ +package com.refinedmods.refinedstorage2.api.storage; + +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; + +public enum TestResource implements ResourceKey { + A, + B, + C +} diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/TransferHelperTest.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/TransferHelperTest.java index 1dd7c763d..88ac349e0 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/TransferHelperTest.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/TransferHelperTest.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.limited.LimitedStorageImpl; import java.util.Objects; @@ -14,6 +15,7 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import static com.refinedmods.refinedstorage2.api.storage.TestResource.A; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Named.named; @@ -22,43 +24,43 @@ class TransferHelperTest { static Stream provideTransfers() { return Stream.of( Arguments.of(named("partly, space in destination", TransferBuilder.create() - .amountInSource("A", 100) - .amountToTransfer("A", 1) + .amountInSource(A, 100) + .amountToTransfer(A, 1) .amountExpectedToBeTransferred(1) - .amountExpectedAfterTransferInSource("A", 99) - .amountExpectedAfterTransferInDestination("A", 1) + .amountExpectedAfterTransferInSource(A, 99) + .amountExpectedAfterTransferInDestination(A, 1) .build())), Arguments.of(named("completely, space in destination", TransferBuilder.create() - .amountInSource("A", 100) - .amountToTransfer("A", 100) + .amountInSource(A, 100) + .amountToTransfer(A, 100) .amountExpectedToBeTransferred(100) - .amountExpectedAfterTransferInDestination("A", 100) + .amountExpectedAfterTransferInDestination(A, 100) .build())), Arguments.of(named("more than is available, space in destination", TransferBuilder.create() - .amountInSource("A", 10) - .amountToTransfer("A", 11) + .amountInSource(A, 10) + .amountToTransfer(A, 11) .amountExpectedToBeTransferred(10) - .amountExpectedAfterTransferInDestination("A", 10) + .amountExpectedAfterTransferInDestination(A, 10) .build())), Arguments.of(named("resource not existing in source", TransferBuilder.create() - .amountToTransfer("A", 1) + .amountToTransfer(A, 1) .amountExpectedToBeTransferred(0) .build())), Arguments.of(named("with remainder, space in destination", TransferBuilder.create() - .amountInSource("A", 50) - .amountInDestination("A", 51) - .amountToTransfer("A", 50) + .amountInSource(A, 50) + .amountInDestination(A, 51) + .amountToTransfer(A, 50) .amountExpectedToBeTransferred(49) - .amountExpectedAfterTransferInSource("A", 1) - .amountExpectedAfterTransferInDestination("A", 100) + .amountExpectedAfterTransferInSource(A, 1) + .amountExpectedAfterTransferInDestination(A, 100) .build())), Arguments.of(named("with remainder, no space in destination", TransferBuilder.create() - .amountInSource("A", 50) - .amountInDestination("A", 100) - .amountToTransfer("A", 50) + .amountInSource(A, 50) + .amountInDestination(A, 100) + .amountToTransfer(A, 50) .amountExpectedToBeTransferred(0) - .amountExpectedAfterTransferInSource("A", 50) - .amountExpectedAfterTransferInDestination("A", 100) + .amountExpectedAfterTransferInSource(A, 50) + .amountExpectedAfterTransferInDestination(A, 100) .build())) ); } @@ -67,8 +69,8 @@ static Stream provideTransfers() { @MethodSource("provideTransfers") void shouldTransferCorrectly(final Transfer transfer) { // Arrange - final Storage source = new LimitedStorageImpl<>(100); - final Storage destination = new LimitedStorageImpl<>(100); + final Storage source = new LimitedStorageImpl(100); + final Storage destination = new LimitedStorageImpl(100); if (transfer.amountInSource != null) { source.insert( @@ -119,26 +121,26 @@ void shouldTransferCorrectly(final Transfer transfer) { @Test void shouldNotTransferWhenEventualExecutedExtractFromSourceFailed() { // Arrange - final Storage source = new LimitedStorageImpl<>(100) { + final Storage source = new LimitedStorageImpl(100) { @Override - public long extract(final String resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { if (action == Action.EXECUTE) { return 0L; } return super.extract(resource, amount, action, actor); } }; - final Storage destination = new LimitedStorageImpl<>(100); + final Storage destination = new LimitedStorageImpl(100); - source.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); + source.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final long transferred = TransferHelper.transfer("A", 50, EmptyActor.INSTANCE, source, destination, null); + final long transferred = TransferHelper.transfer(A, 50, EmptyActor.INSTANCE, source, destination, null); // Assert assertThat(transferred).isZero(); assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 100) + new ResourceAmount(A, 100) ); assertThat(destination.getAll()).isEmpty(); } @@ -146,10 +148,10 @@ public long extract(final String resource, final long amount, final Action actio @Test void shouldThrowExceptionWhenEventualExecutedInsertToDestinationFailed() { // Arrange - final Storage source = new LimitedStorageImpl<>(100); - final Storage destination = new LimitedStorageImpl<>(100) { + final Storage source = new LimitedStorageImpl(100); + final Storage destination = new LimitedStorageImpl(100) { @Override - public long insert(final String resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { if (action == Action.EXECUTE) { return 0L; } @@ -157,22 +159,22 @@ public long insert(final String resource, final long amount, final Action action } }; - source.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); + source.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); // Act & assert assertThrows( IllegalStateException.class, - () -> TransferHelper.transfer("A", 50, EmptyActor.INSTANCE, source, destination, null) + () -> TransferHelper.transfer(A, 50, EmptyActor.INSTANCE, source, destination, null) ); } @Test void shouldRefundLeftoversToFallbackWhenEventualExecutedInsertToDestinationFailed() { // Arrange - final Storage source = new LimitedStorageImpl<>(100); - final Storage destination = new LimitedStorageImpl<>(100) { + final Storage source = new LimitedStorageImpl(100); + final Storage destination = new LimitedStorageImpl(100) { @Override - public long insert(final String resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { if (action == Action.EXECUTE) { return super.insert(resource, Math.min(amount, 25), action, actor); } @@ -180,27 +182,27 @@ public long insert(final String resource, final long amount, final Action action } }; - source.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); + source.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); // Act - TransferHelper.transfer("A", 50, EmptyActor.INSTANCE, source, destination, source); + TransferHelper.transfer(A, 50, EmptyActor.INSTANCE, source, destination, source); // Assert assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 75) + new ResourceAmount(A, 75) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 25) + new ResourceAmount(A, 25) ); } @Test void shouldRefundLeftoversToFallbackWhenEventualExecutedInsertToDestinationFailedEvenIfFallbackDoesNotAcceptAll() { // Arrange - final InMemoryStorageImpl underlyingSource = new InMemoryStorageImpl<>(); - final Storage source = new LimitedStorageImpl<>(underlyingSource, 100) { + final InMemoryStorageImpl underlyingSource = new InMemoryStorageImpl(); + final Storage source = new LimitedStorageImpl(underlyingSource, 100) { @Override - public long insert(final String resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { if (action == Action.EXECUTE) { // we'll try to reinsert 25, but only accept 10. return super.insert(resource, Math.min(amount, 10), action, actor); @@ -208,9 +210,9 @@ public long insert(final String resource, final long amount, final Action action return super.insert(resource, amount, action, actor); } }; - final Storage destination = new LimitedStorageImpl<>(100) { + final Storage destination = new LimitedStorageImpl(100) { @Override - public long insert(final String resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { if (action == Action.EXECUTE) { return super.insert(resource, Math.min(amount, 25), action, actor); } @@ -218,17 +220,17 @@ public long insert(final String resource, final long amount, final Action action } }; - underlyingSource.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); + underlyingSource.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); // Act - TransferHelper.transfer("A", 50, EmptyActor.INSTANCE, source, destination, source); + TransferHelper.transfer(A, 50, EmptyActor.INSTANCE, source, destination, source); // Assert assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 60) + new ResourceAmount(A, 60) ); assertThat(destination.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 25) + new ResourceAmount(A, 25) ); } @@ -236,12 +238,12 @@ public long insert(final String resource, final long amount, final Action action @SuppressWarnings("ConstantConditions") void shouldNotTransferInvalidAmount() { // Arrange - final Storage source = new LimitedStorageImpl<>(100); - final Storage destination = new LimitedStorageImpl<>(100); + final Storage source = new LimitedStorageImpl(100); + final Storage destination = new LimitedStorageImpl(100); // Act final Executable action1 = () -> TransferHelper.transfer( - "A", + A, 0, EmptyActor.INSTANCE, source, @@ -249,7 +251,7 @@ void shouldNotTransferInvalidAmount() { null ); final Executable action2 = () -> TransferHelper.transfer( - "A", + A, -1, EmptyActor.INSTANCE, source, @@ -271,26 +273,26 @@ void shouldNotTransferInvalidAmount() { assertThrows(NullPointerException.class, action3); } - record Transfer(@Nullable ResourceAmount amountInSource, - @Nullable ResourceAmount amountInDestination, - ResourceAmount amountToTransfer, + record Transfer(@Nullable ResourceAmount amountInSource, + @Nullable ResourceAmount amountInDestination, + ResourceAmount amountToTransfer, long amountExpectedToBeTransferred, - @Nullable ResourceAmount amountExpectedAfterTransferInSource, - @Nullable ResourceAmount amountExpectedAfterTransferInDestination) { + @Nullable ResourceAmount amountExpectedAfterTransferInSource, + @Nullable ResourceAmount amountExpectedAfterTransferInDestination) { } public static class TransferBuilder { @Nullable - private ResourceAmount amountInSource; + private ResourceAmount amountInSource; @Nullable - private ResourceAmount amountInDestination; + private ResourceAmount amountInDestination; @Nullable - private ResourceAmount amountToTransfer; + private ResourceAmount amountToTransfer; private long amountExpectedToBeTransferred; @Nullable - private ResourceAmount amountExpectedAfterTransferInSource; + private ResourceAmount amountExpectedAfterTransferInSource; @Nullable - private ResourceAmount amountExpectedAfterTransferInDestination; + private ResourceAmount amountExpectedAfterTransferInDestination; private TransferBuilder() { } @@ -299,28 +301,28 @@ public static TransferBuilder create() { return new TransferBuilder(); } - public TransferBuilder amountInSource(final String resource, final long amount) { - this.amountInSource = new ResourceAmount<>(resource, amount); + public TransferBuilder amountInSource(final ResourceKey resource, final long amount) { + this.amountInSource = new ResourceAmount(resource, amount); return this; } - public TransferBuilder amountInDestination(final String resource, final long amount) { - this.amountInDestination = new ResourceAmount<>(resource, amount); + public TransferBuilder amountInDestination(final ResourceKey resource, final long amount) { + this.amountInDestination = new ResourceAmount(resource, amount); return this; } - public TransferBuilder amountToTransfer(final String resource, final long amount) { - this.amountToTransfer = new ResourceAmount<>(resource, amount); + public TransferBuilder amountToTransfer(final ResourceKey resource, final long amount) { + this.amountToTransfer = new ResourceAmount(resource, amount); return this; } - public TransferBuilder amountExpectedAfterTransferInSource(final String resource, final long amount) { - this.amountExpectedAfterTransferInSource = new ResourceAmount<>(resource, amount); + public TransferBuilder amountExpectedAfterTransferInSource(final ResourceKey resource, final long amount) { + this.amountExpectedAfterTransferInSource = new ResourceAmount(resource, amount); return this; } - public TransferBuilder amountExpectedAfterTransferInDestination(final String resource, final long amount) { - this.amountExpectedAfterTransferInDestination = new ResourceAmount<>(resource, amount); + public TransferBuilder amountExpectedAfterTransferInDestination(final ResourceKey resource, final long amount) { + this.amountExpectedAfterTransferInDestination = new ResourceAmount(resource, amount); return this; } diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/channel/StorageChannelImplTest.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/channel/StorageChannelImplTest.java index 0386616fa..bee737706 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/channel/StorageChannelImplTest.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/channel/StorageChannelImplTest.java @@ -19,6 +19,8 @@ import org.junit.jupiter.params.provider.EnumSource; import org.mockito.ArgumentCaptor; +import static com.refinedmods.refinedstorage2.api.storage.TestResource.A; +import static com.refinedmods.refinedstorage2.api.storage.TestResource.B; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atMost; @@ -27,27 +29,27 @@ import static org.mockito.Mockito.verify; class StorageChannelImplTest { - private StorageChannel sut; + private StorageChannel sut; @BeforeEach void setUp() { - sut = new StorageChannelImpl<>(); + sut = new StorageChannelImpl(); } @Test void shouldAddSource() { // Arrange - final Storage storage = new LimitedStorageImpl<>(10); - storage.insert("A", 8, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(10); + storage.insert(A, 8, Action.EXECUTE, EmptyActor.INSTANCE); // Act sut.addSource(storage); - final long inserted = sut.insert("A", 3, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted = sut.insert(A, 3, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(inserted).isEqualTo(2); } @@ -55,11 +57,11 @@ void shouldAddSource() { @Test void shouldRemoveSource() { // Arrange - final Storage storage = new LimitedStorageImpl<>(10); - storage.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(10); + storage.insert(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage removedStorage = new LimitedStorageImpl<>(10); - removedStorage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage removedStorage = new LimitedStorageImpl(10); + removedStorage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(storage); sut.addSource(removedStorage); @@ -67,11 +69,11 @@ void shouldRemoveSource() { // Act sut.removeSource(removedStorage); - final long extracted = sut.extract("A", 15, Action.SIMULATE, EmptyActor.INSTANCE); + final long extracted = sut.extract(A, 15, Action.SIMULATE, EmptyActor.INSTANCE); // Assert assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 5) + new ResourceAmount(A, 5) ); assertThat(extracted).isEqualTo(5); } @@ -79,11 +81,11 @@ void shouldRemoveSource() { @Test void shouldFindMatchingStorage() { // Arrange - final Storage matchedStorage = new LimitedStorageImpl<>(10); - matchedStorage.insert("A", 8, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage matchedStorage = new LimitedStorageImpl(10); + matchedStorage.insert(A, 8, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(matchedStorage); - final Storage unmatchedStorage = new LimitedStorageImpl<>(10); + final Storage unmatchedStorage = new LimitedStorageImpl(10); // Act final boolean foundMatched = sut.hasSource(s -> s == matchedStorage); @@ -96,19 +98,18 @@ void shouldFindMatchingStorage() { @ParameterizedTest @EnumSource(Action.class) - @SuppressWarnings("unchecked") void shouldCallListenerOnInsertion(final Action action) { // Arrange - sut.addSource(new LimitedStorageImpl<>(10)); - sut.insert("A", 2, Action.EXECUTE, EmptyActor.INSTANCE); + sut.addSource(new LimitedStorageImpl(10)); + sut.insert(A, 2, Action.EXECUTE, EmptyActor.INSTANCE); - final ResourceListListener listener = mock(ResourceListListener.class); + final ResourceListListener listener = mock(ResourceListListener.class); sut.addListener(listener); final var changedResource = ArgumentCaptor.forClass(ResourceListOperationResult.class); // Act - sut.insert("A", 8, action, EmptyActor.INSTANCE); + sut.insert(A, 8, action, EmptyActor.INSTANCE); // Assert if (action == Action.EXECUTE) { @@ -116,7 +117,7 @@ void shouldCallListenerOnInsertion(final Action action) { assertThat(changedResource.getValue().change()).isEqualTo(8); assertThat(changedResource.getValue().resourceAmount()).usingRecursiveComparison().isEqualTo( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); } else { verify(listener, never()).onChanged(any()); @@ -125,22 +126,21 @@ void shouldCallListenerOnInsertion(final Action action) { @ParameterizedTest @EnumSource(Action.class) - @SuppressWarnings("unchecked") void shouldCallListenerOnExtraction(final Action action) { // Arrange - final Storage storage = new LimitedStorageImpl<>(10); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(10); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(storage); - sut.extract("A", 2, Action.EXECUTE, EmptyActor.INSTANCE); + sut.extract(A, 2, Action.EXECUTE, EmptyActor.INSTANCE); - final ResourceListListener listener = mock(ResourceListListener.class); + final ResourceListListener listener = mock(ResourceListListener.class); sut.addListener(listener); final var changedResource = ArgumentCaptor.forClass(ResourceListOperationResult.class); // Act - sut.extract("A", 5, action, EmptyActor.INSTANCE); + sut.extract(A, 5, action, EmptyActor.INSTANCE); // Assert if (action == Action.EXECUTE) { @@ -148,7 +148,7 @@ void shouldCallListenerOnExtraction(final Action action) { assertThat(changedResource.getValue().change()).isEqualTo(-5); assertThat(changedResource.getValue().resourceAmount()).usingRecursiveComparison().isEqualTo( - new ResourceAmount<>("A", 3) + new ResourceAmount(A, 3) ); } else { verify(listener, never()).onChanged(any()); @@ -156,18 +156,17 @@ void shouldCallListenerOnExtraction(final Action action) { } @Test - @SuppressWarnings("unchecked") void shouldRemoveListener() { // Arrange - sut.addSource(new LimitedStorageImpl<>(10)); - sut.insert("A", 2, Action.EXECUTE, EmptyActor.INSTANCE); + sut.addSource(new LimitedStorageImpl(10)); + sut.insert(A, 2, Action.EXECUTE, EmptyActor.INSTANCE); - final ResourceListListener listener = mock(ResourceListListener.class); + final ResourceListListener listener = mock(ResourceListListener.class); sut.addListener(listener); // Act sut.removeListener(listener); - sut.insert("A", 8, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(A, 8, Action.EXECUTE, EmptyActor.INSTANCE); // Assert verify(listener, never()).onChanged(any()); @@ -176,16 +175,16 @@ void shouldRemoveListener() { @Test void shouldInsert() { // Arrange - sut.addSource(new LimitedStorageImpl<>(10)); + sut.addSource(new LimitedStorageImpl(10)); // Act - final long inserted1 = sut.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); - final long inserted2 = sut.insert("B", 4, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted1 = sut.insert(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted2 = sut.insert(B, 4, Action.EXECUTE, EmptyActor.INSTANCE); // Assert - assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 5), - new ResourceAmount<>("B", 4) + assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A, 5), + new ResourceAmount(B, 4) ); assertThat(inserted1).isEqualTo(5); assertThat(inserted2).isEqualTo(4); @@ -195,17 +194,17 @@ void shouldInsert() { @Test void shouldExtract() { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - storage.insert("A", 50, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(100); + storage.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(storage); // Act - final long extracted = sut.extract("A", 49, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = sut.extract(A, 49, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 1) + new ResourceAmount(A, 1) ); assertThat(extracted).isEqualTo(49); assertThat(sut.getStored()).isEqualTo(1); @@ -214,39 +213,39 @@ void shouldExtract() { @Test void shouldBeAbleToRetrieveResource() { // Arrange - final Storage storage = new LimitedStorageImpl<>(100); - storage.insert("A", 50, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(100); + storage.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(storage); // Act - final Optional> resource = sut.get("A"); + final Optional resource = sut.get(A); // Assert assertThat(resource).isPresent(); - assertThat(resource.get()).usingRecursiveComparison().isEqualTo(new ResourceAmount<>("A", 50)); - assertThat(sut.findTrackedResourceByActorType("A", EmptyActor.class)).isEmpty(); + assertThat(resource.get()).usingRecursiveComparison().isEqualTo(new ResourceAmount(A, 50)); + assertThat(sut.findTrackedResourceByActorType(A, EmptyActor.class)).isEmpty(); } @Test void shouldBeAbleToRetrieveTrackedResource() { // Arrange - final Storage storage = new TrackedStorageImpl<>( - new LimitedStorageImpl<>(100), + final Storage storage = new TrackedStorageImpl( + new LimitedStorageImpl(100), () -> 0L ); sut.addSource(storage); // Act - sut.insert("A", 50, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); // Assert - final Optional> value = sut.get("A"); + final Optional value = sut.get(A); assertThat(value).isPresent(); - assertThat(value.get()).usingRecursiveComparison().isEqualTo(new ResourceAmount<>("A", 50)); + assertThat(value.get()).usingRecursiveComparison().isEqualTo(new ResourceAmount(A, 50)); - assertThat(sut.findTrackedResourceByActorType("A", EmptyActor.class)) + assertThat(sut.findTrackedResourceByActorType(A, EmptyActor.class)) .get() .usingRecursiveComparison() .isEqualTo(new TrackedResource("Empty", 0)); @@ -255,10 +254,10 @@ void shouldBeAbleToRetrieveTrackedResource() { @Test void shouldNotBeAbleToRetrieveNonExistentResource() { // Arrange - sut.addSource(new LimitedStorageImpl<>(100)); + sut.addSource(new LimitedStorageImpl(100)); // Act - final Optional> resource = sut.get("A"); + final Optional resource = sut.get(A); // Assert assertThat(resource).isEmpty(); @@ -267,9 +266,9 @@ void shouldNotBeAbleToRetrieveNonExistentResource() { @Test void shouldSortSources() { // Arrange - final PrioritizedStorage storage1 = new PrioritizedStorage<>(0, new LimitedStorageImpl<>(10)); - final PrioritizedStorage storage2 = new PrioritizedStorage<>(0, new LimitedStorageImpl<>(10)); - final PrioritizedStorage storage3 = new PrioritizedStorage<>(0, new LimitedStorageImpl<>(10)); + final PrioritizedStorage storage1 = new PrioritizedStorage(0, new LimitedStorageImpl(10)); + final PrioritizedStorage storage2 = new PrioritizedStorage(0, new LimitedStorageImpl(10)); + final PrioritizedStorage storage3 = new PrioritizedStorage(0, new LimitedStorageImpl(10)); sut.addSource(storage1); sut.addSource(storage2); @@ -282,14 +281,14 @@ void shouldSortSources() { // Act sut.sortSources(); - sut.insert("A", 15, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(A, 15, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(storage2.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(storage1.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 5) + new ResourceAmount(A, 5) ); assertThat(storage3.getAll()).isEmpty(); } diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/CompositeStorageImplTest.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/CompositeStorageImplTest.java index 2b3917204..92d37d937 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/CompositeStorageImplTest.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/CompositeStorageImplTest.java @@ -17,14 +17,17 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static com.refinedmods.refinedstorage2.api.storage.TestResource.A; +import static com.refinedmods.refinedstorage2.api.storage.TestResource.B; +import static com.refinedmods.refinedstorage2.api.storage.TestResource.C; import static org.assertj.core.api.Assertions.assertThat; class CompositeStorageImplTest { - private CompositeStorageImpl sut; + private CompositeStorageImpl sut; @BeforeEach void setUp() { - sut = new CompositeStorageImpl<>(new ResourceListImpl<>()); + sut = new CompositeStorageImpl(new ResourceListImpl()); } @Test @@ -37,28 +40,28 @@ void testInitialState() { @Test void shouldAddSource() { // Arrange - final Storage storage1 = new LimitedStorageImpl<>(10); - storage1.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage1 = new LimitedStorageImpl(10); + storage1.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage storage2 = new LimitedStorageImpl<>(10); - storage2.insert("B", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage2 = new LimitedStorageImpl(10); + storage2.insert(B, 5, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage storage3 = new LimitedStorageImpl<>(10); - storage3.insert("C", 7, Action.EXECUTE, EmptyActor.INSTANCE); - storage3.insert("A", 3, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage3 = new LimitedStorageImpl(10); + storage3.insert(C, 7, Action.EXECUTE, EmptyActor.INSTANCE); + storage3.insert(A, 3, Action.EXECUTE, EmptyActor.INSTANCE); // Act sut.addSource(storage1); sut.addSource(storage2); sut.addSource(storage3); - final long inserted = sut.insert("B", 6, Action.SIMULATE, EmptyActor.INSTANCE); + final long inserted = sut.insert(B, 6, Action.SIMULATE, EmptyActor.INSTANCE); // Assert assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 13), - new ResourceAmount<>("B", 5), - new ResourceAmount<>("C", 7) + new ResourceAmount(A, 13), + new ResourceAmount(B, 5), + new ResourceAmount(C, 7) ); assertThat(sut.getSources()).containsExactly(storage1, storage2, storage3); assertThat(inserted).isEqualTo(5); @@ -67,15 +70,15 @@ void shouldAddSource() { @Test void shouldRemoveSource() { // Arrange - final Storage storage1 = new LimitedStorageImpl<>(10); - storage1.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage1 = new LimitedStorageImpl(10); + storage1.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage storage2 = new LimitedStorageImpl<>(10); - storage2.insert("B", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage2 = new LimitedStorageImpl(10); + storage2.insert(B, 5, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage storage3 = new LimitedStorageImpl<>(10); - storage3.insert("C", 7, Action.EXECUTE, EmptyActor.INSTANCE); - storage3.insert("A", 3, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage3 = new LimitedStorageImpl(10); + storage3.insert(C, 7, Action.EXECUTE, EmptyActor.INSTANCE); + storage3.insert(A, 3, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(storage1); sut.addSource(storage2); @@ -84,12 +87,12 @@ void shouldRemoveSource() { // Act sut.removeSource(storage3); - final long extracted = sut.extract("C", 1, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = sut.extract(C, 1, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 10), - new ResourceAmount<>("B", 5) + new ResourceAmount(A, 10), + new ResourceAmount(B, 5) ); assertThat(sut.getSources()).containsExactly(storage1, storage2); assertThat(extracted).isZero(); @@ -98,15 +101,15 @@ void shouldRemoveSource() { @Test void shouldClearSources() { // Arrange - final Storage storage1 = new LimitedStorageImpl<>(10); - storage1.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage1 = new LimitedStorageImpl(10); + storage1.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage storage2 = new LimitedStorageImpl<>(10); - storage2.insert("B", 5, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage2 = new LimitedStorageImpl(10); + storage2.insert(B, 5, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage storage3 = new LimitedStorageImpl<>(10); - storage3.insert("C", 7, Action.EXECUTE, EmptyActor.INSTANCE); - storage3.insert("A", 3, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage3 = new LimitedStorageImpl(10); + storage3.insert(C, 7, Action.EXECUTE, EmptyActor.INSTANCE); + storage3.insert(A, 3, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(storage1); sut.addSource(storage2); @@ -115,7 +118,7 @@ void shouldClearSources() { // Act sut.clearSources(); - final long extracted = sut.extract("C", 1, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = sut.extract(C, 1, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(sut.getAll()).isEmpty(); @@ -126,20 +129,20 @@ void shouldClearSources() { @Test void shouldRespectPriorityWhenAddingNewSources() { // Arrange - final Storage storage1 = new PrioritizedStorage<>(20, new LimitedStorageImpl<>(10)); - final Storage storage2 = new PrioritizedStorage<>(10, new LimitedStorageImpl<>(10)); - final Storage storage3 = new PrioritizedStorage<>(30, new LimitedStorageImpl<>(10)); + final Storage storage1 = new PrioritizedStorage(20, new LimitedStorageImpl(10)); + final Storage storage2 = new PrioritizedStorage(10, new LimitedStorageImpl(10)); + final Storage storage3 = new PrioritizedStorage(30, new LimitedStorageImpl(10)); // Act sut.addSource(storage1); sut.addSource(storage2); sut.addSource(storage3); - final long inserted = sut.insert("A", 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted = sut.insert(A, 12, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 12) + new ResourceAmount(A, 12) ); assertThat(sut.getSources()).containsExactly(storage3, storage1, storage2); assertThat(inserted).isEqualTo(12); @@ -151,9 +154,9 @@ void shouldRespectPriorityWhenAddingNewSources() { @Test void shouldRespectPriorityWhenRemovingSources() { // Arrange - final Storage storage1 = new PrioritizedStorage<>(20, new LimitedStorageImpl<>(10)); - final Storage storage2 = new PrioritizedStorage<>(10, new LimitedStorageImpl<>(10)); - final Storage storage3 = new PrioritizedStorage<>(30, new LimitedStorageImpl<>(10)); + final Storage storage1 = new PrioritizedStorage(20, new LimitedStorageImpl(10)); + final Storage storage2 = new PrioritizedStorage(10, new LimitedStorageImpl(10)); + final Storage storage3 = new PrioritizedStorage(30, new LimitedStorageImpl(10)); sut.addSource(storage1); sut.addSource(storage2); @@ -161,11 +164,11 @@ void shouldRespectPriorityWhenRemovingSources() { sut.removeSource(storage3); // Act - final long inserted = sut.insert("A", 12, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted = sut.insert(A, 12, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 12) + new ResourceAmount(A, 12) ); assertThat(sut.getSources()).containsExactly(storage1, storage2); assertThat(inserted).isEqualTo(12); @@ -177,26 +180,26 @@ void shouldRespectPriorityWhenRemovingSources() { @Test void shouldOnlyRespectPriorityWhenSortingSourcesExplicitlyWhenChangingPriorityAfterAddingSource() { // Arrange - final PrioritizedStorage storage1 = new PrioritizedStorage<>(1, new LimitedStorageImpl<>(10)); - final Storage storage2 = new PrioritizedStorage<>(2, new LimitedStorageImpl<>(10)); + final PrioritizedStorage storage1 = new PrioritizedStorage(1, new LimitedStorageImpl(10)); + final Storage storage2 = new PrioritizedStorage(2, new LimitedStorageImpl(10)); sut.addSource(storage1); sut.addSource(storage2); // Act & assert - sut.insert("A", 1, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(A, 1, Action.EXECUTE, EmptyActor.INSTANCE); assertThat(storage1.getStored()).isZero(); assertThat(storage2.getStored()).isEqualTo(1); storage1.setPriority(3); - sut.insert("A", 1, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(A, 1, Action.EXECUTE, EmptyActor.INSTANCE); assertThat(storage1.getStored()).isZero(); assertThat(storage2.getStored()).isEqualTo(2); sut.sortSources(); - sut.insert("A", 1, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(A, 1, Action.EXECUTE, EmptyActor.INSTANCE); assertThat(storage1.getStored()).isEqualTo(1); assertThat(storage2.getStored()).isEqualTo(2); } @@ -206,28 +209,28 @@ void shouldFindMostRecentChange() { // Arrange final AtomicLong clock = new AtomicLong(0L); - final TrackedStorage a = new TrackedStorageImpl<>(new InMemoryStorageImpl<>(), clock::get); - final TrackedStorage b = new TrackedStorageImpl<>(new InMemoryStorageImpl<>(), clock::get); + final TrackedStorage a = new TrackedStorageImpl(new InMemoryStorageImpl(), clock::get); + final TrackedStorage b = new TrackedStorageImpl(new InMemoryStorageImpl(), clock::get); // Test if it uses the latest across 2 different storages - a.insert("1", 1, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); + a.insert(A, 1, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); clock.set(1L); - b.insert("1", 1, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); + b.insert(A, 1, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); // Test if it differentiates between source types properly clock.set(2L); - b.insert("2", 1, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); + b.insert(B, 1, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); clock.set(3L); - b.insert("2", 1, Action.EXECUTE, FakeActors.FakeActor2.INSTANCE); + b.insert(B, 1, Action.EXECUTE, FakeActors.FakeActor2.INSTANCE); sut.addSource(a); sut.addSource(b); // Act - final var oneOne = sut.findTrackedResourceByActorType("1", FakeActors.FakeActor1.class); - final var oneTwo = sut.findTrackedResourceByActorType("1", FakeActors.FakeActor2.class); - final var twoOne = sut.findTrackedResourceByActorType("2", FakeActors.FakeActor1.class); - final var twoTwo = sut.findTrackedResourceByActorType("2", FakeActors.FakeActor2.class); + final var oneOne = sut.findTrackedResourceByActorType(A, FakeActors.FakeActor1.class); + final var oneTwo = sut.findTrackedResourceByActorType(A, FakeActors.FakeActor2.class); + final var twoOne = sut.findTrackedResourceByActorType(B, FakeActors.FakeActor1.class); + final var twoTwo = sut.findTrackedResourceByActorType(B, FakeActors.FakeActor2.class); // Assert assertThat(oneOne).get().usingRecursiveComparison().isEqualTo(new TrackedResource("Source1", 1L)); diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/ConsumingStorageCompositeStorageImplTest.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/ConsumingStorageCompositeStorageImplTest.java index 5ff6940c1..13fa6cca2 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/ConsumingStorageCompositeStorageImplTest.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/ConsumingStorageCompositeStorageImplTest.java @@ -9,28 +9,29 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static com.refinedmods.refinedstorage2.api.storage.TestResource.A; import static org.assertj.core.api.Assertions.assertThat; class ConsumingStorageCompositeStorageImplTest { - private CompositeStorageImpl sut; + private CompositeStorageImpl sut; @BeforeEach void setUp() { - sut = new CompositeStorageImpl<>(new ResourceListImpl<>()); + sut = new CompositeStorageImpl(new ResourceListImpl()); } @Test void shouldLoadResourcesFromConsumingStorageWhenAddingSource() { // Arrange - final ConsumingStorageImpl consumingStorage = new ConsumingStorageImpl<>(); - consumingStorage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final ConsumingStorageImpl consumingStorage = new ConsumingStorageImpl(); + consumingStorage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Act sut.addSource(consumingStorage); // Assert assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(sut.getStored()).isEqualTo(10); } @@ -38,8 +39,8 @@ void shouldLoadResourcesFromConsumingStorageWhenAddingSource() { @Test void shouldRemoveResourcesFromConsumingStorageWhenRemovingSource() { // Arrange - final ConsumingStorageImpl consumingStorage = new ConsumingStorageImpl<>(); - consumingStorage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final ConsumingStorageImpl consumingStorage = new ConsumingStorageImpl(); + consumingStorage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(consumingStorage); // Act @@ -53,10 +54,10 @@ void shouldRemoveResourcesFromConsumingStorageWhenRemovingSource() { @Test void shouldInsertResourceEntirelyIntoConsumingStorage() { // Arrange - sut.addSource(new ConsumingStorageImpl<>()); + sut.addSource(new ConsumingStorageImpl()); // Act - final long inserted = sut.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted = sut.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted).isEqualTo(10); @@ -67,16 +68,16 @@ void shouldInsertResourceEntirelyIntoConsumingStorage() { @Test void shouldInsertPartlyEntirelyIntoConsumingStorage() { // Arrange - sut.addSource(new PrioritizedStorage<>(10, new LimitedStorageImpl<>(7))); - sut.addSource(new ConsumingStorageImpl<>()); + sut.addSource(new PrioritizedStorage(10, new LimitedStorageImpl(7))); + sut.addSource(new ConsumingStorageImpl()); // Act - final long inserted = sut.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted = sut.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted).isEqualTo(10); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 7) + new ResourceAmount(A, 7) ); assertThat(sut.getStored()).isEqualTo(10); } @@ -84,11 +85,11 @@ void shouldInsertPartlyEntirelyIntoConsumingStorage() { @Test void shouldExtractResourceEntirelyFromConsumingStorage() { // Arrange - sut.addSource(new ConsumingStorageImpl<>()); - sut.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + sut.addSource(new ConsumingStorageImpl()); + sut.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final long extracted = sut.extract("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = sut.extract(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(10); @@ -99,12 +100,12 @@ void shouldExtractResourceEntirelyFromConsumingStorage() { @Test void shouldExtractResourcePartlyFromConsumingStorage() { // Arrange - sut.addSource(new PrioritizedStorage<>(10, new LimitedStorageImpl<>(7))); - sut.addSource(new ConsumingStorageImpl<>()); - sut.insert("A", 8, Action.EXECUTE, EmptyActor.INSTANCE); + sut.addSource(new PrioritizedStorage(10, new LimitedStorageImpl(7))); + sut.addSource(new ConsumingStorageImpl()); + sut.insert(A, 8, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final long extracted = sut.extract("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = sut.extract(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(8); diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/ConsumingStorageImpl.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/ConsumingStorageImpl.java index ebd479fa5..bfb5be74f 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/ConsumingStorageImpl.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/ConsumingStorageImpl.java @@ -3,8 +3,8 @@ import com.refinedmods.refinedstorage2.api.storage.AbstractProxyStorage; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; -public class ConsumingStorageImpl extends AbstractProxyStorage implements ConsumingStorage { - public ConsumingStorageImpl() { - super(new InMemoryStorageImpl<>()); +class ConsumingStorageImpl extends AbstractProxyStorage implements ConsumingStorage { + ConsumingStorageImpl() { + super(new InMemoryStorageImpl()); } } diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/ExtractCompositeStorageImplTest.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/ExtractCompositeStorageImplTest.java index c91a17840..28e9d0343 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/ExtractCompositeStorageImplTest.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/ExtractCompositeStorageImplTest.java @@ -7,6 +7,7 @@ import com.refinedmods.refinedstorage2.api.storage.ActorCapturingStorage; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; import com.refinedmods.refinedstorage2.api.storage.Storage; +import com.refinedmods.refinedstorage2.api.storage.TestResource; import com.refinedmods.refinedstorage2.api.storage.limited.LimitedStorageImpl; import org.junit.jupiter.api.BeforeEach; @@ -14,49 +15,50 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import static com.refinedmods.refinedstorage2.api.storage.TestResource.A; import static org.assertj.core.api.Assertions.assertThat; class ExtractCompositeStorageImplTest { - private CompositeStorageImpl sut; + private CompositeStorageImpl sut; @BeforeEach void setUp() { - sut = new CompositeStorageImpl<>(new ResourceListImpl<>()); + sut = new CompositeStorageImpl(new ResourceListImpl()); } @ParameterizedTest @EnumSource(Action.class) void shouldExtractFromSingleSourcePartially(final Action action) { // Arrange - final ActorCapturingStorage storage = new ActorCapturingStorage<>(new LimitedStorageImpl<>(10)); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final ActorCapturingStorage storage = new ActorCapturingStorage(new LimitedStorageImpl(10)); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(storage); final Actor actor = () -> "Custom"; // Act - final long extracted = sut.extract("A", 3, action, actor); + final long extracted = sut.extract(A, 3, action, actor); // Assert assertThat(extracted).isEqualTo(3); if (action == Action.EXECUTE) { assertThat(storage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 7) + new ResourceAmount(A, 7) ); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 7) + new ResourceAmount(A, 7) ); assertThat(sut.getStored()).isEqualTo(7); } else { assertThat(storage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(sut.getStored()).isEqualTo(10); } @@ -68,13 +70,13 @@ void shouldExtractFromSingleSourcePartially(final Action action) { @EnumSource(Action.class) void shouldExtractFromSingleSourceCompletely(final Action action) { // Arrange - final Storage storage = new LimitedStorageImpl<>(10); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(10); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(storage); // Act - final long extracted = sut.extract("A", 10, action, EmptyActor.INSTANCE); + final long extracted = sut.extract(A, 10, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(10); @@ -86,11 +88,11 @@ void shouldExtractFromSingleSourceCompletely(final Action action) { assertThat(sut.getStored()).isZero(); } else { assertThat(storage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(sut.getStored()).isEqualTo(10); } @@ -100,13 +102,13 @@ void shouldExtractFromSingleSourceCompletely(final Action action) { @EnumSource(Action.class) void shouldNotExtractMoreThanIsAvailableFromSingleSource(final Action action) { // Arrange - final Storage storage = new LimitedStorageImpl<>(10); - storage.insert("A", 4, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(10); + storage.insert(A, 4, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(storage); // Act - final long extracted = sut.extract("A", 7, action, EmptyActor.INSTANCE); + final long extracted = sut.extract(A, 7, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(4); @@ -118,11 +120,11 @@ void shouldNotExtractMoreThanIsAvailableFromSingleSource(final Action action) { assertThat(sut.getStored()).isZero(); } else { assertThat(storage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 4) + new ResourceAmount(A, 4) ); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 4) + new ResourceAmount(A, 4) ); assertThat(sut.getStored()).isEqualTo(4); } @@ -132,17 +134,17 @@ void shouldNotExtractMoreThanIsAvailableFromSingleSource(final Action action) { @EnumSource(Action.class) void shouldExtractFromMultipleSourcesPartially(final Action action) { // Arrange - final Storage storage1 = new LimitedStorageImpl<>(10); - storage1.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage1 = new LimitedStorageImpl(10); + storage1.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage storage2 = new LimitedStorageImpl<>(5); - storage2.insert("A", 3, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage2 = new LimitedStorageImpl(5); + storage2.insert(A, 3, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(storage1); sut.addSource(storage2); // Act - final long extracted = sut.extract("A", 12, action, EmptyActor.INSTANCE); + final long extracted = sut.extract(A, 12, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(12); @@ -150,23 +152,23 @@ void shouldExtractFromMultipleSourcesPartially(final Action action) { if (action == Action.EXECUTE) { assertThat(storage1.getAll()).isEmpty(); assertThat(storage2.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 1) + new ResourceAmount(A, 1) ); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 1) + new ResourceAmount(A, 1) ); assertThat(sut.getStored()).isEqualTo(1); } else { assertThat(storage1.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(storage2.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 3) + new ResourceAmount(A, 3) ); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 13) + new ResourceAmount(A, 13) ); assertThat(sut.getStored()).isEqualTo(13); } @@ -176,17 +178,17 @@ void shouldExtractFromMultipleSourcesPartially(final Action action) { @EnumSource(Action.class) void shouldExtractFromMultipleSourcesCompletely(final Action action) { // Arrange - final Storage storage1 = new LimitedStorageImpl<>(10); - storage1.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage1 = new LimitedStorageImpl(10); + storage1.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage storage2 = new LimitedStorageImpl<>(5); - storage2.insert("A", 3, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage2 = new LimitedStorageImpl(5); + storage2.insert(A, 3, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(storage1); sut.addSource(storage2); // Act - final long extracted = sut.extract("A", 13, action, EmptyActor.INSTANCE); + final long extracted = sut.extract(A, 13, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(13); @@ -199,14 +201,14 @@ void shouldExtractFromMultipleSourcesCompletely(final Action action) { assertThat(sut.getStored()).isZero(); } else { assertThat(storage1.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(storage2.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 3) + new ResourceAmount(A, 3) ); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 13) + new ResourceAmount(A, 13) ); assertThat(sut.getStored()).isEqualTo(13); } @@ -216,17 +218,17 @@ void shouldExtractFromMultipleSourcesCompletely(final Action action) { @EnumSource(Action.class) void shouldNotExtractMoreThanIsAvailableFromMultipleSources(final Action action) { // Arrange - final Storage storage1 = new LimitedStorageImpl<>(10); - storage1.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage1 = new LimitedStorageImpl(10); + storage1.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage storage2 = new LimitedStorageImpl<>(5); - storage2.insert("A", 3, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage2 = new LimitedStorageImpl(5); + storage2.insert(A, 3, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(storage1); sut.addSource(storage2); // Act - final long extracted = sut.extract("A", 30, action, EmptyActor.INSTANCE); + final long extracted = sut.extract(A, 30, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(13); @@ -239,14 +241,14 @@ void shouldNotExtractMoreThanIsAvailableFromMultipleSources(final Action action) assertThat(sut.getStored()).isZero(); } else { assertThat(storage1.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(storage2.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 3) + new ResourceAmount(A, 3) ); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 13) + new ResourceAmount(A, 13) ); assertThat(sut.getStored()).isEqualTo(13); } @@ -255,13 +257,13 @@ void shouldNotExtractMoreThanIsAvailableFromMultipleSources(final Action action) @Test void shouldNotExtractWithoutResourcePresent() { // Arrange - final Storage storage = new LimitedStorageImpl<>(10); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new LimitedStorageImpl(10); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(storage); // Act - final long extracted = sut.extract("B", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = sut.extract(TestResource.B, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(extracted).isZero(); @@ -270,7 +272,7 @@ void shouldNotExtractWithoutResourcePresent() { @Test void shouldNotExtractWithoutAnySourcesPresent() { // Act - final long extracted = sut.extract("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long extracted = sut.extract(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(extracted).isZero(); @@ -279,22 +281,22 @@ void shouldNotExtractWithoutAnySourcesPresent() { @Test void shouldRespectPriorityWhenExtracting() { // Arrange - final PrioritizedStorage lowestPriority = new PrioritizedStorage<>(5, new LimitedStorageImpl<>(10)); - final PrioritizedStorage highestPriority = new PrioritizedStorage<>(10, new LimitedStorageImpl<>(10)); + final PrioritizedStorage lowestPriority = new PrioritizedStorage(5, new LimitedStorageImpl(10)); + final PrioritizedStorage highestPriority = new PrioritizedStorage(10, new LimitedStorageImpl(10)); - lowestPriority.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); - highestPriority.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + lowestPriority.insert(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); + highestPriority.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(lowestPriority); sut.addSource(highestPriority); // Act - sut.extract("A", 11, Action.EXECUTE, EmptyActor.INSTANCE); + sut.extract(A, 11, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(highestPriority.getAll()).isEmpty(); assertThat(lowestPriority.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 4) + new ResourceAmount(A, 4) ); } } diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/InsertCompositeStorageImplTest.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/InsertCompositeStorageImplTest.java index 0c3e64a0f..4f882bcb2 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/InsertCompositeStorageImplTest.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/InsertCompositeStorageImplTest.java @@ -14,37 +14,38 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import static com.refinedmods.refinedstorage2.api.storage.TestResource.A; import static org.assertj.core.api.Assertions.assertThat; class InsertCompositeStorageImplTest { - private CompositeStorageImpl sut; + private CompositeStorageImpl sut; @BeforeEach void setUp() { - sut = new CompositeStorageImpl<>(new ResourceListImpl<>()); + sut = new CompositeStorageImpl(new ResourceListImpl()); } @ParameterizedTest @EnumSource(Action.class) void shouldInsertToSingleSourceWithoutRemainder(final Action action) { // Arrange - final ActorCapturingStorage storage = new ActorCapturingStorage<>(new LimitedStorageImpl<>(20)); + final ActorCapturingStorage storage = new ActorCapturingStorage(new LimitedStorageImpl(20)); sut.addSource(storage); final Actor actor = () -> "Custom"; // Act - final long inserted = sut.insert("A", 10, action, actor); + final long inserted = sut.insert(A, 10, action, actor); // Assert assertThat(inserted).isEqualTo(10); if (action == Action.EXECUTE) { assertThat(storage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(sut.getStored()).isEqualTo(10); } else { @@ -60,22 +61,22 @@ void shouldInsertToSingleSourceWithoutRemainder(final Action action) { @EnumSource(Action.class) void shouldInsertToSingleSourceWithRemainder(final Action action) { // Arrange - final Storage storage = new LimitedStorageImpl<>(20); + final Storage storage = new LimitedStorageImpl(20); sut.addSource(storage); // Act - final long inserted = sut.insert("A", 30, action, EmptyActor.INSTANCE); + final long inserted = sut.insert(A, 30, action, EmptyActor.INSTANCE); // Assert assertThat(inserted).isEqualTo(20); if (action == Action.EXECUTE) { assertThat(storage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 20) + new ResourceAmount(A, 20) ); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 20) + new ResourceAmount(A, 20) ); assertThat(sut.getStored()).isEqualTo(20); } else { @@ -90,33 +91,33 @@ void shouldInsertToSingleSourceWithRemainder(final Action action) { @EnumSource(Action.class) void shouldInsertToMultipleSourcesWithoutRemainder(final Action action) { // Arrange - final Storage storage1 = new LimitedStorageImpl<>(5); - final Storage storage2 = new LimitedStorageImpl<>(10); - final Storage storage3 = new LimitedStorageImpl<>(20); + final Storage storage1 = new LimitedStorageImpl(5); + final Storage storage2 = new LimitedStorageImpl(10); + final Storage storage3 = new LimitedStorageImpl(20); sut.addSource(storage1); sut.addSource(storage2); sut.addSource(storage3); // Act - final long inserted = sut.insert("A", 17, action, EmptyActor.INSTANCE); + final long inserted = sut.insert(A, 17, action, EmptyActor.INSTANCE); // Assert assertThat(inserted).isEqualTo(17); if (action == Action.EXECUTE) { assertThat(storage1.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 5) + new ResourceAmount(A, 5) ); assertThat(storage2.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(storage3.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 2) + new ResourceAmount(A, 2) ); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 17) + new ResourceAmount(A, 17) ); assertThat(sut.getStored()).isEqualTo(17); } else { @@ -133,33 +134,33 @@ void shouldInsertToMultipleSourcesWithoutRemainder(final Action action) { @EnumSource(Action.class) void shouldInsertToMultipleSourcesWithRemainder(final Action action) { // Arrange - final Storage storage1 = new LimitedStorageImpl<>(5); - final Storage storage2 = new LimitedStorageImpl<>(10); - final Storage storage3 = new LimitedStorageImpl<>(20); + final Storage storage1 = new LimitedStorageImpl(5); + final Storage storage2 = new LimitedStorageImpl(10); + final Storage storage3 = new LimitedStorageImpl(20); sut.addSource(storage1); sut.addSource(storage2); sut.addSource(storage3); // Act - final long inserted = sut.insert("A", 39, action, EmptyActor.INSTANCE); + final long inserted = sut.insert(A, 39, action, EmptyActor.INSTANCE); // Assert assertThat(inserted).isEqualTo(35); if (action == Action.EXECUTE) { assertThat(storage1.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 5) + new ResourceAmount(A, 5) ); assertThat(storage2.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(storage3.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 20) + new ResourceAmount(A, 20) ); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 35) + new ResourceAmount(A, 35) ); assertThat(sut.getStored()).isEqualTo(35); } else { @@ -175,7 +176,7 @@ void shouldInsertToMultipleSourcesWithRemainder(final Action action) { @Test void shouldNotInsertWithoutAnySourcesPresent() { // Act - final long inserted = sut.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long inserted = sut.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(inserted).isZero(); @@ -184,21 +185,21 @@ void shouldNotInsertWithoutAnySourcesPresent() { @Test void shouldRespectPriorityWhenInserting() { // Arrange - final PrioritizedStorage lowestPriority = new PrioritizedStorage<>(5, new LimitedStorageImpl<>(10)); - final PrioritizedStorage highestPriority = new PrioritizedStorage<>(10, new LimitedStorageImpl<>(10)); + final PrioritizedStorage lowestPriority = new PrioritizedStorage(5, new LimitedStorageImpl(10)); + final PrioritizedStorage highestPriority = new PrioritizedStorage(10, new LimitedStorageImpl(10)); sut.addSource(lowestPriority); sut.addSource(highestPriority); // Act - sut.insert("A", 11, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(A, 11, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(highestPriority.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); assertThat(lowestPriority.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 1) + new ResourceAmount(A, 1) ); } } diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/PrioritizedStorage.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/PrioritizedStorage.java index c17d6ff50..fafebcb41 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/PrioritizedStorage.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/PrioritizedStorage.java @@ -3,10 +3,10 @@ import com.refinedmods.refinedstorage2.api.storage.AbstractProxyStorage; import com.refinedmods.refinedstorage2.api.storage.Storage; -public class PrioritizedStorage extends AbstractProxyStorage implements Priority { +public class PrioritizedStorage extends AbstractProxyStorage implements Priority { private int priority; - public PrioritizedStorage(final int priority, final Storage delegate) { + public PrioritizedStorage(final int priority, final Storage delegate) { super(delegate); this.priority = priority; } diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/SubCompositeCompositeStorageImplTest.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/SubCompositeCompositeStorageImplTest.java index 4bbf1fdd9..c6c9d26f0 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/SubCompositeCompositeStorageImplTest.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/composite/SubCompositeCompositeStorageImplTest.java @@ -10,43 +10,45 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static com.refinedmods.refinedstorage2.api.storage.TestResource.A; +import static com.refinedmods.refinedstorage2.api.storage.TestResource.B; import static org.assertj.core.api.Assertions.assertThat; class SubCompositeCompositeStorageImplTest { - private CompositeStorageImpl sut; + private CompositeStorageImpl sut; @BeforeEach void setUp() { - sut = new CompositeStorageImpl<>(new ResourceListImpl<>()); + sut = new CompositeStorageImpl(new ResourceListImpl()); } @Test void testAddingSubCompositeShouldAddAllResourcesToParent() { // Arrange - final CompositeStorage subComposite = new CompositeStorageImpl<>(new ResourceListImpl<>()); - subComposite.addSource(new InMemoryStorageImpl<>()); - subComposite.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final CompositeStorage subComposite = new CompositeStorageImpl(new ResourceListImpl()); + subComposite.addSource(new InMemoryStorageImpl()); + subComposite.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Act sut.addSource(subComposite); // Assert assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); } @Test void testRemovingSubCompositeShouldRemoveAllResourcesFromParent() { // Arrange - final CompositeStorage subComposite = new CompositeStorageImpl<>(new ResourceListImpl<>()); - subComposite.addSource(new InMemoryStorageImpl<>()); - subComposite.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final CompositeStorage subComposite = new CompositeStorageImpl(new ResourceListImpl()); + subComposite.addSource(new InMemoryStorageImpl()); + subComposite.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(subComposite); - final Storage subCompositeStorage = new InMemoryStorageImpl<>(); - subCompositeStorage.insert("B", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage subCompositeStorage = new InMemoryStorageImpl(); + subCompositeStorage.insert(B, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Act sut.removeSource(subComposite); @@ -60,42 +62,42 @@ void testRemovingSubCompositeShouldRemoveAllResourcesFromParent() { @Test void testAddingSourceToSubCompositeShouldNotifyParent() { // Arrange - final CompositeStorage subComposite = new CompositeStorageImpl<>(new ResourceListImpl<>()); - final Storage subStorage = new InMemoryStorageImpl<>(); - subStorage.insert("B", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final CompositeStorage subComposite = new CompositeStorageImpl(new ResourceListImpl()); + final Storage subStorage = new InMemoryStorageImpl(); + subStorage.insert(B, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(subComposite); sut.addSource(subStorage); - final Storage subCompositeStorage = new InMemoryStorageImpl<>(); - subCompositeStorage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage subCompositeStorage = new InMemoryStorageImpl(); + subCompositeStorage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Act subComposite.addSource(subCompositeStorage); // Assert assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 10), - new ResourceAmount<>("B", 10) + new ResourceAmount(A, 10), + new ResourceAmount(B, 10) ); assertThat(subComposite.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 10) + new ResourceAmount(A, 10) ); } @Test void testRemovingSourceFromSubCompositeShouldNotifyParent() { // Arrange - final CompositeStorage subComposite = new CompositeStorageImpl<>(new ResourceListImpl<>()); - final Storage subStorage = new InMemoryStorageImpl<>(); - subStorage.insert("B", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final CompositeStorage subComposite = new CompositeStorageImpl(new ResourceListImpl()); + final Storage subStorage = new InMemoryStorageImpl(); + subStorage.insert(B, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(subComposite); sut.addSource(subStorage); - final Storage subCompositeStorage = new InMemoryStorageImpl<>(); - subCompositeStorage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage subCompositeStorage = new InMemoryStorageImpl(); + subCompositeStorage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); subComposite.addSource(subCompositeStorage); @@ -104,7 +106,7 @@ void testRemovingSourceFromSubCompositeShouldNotifyParent() { // Assert assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("B", 10) + new ResourceAmount(B, 10) ); assertThat(subComposite.getAll()).isEmpty(); } diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorageProviderImpl.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorageProviderImpl.java index c361d566d..df78ba786 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorageProviderImpl.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorageProviderImpl.java @@ -2,30 +2,31 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.Storage; import java.util.Iterator; -class ExternalStorageProviderImpl implements ExternalStorageProvider { - private final Storage storage; +class ExternalStorageProviderImpl implements ExternalStorageProvider { + private final Storage storage; - ExternalStorageProviderImpl(final Storage storage) { + ExternalStorageProviderImpl(final Storage storage) { this.storage = storage; } @Override - public long extract(final T resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return storage.extract(resource, amount, action, actor); } @Override - public long insert(final T resource, final long amount, final Action action, final Actor actor) { + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return storage.insert(resource, amount, action, actor); } @Override - public Iterator> iterator() { + public Iterator iterator() { return storage.getAll().iterator(); } } diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorageTest.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorageTest.java index 1fe3b3da1..fa7c7d6ec 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorageTest.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalStorageTest.java @@ -11,6 +11,11 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import static com.refinedmods.refinedstorage2.api.storage.external.ExternalTestResource.A; +import static com.refinedmods.refinedstorage2.api.storage.external.ExternalTestResource.A_ALTERNATIVE; +import static com.refinedmods.refinedstorage2.api.storage.external.ExternalTestResource.A_TRANSFORMED; +import static com.refinedmods.refinedstorage2.api.storage.external.ExternalTestResource.B; +import static com.refinedmods.refinedstorage2.api.storage.external.ExternalTestResource.B_TRANSFORMED; import static org.assertj.core.api.Assertions.assertThat; class ExternalStorageTest { @@ -24,11 +29,11 @@ void setUp() { @Test void shouldNotTakeExistingResourcesIntoConsiderationWhenBuildingInitialState() { // Arrange - final Storage storage = new TransformingStorage(); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new TransformingStorage(); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final Storage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); + final Storage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); // Assert assertThat(sut.getAll()).isEmpty(); @@ -40,9 +45,9 @@ void shouldNotTakeExistingResourcesIntoConsiderationWhenBuildingInitialState() { @Test void shouldTakeExistingResourcesIntoConsiderationWhenDetectingChanges() { // Arrange - final Storage storage = new TransformingStorage(); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - final ExternalStorage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); + final Storage storage = new TransformingStorage(); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + final ExternalStorage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); // Act final boolean hasChanges = sut.detectChanges(); @@ -50,7 +55,7 @@ void shouldTakeExistingResourcesIntoConsiderationWhenDetectingChanges() { // Assert assertThat(hasChanges).isTrue(); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A!", 10) + new ResourceAmount(A_TRANSFORMED, 10) ); assertThat(sut.getStored()).isEqualTo(10); assertThat(listener.resources).isEmpty(); @@ -60,17 +65,17 @@ void shouldTakeExistingResourcesIntoConsiderationWhenDetectingChanges() { @Test void shouldDetectCompletelyNewResource() { // Arrange - final Storage storage = new TransformingStorage(); - final ExternalStorage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); + final Storage storage = new TransformingStorage(); + final ExternalStorage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); // Act - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); final boolean hasChanges = sut.detectChanges(); // Assert assertThat(hasChanges).isTrue(); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A!", 10) + new ResourceAmount(A_TRANSFORMED, 10) ); assertThat(sut.getStored()).isEqualTo(10); assertThat(listener.resources).isEmpty(); @@ -80,20 +85,20 @@ void shouldDetectCompletelyNewResource() { @Test void shouldDetectAdditionToExistingResource() { // Arrange - final Storage storage = new TransformingStorage(); - final ExternalStorage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); + final Storage storage = new TransformingStorage(); + final ExternalStorage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.detectChanges(); // Act - storage.insert("A", 1, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(A, 1, Action.EXECUTE, EmptyActor.INSTANCE); final boolean hasChanges = sut.detectChanges(); // Assert assertThat(hasChanges).isTrue(); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A!", 11) + new ResourceAmount(A_TRANSFORMED, 11) ); assertThat(sut.getStored()).isEqualTo(11); assertThat(listener.resources).isEmpty(); @@ -104,20 +109,20 @@ void shouldDetectAdditionToExistingResource() { @Test void shouldDetectPartialRemovalOfExistingResource() { // Arrange - final Storage storage = new TransformingStorage(); - final ExternalStorage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); + final Storage storage = new TransformingStorage(); + final ExternalStorage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.detectChanges(); // Act - storage.extract("A!", 2, Action.EXECUTE, EmptyActor.INSTANCE); + storage.extract(A_TRANSFORMED, 2, Action.EXECUTE, EmptyActor.INSTANCE); final boolean hasChanges = sut.detectChanges(); // Assert assertThat(hasChanges).isTrue(); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A!", 8) + new ResourceAmount(A_TRANSFORMED, 8) ); assertThat(sut.getStored()).isEqualTo(8); assertThat(listener.resources).isEmpty(); @@ -127,14 +132,14 @@ void shouldDetectPartialRemovalOfExistingResource() { @Test void shouldDetectCompleteRemovalOfExistingResource() { // Arrange - final Storage storage = new TransformingStorage(); - final ExternalStorage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); + final Storage storage = new TransformingStorage(); + final ExternalStorage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.detectChanges(); // Act - storage.extract("A!", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storage.extract(A_TRANSFORMED, 10, Action.EXECUTE, EmptyActor.INSTANCE); final boolean hasChanges = sut.detectChanges(); // Assert @@ -148,21 +153,21 @@ void shouldDetectCompleteRemovalOfExistingResource() { @Test void shouldDetectCompleteRemovalOfExistingResourceAndAdditionOfNewResource() { // Arrange - final Storage storage = new TransformingStorage(); - final ExternalStorage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); + final Storage storage = new TransformingStorage(); + final ExternalStorage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.detectChanges(); // Act - storage.extract("A!", 10, Action.EXECUTE, EmptyActor.INSTANCE); - storage.insert("B", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storage.extract(A_TRANSFORMED, 10, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(B, 10, Action.EXECUTE, EmptyActor.INSTANCE); final boolean hasChanges = sut.detectChanges(); // Assert assertThat(hasChanges).isTrue(); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("B!", 10) + new ResourceAmount(B_TRANSFORMED, 10) ); assertThat(sut.getStored()).isEqualTo(10); assertThat(listener.resources).isEmpty(); @@ -172,22 +177,22 @@ void shouldDetectCompleteRemovalOfExistingResourceAndAdditionOfNewResource() { @Test void shouldDetectAdditionOfExistingResourceAndAdditionOfNewResource() { // Arrange - final Storage storage = new TransformingStorage(); - final ExternalStorage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); + final Storage storage = new TransformingStorage(); + final ExternalStorage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.detectChanges(); // Act - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - storage.insert("B", 1, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(B, 1, Action.EXECUTE, EmptyActor.INSTANCE); final boolean hasChanges = sut.detectChanges(); // Assert assertThat(hasChanges).isTrue(); - assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A!", 20), - new ResourceAmount<>("B!", 1) + assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A_TRANSFORMED, 20), + new ResourceAmount(B_TRANSFORMED, 1) ); assertThat(sut.getStored()).isEqualTo(21); assertThat(listener.resources).isEmpty(); @@ -197,14 +202,14 @@ void shouldDetectAdditionOfExistingResourceAndAdditionOfNewResource() { @Test void shouldNotDetectAnyChangesWhenNoChangesAreMade() { // Arrange - final Storage storage = new TransformingStorage(); - final ExternalStorage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); - - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - storage.insert("B", 10, Action.EXECUTE, EmptyActor.INSTANCE); - storage.extract("A!", 5, Action.EXECUTE, EmptyActor.INSTANCE); - storage.extract("B!", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new TransformingStorage(); + final ExternalStorage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); + + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + storage.insert(B, 10, Action.EXECUTE, EmptyActor.INSTANCE); + storage.extract(A_TRANSFORMED, 5, Action.EXECUTE, EmptyActor.INSTANCE); + storage.extract(B_TRANSFORMED, 10, Action.EXECUTE, EmptyActor.INSTANCE); sut.detectChanges(); // Act @@ -213,7 +218,7 @@ void shouldNotDetectAnyChangesWhenNoChangesAreMade() { // Assert assertThat(hasChanges).isFalse(); assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A!", 15) + new ResourceAmount(A_TRANSFORMED, 15) ); assertThat(sut.getStored()).isEqualTo(15); assertThat(listener.resources).isEmpty(); @@ -224,13 +229,13 @@ void shouldNotDetectAnyChangesWhenNoChangesAreMade() { @EnumSource(Action.class) void shouldInsertAndDetectChanges(final Action action) { // Arrange - final Storage storage = new TransformingStorage(); - final Storage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); + final Storage storage = new TransformingStorage(); + final Storage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); // Act - final long insertedA1 = sut.insert("A", 10, action, EmptyActor.INSTANCE); - final long insertedA2 = sut.insert("A", 1, action, EmptyActor.INSTANCE); - final long insertedB = sut.insert("B", 5, action, EmptyActor.INSTANCE); + final long insertedA1 = sut.insert(A, 10, action, EmptyActor.INSTANCE); + final long insertedA2 = sut.insert(A, 1, action, EmptyActor.INSTANCE); + final long insertedB = sut.insert(B, 5, action, EmptyActor.INSTANCE); // Assert assertThat(insertedA1).isEqualTo(10); @@ -238,12 +243,12 @@ void shouldInsertAndDetectChanges(final Action action) { assertThat(insertedB).isEqualTo(5); if (action == Action.EXECUTE) { - assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A!", 11), - new ResourceAmount<>("B!", 5) + assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A_TRANSFORMED, 11), + new ResourceAmount(B_TRANSFORMED, 5) ); assertThat(sut.getStored()).isEqualTo(16); - assertThat(listener.resources).containsExactly("A", "A", "B"); + assertThat(listener.resources).containsExactly(A, A, B); assertThat(listener.actors).containsOnly(EmptyActor.INSTANCE); } else { assertThat(sut.getAll()).isEmpty(); @@ -257,11 +262,11 @@ void shouldInsertAndDetectChanges(final Action action) { @EnumSource(Action.class) void shouldNotCallListenerWhenInsertionFailed(final Action action) { // Arrange - final Storage storage = new LimitedStorageImpl<>(0); - final Storage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); + final Storage storage = new LimitedStorageImpl(0); + final Storage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); // Act - final long extracted = sut.insert("A", 1, action, EmptyActor.INSTANCE); + final long extracted = sut.insert(A, 1, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isZero(); @@ -275,36 +280,36 @@ void shouldNotCallListenerWhenInsertionFailed(final Action action) { @EnumSource(Action.class) void shouldPartiallyExtractAndDetectChanges(final Action action) { // Arrange - final Storage storage = new TransformingStorage(); - final Storage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); - sut.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - sut.insert("A2", 10, Action.EXECUTE, EmptyActor.INSTANCE); - sut.insert("B", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new TransformingStorage(); + final Storage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); + sut.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(A_ALTERNATIVE, 10, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(B, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Act // this will try to extract A!(5) and A2!(5/2) - final long extracted = sut.extract("A!", 5, action, EmptyActor.INSTANCE); + final long extracted = sut.extract(A_TRANSFORMED, 5, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(5); if (action == Action.EXECUTE) { - assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A!", 5), - new ResourceAmount<>("A2!", 8), - new ResourceAmount<>("B!", 10) + assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A_TRANSFORMED, 5), + new ResourceAmount(A_ALTERNATIVE, 8), + new ResourceAmount(B_TRANSFORMED, 10) ); assertThat(sut.getStored()).isEqualTo(23); - assertThat(listener.resources).containsExactly("A", "A2", "B", "A!"); + assertThat(listener.resources).containsExactly(A, A_ALTERNATIVE, B, A_TRANSFORMED); assertThat(listener.actors).containsOnly(EmptyActor.INSTANCE); } else { - assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A!", 10), - new ResourceAmount<>("A2!", 10), - new ResourceAmount<>("B!", 10) + assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A_TRANSFORMED, 10), + new ResourceAmount(A_ALTERNATIVE, 10), + new ResourceAmount(B_TRANSFORMED, 10) ); assertThat(sut.getStored()).isEqualTo(30); - assertThat(listener.resources).containsExactly("A", "A2", "B"); + assertThat(listener.resources).containsExactly(A, A_ALTERNATIVE, B); assertThat(listener.actors).containsOnly(EmptyActor.INSTANCE); } } @@ -313,35 +318,35 @@ void shouldPartiallyExtractAndDetectChanges(final Action action) { @EnumSource(Action.class) void shouldCompletelyExtractAndDetectChanges(final Action action) { // Arrange - final Storage storage = new TransformingStorage(); - final Storage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); - sut.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - sut.insert("A2", 10, Action.EXECUTE, EmptyActor.INSTANCE); - sut.insert("B", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage storage = new TransformingStorage(); + final Storage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); + sut.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(A_ALTERNATIVE, 10, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(B, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Act // this will try to extract A!(10) and A2!(10/2) - final long extracted = sut.extract("A!", 10, action, EmptyActor.INSTANCE); + final long extracted = sut.extract(A_TRANSFORMED, 10, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(10); if (action == Action.EXECUTE) { - assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A2!", 5), - new ResourceAmount<>("B!", 10) + assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A_ALTERNATIVE, 5), + new ResourceAmount(B_TRANSFORMED, 10) ); assertThat(sut.getStored()).isEqualTo(15); - assertThat(listener.resources).containsExactly("A", "A2", "B", "A!"); + assertThat(listener.resources).containsExactly(A, A_ALTERNATIVE, B, A_TRANSFORMED); assertThat(listener.actors).containsOnly(EmptyActor.INSTANCE); } else { - assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A!", 10), - new ResourceAmount<>("A2!", 10), - new ResourceAmount<>("B!", 10) + assertThat(sut.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A_TRANSFORMED, 10), + new ResourceAmount(A_ALTERNATIVE, 10), + new ResourceAmount(B_TRANSFORMED, 10) ); assertThat(sut.getStored()).isEqualTo(30); - assertThat(listener.resources).containsExactly("A", "A2", "B"); + assertThat(listener.resources).containsExactly(A, A_ALTERNATIVE, B); assertThat(listener.actors).containsOnly(EmptyActor.INSTANCE); } } @@ -350,11 +355,11 @@ void shouldCompletelyExtractAndDetectChanges(final Action action) { @EnumSource(Action.class) void shouldNotCallListenerWhenExtractionFailed(final Action action) { // Arrange - final Storage storage = new TransformingStorage(); - final Storage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); + final Storage storage = new TransformingStorage(); + final Storage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); // Act - final long extracted = sut.extract("A", 10, action, EmptyActor.INSTANCE); + final long extracted = sut.extract(A, 10, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isZero(); diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalTestResource.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalTestResource.java new file mode 100644 index 000000000..0614971fb --- /dev/null +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/ExternalTestResource.java @@ -0,0 +1,11 @@ +package com.refinedmods.refinedstorage2.api.storage.external; + +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; + +enum ExternalTestResource implements ResourceKey { + A, + A_TRANSFORMED, + A_ALTERNATIVE, + B, + B_TRANSFORMED +} diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/SpyingExternalStorageListener.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/SpyingExternalStorageListener.java index ed595becc..f9773c7a3 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/SpyingExternalStorageListener.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/SpyingExternalStorageListener.java @@ -1,16 +1,17 @@ package com.refinedmods.refinedstorage2.api.storage.external; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.Actor; import java.util.ArrayList; import java.util.List; -class SpyingExternalStorageListener implements ExternalStorageListener { - public final List resources = new ArrayList<>(); +class SpyingExternalStorageListener implements ExternalStorageListener { + public final List resources = new ArrayList<>(); public final List actors = new ArrayList<>(); @Override - public void beforeDetectChanges(final String resource, final Actor actor) { + public void beforeDetectChanges(final ResourceKey resource, final Actor actor) { resources.add(resource); actors.add(actor); } diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/StorageChannelExternalStorageTest.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/StorageChannelExternalStorageTest.java index 3ff3af531..8f6ec8624 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/StorageChannelExternalStorageTest.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/StorageChannelExternalStorageTest.java @@ -12,6 +12,11 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import static com.refinedmods.refinedstorage2.api.storage.external.ExternalTestResource.A; +import static com.refinedmods.refinedstorage2.api.storage.external.ExternalTestResource.A_ALTERNATIVE; +import static com.refinedmods.refinedstorage2.api.storage.external.ExternalTestResource.A_TRANSFORMED; +import static com.refinedmods.refinedstorage2.api.storage.external.ExternalTestResource.B; +import static com.refinedmods.refinedstorage2.api.storage.external.ExternalTestResource.B_TRANSFORMED; import static org.assertj.core.api.Assertions.assertThat; class StorageChannelExternalStorageTest { @@ -25,10 +30,10 @@ void setUp() { @Test void shouldNotTakeExistingResourcesIntoConsiderationWhenBuildingInitialState() { // Arrange - final Storage storage = new TransformingStorage(); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); - final StorageChannel storageChannel = new StorageChannelImpl<>(); + final Storage storage = new TransformingStorage(); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); + final StorageChannel storageChannel = new StorageChannelImpl(); // Act storageChannel.addSource(sut); @@ -45,10 +50,10 @@ void shouldNotTakeExistingResourcesIntoConsiderationWhenBuildingInitialState() { @Test void shouldTakeExistingResourcesIntoConsiderationWhenDetectingChanges() { // Arrange - final Storage storage = new TransformingStorage(); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - final ExternalStorage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); - final StorageChannel storageChannel = new StorageChannelImpl<>(); + final Storage storage = new TransformingStorage(); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + final ExternalStorage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); + final StorageChannel storageChannel = new StorageChannelImpl(); storageChannel.addSource(sut); // Act @@ -56,7 +61,7 @@ void shouldTakeExistingResourcesIntoConsiderationWhenDetectingChanges() { // Assert assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A!", 10) + new ResourceAmount(A_TRANSFORMED, 10) ); assertThat(storageChannel.getStored()).isEqualTo(10); assertThat(listener.resources).isEmpty(); @@ -66,17 +71,17 @@ void shouldTakeExistingResourcesIntoConsiderationWhenDetectingChanges() { @Test void shouldNoLongerPropagateChangesToStorageChannelWhenRemoving() { // Arrange - final Storage storage = new TransformingStorage(); - storage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - final Storage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); - final StorageChannel storageChannel = new StorageChannelImpl<>(); + final Storage storage = new TransformingStorage(); + storage.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + final Storage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); + final StorageChannel storageChannel = new StorageChannelImpl(); storageChannel.addSource(sut); // Act - storageChannel.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); + storageChannel.insert(A, 5, Action.EXECUTE, EmptyActor.INSTANCE); storageChannel.removeSource(sut); - final long insertedStraightIntoExternalStorage = sut.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - final long insertedIntoStorageChannel = storageChannel.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long insertedStraightIntoExternalStorage = sut.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + final long insertedIntoStorageChannel = storageChannel.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); // Assert assertThat(insertedStraightIntoExternalStorage).isEqualTo(10); @@ -85,7 +90,7 @@ void shouldNoLongerPropagateChangesToStorageChannelWhenRemoving() { assertThat(sut.getStored()).isEqualTo(25); assertThat(storageChannel.getAll()).isEmpty(); assertThat(storageChannel.getStored()).isZero(); - assertThat(listener.resources).containsExactly("A", "A"); + assertThat(listener.resources).containsExactly(A, A); assertThat(listener.actors).containsOnly(EmptyActor.INSTANCE); } @@ -93,15 +98,15 @@ void shouldNoLongerPropagateChangesToStorageChannelWhenRemoving() { @EnumSource(Action.class) void shouldInsertAndDetectAndPropagateChanges(final Action action) { // Arrange - final Storage storage = new TransformingStorage(); - final Storage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); - final StorageChannel storageChannel = new StorageChannelImpl<>(); + final Storage storage = new TransformingStorage(); + final Storage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); + final StorageChannel storageChannel = new StorageChannelImpl(); storageChannel.addSource(sut); // Act - final long insertedA1 = storageChannel.insert("A", 10, action, EmptyActor.INSTANCE); - final long insertedA2 = storageChannel.insert("A", 1, action, EmptyActor.INSTANCE); - final long insertedB = storageChannel.insert("B", 5, action, EmptyActor.INSTANCE); + final long insertedA1 = storageChannel.insert(A, 10, action, EmptyActor.INSTANCE); + final long insertedA2 = storageChannel.insert(A, 1, action, EmptyActor.INSTANCE); + final long insertedB = storageChannel.insert(B, 5, action, EmptyActor.INSTANCE); // Assert assertThat(insertedA1).isEqualTo(10); @@ -109,12 +114,12 @@ void shouldInsertAndDetectAndPropagateChanges(final Action action) { assertThat(insertedB).isEqualTo(5); if (action == Action.EXECUTE) { - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A!", 11), - new ResourceAmount<>("B!", 5) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A_TRANSFORMED, 11), + new ResourceAmount(B_TRANSFORMED, 5) ); assertThat(storageChannel.getStored()).isEqualTo(16); - assertThat(listener.resources).containsExactly("A", "A", "B"); + assertThat(listener.resources).containsExactly(A, A, B); assertThat(listener.actors).containsOnly(EmptyActor.INSTANCE); } else { assertThat(storageChannel.getAll()).isEmpty(); @@ -128,38 +133,38 @@ void shouldInsertAndDetectAndPropagateChanges(final Action action) { @EnumSource(Action.class) void shouldExtractPartiallyAndDetectAndPropagateChanges(final Action action) { // Arrange - final Storage storage = new TransformingStorage(); - final Storage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); - sut.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - sut.insert("A2", 10, Action.EXECUTE, EmptyActor.INSTANCE); - sut.insert("B", 10, Action.EXECUTE, EmptyActor.INSTANCE); - final StorageChannel storageChannel = new StorageChannelImpl<>(); + final Storage storage = new TransformingStorage(); + final Storage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); + sut.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(A_ALTERNATIVE, 10, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(B, 10, Action.EXECUTE, EmptyActor.INSTANCE); + final StorageChannel storageChannel = new StorageChannelImpl(); storageChannel.addSource(sut); // Act // this will try to extract A!(5) and A2!(5/2) - final long extracted = storageChannel.extract("A!", 5, action, EmptyActor.INSTANCE); + final long extracted = storageChannel.extract(A_TRANSFORMED, 5, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(5); if (action == Action.EXECUTE) { - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A!", 5), - new ResourceAmount<>("A2!", 8), - new ResourceAmount<>("B!", 10) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A_TRANSFORMED, 5), + new ResourceAmount(A_ALTERNATIVE, 8), + new ResourceAmount(B_TRANSFORMED, 10) ); assertThat(storageChannel.getStored()).isEqualTo(23); - assertThat(listener.resources).containsExactly("A", "A2", "B", "A!"); + assertThat(listener.resources).containsExactly(A, A_ALTERNATIVE, B, A_TRANSFORMED); assertThat(listener.actors).containsOnly(EmptyActor.INSTANCE); } else { - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A!", 10), - new ResourceAmount<>("A2!", 10), - new ResourceAmount<>("B!", 10) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A_TRANSFORMED, 10), + new ResourceAmount(A_ALTERNATIVE, 10), + new ResourceAmount(B_TRANSFORMED, 10) ); assertThat(storageChannel.getStored()).isEqualTo(30); - assertThat(listener.resources).containsExactly("A", "A2", "B"); + assertThat(listener.resources).containsExactly(A, A_ALTERNATIVE, B); assertThat(listener.actors).containsOnly(EmptyActor.INSTANCE); } } @@ -168,37 +173,37 @@ void shouldExtractPartiallyAndDetectAndPropagateChanges(final Action action) { @EnumSource(Action.class) void shouldExtractCompletelyAndDetectAndPropagateChanges(final Action action) { // Arrange - final Storage storage = new TransformingStorage(); - final Storage sut = new ExternalStorage<>(new ExternalStorageProviderImpl<>(storage), listener); - sut.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); - sut.insert("A2", 10, Action.EXECUTE, EmptyActor.INSTANCE); - sut.insert("B", 10, Action.EXECUTE, EmptyActor.INSTANCE); - final StorageChannel storageChannel = new StorageChannelImpl<>(); + final Storage storage = new TransformingStorage(); + final Storage sut = new ExternalStorage(new ExternalStorageProviderImpl(storage), listener); + sut.insert(A, 10, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(A_ALTERNATIVE, 10, Action.EXECUTE, EmptyActor.INSTANCE); + sut.insert(B, 10, Action.EXECUTE, EmptyActor.INSTANCE); + final StorageChannel storageChannel = new StorageChannelImpl(); storageChannel.addSource(sut); // Act // this will try to extract A!(10) and A2!(10/2) - final long extracted = storageChannel.extract("A!", 10, action, EmptyActor.INSTANCE); + final long extracted = storageChannel.extract(A_TRANSFORMED, 10, action, EmptyActor.INSTANCE); // Assert assertThat(extracted).isEqualTo(10); if (action == Action.EXECUTE) { - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A2!", 5), - new ResourceAmount<>("B!", 10) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A_ALTERNATIVE, 5), + new ResourceAmount(B_TRANSFORMED, 10) ); assertThat(storageChannel.getStored()).isEqualTo(15); - assertThat(listener.resources).containsExactly("A", "A2", "B", "A!"); + assertThat(listener.resources).containsExactly(A, A_ALTERNATIVE, B, A_TRANSFORMED); assertThat(listener.actors).containsOnly(EmptyActor.INSTANCE); } else { - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A!", 10), - new ResourceAmount<>("A2!", 10), - new ResourceAmount<>("B!", 10) + assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(A_TRANSFORMED, 10), + new ResourceAmount(A_ALTERNATIVE, 10), + new ResourceAmount(B_TRANSFORMED, 10) ); assertThat(storageChannel.getStored()).isEqualTo(30); - assertThat(listener.resources).containsExactly("A", "A2", "B"); + assertThat(listener.resources).containsExactly(A, A_ALTERNATIVE, B); assertThat(listener.actors).containsOnly(EmptyActor.INSTANCE); } } diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/TransformingStorage.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/TransformingStorage.java index 9e8cc1bc4..4458aa0af 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/TransformingStorage.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/external/TransformingStorage.java @@ -1,24 +1,39 @@ package com.refinedmods.refinedstorage2.api.storage.external; import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.resource.ResourceKey; import com.refinedmods.refinedstorage2.api.storage.AbstractProxyStorage; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; -class TransformingStorage extends AbstractProxyStorage { +import static com.refinedmods.refinedstorage2.api.storage.external.ExternalTestResource.A_ALTERNATIVE; +import static com.refinedmods.refinedstorage2.api.storage.external.ExternalTestResource.A_TRANSFORMED; + +class TransformingStorage extends AbstractProxyStorage { TransformingStorage() { - super(new InMemoryStorageImpl<>()); + super(new InMemoryStorageImpl()); + } + + private ResourceKey transform(final ResourceKey resource) { + if (resource == ExternalTestResource.A) { + return A_TRANSFORMED; + } else if (resource == ExternalTestResource.B) { + return ExternalTestResource.B_TRANSFORMED; + } + return resource; } @Override - public long insert(final String resource, final long amount, final Action action, final Actor actor) { - return super.insert(resource + "!", amount, action, actor); + public long insert(final ResourceKey resource, final long amount, final Action action, final Actor actor) { + return super.insert(transform(resource), amount, action, actor); } @Override - public long extract(final String resource, final long amount, final Action action, final Actor actor) { + public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { final long extracted = super.extract(resource, amount, action, actor); - super.extract(resource.replace("!", "") + "2!", amount / 2, action, actor); + if (resource == A_TRANSFORMED) { + super.extract(A_ALTERNATIVE, amount / 2, action, actor); + } return extracted; } } diff --git a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/tracked/TrackedStorageImplTest.java b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/tracked/TrackedStorageImplTest.java index 690c7c108..04ff6254d 100644 --- a/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/tracked/TrackedStorageImplTest.java +++ b/refinedstorage2-storage-api/src/test/java/com/refinedmods/refinedstorage2/api/storage/tracked/TrackedStorageImplTest.java @@ -15,25 +15,27 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import static com.refinedmods.refinedstorage2.api.storage.TestResource.A; +import static com.refinedmods.refinedstorage2.api.storage.TestResource.B; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; class TrackedStorageImplTest { private final AtomicLong clock = new AtomicLong(0); - private LimitedStorageImpl backed; - private TrackedStorage sut; + private LimitedStorageImpl backed; + private TrackedStorage sut; @BeforeEach void setUp() { - backed = new LimitedStorageImpl<>(100); - sut = new TrackedStorageImpl<>(backed, clock::get); + backed = new LimitedStorageImpl(100); + sut = new TrackedStorageImpl(backed, clock::get); } @Test void testInitialState() { // Act - final Optional trackedResource = sut.findTrackedResourceByActorType("A", EmptyActor.class); + final Optional trackedResource = sut.findTrackedResourceByActorType(A, EmptyActor.class); // Assert assertThat(trackedResource).isEmpty(); @@ -43,14 +45,14 @@ void testInitialState() { @SuppressWarnings("ConstantConditions") void testInvalidParent() { // Act & assert - assertThrows(NullPointerException.class, () -> new TrackedStorageImpl<>(null, clock::get)); + assertThrows(NullPointerException.class, () -> new TrackedStorageImpl(null, clock::get)); } @Test @SuppressWarnings("ConstantConditions") void shouldNotInsertWithInvalidSource() { // Act - final Executable action = () -> sut.insert("A", 1, Action.EXECUTE, null); + final Executable action = () -> sut.insert(A, 1, Action.EXECUTE, null); // Assert assertThrows(NullPointerException.class, action); @@ -60,7 +62,7 @@ void shouldNotInsertWithInvalidSource() { @SuppressWarnings("ConstantConditions") void shouldNotExtractWithInvalidSource() { // Act - final Executable action = () -> sut.extract("A", 1, Action.EXECUTE, null); + final Executable action = () -> sut.extract(A, 1, Action.EXECUTE, null); // Assert assertThrows(NullPointerException.class, action); @@ -71,15 +73,15 @@ class InitialTrackTest { @Test void shouldNotFindUntrackedResource() { // Act - sut.insert("B", 100, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); + sut.insert(B, 100, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); // Assert - final Optional resourceA1 = sut.findTrackedResourceByActorType("A", EmptyActor.class); + final Optional resourceA1 = sut.findTrackedResourceByActorType(A, EmptyActor.class); final Optional resourceA2 = - sut.findTrackedResourceByActorType("A", FakeActors.FakeActor1.class); - final Optional resourceB1 = sut.findTrackedResourceByActorType("B", EmptyActor.class); + sut.findTrackedResourceByActorType(A, FakeActors.FakeActor1.class); + final Optional resourceB1 = sut.findTrackedResourceByActorType(B, EmptyActor.class); final Optional resourceB2 = - sut.findTrackedResourceByActorType("B", FakeActors.FakeActor1.class); + sut.findTrackedResourceByActorType(B, FakeActors.FakeActor1.class); assertThat(resourceA1).isEmpty(); assertThat(resourceA2).isEmpty(); @@ -94,13 +96,13 @@ void shouldTrackResourceByInserting(final Action action) { clock.set(1L); // Act - final long inserted = sut.insert("A", 100, action, FakeActors.FakeActor1.INSTANCE); + final long inserted = sut.insert(A, 100, action, FakeActors.FakeActor1.INSTANCE); // Assert assertThat(inserted).isEqualTo(100); final Optional trackedResource = - sut.findTrackedResourceByActorType("A", FakeActors.FakeActor1.class); + sut.findTrackedResourceByActorType(A, FakeActors.FakeActor1.class); if (action == Action.EXECUTE) { assertThat(trackedResource).isPresent(); @@ -119,16 +121,16 @@ void shouldTrackResourceByInserting(final Action action) { @EnumSource(Action.class) void shouldNotTrackResourceByInsertingToAlreadyFullStorage(final Action action) { // Arrange - backed.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); + backed.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final long inserted = sut.insert("A", 1, action, FakeActors.FakeActor1.INSTANCE); + final long inserted = sut.insert(A, 1, action, FakeActors.FakeActor1.INSTANCE); // Assert assertThat(inserted).isZero(); final Optional resource = - sut.findTrackedResourceByActorType("A", FakeActors.FakeActor1.class); + sut.findTrackedResourceByActorType(A, FakeActors.FakeActor1.class); assertThat(resource).isEmpty(); } @@ -136,16 +138,16 @@ void shouldNotTrackResourceByInsertingToAlreadyFullStorage(final Action action) @EnumSource(Action.class) void shouldTrackResourceByExtracting(final Action action) { // Arrange - backed.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); + backed.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); // Act - final long extracted = sut.extract("A", 10, action, FakeActors.FakeActor1.INSTANCE); + final long extracted = sut.extract(A, 10, action, FakeActors.FakeActor1.INSTANCE); // Assert assertThat(extracted).isEqualTo(10); final Optional trackedResource = - sut.findTrackedResourceByActorType("A", FakeActors.FakeActor1.class); + sut.findTrackedResourceByActorType(A, FakeActors.FakeActor1.class); if (action == Action.EXECUTE) { assertThat(trackedResource).get().usingRecursiveComparison() @@ -159,28 +161,28 @@ void shouldTrackResourceByExtracting(final Action action) { @EnumSource(Action.class) void shouldNotTrackResourceByExtractingNothing(final Action action) { // Act - final long extracted = sut.extract("A", 1, action, FakeActors.FakeActor1.INSTANCE); + final long extracted = sut.extract(A, 1, action, FakeActors.FakeActor1.INSTANCE); // Assert assertThat(extracted).isZero(); final Optional trackedResource = - sut.findTrackedResourceByActorType("A", FakeActors.FakeActor1.class); + sut.findTrackedResourceByActorType(A, FakeActors.FakeActor1.class); assertThat(trackedResource).isEmpty(); } @Test void shouldTrackMultipleResources() { // Act - sut.insert("A", 1, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); + sut.insert(A, 1, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); clock.set(1); - sut.insert("B", 1, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); + sut.insert(B, 1, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); // Assert final Optional resourceA = - sut.findTrackedResourceByActorType("A", FakeActors.FakeActor1.class); + sut.findTrackedResourceByActorType(A, FakeActors.FakeActor1.class); final Optional resourceB = - sut.findTrackedResourceByActorType("B", FakeActors.FakeActor1.class); + sut.findTrackedResourceByActorType(B, FakeActors.FakeActor1.class); assertThat(resourceA).get().usingRecursiveComparison().isEqualTo(new TrackedResource("Source1", 0)); assertThat(resourceB).get().usingRecursiveComparison().isEqualTo(new TrackedResource("Source1", 1)); @@ -193,13 +195,13 @@ class UpdateTrackedResourceTest { @EnumSource(Action.class) void shouldUpdateTrackedResourceByInserting(final Action action) { // Act - sut.insert("A", 50, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); + sut.insert(A, 50, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); clock.set(10); - sut.insert("A", 60, action, FakeActors.FakeActor1.INSTANCE); + sut.insert(A, 60, action, FakeActors.FakeActor1.INSTANCE); // Assert final Optional trackedResource = - sut.findTrackedResourceByActorType("A", FakeActors.FakeActor1.class); + sut.findTrackedResourceByActorType(A, FakeActors.FakeActor1.class); if (action == Action.EXECUTE) { assertThat(trackedResource).get().usingRecursiveComparison() @@ -214,13 +216,13 @@ void shouldUpdateTrackedResourceByInserting(final Action action) { @EnumSource(Action.class) void shouldNotUpdateTrackedResourceByInsertingToAnAlreadyFullStorage(final Action action) { // Act - sut.insert("A", 100, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); + sut.insert(A, 100, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); clock.set(10); - sut.insert("A", 1, action, FakeActors.FakeActor1.INSTANCE); + sut.insert(A, 1, action, FakeActors.FakeActor1.INSTANCE); // Assert final Optional trackedResource = - sut.findTrackedResourceByActorType("A", FakeActors.FakeActor1.class); + sut.findTrackedResourceByActorType(A, FakeActors.FakeActor1.class); assertThat(trackedResource).get().usingRecursiveComparison().isEqualTo(new TrackedResource("Source1", 0)); } @@ -228,16 +230,16 @@ void shouldNotUpdateTrackedResourceByInsertingToAnAlreadyFullStorage(final Actio @EnumSource(Action.class) void shouldUpdateTrackedResourceByExtracting(final Action action) { // Arrange - backed.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); + backed.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); // Act - sut.extract("A", 50, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); + sut.extract(A, 50, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); clock.set(10); - sut.extract("A", 60, action, FakeActors.FakeActor1.INSTANCE); + sut.extract(A, 60, action, FakeActors.FakeActor1.INSTANCE); // Assert final Optional trackedResource = - sut.findTrackedResourceByActorType("A", FakeActors.FakeActor1.class); + sut.findTrackedResourceByActorType(A, FakeActors.FakeActor1.class); if (action == Action.EXECUTE) { assertThat(trackedResource).get().usingRecursiveComparison() @@ -252,42 +254,42 @@ void shouldUpdateTrackedResourceByExtracting(final Action action) { @EnumSource(Action.class) void shouldNotUpdateTrackedResourceByExtractingNothing(final Action action) { // Arrange - backed.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); + backed.insert(A, 100, Action.EXECUTE, EmptyActor.INSTANCE); // Act - sut.extract("A", 100, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); + sut.extract(A, 100, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); clock.set(10); - sut.extract("A", 1, action, FakeActors.FakeActor1.INSTANCE); + sut.extract(A, 1, action, FakeActors.FakeActor1.INSTANCE); // Assert final Optional trackedResource = - sut.findTrackedResourceByActorType("A", FakeActors.FakeActor1.class); + sut.findTrackedResourceByActorType(A, FakeActors.FakeActor1.class); assertThat(trackedResource).get().usingRecursiveComparison().isEqualTo(new TrackedResource("Source1", 0)); } @Test void shouldBeAbleToUpdateMultipleTrackedResources() { // Act - sut.insert("A", 1, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); + sut.insert(A, 1, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); clock.set(1); - sut.insert("B", 1, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); + sut.insert(B, 1, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); clock.set(2); - sut.insert("A", 1, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); + sut.insert(A, 1, Action.EXECUTE, FakeActors.FakeActor1.INSTANCE); clock.set(3); - sut.insert("B", 1, Action.EXECUTE, FakeActors.FakeActor2.INSTANCE); + sut.insert(B, 1, Action.EXECUTE, FakeActors.FakeActor2.INSTANCE); // Assert final Optional resourceAWithSource1 = - sut.findTrackedResourceByActorType("A", FakeActors.FakeActor1.class); + sut.findTrackedResourceByActorType(A, FakeActors.FakeActor1.class); final Optional resourceAWithSource2 = - sut.findTrackedResourceByActorType("A", FakeActors.FakeActor2.class); + sut.findTrackedResourceByActorType(A, FakeActors.FakeActor2.class); final Optional resourceBWithSource1 = - sut.findTrackedResourceByActorType("B", FakeActors.FakeActor1.class); + sut.findTrackedResourceByActorType(B, FakeActors.FakeActor1.class); final Optional resourceBWithSource2 = - sut.findTrackedResourceByActorType("B", FakeActors.FakeActor2.class); + sut.findTrackedResourceByActorType(B, FakeActors.FakeActor2.class); assertThat(resourceAWithSource1).get().usingRecursiveComparison() .isEqualTo(new TrackedResource("Source1", 2));