Java Code Examples for org.bukkit.inventory.meta.BookMeta#setTitle()

The following examples show how to use org.bukkit.inventory.meta.BookMeta#setTitle() . 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: LecternInteractListener.java    From ViaBackwards with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onLecternInteract(PlayerInteractEvent event) {
    Player player = event.getPlayer();
    if (!isOnPipe(player)) return;

    Block block = event.getClickedBlock();
    if (block == null || block.getType() != Material.LECTERN) return;

    Lectern lectern = (Lectern) block.getState();
    ItemStack book = lectern.getInventory().getItem(0);
    if (book == null) return;

    BookMeta meta = (BookMeta) book.getItemMeta();

    // Open a book with the text of the lectern's writable book
    ItemStack newBook = new ItemStack(Material.WRITTEN_BOOK);
    BookMeta newBookMeta = (BookMeta) newBook.getItemMeta();
    newBookMeta.setPages(meta.getPages());
    newBookMeta.setAuthor("an upsidedown person");
    newBookMeta.setTitle("buk");
    newBook.setItemMeta(newBookMeta);
    player.openBook(newBook);

    event.setCancelled(true);
}
 
Example 2
Source File: CustomBookOverlay.java    From CS-CoreLib with GNU General Public License v3.0 6 votes vote down vote up
public CustomBookOverlay(String title, String author, TellRawMessage... pages) {
	this.book = new ItemStack(Material.WRITTEN_BOOK);

	BookMeta meta = (BookMeta) this.book.getItemMeta();
	meta.setTitle(title);
	meta.setAuthor(author);

	for (TellRawMessage page: pages) {
		try {
			addPage(meta, page);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	this.book.setItemMeta(meta);
}
 
Example 3
Source File: CommandHandler.java    From NyaaUtils with MIT License 6 votes vote down vote up
@SubCommand(value = "setbooktitle", permission = "nu.setbook")
public void setbooktitle(CommandSender sender, Arguments args) {
    if (!(args.length() > 1)) {
        msg(sender, "manual.setbooktitle.usage");
        return;
    }
    String title = args.next();
    Player p = asPlayer(sender);
    title = ChatColor.translateAlternateColorCodes('&', title);

    ItemStack item = p.getInventory().getItemInMainHand();
    if (item == null || !item.getType().equals(Material.WRITTEN_BOOK)) {
        msg(sender, "user.setbook.no_book");
        return;
    }
    BookMeta meta = (BookMeta) item.getItemMeta();
    meta.setTitle(title);
    item.setItemMeta(meta);
    msg(sender, "user.setbook.success");
}
 
Example 4
Source File: KitParser.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public ItemStack parseBook(Element el) throws InvalidXMLException {
  ItemStack itemStack = parseItem(el, Material.WRITTEN_BOOK);
  BookMeta meta = (BookMeta) itemStack.getItemMeta();
  meta.setTitle(BukkitUtils.colorize(XMLUtils.getRequiredUniqueChild(el, "title").getText()));
  meta.setAuthor(BukkitUtils.colorize(XMLUtils.getRequiredUniqueChild(el, "author").getText()));

  Element elPages = el.getChild("pages");
  if (elPages != null) {
    for (Element elPage : elPages.getChildren("page")) {
      String text = elPage.getText();
      text = text.trim(); // Remove leading and trailing whitespace
      text =
          Pattern.compile("^[ \\t]+", Pattern.MULTILINE)
              .matcher(text)
              .replaceAll(""); // Remove indentation on each line
      text =
          Pattern.compile("^\\n", Pattern.MULTILINE)
              .matcher(text)
              .replaceAll(
                  " \n"); // Add a space to blank lines, otherwise they vanish for unknown reasons
      text = BukkitUtils.colorize(text); // Color codes
      meta.addPage(text);
    }
  }

  itemStack.setItemMeta(meta);
  return itemStack;
}
 
Example 5
Source File: MapPoll.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public void sendBook(MatchPlayer viewer, boolean forceOpen) {
  String title = ChatColor.GOLD + "" + ChatColor.BOLD;
  title += TextTranslations.translate("vote.title.map", viewer.getBukkit());

  ItemStack is = new ItemStack(Material.WRITTEN_BOOK);
  BookMeta meta = (BookMeta) is.getItemMeta();
  meta.setAuthor("PGM");
  meta.setTitle(title);

  TextComponent.Builder content = TextComponent.builder();
  content.append(TranslatableComponent.of("vote.header.map", TextColor.DARK_PURPLE));
  content.append(TextComponent.of("\n\n"));

  for (MapInfo pgmMap : votes.keySet()) content.append(getMapBookComponent(viewer, pgmMap));

  NMSHacks.setBookPages(
      meta, TextTranslations.toBaseComponent(content.build(), viewer.getBukkit()));
  is.setItemMeta(meta);

  ItemStack held = viewer.getInventory().getItemInHand();
  if (held.getType() != Material.WRITTEN_BOOK
      || !title.equals(((BookMeta) is.getItemMeta()).getTitle())) {
    viewer.getInventory().setHeldItemSlot(2);
  }
  viewer.getInventory().setItemInHand(is);

  if (forceOpen || viewer.getSettings().getValue(SettingKey.VOTE) == SettingValue.VOTE_ON)
    NMSHacks.openBook(is, viewer.getBukkit());
}
 
Example 6
Source File: BukkitUtils.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public static ItemStack generateBook(String title, String author, List<String> pages) {
    ItemStack stack = new ItemStack(Material.WRITTEN_BOOK);
    BookMeta meta = (BookMeta) factory.getItemMeta(Material.WRITTEN_BOOK);

    meta.setTitle(title);
    meta.setAuthor(author);
    meta.setPages(pages);

    stack.setItemMeta(meta);
    return stack;
}
 
Example 7
Source File: Spy.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onPlayerDeath(EntityDeathEvent event, ItemStack stack) {
	
	Player player = (Player)event.getEntity();
	Resident resident = CivGlobal.getResident(player);
	if (resident == null || !resident.hasTown()) {
		return;
	}
	
	
	ArrayList<String> bookout = MissionLogger.getMissionLogs(resident.getTown());
	
	ItemStack book = new ItemStack(Material.WRITTEN_BOOK, 1);
	BookMeta meta = (BookMeta) book.getItemMeta();
	ArrayList<String> lore = new ArrayList<String>();
	lore.add("Mission Report");
	meta.setAuthor("Mission Reports");
	meta.setTitle("Missions From "+resident.getTown().getName());
	
	String out = "";
	for (String str : bookout) {
		out += str+"\n";
	}
	BookUtil.paginate(meta, out);			

	
	meta.setLore(lore);
	book.setItemMeta(meta);
	player.getWorld().dropItem(player.getLocation(), book);
	
}
 
Example 8
Source File: SchematicUtil.java    From PlotMe-Core with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private void setTag(ItemStack is, ItemTag itemtag) {
    List<Ench> enchants = itemtag.getEnchants();
    //Integer repaircost = itemtag.getRepairCost();
    List<String> pages = itemtag.getPages();
    String author = itemtag.getAuthor();
    String title = itemtag.getTitle();
    Display display = itemtag.getDisplay();

    ItemMeta itemmeta = is.getItemMeta();

    if (display != null) {
        List<String> lores = display.getLore();
        String name = display.getName();

        itemmeta.setLore(lores);
        itemmeta.setDisplayName(name);
    }

    if (itemmeta instanceof BookMeta) {
        BookMeta bookmeta = (BookMeta) itemmeta;
        bookmeta.setAuthor(author);
        bookmeta.setTitle(title);
        bookmeta.setPages(pages);
    }

    if (itemmeta instanceof EnchantmentStorageMeta) {
        EnchantmentStorageMeta enchantmentstoragemeta = (EnchantmentStorageMeta) itemmeta;

        for (Ench enchant : enchants) {
            enchantmentstoragemeta.addEnchant(Enchantment.getById(enchant.getId()), enchant.getLvl(), true);
        }
    }

    is.setItemMeta(itemmeta);
}
 
Example 9
Source File: UtilsMc.java    From NBTEditor with GNU General Public License v3.0 5 votes vote down vote up
public static ItemStack newWrittenBook(String title, String author) {
	ItemStack book = new ItemStack(Material.WRITTEN_BOOK);
	BookMeta meta = (BookMeta) book.getItemMeta();
	meta.setTitle(title);
	meta.setAuthor(author);
	book.setItemMeta(meta);
	return book;
}
 
Example 10
Source File: ItemsFixModule.java    From ExploitFixer with GNU General Public License v3.0 4 votes vote down vote up
public ItemStack fixItem(final ItemStack itemStack) {
	final Material material = Material.getMaterial(itemStack.getType().name());
	final ItemMeta itemMeta = itemStack.getItemMeta(),
			newItemMeta = plugin.getServer().getItemFactory().getItemMeta(material);
	final int maxStackSize = getMaxStackSize();
	final short durability = itemStack.getDurability();

	if (itemStack.hasItemMeta()) {
		final Map<Enchantment, Integer> enchantments = itemStack.getEnchantments();
		final String displayName = itemMeta.getDisplayName();
		final List<String> lore = itemMeta.getLore();

		if (enchantLimit > -1) {
			for (final Enchantment enchantment : enchantments.keySet()) {
				final int level = enchantments.get(enchantment);

				if (level <= enchantLimit && level > -1) {
					newItemMeta.addEnchant(enchantment, level, true);
				}
			}
		}

		if (newItemMeta instanceof BookMeta) {
			final BookMeta bookMeta = (BookMeta) itemMeta;
			final BookMeta newBookMeta = (BookMeta) newItemMeta;

			newBookMeta.setTitle(bookMeta.getTitle());
			newBookMeta.setAuthor(bookMeta.getAuthor());
			newBookMeta.setPages(bookMeta.getPages());
		} else if (newItemMeta instanceof SkullMeta) {
			final SkullMeta skullMeta = (SkullMeta) itemMeta;
			final SkullMeta newSkullMeta = (SkullMeta) newItemMeta;

			newSkullMeta.setOwner(skullMeta.getOwner());
		}

		if (displayName != null && displayName.getBytes().length < 128) {
			newItemMeta.setDisplayName(displayName);
		}

		if (lore != null && lore.toString().getBytes().length < 1024) {
			newItemMeta.setLore(lore);
		}
	}

	if (maxStackSize > 0 && itemStack.getAmount() > maxStackSize) {
		itemStack.setAmount(maxStackSize);
	}

	itemStack.setType(material);
	itemStack.setItemMeta(newItemMeta);
	itemStack.setDurability(durability);

	return itemStack;
}
 
Example 11
Source File: GeneralCommands.java    From GlobalWarming with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Add an instructional booklet to a player's inventory
 * - Will prevent duplicates
 */
public static void getBooklet(GPlayer gPlayer) {
    Player onlinePlayer = gPlayer.getOnlinePlayer();
    if (onlinePlayer != null) {
        //Prevent duplicates:
        // - Note that empty inventory slots will be NULL
        boolean isDuplicate = false;
        PlayerInventory inventory = onlinePlayer.getInventory();
        for (ItemStack item : inventory.getContents()) {
            if (item != null &&
                    item.getType().equals(Material.WRITTEN_BOOK) &&
                    item.getItemMeta().getDisplayName().equals(Lang.WIKI_NAME.get())) {
                gPlayer.sendMsg(Lang.WIKI_ALREADYADDED);
                isDuplicate = true;
                break;
            }
        }

        //Add the booklet:
        if (!isDuplicate) {
            ItemStack wiki = new ItemStack(Material.WRITTEN_BOOK);
            final BookMeta meta = (BookMeta) wiki.getItemMeta();
            if (meta != null) {
                meta.setDisplayName(Lang.WIKI_NAME.get());
                meta.setAuthor(Lang.WIKI_AUTHOR.get());
                meta.setTitle(Lang.WIKI_LORE.get());
                meta.setPages(
                        Lang.WIKI_INTRODUCTION.get(),
                        Lang.WIKI_SCORES.get(),
                        Lang.WIKI_EFFECTS.get(),
                        Lang.WIKI_BOUNTY.get(),
                        Lang.WIKI_OTHER.get()
                        );

                //Create the book and add to inventory:
                wiki.setItemMeta(meta);
                if (onlinePlayer.getInventory().addItem(wiki).isEmpty()) {
                    //Added:
                    gPlayer.sendMsg(Lang.WIKI_ADDED);
                } else {
                    //Inventory full:
                    gPlayer.sendMsg(Lang.GENERIC_INVENTORYFULL);
                }
            }
        }
    }
}
 
Example 12
Source File: Items.java    From StaffPlus with GNU General Public License v3.0 4 votes vote down vote up
BookBuilder()
{
	meta = (BookMeta) itemStack.clone().getItemMeta();
	meta.setTitle(Strings.format("&lWritten Book"));
	meta.setAuthor("Hex Framework");
}
 
Example 13
Source File: Journal.java    From BetonQuest with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Generates the journal as ItemStack
 *
 * @return the journal ItemStack
 */
public ItemStack getAsItem() {
    // create the book with default title/author
    ItemStack item = new ItemStack(Material.WRITTEN_BOOK);
    BookMeta meta = (BookMeta) item.getItemMeta();
    meta.setTitle(Utils.format(Config.getMessage(lang, "journal_title")));
    meta.setAuthor(PlayerConverter.getPlayer(playerID).getName());
    List<String> lore = new ArrayList<>();
    lore.add(Utils.format(Config.getMessage(lang, "journal_lore")));
    meta.setLore(lore);
    // add main page and generate pages from texts
    List<String> finalList = new ArrayList<>();
    if (Config.getString("config.journal.one_entry_per_page").equalsIgnoreCase("false")) {
        String color = Config.getString("config.journal_colors.line");
        String separator = Config.parseMessage(playerID, "journal_separator", null);
        if (separator == null) {
            separator = "---------------";
        }
        String line = "\n§" + color + separator + "\n";

        if (Config.getString("config.journal.show_separator") != null &&
                Config.getString("config.journal.show_separator").equalsIgnoreCase("false")) {
            line = "\n";
        }

        StringBuilder stringBuilder = new StringBuilder();
        for (String entry : getText()) {
            stringBuilder.append(entry).append(line);
        }
        if (mainPage != null && mainPage.length() > 0) {
            if (Config.getString("config.journal.full_main_page").equalsIgnoreCase("true")) {
                finalList.addAll(Utils.pagesFromString(mainPage));
            } else {
                stringBuilder.insert(0, mainPage + line);
            }
        }
        String wholeString = stringBuilder.toString().trim();
        finalList.addAll(Utils.pagesFromString(wholeString));
    } else {
        if (mainPage != null && mainPage.length() > 0) {
            finalList.addAll(Utils.pagesFromString(mainPage));
        }
        finalList.addAll(getText());
    }
    if (finalList.size() > 0) {
        meta.setPages(Utils.multiLineColorCodes(finalList, "§" + Config.getString("config.journal_colors.line")));
    } else {
        meta.addPage("");
    }
    item.setItemMeta(meta);
    return item;
}
 
Example 14
Source File: MissionBook.java    From civcraft with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private static void performInvestigateTown(Player player, ConfigMission mission) throws CivException {
	
	Resident resident = CivGlobal.getResident(player);
	if (resident == null || !resident.hasTown()) {
		throw new CivException("Only residents of towns can perform spy missions.");
	}
	
	// Must be within enemy town borders.
	ChunkCoord coord = new ChunkCoord(player.getLocation());
	TownChunk tc = CivGlobal.getTownChunk(coord);
	
	if (tc == null || tc.getTown().getCiv() == resident.getTown().getCiv()) {
		throw new CivException("Must be in another civilization's town's borders.");
	}
	
	if(processMissionResult(player, tc.getTown(), mission)) {
		ItemStack book = new ItemStack(Material.WRITTEN_BOOK, 1);
		BookMeta meta = (BookMeta) book.getItemMeta();
		ArrayList<String> lore = new ArrayList<String>();
		lore.add("Mission Report");
		
		meta.setAuthor("Mission Reports");
		meta.setTitle("Investigate Town");
		
	//	ArrayList<String> out = new ArrayList<String>();
		String out = "";
		
		out += ChatColor.UNDERLINE+"Town:"+tc.getTown().getName()+"\n"+ChatColor.RESET;
		out += ChatColor.UNDERLINE+"Civ:"+tc.getTown().getCiv().getName()+"\n\n"+ChatColor.RESET;
		
		SimpleDateFormat sdf = new SimpleDateFormat("M/dd h:mm:ss a z");
		out += "Time: "+sdf.format(new Date())+"\n";
		out += ("Treasury: "+tc.getTown().getTreasury().getBalance()+"\n");
		out += ("Hammers: "+tc.getTown().getHammers().total+"\n");
		out += ("Culture: "+tc.getTown().getCulture().total+"\n");
		out += ("Growth: "+tc.getTown().getGrowth().total+"\n");
		out += ("Beakers(civ): "+tc.getTown().getBeakers().total+"\n");
		if (tc.getTown().getCiv().getResearchTech() != null) {
			out += ("Researching: "+tc.getTown().getCiv().getResearchTech().name+"\n");
		} else {
			out += ("Researching:Nothing"+"\n");
		}
		
		BookUtil.paginate(meta, out);
		
		out = ChatColor.UNDERLINE+"Upkeep Info\n\n"+ChatColor.RESET;
		try {
			out += "From Spread:"+tc.getTown().getSpreadUpkeep()+"\n";
			out += "From Structures:"+tc.getTown().getStructureUpkeep()+"\n";
			out += "Total:"+tc.getTown().getTotalUpkeep();
			BookUtil.paginate(meta, out);
		} catch (InvalidConfiguration e) {
			e.printStackTrace();
			throw new CivException("Internal configuration exception.");
		}
		
		
		meta.setLore(lore);
		book.setItemMeta(meta);
		
		HashMap<Integer, ItemStack> leftovers = player.getInventory().addItem(book);
		for (ItemStack stack : leftovers.values()) {
			player.getWorld().dropItem(player.getLocation(), stack);
		}
		
		player.updateInventory();
		
		CivMessage.sendSuccess(player, "Mission Accomplished");
	}
}
 
Example 15
Source File: BookOfSouls.java    From NBTEditor with GNU General Public License v3.0 4 votes vote down vote up
public void saveBook(boolean resetName) {
	BookMeta meta = (BookMeta) _book.getItemMeta();
	String entityName = EntityTypeMap.getSimpleName(_entityNbt.getEntityType());

	if (resetName) {
		meta.setDisplayName(_bosCustomItem.getName() + ChatColor.RESET + " - " + ChatColor.RED + entityName);
		meta.setTitle(_bosCustomItem.getName());
		meta.setAuthor(_author);
	}

	meta.setPages(new ArrayList<String>());

	StringBuilder sb = new StringBuilder();
	sb.append("This book contains the soul of a " + ChatColor.RED + ChatColor.BOLD + entityName + "\n\n");

	int x = 7;
	if (_entityNbt instanceof MinecartSpawnerNBT) {
		sb.append(ChatColor.BLACK + "Left-click a existing spawner to copy the entities and variables from the spawner, left-click while sneaking to copy them back to the spawner.");
		meta.addPage(sb.toString());
		sb = new StringBuilder();
		x = 11;
	} else if (_entityNbt instanceof FallingBlockNBT) {
		sb.append(ChatColor.BLACK + "Left-click a block while sneaking to copy block data.\n\n");
		x = 5;
	}

	for (NBTVariableContainer container : _entityNbt.getAllVariables()) {
		if (x == 1) {
			meta.addPage(sb.toString());
			sb = new StringBuilder();
			x = 11;
		}
		sb.append("" + ChatColor.DARK_PURPLE + ChatColor.ITALIC + container.getName() + ":\n");
		for (String name : container.getVariableNames()) {
			if (--x == 0) {
				meta.addPage(sb.toString());
				sb = new StringBuilder();
				x = 10;
			}
			String value = container.getVariable(name).get();
			sb.append("  " + ChatColor.DARK_BLUE + name + ": " + ChatColor.BLACK + (value != null ? value : ChatColor.ITALIC + "-") + "\n");
		}
	}
	meta.addPage(sb.toString());

	if (_entityNbt instanceof MobNBT) {
		MobNBT mob = (MobNBT) _entityNbt;
		sb = new StringBuilder();
		sb.append("" + ChatColor.DARK_PURPLE + ChatColor.BOLD + "Attributes:\n");
		Collection<Attribute> attributes = mob.getAttributes().values();
		if (attributes.size() == 0) {
			sb.append("  " + ChatColor.BLACK + ChatColor.ITALIC +"none\n");
		} else {
			x = 11;
			for (Attribute attribute : attributes) {
				if (x <= 3) {
					meta.addPage(sb.toString());
					sb = new StringBuilder();
					x = 11;
				}
				sb.append("" + ChatColor.DARK_PURPLE + ChatColor.ITALIC + attribute.getType().getName() + ":\n");
				sb.append("  " + ChatColor.DARK_BLUE + "Base: " + ChatColor.BLACK + attribute.getBase() + "\n");
				sb.append("  " + ChatColor.DARK_BLUE + "Modifiers:\n");
				x -= 3;
				List<Modifier> modifiers = attribute.getModifiers();
				if (modifiers.size() == 0) {
					sb.append("    " + ChatColor.BLACK + ChatColor.ITALIC +"none\n");
				} else {
					for (Modifier modifier : modifiers) {
						if (x <= 3) {
							meta.addPage(sb.toString());
							sb = new StringBuilder();
							x = 11;
						}
						sb.append("    " + ChatColor.RED + modifier.getName() + ChatColor.DARK_GREEN + " Op: " + ChatColor.BLACK + modifier.getOperation() + "\n");
						sb.append("      " + ChatColor.DARK_GREEN + "Amount: " + ChatColor.BLACK + modifier.getAmount() + "\n");
						x -= 3;
					}
				}
				sb.append("\n");
				--x;
			}
		}
		meta.addPage(sb.toString());
	}

	BookSerialize.saveToBook(meta, _entityNbt.serialize(), _dataTitle);
	meta.addPage("RandomId: " + Integer.toHexString((new Random()).nextInt()) + "\n\n\n"
			+ ChatColor.DARK_BLUE + ChatColor.BOLD + "      The END.");
	_book.setItemMeta(meta);
}