Java tutorial
/* * BasePlugin * Copyright (C) 2014 Viciouss <http://www.doncarnage.de> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package de.doncarnage.minecraft.baseplugin.util; import com.google.common.base.Preconditions; import org.apache.commons.lang.StringUtils; import org.bukkit.Material; import org.bukkit.material.MaterialData; public class ItemUtil { private static final String ITEM_SPLITTER = ":"; private ItemUtil() { } /** * Returns the corresponding item for the given item and sub string. * * @param item the wanted item, e.g. log or step * @param sub the data byte of the material * @return a {@link MaterialData} instance reflecting this item */ @SuppressWarnings("deprecation") public static MaterialData getMaterialDataByString(String item, String sub) { Preconditions.checkNotNull(item); Material mat = Material.getMaterial(item.toUpperCase()); if (mat == null) { return null; } MaterialData matData = new MaterialData(mat); if (!StringUtils.isBlank(sub)) { try { matData.setData(Byte.parseByte(sub)); } catch (NumberFormatException nfe) { return null; } } return matData; } /** * Returns a MaterialData object of the given item string. * * @param item the item name as string * @return a {@link MaterialData} instance */ public static MaterialData getMaterialDataByString(String item) { Preconditions.checkNotNull(item); if (!item.contains(ITEM_SPLITTER)) { return getMaterialDataByString(item, null); } String[] block = item.split(ITEM_SPLITTER); if (block.length > 2) { return null; } else if (block.length == 2) { return ItemUtil.getMaterialDataByString(block[0], block[1]); } else if (block.length == 1) { return ItemUtil.getMaterialDataByString(block[0]); } return null; } /** * Returns the item string of a MaterialData object as string. * * @param md the {@link MaterialData} for which the string should be looked up * @return the string representing the {@link MaterialData} object */ @SuppressWarnings("deprecation") public static String getItemStringFromMaterialData(MaterialData md) { return String.format("%s%s", md.getItemType().name(), md.getData() != 0 ? ":" + Byte.toString(md.getData()) : ""); } }