I know there are other questions like this but none that I could find are fully helpful to this case.
So basically on the line that says
getCommand("minealchemy").setExecutor(new Commands());
I get this error:
The constructor Commands() is undefined
Any help? When i put "null" in the () for Commands ... Commands(null)... then i get a NullPointerException error...
Here are all of my classes:
Main Class:
package me.zachbears27;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import me.zachbears27.utils.Commands;
public class Main extends JavaPlugin implements Listener {
#Override
public void onDisable() {
}
#Override
public void onEnable() {
getServer().getPluginManager().registerEvents(this, this);
registerConfig();
getCommand("minealchemy").setExecutor(new Commands());
}
public void registerConfig() {
saveDefaultConfig();
}
}
Commands Class:
package me.zachbears27.utils;
import java.io.File;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import me.zachbears27.utils.Methods;
import net.md_5.bungee.api.ChatColor;
public class Commands implements CommandExecutor {
private final Methods methods;
public Commands(Methods methods) {
this.methods = methods;
}
public boolean onCommand(CommandSender sender, Command label, String cmd, String[] args) {
Player p = (Player) sender;
if (cmd.equalsIgnoreCase("minealchemy")) {
if(args.length > 0) {
//Get File
File file = methods.getPlayerFile(p.getUniqueId());
FileConfiguration fileSettings = YamlConfiguration.loadConfiguration(file);
//Make Sure It's False
fileSettings.set("Enabled", false);
//Save Inventory
methods.savePlayerInv(p.getUniqueId(), p.getInventory().getContents());
//Clear It
p.getInventory().clear();
//Put In God Mode
p.setInvulnerable(true);
//Open Inventory
p.openWorkbench(p.getLocation(), true);
} else {
p.sendMessage(ChatColor.RED + "Incorrect Arguments... Please use \"start\" or \"list\".");
}
}
return true;
}
}
Methods Class:
package me.zachbears27.utils;
import java.io.File;
import java.util.ArrayList;
import java.util.UUID;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemStack;
import me.zachbears27.Main;
import net.md_5.bungee.api.ChatColor;
public class Methods {
private final Main plugin;
public Methods(Main plugin) {
this.plugin = plugin;
}
public ArrayList<String> getAllItems() {
ArrayList<String> allItems = new ArrayList<String>();
//Basics
String Air = ChatColor.GREEN + "Air" + ChatColor.RESET;
String Earth = ChatColor.GREEN + "Earth" + ChatColor.RESET;
String Fire = ChatColor.GREEN + "Fire" + ChatColor.RESET;
String Metal = ChatColor.GREEN + "Metal" + ChatColor.RESET;
String Water = ChatColor.GREEN + "Water" + ChatColor.RESET;
String Motion = ChatColor.GREEN + "Motion" + ChatColor.RESET;
String Big = ChatColor.GREEN + "Big" + ChatColor.RESET;
String Time = ChatColor.GREEN + "Time" + ChatColor.RESET;
String Small = ChatColor.GREEN + "Small" + ChatColor.RESET;
allItems.add(Air);
allItems.add(Earth);
allItems.add(Fire);
allItems.add(Metal);
allItems.add(Water);
allItems.add(Motion);
allItems.add(Big);
allItems.add(Time);
allItems.add(Small);
//Animals
String Cat = ChatColor.GOLD + "Cat" + ChatColor.RESET;
allItems.add(Cat);
return allItems;
}
public String addItems(String item1, String item2) {
String returnStatement = ChatColor.RED + "X";
if(item1.equals("Air") && item2.equals("Fire")) {
returnStatement = "Mist";
}
return returnStatement;
}
public File getPlayerFile(UUID playerUUID) {
//Creates The Player File
File playerFile = new File (plugin.getDataFolder() + File.separator + "Player Data", playerUUID + ".yml");
return playerFile;
}
public void savePlayerInv(UUID playerUUID, ItemStack[] inv) {
File playerFile = getPlayerFile(playerUUID);
FileConfiguration playerData = YamlConfiguration.loadConfiguration(playerFile);
playerData.set("SavedInventory", inv);
}
}
Change the .setExecutor(new Commands()) in the onEnable() function to
.setExecutor(new Commands(new Methods(this)))
Related
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
You said it's full code, so there is multiple issues :
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);
}
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);
}
}
You should not use GET request to update datas. The method POST is here.
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
I have a small demo app I followed on youtube https://www.youtube.com/watch?v=DrMmHTHTcCo
I have setup everything as instructed but it does not work.
here are the classes
AnnotationConfiguration.java
package com.milind.spring.event;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan("com.milind.spring.event")
public class AnnotationConfiguration
{
}
AnnotationMain.java
package com.milind.spring.event;
import java.util.logging.Logger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AnnotationMain
{
private static final Logger LOG = Logger
.getLogger(AnnotationMain.class.getName());
public static void main(String[] args)
{
LOG.info("main app started");
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
AnnotationConfiguration.class);
ctx.getBean(MessagePublisher.class).publishMessage();
LOG.info("End of main");
ctx.close();
}
}
MessageEvent.java
package com.milind.spring.event;
import java.util.Calendar;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
import org.springframework.context.ApplicationEvent;
public class MessageEvent extends ApplicationEvent
{
private static final Logger LOG = Logger
.getLogger(MessageEvent.class.getName());
private static final long serialVersionUID = -248303624330278824L;
private String message;
private static AtomicInteger messageCounter = new AtomicInteger();
public MessageEvent(Object source, String message)
{
super(source);
LOG.info("MessageEvent constructor: " + message);
this.message = generateMessage(message);
}
private String generateMessage(String message)
{
LOG.info("MessageEvent generateMessage: " + message);
StringBuilder sb = new StringBuilder();
sb.append("| INFO |").append(Calendar.getInstance().getTime())
.append("|").append("Message sequence: ")
.append(messageCounter.getAndIncrement()).append("|")
.append(message);
String string = sb.toString();
LOG.info("MessageEvent generateMessage: " + string);
return string;
}
#Override
public String toString()
{
return "MessageEvent [message=" + message + ", toString()="
+ super.toString() + "]";
}
}
MessageListener.java
package com.milind.spring.event;
import java.util.logging.Logger;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
#Component
public class MessageListener implements ApplicationListener<MessageEvent>
{
private static final Logger LOG = Logger
.getLogger(MessageListener.class.getName());
#Override
public void onApplicationEvent(MessageEvent event)
{
LOG.info("onApplicationEvent: " + event.toString());
System.out.println(event.getSource());
System.out.println(event.getTimestamp());
}
}
MessagePublisher.java
package com.milind.spring.event;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.stereotype.Component;
#Component
public class MessagePublisher implements ApplicationEventPublisherAware
{
private static final Logger LOG = Logger
.getLogger(MessagePublisher.class.getName());
private ApplicationEventPublisher applicationEventPublisher;
private static Map<Integer, String> messages = new HashMap<>();
static
{
LOG.info("static init");
messages.put(1, "Sample message 1");
messages.put(2, "Sample message 2");
messages.put(3, "Sample message 3");
messages.put(4, "Sample message 4");
messages.put(5, "Sample message 5");
}
#Override
public void setApplicationEventPublisher(
ApplicationEventPublisher applicationEventPublisher)
{
LOG.info("setApplicationEventPublisher");
this.applicationEventPublisher = applicationEventPublisher;
}
public void publishMessage()
{
LOG.info("publishMessage");
new SimpleAsyncTaskExecutor().execute(() ->
{
for (int i = 0; i < 5; ++i)
{
int id = new Random().nextInt(5);
String message = messages.get(++id);
LOG.info("publishMessage.run(): message=" + message);
MessageEvent event = new MessageEvent(this, message);
applicationEventPublisher.publishEvent(event);
LOG.info("publishMessage.run(): event=" + event);
}
});
}
}
I debugged the code, everything from the publishing the event works but the listener is not receiving the event. I introduced log messages everywhere but no luck. What am I missing?
It started working. Only change I did was removed the ctx.close() from AnnotationMain.main method.
I am developing some minecraft mod for 1.8.9.
What I'm trying to create is command that simply send message to sender.
here's the code for command class and main class
command class:
package happyandjust.happymod.commands;
import java.util.HashMap;
import java.util.List;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
public class Command extends CommandBase {
private HashMap<String, String> collection = new HashMap<String, String>();
#Override
public String getCommandName() {
return "collection";
}
#Override
public String getCommandUsage(ICommandSender sender) {
return "collection <enchant name>";
}
#Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
collection.put("harvesting", "Wheat Collection Level 2");
collection.put("cubism", "Pumpkin Collection Level 5");
if (args.length < 1) {
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "Usage: /collection [Enchant Name]"));
return;
}
if (args.length == 1) {
String enchant_name = args[0].toLowerCase();
String collec = collection.get(enchant_name);
if (collec == null) {
sender.addChatMessage(new ChatComponentText(
EnumChatFormatting.RED + enchant_name.toUpperCase() + " is not valid Enchant Name"));
return;
}
sender.addChatMessage(new ChatComponentText(
EnumChatFormatting.GREEN + enchant_name.toUpperCase() + " is at " + collection.get(enchant_name)));
}
}
#Override
public boolean canCommandSenderUseCommand(ICommandSender sender) {
return true;
}
}
main class:
package happyandjust.happymod.main;
import happyandjust.happymod.commands.Command;
import happyandjust.happymod.proxy.CommonProxy;
import happyandjust.happymod.util.Reference;
import net.minecraftforge.client.ClientCommandHandler;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
#Mod(modid = Reference.MOD_ID, name = Reference.NAME, version = Reference.VERSION)
public class HappyMod {
#Instance
public static HappyMod instance;
#SidedProxy(clientSide = Reference.CLIENT_PROXY_CLASS, serverSide = Reference.COMMON_PROXY_CLASS)
public static CommonProxy proxy;
#EventHandler
public static void preInit(FMLPostInitializationEvent e) {
}
#EventHandler
public static void init(FMLInitializationEvent e) {
ClientCommandHandler.instance.registerCommand(new Command());
}
#EventHandler
public static void postInit(FMLPostInitializationEvent e) {
}
}
It works fine in single player but if I went to the multi player server like hypixel.
It says "Unknown command"
I have no idea to do this
Can anyone help me to work this command in multi player server?
You need to override the getRequiredPermissionLevel() method from CommandBase for it to work on multiplayer.
#Override
public int getRequiredPermissionLevel() {
return 0;
}
I'm making a Custom Horse plugin and this is the first real plugin that I'm making so please excuse my messy code.
In one class (HorseSaddles) I have created 4 different saddles:
package io.github.bxnie.Items;
import java.util.ArrayList;
import org.bukkit.Material;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import net.md_5.bungee.api.ChatColor;
public class HorseSaddles implements Listener {
public void DonkeyHorse() {
ItemStack dhorse = new ItemStack(Material.SADDLE);
ItemMeta dhorsemeta = dhorse.getItemMeta();
dhorsemeta.setDisplayName(ChatColor.RED + "Donkey");
ArrayList<String> dhorselore = new ArrayList<String>();
dhorselore.add(ChatColor.DARK_GRAY + "1/4");
dhorselore.add(ChatColor.DARK_GRAY + "Right click to spawn your Donkey!");
dhorsemeta.setLore(dhorselore);
dhorse.setItemMeta(dhorsemeta);
}
public void BrownHorse() {
ItemStack brhorse = new ItemStack(Material.SADDLE);
ItemMeta brhorsemeta = brhorse.getItemMeta();
brhorsemeta.setDisplayName(ChatColor.RED + "Brown Horse");
ArrayList<String> brhorselore = new ArrayList<String>();
brhorselore.add(ChatColor.DARK_GRAY + "2/4");
brhorselore.add(ChatColor.DARK_GRAY + "Right click to spawn your Horse!");
brhorsemeta.setLore(brhorselore);
brhorse.setItemMeta(brhorsemeta);
}
public void BlackHorse() {
ItemStack blhorse = new ItemStack(Material.SADDLE);
ItemMeta blhorsemeta = blhorse.getItemMeta();
blhorsemeta.setDisplayName(ChatColor.BLACK + "Black" + ChatColor.RED + "Horse");
ArrayList<String> blhorselore = new ArrayList<String>();
blhorselore.add(ChatColor.DARK_GRAY + "3/4");
blhorselore.add(ChatColor.DARK_GRAY + "Right click to spawn your Horse!");
blhorsemeta.setLore(blhorselore);
blhorse.setItemMeta(blhorsemeta);
}
public void WhiteHorse() {
ItemStack whorse = new ItemStack(Material.SADDLE);
ItemMeta whorsemeta = whorse.getItemMeta();
whorsemeta.setDisplayName(ChatColor.WHITE + "White" + ChatColor.RED + "Horse");
ArrayList<String> whorselore = new ArrayList<String>();
whorselore.add(ChatColor.DARK_GRAY + "4/4");
whorselore.add(ChatColor.DARK_GRAY + "Right click to spawn your Horse!");
whorsemeta.setLore(whorselore);
whorse.setItemMeta(whorsemeta);
}
}
And in another class (SaddleCommands) I am attempting to create a command which will give the user that an that item if they have the correct permissions
package io.github.bxnie.commands;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import net.minecraft.server.v1_12_R1.CommandExecute;
public class SaddleCommands extends CommandExecute implements Listener, CommandExecutor{
public String cmd1 = "fhdonkey";
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] arg3) {
if (!(sender instanceof Player)) {
sender.sendMessage("Only players may execute this command!");
return true;
}
Player p = (Player) sender;
if(cmd.getName().equalsIgnoreCase(cmd1)) {
if (p.hasPermission("fh.donkey")) {
p.sendMessage("You Have Purchased a Donkey");
p.getInventory().addItem(...);
return true;
} else {
p.sendMessage("§cInsufficient Permission!");
return false;
}
}
return false;
}
}
where it says p.getInventory().addItem(...); i put in the 3dots as a placeholder as I don't know how to retrieve an item from another class.
Welcome to the forum :)
You created an Class HorseSaddles. In there you got 3 functions which create an ItemStack, without doing anything with the object. Simply just return the ItemStack object.
i created an minimalistic solution:
public class Horse {
// we create an function which returns an ItemStack
public ItemStack getBrownHorseItemStack() {
// Create the ItemStack Object
ItemStack horseItem = new Itemstack(Material.SADDLE);
// return our ItemStack Object
return horseItem;
}
}
class Saddle {
private Horse horse = new Horse();
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
// an CommandSender object is NOT always an Player Object. Normally we would check if sender is a Player Object
// We cast the CommandSender to an player
Player player = (Player) sender;
// check the command received
if (cmd.getName().equalsIgnoreCase("fhdonkey")) {
// horse.getBrownHorseItemStack() will return an ItemStack Object
player.getInventory().addItem(horse.getBrownHorseItemStack());
}
return false;
}
}
for more informations: Returning a Value from a Method
I am absolutely new to RIAK KV. I actually learn it in the university and have to write some Java Code to store 5000 datasets in an RIAK Cluster. So I started to code:
package main;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;
import java.util.Scanner;
import org.w3c.dom.NameList;
public class Product {
String artikelnummer;
String name;
String color;
Integer price;
String picture;
Integer max = 999;
String filepath = "./assets/products.txt";
ArrayList<String> productNames;
public Product() throws FileNotFoundException{
productNames = readFile(filepath);
name = randomName();
color = randomColor();
price = randomPrice(max);
picture = randomPic();
}
private String randomPic() {
String[] picNames = {"ikea0.jpg","ikea1.jpg","ikea2.jpg","ikea3.jpg","ikea4.jpg","ikea5.jpg","ikea6.jpg","ikea7.jpg","ikea8.jpg","ikea9.jpg"};
Random randPicIndex = new Random();
int randomPicIndex = randPicIndex.nextInt(9);
return picNames[randomPicIndex];
}
public Integer randomPrice(int max){
Random rand = new Random();
int randomNum = rand.nextInt(max);
price = randomNum;
return price;
}
public String randomColor(){
String[] colorArray = {"blue","red","yellow","magenta","green","black","white","cyan","purple","brown"};
Random randIndex = new Random();
int randomIndex = randIndex.nextInt(10);
int i = randomIndex;
color = colorArray[i];
return color;
}
public String randomName(){
Random randomName = new Random();
name = productNames.get(randomName.nextInt(productNames.size()));
return name;
}
public ArrayList<String> readFile(String filepath) throws FileNotFoundException {
Scanner scanner = new Scanner(new File(filepath));
ArrayList<String> nameList = new ArrayList<String>();
while (scanner.hasNextLine()){
nameList.add(scanner.nextLine());
}
scanner.close();
return nameList;
}
//Class for testing purposes
public void printProduct(){
System.out.println("Produktdatenblatt: Artikelnummer --> "+ artikelnummer + " " + name + " mit Farbe: " + color + " mit dem Preis: " + price + " ein Bild --> " + picture);
System.out.println("Hat funktioniert!!!");
}
}
Above you can see the code that contains the Product Class. To generate 500 products randomly and store this products in the KV Database of Rick i wrote following:
package main;
import io.netty.util.internal.shaded.org.jctools.queues.MessagePassingQueue.WaitStrategy;
import java.io.FileNotFoundException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.ExecutionException;
import com.basho.riak.client.api.RiakClient;
import com.basho.riak.client.api.annotations.RiakKey;
import com.basho.riak.client.api.annotations.RiakLinks;
import com.basho.riak.client.api.commands.kv.StoreValue;
import com.basho.riak.client.core.RiakCluster;
import com.basho.riak.client.core.RiakNode;
import com.basho.riak.client.core.query.Location;
import com.basho.riak.client.core.query.Namespace;
import com.basho.riak.client.core.query.RiakObject;
import com.basho.riak.client.core.query.links.RiakLink;
import com.basho.riak.client.core.util.BinaryValue;
public class ProductRiakCluster {
static String artikelnummer;
public static void main(String args[]) throws FileNotFoundException, UnknownHostException, ExecutionException, InterruptedException {
System.out.println("main-method started...");
System.out.println("Starting create RiakCluster...");
for (int i = 5000; i > 0; i--) {
dataGenerator(i);
RiakClient client = RiakClient.newClient(8087, "127.0.0.1");
System.out.println("RiakClient " + client);
RiakObject riakObj = new RiakObject();
System.out.println("RiakObjekt " + riakObj);
Namespace productsBucket = new Namespace("products");
System.out.println("Bucket " + productsBucket);
Location productObjectLocation = new Location(productsBucket, artikelnummer);
System.out.println("Location " + productObjectLocation);
StoreValue storeP = new StoreValue.Builder(riakObj).withLocation(productObjectLocation).build();
StoreValue.Response response = client.execute(storeP);
client.shutdown();
}
System.out.println("RiakCluster setup finished...");
}
public static class ProductPojo {
#RiakKey
public String artikelnummer;
public String name;
public String color;
public Integer price;
#RiakLinks
public Collection < RiakLink > picture = new ArrayList < RiakLink > ();
}
private static void dataGenerator(int i) {
System.out.println("Started DataGenerator...");
try {
artikelnummer = String.valueOf(i);
generateRandomProduct(artikelnummer);
} catch (FileNotFoundException e) {
System.out.println("File not found...");
e.printStackTrace();
}
}
private static void generateRandomProduct(String artikelnummer) throws FileNotFoundException {
System.out.println("Method <generateRandomProduct> is running..." + artikelnummer);
Product product = new Product();
ProductPojo propo = new ProductPojo();
propo.artikelnummer = artikelnummer;
propo.name = product.name;
propo.color = product.color;
propo.price = product.price;
propo.picture.add(new RiakLink("pictures", product.picture, "Produktbild"));
product.printProduct();
}
}
After I started this program the following error occurs:
RiakClient com.basho.riak.client.api.RiakClient#2096442d
RiakObjekt RiakObject{contentType: application/octet-stream, value: null, riakIndexes: null, links: null, userMeta: null, vtag: null, isDeleted: false, isModified: false, vclock: null, lastModified: 0}
Bucket {type: default, bucket: products}
Location {namespace: {type: default, bucket: products}, key: 1}
Exception in thread "main" shaded.com.google.protobuf.UninitializedMessageException: Message missing required fields: value
at shaded.com.google.protobuf.AbstractMessage$Builder.newUninitializedMessageException(AbstractMessage.java:372)
at shaded.com.basho.riak.protobuf.RiakKvPB$RpbContent$Builder.build(RiakKvPB.java:18352)
at com.basho.riak.client.core.converters.RiakObjectConverter.convert(RiakObjectConverter.java:198)
at com.basho.riak.client.core.operations.StoreOperation$Builder.withContent(StoreOperation.java:158)
at com.basho.riak.client.api.commands.kv.StoreValue.buildCoreOperation(StoreValue.java:151)
at com.basho.riak.client.api.commands.kv.StoreValue.buildCoreOperation(StoreValue.java:72)
at com.basho.riak.client.api.GenericRiakCommand.executeAsync(GenericRiakCommand.java:41)
at com.basho.riak.client.api.commands.kv.StoreValue.executeAsync(StoreValue.java:112)
at com.basho.riak.client.api.RiakCommand.execute(RiakCommand.java:91)
at com.basho.riak.client.api.RiakClient.execute(RiakClient.java:355)
at main.ProductRiakCluster.main(ProductRiakCluster.java:49)
My thoughts about this: I generate an "artikelnummer" but it doesn't occurs in the Pojo class and so the Pojo has a null value. But I have no solution how to fix this problem.
The problem is that you don't pass anything to RiakObject.
Return a generated instance of ProductPojo and save it in a variable, say productToSave.
Then, either call new StoreValue.Builder(productToSave), or use RiakObject as follows:
RiakObject riakObj = new RiakObject();
riakObj.setValue(BinaryValue.create(productToSave));
As a side note, your code suffers from a few programming issues, unfortunately. For examples, exchanging data between methods via a static member is not good. You also don't have to create and shutdown a client every time you need it - reuse one instance for all of your queries.