Skip to content

Commit

Permalink
bazaar module update
Browse files Browse the repository at this point in the history
+ added bazaar module storage limit
+ created array issue on JSONObject creation
  • Loading branch information
poyrazinan committed Oct 11, 2023
1 parent 69cdaa3 commit 0238d98
Show file tree
Hide file tree
Showing 7 changed files with 118 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -347,13 +347,18 @@ public static class WebStoreGui extends OkaeriConfig {
/**
* Bazaar gui object
*/
private BazaarGui bazaarGui = new BazaarGui();
private Bazaar bazaarGui = new Bazaar();

/**
* Bazaar gui arguments class
*/
@Getter @Setter
public static class BazaarGui extends OkaeriConfig {
public static class Bazaar extends OkaeriConfig {

/**
* return item message
*/
private String returnItemMessage = "{prefix} &cYou have reached max storage amount &4(%max_amount%) &creturned &4%amount% &citem.";

/**
* layout of gui
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,10 @@ public static class Bazaar extends OkaeriConfig {
* Server id of bazaar
*/
private int serverId = 1;

/**
* default storage size
*/
private int defaultStorageSize = 5;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import net.leaderos.plugin.bukkit.helpers.ChatUtil;
import net.leaderos.plugin.bukkit.helpers.ItemUtils;
import net.leaderos.plugin.bukkit.modules.bazaar.Bazaar;
import net.leaderos.plugin.bukkit.modules.bazaar.model.PlayerBazaar;
import net.leaderos.plugin.shared.model.request.PostRequest;
import net.leaderos.plugin.shared.module.auth.model.User;
import org.bukkit.Bukkit;
Expand All @@ -16,6 +17,7 @@
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;

Expand Down Expand Up @@ -51,23 +53,43 @@ public static void showGui(Player player) {
// With a virtual inventory to access items later on
Inventory inv = Bukkit.createInventory(null, InventoryType.CHEST);
gui.addElement(new GuiStorageElement('i', inv));
// Close action area (event)
gui.setCloseAction(close -> {

// Calculating storage amounts
int maxStorageAmount = PlayerBazaar.getStorageAmount(player);
int storedItemAmount = PlayerBazaar.getBazaarStorage(User.getUser(player.getName()).getId()).size();
int canStoreAmount = maxStorageAmount - storedItemAmount;
// Items which stored (airs included)
ItemStack[] items = inv.getContents();
String userId = User.getUser(player.getName()).getId();
int serverId = Bazaar.getServerId();

// If player maxed out storage limit items will be added to
// this list then gives back to player.
List<ItemStack> returnItems = new ArrayList<>();

// item loop
for (ItemStack item : items) {
// Checks if item is empty or null (can be AIR etc.)
if (item == null)
continue;
if (item.getType() == null)
continue;
if (item.getType().equals(Material.AIR))
continue;

// Calculates storage amount
if (canStoreAmount > 0)
canStoreAmount--;
// If maxed out then add items to temp array
else {
returnItems.add(item);
continue;
}
// Item info
String material = item.getType().name();
String name = (item.hasItemMeta() && item.getItemMeta().hasDisplayName()) ?
item.getItemMeta().getDisplayName() : material.toString();
item.getItemMeta().getDisplayName() : material;
String lore = (item.hasItemMeta() && item.getItemMeta().hasLore()) ?
String.join("\n", item.getItemMeta().getLore()) : null;
int amount = item.getAmount();
Expand Down Expand Up @@ -98,6 +120,7 @@ public static void showGui(Player player) {
body.put("serverID", serverId+"");
body.put("itemID", item.getType().name());

// Sends response
try {
PostRequest postItem = new PostRequest("bazaar/storages/" + userId + "/items", body);
if (postItem.getResponse().getResponseCode() == HttpURLConnection.HTTP_OK) {
Expand All @@ -109,6 +132,16 @@ public static void showGui(Player player) {
throw new RuntimeException(e);
}
}

// Gives items back to player
if (!returnItems.isEmpty()) {
PlayerInventory playerInventory = player.getInventory();
returnItems.forEach(playerInventory::addItem);
String returnMessage = Main.getInstance().getLangFile().getGui().getBazaarGui().getReturnItemMessage();
returnMessage = returnMessage.replace("%max_amount%", maxStorageAmount+"")
.replace("%amount%", returnItems.size()+"");
ChatUtil.sendMessage(player, returnMessage);
}
return false; // Don't go back to the previous GUI (true would automatically go back to the previously opened one)
});
gui.show(player);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import net.leaderos.plugin.bukkit.modules.bazaar.exception.CacheNotFoundException;
import net.leaderos.plugin.bukkit.modules.bazaar.model.PlayerBazaar;
import net.leaderos.plugin.shared.module.auth.model.User;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

Expand Down Expand Up @@ -62,9 +61,9 @@ public static void showGui(Player player) {
// Category group creator
GuiElementGroup bazaarGui = new GuiElementGroup('i');
if (!playerBazaarList.isEmpty())
playerBazaarList.stream().forEach(element -> bazaarGui.addElement(new DynamicGuiElement('s', (viewer)
playerBazaarList.stream().forEach(playerBazaarItem -> bazaarGui.addElement(new DynamicGuiElement('s', (viewer)
-> new StaticGuiElement('s',
element.getItem(),
playerBazaarItem.getItem(),
1,
click -> {
click.getEvent().setCancelled(true);
Expand All @@ -74,7 +73,7 @@ public static void showGui(Player player) {
String subtitleSuccess = ChatUtil.color(Main.getInstance().getLangFile().getGui().getBazaarGui().getWithdrawSuccessSubtitle());
String subtitleProgress = ChatUtil.color(Main.getInstance().getLangFile().getGui().getBazaarGui().getWithdrawProgressSubtitle());
player.sendTitle(title, subtitleProgress);
boolean withdrawStatus = element.withdrawItem(player);
boolean withdrawStatus = playerBazaarItem.withdrawItem(player);
// TODO Title edit
if (withdrawStatus)
player.sendTitle(title, subtitleSuccess);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,18 @@
import lombok.Setter;
import lombok.SneakyThrows;
import net.leaderos.plugin.Main;
import net.leaderos.plugin.bukkit.exceptions.RequestException;
import net.leaderos.plugin.bukkit.helpers.ChatUtil;
import net.leaderos.plugin.bukkit.helpers.ItemUtils;
import net.leaderos.plugin.bukkit.modules.bazaar.Bazaar;
import net.leaderos.plugin.shared.model.request.DeleteRequest;
import net.leaderos.plugin.shared.model.request.GetRequest;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.json.JSONArray;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.json.JSONObject;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
Expand Down Expand Up @@ -77,6 +76,8 @@ public ItemStack getItem() {
@SneakyThrows
public boolean withdrawItem(Player player) {
DeleteRequest deleteRequest = new DeleteRequest("bazaar/storage/" + getUserId() + "/items/" + getId());
// TODO Remove
Bukkit.broadcastMessage(deleteRequest.getResponse().getResponseCode() + "");
if (deleteRequest.getResponse().getResponseCode() == HttpURLConnection.HTTP_OK) {
ItemStack item = ItemUtils.fromBase64(getBase64());
player.getInventory().addItem(item);
Expand All @@ -93,17 +94,61 @@ public boolean withdrawItem(Player player) {
public static List<PlayerBazaar> getBazaarStorage(String userId) {
try {
int serverId = Bazaar.getServerId();
GetRequest getRequest = new GetRequest("bazaar/storages/" + userId + "/items");
// TODO Fix
//+ serverId);
GetRequest getRequest = new GetRequest("bazaar/storages/" + userId + "/items?serverID=" + serverId);
JSONObject response = getRequest.getResponse().getResponseMessage();
List<PlayerBazaar> playerBazaarList = new ArrayList<>();
// TODO NO ANY TEST HERE FIXXXXX!!
response.getJSONArray("test").forEach(bazaar -> playerBazaarList.add(new PlayerBazaar((JSONObject) bazaar, userId)));
response.getJSONArray("array").forEach(bazaar -> playerBazaarList.add(new PlayerBazaar((JSONObject) bazaar, userId)));
return playerBazaarList;
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<>();
}
}


/**
* How many item can player store to bazaar.
*
* @param player to check player perm
* @return amount of can add
*/
public static int getStorageAmount(Player player) {
String permissionPrefix = "bazaar.maxstorage.";
int defaultValue = Main.getInstance().getModulesFile().getBazaar().getDefaultStorageSize();
try {
if (player == null)
return defaultValue;
else {
List<Integer> lists = new ArrayList<>();
for (PermissionAttachmentInfo attachmentInfo : player.getEffectivePermissions()) {
if (attachmentInfo.getPermission().startsWith(permissionPrefix))
lists.add(Integer.parseInt(attachmentInfo.getPermission().substring(attachmentInfo.getPermission().lastIndexOf(".") +1)));
}
if (!lists.isEmpty())
defaultValue = lists.stream()
.filter(PlayerBazaar::isInteger)
.reduce(1, Integer::max);
}
return defaultValue;
}

catch(Exception e1) {
return defaultValue;
}
}

/**
* Checks the input is integer
*
* @param input of data
* @return status of int or not
*/
private static boolean isInteger(int input) {
try {
return input > 0;
} catch(NumberFormatException exception) {
return false;
}
}
}
20 changes: 14 additions & 6 deletions src/main/java/net/leaderos/plugin/shared/model/Request.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.bukkit.Bukkit;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
Expand Down Expand Up @@ -91,8 +92,7 @@ public Request(String api, Map<String, String> body, @NotNull RequestType type)
* @return JSONObject of response
* @throws IOException for reader errors
*/
@SneakyThrows
private JSONObject getStream(InputStream stream) {
private String getStream(InputStream stream) throws IOException {
// BufferedReader for read data
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder response = new StringBuilder();
Expand All @@ -102,21 +102,29 @@ private JSONObject getStream(InputStream stream) {
response.append(line);
}
reader.close();
return new JSONObject(response.toString());
return response.toString();
}

/**
* Gets response of request
*
* @return JSONObject of response
*/
@SneakyThrows
private JSONObject getResponseObj() {
JSONObject response;
String responseString = null;
try {
response = getStream(connection.getInputStream());
responseString = getStream(connection.getInputStream());
response = new JSONObject(responseString);
}
catch (JSONException jsonException) {
JSONArray jsonArray = new JSONArray(responseString);
response = new JSONObject();
response.put("array", jsonArray);
}
catch (Exception e) {
response = getStream(connection.getErrorStream());
catch (IOException e) {
response = new JSONObject(getStream(connection.getErrorStream()));
}
// BufferedReader for read dat
connection.disconnect();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class PostRequest extends Request {
* @throws IOException for HttpUrlConnection
* @throws RequestException for response errors
*/
public PostRequest(String api, Map<String, String> body) throws IOException, RequestException {
public PostRequest(String api, Map<String, String> body) throws IOException {
super(api, body, RequestType.POST);
}

Expand All @@ -34,7 +34,7 @@ public PostRequest(String api, Map<String, String> body) throws IOException, Req
* @throws IOException
* @throws RequestException
*/
public PostRequest(String api) throws IOException, RequestException {
public PostRequest(String api) throws IOException {
super(api, null, RequestType.POST);
}
}

0 comments on commit 0238d98

Please sign in to comment.