net.minecraft.nbt.JsonToNBT Java Examples

The following examples show how to use net.minecraft.nbt.JsonToNBT. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OreDictUtil.java    From AgriCraft with MIT License 6 votes vote down vote up
@Nonnull
private static Optional<ItemStack> addNbtData(@Nonnull ItemStack stack, @Nullable String tags) {
    // Step 0. Validate.
    Preconditions.checkNotNull(stack, "The itemstack to add NBT data to may not be null");

    // Step 1. Abort if tags are null.
    if (Strings.isNullOrEmpty(tags)) {
        return Optional.of(stack);
    }

    // Step 2. Get the tag instance.
    final NBTTagCompound tag = StackHelper.getTag(stack);

    // Step 3. Parse the tags.
    try {
        final NBTTagCompound added = JsonToNBT.getTagFromJson(tags);
        tag.merge(added);
        stack.setTagCompound(tag);
        return Optional.of(stack);
    } catch (NBTException e) {
        AgriCore.getLogger("agricraft").error("Unable to parse NBT Data: \"{0}\".\nCause: {1}", tags, e);
        return Optional.empty();
    }
}
 
Example #2
Source File: WeightedRandomLoot.java    From minecraft-roguelike with GNU General Public License v3.0 6 votes vote down vote up
public WeightedRandomLoot(JsonObject json, int weight) throws Exception{

	this.name = json.get("name").getAsString();
	ResourceLocation location = new ResourceLocation(name);
	this.item = (Item) Item.REGISTRY.getObject(location);
	try{
		this.item.getUnlocalizedName();
	} catch (NullPointerException e){
		throw new Exception("Invalid item: " + this.name);
	}
	this.damage = json.has("meta") ? json.get("meta").getAsInt() : 0;
	this.weight = weight;
	this.enchLevel = json.has("ench") ? json.get("ench").getAsInt() : 0;

	if(json.has("min") && json.has("max")){
		min = json.get("min").getAsInt();
		max = json.get("max").getAsInt();	
	} else {
		min = 1;
		max = 1;
	}
	
	if(json.has("nbt")) this.nbt = JsonToNBT.getTagFromJson(json.get("nbt").getAsString());
	
}
 
Example #3
Source File: ItemUtils.java    From LiquidBounce with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Allows you to create a item using the item json
 *
 * @param itemArguments arguments of item
 * @return created item
 * @author MCModding4K
 */
public static ItemStack createItem(String itemArguments) {
    try {
        itemArguments = itemArguments.replace('&', 'ยง');
        Item item = new Item();
        String[] args = null;
        int i = 1;
        int j = 0;

        for (int mode = 0; mode <= Math.min(12, itemArguments.length() - 2); ++mode) {
            args = itemArguments.substring(mode).split(Pattern.quote(" "));
            ResourceLocation resourcelocation = new ResourceLocation(args[0]);
            item = Item.itemRegistry.getObject(resourcelocation);
            if (item != null)
                break;
        }

        if (item == null)
            return null;

        if (Objects.requireNonNull(args).length >= 2 && args[1].matches("\\d+"))
            i = Integer.parseInt(args[1]);
        if (args.length >= 3 && args[2].matches("\\d+"))
            j = Integer.parseInt(args[2]);

        ItemStack itemstack = new ItemStack(item, i, j);
        if (args.length >= 4) {
            StringBuilder NBT = new StringBuilder();
            for (int nbtcount = 3; nbtcount < args.length; ++nbtcount)
                NBT.append(" ").append(args[nbtcount]);
            itemstack.setTagCompound(JsonToNBT.getTagFromJson(NBT.toString()));
        }
        return itemstack;
    } catch (Exception exception) {
        exception.printStackTrace();
        return null;
    }
}
 
Example #4
Source File: CraftMagicNumbers.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ItemStack modifyItemStack(ItemStack stack, String arguments) {
    net.minecraft.item.ItemStack nmsStack = CraftItemStack.asNMSCopy(stack);

    try {
        nmsStack.setTagCompound((NBTTagCompound) JsonToNBT.getTagFromJson(arguments));
    } catch (NBTException ex) {
        Logger.getLogger(CraftMagicNumbers.class.getName()).log(Level.SEVERE, null, ex);
    }

    stack.setItemMeta(CraftItemStack.getItemMeta(nmsStack));

    return stack;
}
 
Example #5
Source File: Debug.java    From ehacks-pro with GNU General Public License v3.0 5 votes vote down vote up
public static NBTTagCompound jsonToNBT(String json) {
    NBTBase nbtTag = null;
    try {
        nbtTag = JsonToNBT.func_150315_a(json.replaceAll("'", "\""));
    } catch (Exception err) {
        return null;
    }
    return (NBTTagCompound) nbtTag;
}
 
Example #6
Source File: NBTTagCompoundDeserializer.java    From customstuff4 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public NBTTagCompound deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
    try
    {
        return JsonToNBT.getTagFromJson(json.getAsString());
    } catch (NBTException e)
    {
        e.printStackTrace();
    }

    throw new JsonParseException("Failed to parse nbt");
}
 
Example #7
Source File: CustomDropsHandler.java    From NewHorizonsCoreMod with GNU General Public License v3.0 5 votes vote down vote up
private boolean VerifyConfig(CustomDrops pDropListToCheck)
{
    boolean tSuccess = true;

    for (CustomDrops.CustomDrop X : pDropListToCheck.getCustomDrops())
    {
        for (CustomDrops.CustomDrop.Drop Y : X.getDrops())
        {
            if (ItemDescriptor.fromString(Y.getItemName()) == null)
            {
                _mLogger.error(String.format("In ItemDropID: [%s], can't find item [%s]", Y.getIdentifier(), Y.getItemName()));
                tSuccess = false;
            }

            if (Y.mTag != null && !Y.mTag.isEmpty())
            {
                try
                {
                    NBTTagCompound tNBT = (NBTTagCompound) JsonToNBT.func_150315_a(Y.mTag);
                    if (tNBT == null) {
                        tSuccess = false;
                    }
                }
                catch (Exception e)
                {
                    _mLogger.error(String.format("In ItemDropID: [%s], NBTTag is invalid", Y.getIdentifier()));
                    tSuccess = false;
                }
            }
        }
    }
    return tSuccess;
}
 
Example #8
Source File: SpawnPotential.java    From minecraft-roguelike with GNU General Public License v3.0 5 votes vote down vote up
public SpawnPotential(JsonObject entry) throws Exception{
	this.weight = entry.has("weight") ? entry.get("weight").getAsInt() : 1;
	if(!entry.has("name")){
		throw new Exception("Spawn potential missing name");
	}
	
	this.name = entry.get("name").getAsString();
	this.equip = entry.has("equip") ? entry.get("equip").getAsBoolean() : false;
	
	if(entry.has("nbt")){
		String metadata = entry.get("nbt").getAsString();
		this.nbt = JsonToNBT.getTagFromJson(metadata);
	}
}
 
Example #9
Source File: GiveCommand.java    From seppuku with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void exec(String input) {
    if (!this.clamp(input, 2)) {
        this.printUsage();
        return;
    }

    final Minecraft mc = Minecraft.getMinecraft();

    if (!mc.player.isCreative()) {
        Seppuku.INSTANCE.errorChat("Creative mode is required to use this command.");
        return;
    }

    final String[] split = input.split(" ");

    final Item item = this.findItem(split[1]);

    if(item != null) {
        int amount = 1;
        int meta = 0;

        if(split.length >= 3) {
            if(StringUtil.isInt(split[2])) {
                amount = Integer.parseInt(split[2]);
            }else{
                Seppuku.INSTANCE.errorChat("Unknown number " + "\247f\"" + split[2] + "\"");
            }
        }

        if(split.length >= 4) {
            if(StringUtil.isInt(split[3])) {
                meta = Integer.parseInt(split[3]);
            }else{
                Seppuku.INSTANCE.errorChat("Unknown number " + "\247f\"" + split[3] + "\"");
            }
        }

        final ItemStack itemStack = new ItemStack(item, amount, meta);

        if(split.length >= 5) {
            final String s = this.buildString(split, 4);

            try {
                itemStack.setTagCompound(JsonToNBT.getTagFromJson(s));
            } catch (NBTException e) {
                e.printStackTrace();
            }
        }

        final int slot = this.findEmptyhotbar();
        mc.player.connection.sendPacket(new CPacketCreativeInventoryAction(36 + (slot != -1 ? slot : mc.player.inventory.currentItem), itemStack));
        Seppuku.INSTANCE.logChat("Gave you " + amount + " " + itemStack.getDisplayName());
    }else{
        final ResourceLocation similar = this.findSimilarItem(split[1]);

        if(similar != null) {
            Seppuku.INSTANCE.errorChat("Unknown item " + "\247f\"" + split[1] + "\"");
            Seppuku.INSTANCE.logChat("Did you mean " + "\247c" + similar.getPath() + "\247f?");
        }
    }
}
 
Example #10
Source File: ConsoleInputGui.java    From ehacks-pro with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Draws the screen and all the components in it.
 */
@SuppressWarnings("unchecked")
@Override
public void drawScreen(int p_73863_1_, int p_73863_2_, float p_73863_3_) {
    drawRect(2, this.height - 14, this.width - 2, this.height - 2, Integer.MIN_VALUE);
    if (this.inputField.getText().length() == 0) {
        this.inputField.setText("/");
    }
    if (this.inputField.getText().charAt(0) != '/') {
        this.inputField.setText("/" + this.inputField.getText());
    }
    this.inputField.drawTextBox();
    IChatComponent ichatcomponent = EHacksGui.clickGui.consoleGui.getChatComponent(Mouse.getX(), Mouse.getY());

    if (ichatcomponent != null && ichatcomponent.getChatStyle().getChatHoverEvent() != null) {
        HoverEvent hoverevent = ichatcomponent.getChatStyle().getChatHoverEvent();

        if (null != hoverevent.getAction()) {
            switch (hoverevent.getAction()) {
                case SHOW_ITEM:
                    ItemStack itemstack = null;
                    try {
                        NBTBase nbtbase = JsonToNBT.func_150315_a(hoverevent.getValue().getUnformattedText());

                        if (nbtbase instanceof NBTTagCompound) {
                            itemstack = ItemStack.loadItemStackFromNBT((NBTTagCompound) nbtbase);
                        }
                    } catch (NBTException ignored) {
                    }
                    if (itemstack != null) {
                        this.renderToolTip(itemstack, p_73863_1_, p_73863_2_);
                    } else {
                        this.drawCreativeTabHoveringText(EnumChatFormatting.RED + "Invalid Item!", p_73863_1_, p_73863_2_);
                    }
                    break;
                case SHOW_TEXT:
                    this.func_146283_a(Splitter.on("\n").splitToList(hoverevent.getValue().getFormattedText()), p_73863_1_, p_73863_2_);
                    break;
                case SHOW_ACHIEVEMENT:
                    StatBase statbase = StatList.func_151177_a(hoverevent.getValue().getUnformattedText());
                    if (statbase != null) {
                        IChatComponent ichatcomponent1 = statbase.func_150951_e();
                        ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation("stats.tooltip.type." + (statbase.isAchievement() ? "achievement" : "statistic"));
                        chatcomponenttranslation.getChatStyle().setItalic(Boolean.TRUE);
                        String s = statbase instanceof Achievement ? ((Achievement) statbase).getDescription() : null;
                        ArrayList<String> arraylist = Lists.newArrayList(ichatcomponent1.getFormattedText(), chatcomponenttranslation.getFormattedText());

                        if (s != null) {
                            arraylist.addAll(this.fontRendererObj.listFormattedStringToWidth(s, 150));
                        }

                        this.func_146283_a(arraylist, p_73863_1_, p_73863_2_);
                    } else {
                        this.drawCreativeTabHoveringText(EnumChatFormatting.RED + "Invalid statistic/achievement!", p_73863_1_, p_73863_2_);
                    }
                    break;
                default:
                    break;
            }
        }

        GL11.glDisable(GL11.GL_LIGHTING);
    }

    super.drawScreen(p_73863_1_, p_73863_2_, p_73863_3_);
}