-1

I made java script, it save/load player inventory when he leave/join, but someting goes wrong(GET request dont send) here is classes.

InventorySync:

import com.google.gson.Gson;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.IOException;
import java.util.Arrays;
import java.util.Base64;
import java.util.UUID;

import InventoryGet.*;

public class InventorySync extends JavaPlugin implements Listener {
    String saveInv = "*correct url*";
    String loadInv = "*correct url*";
    Gson gson = new Gson();
    @EventHandler
    public void onJoin(PlayerJoinEvent event) throws IOException {
        Player player = event.getPlayer();
        UUID uuid = player.getUniqueId();
        //InventoryGet.main(loadInv + "?username=" + uuid.toString());
    }

    @EventHandler
    public void onQuit(PlayerQuitEvent event) throws IOException {
        Player player = event.getPlayer();
        UUID uuid = player.getUniqueId();
        Object[] contents = Arrays.stream(player.getInventory().getContents()).toArray();
        String inv = Base64.getEncoder().encodeToString( gson.toJson(contents).getBytes() );
        InventoryGet.main(saveInv + "?username=" + uuid.toString() + "&inventory=" + inv);
    }
}

InventoryGet:

package InventoryGet;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

public class InventoryGet {
    public static String main(String urlString) throws IOException {
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                Scanner scanner = new Scanner(connection.getInputStream());
                String response = scanner.useDelimiter("\\A").next();
                scanner.close();
                return response;
            } else {
                return "GET request failed with response code " + responseCode;
            }
        } catch (Exception e) {
            return "Exception occurred: " + e.getMessage();
        }
    }
}

The URL is correct.

For the PHP script:

Update inventory:

<?php
//Get player nickname
//check username for exist
if (!isset($_GET['username']))
{
    die();
} else { //username exist:
    $username = $_GET['username'];
}
//get player inventory(if exist)
if (!isset($_GET['inventory'])) {
    die();
} else { //decode inventory from base64:
    $inventory = base64_decode($_GET['inventory']);
} //save inventory to file
file_put_contents('inventory/' . $username . '.inv', $inventory);

Get inventory:

<?php
header("content-type: application/json");
//Get player nickname
//check username for exist
if (!isset($_GET['username'])) {
    die('[]');
} else { // username exist
    $username = $_GET['username'];
} 
if (file_exists('inventory/' . $username . '.inv')) { //find player's inventory if exists
    echo file_get_contents('inventory/' . $username . '.inv');
} else { //player file not found:
   echo '[]';
}

When player disconnect from server, server save his inventory, but server not do a GET request

Elikill58
  • 4,050
  • 24
  • 23
  • 45

1 Answers1

1

You said it's full code, so there is multiple issues :

  1. You are in the JavaPlugin class, and there isn't onEnable() method that register listener. So, you should add:
@Override
public void onEnable() {
   getServer().getPluginManager().registerEvents(this, this);
}
  1. I suggest you to create a new class for listeners, to have (I omitted import):
public class InventorySync extends JavaPlugin {
    
   @Override
   public void onEnable() {
      getServer().getPluginManager().registerEvents(new ConnectionListener(), this);
   }
}
public class ConnectionListener implements Listener {
    
   String saveInv = "*correct url*";
   String loadInv = "*correct url*";
   Gson gson = new Gson();
   @EventHandler
   public void onJoin(PlayerJoinEvent event) throws IOException {
        Player player = event.getPlayer();
        UUID uuid = player.getUniqueId();
        //InventoryGet.main(loadInv + "?username=" + uuid.toString());
   }

   @EventHandler
   public void onQuit(PlayerQuitEvent event) throws IOException {
        Player player = event.getPlayer();
        UUID uuid = player.getUniqueId();
        Object[] contents = Arrays.stream(player.getInventory().getContents()).toArray();
        String inv = Base64.getEncoder().encodeToString( gson.toJson(contents).getBytes() );
        InventoryGet.main(saveInv + "?username=" + uuid.toString() + "&inventory=" + inv);
   }
}
  1. You should not use GET request to update datas. The method POST is here.

  2. You are wrongly using gson according to Spigot API. You should use ItemStack#serialize and ItemStack#deserialize, like that:

@EventHandler
public void onJoin(PlayerJoinEvent event) throws IOException {
    Player player = event.getPlayer();
    UUID uuid = player.getUniqueId();
    String inv = main(loadInv + "?username=" + uuid.toString());
    List<Map<String, Object>> list = gson.fromJson(inv, List.class);
    list.stream().map(ItemStack::deserialize).forEach(it -> {
         // here you have items
    });
}

@EventHandler
public void onQuit(PlayerQuitEvent event) throws IOException {
    Player player = event.getPlayer();
    UUID uuid = player.getUniqueId();
    List<Map<String, Object>> contents = Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).map(ItemStack::serialize).collect(Collectors.toList());
    String inv = Base64.getEncoder().encodeToString(gson.toJson(contents).getBytes());
    main(saveInv + "?username=" + uuid.toString() + "&inventory=" + inv);
}

I added filter(Objects::nonNull) to prevent empty slot

Elikill58
  • 4,050
  • 24
  • 23
  • 45