answer
stringlengths
17
10.2M
package com.amee.platform.science; import org.apache.commons.lang.builder.ToStringBuilder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Holds a collection of {@link ReturnValue} objects added by Algorithms. * The first ReturnValue added is marked as the default but this may be changed by calling setDefaultType. * A list of Note objects may be added containing additional textual information about the ReturnValues. * * A new ReturnValues object is provided to each Algorithm. See: {@link AlgorithmRunner}. * * Note: if an algorithm is unable to calculate a result for a particular GHG null will be stored. * * Not thread-safe. * * TODO: Consider implementing Map interface. */ public class ReturnValues { /** The return values, indexed by GHG type. */ private Map<String, ReturnValue> returnValues = new HashMap<String, ReturnValue>(); /** The default GHG type. */ private String defaultType; /** Optional text notes. */ private List<Note> notes = new ArrayList<Note>(); public Map<String, ReturnValue> getReturnValues() { return returnValues; } /** * Add an amount to the return values. * * This method is called by algorithms. * * @param type the GHG type to add, eg 'CO2'. * @param unit the unit, eg 'kg'. * @param perUnit the per unit, eg 'month'. * @param value the value of the amount. */ public void putValue(String type, String unit, String perUnit, double value) { ReturnValue returnValue = new ReturnValue(type, unit, perUnit, value); returnValues.put(type, returnValue); // We make the first added amount the default. if (returnValues.size() == 1) { setDefaultType(type); } } /** * Add an empty amount to the return values. * * This method is called by algorithms when we cannot calculate a value for a certain type. * * @param type the GHG type to add, eg 'CH4'. */ public void putEmptyValue(String type) { returnValues.put(type, null); // We still make the first added amount the default even if null. if (returnValues.size() == 1) { setDefaultType(type); } } public void setDefaultType(String type) { if (returnValues.containsKey(type)) { defaultType = type; } else { throw new IllegalArgumentException("There are no values of type " + type); } } public String getDefaultType() { if (defaultType == null) { throw new IllegalStateException("There is no default type"); } return defaultType; } /** * Get the default value. * * @return the default ReturnValue. May return null. */ public ReturnValue getDefaultValue() { if (defaultType == null) { throw new IllegalStateException("There is no default type"); } if (!returnValues.containsKey(defaultType)) { throw new IllegalArgumentException("There are no values of type " + defaultType); } else { return returnValues.get(defaultType); } } public CO2Amount defaultValueAsAmount() { if (returnValues.isEmpty()) { return CO2Amount.ZERO; } if (defaultType == null) { throw new IllegalStateException("There is no default type"); } if (returnValues.get(defaultType) == null) { return CO2Amount.ZERO; } ReturnValue defaultValue = returnValues.get(defaultType); return defaultValue.toAmount(); } /** * Get the numeric value of the default ReturnValue. * * @return the value of the default Amount. */ public double defaultValueAsDouble() { if (defaultType == null) { throw new IllegalStateException("There is no default type"); } if (returnValues.get(defaultType) == null) { return 0.0; } else { return returnValues.get(defaultType).getValue(); } } /** * Add a text note. * * @param type the type of note, eg 'comment'. * @param value the value of the note. */ public void addNote(String type, String value) { notes.add(new Note(type, value)); } /** * Get the notes. * * @return the List of notes. */ public List<Note> getNotes() { return notes; } /** * Returns a string representation of this object. * * @return a String representation of this object. */ @Override public String toString() { return new ToStringBuilder(this). append("returnValues", returnValues). append("defaultType", defaultType). append("notes", notes). toString(); } public boolean hasReturnValues() { return !returnValues.isEmpty(); } /** * Returns the number of ReturnValues in this collection. * * @return the number of ReturnValues in this collection. */ public int size() { return returnValues.size(); } }
package com.assylias.jbloomberg; import com.bloomberglp.blpapi.Datetime; import com.bloomberglp.blpapi.Element; import com.bloomberglp.blpapi.ElementIterator; import com.bloomberglp.blpapi.Schema; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Calendar; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A utility class that should not be very useful for the users of the API. */ final class BloombergUtils { private final static Logger logger = LoggerFactory.getLogger(BloombergUtils.class); private static volatile boolean isBbcommStarted = false; private final static String BBCOMM_PROCESS = "bbcomm.exe"; private final static String BBCOMM_FOLDER = "C:/blp/API"; private BloombergUtils() { } /** * Transforms a Bloomberg Element into the most specific Object (for example: Double, Float, Integer, DateTime, * String etc.).<br> * Complex types are returned in the form of collections ({@code List<Object>} for arrays and * {@code Map<String, Object>} * for sequences). */ public static Object getSpecificObjectOf(Element field) { if (field.datatype() == Schema.Datatype.FLOAT64) { //likeliest data type return field.getValueAsFloat64(); } else if (field.datatype() == Schema.Datatype.FLOAT32) { return field.getValueAsFloat32(); } else if (field.datatype() == Schema.Datatype.BOOL) { return field.getValueAsBool(); } else if (field.datatype() == Schema.Datatype.CHAR) { return field.getValueAsChar(); } else if (field.datatype() == Schema.Datatype.INT32) { return field.getValueAsInt32(); } else if (field.datatype() == Schema.Datatype.INT64) { return field.getValueAsInt64(); } else if (field.datatype() == Schema.Datatype.STRING) { return field.getValueAsString(); } else if (field.datatype() == Schema.Datatype.DATE) { Datetime dt = field.getValueAsDate(); return LocalDate.of(dt.year(), dt.month(), dt.dayOfMonth()); } else if (field.datatype() == Schema.Datatype.TIME) { Datetime dt = field.getValueAsDatetime(); Calendar cal = dt.calendar(); //returns a calendar with TZ = UTC return LocalTime.of(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND), dt.nanosecond()); } else if (field.datatype() == Schema.Datatype.DATETIME) { Datetime dt = field.getValueAsDatetime(); Calendar cal = dt.calendar(); //returns a calendar with TZ = UTC ZonedDateTime zdt = ZonedDateTime.ofInstant(cal.toInstant(), ZoneId.of("Z")); if (!dt.hasParts(Datetime.DATE)) return zdt.toLocalTime(); else return zdt; } else if (field.isArray()) { List<Object> list = new ArrayList<>(field.numValues()); for (int i = 0; i < field.numValues(); i++) { list.add(getSpecificObjectOf(field.getValueAsElement(i))); } return list; } else if (field.datatype() == Schema.Datatype.SEQUENCE || field.datatype() == Schema.Datatype.CHOICE) { //has to be after array because arrays are sequences... ElementIterator it = field.elementIterator(); Map<String, Object> map = new LinkedHashMap<>(field.numElements(), 1.0f); while (it.hasNext()) { Element e = it.next(); map.put(e.name().toString(), getSpecificObjectOf(e)); } return map; } else { return field.toString(); //always works } } /** * Starts the bbcomm process if necessary, which is required to connect to the Bloomberg data feed.<br> * This method will block up to one second if it needs to manually start the process. If the process is not * started by the end of the timeout, this method will return false but the process might start later on. * <p/> * @return true if bbcomm was started successfully within one second, false otherwise. */ public static boolean startBloombergProcessIfNecessary() { return isBbcommStarted || isBloombergProcessRunning() || startBloombergProcess(); } /** * * @return true if the bbcomm process is running */ private static boolean isBloombergProcessRunning() { if (ShellUtils.isProcessRunning(BBCOMM_PROCESS)) { logger.info("{} is started", BBCOMM_PROCESS); return true; } return false; } private static boolean startBloombergProcess() { Callable<Boolean> startBloombergProcess = BloombergUtils::getStartingCallable; isBbcommStarted = getResultWithTimeout(startBloombergProcess, 1, TimeUnit.SECONDS); return isBbcommStarted; } private static Boolean getStartingCallable() throws Exception { logger.info("Starting {} manually", BBCOMM_PROCESS); ProcessBuilder pb = new ProcessBuilder(BBCOMM_PROCESS); pb.directory(new File(BBCOMM_FOLDER)); pb.redirectErrorStream(true); Process p = pb.start(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.forName("UTF-8")))) { String line; while ((line = reader.readLine()) != null) { logger.info("{} > {}", BBCOMM_PROCESS, line); if (line.toLowerCase().contains("started")) { logger.info("{} is started", BBCOMM_PROCESS); return true; } } return false; } } private static boolean getResultWithTimeout(Callable<Boolean> startBloombergProcess, int timeout, TimeUnit timeUnit) { ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, "Bloomberg - bbcomm starter thread"); t.setDaemon(true); return t; } }); Future<Boolean> future = executor.submit(startBloombergProcess); try { return future.get(timeout, timeUnit); } catch (InterruptedException ignore) { Thread.currentThread().interrupt(); return false; } catch (ExecutionException | TimeoutException e) { logger.error("Could not start bbcomm", e); return false; } finally { executor.shutdownNow(); try { if (!executor.awaitTermination(100, TimeUnit.MILLISECONDS)) { logger.warn("bbcomm starter thread still running"); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } }
package com.avairebot.orion.audio; import com.avairebot.orion.factories.MessageFactory; import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler; import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager; import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager; import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers; import com.sedmelluq.discord.lavaplayer.tools.FriendlyException; import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.VoiceChannel; import net.dv8tion.jda.core.managers.AudioManager; import java.util.HashMap; import java.util.Map; public class AudioHandler { private static final AudioPlayerManager AUDIO_PLAYER_MANAGER; private static final Map<Long, GuildMusicManager> MUSIC_MANAGER; static { MUSIC_MANAGER = new HashMap<>(); AUDIO_PLAYER_MANAGER = new DefaultAudioPlayerManager(); AudioSourceManagers.registerRemoteSources(AUDIO_PLAYER_MANAGER); AudioSourceManagers.registerLocalSource(AUDIO_PLAYER_MANAGER); } public static void loadAndPlay(final Message message, final String trackUrl) { GuildMusicManager musicManager = getGuildAudioPlayer(message.getGuild()); musicManager.setLastActiveMessage(message); AUDIO_PLAYER_MANAGER.loadItemOrdered(musicManager, trackUrl, new AudioLoadResultHandler() { @Override public void trackLoaded(AudioTrack track) { if (musicManager.getPlayer().getPlayingTrack() != null) { MessageFactory.makeSuccess(message, "<@%s> has added [%s](%s) to the queue. There are `%s` song(s) ahead of it in the queue.", message.getAuthor().getId(), track.getInfo().title, track.getInfo().uri, getQueueSize(musicManager) ).queue(); } play(message, musicManager, track); } @Override public void playlistLoaded(AudioPlaylist playlist) { MessageFactory.makeSuccess(message, "<@%s> has added %s songs from the [%s](%s) playlist to the queue. There are `%s` song(s) ahead of it in the queue.", message.getAuthor().getId(), playlist.getTracks().size(), playlist.getName(), trackUrl, getQueueSize(musicManager) ).queue(); for (AudioTrack track : playlist.getTracks()) { play(message, musicManager, track); } } @Override public void noMatches() { MessageFactory.makeWarning(message, "I found nothing with the given query `%s`", trackUrl).queue(); } @Override public void loadFailed(FriendlyException exception) { MessageFactory.makeError(message, "I couldn't add that to the queue: %s", exception.getMessage()).queue(); } }); } public static void skipTrack(Message message) { GuildMusicManager musicManager = getGuildAudioPlayer(message.getGuild()); musicManager.scheduler.nextTrack(); } private static void play(Message message, GuildMusicManager musicManager, AudioTrack track) { connectToFirstVoiceChannel(message.getGuild().getAudioManager()); musicManager.scheduler.queue(track, message.getAuthor()); } private static void connectToFirstVoiceChannel(AudioManager audioManager) { if (!audioManager.isConnected() && !audioManager.isAttemptingToConnect()) { for (VoiceChannel voiceChannel : audioManager.getGuild().getVoiceChannels()) { audioManager.openAudioConnection(voiceChannel); break; } } } private static synchronized GuildMusicManager getGuildAudioPlayer(Guild guild) { long guildId = Long.parseLong(guild.getId()); GuildMusicManager musicManager = MUSIC_MANAGER.get(guildId); if (musicManager == null) { musicManager = new GuildMusicManager(AUDIO_PLAYER_MANAGER); MUSIC_MANAGER.put(guildId, musicManager); } guild.getAudioManager().setSendingHandler(musicManager.getSendHandler()); return musicManager; } private static int getQueueSize(GuildMusicManager manager) { return manager.getPlayer().getPlayingTrack() == null ? manager.scheduler.getQueue().size() : manager.scheduler.getQueue().size() + 1; } }
package com.choonster.testmod3.item; import com.choonster.testmod3.TestMod3; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntityArrow; import net.minecraft.init.Enchantments; import net.minecraft.init.Items; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemArrow; import net.minecraft.item.ItemBow; import net.minecraft.item.ItemStack; import net.minecraft.stats.StatList; import net.minecraft.util.*; import net.minecraft.world.World; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandlerModifiable; import net.minecraftforge.items.ItemStackHandler; import net.minecraftforge.items.wrapper.PlayerOffhandInvWrapper; import net.minecraftforge.items.wrapper.RangedWrapper; import java.util.function.Predicate; public class ItemModBow extends ItemBow { public ItemModBow(String itemName) { ItemTestMod3.setItemName(this, itemName); setCreativeTab(TestMod3.creativeTab); // ItemBow's "pull" getter only works for Items.bow, so register a custom getter that works for any instance of this class. addPropertyOverride(new ResourceLocation(TestMod3.MODID, "pull"), IItemPropertyGetterFix.create((stack, worldIn, entityIn) -> { if (entityIn == null) return 0.0f; ItemStack activeItemStack = entityIn.getActiveItemStack(); if (activeItemStack != null && activeItemStack.getItem() instanceof ItemModBow) { return (stack.getMaxItemUseDuration() - entityIn.getItemInUseCount()) / 20.0f; } return 0.0f; }) ); } /** * Get an {@link IItemHandler} wrapper of the first slot in the player's inventory containing an {@link ItemStack} of ammunition. * <p> * This {@link IItemHandler} will always have a single slot containing the ammunition {@link ItemStack}. * <p> * Adapted from {@link ItemBow#findAmmo(EntityPlayer)}. * * @param player The player * @param isAmmo A function that detects whether a given ItemStack is valid ammunition * @return The ammunition slot's IItemHandler, or null if there isn't any ammunition */ public static IItemHandler findAmmoSlot(EntityPlayer player, Predicate<ItemStack> isAmmo) { if (isAmmo.test(player.getHeldItemOffhand())) { return new PlayerOffhandInvWrapper(player.inventory); } // Vertical facing = main inventory final EnumFacing mainInventoryFacing = EnumFacing.UP; if (player.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, mainInventoryFacing)) { final IItemHandler mainInventory = player.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, mainInventoryFacing); if (isAmmo.test(player.getHeldItemMainhand())) { final int currentItem = player.inventory.currentItem; return new RangedWrapper((IItemHandlerModifiable) mainInventory, currentItem, currentItem + 1); } for (int slot = 0; slot < mainInventory.getSlots(); ++slot) { final ItemStack itemStack = mainInventory.getStackInSlot(slot); if (isAmmo.test(itemStack)) { return new RangedWrapper((IItemHandlerModifiable) mainInventory, slot, slot + 1); } } } return null; } /** * Is ammunition required to fire this bow? * * @param bow The bow * @param shooter The shooter * @return Is ammunition required? */ protected boolean isAmmoRequired(ItemStack bow, EntityPlayer shooter) { return !shooter.capabilities.isCreativeMode && EnchantmentHelper.getEnchantmentLevel(Enchantments.infinity, bow) == 0; } /** * Nock an arrow. * * @param bow The bow ItemStack * @param shooter The player shooting the bow * @param world The World * @param hand The hand holding the bow * @return The result */ protected ActionResult<ItemStack> nockArrow(ItemStack bow, World world, EntityPlayer shooter, EnumHand hand) { boolean hasAmmo = findAmmoSlot(shooter, this::isArrow) != null; ActionResult<ItemStack> ret = ForgeEventFactory.onArrowNock(bow, world, shooter, hand, hasAmmo); if (ret != null) return ret; if (isAmmoRequired(bow, shooter) && !hasAmmo) { return new ActionResult<>(EnumActionResult.FAIL, bow); } else { shooter.setActiveHand(hand); return new ActionResult<>(EnumActionResult.SUCCESS, bow); } } /** * Fire an arrow with the specified charge. * * @param bow The bow ItemStack * @param world The firing player's World * @param shooter The player firing the bow * @param charge The charge of the arrow */ protected void fireArrow(ItemStack bow, World world, EntityLivingBase shooter, int charge) { if (!(shooter instanceof EntityPlayer)) return; final EntityPlayer player = (EntityPlayer) shooter; final boolean ammoRequired = isAmmoRequired(bow, player); IItemHandler ammoSlot = findAmmoSlot(player, this::isArrow); charge = ForgeEventFactory.onArrowLoose(bow, world, player, charge, ammoSlot != null || !ammoRequired); if (charge < 0) return; if (ammoSlot != null || !ammoRequired) { if (ammoSlot == null) { ammoSlot = new ItemStackHandler(new ItemStack[]{new ItemStack(Items.arrow)}); } final ItemStack ammo = ammoSlot.getStackInSlot(0); final float arrowVelocity = getArrowVelocity(charge); if (arrowVelocity >= 0.1) { final boolean consumeAmmo = ammoRequired && ammo.getItem() instanceof ItemArrow; if (!world.isRemote) { final ItemArrow itemArrow = (ItemArrow) (ammo.getItem() instanceof ItemArrow ? ammo.getItem() : Items.arrow); final EntityArrow entityArrow = itemArrow.createArrow(world, ammo, player); entityArrow.func_184547_a(player, player.rotationPitch, player.rotationYaw, 0.0F, arrowVelocity * 3.0F, 1.0F); if (arrowVelocity == 1.0f) { entityArrow.setIsCritical(true); } final int powerLevel = EnchantmentHelper.getEnchantmentLevel(Enchantments.power, bow); if (powerLevel > 0) { entityArrow.setDamage(entityArrow.getDamage() + (double) powerLevel * 0.5D + 0.5D); } final int punchLevel = EnchantmentHelper.getEnchantmentLevel(Enchantments.punch, bow); if (punchLevel > 0) { entityArrow.setKnockbackStrength(punchLevel); } if (EnchantmentHelper.getEnchantmentLevel(Enchantments.flame, bow) > 0) { entityArrow.setFire(100); } bow.damageItem(1, player); if (!consumeAmmo) { entityArrow.canBePickedUp = EntityArrow.PickupStatus.CREATIVE_ONLY; } world.spawnEntityInWorld(entityArrow); } world.playSound(null, player.posX, player.posY, player.posZ, SoundEvents.entity_arrow_shoot, SoundCategory.NEUTRAL, 1.0F, 1.0F / (itemRand.nextFloat() * 0.4F + 1.2F) + arrowVelocity * 0.5F); if (consumeAmmo && ammoSlot.extractItem(0, 1, true) != null) { ammoSlot.extractItem(0, 1, false); } player.addStat(StatList.getObjectUseStats(this)); } } } @Override public void onPlayerStoppedUsing(ItemStack stack, World worldIn, EntityLivingBase entityLiving, int timeLeft) { int charge = this.getMaxItemUseDuration(stack) - timeLeft; fireArrow(stack, worldIn, entityLiving, charge); } @Override public ActionResult<ItemStack> onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { return nockArrow(itemStackIn, worldIn, playerIn, hand); } }
package com.crawljax.browser; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.ElementNotVisibleException; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.RenderedWebElement; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.crawljax.core.CrawljaxException; import com.crawljax.core.state.Eventable; import com.crawljax.util.Helper; import com.crawljax.util.PropertyHelper; /** * @author mesbah * @version $Id$ */ public abstract class AbstractWebDriver implements EmbeddedBrowser { private static Logger logger = Logger.getLogger(WebDriver.class.getName()); private WebDriver browser; /** * @param browser * the browser to set */ protected void setBrowser(WebDriver browser) { this.browser = browser; } /** * Public constructor. * * @param logger * the log4j logger. */ public AbstractWebDriver(Logger logger) { AbstractWebDriver.logger = logger; } /** * Constructor. * * @param driver * The WebDriver to use. */ public AbstractWebDriver(WebDriver driver) { this.browser = driver; } /** * @param url * The URL. * @throws InterruptedException * @throws CrawljaxException * if fails. */ public void goToUrl(String url) throws CrawljaxException { browser.navigate().to(url); handlePopups(); try { Thread.sleep(PropertyHelper.getCrawlWaitReloadValue()); } catch (InterruptedException e) { throw new CrawljaxException(e.getMessage(), e); } } /** * alert, prompt, and confirm behave as if the OK button is always clicked. */ private void handlePopups() { executeJavaScript("window.alert = function(msg){return true;};" + "window.confirm = function(msg){return true;};" + "window.prompt = function(msg){return true;};"); } /** * Fires the event and waits for a specified time. * * @param webElement * @param eventable * The HTML event type (onclick, onmouseover, ...). * @throws Exception * if fails. */ private boolean fireEventWait(WebElement webElement, Eventable eventable) throws CrawljaxException { String eventType = eventable.getEventType(); if ("onclick".equals(eventType)) { try { webElement.click(); } catch (ElementNotVisibleException e1) { logger.info("Element not visible, so cannot be clicked: " + webElement.getTagName().toUpperCase() + " " + webElement.getText()); return false; } catch (Exception e) { logger.error(e.getMessage()); return false; } } else { logger.info("EventType " + eventType + " not supported in WebDriver."); } try { Thread.sleep(PropertyHelper.getCrawlWaitEventValue()); } catch (InterruptedException e) { throw new CrawljaxException(e.getMessage(), e); } return true; } /** * @see EmbeddedBrowser#close() */ public void close() { logger.info("Closing the browser..."); // close browser and close every associated window. browser.quit(); } /** * @return a string representation of the borser's DOM. * @throws CrawljaxException * if fails. * @see com.crawljax.browser.EmbeddedBrowser#getDom() */ public String getDom() throws CrawljaxException { try { return toUniformDOM(Helper.getDocumentToString(getDomTreeWithFrames())); } catch (Exception e) { throw new CrawljaxException(e.getMessage(), e); } } /** * @param html * The html string. * @return uniform version of dom with predefined attributes stripped * @throws Exception * On error. */ private static String toUniformDOM(String html) throws Exception { Pattern p = Pattern.compile("<SCRIPT(.*?)</SCRIPT>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(html); String htmlFormatted = m.replaceAll(""); p = Pattern.compile("<\\?xml:(.*?)>"); m = p.matcher(html); htmlFormatted = m.replaceAll(""); // html = html.replace("<?xml:namespace prefix = gwt >", ""); Document doc = Helper.getDocument(htmlFormatted); htmlFormatted = Helper.getDocumentToString(doc); htmlFormatted = Helper.filterAttributes(htmlFormatted); return htmlFormatted; } /** * @see com.crawljax.browser.EmbeddedBrowser#goBack() */ public void goBack() { browser.navigate().back(); } /** * @return true if succeeds. * @see com.crawljax.browser.EmbeddedBrowser#canGoBack() */ public boolean canGoBack() { // NOT IMPLEMENTED return false; } /** * @param clickable * The clickable object. * @param text * The input. * @return true if succeeds. */ public boolean input(Eventable clickable, String text) { WebElement field = browser.findElement(clickable.getIdentification().getWebDriverBy()); if (field != null) { field.sendKeys(text); // this.activeElement = field; return true; } return false; } /** * Fires an event on an element using its identification. * * @param eventable * The eventable. * @return true if it is able to fire the event successfully on the element. * @throws CrawljaxException * On failure. */ public synchronized boolean fireEvent(Eventable eventable) throws CrawljaxException { try { String handle = browser.getWindowHandle(); boolean result = false; if (eventable.getRelatedFrame() != null && !eventable.getRelatedFrame().equals("")) { browser.switchTo().frame(eventable.getRelatedFrame()); } WebElement webElement = browser.findElement(eventable.getIdentification().getWebDriverBy()); if (webElement != null) { result = fireEventWait(webElement, eventable); } browser.switchTo().window(handle); return result; } catch (NoSuchElementException e) { logger.info("Could not fire eventable: " + eventable.toString()); return false; } catch (RuntimeException e) { logger.error("Caught Exception: " + e.getMessage(), e); return false; } } /** * @return the browser instance. */ public WebDriver getBrowser() { return browser; } /** * Execute JavaScript in the browser. * * @param code * The code to execute. * @return The return value of the JavaScript. */ public Object executeJavaScript(String code) { JavascriptExecutor js = (JavascriptExecutor) browser; return js.executeScript(code); } /** * Determines whether locater is visible. * * @param locater * The element to search for. * @return Whether it is visible. */ public boolean isVisible(By locater) { try { WebElement el = browser.findElement(locater); return ((RenderedWebElement) el).isDisplayed(); } catch (Exception e) { return false; } } /** * @return The current browser url. */ public String getCurrentUrl() { return browser.getCurrentUrl(); } /** * @return the webdriver instance. */ public WebDriver getDriver() { return this.browser; } @Override public void closeOtherWindows() { if (browser instanceof FirefoxDriver) { for (String handle : browser.getWindowHandles()) { if (!handle.equals(browser.getWindowHandle())) { String current = browser.getWindowHandle(); browser.switchTo().window(handle); logger.info("Closing other window with title \"" + browser.getTitle() + "\""); browser.close(); browser.switchTo().window(current); } } } } /** * @param file * the file to write to the filename to save the screenshot in. */ public void saveScreenShot(File file) { if (browser instanceof FirefoxDriver) { ((FirefoxDriver) browser).saveScreenshot(file); removeCanvasGeneratedByFirefoxDriverForScreenshots(); } else { logger.warn("Screenshot not supported."); } } private void removeCanvasGeneratedByFirefoxDriverForScreenshots() { String js = ""; js += "var canvas = document.getElementById('fxdriver-screenshot-canvas');"; js += "if(canvas != null){"; js += "canvas.parentNode.removeChild(canvas);"; js += "}"; try { executeJavaScript(js); } catch (Exception e) { logger.info("Could not remove the screenshot canvas from the DOM."); } } private String getFrameIdentification(Element frame, int index) { Attr attr = (Attr) frame.getAttributeNode("name"); if (attr != null && attr.getNodeValue() != null && !attr.getNodeValue().equals("")) { return attr.getNodeValue(); } attr = (Attr) frame.getAttributeNode("id"); if (attr != null && attr.getNodeValue() != null && !attr.getNodeValue().equals("")) { return attr.getNodeValue(); } // return "" + index; return null; } @Override public abstract EmbeddedBrowser clone(); /** * @return a Document object containing the contents of iframes as well. * @throws CrawljaxException * if an exception is thrown. */ private Document getDomTreeWithFrames() throws CrawljaxException { Document document; try { document = Helper.getDocument(browser.getPageSource()); appendFrameContent(browser.getWindowHandle(), document.getDocumentElement(), document, ""); } catch (SAXException e) { throw new CrawljaxException(e.getMessage(), e); } catch (IOException e) { throw new CrawljaxException(e.getMessage(), e); } return document; } private void appendFrameContent(String windowHandle, Element orig, Document document, String topFrame) throws SAXException, IOException { NodeList frameNodes = orig.getElementsByTagName("IFRAME"); browser.switchTo().window(windowHandle); List<Element> nodeList = new ArrayList<Element>(); for (int i = 0; i < frameNodes.getLength(); i++) { Element frameElement = (Element) frameNodes.item(i); nodeList.add(frameElement); } for (int i = 0; i < nodeList.size(); i++) { String frameIdentification = ""; if (topFrame != null && !topFrame.equals("")) { frameIdentification += topFrame + "."; } Element frameElement = nodeList.get(i); String nameId = getFrameIdentification(frameElement, i); if (nameId != null) { frameIdentification += nameId; logger.info("frame-identification: " + frameIdentification); String toAppend = browser.switchTo().frame(frameIdentification).getPageSource(); Element toAppendElement = Helper.getDocument(toAppend).getDocumentElement(); Element importedElement = (Element) document.importNode(toAppendElement, true); frameElement.appendChild(importedElement); appendFrameContent(windowHandle, importedElement, document, frameIdentification); } } } /** * @return the dom without the iframe contents. * @throws CrawljaxException * if it fails. * @see com.crawljax.browser.EmbeddedBrowser#getDomWithoutIframeContent(). */ public String getDomWithoutIframeContent() throws CrawljaxException { try { return toUniformDOM(browser.getPageSource()); } catch (Exception e) { throw new CrawljaxException(e.getMessage(), e); } } }
package com.ds.listing.rest; import com.ds.listing.model.Listing; import com.ds.listing.services.ListingService; import java.util.ArrayList; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; @Path("/rest/list") public class ListingRestService { @Inject private ListingService service; @GET @Produces("application/json") public ArrayList<Listing> getAllListings() { return service.getAllListings(); } }
package com.edwardsit.spark4n6; import edu.nps.jlibewf.EWFFileReader; import edu.nps.jlibewf.EWFSegmentFileReader; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.lib.input.SequenceFileRecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.log4j.Logger; import org.apache.log4j.Level; import java.io.IOException; import java.nio.ByteBuffer; public class EWFRecordReader extends SequenceFileRecordReader<BytesWritable, BytesWritable> { private static Logger log = Logger.getLogger(EWFRecordReader.class); private static long nChunksPerRecord = -1L; private long chunkSize = 0L; private EWFFileReader stream = null; public EWFRecordReader() { } long start = 0L; long end = 0L; long currentStart = 0L; long currentEnd = 0L; boolean notReadYet = true; boolean atEOF = false; BytesWritable currentKey = new BytesWritable(); BytesWritable currentValue = new BytesWritable(); FileSystem fs = null; Path file = null; protected Path getFirstFile() { int length = file.getName().length(); Path parent = file.getParent(); return new Path(parent,file.getName().substring(0,length-4) + ".E01"); } @Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { FileSplit fileSplit = (FileSplit) split; Configuration conf = context.getConfiguration(); file = fileSplit.getPath(); start = fileSplit.getStart(); end = start + fileSplit.getLength(); fs = file.getFileSystem(conf); stream = new EWFFileReader(fs,getFirstFile()); chunkSize = new EWFSegmentFileReader(fs).DEFAULT_CHUNK_SIZE; log.setLevel(Level.DEBUG); } @Override public boolean nextKeyValue() throws IOException, InterruptedException { if (atEOF || currentEnd >= end) return false; else if (notReadYet) { currentStart = start; notReadYet = false; } else { currentStart = currentEnd; } long bytesToRead = ((end - currentStart) > (getChunksPerRecord() * chunkSize)) ? (getChunksPerRecord() * chunkSize) : (end - currentStart); byte[] valBuf = stream.readImageBytes(currentStart, (int) bytesToRead); log.debug("stream.readImageBytes(" + currentStart + ", (int) " + bytesToRead + ") = " + valBuf.length + ";"); byte[] keyBuf = ByteBuffer.allocate(Long.SIZE + file.toUri().toASCIIString().getBytes().length) .putLong(currentStart) .put(file.toUri().toASCIIString().getBytes()) .array(); currentKey.set(keyBuf,0,keyBuf.length); currentValue.set(valBuf, 0, valBuf.length); currentEnd = currentStart + valBuf.length; return currentEnd <= end; } @Override public BytesWritable getCurrentKey() { return new BytesWritable(currentKey.copyBytes()); } @Override public BytesWritable getCurrentValue() { return new BytesWritable(currentValue.copyBytes()); } @Override public float getProgress() throws IOException { if (start == end) return 0.0f; else return (float) (currentEnd - start) / (end - start); } @Override public void close() throws IOException { if(stream != null) stream.close(); } protected long getChunksPerRecord() throws IOException { if (nChunksPerRecord == -1L) { long hdfsBlockSize = fs.getFileStatus(file).getBlockSize(); // nChunksPerRecord = (hdfsBlockSize/chunkSize/8) - 1L; nChunksPerRecord = 2L; // 64 KiB, the default block size for HBase } return nChunksPerRecord; } }
package com.faforever.client.remote; import com.faforever.client.api.FafApiAccessor; import com.faforever.client.api.dto.AchievementDefinition; import com.faforever.client.api.dto.CoopResult; import com.faforever.client.api.dto.FeaturedModFile; import com.faforever.client.api.dto.Game; import com.faforever.client.api.dto.GamePlayerStats; import com.faforever.client.api.dto.GameReview; import com.faforever.client.api.dto.MapVersion; import com.faforever.client.api.dto.MapVersionReview; import com.faforever.client.api.dto.ModVersionReview; import com.faforever.client.api.dto.PlayerAchievement; import com.faforever.client.chat.avatar.AvatarBean; import com.faforever.client.chat.avatar.event.AvatarChangedEvent; import com.faforever.client.clan.Clan; import com.faforever.client.config.CacheNames; import com.faforever.client.coop.CoopMission; import com.faforever.client.domain.RatingHistoryDataPoint; import com.faforever.client.fa.relay.GpgGameMessage; import com.faforever.client.game.Faction; import com.faforever.client.game.KnownFeaturedMod; import com.faforever.client.game.NewGameInfo; import com.faforever.client.leaderboard.LeaderboardEntry; import com.faforever.client.map.MapBean; import com.faforever.client.mod.FeaturedMod; import com.faforever.client.mod.ModVersion; import com.faforever.client.net.ConnectionState; import com.faforever.client.player.Player; import com.faforever.client.remote.domain.GameEndedMessage; import com.faforever.client.remote.domain.GameLaunchMessage; import com.faforever.client.remote.domain.IceMessage; import com.faforever.client.remote.domain.IceServersServerMessage.IceServer; import com.faforever.client.remote.domain.LoginMessage; import com.faforever.client.remote.domain.ServerMessage; import com.faforever.client.replay.Replay; import com.faforever.client.tournament.TournamentBean; import com.faforever.client.vault.review.Review; import com.faforever.client.vault.search.SearchController.SearchConfig; import com.faforever.client.vault.search.SearchController.SortConfig; import com.faforever.commons.io.ByteCountListener; import com.google.common.eventbus.EventBus; import javafx.beans.property.ReadOnlyObjectProperty; import org.springframework.cache.annotation.CacheEvict; import org.springframework.context.annotation.Lazy; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import javax.inject.Inject; import java.nio.file.Path; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; @Lazy @Service public class FafService { private final FafServerAccessor fafServerAccessor; private final FafApiAccessor fafApiAccessor; private final EventBus eventBus; @Inject public FafService(FafServerAccessor fafServerAccessor, FafApiAccessor fafApiAccessor, EventBus eventBus) { this.fafServerAccessor = fafServerAccessor; this.fafApiAccessor = fafApiAccessor; this.eventBus = eventBus; } public <T extends ServerMessage> void addOnMessageListener(Class<T> type, Consumer<T> listener) { fafServerAccessor.addOnMessageListener(type, listener); } @SuppressWarnings("unchecked") public <T extends ServerMessage> void removeOnMessageListener(Class<T> type, Consumer<T> listener) { fafServerAccessor.removeOnMessageListener(type, listener); } public CompletableFuture<GameLaunchMessage> requestHostGame(NewGameInfo newGameInfo) { return fafServerAccessor.requestHostGame(newGameInfo); } public ReadOnlyObjectProperty<ConnectionState> connectionStateProperty() { return fafServerAccessor.connectionStateProperty(); } public CompletableFuture<GameLaunchMessage> requestJoinGame(int gameId, String password) { return fafServerAccessor.requestJoinGame(gameId, password); } public CompletableFuture<GameLaunchMessage> startSearchLadder1v1(Faction faction, int port) { return fafServerAccessor.startSearchLadder1v1(faction); } public void stopSearchingRanked() { fafServerAccessor.stopSearchingRanked(); } public void sendGpgGameMessage(GpgGameMessage message) { fafServerAccessor.sendGpgMessage(message); } public CompletableFuture<LoginMessage> connectAndLogIn(String username, String password) { return fafServerAccessor.connectAndLogIn(username, password); } public void disconnect() { fafServerAccessor.disconnect(); } public void addFriend(Player player) { fafServerAccessor.addFriend(player.getId()); } public void addFoe(Player player) { fafServerAccessor.addFoe(player.getId()); } public void removeFriend(Player player) { fafServerAccessor.removeFriend(player.getId()); } public void removeFoe(Player player) { fafServerAccessor.removeFoe(player.getId()); } @Async public void notifyGameEnded() { fafServerAccessor.sendGpgMessage(new GameEndedMessage()); } @Async public CompletableFuture<LeaderboardEntry> getLadder1v1EntryForPlayer(int playerId) { return CompletableFuture.completedFuture(LeaderboardEntry.fromLadder1v1(fafApiAccessor.getLadder1v1EntryForPlayer(playerId))); } @Async public CompletableFuture<List<ModVersion>> getMods() { return CompletableFuture.completedFuture(fafApiAccessor.getMods().stream() .map(ModVersion::fromModDto) .collect(toList())); } @Async public CompletableFuture<com.faforever.client.mod.ModVersion> getModVersion(String uid) { return CompletableFuture.completedFuture(com.faforever.client.mod.ModVersion.fromDto(fafApiAccessor.getModVersion(uid), null)); } public void reconnect() { fafServerAccessor.reconnect(); } @Async public CompletableFuture<List<MapBean>> getMostPlayedMaps(int count, int page) { return CompletableFuture.completedFuture(fafApiAccessor.getMostPlayedMaps(count, page).stream() .map(MapBean::fromMapDto) .collect(toList())); } @Async public CompletableFuture<List<MapBean>> getHighestRatedMaps(int count, int page) { return CompletableFuture.completedFuture(fafApiAccessor.getHighestRatedMaps(count, page).stream() .map(MapBean::fromMapDto) .collect(toList())); } @Async public CompletableFuture<List<MapBean>> getNewestMaps(int count, int page) { return CompletableFuture.completedFuture(fafApiAccessor.getNewestMaps(count, page).stream() .map(MapBean::fromMapDto) .collect(toList())); } @Async public CompletableFuture<List<CoopMission>> getCoopMaps() { return CompletableFuture.completedFuture(fafApiAccessor.getCoopMissions().stream() .map(CoopMission::fromCoopInfo) .collect(toList())); } @Async public CompletableFuture<List<AvatarBean>> getAvailableAvatars() { return CompletableFuture.completedFuture(fafServerAccessor.getAvailableAvatars().stream() .map(AvatarBean::fromAvatar) .collect(Collectors.toList())); } public void selectAvatar(AvatarBean avatar) { fafServerAccessor.selectAvatar(avatar == null ? null : avatar.getUrl()); eventBus.post(new AvatarChangedEvent(avatar)); } @CacheEvict(CacheNames.MODS) public void evictModsCache() { // Cache eviction by annotation } @Async public CompletableFuture<List<CoopResult>> getCoopLeaderboard(CoopMission mission, int numberOfPlayers) { return CompletableFuture.completedFuture(fafApiAccessor.getCoopLeaderboard(mission.getId(), numberOfPlayers)); } @Async public CompletableFuture<List<RatingHistoryDataPoint>> getRatingHistory(int playerId, KnownFeaturedMod knownFeaturedMod) { return CompletableFuture.completedFuture(fafApiAccessor.getGamePlayerStats(playerId, knownFeaturedMod) .parallelStream() .filter(gamePlayerStats -> gamePlayerStats.getScoreTime() != null && gamePlayerStats.getAfterMean() != null && gamePlayerStats.getAfterDeviation() != null) .sorted(Comparator.comparing(GamePlayerStats::getScoreTime)) .map(entry -> new RatingHistoryDataPoint(entry.getScoreTime(), entry.getAfterMean(), entry.getAfterDeviation())) .collect(Collectors.toList()) ); } @Async public CompletableFuture<List<FeaturedMod>> getFeaturedMods() { return CompletableFuture.completedFuture(fafApiAccessor.getFeaturedMods().stream() .sorted(Comparator.comparingInt(com.faforever.client.api.dto.FeaturedMod::getOrder)) .map(FeaturedMod::fromFeaturedMod) .collect(Collectors.toList())); } @Async public CompletableFuture<List<FeaturedModFile>> getFeaturedModFiles(FeaturedMod featuredMod, Integer version) { return CompletableFuture.completedFuture(fafApiAccessor.getFeaturedModFiles(featuredMod, version)); } @Async public CompletableFuture<List<LeaderboardEntry>> getLadder1v1Leaderboard() { return CompletableFuture.completedFuture(fafApiAccessor.getLadder1v1Leaderboard().parallelStream() .map(LeaderboardEntry::fromLadder1v1) .collect(toList())); } @Async public CompletableFuture<List<LeaderboardEntry>> getGlobalLeaderboard() { return CompletableFuture.completedFuture(fafApiAccessor.getGlobalLeaderboard().parallelStream() .map(LeaderboardEntry::fromGlobalRating) .collect(toList())); } @Async public CompletableFuture<List<Replay>> getNewestReplays(int topElementCount, int page) { return CompletableFuture.completedFuture(fafApiAccessor.getNewestReplays(topElementCount, page) .parallelStream() .map(Replay::fromDto) .collect(toList())); } @Async public CompletableFuture<List<Replay>> getHighestRatedReplays(int topElementCount, int page) { return CompletableFuture.completedFuture(fafApiAccessor.getHighestRatedReplays(topElementCount, page) .parallelStream() .map(Replay::fromDto) .collect(toList())); } public void uploadMod(Path modFile, ByteCountListener byteListener) { fafApiAccessor.uploadMod(modFile, byteListener); } @Async public CompletableFuture<List<PlayerAchievement>> getPlayerAchievements(int playerId) { return CompletableFuture.completedFuture(fafApiAccessor.getPlayerAchievements(playerId)); } @Async public CompletableFuture<List<AchievementDefinition>> getAchievementDefinitions() { return CompletableFuture.completedFuture(fafApiAccessor.getAchievementDefinitions()); } @Async public CompletableFuture<AchievementDefinition> getAchievementDefinition(String achievementId) { return CompletableFuture.completedFuture(fafApiAccessor.getAchievementDefinition(achievementId)); } @Async public CompletableFuture<List<Replay>> findReplaysByQuery(String query, int maxResults, int page, SortConfig sortConfig) { return CompletableFuture.completedFuture(fafApiAccessor.findReplaysByQuery(query, maxResults, page, sortConfig) .parallelStream() .map(Replay::fromDto) .collect(toList())); } @Async public CompletableFuture<List<MapBean>> findMapsByQuery(String query, int page, int maxSearchResults, SortConfig sortConfig) { return CompletableFuture.completedFuture(fafApiAccessor.findMapsByQuery(query, page, maxSearchResults, sortConfig) .parallelStream() .map(MapBean::fromMapDto) .collect(toList())); } public CompletableFuture<Optional<MapBean>> findMapByFolderName(String folderName) { return CompletableFuture.completedFuture(fafApiAccessor.findMapByFolderName(folderName) .map(MapBean::fromMapVersionDto)); } public CompletableFuture<List<Player>> getPlayersByIds(Collection<Integer> playerIds) { return CompletableFuture.completedFuture(fafApiAccessor.getPlayersByIds(playerIds).stream() .map(Player::fromDto) .collect(toList())); } @Async public CompletableFuture<Void> saveGameReview(Review review, int gameId) { GameReview gameReview = (GameReview) new GameReview() .setScore(review.getScore().byteValue()) .setText(review.getText()); if (review.getId() == null) { Assert.notNull(review.getPlayer(), "Player ID must be set"); GameReview updatedReview = fafApiAccessor.createGameReview( (GameReview) gameReview .setGame(new Game().setId(String.valueOf(gameId))) .setPlayer(new com.faforever.client.api.dto.Player().setId(String.valueOf(review.getPlayer().getId()))) ); review.setId(updatedReview.getId()); } else { fafApiAccessor.updateGameReview((GameReview) gameReview.setId(String.valueOf(review.getId()))); } return CompletableFuture.completedFuture(null); } @Async public CompletableFuture<Void> saveModVersionReview(Review review, String modVersionId) { ModVersionReview modVersionReview = (ModVersionReview) new ModVersionReview() .setScore(review.getScore().byteValue()) .setText(review.getText()); if (review.getId() == null) { Assert.notNull(review.getPlayer(), "Player ID must be set"); ModVersionReview updatedReview = fafApiAccessor.createModVersionReview( (ModVersionReview) modVersionReview .setModVersion(new com.faforever.client.api.dto.ModVersion().setId(String.valueOf(modVersionId))) .setId(String.valueOf(review.getId())) .setPlayer(new com.faforever.client.api.dto.Player().setId(String.valueOf(review.getPlayer().getId()))) ); review.setId(updatedReview.getId()); } else { fafApiAccessor.updateModVersionReview((ModVersionReview) modVersionReview.setId(String.valueOf(review.getId()))); } return CompletableFuture.completedFuture(null); } @Async public CompletableFuture<Void> saveMapVersionReview(Review review, String mapVersionId) { MapVersionReview mapVersionReview = (MapVersionReview) new MapVersionReview() .setScore(review.getScore().byteValue()) .setText(review.getText()); if (review.getId() == null) { Assert.notNull(review.getPlayer(), "Player ID must be set"); MapVersionReview updatedReview = fafApiAccessor.createMapVersionReview( (MapVersionReview) mapVersionReview .setMapVersion(new MapVersion().setId(mapVersionId)) .setId(String.valueOf(review.getId())) .setPlayer(new com.faforever.client.api.dto.Player().setId(String.valueOf(review.getPlayer().getId()))) ); review.setId(updatedReview.getId()); } else { fafApiAccessor.updateMapVersionReview((MapVersionReview) mapVersionReview.setId(String.valueOf(review.getId()))); } return CompletableFuture.completedFuture(null); } @Async public CompletableFuture<Optional<Replay>> getLastGameOnMap(int playerId, String mapVersionId) { return CompletableFuture.completedFuture(fafApiAccessor.getLastGamesOnMap(playerId, mapVersionId, 1).stream() .map(Replay::fromDto) .findFirst()); } @Async public CompletableFuture<Void> deleteGameReview(Review review) { fafApiAccessor.deleteGameReview(review.getId()); return CompletableFuture.completedFuture(null); } @Async public CompletableFuture<Void> deleteMapVersionReview(Review review) { fafApiAccessor.deleteMapVersionReview(review.getId()); return CompletableFuture.completedFuture(null); } @Async public CompletableFuture<Void> deleteModVersionReview(Review review) { fafApiAccessor.deleteModVersionReview(review.getId()); return CompletableFuture.completedFuture(null); } public CompletableFuture<Optional<Replay>> findReplayById(int id) { return CompletableFuture.completedFuture(fafApiAccessor.findReplayById(id) .map(Replay::fromDto)); } public CompletableFuture<List<IceServer>> getIceServers() { return fafServerAccessor.getIceServers(); } public void restoreGameSession(int id) { fafServerAccessor.restoreGameSession(id); } @Async public CompletableFuture<List<ModVersion>> findModsByQuery(SearchConfig query, int page, int count) { return CompletableFuture.completedFuture(fafApiAccessor.findModsByQuery(query, page, count) .parallelStream() .map(ModVersion::fromModDto) .collect(toList())); } @Async public CompletableFuture<List<MapBean>> getLadder1v1Maps(int count, int page) { List<MapBean> maps = fafApiAccessor.getLadder1v1Maps(count, page).stream() .map(ladder1v1Map -> MapBean.fromMapVersionDto(ladder1v1Map.getMapVersion())) .collect(toList()); return CompletableFuture.completedFuture(maps); } @Async public CompletableFuture<Optional<Clan>> getClanByTag(String tag) { return CompletableFuture.completedFuture(fafApiAccessor.getClanByTag(tag) .map(Clan::fromDto)); } public Optional<MapBean> findMapById(String id) { return fafApiAccessor.findMapVersionById(id) .map(MapBean::fromMapVersionDto); } public void sendIceMessage(int remotePlayerId, Object message) { fafServerAccessor.sendGpgMessage(new IceMessage(remotePlayerId, message)); } @Async public CompletableFuture<List<TournamentBean>> getAllTournaments() { return CompletableFuture.completedFuture(fafApiAccessor.getAllTournaments() .stream() .map(TournamentBean::fromTournamentDto) .collect(toList())); } }
package com.gamingmesh.jobs.CMILib; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.block.Block; import org.bukkit.entity.EntityType; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.Recipe; import org.bukkit.inventory.meta.SkullMeta; import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.stuff.Debug; import com.gamingmesh.jobs.stuff.VersionChecker.Version; public class ItemManager { static HashMap<Integer, CMIItemStack> byId = new HashMap<Integer, CMIItemStack>(); static HashMap<String, CMIItemStack> byBukkitName = new HashMap<String, CMIItemStack>(); static HashMap<String, CMIItemStack> byMojangName = new HashMap<String, CMIItemStack>(); static HashMap<CMIMaterial, CMIItemStack> byMaterial = new HashMap<CMIMaterial, CMIItemStack>(); static final Version version = Jobs.getVersionCheckManager().getVersion(); public static void load() { for (CMIMaterial one : CMIMaterial.values()) { if (one == null) continue; one.updateMaterial(); Material mat = one.getMaterial(); if (mat == null) { continue; } int id = one.getId(); int data = one.getLegacyData(); int legacyId = one.getLegacyId(); String bukkitName = one.name(); String mojangName = one.name(); try { mojangName = ItemReflection.getItemMinecraftName(new ItemStack(mat)); } catch (Exception e) { } CMIItemStack cm = new CMIItemStack(one); cm.setId(id); cm.setData((short) (data > 0 ? data : 0)); cm.setBukkitName(bukkitName); cm.setMojangName(mojangName); byBukkitName.put(id + ":" + one.getData(), cm); byBukkitName.put(legacyId + ":" + one.getLegacyData(), cm); if (!one.getLegacyName().isEmpty()) { byBukkitName.put(one.getLegacyName().toLowerCase().replace("_", "").replace(" ", ""), cm); } byBukkitName.put(one.name().toLowerCase().replace("_", "").replace(" ", ""), cm); if (mojangName != null) { String n = mojangName.toLowerCase().replace("_", "").replace(" ", "").replace("minecraft:", ""); if (!byMojangName.containsKey(n)) byMojangName.put(n, cm); } byMaterial.put(one, cm); if (!byId.containsKey(id)) byId.put(id, cm); if (!byId.containsKey(one.getLegacyId())) byId.put(one.getLegacyId(), cm); } for (Material one : Material.class.getEnumConstants()) { CMIMaterial mat = CMIMaterial.get(one); if (mat == null && !one.toString().startsWith("LEGACY_")) { CMIItemStack cm = new CMIItemStack(new ItemStack(one)); cm.setId(one.getId()); cm.setBukkitName(one.name()); byBukkitName.put(one.getId() + ":" + cm.getData(), cm); byBukkitName.put(one.name().toLowerCase().replace("_", "").replace(" ", ""), cm); String mojangName = one.name(); try { mojangName = ItemReflection.getItemMinecraftName(new ItemStack(one)); } catch (Exception e) { } cm.setMojangName(mojangName); String n = mojangName.toLowerCase().replace("_", "").replace(" ", "").replace("minecraft:", ""); if (!byMojangName.containsKey(n)) byMojangName.put(n, cm); if (!byId.containsKey(one.getId())) byId.put(one.getId(), cm); } } } @Deprecated public static CMIItemStack getItem(Material mat) { CMIItemStack cm = byMaterial.get(CMIMaterial.get(mat)); return cm.clone(); } public static CMIItemStack getItem(CMIMaterial mat) { CMIItemStack cm = byMaterial.get(mat); return cm.clone(); } public static CMIItemStack getItem(ItemStack item) { if (item == null) item = new ItemStack(Material.AIR); CMIItemStack cm = getItem(CMIMaterial.get(item)); cm.setItemStack(item); return cm; } static HashMap<String, ItemStack> headCache = new HashMap<String, ItemStack>(); public static CMIItemStack getItem(String name) { if (byBukkitName.isEmpty()) load(); CMIItemStack cm = null; name = name.toLowerCase().replace("_", "").replace("minecraft:", ""); String original = name; Integer amount = null; if (name.contains("-")) { String a = name.split("-")[1]; try { amount = Integer.parseInt(a); } catch (Exception e) { } name = name.split("-")[0]; } short data = -999; if (name.contains(":")) { try { data = (short) Integer.parseInt(name.split(":")[1]); } catch (Exception e) { } try { CMIEntityType e = CMIEntityType.getByName(name.split(":")[1]); if (e != null) data = e.getType().getTypeId(); } catch (Exception e) { } name = name.split(":")[0]; } switch (name.toLowerCase()) { case "skull": cm = byMaterial.get(CMIMaterial.SKELETON_SKULL); break; case "door": cm = byMaterial.get(CMIMaterial.SPRUCE_DOOR); break; case "head": cm = byMaterial.get(CMIMaterial.PLAYER_HEAD); data = 3; main: if (original.contains(":")) { ItemStack old = headCache.get(original); if (old != null) { cm.setItemStack(old); } else { String d = original.split(":")[1]; ItemStack skull = new ItemStack(CMIMaterial.PLAYER_HEAD.getMaterial(), 1, (byte) 3); SkullMeta skullMeta = (SkullMeta) skull.getItemMeta(); if (d.length() == 36) { try { OfflinePlayer offPlayer = Bukkit.getOfflinePlayer(UUID.fromString(d)); skullMeta.setOwningPlayer(offPlayer); } catch (Exception e) { break main; } skull.setItemMeta(skullMeta); } else { skullMeta.setOwner(d); skull.setItemMeta(skullMeta); } headCache.put(original, skull); cm.setItemStack(skull); } } break; } if (cm == null) { cm = byBukkitName.get(name); if (cm == null) { try { cm = byId.get(Integer.parseInt(name)); } catch (Exception e) { } if (cm == null) { cm = byMojangName.get(name); if (cm == null) { for (Material one : Material.class.getEnumConstants()) { if (one.name().replace("_", "").equalsIgnoreCase(name)) { cm = byMaterial.get(CMIMaterial.get(one)); break; } } if (cm == null) { for (CMIMaterial one : CMIMaterial.values()) { if (one.getName().replace(" ", "").equalsIgnoreCase(name)) { cm = byMaterial.get(one); if (cm != null && data == -999) { data = one.getData(); } break; } } if (cm == null) { for (CMIMaterial one : CMIMaterial.values()) { if (one.getName().replace(" ", "").toLowerCase().startsWith(name)) { cm = byMaterial.get(one); if (cm != null && data == -999) { data = one.getData(); } break; } } } if (cm == null) { for (CMIMaterial one : CMIMaterial.values()) { if (one.getName().replace(" ", "").toLowerCase().contains(name)) { cm = byMaterial.get(one); if (cm != null && data == -999) { data = one.getData(); } break; } } } if (cm == null) { for (Entry<String, CMIItemStack> one : byMojangName.entrySet()) { if (one.getKey().contains(name)) { cm = one.getValue(); if (cm != null && data == -999) { data = one.getValue().getData(); } break; } } } } } } } } CMIItemStack ncm = null; if (cm != null) ncm = cm.clone(); if (ncm != null && data != -999) { if (ncm.getMaxDurability() > 15) ncm.setData((short) 0); else { ncm.setData(data); } } if (ncm != null && amount != null) ncm.setAmount(amount); return ncm; } static public List<Recipe> getAllRecipes() { List<Recipe> results = new ArrayList<Recipe>(); Iterator<Recipe> iter = Bukkit.recipeIterator(); while (iter.hasNext()) { Recipe recipe = iter.next(); results.add(recipe); } return results; } static public List<Recipe> getRecipesFor(ItemStack result) { List<Recipe> results = new ArrayList<Recipe>(); Iterator<Recipe> iter = Bukkit.recipeIterator(); while (iter.hasNext()) { Recipe recipe = iter.next(); ItemStack stack = recipe.getResult(); if (stack.getType() != result.getType()) { continue; } if (result.getDurability() == -1 || result.getDurability() == stack.getDurability()) { results.add(recipe); } } return results; } static public Material getMaterial(String name) { CMIItemStack cm = getItem(name); if (cm == null) return Material.AIR; return cm.getMaterial(); } public enum colorNames { White(0, "White"), Orange(1, "Orange"), Magenta(2, "Magenta"), Light(3, "Light Blue"), Yellow(4, "Yellow"), Lime(5, "Lime"), Pink(6, "Pink"), Gray(7, "Gray"), Light_Gray(8, "Light Gray"), Cyan(9, "Cyan"), Purple(10, "Purple"), Blue(11, "Blue"), Brown(12, "Brown"), Green(13, "Green"), Red(14, "Red"), Black(15, "Black"); private int id; private String name; colorNames(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public String getName() { return name; } public static colorNames getById(int id) { for (colorNames one : colorNames.values()) { if (one.getId() == id) return one; } return colorNames.White; } } public enum CMIEntityType { DROPPED_ITEM(1, "Item"), EXPERIENCE_ORB(2, "Experience Orb"), AREA_EFFECT_CLOUD(3, "Area Effect Cloud"), ELDER_GUARDIAN(4, "Elder Guardian"), WITHER_SKELETON(5, "Wither Skeleton"), STRAY(6, "Stray"), EGG(7, "Thrown Egg"), LEASH_HITCH(8, "Leash Knot"), PAINTING(9, "Painting"), ARROW(10, "Arrow"), SNOWBALL(11, "Snowball"), FIREBALL(12, "Fireball"), SMALL_FIREBALL(13, "Small Fireball"), ENDER_PEARL(14, "Thrown Ender Pearl"), ENDER_SIGNAL(15, "End Signal"), SPLASH_POTION(16, "Splash Potion"), THROWN_EXP_BOTTLE(17, "Thrown Bottle o' Enchanting"), ITEM_FRAME(18, "Item Frame"), WITHER_SKULL(19, "Wither Skull"), PRIMED_TNT(20, "Primed TNT"), FALLING_BLOCK(21, "Falling Block"), FIREWORK(22, "Firework Rocket"), HUSK(23, "Husk"), SPECTRAL_ARROW(24, "Spectral Arrow"), SHULKER_BULLET(25, "Shulker Bullet"), DRAGON_FIREBALL(26, "Dragon Fireball"), ZOMBIE_VILLAGER(27, "Zombie Villager"), SKELETON_HORSE(28, "Skeleton Horse"), ZOMBIE_HORSE(29, "Zombie Horse"), ARMOR_STAND(30, "Armor Stand"), DONKEY(31, "Donkey"), MULE(32, "Mule"), EVOKER_FANGS(33, "Evoker Fangs"), EVOKER(34, "Evoker"), VEX(35, "Vex"), VINDICATOR(36, "Vindicator"), ILLUSIONER(37, "Illusioner"), MINECART_COMMAND(40, "Minecart with Command Block"), BOAT(41, "Boat"), MINECART(42, "Minecart"), MINECART_CHEST(43, "Minecart with Chest"), MINECART_FURNACE(44, "Minecart with Furnace"), MINECART_TNT(45, "Minecart with TNT"), MINECART_HOPPER(46, "Minecart with Hopper"), MINECART_MOB_SPAWNER(47, "Minecart with Spawner"), CREEPER(50, "Creeper"), SKELETON(51, "Skeleton"), SPIDER(52, "Spider"), GIANT(53, "Giant"), ZOMBIE(54, "Zombie"), SLIME(55, "Slime"), GHAST(56, "Ghast"), PIG_ZOMBIE(57, "Zombie Pigman"), ENDERMAN(58, "Enderman"), CAVE_SPIDER(59, "Cave Spider"), SILVERFISH(60, "Silverfish"), BLAZE(61, "Blaze"), MAGMA_CUBE(62, "Magma Cube"), ENDER_DRAGON(63, "Ender Dragon"), WITHER(64, "Wither"), BAT(65, "Bat"), WITCH(66, "Witch"), ENDERMITE(67, "Endermite"), GUARDIAN(68, "Guardian"), SHULKER(69, "Shulker"), PIG(90, "Pig"), SHEEP(91, "Sheep"), COW(92, "Cow"), CHICKEN(93, "Chicken"), SQUID(94, "Squid"), WOLF(95, "Wolf"), MUSHROOM_COW(96, "Mushroom Cow"), SNOWMAN(97, "Snowman"), OCELOT(98, "Ocelot"), IRON_GOLEM(99, "Iron Golem"), HORSE(100, "Horse"), RABBIT(101, "Rabbit"), POLAR_BEAR(102, "Polar Bear"), LLAMA(103, "Llama"), LLAMA_SPIT(104, "Llama Spit"), PARROT(105, "Parrot"), VILLAGER(120, "Villager"), ENDER_CRYSTAL(200, "End Crystal"), TURTLE(-1, "Turtle"), PHANTOM(-1, "Phantom"), TRIDENT(-1, "Trident"), COD(-1, "Cod"), SALMON(-1, "Salmon"), PUFFERFISH(-1, "Pufferfish"), TROPICAL_FISH(-1, "Tropical Fish"), DROWNED(-1, "Drowned"), DOLPHIN(-1, "Dolphin"), LINGERING_POTION(-1, "Lingering Potion"), FISHING_HOOK(-1, "Fishing Hook"), LIGHTNING(-1, "Lightning Bolt"), WEATHER(-1, "Weather"), PLAYER(-1, "Player"), COMPLEX_PART(-1, "Complex Part"), TIPPED_ARROW(-1, "Tipped Arrow"), UNKNOWN(-1, "Unknown"); private int id; private String name; EntityType type = null; CMIEntityType(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public String getName() { return name; } public static CMIEntityType getById(int id) { for (CMIEntityType one : CMIEntityType.values()) { if (one.getId() == id) return one; } return CMIEntityType.PIG; } public static CMIEntityType getByType(EntityType entity) { return getByName(entity.toString()); } public static CMIEntityType getByName(String name) { String main = name; String sub = null; if (name.contains("_")) { main = name.split("_")[0]; sub = name.split("_")[1]; } if (name.contains(":")) { main = name.split(":")[0]; sub = name.split(":")[1]; } String updated = (main + (sub == null ? "" : sub)).toLowerCase(); String reverse = ((sub == null ? "" : sub) + main).toLowerCase(); CMIEntityType type = null; Integer id = null; try { id = Integer.parseInt(main); } catch (Exception e) { } for (CMIEntityType one : CMIEntityType.values()) { if (one.name().replace("_", "").equalsIgnoreCase(updated) || one.name.replace(" ", "").equalsIgnoreCase(updated)) { type = one; break; } } if (type == null) for (CMIEntityType one : CMIEntityType.values()) { if (one.name.replace("_", "").contains(updated)) { type = one; break; } } if (sub != null) { if (type == null) for (CMIEntityType one : CMIEntityType.values()) { if (one.name().replace("_", "").equalsIgnoreCase(reverse) || one.name.replace(" ", "").equalsIgnoreCase(reverse)) { type = one; break; } } if (type == null) for (CMIEntityType one : CMIEntityType.values()) { if (one.name.replace("_", "").contains(reverse)) { type = one; break; } } } if (id != null) { if (type == null) for (CMIEntityType one : CMIEntityType.values()) { if (one.getId() == id) { type = one; break; } } } if (type == null) for (CMIEntityType one : CMIEntityType.values()) { if (one.name.contains("_")) continue; if (one.name.equalsIgnoreCase(main)) { type = one; break; } } return type; } public EntityType getType() { if (type != null) return type; for (EntityType one : EntityType.values()) { if (one.toString().equalsIgnoreCase(this.name())) { type = one; break; } } return type; } public boolean isAlive() { return getType().isAlive(); } public boolean isSpawnable() { return getType().isSpawnable(); } public static String getRealNameByType(EntityType type) { if (type == null) return null; CMIEntityType ctype = CMIEntityType.getByType(type); if (ctype != null) return ctype.getName(); String name = type.name(); name = name.toLowerCase().replace("_", " "); name = name.substring(0, 1).toUpperCase() + name.substring(1); return name; } } public static enum CMIMaterial { NONE(-1, -1, -1, "None"), ACACIA_BOAT(447, 0, 27326, "Acacia Boat", "BOAT_ACACIA"), ACACIA_BUTTON(-1, -1, 13993, "Acacia Button", ""), ACACIA_DOOR(430, 0, 23797, "Acacia Door", "ACACIA_DOOR_ITEM"), ACACIA_FENCE(192, 0, 4569, "Acacia Fence", "ACACIA_FENCE"), ACACIA_FENCE_GATE(187, 0, 14145, "Acacia Fence Gate", "ACACIA_FENCE_GATE"), ACACIA_LEAVES(161, 0, 16606, "Acacia Leaves", "LEAVES_2"), ACACIA_LOG(162, 0, 8385, "Acacia Log", "LOG_2"), ACACIA_PLANKS(5, 4, 31312, "Acacia Wood Plank", "Acacia Planks"), ACACIA_PRESSURE_PLATE(-1, -1, 17586, "Acacia Pressure Plate", ""), ACACIA_SAPLING(6, 4, 20806, "Acacia Sapling", ""), ACACIA_SLAB(126, 4, 23730, "Acacia Wood Slab", "Acacia Slab"), ACACIA_STAIRS(163, 0, 17453, "Acacia Stairs", "ACACIA_STAIRS"), ACACIA_TRAPDOOR(-1, -1, 18343, "Acacia Trapdoor", ""), ACACIA_WOOD(-1, -1, 21861, "Acacia Wood", "Acacia Log"), ACTIVATOR_RAIL(157, 0, 5834, "Activator Rail", "ACTIVATOR_RAIL"), AIR(0, 0, 9648, "Unknown", "Air"), ALLIUM(38, 2, 6871, "Allium", "RED_ROSE"), ANDESITE(1, 5, 25975, "Andesite", ""), ANVIL(145, 0, 18718, "Anvil", "ANVIL"), APPLE(260, 0, 7720, "Apple", "APPLE"), ARMOR_STAND(416, 0, 12852, "Armor Stand", ""), ARROW(262, 0, 31091, "Arrow", "ARROW"), ATTACHED_MELON_STEM(-1, -1, 30882, "Attached Melon Stem", ""), ATTACHED_PUMPKIN_STEM(-1, -1, 12724, "Attached Pumpkin Stem", ""), AZURE_BLUET(38, 3, 17608, "Azure Bluet", ""), BAKED_POTATO(393, 0, 14624, "Baked Potato", ""), BARRIER(166, 0, 26453, "Barrier", "BARRIER"), BAT_SPAWN_EGG(383, 65, 14607, "Spawn Bat", "Bat Spawn Egg"), BEACON(138, 0, 6608, "Beacon", "BEACON"), BEDROCK(7, 0, 23130, "Bedrock", ""), BEEF(363, 0, 4803, "Raw Beef", ""), BEETROOT(434, 0, 23305, "Beetroot", ""), BEETROOTS(207, 0, 22075, "Beetroots", "BEETROOT_BLOCK"), BEETROOT_SEEDS(435, 0, 21282, "Beetroot Seeds", ""), BEETROOT_SOUP(436, 0, 16036, "Beetroot Soup", ""), BIRCH_BOAT(445, 0, 28104, "Birch Boat", "BOAT_BIRCH"), BIRCH_BUTTON(-1, -1, 26934, "Birch Button", ""), BIRCH_DOOR(428, 0, 14759, "Birch Door", "BIRCH_DOOR_ITEM"), BIRCH_FENCE(189, 0, 17347, "Birch Fence", "BIRCH_FENCE"), BIRCH_FENCE_GATE(184, 0, 6322, "Birch Fence Gate", "BIRCH_FENCE_GATE"), BIRCH_LEAVES(18, 2, 12601, "Birch Leaves", "LEAVES"), BIRCH_LOG(17, 2, 26727, "Birch Log", "LOG"), BIRCH_PLANKS(5, 2, 29322, "Birch Wood Plank", "Birch Planks"), BIRCH_PRESSURE_PLATE(-1, -1, 9664, "Birch Pressure Plate", ""), BIRCH_SAPLING(6, 2, 31533, "Birch Sapling", ""), BIRCH_SLAB(126, 2, 13807, "Birch Slab", ""), BIRCH_STAIRS(135, 0, 7657, "Birch Wood Stairs", "Birch Stairs"), BIRCH_TRAPDOOR(-1, -1, 32585, "Birch Trapdoor", ""), BIRCH_WOOD(-1, -1, 7924, "Birch Wood", ""), BLACK_BANNER(425, 0, 9365, "Banner", "Black Banner"), BLACK_BED(355, 15, 20490, "Black Bed", "Black Bed"), BLACK_CARPET(171, 15, 6056, "Black Carpet", "CARPET"), BLACK_CONCRETE(251, 15, 13338, "Black Concrete", "CONCRETE"), BLACK_CONCRETE_POWDER(252, 15, 16150, "Black Concrete Powder", "CONCRETE_POWDER"), BLACK_GLAZED_TERRACOTTA(250, 0, 29678, "Black Glazed Terracotta", "BLACK_GLAZED_TERRACOTTA"), BLACK_SHULKER_BOX(234, 0, 24076, "Black Shulker Box", "BLACK_SHULKER_BOX"), BLACK_STAINED_GLASS(95, 15, 13941, "Black Stained Glass", "STAINED_GLASS"), BLACK_STAINED_GLASS_PANE(160, 15, 13201, "Black Stained Glass Pane", "STAINED_GLASS_PANE"), BLACK_TERRACOTTA(159, 15, 26691, "Black Terracotta", "STAINED_CLAY"), BLACK_WALL_BANNER(117, 0, 4919, "Black Banner", ""), BLACK_WOOL(35, 15, 16693, "Black Wool", ""), BLAZE_POWDER(377, 0, 18941, "Blaze Powder", ""), BLAZE_ROD(369, 0, 8289, "Blaze Rod", ""), BLAZE_SPAWN_EGG(383, 61, 4759, "Spawn Blaze", "Blaze Spawn Egg"), BLUE_BANNER(245, 4, 18481, "Blue Banner", "PURPLE_GLAZED_TERRACOTTA"), BLUE_BED(355, 11, 12714, "Blue Bed", "Blue Bed"), BLUE_CARPET(171, 11, 13292, "Blue Carpet", ""), BLUE_CONCRETE(251, 11, 18756, "Blue Concrete", ""), BLUE_CONCRETE_POWDER(252, 11, 17773, "Blue Concrete Powder", ""), BLUE_GLAZED_TERRACOTTA(246, 0, 23823, "Blue Glazed Terracotta", "BLUE_GLAZED_TERRACOTTA"), BLUE_ICE(-1, -1, 22449, "Blue Ice", ""), BLUE_ORCHID(38, 1, 13432, "Blue Orchid", ""), BLUE_SHULKER_BOX(230, 0, 11476, "Blue Shulker Box", "BLUE_SHULKER_BOX"), BLUE_STAINED_GLASS(95, 11, 7107, "Blue Stained Glass", ""), BLUE_STAINED_GLASS_PANE(160, 11, 28484, "Blue Stained Glass Pane", ""), BLUE_TERRACOTTA(159, 11, 5236, "Blue Terracotta", ""), BLUE_WALL_BANNER(117, 4, 17757, "Blue Banner", ""), BLUE_WOOL(35, 11, 15738, "Blue Wool", ""), BONE(352, 0, 5686, "Bone", ""), BONE_BLOCK(216, 0, 17312, "Bone Block", "BONE_BLOCK"), BONE_MEAL(351, 15, 32458, "Bone Meal", ""), BOOK(340, 0, 23097, "Book", ""), BOOKSHELF(47, 0, 10069, "Bookshelf", "BOOKSHELF"), BOW(261, 0, 8745, "Bow", "BOW"), BOWL(281, 0, 32661, "Bowl", "BOWL"), BRAIN_CORAL(-1, -1, 31316, "Brain Coral", ""), BRAIN_CORAL_BLOCK(-1, -1, 30618, "Brain Coral Block", ""), BRAIN_CORAL_FAN(-1, -1, 13849, "Brain Coral Fan", ""), BRAIN_CORAL_WALL_FAN(-1, -1, 22685, "Brain Coral Wall Fan", ""), BREAD(297, 0, 32049, "Bread", "BREAD"), BREWING_STAND(379, 0, 14539, "Brewing Stand", "BREWING_STAND_ITEM"), BRICK(336, 0, 6820, "Brick", "claybrick"), BRICKS(45, 0, 14165, "Bricks", ""), BRICK_SLAB(44, 4, 26333, "Brick Slab", "STEP"), BRICK_STAIRS(108, 0, 21534, "Brick Stairs", "BRICK_STAIRS"), BROWN_BANNER(425, 3, 11481, "Brown Banner", ""), BROWN_BED(355, 12, 25624, "Brown Bed", "Brown Bed"), BROWN_CARPET(171, 12, 23352, "Brown Carpet", ""), BROWN_CONCRETE(251, 12, 19006, "Brown Concrete", ""), BROWN_CONCRETE_POWDER(252, 12, 21485, "Brown Concrete Powder", ""), BROWN_GLAZED_TERRACOTTA(247, 0, 5655, "Brown Glazed Terracotta", "BROWN_GLAZED_TERRACOTTA"), BROWN_MUSHROOM(39, 0, 9665, "Brown Mushroom", "BROWN_MUSHROOM"), BROWN_MUSHROOM_BLOCK(99, 0, 6291, "Brown Mushroom Block", "HUGE_MUSHROOM_1"), BROWN_SHULKER_BOX(231, 0, 24230, "Brown Shulker Box", "BROWN_SHULKER_BOX"), BROWN_STAINED_GLASS(95, 12, 20945, "Brown Stained Glass", ""), BROWN_STAINED_GLASS_PANE(160, 12, 17557, "Brown Stained Glass Pane", ""), BROWN_TERRACOTTA(159, 12, 23664, "Brown Terracotta", ""), BROWN_WALL_BANNER(117, 3, 14731, "Brown Banner", ""), BROWN_WOOL(35, 12, 32638, "Brown Wool", ""), BUBBLE_COLUMN(-1, -1, 13758, "Bubble Column", ""), BUBBLE_CORAL(-1, -1, 12464, "Bubble Coral", ""), BUBBLE_CORAL_BLOCK(-1, -1, 15437, "Bubble Coral Block", ""), BUBBLE_CORAL_FAN(-1, -1, 10795, "Bubble Coral Fan", ""), BUBBLE_CORAL_WALL_FAN(-1, -1, 20382, "Bubble Coral Wall Fan", ""), BUCKET(325, 0, 15215, "Bucket", ""), CACTUS(81, 0, 12191, "Cactus", "CACTUS"), CACTUS_GREEN(351, 2, 17296, "Cactus Green", ""), CAKE(354, 0, 27048, "Cake", ""), CARROT(391, 0, 22824, "Carrot", "Carrotitem"), CARROTS(141, 0, 17258, "Carrots", "CARROT"), CARROT_ON_A_STICK(398, 0, 27809, "Carrot on a Stick", "carrotstick"), CARVED_PUMPKIN(-1, -1, 25833, "Carved Pumpkin", ""), CAULDRON(380, 0, 26531, "Cauldron", "CAULDRON_ITEM"), CAVE_AIR(-1, -1, 17422, "Air", ""), CAVE_SPIDER_SPAWN_EGG(383, 59, 23341, "Spawn Cave Spider", "Cave Spider Spawn Egg"), CHAINMAIL_BOOTS(305, 0, 17953, "Chainmail Boots", ""), CHAINMAIL_CHESTPLATE(303, 0, 23602, "Chainmail Chestplate", "CHAINMAIL_CHESTPLATE"), CHAINMAIL_HELMET(302, 0, 26114, "Chainmail Helmet", "CHAINMAIL_HELMET"), CHAINMAIL_LEGGINGS(304, 0, 19087, "Chainmail Leggings", "CHAINMAIL_LEGGINGS"), CHAIN_COMMAND_BLOCK(-1, -1, 26798, "Chain Command Block", ""), CHARCOAL(263, 1, 5390, "Charcoal", "COAL"), CHEST(54, 0, 22969, "Chest", "CHEST"), CHEST_MINECART(342, 0, 4497, "Minecart with Chest", "Storageminecart"), CHICKEN(365, 0, 17281, "Raw Chicken", ""), CHICKEN_SPAWN_EGG(383, 93, 5462, "Spawn Chicken", "Chicken Spawn Egg"), CHIPPED_ANVIL(145, 1, 10623, "Chipped Anvil", ""), CHISELED_QUARTZ_BLOCK(155, 1, 30964, "Chiseled Quartz Block", "QUARTZ_BLOCK"), CHISELED_RED_SANDSTONE(179, 1, 15529, "Chiseled Red Sandstone", "RED_SANDSTONE"), CHISELED_SANDSTONE(24, 1, 31763, "Chiseled Sandstone", "SANDSTONE"), CHISELED_STONE_BRICKS(98, 3, 9087, "Chiseled Stone Bricks", "SMOOTH_BRICK"), CHORUS_FLOWER(200, 0, 28542, "Chorus Flower", "CHORUS_FLOWER"), CHORUS_FRUIT(432, 0, 7652, "Chorus Fruit", ""), CHORUS_PLANT(199, 0, 28243, "Chorus Plant", "CHORUS_PLANT"), CLAY(82, 0, 27880, "Clay", "CLAY"), CLAY_BALL(337, 0, 24603, "Clay Ball", "Clay"), CLOCK(347, 0, 14980, "Clock", "watch"), COAL(263, 0, 29067, "Coal", ""), COAL_BLOCK(173, 0, 27968, "Block of Coal", "COAL_BLOCK"), COAL_ORE(16, 0, 30965, "Coal Ore", "COAL_ORE"), COARSE_DIRT(3, 1, 15411, "Coarse Dirt", ""), COBBLESTONE(4, 0, 32147, "Cobblestone", ""), COBBLESTONE_SLAB(44, 3, 6340, "Cobblestone Slab", ""), COBBLESTONE_STAIRS(67, 0, 24715, "Cobblestone Stairs", "COBBLESTONE_STAIRS"), COBBLESTONE_WALL(139, 0, 12616, "Cobblestone Wall", "COBBLE_WALL"), COBWEB(30, 0, 9469, "Cobweb", "WEB"), COCOA(127, 0, 29709, "Cocoa", ""), COCOA_BEANS(351, 3, 27381, "Coco Beans", "INK_SACK"), COD(349, 0, 24691, "Raw Cod", "RAW_FISH"), COD_BUCKET(-1, -1, 28601, "Bucket of Cod", ""), COD_SPAWN_EGG(-1, -1, 27248, "Cod Spawn Egg", ""), COMMAND_BLOCK(137, 0, 4355, "Command Block", "COMMAND"), COMMAND_BLOCK_MINECART(422, 0, 7992, "Minecart with Command Block", ""), COMPARATOR(404, 0, 18911, "Redstone Comparator", ""), COMPASS(345, 0, 24139, "Compass", ""), CONDUIT(-1, -1, 5148, "Conduit", ""), COOKED_BEEF(364, 0, 21595, "Steak", ""), COOKED_CHICKEN(366, 0, 20780, "Cooked Chicken", ""), COOKED_COD(350, 0, 9681, "Cooked Fish", "COOKED_FISH"), COOKED_MUTTON(424, 0, 31447, "Cooked Mutton", ""), COOKED_PORKCHOP(320, 0, 27231, "Cooked Porkchop", "grilledpork"), COOKED_RABBIT(412, 0, 4454, "Cooked Rabbit", ""), COOKED_SALMON(350, 1, 5615, "Cooked Salmon", ""), COOKIE(357, 0, 27431, "Cookie", ""), COW_SPAWN_EGG(383, 92, 14761, "Spawn Cow", "Cow Spawn Egg"), CRACKED_STONE_BRICKS(98, 2, 27869, "Cracked Stone Bricks", ""), CRAFTING_TABLE(58, 0, 20706, "Crafting Table", "WORKBENCH"), CREEPER_HEAD(397, 4, 29146, "Mob Head (Creeper)", "Creeper Head"), CREEPER_SPAWN_EGG(383, 50, 9653, "Spawn Creeper", "Creeper Spawn Egg"), CREEPER_WALL_HEAD(144, 4, 30123, "Creeper Wall Head", ""), CUT_RED_SANDSTONE(-1, -1, 26842, "Cut Red Sandstone", ""), CUT_SANDSTONE(-1, -1, 6118, "Cut Sandstone", ""), CYAN_BANNER(425, 6, 9839, "Cyan Banner", ""), CYAN_BED(355, 9, 16746, "Cyan Bed", "Cyan Bed"), CYAN_CARPET(171, 9, 31495, "Cyan Carpet", ""), CYAN_CONCRETE(251, 9, 26522, "Cyan Concrete", ""), CYAN_CONCRETE_POWDER(252, 9, 15734, "Cyan Concrete Powder", ""), CYAN_DYE(351, 6, 8043, "Cyan Dye", ""), CYAN_GLAZED_TERRACOTTA(244, 0, 9550, "Cyan Glazed Terracotta", "CYAN_GLAZED_TERRACOTTA"), CYAN_SHULKER_BOX(228, 0, 28123, "Cyan Shulker Box", "CYAN_SHULKER_BOX"), CYAN_STAINED_GLASS(95, 9, 30604, "Cyan Stained Glass", ""), CYAN_STAINED_GLASS_PANE(160, 9, 11784, "Cyan Stained Glass Pane", ""), CYAN_TERRACOTTA(159, 9, 25940, "Cyan Terracotta", ""), CYAN_WALL_BANNER(117, 6, 10889, "Cyan Banner", ""), CYAN_WOOL(35, 9, 12221, "Cyan Wool", ""), DAMAGED_ANVIL(145, 2, 10274, "Damaged Anvil", ""), DANDELION(37, 0, 30558, "Dandelion", "YELLOW_FLOWER"), DANDELION_YELLOW(351, 11, 21789, "Dandelion Yellow", ""), DARK_OAK_BOAT(448, 0, 28618, "Dark Oak Boat", "BOAT_DARK_OAK"), DARK_OAK_BUTTON(-1, -1, 6214, "Dark Oak Button", ""), DARK_OAK_DOOR(431, 0, 10669, "Dark Oak Door", "DARK_OAK_DOOR_ITEM"), DARK_OAK_FENCE(191, 0, 21767, "Dark Oak Fence", "DARK_OAK_FENCE"), DARK_OAK_FENCE_GATE(186, 0, 10679, "Dark Oak Fence Gate", "DARK_OAK_FENCE_GATE"), DARK_OAK_LEAVES(161, 1, 22254, "Dark Oak Leaves", ""), DARK_OAK_LOG(162, 1, 14831, "Dark Oak Log", ""), DARK_OAK_PLANKS(5, 5, 20869, "Dark Oak Wood Plank", "Dark Oak Planks"), DARK_OAK_PRESSURE_PLATE(-1, -1, 31375, "Dark Oak Pressure Plate", ""), DARK_OAK_SAPLING(6, 5, 14933, "Dark Oak Sapling", ""), DARK_OAK_SLAB(126, 5, 28852, "Dark Oak Wood Slab", "Dark Oak Slab"), DARK_OAK_STAIRS(164, 0, 22921, "Dark Oak Stairs", "DARK_OAK_STAIRS"), DARK_OAK_TRAPDOOR(-1, -1, 10355, "Dark Oak Trapdoor", ""), DARK_OAK_WOOD(-1, -1, 7871, "Dark Oak Wood", ""), DARK_PRISMARINE(168, 2, 19940, "Dark Prismarine", "PRISMARINE"), DARK_PRISMARINE_SLAB(-1, -1, 7577, "Dark Prismarine Slab", ""), DARK_PRISMARINE_STAIRS(-1, -1, 26511, "Dark Prismarine Stairs", ""), DAYLIGHT_DETECTOR(151, 0, 8864, "Daylight Detector", "DAYLIGHT_DETECTOR"), DEAD_BRAIN_CORAL_BLOCK(-1, -1, 12979, "Dead Brain Coral Block", ""), DEAD_BRAIN_CORAL_FAN(-1, -1, 26150, "Dead Brain Coral Fan", ""), DEAD_BRAIN_CORAL_WALL_FAN(-1, -1, 23718, "Dead Brain Coral Wall Fan", ""), DEAD_BUBBLE_CORAL_BLOCK(-1, -1, 28220, "Dead Bubble Coral Block", ""), DEAD_BUBBLE_CORAL_FAN(-1, -1, 17322, "Dead Bubble Coral Fan", ""), DEAD_BUBBLE_CORAL_WALL_FAN(-1, -1, 18453, "Dead Bubble Coral Wall Fan", ""), DEAD_BUSH(32, 0, 22888, "Dead Bush", "DEAD_BUSH"), DEAD_FIRE_CORAL_BLOCK(-1, -1, 5307, "Dead Fire Coral Block", ""), DEAD_FIRE_CORAL_FAN(-1, -1, 27073, "Dead Fire Coral Fan", ""), DEAD_FIRE_CORAL_WALL_FAN(-1, -1, 23375, "Dead Fire Coral Wall Fan", ""), DEAD_HORN_CORAL_BLOCK(-1, -1, 15103, "Dead Horn Coral Block", ""), DEAD_HORN_CORAL_FAN(-1, -1, 11387, "Dead Horn Coral Fan", ""), DEAD_HORN_CORAL_WALL_FAN(-1, -1, 27550, "Dead Horn Coral Wall Fan", ""), DEAD_TUBE_CORAL_BLOCK(-1, -1, 28350, "Dead Tube Coral Block", ""), DEAD_TUBE_CORAL_FAN(-1, -1, 17628, "Dead Tube Coral Fan", ""), DEAD_TUBE_CORAL_WALL_FAN(-1, -1, 5128, "Dead Tube Coral Wall Fan", ""), DEBUG_STICK(-1, -1, 24562, "Debug Stick", ""), DETECTOR_RAIL(28, 0, 13475, "Detector Rail", "DETECTOR_RAIL"), DIAMOND(264, 0, 20865, "Diamond", "DIAMOND"), DIAMOND_AXE(279, 0, 27277, "Diamond Axe", "DIAMOND_AXE"), DIAMOND_BLOCK(57, 0, 5944, "Block of Diamond", "DIAMOND_BLOCK"), DIAMOND_BOOTS(313, 0, 16522, "Diamond Boots", ""), DIAMOND_CHESTPLATE(311, 0, 32099, "Diamond Chestplate", ""), DIAMOND_HELMET(310, 0, 10755, "Diamond Helmet", ""), DIAMOND_HOE(293, 0, 24050, "Diamond Hoe", "DIAMOND_HOE"), DIAMOND_HORSE_ARMOR(419, 0, 10321, "Diamond Horse Armor", "Diamond_barding"), DIAMOND_LEGGINGS(312, 0, 11202, "Diamond Leggings", ""), DIAMOND_ORE(56, 0, 9292, "Diamond Ore", "DIAMOND_ORE"), DIAMOND_PICKAXE(278, 0, 24291, "Diamond Pickaxe", "DIAMOND_PICKAXE"), DIAMOND_SHOVEL(277, 0, 25415, "Diamond Shovel", "DIAMOND_SPADE"), DIAMOND_SWORD(276, 0, 27707, "Diamond Sword", "DIAMOND_SWORD"), DIORITE(1, 3, 24688, "Diorite", ""), DIRT(3, 0, 10580, "Dirt", ""), DISPENSER(23, 0, 20871, "Dispenser", "DISPENSER"), DOLPHIN_SPAWN_EGG(-1, -1, 20787, "Dolphin Spawn Egg", ""), DONKEY_SPAWN_EGG(383, 31, 14513, "Spawn Donkey", "Donkey Spawn Egg"), DRAGON_BREATH(437, 0, 20154, "Dragon's Breath", ""), DRAGON_EGG(122, 0, 29946, "Dragon Egg", "DRAGON_EGG"), DRAGON_HEAD(397, 5, 20084, "Dragon Head", ""), DRAGON_WALL_HEAD(144, 5, 19818, "Dragon Wall Head", ""), DRIED_KELP(-1, -1, 21042, "Dried Kelp", ""), DRIED_KELP_BLOCK(-1, -1, 12966, "Dried Kelp Block", ""), DROPPER(158, 0, 31273, "Dropper", "DROPPER"), DROWNED_SPAWN_EGG(-1, -1, 19368, "Drowned Spawn Egg", ""), EGG(344, 0, 21603, "Egg", ""), ELDER_GUARDIAN_SPAWN_EGG(383, 4, 11418, "Spawn Elder Guardian", "Elder Guardian Spawn Egg"), ELYTRA(443, 0, 23829, "Elytra", ""), EMERALD(388, 0, 5654, "Emerald", ""), EMERALD_BLOCK(133, 0, 9914, "Emerald Block", "Block of Emerald"), EMERALD_ORE(129, 0, 16630, "Emerald Ore", ""), ENCHANTED_BOOK(403, 0, 11741, "Enchanted Book", ""), ENCHANTED_GOLDEN_APPLE(322, 1, 8280, "Enchanted Golden Apple", ""), ENCHANTING_TABLE(116, 0, 16255, "Enchanting Table", "ENCHANTMENT_TABLE"), ENDERMAN_SPAWN_EGG(383, 58, 29488, "Spawn Enderman", "Enderman Spawn Egg"), ENDERMITE_SPAWN_EGG(383, 67, 16617, "Spawn Endermite", "Endermite Spawn Egg"), ENDER_CHEST(130, 0, 32349, "Ender Chest", ""), ENDER_EYE(381, 0, 24860, "Eye of Ender", ""), ENDER_PEARL(368, 0, 5259, "Ender Pearl", ""), END_CRYSTAL(426, 0, 19090, "End Crystal", ""), END_GATEWAY(209, 0, 26605, "End Gateway", "END_GATEWAY"), END_PORTAL(119, 0, 16782, "End Portal", "ENDER_PORTAL"), END_PORTAL_FRAME(120, 0, 15480, "End Portal Frame", "ENDER_PORTAL_FRAME"), END_ROD(198, 0, 24832, "End Rod", "END_ROD"), END_STONE(121, 0, 29686, "End Stone", "ENDER_STONE"), END_STONE_BRICKS(206, 0, 20314, "End Stone Bricks", "END_BRICKS"), EVOKER_SPAWN_EGG(383, 34, 19365, "Spawn Evoker", "Evoker Spawn Egg"), EXPERIENCE_BOTTLE(384, 0, 12858, "Bottle o' Enchanting", "expbottle"), FARMLAND(60, 0, 31166, "Farmland", "SOIL"), FEATHER(288, 0, 30548, "Feather", "FEATHER"), FERMENTED_SPIDER_EYE(376, 0, 19386, "Fermented Spider Eye", ""), FERN(31, 2, 15794, "Fern", "LONG_GRASS"), FILLED_MAP(358, 0, 23504, "Map", ""), FIRE(51, 0, 16396, "Fire", "FIRE"), FIREWORK_ROCKET(401, 0, 23841, "Firework Rocket", ""), FIREWORK_STAR(402, 0, 12190, "Firework Star", "FIREWORK_CHARGE"), FIRE_CHARGE(385, 0, 4842, "Fire Charge", "Fireball"), FIRE_CORAL(-1, -1, 29151, "Fire Coral", ""), FIRE_CORAL_BLOCK(-1, -1, 12119, "Fire Coral Block", ""), FIRE_CORAL_FAN(-1, -1, 11112, "Fire Coral Fan", ""), FIRE_CORAL_WALL_FAN(-1, -1, 20100, "Fire Coral Wall Fan", ""), FISHING_ROD(346, 0, 4167, "Fishing Rod", ""), FLINT(318, 0, 23596, "Flint", ""), FLINT_AND_STEEL(259, 0, 28620, "Flint and Steel", "FLINT_AND_STEEL"), FLOWER_POT(390, 0, 30567, "Flower Pot", "FLOWER_POT_ITEM"), FROSTED_ICE(212, 0, 21814, "Frosted Ice", "FROSTED_ICE"), FURNACE(61, 0, 8133, "Furnace", ""), FURNACE_MINECART(343, 0, 14196, "Minecart with Furnace", "POWERED_MINECART"), GHAST_SPAWN_EGG(383, 56, 9970, "Spawn Ghast", "Ghast Spawn Egg"), GHAST_TEAR(370, 0, 18222, "Ghast Tear", ""), GLASS(20, 0, 6195, "Glass", "GLASS"), GLASS_BOTTLE(374, 0, 6116, "Glass Bottle", ""), GLASS_PANE(102, 0, 5709, "Glass Pane", "THIN_GLASS"), GLISTERING_MELON_SLICE(382, 0, 20158, "Glistering Melon", "speckledmelon"), GLOWSTONE(89, 0, 32713, "Glowstone", "GLOWSTONE"), GLOWSTONE_DUST(348, 0, 6665, "Glowstone Dust", ""), GOLDEN_APPLE(322, 0, 27732, "Golden Apple", "Gold apple"), GOLDEN_AXE(286, 0, 4878, "Golden Axe", "Gold Axe"), GOLDEN_BOOTS(317, 0, 7859, "Golden Boots", "Gold Boots"), GOLDEN_CARROT(396, 0, 5300, "Golden Carrot", "Gold Carrot"), GOLDEN_CHESTPLATE(315, 0, 4507, "Golden Chestplate", "Gold Chestplate"), GOLDEN_HELMET(314, 0, 7945, "Golden Helmet", "Gold Helmet"), GOLDEN_HOE(294, 0, 19337, "Golden Hoe", "Gold Hoe"), GOLDEN_HORSE_ARMOR(418, 0, 7996, "Golden Horse Armor", "Gold Barding"), GOLDEN_LEGGINGS(316, 0, 21002, "Golden Leggings", "Gold Leggings"), GOLDEN_PICKAXE(285, 0, 10901, "Golden Pickaxe", "GOLD_PICKAXE"), GOLDEN_SHOVEL(284, 0, 15597, "Golden Shovel", "GOLD_SPADE"), GOLDEN_SWORD(283, 0, 10505, "Golden Sword", "GOLD_SWORD"), GOLD_BLOCK(41, 0, 27392, "Block of Gold", "GOLD_BLOCK"), GOLD_INGOT(266, 0, 28927, "Gold Ingot", "GOLD_INGOT"), GOLD_NUGGET(371, 0, 28814, "Gold Nugget", ""), GOLD_ORE(14, 0, 32625, "Gold Ore", "GOLD_ORE"), GRANITE(1, 1, 21091, "Granite", ""), GRASS(31, 1, 6155, "Grass", ""), GRASS_BLOCK(2, 0, 28346, "Grass", "Grass Block"), GRASS_PATH(208, 0, 8604, "Grass Path", "GRASS_PATH"), GRAVEL(13, 0, 7804, "Gravel", "GRAVEL"), GRAY_BANNER(425, 8, 12053, "Gray Banner", ""), GRAY_BED(355, 7, 15745, "Gray Bed", "Gray Bed"), GRAY_CARPET(171, 7, 26991, "Gray Carpet", ""), GRAY_CONCRETE(251, 7, 13959, "Gray Concrete", ""), GRAY_CONCRETE_POWDER(252, 7, 13031, "Gray Concrete Powder", ""), GRAY_DYE(351, 8, 9184, "Gray Dye", ""), GRAY_GLAZED_TERRACOTTA(242, 0, 6256, "Gray Glazed Terracotta", "GRAY_GLAZED_TERRACOTTA"), GRAY_SHULKER_BOX(226, 0, 12754, "Gray Shulker Box", "GRAY_SHULKER_BOX"), GRAY_STAINED_GLASS(95, 7, 29979, "Gray Stained Glass", ""), GRAY_STAINED_GLASS_PANE(160, 7, 25272, "Gray Stained Glass Pane", ""), GRAY_TERRACOTTA(159, 7, 18004, "Gray Terracotta", ""), GRAY_WALL_BANNER(117, 8, 24275, "Gray Banner", ""), GRAY_WOOL(35, 7, 27209, "Gray Wool", ""), GREEN_BANNER(425, 2, 10698, "Green Banner", ""), GREEN_BED(355, 13, 13797, "Green Bed", "Green Bed"), GREEN_CARPET(171, 13, 7780, "Green Carpet", ""), GREEN_CONCRETE(251, 13, 17949, "Green Concrete", ""), GREEN_CONCRETE_POWDER(252, 13, 6904, "Green Concrete Powder", ""), GREEN_GLAZED_TERRACOTTA(248, 0, 6958, "Green Glazed Terracotta", "GREEN_GLAZED_TERRACOTTA"), GREEN_SHULKER_BOX(232, 0, 9377, "Green Shulker Box", "GREEN_SHULKER_BOX"), GREEN_STAINED_GLASS(95, 13, 22503, "Green Stained Glass", ""), GREEN_STAINED_GLASS_PANE(160, 13, 4767, "Green Stained Glass Pane", ""), GREEN_TERRACOTTA(159, 13, 4105, "Green Terracotta", ""), GREEN_WALL_BANNER(117, 2, 15046, "Green Banner", ""), GREEN_WOOL(35, 13, 25085, "Green Wool", ""), GUARDIAN_SPAWN_EGG(383, 68, 20113, "Spawn Guardian", "Guardian Spawn Egg"), GUNPOWDER(289, 0, 29974, "Gunpowder", "SULPHUR"), HAY_BLOCK(170, 0, 17461, "Hay Bale", "HAY_BLOCK"), HEART_OF_THE_SEA(-1, -1, 11807, "Heart of the Sea", ""), HEAVY_WEIGHTED_PRESSURE_PLATE(148, 0, 16970, "Heavy Weighted Pressure Plate", "IRON_PLATE"), HOPPER(154, 0, 31974, "Hopper", "HOPPER"), HOPPER_MINECART(408, 0, 19024, "Minecart with Hopper", ""), HORN_CORAL(-1, -1, 19511, "Horn Coral", ""), HORN_CORAL_BLOCK(-1, -1, 19958, "Horn Coral Block", ""), HORN_CORAL_FAN(-1, -1, 13610, "Horn Coral Fan", ""), HORN_CORAL_WALL_FAN(-1, -1, 28883, "Horn Coral Wall Fan", ""), HORSE_SPAWN_EGG(383, 100, 25981, "Spawn Horse", "Horse Spawn Egg"), HUSK_SPAWN_EGG(383, 23, 20178, "Spawn Husk", "Husk Spawn Egg"), ICE(79, 0, 30428, "Ice", "ICE"), INFESTED_CHISELED_STONE_BRICKS(97, 5, 4728, "Infested Chiseled Stone Bricks", "MONSTER_EGGS"), INFESTED_COBBLESTONE(97, 1, 28798, "Infested Cobblestone", ""), INFESTED_CRACKED_STONE_BRICKS(97, 4, 7476, "Infested Cracked Stone Bricks", ""), INFESTED_MOSSY_STONE_BRICKS(97, 3, 9850, "Infested Mossy Stone Bricks", ""), INFESTED_STONE(97, 0, 18440, "Infested Stone", ""), INFESTED_STONE_BRICKS(97, 2, 19749, "Infested Stone Bricks", ""), INK_SAC(351, 0, 7184, "Ink Sack", "Ink Sac"), IRON_AXE(258, 0, 15894, "Iron Axe", "IRON_AXE"), IRON_BARS(101, 0, 9378, "Iron Bars", "IRON_FENCE"), IRON_BLOCK(42, 0, 24754, "Block of Iron", "IRON_BLOCK"), IRON_BOOTS(309, 0, 8531, "Iron Boots", ""), IRON_CHESTPLATE(307, 0, 28112, "Iron Chestplate", ""), IRON_DOOR(330, 0, 4788, "Iron Door", ""), IRON_HELMET(306, 0, 12025, "Iron Helmet", ""), IRON_HOE(292, 0, 11339, "Iron Hoe", "IRON_HOE"), IRON_HORSE_ARMOR(417, 0, 30108, "Iron Horse Armor", "Iron_barding"), IRON_INGOT(265, 0, 24895, "Iron Ingot", "IRON_INGOT"), IRON_LEGGINGS(308, 0, 18951, "Iron Leggings", ""), IRON_NUGGET(452, 0, 13715, "Iron Nugget", ""), IRON_ORE(15, 0, 19834, "Iron Ore", "IRON_ORE"), IRON_PICKAXE(257, 0, 8842, "Iron Pickaxe", "IRON_PICKAXE"), IRON_SHOVEL(256, 0, 30045, "Iron Shovel", "IRON_SPADE"), IRON_SWORD(267, 0, 10904, "Iron Sword", "IRON_SWORD"), IRON_TRAPDOOR(167, 0, 17095, "Iron Trapdoor", "IRON_TRAPDOOR"), ITEM_FRAME(389, 0, 27318, "Item Frame", ""), JACK_O_LANTERN(91, 0, 31612, "Jack o'Lantern", "JACK_O_LANTERN"), JUKEBOX(84, 0, 19264, "Jukebox", "JUKEBOX"), JUNGLE_BOAT(446, 0, 4495, "Jungle Boat", "BOAT_JUNGLE"), JUNGLE_BUTTON(-1, -1, 25317, "Jungle Button", ""), JUNGLE_DOOR(429, 0, 28163, "Jungle Door", "JUNGLE_DOOR_ITEM"), JUNGLE_FENCE(190, 0, 14358, "Jungle Fence", "JUNGLE_FENCE"), JUNGLE_FENCE_GATE(185, 0, 21360, "Jungle Fence Gate", "JUNGLE_FENCE_GATE"), JUNGLE_LEAVES(18, 3, 5133, "Jungle Leaves", ""), JUNGLE_LOG(17, 3, 20721, "Jungle Log", ""), JUNGLE_PLANKS(5, 3, 26445, "Jungle Wood Plank", "Jungle Planks"), JUNGLE_PRESSURE_PLATE(-1, -1, 11376, "Jungle Pressure Plate", ""), JUNGLE_SAPLING(6, 3, 17951, "Jungle Sapling", ""), JUNGLE_SLAB(43, 0, 19117, "Double Stone Slab", ""), JUNGLE_STAIRS(136, 0, 20636, "Jungle Wood Stairs", "Jungle Stairs"), JUNGLE_TRAPDOOR(-1, -1, 8626, "Jungle Trapdoor", ""), JUNGLE_WOOD(-1, -1, 30228, "Jungle Wood", ""), KELP(-1, -1, 21916, "Kelp", ""), KELP_PLANT(-1, -1, 29697, "Kelp Plant", ""), KNOWLEDGE_BOOK(453, 0, 12646, "Knowledge Book", ""), LADDER(65, 0, 23599, "Ladder", "LADDER"), LAPIS_BLOCK(22, 0, 14485, "Lapis Lazuli Block", "LAPIS_BLOCK"), LAPIS_LAZULI(351, 4, 11075, "Lapis Lazuli", ""), LAPIS_ORE(21, 0, 22934, "Lapis Lazuli Ore", "LAPIS_ORE"), LARGE_FERN(175, 3, 30177, "Large Fern", "DOUBLE_PLANT"), LAVA(10, 0, 8415, "Flowing Lava", "FLOWING_LAVA"), LAVA_BUCKET(327, 0, 9228, "Lava Bucket", ""), LEAD(420, 0, 29539, "Lead", "Leash"), LEATHER(334, 0, 16414, "Leather", ""), LEATHER_BOOTS(301, 0, 15282, "Leather Boots", "LEATHER_BOOTS"), LEATHER_CHESTPLATE(299, 0, 29275, "Leather Tunic", "LEATHER_CHESTPLATE"), LEATHER_HELMET(298, 0, 11624, "Leather Cap", "LEATHER_HELMET"), LEATHER_LEGGINGS(300, 0, 28210, "Leather Pants", "LEATHER_LEGGINGS"), LEVER(69, 0, 15319, "Lever", "LEVER"), LIGHT_BLUE_BANNER(425, 12, 18060, "Light Blue Banner", ""), LIGHT_BLUE_BED(355, 3, 20957, "Light Blue Bed", "Light Blue Bed"), LIGHT_BLUE_CARPET(171, 3, 21194, "Light Blue Carpet", ""), LIGHT_BLUE_CONCRETE(251, 3, 29481, "Light Blue Concrete", ""), LIGHT_BLUE_CONCRETE_POWDER(252, 3, 31206, "Light Blue Concrete Powder", ""), LIGHT_BLUE_DYE(351, 12, 28738, "Light Blue Dye", ""), LIGHT_BLUE_GLAZED_TERRACOTTA(238, 0, 4336, "Light Blue Glazed Terracotta", "LIGHT_BLUE_GLAZED_TERRACOTTA"), LIGHT_BLUE_SHULKER_BOX(222, 0, 18226, "Light Blue Shulker Box", "LIGHT_BLUE_SHULKER_BOX"), LIGHT_BLUE_STAINED_GLASS(95, 3, 17162, "Light Blue Stained Glass", ""), LIGHT_BLUE_STAINED_GLASS_PANE(160, 3, 18721, "Light Blue Stained Glass Pane", ""), LIGHT_BLUE_TERRACOTTA(159, 3, 31779, "Light Blue Terracotta", ""), LIGHT_BLUE_WALL_BANNER(117, 12, 12011, "Light Blue Banner", ""), LIGHT_BLUE_WOOL(35, 3, 21073, "Light Blue Wool", ""), LIGHT_GRAY_BANNER(425, 7, 11417, "Light Gray Banner", ""), LIGHT_GRAY_BED(355, 8, 5090, "Light Gray Bed", "Light Gray Bed"), LIGHT_GRAY_CARPET(171, 8, 11317, "Light Gray Carpet", ""), LIGHT_GRAY_CONCRETE(251, 8, 14453, "Light Gray Concrete", ""), LIGHT_GRAY_CONCRETE_POWDER(252, 8, 21589, "Light Gray Concrete Powder", ""), LIGHT_GRAY_DYE(351, 7, 27643, "Light Gray Dye", ""), LIGHT_GRAY_GLAZED_TERRACOTTA(243, 0, 10707, "Light Gray Glazed Terracotta", "SILVER_GLAZED_TERRACOTTA"), LIGHT_GRAY_SHULKER_BOX(227, 0, 21345, "Light Gray Shulker Box", "SILVER_SHULKER_BOX"), LIGHT_GRAY_STAINED_GLASS(95, 8, 5843, "Light Gray Stained Glass", ""), LIGHT_GRAY_STAINED_GLASS_PANE(160, 8, 19008, "Light Gray Stained Glass Pane", ""), LIGHT_GRAY_TERRACOTTA(159, 8, 26388, "Light Gray Terracotta", ""), LIGHT_GRAY_WALL_BANNER(117, 7, 31088, "Light Gray Banner", ""), LIGHT_GRAY_WOOL(35, 8, 22936, "Light Gray Wool", ""), LIGHT_WEIGHTED_PRESSURE_PLATE(147, 0, 14875, "Light Weighted Pressure Plate", "GOLD_PLATE"), LILAC(175, 1, 22837, "Lilac", ""), LILY_PAD(111, 0, 19271, "Lily Pad", "WATER_LILY"), LIME_BANNER(425, 10, 18887, "Lime Banner", ""), LIME_BED(355, 5, 27860, "Lime Bed", "Lime Bed"), LIME_CARPET(171, 5, 15443, "Lime Carpet", ""), LIME_CONCRETE(251, 5, 5863, "Lime Concrete", ""), LIME_CONCRETE_POWDER(252, 5, 28859, "Lime Concrete Powder", ""), LIME_DYE(351, 10, 6147, "Lime Dye", ""), LIME_GLAZED_TERRACOTTA(240, 0, 13861, "Lime Glazed Terracotta", "LIME_GLAZED_TERRACOTTA"), LIME_SHULKER_BOX(224, 0, 28360, "Lime Shulker Box", "LIME_SHULKER_BOX"), LIME_STAINED_GLASS(95, 5, 24266, "Lime Stained Glass", ""), LIME_STAINED_GLASS_PANE(160, 5, 10610, "Lime Stained Glass Pane", ""), LIME_TERRACOTTA(159, 5, 24013, "Lime Terracotta", ""), LIME_WALL_BANNER(117, 10, 21422, "Lime Banner", ""), LIME_WOOL(35, 5, 10443, "Lime Wool", ""), LINGERING_POTION(441, 0, 25857, "Lingering Potion", ""), LLAMA_SPAWN_EGG(383, 103, 23640, "Spawn Llama", "Llama Spawn Egg"), MAGENTA_BANNER(425, 13, 15591, "Magenta Banner", ""), MAGENTA_BED(355, 2, 20061, "Magenta Bed", "Magenta Bed"), MAGENTA_CARPET(171, 2, 6180, "Magenta Carpet", ""), MAGENTA_CONCRETE(251, 2, 20591, "Magenta Concrete", ""), MAGENTA_CONCRETE_POWDER(252, 2, 8272, "Magenta Concrete Powder", ""), MAGENTA_DYE(351, 13, 11788, "Magenta Dye", ""), MAGENTA_GLAZED_TERRACOTTA(237, 0, 8067, "Magenta Glazed Terracotta", "MAGENTA_GLAZED_TERRACOTTA"), MAGENTA_SHULKER_BOX(221, 0, 21566, "Magenta Shulker Box", "MAGENTA_SHULKER_BOX"), MAGENTA_STAINED_GLASS(95, 2, 26814, "Magenta Stained Glass", ""), MAGENTA_STAINED_GLASS_PANE(160, 2, 14082, "Magenta Stained Glass Pane", ""), MAGENTA_TERRACOTTA(159, 2, 25900, "Magenta Terracotta", ""), MAGENTA_WALL_BANNER(117, 13, 23291, "Magenta Banner", ""), MAGENTA_WOOL(35, 2, 11853, "Magenta Wool", ""), MAGMA_BLOCK(213, 0, 25927, "Magma Block", "MAGMA"), MAGMA_CREAM(378, 0, 25097, "Magma Cream", ""), MAGMA_CUBE_SPAWN_EGG(383, 62, 26638, "Spawn Magma Cube", "Magma Cube Spawn Egg"), MAP(395, 0, 21655, "Empty Map", "EMPTY_MAP"), MELON(103, 0, 25172, "Melon", "Melon_Block"), MELON_SEEDS(362, 0, 18340, "Melon Seeds", ""), MELON_SLICE(360, 0, 5347, "Melon", "Melon Slice"), MELON_STEM(105, 0, 8247, "Melon Stem", "MELON_STEM"), MILK_BUCKET(335, 0, 9680, "Milk Bucket", ""), MINECART(328, 0, 14352, "Minecart", ""), MOOSHROOM_SPAWN_EGG(383, 96, 22125, "Spawn Mushroom Cow", "Mooshroom Spawn Egg"), MOSSY_COBBLESTONE(48, 0, 21900, "Mossy Cobblestone", "MOSSY_COBBLESTONE"), MOSSY_COBBLESTONE_WALL(139, 1, 11536, "Mossy Cobblestone Wall", ""), MOSSY_STONE_BRICKS(98, 1, 16415, "Mossy Stone Bricks", ""), MOVING_PISTON(36, 0, 13831, "Piston Moving Piece", ""), MULE_SPAWN_EGG(383, 32, 11229, "Spawn Mule", "Mule Spawn Egg"), MUSHROOM_STEM(-1, -1, 16543, "Mushroom Stem", ""), MUSHROOM_STEW(282, 0, 16336, "Mushroom Stew", "MUSHROOM_SOUP"), MUSIC_DISC_11(2266, 0, 27426, "11 Disc", "RECORD_11"), MUSIC_DISC_13(2256, 0, 16359, "13 Disc", "GOLD_RECORD"), MUSIC_DISC_BLOCKS(2258, 0, 26667, "Blocks Disc", "RECORD_3"), MUSIC_DISC_CAT(2257, 0, 16246, "Cat Disc", "GREEN_RECORD"), MUSIC_DISC_CHIRP(2259, 0, 19436, "Chirp Disc", "RECORD_4"), MUSIC_DISC_FAR(2260, 0, 13823, "Far Disc", "RECORD_5"), MUSIC_DISC_MALL(2261, 0, 11517, "Mall Disc", "RECORD_6"), MUSIC_DISC_MELLOHI(2262, 0, 26117, "Mellohi Disc", "RECORD_7"), MUSIC_DISC_STAL(2263, 0, 14989, "Stal Disc", "RECORD_8"), MUSIC_DISC_STRAD(2264, 0, 16785, "Strad Disc", "RECORD_9"), MUSIC_DISC_WAIT(2267, 0, 26499, "Wait Disc", "RECORD_12"), MUSIC_DISC_WARD(2265, 0, 24026, "Ward Disc", "RECORD_10"), MUTTON(423, 0, 4792, "Raw Mutton", ""), MYCELIUM(110, 0, 9913, "Mycelium", "MYCEL"), NAME_TAG(421, 0, 30731, "Name Tag", ""), NAUTILUS_SHELL(-1, -1, 19989, "Nautilus Shell", ""), NETHERRACK(87, 0, 23425, "Netherrack", "NETHERRACK"), NETHER_BRICK(405, 0, 19996, "Nether Brick", "NETHER_BRICK"), NETHER_BRICKS(112, 0, 27802, "Nether Bricks"), NETHER_BRICK_FENCE(113, 0, 5286, "Nether Brick Fence", "NETHER_FENCE"), NETHER_BRICK_SLAB(44, 6, 26586, "Nether Brick Slab", ""), NETHER_BRICK_STAIRS(114, 0, 12085, "Nether Brick Stairs", "NETHER_BRICK_STAIRS"), NETHER_PORTAL(90, 0, 19085, "Nether Portal", "PORTAL"), NETHER_QUARTZ_ORE(153, 0, 4807, "Nether Quartz Ore", "QUARTZ_ORE"), NETHER_STAR(399, 0, 12469, "Nether Star", ""), NETHER_WART(372, 0, 29227, "Nether Wart", "NETHER_STALK"), NETHER_WART_BLOCK(214, 0, 15486, "Nether Wart Block", "NETHER_WART_BLOCK"), NOTE_BLOCK(25, 0, 20979, "Note Block", "NOTE_BLOCK"), OAK_BOAT(333, 0, 17570, "Boat", "Oak Boat"), OAK_BUTTON(143, 0, 13510, "Oak Button", "Wooden_button"), OAK_DOOR(324, 0, 20341, "Wooden Door", "Wood Door"), OAK_FENCE(85, 0, 6442, "Oak Fence", "FENCE"), OAK_FENCE_GATE(107, 0, 16689, "Oak Fence Gate", "FENCE_GATE"), OAK_LEAVES(18, 0, 4385, "Oak Leaves", ""), OAK_LOG(17, 0, 26723, "Oak Log", ""), OAK_PLANKS(5, 0, 14905, "Oak Wood Plank", "Oak Planks"), OAK_PRESSURE_PLATE(72, 0, 20108, "Oak Pressure Plate", "Wooden_Presure_Plate"), OAK_SAPLING(6, 0, 9636, "Oak Sapling", ""), OAK_SLAB(126, 0, 12002, "Oak Slab", "Wood step"), OAK_STAIRS(53, 0, 5449, "Oak Stairs", "WOOD_STAIRS"), OAK_TRAPDOOR(96, 0, 16927, "Oak Trapdoor", "Trapdoor"), OAK_WOOD(-1, -1, 23286, "Oak Wood", ""), OBSERVER(218, 0, 10726, "Observer", "OBSERVER"), OBSIDIAN(49, 0, 32723, "Obsidian", "OBSIDIAN"), OCELOT_SPAWN_EGG(383, 98, 30080, "Spawn Ocelot", "Ocelot Spawn Egg"), ORANGE_BANNER(425, 14, 4839, "Orange Banner", ""), ORANGE_BED(355, 1, 11194, "Orange Bed", "Orange Bed"), ORANGE_CARPET(171, 1, 24752, "Orange Carpet", ""), ORANGE_CONCRETE(251, 1, 19914, "Orange Concrete", ""), ORANGE_CONCRETE_POWDER(252, 1, 30159, "Orange Concrete Powder", ""), ORANGE_DYE(351, 14, 13866, "Orange Dye", ""), ORANGE_GLAZED_TERRACOTTA(236, 0, 27451, "Orange Glazed Terracotta", "ORANGE_GLAZED_TERRACOTTA"), ORANGE_SHULKER_BOX(220, 0, 21673, "Orange Shulker Box", "ORANGE_SHULKER_BOX"), ORANGE_STAINED_GLASS(95, 1, 25142, "Orange Stained Glass", ""), ORANGE_STAINED_GLASS_PANE(160, 1, 21089, "Orange Stained Glass Pane", ""), ORANGE_TERRACOTTA(159, 1, 18684, "Orange Terracotta", ""), ORANGE_TULIP(38, 5, 26038, "Orange Tulip", ""), ORANGE_WALL_BANNER(117, 114, 9936, "Orange Banner", ""), ORANGE_WOOL(35, 1, 23957, "Orange Wool", ""), OXEYE_DAISY(38, 8, 11709, "Oxeye Daisy", ""), PACKED_ICE(174, 0, 28993, "Packed Ice", "PACKED_ICE"), PAINTING(321, 0, 23945, "Painting", ""), PAPER(339, 0, 9923, "Paper", ""), PARROT_SPAWN_EGG(383, 105, 23614, "Spawn Parrot", "Parrot Spawn Egg"), PEONY(175, 5, 21155, "Peony", ""), PETRIFIED_OAK_SLAB(-1, -1, 18658, "Petrified Oak Slab", ""), PHANTOM_MEMBRANE(-1, -1, 18398, "Phantom Membrane", ""), PHANTOM_SPAWN_EGG(-1, -1, 24648, "Phantom Spawn Egg", ""), PIG_SPAWN_EGG(383, 90, 22584, "Spawn Pig", "Pig Spawn Egg"), PINK_BANNER(425, 9, 19439, "Pink Banner", ""), PINK_BED(355, 6, 13795, "Pink Bed", "Pink Bed"), PINK_CARPET(171, 6, 30186, "Pink Carpet", ""), PINK_CONCRETE(251, 6, 5227, "Pink Concrete", ""), PINK_CONCRETE_POWDER(252, 6, 6421, "Pink Concrete Powder", ""), PINK_DYE(351, 9, 31151, "Pink Dye", ""), PINK_GLAZED_TERRACOTTA(241, 0, 10260, "Pink Glazed Terracotta", "PINK_GLAZED_TERRACOTTA"), PINK_SHULKER_BOX(225, 0, 24968, "Pink Shulker Box", "PINK_SHULKER_BOX"), PINK_STAINED_GLASS(95, 6, 16164, "Pink Stained Glass", ""), PINK_STAINED_GLASS_PANE(160, 6, 24637, "Pink Stained Glass Pane", ""), PINK_TERRACOTTA(159, 6, 23727, "Pink Terracotta", ""), PINK_TULIP(38, 7, 27319, "Pink Tulip", ""), PINK_WALL_BANNER(117, 9, 9421, "Pink Banner", ""), PINK_WOOL(35, 6, 7611, "Pink Wool", ""), PISTON(33, 0, 21130, "Piston", "PISTON_BASE"), PISTON_HEAD(34, 0, 30226, "Piston Head", "PISTON_EXTENSION"), PLAYER_HEAD(397, 3, 21174, "Mob Head (Human)", "Player Head"), PLAYER_WALL_HEAD(144, 3, 13164, "Player Wall Head", ""), PODZOL(3, 2, 24068, "Podzol", ""), POISONOUS_POTATO(394, 0, 32640, "Poisonous Potato", ""), POLAR_BEAR_SPAWN_EGG(383, 102, 17015, "Spawn Polar Bear", "Polar Bear Spawn Egg"), POLISHED_ANDESITE(1, 6, 8335, "Polished Andesite", ""), POLISHED_DIORITE(1, 4, 31615, "Polished Diorite", ""), POLISHED_GRANITE(1, 2, 5477, "Polished Granite", ""), POPPED_CHORUS_FRUIT(433, 0, 16880, "Popped Chorus Fruit", ""), POPPY(38, 0, 12851, "Poppy", ""), PORKCHOP(319, 0, 30896, "Raw Porkchop", ""), POTATO(392, 0, 21088, "Potato", "Potatoitem"), POTATOES(142, 0, 10879, "Potatoes", "POTATO"), POTION(373, 0, 24020, "Potion", ""), POTTED_ACACIA_SAPLING(-1, -1, 14096, "Potted Acacia Sapling", ""), POTTED_ALLIUM(-1, -1, 13184, "Potted Allium", ""), POTTED_AZURE_BLUET(-1, -1, 8754, "Potted Azure Bluet", ""), POTTED_BIRCH_SAPLING(-1, -1, 32484, "Potted Birch Sapling", ""), POTTED_BLUE_ORCHID(-1, -1, 6599, "Potted Blue Orchid", ""), POTTED_BROWN_MUSHROOM(-1, -1, 14481, "Potted Brown Mushroom", ""), POTTED_CACTUS(-1, -1, 8777, "Potted Cactus", ""), POTTED_DANDELION(-1, -1, 9727, "Potted Dandelion", ""), POTTED_DARK_OAK_SAPLING(-1, -1, 6486, "Potted Dark Oak Sapling", ""), POTTED_DEAD_BUSH(-1, -1, 13020, "Potted Dead Bush", ""), POTTED_FERN(-1, -1, 23315, "Potted Fern", ""), POTTED_JUNGLE_SAPLING(-1, -1, 7525, "Potted Jungle Sapling", ""), POTTED_OAK_SAPLING(-1, -1, 11905, "Potted Oak Sapling", ""), POTTED_ORANGE_TULIP(-1, -1, 28807, "Potted Orange Tulip", ""), POTTED_OXEYE_DAISY(-1, -1, 19707, "Potted Oxeye Daisy", ""), POTTED_PINK_TULIP(-1, -1, 10089, "Potted Pink Tulip", ""), POTTED_POPPY(-1, -1, 7457, "Potted Poppy", ""), POTTED_RED_MUSHROOM(-1, -1, 22881, "Potted Red Mushroom", ""), POTTED_RED_TULIP(-1, -1, 28594, "Potted Red Tulip", ""), POTTED_SPRUCE_SAPLING(-1, -1, 29498, "Potted Spruce Sapling", ""), POTTED_WHITE_TULIP(-1, -1, 24330, "Potted White Tulip", ""), POWERED_RAIL(27, 0, 11064, "Powered Rail", "POWERED_RAIL"), PRISMARINE(168, 0, 7539, "Prismarine", ""), PRISMARINE_BRICKS(168, 1, 29118, "Prismarine Bricks", ""), PRISMARINE_BRICK_SLAB(-1, -1, 26672, "Prismarine Brick Slab", ""), PRISMARINE_BRICK_STAIRS(-1, -1, 15445, "Prismarine Brick Stairs", ""), PRISMARINE_CRYSTALS(410, 0, 31546, "Prismarine Crystals", ""), PRISMARINE_SHARD(409, 0, 10993, "Prismarine Shard", ""), PRISMARINE_SLAB(-1, -1, 31323, "Prismarine Slab", ""), PRISMARINE_STAIRS(-1, -1, 19217, "Prismarine Stairs", ""), PUFFERFISH(349, 3, 8115, "Pufferfish", ""), PUFFERFISH_BUCKET(-1, -1, 8861, "Bucket of Pufferfish", ""), PUFFERFISH_SPAWN_EGG(-1, -1, 24573, "Pufferfish Spawn Egg", ""), PUMPKIN(86, 0, 19170, "Pumpkin", "PUMPKIN"), PUMPKIN_PIE(400, 0, 28725, "Pumpkin Pie", ""), PUMPKIN_SEEDS(361, 0, 28985, "Pumpkin Seeds", ""), PUMPKIN_STEM(104, 0, 19021, "Pumpkin Stem", "PUMPKIN_STEM"), PURPLE_BANNER(425, 5, 29027, "Purple Banner", ""), PURPLE_BED(355, 10, 29755, "Purple Bed", "Purple Bed"), PURPLE_CARPET(171, 10, 5574, "Purple Carpet", ""), PURPLE_CONCRETE(251, 10, 20623, "Purple Concrete", ""), PURPLE_CONCRETE_POWDER(252, 10, 26808, "Purple Concrete Powder", ""), PURPLE_DYE(351, 5, 6347, "Purple Dye", ""), PURPLE_GLAZED_TERRACOTTA(245, 0, 4818, "Purple Glazed Terracotta", ""), PURPLE_SHULKER_BOX(229, 0, 10373, "Purple Shulker Box", "PURPLE_SHULKER_BOX"), PURPLE_STAINED_GLASS(95, 10, 21845, "Purple Stained Glass", ""), PURPLE_STAINED_GLASS_PANE(160, 10, 10948, "Purple Stained Glass Pane", ""), PURPLE_TERRACOTTA(159, 10, 10387, "Purple Terracotta", ""), PURPLE_WALL_BANNER(117, 5, 14298, "Purple Banner", ""), PURPLE_WOOL(35, 10, 11922, "Purple Wool", ""), PURPUR_BLOCK(201, 0, 7538, "Purpur Block", "PURPUR_BLOCK"), PURPUR_PILLAR(202, 0, 26718, "Purpur Pillar", "PURPUR_PILLAR"), PURPUR_SLAB(205, 0, 11487, "Purpur Slab", "PURPUR_SLAB"), PURPUR_STAIRS(203, 0, 8921, "Purpur Stairs", "PURPUR_STAIRS"), QUARTZ(406, 0, 23608, "Nether Quartz", ""), QUARTZ_BLOCK(155, 0, 11987, "Block of Quartz", ""), QUARTZ_PILLAR(155, 2, 16452, "Quartz Pillar", ""), QUARTZ_SLAB(44, 7, 4423, "Quartz Slab", ""), QUARTZ_STAIRS(156, 0, 24079, "Quartz Stairs", "QUARTZ_STAIRS"), RABBIT(411, 0, 23068, "Raw Rabbit", ""), RABBIT_FOOT(414, 0, 13864, "Rabbit's Foot", ""), RABBIT_HIDE(415, 0, 12467, "Rabbit Hide", ""), RABBIT_SPAWN_EGG(383, 101, 26496, "Spawn Rabbit", "Rabbit Spawn Egg"), RABBIT_STEW(413, 0, 10611, "Rabbit Stew", ""), RAIL(66, 0, 13285, "Rail", "RAILS"), REDSTONE(331, 0, 11233, "Redstone", "Redstone Dust"), REDSTONE_BLOCK(152, 0, 19496, "Block of Redstone", "REDSTONE_BLOCK"), REDSTONE_LAMP(123, 0, 8217, "Redstone Lamp", "REDSTONE_LAMP_OFF"), REDSTONE_ORE(73, 0, 10887, "Redstone Ore"), REDSTONE_TORCH(76, 0, 22547, "Redstone Torch(on)", "REDSTONE_TORCH_ON"), REDSTONE_WALL_TORCH(76, 0, 7595, "Redstone Wall Torch", ""), REDSTONE_WIRE(55, 0, 25984, "Redstone Dust", "REDSTONE_WIRE"), RED_BANNER(425, 1, 26961, "Red Banner", ""), RED_BED(355, 14, 30910, "Red Bed", "Red Bed"), RED_CARPET(171, 14, 5424, "Red Carpet", ""), RED_CONCRETE(251, 14, 8032, "Red Concrete", ""), RED_CONCRETE_POWDER(252, 14, 13286, "Red Concrete Powder", ""), RED_GLAZED_TERRACOTTA(249, 0, 24989, "Red Glazed Terracotta", "RED_GLAZED_TERRACOTTA"), RED_MUSHROOM(40, 0, 19728, "Red Mushroom", "RED_MUSHROOM"), RED_MUSHROOM_BLOCK(100, 0, 20766, "Red Mushroom Block", "HUGE_MUSHROOM_2"), RED_NETHER_BRICKS(215, 0, 18056, "Red Nether Bricks", "RED_NETHER_BRICK"), RED_SAND(12, 1, 16279, "Red Sand", "SAND"), RED_SANDSTONE(179, 0, 9092, "Red Sandstone", ""), RED_SANDSTONE_SLAB(182, 0, 17550, "Red Sandstone Slab", "STONE_SLAB2"), RED_SANDSTONE_STAIRS(180, 0, 25466, "Red Sandstone Stairs", "RED_SANDSTONE_STAIRS"), RED_SHULKER_BOX(233, 0, 32448, "Red Shulker Box", "RED_SHULKER_BOX"), RED_STAINED_GLASS(95, 14, 9717, "Red Stained Glass", ""), RED_STAINED_GLASS_PANE(160, 14, 8630, "Red Stained Glass Pane", ""), RED_TERRACOTTA(159, 14, 5086, "Red Terracotta", ""), RED_TULIP(38, 4, 16781, "Red Tulip", ""), RED_WALL_BANNER(117, 1, 4378, "Red Banner", ""), RED_WOOL(35, 14, 11621, "Red Wool", ""), REPEATER(356, 0, 28823, "Redstone Repeater", "Diode"), REPEATING_COMMAND_BLOCK(-1, -1, 12405, "Repeating Command Block", ""), ROSE_BUSH(175, 4, 6080, "Rose Bush", ""), ROSE_RED(351, 1, 15694, "Rose Red", ""), ROTTEN_FLESH(367, 0, 21591, "Rotten Flesh", ""), SADDLE(329, 0, 30206, "Saddle", ""), SALMON(349, 1, 18516, "Raw Salmon", ""), SALMON_BUCKET(-1, -1, 31427, "Bucket of Salmon", ""), SALMON_SPAWN_EGG(-1, -1, 18739, "Salmon Spawn Egg", ""), SAND(12, 0, 11542, "Sand", ""), SANDSTONE(24, 0, 13141, "Sandstone", ""), SANDSTONE_SLAB(44, 1, 29830, "Sandstone Slab", ""), SANDSTONE_STAIRS(128, 0, 18474, "Sandstone Stairs", ""), SCUTE(-1, -1, 11914, "Scute", ""), SEAGRASS(-1, -1, 23942, "Seagrass", ""), SEA_LANTERN(169, 0, 16984, "Sea Lantern", "SEA_LANTERN"), SEA_PICKLE(-1, -1, 19562, "Sea Pickle", ""), SHEARS(359, 0, 27971, "Shears", ""), SHEEP_SPAWN_EGG(383, 91, 24488, "Spawn Sheep", "Sheep Spawn Egg"), SHIELD(442, 0, 29943, "Shield", ""), SHULKER_BOX(229, 0, 7776, "Shulker Box", ""), SHULKER_SHELL(450, 0, 27848, "Shulker Shell", "SHULKER_SHELL"), SHULKER_SPAWN_EGG(383, 69, 31848, "Spawn Shulker", "Shulker Spawn Egg"), SIGN(323, 0, 16918, "Sign", ""), SILVERFISH_SPAWN_EGG(383, 60, 14537, "Spawn Silverfish", "Silverfish Spawn Egg"), SKELETON_HORSE_SPAWN_EGG(383, 28, 21356, "Spawn Skeleton Horse", "Skeleton Horse Spawn Egg"), SKELETON_SKULL(397, 0, 13270, "Mob Head (Skeleton)", "Skeleton Skull"), SKELETON_SPAWN_EGG(383, 51, 15261, "Spawn Skeleton", "Skeleton Spawn Egg"), SKELETON_WALL_SKULL(144, 0, 31650, "Skeleton Wall Skull", ""), SLIME_BALL(341, 0, 5242, "Slimeball", ""), SLIME_BLOCK(165, 0, 31892, "Slime Block", "SLIME_BLOCK"), SLIME_SPAWN_EGG(383, 55, 6550, "Spawn Slime", "Slime Spawn Egg"), SMOOTH_QUARTZ(-1, -1, 14415, "Smooth Quartz", ""), SMOOTH_RED_SANDSTONE(179, 2, 25180, "Smooth Red Sandstone", ""), SMOOTH_SANDSTONE(24, 2, 30039, "Smooth Sandstone", ""), SMOOTH_STONE(-1, -1, 21910, "Smooth Stone", ""), SNOW(78, 0, 14146, "Snow", "SNOW"), SNOWBALL(332, 0, 19487, "Snowball", ""), SNOW_BLOCK(80, 0, 19913, "Snow Block", "SNOW_BLOCK"), SOUL_SAND(88, 0, 16841, "Soul Sand", "SOUL_SAND"), SPAWNER(52, 90, 25500, "Spawner", "MOB_SPAWNER"), SPECTRAL_ARROW(439, 0, 4568, "Spectral Arrow", ""), SPIDER_EYE(375, 0, 9318, "Spider Eye", ""), SPIDER_SPAWN_EGG(383, 52, 14984, "Spawn Spider", "Spider Spawn Egg"), SPLASH_POTION(438, 0, 30248, "Splash Potion", "SPLASH_POTION"), SPONGE(19, 0, 15860, "Sponge", "SPONGE"), SPRUCE_BOAT(444, 0, 9606, "Spruce Boat", "BOAT_SPRUCE"), SPRUCE_BUTTON(-1, -1, 23281, "Spruce Button", ""), SPRUCE_DOOR(427, 0, 10642, "Spruce Door", "SPRUCE_DOOR_ITEM"), SPRUCE_FENCE(188, 0, 25416, "Spruce Fence", "SPRUCE_FENCE"), SPRUCE_FENCE_GATE(183, 0, 26423, "Spruce Fence Gate", "SPRUCE_FENCE_GATE"), SPRUCE_LEAVES(18, 1, 20039, "Spruce Leaves", ""), SPRUCE_LOG(17, 1, 9726, "Spruce Log", ""), SPRUCE_PLANKS(5, 1, 14593, "Spruce Wood Plank", "Spruce Planks"), SPRUCE_PRESSURE_PLATE(-1, -1, 15932, "Spruce Pressure Plate", ""), SPRUCE_SAPLING(6, 1, 19874, "Spruce Sapling", ""), SPRUCE_SLAB(126, 1, 4348, "Spruce Slab", ""), SPRUCE_STAIRS(134, 0, 11192, "Spruce Wood Stairs", "Spruce Stairs"), SPRUCE_TRAPDOOR(-1, -1, 10289, "Spruce Trapdoor", ""), SPRUCE_WOOD(-1, -1, 22538, "Spruce Wood", ""), SQUID_SPAWN_EGG(383, 94, 10682, "Spawn Squid", "Squid Spawn Egg"), STICK(280, 0, 9773, "Stick", "STICK"), STICKY_PISTON(29, 0, 18127, "Sticky Piston", "PISTON_STICKY_BASE"), STONE(1, 0, 22948, "Stone", ""), STONE_AXE(275, 0, 6338, "Stone Axe", "STONE_AXE"), STONE_BRICKS(98, 0, 6962, "Stone Bricks", ""), STONE_BRICK_SLAB(44, 5, 19676, "Stone Brick Slab", ""), STONE_BRICK_STAIRS(109, 0, 27032, "Stone Brick Stairs", "SMOOTH_STAIRS"), STONE_BUTTON(77, 0, 12279, "Stone Button", "STONE_BUTTON"), STONE_HOE(291, 0, 22855, "Stone Hoe", "STONE_HOE"), STONE_PICKAXE(274, 0, 14611, "Stone Pickaxe", "STONE_PICKAXE"), STONE_PRESSURE_PLATE(70, 0, 22591, "Stone Pressure Plate", "STONE_PLATE"), STONE_SHOVEL(273, 0, 9520, "Stone Shovel", "STONE_SPADE"), STONE_SLAB(44, 0, 19838, "Stone Slab", ""), STONE_SWORD(272, 0, 25084, "Stone Sword", "STONE_SWORD"), STRAY_SPAWN_EGG(383, 6, 30153, "Spawn Stray", "Stray Spawn Egg"), STRING(287, 0, 12806, "String", "STRING"), STRIPPED_ACACIA_LOG(-1, -1, 18167, "Stripped Acacia Log", "Oak Log"), STRIPPED_ACACIA_WOOD(-1, -1, 27193, "Stripped Acacia Wood", "Oak Planks"), STRIPPED_BIRCH_LOG(-1, -1, 8838, "Stripped Birch Log", "Spruce Log"), STRIPPED_BIRCH_WOOD(-1, -1, 22350, "Stripped Birch Wood", "Spruce Planks"), STRIPPED_DARK_OAK_LOG(-1, -1, 6492, "Stripped Dark Oak Log", "Birch Log"), STRIPPED_DARK_OAK_WOOD(-1, -1, 16000, "Stripped Dark Oak Wood", "Birch Planks"), STRIPPED_JUNGLE_LOG(-1, -1, 15476, "Stripped Jungle Log", "Jungle Log"), STRIPPED_JUNGLE_WOOD(-1, -1, 30315, "Stripped Jungle Wood", "Jungle Planks"), STRIPPED_OAK_LOG(-1, -1, 20523, "Stripped Oak Log", "Acacia Log"), STRIPPED_OAK_WOOD(-1, -1, 31455, "Stripped Oak Wood", "Acacia Planks"), STRIPPED_SPRUCE_LOG(-1, -1, 6140, "Stripped Spruce Log", "Dark Oak Log"), STRIPPED_SPRUCE_WOOD(-1, -1, 6467, "Stripped Spruce Wood", "Dark Oak Planks"), STRUCTURE_BLOCK(255, 0, 26831, "Structure Block", "STRUCTURE_BLOCK"), STRUCTURE_VOID(217, 0, 30806, "Structure Void", "STRUCTURE_VOID"), SUGAR(353, 0, 30638, "Sugar", ""), SUGAR_CANE(338, 0, 7726, "Sugar Canes", "Sugar Cane"), SUNFLOWER(175, 0, 7408, "Sunflower", ""), TALL_GRASS(31, 0, 21559, "Tall Grass", ""), TALL_SEAGRASS(-1, -1, 27189, "Tall Seagrass", ""), TERRACOTTA(172, 0, 16544, "Terracotta", "HARD_CLAY"), TIPPED_ARROW(440, 0, 25164, "Tipped Arrow", ""), TNT(46, 0, 7896, "TNT", "TNT"), TNT_MINECART(407, 0, 4277, "Minecart with TNT", "explosiveminecart"), TORCH(50, 0, 6063, "Torch", "TORCH"), TOTEM_OF_UNDYING(449, 0, 10139, "Totem Of Undying", ""), TRAPPED_CHEST(146, 0, 18970, "Trapped Chest", "TRAPPED_CHEST"), TRIDENT(-1, -1, 7534, "Trident", ""), TRIPWIRE(132, 0, 8810, "Tripwire", ""), TRIPWIRE_HOOK(131, 0, 8130, "Tripwire Hook", ""), TROPICAL_FISH(349, 2, 12795, "Tropical Fish", ""), TROPICAL_FISH_BUCKET(-1, -1, 30390, "Bucket of Tropical Fish", ""), TROPICAL_FISH_SPAWN_EGG(-1, -1, 19713, "Tropical Fish Spawn Egg", ""), TUBE_CORAL(-1, -1, 23048, "Tube Coral", ""), TUBE_CORAL_BLOCK(-1, -1, 23723, "Tube Coral Block", ""), TUBE_CORAL_FAN(-1, -1, 19929, "Tube Coral Fan", ""), TUBE_CORAL_WALL_FAN(-1, -1, 25282, "Tube Coral Wall Fan", ""), TURTLE_EGG(-1, -1, 32101, "Turtle Egg", ""), TURTLE_HELMET(-1, -1, 30120, "Turtle Shell", ""), TURTLE_SPAWN_EGG(-1, -1, 17324, "Turtle Spawn Egg", ""), VEX_SPAWN_EGG(383, 35, 27751, "Spawn Vex", "Vex Spawn Egg"), VILLAGER_SPAWN_EGG(383, 120, 30348, "Spawn Villager", "Villager Spawn Egg"), VINDICATOR_SPAWN_EGG(383, 36, 21672, "Spawn Vindicator", "Vindicator Spawn Egg"), VINE(106, 0, 14564, "Vines", "VINE"), VOID_AIR(-1, -1, 13668, "Void Air", ""), WALL_SIGN(68, 0, 10644, "Wall Sign", "WALL_SIGN"), WALL_TORCH(50, 0, 25890, "Wall Torch", ""), WATER(8, 0, 24998, "Flowing Water", "FLOWING_WATER"), WATER_BUCKET(326, 0, 8802, "Water Bucket", ""), WET_SPONGE(19, 1, 9043, "Wet Sponge", ""), WHEAT(59, 0, 27709, "Crops", ""), WHEAT_SEEDS(295, 0, 28742, "Wheat Seeds", "SEEDS"), WHITE_BANNER(425, 15, 17562, "White Banner", ""), WHITE_BED(355, 0, 8185, "White Bed", "Bed"), WHITE_CARPET(171, 0, 15117, "White Carpet", ""), WHITE_CONCRETE(251, 0, 6281, "White Concrete", ""), WHITE_CONCRETE_POWDER(252, 0, 10363, "White Concrete Powder", ""), WHITE_GLAZED_TERRACOTTA(235, 0, 11326, "White Glazed Terracotta", "WHITE_GLAZED_TERRACOTTA"), WHITE_SHULKER_BOX(219, 0, 31750, "White Shulker Box", "WHITE_SHULKER_BOX"), WHITE_STAINED_GLASS(95, 0, 31190, "White Stained Glass", ""), WHITE_STAINED_GLASS_PANE(160, 0, 10557, "White Stained Glass Pane", ""), WHITE_TERRACOTTA(159, 0, 20975, "White Terracotta", ""), WHITE_TULIP(38, 6, 9742, "White Tulip", ""), WHITE_WALL_BANNER(425, 15, 15967, "White Banner", ""), WHITE_WOOL(35, 0, 8624, "White Wool", "Wool"), WITCH_SPAWN_EGG(383, 66, 11837, "Spawn Witch", "Witch Spawn Egg"), WITHER_SKELETON_SKULL(397, 1, 31487, "Mob Head (Wither Skeleton)", "Wither Skeleton Skull"), WITHER_SKELETON_SPAWN_EGG(383, 5, 10073, "Spawn Wither Skeleton", "Wither Skeleton Spawn Egg"), WITHER_SKELETON_WALL_SKULL(144, 1, 9326, "Wither Skeleton Wall Skull", ""), WOLF_SPAWN_EGG(383, 95, 21692, "Spawn Wolf", "Wolf Spawn Egg"), WOODEN_AXE(271, 0, 6292, "Wooden Axe", "Wood Axe"), WOODEN_HOE(290, 0, 16043, "Wooden Hoe", "Wood Hoe"), WOODEN_PICKAXE(270, 0, 12792, "Wooden Pickaxe", "WOOD_PICKAXE"), WOODEN_SHOVEL(269, 0, 28432, "Wooden Shovel", "WOOD_SPADE"), WOODEN_SWORD(268, 0, 7175, "Wooden Sword", "WOOD_SWORD"), WRITABLE_BOOK(386, 0, 13393, "Book and Quill", ""), WRITTEN_BOOK(387, 0, 24164, "Written Book", ""), YELLOW_BANNER(425, 11, 30382, "Yellow Banner", ""), YELLOW_BED(355, 4, 30410, "Yellow Bed", "Yellow Bed"), YELLOW_CARPET(171, 4, 18149, "Yellow Carpet", ""), YELLOW_CONCRETE(251, 4, 15722, "Yellow Concrete", ""), YELLOW_CONCRETE_POWDER(252, 4, 10655, "Yellow Concrete Powder", ""), YELLOW_GLAZED_TERRACOTTA(239, 0, 10914, "Yellow Glazed Terracotta", "YELLOW_GLAZED_TERRACOTTA"), YELLOW_SHULKER_BOX(223, 0, 28700, "Yellow Shulker Box", "YELLOW_SHULKER_BOX"), YELLOW_STAINED_GLASS(95, 4, 12182, "Yellow Stained Glass", ""), YELLOW_STAINED_GLASS_PANE(160, 4, 20298, "Yellow Stained Glass Pane", ""), YELLOW_TERRACOTTA(159, 4, 32129, "Yellow Terracotta", ""), YELLOW_WALL_BANNER(425, 11, 32004, "Yellow Banner", ""), YELLOW_WOOL(35, 4, 29507, "Yellow Wool", ""), ZOMBIE_HEAD(397, 2, 9304, "Mob Head (Zombie)", "Zombie Head"), ZOMBIE_HORSE_SPAWN_EGG(383, 29, 4275, "Spawn Zombie Horse", "Zombie Horse Spawn Egg"), ZOMBIE_PIGMAN_SPAWN_EGG(383, 57, 11531, "Spawn Zombie Pigman", "Zombie Pigman Spawn Egg"), ZOMBIE_SPAWN_EGG(383, 54, 5814, "Spawn Zombie", "Zombie Spawn Egg"), ZOMBIE_VILLAGER_SPAWN_EGG(383, 27, 10311, "Spawn Zombie Villager", "Zombie Villager Spawn Egg"), ZOMBIE_WALL_HEAD(144, 2, 16296, "Zombie Wall Head", ""), // Legacy LEGACY_STATIONARY_WATER(9, 0, -1, "Stationary Water", ""), LEGACY_STATIONARY_LAVA(11, 0, -1, "Stationary Lava", ""), LEGACY_BURNING_FURNACE(62, 0, -1, "Burning Furnace", ""), LEGACY_WOODEN_DOOR_BLOCK(64, 0, -1, "LEGACY_WOODEN_DOOR", ""), LEGACY_IRON_DOOR_BLOCK(71, 0, -1, "LEGACY_IRON_DOOR_BLOCK", ""), LEGACY_GLOWING_REDSTON_ORE(74, 0, -1, "Glowing Redstone Ore", ""), LEGACY_RAW_FISH(349, 0, -1, "Raw Fish", ""), LEGACY_SKULL(144, 0, -1, "Skull", ""); private int legacyId; private int legacyData; private int id; private String name; private String legacyName; private String bukkitName; private String mojangName; Material mat; CMIMaterial(int legacyId, int legacyData, int id, String name) { this(legacyId, legacyData, id, name, null); } CMIMaterial(int legacyId, int legacyData, int id, String name, String legacyName) { this.legacyId = legacyId; this.legacyData = legacyData; this.id = id; this.name = name; this.legacyName = legacyName; } public String getName() { return name; } public int getLegacyId() { return this.legacyId; } public int getId() { if (Jobs.getVersionCheckManager().getVersion().isEqualOrHigher(Version.v1_13_R1)) { return this.id; } return getLegacyId(); } public Material getMaterial() { return mat == null ? null : mat; } public void updateMaterial() { if (mat == null) { for (Material one : Material.class.getEnumConstants()) { if (one.getId() != this.getId()) continue; mat = one; break; } } if (mat == null) { for (Material one : Material.class.getEnumConstants()) { if (!one.name().replace("LEGACY_", "").replace("_", "").equalsIgnoreCase(this.name().replace("_", ""))) continue; mat = one; break; } } if (mat == null) { for (Material one : Material.class.getEnumConstants()) { if (!one.name().replace("LEGACY_", "").replace("_", "").equalsIgnoreCase(this.getName().replace(" ", ""))) continue; mat = one; break; } } if (mat == null && !this.getLegacyName().isEmpty()) { for (Material one : Material.class.getEnumConstants()) { if (!one.name().replace("LEGACY_", "").replace("_", "").equalsIgnoreCase(this.getLegacyName().replace(" ", "").replace("_", ""))) continue; mat = one; break; } } } public ItemStack newItemStack() { if (mat == null) { for (Material one : Material.class.getEnumConstants()) { if (one.getId() != this.getId()) continue; mat = one; break; } } if (Jobs.getVersionCheckManager().getVersion().isEqualOrHigher(Version.v1_13_R1)) { return new ItemStack(mat == null ? Material.STONE : mat); } return new ItemStack(mat == null ? Material.STONE : mat, 1, (short) this.getLegacyData()); } @Deprecated public short getData() { if (Jobs.getVersionCheckManager().getVersion().isEqualOrHigher(Version.v1_13_R1)) { return 0; } return (short) legacyData; } public int getLegacyData() { return legacyData; } public static CMIMaterial getRandom(CMIMaterial mat) { List<CMIMaterial> ls = new ArrayList<CMIMaterial>(); for (CMIMaterial one : CMIMaterial.values()) { if (one.getLegacyId() == -1) continue; if (one.getLegacyId() != mat.getLegacyId()) continue; ls.add(one); } if (ls.isEmpty() || ls.size() == 1) { String part = mat.name; if (part.contains("_")) part = part.split("_")[part.split("[_]").length - 1]; for (CMIMaterial one : CMIMaterial.values()) { if (!one.name().endsWith(part)) continue; ls.add(one); } } Collections.shuffle(ls); return ls.isEmpty() ? CMIMaterial.NONE : ls.get(0); } public static CMIMaterial get(String id) { Integer ids = null; Integer data = null; id = id.replace("_", "").replace(" ", "").toLowerCase(); try { ids = Integer.parseInt(id); } catch (Exception e) { if (id.contains(":")) { try { ids = Integer.parseInt(id.split(":")[0]); data = Integer.parseInt(id.split(":")[1]); return get(ids, data); } catch (Exception ex) { } try { data = Integer.parseInt(id.split(":")[1]); id = id.split(":")[0]; } catch (Exception ex) { } } } CMIMaterial mat = null; CMIItemStack ci = byBukkitName.get(id); if (ci != null) mat = ci.getCMIType(); if (mat != null) { if (data != null) { for (CMIMaterial one : CMIMaterial.values()) { if (one.getLegacyId() == mat.getLegacyId()) { if (one.getLegacyData() == data) { mat = one; break; } } } } return mat; } ci = byMojangName.get(id); if (ci != null) mat = ci.getCMIType(); if (mat != null) { if (data != null) { for (CMIMaterial one : CMIMaterial.values()) { if (one.getLegacyId() == mat.getLegacyId()) { if (one.getLegacyData() == data) { mat = one; break; } } } } return mat; } if (ids != null) { if (data == null) mat = get(ids); else mat = get(ids, data); } if (mat != null) return mat; for (CMIMaterial one : CMIMaterial.values()) { if (ids != null && data == null && one.getId() == ids) return one; if (ids != null && data != null && one.getId() == ids && one.getLegacyData() == data) return one; } id = id.replace("_", "").toLowerCase(); for (CMIMaterial one : CMIMaterial.values()) { if (one.name().replace("_", "").equalsIgnoreCase(id)) return one; if (one.getName().replace("_", "").replace(" ", "").equalsIgnoreCase(id)) return one; } return CMIMaterial.NONE; } public static CMIMaterial get(Material mat) { for (CMIMaterial one : CMIMaterial.values()) { if (one.getMaterial() == null) continue; if (one.getMaterial().getId() == mat.getId()) { return one; } } return CMIMaterial.NONE; } public static CMIMaterial get(int id) { for (CMIMaterial one : CMIMaterial.values()) { if (one.getMaterial() == null) continue; if (one.getMaterial().getId() == id) { return one; } } for (CMIMaterial one : CMIMaterial.values()) { if (one.getLegacyId() == id) { return one; } } return CMIMaterial.NONE; } public static CMIMaterial get(ItemStack item) { // if (CMIMaterial.isMonsterEgg(item.getType())) { // int tid = CMI.getInstance().getNMS().getEggId(item); // return get(item.getType().getId(), tid); CMIMaterial m = get(item.getType().getId(), item.getData().getData()); if (m == null) { CMIItemStack cm = byBukkitName.get(item.getType().toString().toLowerCase().replace("_", "")); if (cm != null) m = cm.getCMIType(); } return m == null ? CMIMaterial.NONE : m; } public static CMIMaterial get(Block block) { CMIMaterial m = get(block.getType().getId(), block.getData()); if (m == null) { CMIItemStack cm = byBukkitName.get(block.getType().toString().replace("_", "").toLowerCase()); if (cm != null) m = cm.getCMIType(); } if (m == null) { CMIItemStack cm = byBukkitName.get(block.getType().name().toString().replace("_", "").toLowerCase()); if (cm != null) m = cm.getCMIType(); } return m == null ? CMIMaterial.NONE : m; } public static CMIMaterial get(int id, int data) { CMIMaterial mat = null; CMIItemStack cm = byBukkitName.get(id + ":" + data); if (cm != null) mat = cm.getCMIType(); if (mat == null) { cm = byId.get(id); if (cm != null) mat = cm.getCMIType(); } if (mat == null) { for (CMIMaterial one : CMIMaterial.values()) { if (one.getId() == id) { mat = one; break; } } } if (mat == null) { for (CMIMaterial one : CMIMaterial.values()) { if (one.getLegacyId() == id) { mat = one; break; } } } if (mat != null) { for (CMIMaterial one : CMIMaterial.values()) { if (one.getLegacyId() == mat.getLegacyId()) { if (one.getLegacyData() == data) { mat = one; break; } } } } return mat == null ? CMIMaterial.NONE : mat; } public static CMIMaterial getLegacy(int id) { CMIItemStack cm = byId.get(id); if (cm != null) return cm.getCMIType(); for (CMIMaterial one : CMIMaterial.values()) { if (one.getLegacyId() == id) { return one; } } return CMIMaterial.NONE; } public short getMaxDurability() { return this.getMaterial() == null ? 0 : this.getMaterial().getMaxDurability(); } public boolean isBlock() { return this.getMaterial() == null ? false : this.getMaterial().isBlock(); } public boolean isSolid() { return this.getMaterial() == null ? false : this.getMaterial().isSolid(); } public static boolean isMonsterEgg(Material mat) { CMIMaterial m = CMIMaterial.get(mat); if (m == null) return false; return m.isMonsterEgg(); } public boolean isMonsterEgg() { switch (this) { case ELDER_GUARDIAN_SPAWN_EGG: case WITHER_SKELETON_SPAWN_EGG: case STRAY_SPAWN_EGG: case HUSK_SPAWN_EGG: case ZOMBIE_VILLAGER_SPAWN_EGG: case SKELETON_HORSE_SPAWN_EGG: case ZOMBIE_HORSE_SPAWN_EGG: case DONKEY_SPAWN_EGG: case MULE_SPAWN_EGG: case EVOKER_SPAWN_EGG: case VEX_SPAWN_EGG: case VINDICATOR_SPAWN_EGG: case CREEPER_SPAWN_EGG: case SKELETON_SPAWN_EGG: case SPIDER_SPAWN_EGG: case ZOMBIE_SPAWN_EGG: case SLIME_SPAWN_EGG: case GHAST_SPAWN_EGG: case ZOMBIE_PIGMAN_SPAWN_EGG: case ENDERMAN_SPAWN_EGG: case CAVE_SPIDER_SPAWN_EGG: case SILVERFISH_SPAWN_EGG: case BLAZE_SPAWN_EGG: case MAGMA_CUBE_SPAWN_EGG: case BAT_SPAWN_EGG: case WITCH_SPAWN_EGG: case ENDERMITE_SPAWN_EGG: case GUARDIAN_SPAWN_EGG: case SHULKER_SPAWN_EGG: case PIG_SPAWN_EGG: case SHEEP_SPAWN_EGG: case COW_SPAWN_EGG: case CHICKEN_SPAWN_EGG: case SQUID_SPAWN_EGG: case WOLF_SPAWN_EGG: case MOOSHROOM_SPAWN_EGG: case OCELOT_SPAWN_EGG: case HORSE_SPAWN_EGG: case RABBIT_SPAWN_EGG: case POLAR_BEAR_SPAWN_EGG: case LLAMA_SPAWN_EGG: case PARROT_SPAWN_EGG: case VILLAGER_SPAWN_EGG: case COD_SPAWN_EGG: case DOLPHIN_SPAWN_EGG: case DRAGON_EGG: case DROWNED_SPAWN_EGG: case PHANTOM_SPAWN_EGG: case PUFFERFISH_SPAWN_EGG: case SALMON_SPAWN_EGG: case TROPICAL_FISH_SPAWN_EGG: case TURTLE_EGG: case TURTLE_SPAWN_EGG: return true; default: break; } return false; } public static boolean isBed(Material mat) { CMIMaterial m = CMIMaterial.get(mat); if (m == null) return false; return m.isBed(); } public boolean isBed() { switch (this) { case WHITE_BED: case ORANGE_BED: case MAGENTA_BED: case LIGHT_BLUE_BED: case YELLOW_BED: case LIME_BED: case PINK_BED: case GRAY_BED: case LIGHT_GRAY_BED: case CYAN_BED: case PURPLE_BED: case BLUE_BED: case BROWN_BED: case GREEN_BED: case RED_BED: case BLACK_BED: return true; default: break; } return false; } public static boolean isBoat(Material mat) { CMIMaterial m = CMIMaterial.get(mat); if (m == null) return false; return m.isBoat(); } public boolean isBoat() { switch (this) { case OAK_BOAT: case ACACIA_BOAT: case BIRCH_BOAT: case DARK_OAK_BOAT: case JUNGLE_BOAT: case SPRUCE_BOAT: return true; default: break; } return false; } public static boolean isSapling(Material mat) { CMIMaterial m = CMIMaterial.get(mat); if (m == null) return false; return m.isSapling(); } public boolean isSapling() { switch (this) { case OAK_SAPLING: case SPRUCE_SAPLING: case BIRCH_SAPLING: case JUNGLE_SAPLING: case ACACIA_SAPLING: case DARK_OAK_SAPLING: case POTTED_ACACIA_SAPLING: case POTTED_BIRCH_SAPLING: case POTTED_DARK_OAK_SAPLING: case POTTED_JUNGLE_SAPLING: case POTTED_OAK_SAPLING: case POTTED_SPRUCE_SAPLING: return true; default: break; } return false; } public static boolean isButton(Material mat) { CMIMaterial m = CMIMaterial.get(mat); if (m == null) return false; return m.isButton(); } public boolean isButton() { switch (this) { case ACACIA_BUTTON: case BIRCH_BUTTON: case DARK_OAK_BUTTON: case JUNGLE_BUTTON: case OAK_BUTTON: case SPRUCE_BUTTON: case STONE_BUTTON: return true; default: break; } return false; } public static boolean isPlate(Material mat) { CMIMaterial m = CMIMaterial.get(mat); if (m == null) return false; return m.isPlate(); } public boolean isPlate() { switch (this) { case ACACIA_PRESSURE_PLATE: case BIRCH_PRESSURE_PLATE: case DARK_OAK_PRESSURE_PLATE: case HEAVY_WEIGHTED_PRESSURE_PLATE: case JUNGLE_PRESSURE_PLATE: case LIGHT_WEIGHTED_PRESSURE_PLATE: case OAK_PRESSURE_PLATE: case SPRUCE_PRESSURE_PLATE: case STONE_PRESSURE_PLATE: return true; default: break; } return false; } public static boolean isWool(Material mat) { CMIMaterial m = CMIMaterial.get(mat); if (m == null) return false; return m.isWool(); } public boolean isWool() { switch (this) { case BLACK_WOOL: case BLUE_WOOL: case BROWN_WOOL: case CYAN_WOOL: case GRAY_WOOL: case GREEN_WOOL: case LIGHT_BLUE_WOOL: case LIGHT_GRAY_WOOL: case LIME_WOOL: case MAGENTA_WOOL: case ORANGE_WOOL: case PINK_WOOL: case PURPLE_WOOL: case RED_WOOL: case WHITE_WOOL: case YELLOW_WOOL: return true; default: break; } return false; } public static boolean isShulkerBox(Material mat) { CMIMaterial m = CMIMaterial.get(mat); if (m == null) return false; return m.isShulkerBox(); } public boolean isShulkerBox() { switch (this) { case BLACK_SHULKER_BOX: case BLUE_SHULKER_BOX: case BROWN_SHULKER_BOX: case CYAN_SHULKER_BOX: case GRAY_SHULKER_BOX: case GREEN_SHULKER_BOX: case LIGHT_BLUE_SHULKER_BOX: case LIGHT_GRAY_SHULKER_BOX: case LIME_SHULKER_BOX: case MAGENTA_SHULKER_BOX: case ORANGE_SHULKER_BOX: case PINK_SHULKER_BOX: case PURPLE_SHULKER_BOX: case RED_SHULKER_BOX: case WHITE_SHULKER_BOX: case YELLOW_SHULKER_BOX: return true; default: break; } return false; } public static boolean isAir(Material mat) { CMIMaterial m = CMIMaterial.get(mat); if (m == null) return false; return m.isAir(); } public boolean isAir() { switch (this) { case AIR: case CAVE_AIR: case VOID_AIR: return true; default: break; } return false; } public static boolean isDoor(Material mat) { CMIMaterial m = CMIMaterial.get(mat); if (m == null) return false; return m.isDoor(); } public boolean isDoor() { switch (this) { case OAK_DOOR: case IRON_DOOR: case ACACIA_DOOR: case BIRCH_DOOR: case DARK_OAK_DOOR: case JUNGLE_DOOR: case SPRUCE_DOOR: return true; default: break; } return false; } public static boolean isGate(Material mat) { CMIMaterial m = CMIMaterial.get(mat); if (m == null) return false; return m.isGate(); } public boolean isGate() { switch (this) { case ACACIA_FENCE_GATE: case BIRCH_FENCE_GATE: case DARK_OAK_FENCE_GATE: case END_GATEWAY: case JUNGLE_FENCE_GATE: case OAK_FENCE_GATE: case SPRUCE_FENCE_GATE: return true; default: break; } return false; } public static boolean isTrapDoor(Material mat) { CMIMaterial m = CMIMaterial.get(mat); if (m == null) return false; return m.isTrapDoor(); } public boolean isTrapDoor() { switch (this) { case ACACIA_TRAPDOOR: case BIRCH_TRAPDOOR: case DARK_OAK_TRAPDOOR: case IRON_TRAPDOOR: case JUNGLE_TRAPDOOR: case OAK_TRAPDOOR: case SPRUCE_TRAPDOOR: return true; default: break; } return false; } public static boolean isSkull(Material mat) { CMIMaterial m = CMIMaterial.get(mat); if (m == null) return false; return m.isSkull(); } public boolean isSkull() { switch (this) { case SKELETON_SKULL: case WITHER_SKELETON_SKULL: case SKELETON_WALL_SKULL: case WITHER_SKELETON_WALL_SKULL: return true; default: break; } return false; } public static boolean isDye(Material mat) { Debug.D("ss1"); CMIMaterial m = CMIMaterial.get(mat); Debug.D("ss2"); if (m == null) return false; Debug.D("ss3"); return m.isDye(); } public boolean isDye() { Debug.D("ss4"); switch (this) { case INK_SAC: case ROSE_RED: case CACTUS_GREEN: case COCOA_BEANS: case LAPIS_LAZULI: case PURPLE_DYE: case CYAN_DYE: case LIGHT_GRAY_DYE: case GRAY_DYE: case PINK_DYE: case LIME_DYE: case DANDELION_YELLOW: case LIGHT_BLUE_DYE: case MAGENTA_DYE: case ORANGE_DYE: case BONE_MEAL: return true; default: break; } return false; } public static boolean isSlab(Material mat) { CMIMaterial m = CMIMaterial.get(mat); if (m == null) return false; return m.isSlab(); } public boolean isSlab() { switch (this) { case ACACIA_SLAB: case DARK_OAK_SLAB: case BIRCH_SLAB: case BRICK_SLAB: case COBBLESTONE_SLAB: case DARK_PRISMARINE_SLAB: case JUNGLE_SLAB: case NETHER_BRICK_SLAB: case OAK_SLAB: case PETRIFIED_OAK_SLAB: case PRISMARINE_BRICK_SLAB: case PRISMARINE_SLAB: case PURPUR_SLAB: case QUARTZ_SLAB: case RED_SANDSTONE_SLAB: case SANDSTONE_SLAB: case SPRUCE_SLAB: case STONE_BRICK_SLAB: case STONE_SLAB: return true; default: break; } return false; } public static SlabType getSlabType(Block block) { return checkSlab(block); } public boolean equals(Material mat) { if (getMaterial() == null) return false; return this.getMaterial().equals(mat); } public String getLegacyName() { return legacyName == null ? "" : legacyName; } public void setLegacyName(String legacyName) { this.legacyName = legacyName; } public String getBukkitName() { if (bukkitName == null) bukkitName = getMaterial().name(); return bukkitName; } public void setBukkitName(String bukkitName) { this.bukkitName = bukkitName; } public String getMojangName() { if (mojangName == null) mojangName = ItemReflection.getItemMinecraftName(this.newItemStack()); return mojangName; } public void setMojangName(String mojangName) { this.mojangName = mojangName; } } private static SlabType checkSlab(Block block) { if (!CMIMaterial.isSlab(block.getType())) return SlabType.NOTSLAB; if (version.isEqualOrHigher(Version.v1_13_R1)) { if (block.getBlockData() instanceof org.bukkit.block.data.type.Slab) { org.bukkit.block.data.type.Slab slab = (org.bukkit.block.data.type.Slab) block.getBlockData(); org.bukkit.block.data.type.Slab.Type t = slab.getType(); if (t.equals(org.bukkit.block.data.type.Slab.Type.TOP)) return SlabType.TOP; if (t.equals(org.bukkit.block.data.type.Slab.Type.BOTTOM)) return SlabType.BOTTOM; if (t.equals(org.bukkit.block.data.type.Slab.Type.DOUBLE)) return SlabType.DOUBLE; } return SlabType.NOTSLAB; } if (block.getType().name().contains("STEP")) { switch (CMIMaterial.get(block).getLegacyId()) { case 44: switch (block.getData()) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: return SlabType.BOTTOM; default: return SlabType.DOUBLE; } case 126: switch (block.getData()) { case 0: case 1: case 2: case 3: case 4: case 5: return SlabType.BOTTOM; default: return SlabType.DOUBLE; } case 182: switch (block.getData()) { case 0: return SlabType.BOTTOM; default: return SlabType.DOUBLE; } case 205: switch (block.getData()) { case 0: return SlabType.BOTTOM; default: return SlabType.DOUBLE; } } } return SlabType.NOTSLAB; } public enum SlabType { TOP, BOTTOM, DOUBLE, NOTSLAB; } }
package com.github.davidmoten.rx.jdbc; import static com.github.davidmoten.rx.RxUtil.constant; import static com.github.davidmoten.rx.RxUtil.greaterThanZero; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Types; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observable.Operator; import rx.Scheduler; import rx.functions.Func0; import rx.functions.Func1; import rx.functions.Func2; import rx.observables.StringObservable; import rx.schedulers.Schedulers; import com.github.davidmoten.rx.RxUtil; import com.github.davidmoten.rx.RxUtil.CountingAction; /** * Main entry point for manipulations of a database using rx-java-jdbc style * queries. */ final public class Database { /** * Logger. */ private static final Logger log = LoggerFactory.getLogger(Database.class); /** * Provides access for queries to a limited subset of {@link Database} * methods. */ private final QueryContext context; /** * ThreadLocal storage of the current {@link Scheduler} factory to use with * queries. */ private final ThreadLocal<Func0<Scheduler>> currentSchedulerFactory = new ThreadLocal<Func0<Scheduler>>(); /** * ThreadLocal storage of the current {@link ConnectionProvider} to use with * queries. */ private final ThreadLocal<ConnectionProvider> currentConnectionProvider = new ThreadLocal<ConnectionProvider>(); private final ThreadLocal<Boolean> isTransactionOpen = new ThreadLocal<Boolean>(); /** * Records the result of the last finished transaction (committed = * <code>true</code> or rolled back = <code>false</code>). */ private final ThreadLocal<Observable<Boolean>> lastTransactionResult = new ThreadLocal<Observable<Boolean>>(); /** * Connection provider. */ private final ConnectionProvider cp; /** * Schedules non transactional queries. */ private final Func0<Scheduler> nonTransactionalSchedulerFactory; /** * Constructor. * * @param cp * provides connections * @param nonTransactionalSchedulerFactory * schedules non transactional queries */ public Database(final ConnectionProvider cp, Func0<Scheduler> nonTransactionalSchedulerFactory) { Conditions.checkNotNull(cp); this.cp = cp; currentConnectionProvider.set(cp); if (nonTransactionalSchedulerFactory != null) this.nonTransactionalSchedulerFactory = nonTransactionalSchedulerFactory; else this.nonTransactionalSchedulerFactory = CURRENT_THREAD_SCHEDULER_FACTORY; this.context = new QueryContext(this); } /** * Returns the {@link ConnectionProvider}. * * @return */ public ConnectionProvider getConnectionProvider() { return cp; } /** * Schedules on {@link Schedulers#io()}. */ private final Func0<Scheduler> IO_SCHEDULER_FACTORY = new Func0<Scheduler>() { @Override public Scheduler call() { return Schedulers.io(); } }; /** * Schedules using {@link Schedulers}.trampoline(). */ private static final Func0<Scheduler> CURRENT_THREAD_SCHEDULER_FACTORY = new Func0<Scheduler>() { @Override public Scheduler call() { return Schedulers.trampoline(); } }; /** * Constructor. Thread pool size defaults to * <code>{@link Runtime#getRuntime()}.availableProcessors()+1</code>. This * may be too conservative if the database is on another server. If that is * the case then you may want to use a thread pool size equal to the * available processors + 1 on the database server. * * @param cp * provides connections */ public Database(ConnectionProvider cp) { this(cp, null); } /** * Constructor. Uses a {@link ConnectionProviderFromUrl} based on the given * url. * * @param url * jdbc url * @param username * username for connection * @param password * password for connection */ public Database(String url, String username, String password) { this(new ConnectionProviderFromUrl(url, username, password)); } /** * Constructor. Uses the single connection provided and current thread * scheduler (trampoline) to run all queries. The connection will not be * closed in reality though the log may indicate it as having received a * close call. * * @param con * the connection */ public Database(Connection con) { this(new ConnectionProviderNonClosing(con), CURRENT_THREAD_SCHEDULER_FACTORY); } /** * Returns a {@link Database} based on a jdbc connection string. * * @param url * jdbc connection url * @return */ public static Database from(String url) { return new Database(url, null, null); } /** * Returns a {@link Database} based on a jdbc connection string. * * @param url * jdbc url * @param username * username for connection * @param password * password for connection * @return the database object */ public static Database from(String url, String username, String password) { return new Database(url, username, password); } /** * Returns a {@link Database} based on connections obtained from a * javax.activation.DataSource based on looking up the current * javax.naming.Context. * * @param jndiResource * @return */ public static Database fromContext(String jndiResource) { return new Database(new ConnectionProviderFromContext(jndiResource)); } /** * Returns a {@link Database} that obtains {@link Connection}s on demand * from the given {@link ConnectionProvider}. When {@link Database#close()} * is called, {@link ConnectionProvider#close()} is called. * * @param cp * @return */ public static Database from(ConnectionProvider cp) { return new Database(cp); } /** * Factory method. Uses the single connection provided and current thread * scheduler (trampoline) to run all queries. The connection will not be * closed in reality though the log may indicate it as having received a * close call. * * @param con * the connection */ public static Database from(Connection con) { return new Database(con); } /** * Returns a new {@link Builder}. * * @return */ public static Builder builder() { return new Builder(); } /** * Builds a {@link Database}. */ public final static class Builder { private ConnectionProvider cp; private Func0<Scheduler> nonTransactionalSchedulerFactory = null; private Pool pool = null; private String url; private String username; private String password; private static class Pool { int minSize; int maxSize; Pool(int minSize, int maxSize) { super(); this.minSize = minSize; this.maxSize = maxSize; } } /** * Constructor. */ private Builder() { } /** * Sets the connection provider. * * @param cp * @return */ public Builder connectionProvider(ConnectionProvider cp) { this.cp = cp; return this; } /** * Sets the jdbc url. * * @param url * @return */ public Builder url(String url) { this.url = url; return this; } public Builder username(String username) { this.username = username; return this; } public Builder password(String password) { this.password = password; return this; } /** * Sets the {@link ConnectionProvider} to use a connection pool with the * given jdbc url and pool size. * * @param url * @param minPoolSize * @param maxPoolSize * @return */ public Builder pool(int minPoolSize, int maxPoolSize) { pool = new Pool(minPoolSize, maxPoolSize); return this; } /** * Sets the {@link ConnectionProvider} to use a connection pool with the * given jdbc url and min pool size of 0, max pool size of 10. * * @param url * @return */ public Builder pooled(String url) { this.cp = new ConnectionProviderPooled(url, 0, 10); return this; } /** * Sets the non transactional scheduler. * * @param factory * @return */ public Builder nonTransactionalScheduler(Func0<Scheduler> factory) { nonTransactionalSchedulerFactory = factory; return this; } /** * Requests that the non transactional queries are run using * {@link Schedulers#trampoline()}. * * @return */ public Builder nonTransactionalSchedulerOnCurrentThread() { nonTransactionalSchedulerFactory = CURRENT_THREAD_SCHEDULER_FACTORY; return this; } /** * Returns a {@link Database}. * * @return */ public Database build() { if (url != null && pool != null) cp = new ConnectionProviderPooled(url, username, password, pool.minSize, pool.maxSize); else if (url != null) cp = new ConnectionProviderFromUrl(url, username, password); return new Database(cp, nonTransactionalSchedulerFactory); } } /** * Returns the thread local current query context (will not return null). * Will return overriden context (for example using Database returned from * {@link Database#beginTransaction()} if set. * * @return */ public QueryContext queryContext() { return context; } /** * Returns a {@link QuerySelect.Builder} builder based on the given select * statement sql. * * @param sql * a select statement. * @return select query builder */ public QuerySelect.Builder select(String sql) { return new QuerySelect.Builder(sql, this); } /** * Returns a {@link QueryUpdate.Builder} builder based on the given * update/insert/delete/DDL statement sql. * * @param sql * an update/insert/delete/DDL statement. * @return update/insert query builder */ public QueryUpdate.Builder update(String sql) { return new QueryUpdate.Builder(sql, this); } /** * Starts a transaction. Until commit() or rollback() is called on the * source this will set the query context for all created queries to be a * single threaded executor with one (new) connection. * * @param dependency * @return */ public Observable<Boolean> beginTransaction(Observable<?> dependency) { return update("begin").dependsOn(dependency).count().map(constant(true)); } /** * Starts a transaction. Until commit() or rollback() is called on the * source this will set the query context for all created queries to be a * single threaded executor with one (new) connection. * * @return */ public Observable<Boolean> beginTransaction() { return beginTransaction(Observable.empty()); } /** * Returns true if and only if integer is non-zero. */ private static final Func1<Integer, Boolean> IS_NON_ZERO = new Func1<Integer, Boolean>() { @Override public Boolean call(Integer i) { return i != 0; } }; /** * Commits a transaction and resets the current query context so that * further queries will use the asynchronous version by default. All * Observable dependencies must be complete before commit is called. * * @param depends * depdencies that must complete before commit occurs. * @return */ public Observable<Boolean> commit(Observable<?>... depends) { return commitOrRollback(true, depends); } /** * Waits for the source to complete before returning the result of * db.commit(); * * @return commit operator */ public <T> Operator<Boolean, T> commitOperator() { return commitOrRollbackOperator(true); } /** * Waits for the source to complete before returning the result of * db.rollback(); * * @return rollback operator */ public <T> Operator<Boolean, T> rollbackOperator() { return commitOrRollbackOperator(false); } private <T> Operator<Boolean, T> commitOrRollbackOperator(final boolean commit) { final QueryUpdate.Builder updateBuilder = createCommitOrRollbackQuery(commit); return RxUtil.toOperator(new Func1<Observable<T>, Observable<Boolean>>() { @Override public Observable<Boolean> call(Observable<T> source) { return updateBuilder.dependsOn(source).count().map(IS_NON_ZERO); } }); } /** * Commits or rolls back a transaction depending on the <code>commit</code> * parameter and resets the current query context so that further queries * will use the asynchronous version by default. All Observable dependencies * must be complete before commit/rollback is called. * * @param commit * @param depends * @return */ private Observable<Boolean> commitOrRollback(boolean commit, Observable<?>... depends) { QueryUpdate.Builder u = createCommitOrRollbackQuery(commit); for (Observable<?> dep : depends) u = u.dependsOn(dep); Observable<Boolean> result = u.count().map(IS_NON_ZERO); lastTransactionResult.set(result); return result; } private QueryUpdate.Builder createCommitOrRollbackQuery(boolean commit) { String action; if (commit) action = "commit"; else action = "rollback"; QueryUpdate.Builder u = update(action); return u; } /** * Rolls back a transaction and resets the current query context so that * further queries will use the asynchronous version by default. All * Observable dependencies must be complete before rollback is called. * * @param depends * depdencies that must complete before commit occurs. * @return * **/ public Observable<Boolean> rollback(Observable<?>... depends) { return commitOrRollback(false, depends); } /** * Returns observable that emits true when last transaction committed or * false when last transaction is rolled back. * * @return */ public Observable<Boolean> lastTransactionResult() { Observable<Boolean> o = lastTransactionResult.get(); if (o == null) return Observable.empty(); else return o; } /** * Close the database in particular closes the {@link ConnectionProvider} * for the database. For a {@link ConnectionProviderPooled} this will be a * required call for cleanup. * * @return */ public Database close() { log.debug("closing connection provider"); cp.close(); log.debug("closed connection provider"); return this; } /** * Returns the current thread local {@link Scheduler}. * * @return */ Scheduler currentScheduler() { if (currentSchedulerFactory.get() == null) return nonTransactionalSchedulerFactory.call(); else return currentSchedulerFactory.get().call(); } /** * Returns the current thread local {@link ConnectionProvider}. * * @return */ ConnectionProvider connectionProvider() { if (currentConnectionProvider.get() == null) return cp; else return currentConnectionProvider.get(); } /** * Sets the current thread local {@link ConnectionProvider} to a singleton * manual commit instance. */ void beginTransactionObserve() { log.debug("beginTransactionObserve"); currentConnectionProvider.set(new ConnectionProviderSingletonManualCommit(cp)); if (isTransactionOpen.get() != null && isTransactionOpen.get()) throw new RuntimeException("cannot begin transaction as transaction open already"); isTransactionOpen.set(true); } /** * Sets the current thread local {@link Scheduler} to be * {@link Schedulers#trampoline()}. */ void beginTransactionSubscribe() { log.debug("beginTransactionSubscribe"); currentSchedulerFactory.set(CURRENT_THREAD_SCHEDULER_FACTORY); } /** * Resets the current thread local {@link Scheduler} to default. */ void endTransactionSubscribe() { log.debug("endTransactionSubscribe"); currentSchedulerFactory.set(null); } /** * Resets the current thread local {@link ConnectionProvider} to default. */ void endTransactionObserve() { log.debug("endTransactionObserve"); currentConnectionProvider.set(cp); isTransactionOpen.set(false); } /** * Returns an {@link Operator} that performs commit or rollback of a * transaction. * * @param isCommit * @return */ private <T> Operator<Boolean, T> commitOrRollbackOnCompleteOperator(final boolean isCommit) { return RxUtil.toOperator(new Func1<Observable<T>, Observable<Boolean>>() { @Override public Observable<Boolean> call(Observable<T> source) { return commitOrRollbackOnCompleteOperatorIfAtLeastOneValue(isCommit, Database.this, source); } }); } /** * Commits current transaction on the completion of source if and only if * the source sequence is non-empty. * * @return operator that commits on completion of source. */ public <T> Operator<Boolean, T> commitOnCompleteOperator() { return commitOrRollbackOnCompleteOperator(true); } /** * Rolls back current transaction on the completion of source if and only if * the source sequence is non-empty. * * @return operator that rolls back on completion of source. */ public <T> Operator<Boolean, T> rollbackOnCompleteOperator() { return commitOrRollbackOnCompleteOperator(false); } /** * Starts a database transaction for each onNext call. Following database * calls will be subscribed on current thread (Schedulers.trampoline()) and * share the same {@link Connection} until transaction is rolled back or * committed. * * @return begin transaction operator */ public <T> Operator<T, T> beginTransactionOnNextOperator() { return RxUtil.toOperator(new Func1<Observable<T>, Observable<T>>() { @Override public Observable<T> call(Observable<T> source) { return beginTransactionOnNext(Database.this, source); } }); } /** * Commits the currently open transaction. Emits true. * * @return */ public <T> Operator<Boolean, T> commitOnNextOperator() { return commitOrRollbackOnNextOperator(true); } public <T> Operator<Boolean, Observable<T>> commitOnNextListOperator() { return commitOrRollbackOnNextListOperator(true); } public <T> Operator<Boolean, Observable<T>> rollbackOnNextListOperator() { return commitOrRollbackOnNextListOperator(false); } private <T> Operator<Boolean, Observable<T>> commitOrRollbackOnNextListOperator( final boolean isCommit) { return RxUtil.toOperator(new Func1<Observable<Observable<T>>, Observable<Boolean>>() { @Override public Observable<Boolean> call(Observable<Observable<T>> source) { return source.concatMap(new Func1<Observable<T>, Observable<Boolean>>() { @Override public Observable<Boolean> call(Observable<T> source) { if (isCommit) return commit(source); else return rollback(source); } }); } }); } /** * Rolls back the current transaction. Emits false. * * @return */ public Operator<Boolean, ?> rollbackOnNextOperator() { return commitOrRollbackOnNextOperator(false); } private <T> Operator<Boolean, T> commitOrRollbackOnNextOperator(final boolean isCommit) { return RxUtil.toOperator(new Func1<Observable<T>, Observable<Boolean>>() { @Override public Observable<Boolean> call(Observable<T> source) { return commitOrRollbackOnNext(isCommit, Database.this, source); } }); } private static <T> Observable<Boolean> commitOrRollbackOnCompleteOperatorIfAtLeastOneValue( final boolean isCommit, final Database db, Observable<T> source) { CountingAction<T> counter = RxUtil.counter(); Observable<Boolean> commit = counter // get count .count() // greater than zero or empty .filter(greaterThanZero()) // commit if at least one value .lift(db.commitOrRollbackOperator(isCommit)); return Observable // concatenate .concat(source // count emissions .doOnNext(counter) // ignore emissions .ignoreElements() // cast the empty sequence to type Boolean .cast(Boolean.class), // concat with commit commit); } /** * Emits true for commit and false for rollback. * * @param isCommit * @param db * @param source * @return */ private static <T> Observable<Boolean> commitOrRollbackOnNext(final boolean isCommit, final Database db, Observable<T> source) { return source.concatMap(new Func1<T, Observable<Boolean>>() { @Override public Observable<Boolean> call(T t) { if (isCommit) return db.commit(); else return db.rollback(); } }); } private static <T> Observable<T> beginTransactionOnNext(final Database db, Observable<T> source) { return source.concatMap(new Func1<T, Observable<T>>() { @Override public Observable<T> call(T t) { return db.beginTransaction().map(constant(t)); } }); } /** * Returns an {@link Observable} that is the result of running a sequence of * update commands (insert/update/delete, ddl) read from the given * {@link Observable} sequence. * * @param commands * @return */ public Observable<Integer> run(Observable<String> commands) { return commands.reduce(Observable.<Integer> empty(), new Func2<Observable<Integer>, String, Observable<Integer>>() { @Override public Observable<Integer> call(Observable<Integer> dep, String command) { return update(command).dependsOn(dep).count(); } }).lift(RxUtil.<Integer> flatten()); } /** * Returns an {@link Operator} version of {@link #run(Observable)}. * * @return */ public Operator<Integer, String> run() { return RxUtil.toOperator(new Func1<Observable<String>, Observable<Integer>>() { @Override public Observable<Integer> call(Observable<String> commands) { return run(commands); } }); } /** * Returns an {@link Observable} that is the result of running a sequence of * update commands (insert/update/delete, ddl) commands read from an * InputStream using the given delimiter as the statement delimiter (for * example semicolon). * * @param is * @param delimiter * @return */ public Observable<Integer> run(InputStream is, String delimiter) { return run(is, Charset.defaultCharset(), delimiter); } /** * Returns an {@link Observable} that is the result of running a sequence of * update commands (insert/update/delete, ddl) commands read from an * {@link InputStream} with the given {@link Charset} using the given delimiter as the statement delimiter (for * example semicolon). * * @param is * @param delimiter * @return */ public Observable<Integer> run(InputStream is, Charset charset, String delimiter) { return StringObservable.split(StringObservable.from(new InputStreamReader(is,charset)), ";").lift( run()); } /** * Returns a Database based on the current Database except all queries run * {@link Schedulers#io}. * * @return */ public Database asynchronous() { return new Database(cp, IO_SCHEDULER_FACTORY); } /** * Sentinel object used to indicate in parameters of a query that rather * than calling {@link PreparedStatement#setObject(int, Object)} with a null * we call {@link PreparedStatement#setNull(int, int)} with * {@link Types#CLOB}. This is required by many databases for setting CLOB * and BLOB fields to null. */ public static final Object NULL_CLOB = new Object(); public static Object toSentinelIfNull(String s) { if (s == null) return NULL_CLOB; else return s; } /** * Sentinel object used to indicate in parameters of a query that rather * than calling {@link PreparedStatement#setObject(int, Object)} with a null * we call {@link PreparedStatement#setNull(int, int)} with * {@link Types#CLOB}. This is required by many databases for setting CLOB * and BLOB fields to null. */ public static final Object NULL_BLOB = new Object(); public static Object toSentinelIfNull(byte[] bytes) { if (bytes == null) return NULL_BLOB; else return bytes; } }
package com.google.firebase.database.core; import static com.google.firebase.database.utilities.Utilities.hardAssert; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseException; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.InternalHelpers; import com.google.firebase.database.MutableData; import com.google.firebase.database.Transaction; import com.google.firebase.database.ValueEventListener; import com.google.firebase.database.annotations.NotNull; import com.google.firebase.database.connection.HostInfo; import com.google.firebase.database.connection.ListenHashProvider; import com.google.firebase.database.connection.PersistentConnection; import com.google.firebase.database.connection.RequestResultCallback; import com.google.firebase.database.core.persistence.NoopPersistenceManager; import com.google.firebase.database.core.persistence.PersistenceManager; import com.google.firebase.database.core.utilities.Tree; import com.google.firebase.database.core.view.Event; import com.google.firebase.database.core.view.EventRaiser; import com.google.firebase.database.core.view.QuerySpec; import com.google.firebase.database.logging.LogWrapper; import com.google.firebase.database.snapshot.ChildKey; import com.google.firebase.database.snapshot.EmptyNode; import com.google.firebase.database.snapshot.IndexedNode; import com.google.firebase.database.snapshot.Node; import com.google.firebase.database.snapshot.NodeUtilities; import com.google.firebase.database.snapshot.RangeMerge; import com.google.firebase.database.utilities.DefaultClock; import com.google.firebase.database.utilities.OffsetClock; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class Repo implements PersistentConnection.Delegate { private static final String INTERRUPT_REASON = "repo_interrupt"; /** * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure * that if there's ever a bug causing a mismatch between client / server hashes for some data, we * won't retry indefinitely. */ private static final int TRANSACTION_MAX_RETRIES = 25; private static final String TRANSACTION_TOO_MANY_RETRIES = "maxretries"; private static final String TRANSACTION_OVERRIDE_BY_SET = "overriddenBySet"; private final RepoInfo repoInfo; private final OffsetClock serverClock = new OffsetClock(new DefaultClock(), 0); private final PersistentConnection connection; private final EventRaiser eventRaiser; private final Context ctx; private final LogWrapper operationLogger; private final LogWrapper transactionLogger; private final LogWrapper dataLogger; public long dataUpdateCount = 0; // for testing. private SnapshotHolder infoData; private SparseSnapshotTree onDisconnect; private Tree<List<TransactionData>> transactionQueueTree; private boolean hijackHash = false; private long nextWriteId = 1; private SyncTree infoSyncTree; private SyncTree serverSyncTree; private FirebaseDatabase database; private boolean loggedTransactionPersistenceWarning = false; private long transactionOrder = 0; Repo(RepoInfo repoInfo, Context ctx, FirebaseDatabase database) { this.repoInfo = repoInfo; this.ctx = ctx; this.database = database; operationLogger = this.ctx.getLogger("RepoOperation"); transactionLogger = this.ctx.getLogger("Transaction"); dataLogger = this.ctx.getLogger("DataOperation"); this.eventRaiser = new EventRaiser(this.ctx); HostInfo hostInfo = new HostInfo(repoInfo.host, repoInfo.namespace, repoInfo.secure); connection = ctx.newPersistentConnection(hostInfo, this); // Kick off any expensive additional initialization scheduleNow( new Runnable() { @Override public void run() { deferredInitialization(); } }); } private static DatabaseError fromErrorCode(String optErrorCode, String optErrorReason) { if (optErrorCode != null) { return DatabaseError.fromStatus(optErrorCode, optErrorReason); } else { return null; } } // Regarding the next three methods: scheduleNow, schedule, and postEvent: // Please use these methods rather than accessing the context directly. This ensures that the // context is correctly re-initialized if it was previously shut down. In practice, this means // that when a task is submitted, we will guarantee at least one thread in the core pool for the // run loop. /** * Defers any initialization that is potentially expensive (e.g. disk access) and must be run on * the run loop */ private void deferredInitialization() { this.ctx.getAuthTokenProvider() .addTokenChangeListener( new AuthTokenProvider.TokenChangeListener() { // TODO(mikelehen): Remove this once AndroidAuthTokenProvider is updated to call the // other overload. @Override public void onTokenChange() { operationLogger.debug("Auth token changed, triggering auth token refresh"); connection.refreshAuthToken(); } @Override public void onTokenChange(String token) { operationLogger.debug("Auth token changed, triggering auth token refresh"); connection.refreshAuthToken(token); } }); // Open connection now so that by the time we are connected the deferred init has run // This relies on the fact that all callbacks run on repo's runloop. connection.initialize(); PersistenceManager persistenceManager = ctx.getPersistenceManager(repoInfo.host); infoData = new SnapshotHolder(); onDisconnect = new SparseSnapshotTree(); transactionQueueTree = new Tree<>(); infoSyncTree = new SyncTree(ctx, new NoopPersistenceManager(), new SyncTree.ListenProvider() { @Override public void startListening( final QuerySpec query, Tag tag, final ListenHashProvider hash, final SyncTree.CompletionListener onComplete) { scheduleNow(new Runnable() { @Override public void run() { // This is possibly a hack, but we have different semantics for .info // endpoints. We don't raise null events on initial data... final Node node = infoData.getNode(query.getPath()); if (!node.isEmpty()) { List<? extends Event> infoEvents = infoSyncTree.applyServerOverwrite(query.getPath(), node); postEvents(infoEvents); onComplete.onListenComplete(null); } } }); } @Override public void stopListening(QuerySpec query, Tag tag) {} }); serverSyncTree = new SyncTree(ctx, persistenceManager, new SyncTree.ListenProvider() { @Override public void startListening( QuerySpec query, Tag tag, ListenHashProvider hash, final SyncTree.CompletionListener onListenComplete) { connection.listen( query.getPath().asList(), query.getParams().getWireProtocolParams(), hash, tag != null ? tag.getTagNumber() : null, new RequestResultCallback() { @Override public void onRequestResult(String optErrorCode, String optErrorMessage) { DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage); List<? extends Event> events = onListenComplete.onListenComplete(error); postEvents(events); } }); } @Override public void stopListening(QuerySpec query, Tag tag) { connection.unlisten( query.getPath().asList(), query.getParams().getWireProtocolParams()); } }); restoreWrites(persistenceManager); updateInfo(Constants.DOT_INFO_AUTHENTICATED, false); updateInfo(Constants.DOT_INFO_CONNECTED, false); } private void restoreWrites(PersistenceManager persistenceManager) { List<UserWriteRecord> writes = persistenceManager.loadUserWrites(); Map<String, Object> serverValues = ServerValues.generateServerValues(serverClock); long lastWriteId = Long.MIN_VALUE; for (final UserWriteRecord write : writes) { RequestResultCallback onComplete = new RequestResultCallback() { @Override public void onRequestResult(String optErrorCode, String optErrorMessage) { DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage); warnIfWriteFailed("Persisted write", write.getPath(), error); ackWriteAndRerunTransactions(write.getWriteId(), write.getPath(), error); } }; if (lastWriteId >= write.getWriteId()) { throw new IllegalStateException("Write ids were not in order."); } lastWriteId = write.getWriteId(); nextWriteId = write.getWriteId() + 1; if (write.isOverwrite()) { if (operationLogger.logsDebug()) { operationLogger.debug("Restoring overwrite with id " + write.getWriteId()); } connection.put(write.getPath().asList(), write.getOverwrite().getValue(true), onComplete); Node resolved = ServerValues.resolveDeferredValueSnapshot(write.getOverwrite(), serverValues); serverSyncTree.applyUserOverwrite( write.getPath(), write.getOverwrite(), resolved, write.getWriteId(), /*visible=*/ true, /*persist=*/ false); } else { if (operationLogger.logsDebug()) { operationLogger.debug("Restoring merge with id " + write.getWriteId()); } connection.merge(write.getPath().asList(), write.getMerge().getValue(true), onComplete); CompoundWrite resolved = ServerValues.resolveDeferredValueMerge(write.getMerge(), serverValues); serverSyncTree.applyUserMerge( write.getPath(), write.getMerge(), resolved, write.getWriteId(), /*persist=*/ false); } } } public FirebaseDatabase getDatabase() { return this.database; } @Override public String toString() { return repoInfo.toString(); } public RepoInfo getRepoInfo() { return this.repoInfo; } public void scheduleNow(Runnable r) { ctx.requireStarted(); ctx.getRunLoop().scheduleNow(r); } public void postEvent(Runnable r) { ctx.requireStarted(); ctx.getEventTarget().postEvent(r); } private void postEvents(final List<? extends Event> events) { if (!events.isEmpty()) { this.eventRaiser.raiseEvents(events); } } public long getServerTime() { return serverClock.millis(); } boolean hasListeners() { return !(this.infoSyncTree.isEmpty() && this.serverSyncTree.isEmpty()); } // PersistentConnection.Delegate methods @SuppressWarnings("unchecked") // For the cast on rawMergedData @Override public void onDataUpdate( List<String> pathSegments, Object message, boolean isMerge, Long optTag) { Path path = new Path(pathSegments); if (operationLogger.logsDebug()) { operationLogger.debug("onDataUpdate: " + path); } if (dataLogger.logsDebug()) { operationLogger.debug("onDataUpdate: " + path + " " + message); } dataUpdateCount++; // For testing. List<? extends Event> events; try { if (optTag != null) { Tag tag = new Tag(optTag); if (isMerge) { Map<Path, Node> taggedChildren = new HashMap<>(); Map<String, Object> rawMergeData = (Map<String, Object>) message; for (Map.Entry<String, Object> entry : rawMergeData.entrySet()) { Node newChildNode = NodeUtilities.NodeFromJSON(entry.getValue()); taggedChildren.put(new Path(entry.getKey()), newChildNode); } events = this.serverSyncTree.applyTaggedQueryMerge(path, taggedChildren, tag); } else { Node taggedSnap = NodeUtilities.NodeFromJSON(message); events = this.serverSyncTree.applyTaggedQueryOverwrite(path, taggedSnap, tag); } } else if (isMerge) { Map<Path, Node> changedChildren = new HashMap<>(); Map<String, Object> rawMergeData = (Map<String, Object>) message; for (Map.Entry<String, Object> entry : rawMergeData.entrySet()) { Node newChildNode = NodeUtilities.NodeFromJSON(entry.getValue()); changedChildren.put(new Path(entry.getKey()), newChildNode); } events = this.serverSyncTree.applyServerMerge(path, changedChildren); } else { Node snap = NodeUtilities.NodeFromJSON(message); events = this.serverSyncTree.applyServerOverwrite(path, snap); } if (events.size() > 0) { // Since we have a listener outstanding for each transaction, receiving any events // is a proxy for some change having occurred. this.rerunTransactions(path); } postEvents(events); } catch (DatabaseException e) { operationLogger.error("FIREBASE INTERNAL ERROR", e); } } @Override public void onRangeMergeUpdate( List<String> pathSegments, List<com.google.firebase.database.connection.RangeMerge> merges, Long tagNumber) { Path path = new Path(pathSegments); if (operationLogger.logsDebug()) { operationLogger.debug("onRangeMergeUpdate: " + path); } if (dataLogger.logsDebug()) { operationLogger.debug("onRangeMergeUpdate: " + path + " " + merges); } dataUpdateCount++; // For testing. List<RangeMerge> parsedMerges = new ArrayList<>(merges.size()); for (com.google.firebase.database.connection.RangeMerge merge : merges) { parsedMerges.add(new RangeMerge(merge)); } List<? extends Event> events; if (tagNumber != null) { events = this.serverSyncTree.applyTaggedRangeMerges(path, parsedMerges, new Tag(tagNumber)); } else { events = this.serverSyncTree.applyServerRangeMerges(path, parsedMerges); } if (events.size() > 0) { // Since we have a listener outstanding for each transaction, receiving any events // is a proxy for some change having occurred. this.rerunTransactions(path); } postEvents(events); } void callOnComplete( final DatabaseReference.CompletionListener onComplete, final DatabaseError error, final Path path) { if (onComplete != null) { final DatabaseReference ref; ChildKey last = path.getBack(); if (last != null && last.isPriorityChildName()) { ref = InternalHelpers.createReference(this, path.getParent()); } else { ref = InternalHelpers.createReference(this, path); } postEvent( new Runnable() { @Override public void run() { onComplete.onComplete(error, ref); } }); } } private void ackWriteAndRerunTransactions(long writeId, Path path, DatabaseError error) { if (error != null && error.getCode() == DatabaseError.WRITE_CANCELED) { // This write was already removed, we just need to ignore it... } else { boolean success = error == null; List<? extends Event> clearEvents = serverSyncTree.ackUserWrite(writeId, !success, /*persist=*/ true, serverClock); if (clearEvents.size() > 0) { rerunTransactions(path); } postEvents(clearEvents); } } public void setValue( final Path path, Node newValueUnresolved, final DatabaseReference.CompletionListener onComplete) { if (operationLogger.logsDebug()) { operationLogger.debug("set: " + path); } if (dataLogger.logsDebug()) { dataLogger.debug("set: " + path + " " + newValueUnresolved); } Map<String, Object> serverValues = ServerValues.generateServerValues(serverClock); Node newValue = ServerValues.resolveDeferredValueSnapshot(newValueUnresolved, serverValues); final long writeId = this.getNextWriteId(); List<? extends Event> events = this.serverSyncTree.applyUserOverwrite( path, newValueUnresolved, newValue, writeId, /*visible=*/ true, /*persist=*/ true); this.postEvents(events); connection.put( path.asList(), newValueUnresolved.getValue(true), new RequestResultCallback() { @Override public void onRequestResult(String optErrorCode, String optErrorMessage) { DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage); warnIfWriteFailed("setValue", path, error); ackWriteAndRerunTransactions(writeId, path, error); callOnComplete(onComplete, error, path); } }); Path affectedPath = abortTransactions(path, DatabaseError.OVERRIDDEN_BY_SET); this.rerunTransactions(affectedPath); } public void updateChildren( final Path path, CompoundWrite updates, final DatabaseReference.CompletionListener onComplete, Map<String, Object> unParsedUpdates) { if (operationLogger.logsDebug()) { operationLogger.debug("update: " + path); } if (dataLogger.logsDebug()) { dataLogger.debug("update: " + path + " " + unParsedUpdates); } if (updates.isEmpty()) { if (operationLogger.logsDebug()) { operationLogger.debug("update called with no changes. No-op"); } // dispatch on complete callOnComplete(onComplete, null, path); return; } // Start with our existing data and merge each child into it. Map<String, Object> serverValues = ServerValues.generateServerValues(serverClock); CompoundWrite resolved = ServerValues.resolveDeferredValueMerge(updates, serverValues); final long writeId = this.getNextWriteId(); List<? extends Event> events = this.serverSyncTree.applyUserMerge(path, updates, resolved, writeId, /*persist=*/ true); this.postEvents(events); // TODO: DatabaseReference.CompleteionListener isn't really appropriate (the DatabaseReference // param is meaningless). connection.merge( path.asList(), unParsedUpdates, new RequestResultCallback() { @Override public void onRequestResult(String optErrorCode, String optErrorMessage) { DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage); warnIfWriteFailed("updateChildren", path, error); ackWriteAndRerunTransactions(writeId, path, error); callOnComplete(onComplete, error, path); } }); for (Entry<Path, Node> update : updates) { Path pathFromRoot = path.child(update.getKey()); Path affectedPath = abortTransactions(pathFromRoot, DatabaseError.OVERRIDDEN_BY_SET); rerunTransactions(affectedPath); } } public void purgeOutstandingWrites() { if (operationLogger.logsDebug()) { operationLogger.debug("Purging writes"); } List<? extends Event> events = serverSyncTree.removeAllWrites(); postEvents(events); // Abort any transactions abortTransactions(Path.getEmptyPath(), DatabaseError.WRITE_CANCELED); // Remove outstanding writes from connection connection.purgeOutstandingWrites(); } public void removeEventCallback(@NotNull EventRegistration eventRegistration) { // These are guaranteed not to raise events, since we're not passing in a cancelError. However, // we can future-proof a little bit by handling the return values anyways. List<Event> events; if (Constants.DOT_INFO.equals(eventRegistration.getQuerySpec().getPath().getFront())) { events = infoSyncTree.removeEventRegistration(eventRegistration); } else { events = serverSyncTree.removeEventRegistration(eventRegistration); } this.postEvents(events); } public void onDisconnectSetValue( final Path path, final Node newValue, final DatabaseReference.CompletionListener onComplete) { connection.onDisconnectPut( path.asList(), newValue.getValue(true), new RequestResultCallback() { @Override public void onRequestResult(String optErrorCode, String optErrorMessage) { DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage); warnIfWriteFailed("onDisconnect().setValue", path, error); if (error == null) { onDisconnect.remember(path, newValue); } callOnComplete(onComplete, error, path); } }); } public void onDisconnectUpdate( final Path path, final Map<Path, Node> newChildren, final DatabaseReference.CompletionListener listener, Map<String, Object> unParsedUpdates) { connection.onDisconnectMerge( path.asList(), unParsedUpdates, new RequestResultCallback() { @Override public void onRequestResult(String optErrorCode, String optErrorMessage) { DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage); warnIfWriteFailed("onDisconnect().updateChildren", path, error); if (error == null) { for (Map.Entry<Path, Node> entry : newChildren.entrySet()) { onDisconnect.remember(path.child(entry.getKey()), entry.getValue()); } } callOnComplete(listener, error, path); } }); } public void onDisconnectCancel( final Path path, final DatabaseReference.CompletionListener onComplete) { connection.onDisconnectCancel( path.asList(), new RequestResultCallback() { @Override public void onRequestResult(String optErrorCode, String optErrorMessage) { DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage); if (error == null) { onDisconnect.forget(path); } callOnComplete(onComplete, error, path); } }); } @Override public void onConnect() { onServerInfoUpdate(Constants.DOT_INFO_CONNECTED, true); } @Override public void onDisconnect() { onServerInfoUpdate(Constants.DOT_INFO_CONNECTED, false); runOnDisconnectEvents(); } @Override public void onAuthStatus(boolean authOk) { onServerInfoUpdate(Constants.DOT_INFO_AUTHENTICATED, authOk); } public void onServerInfoUpdate(ChildKey key, Object value) { updateInfo(key, value); } @Override public void onServerInfoUpdate(Map<String, Object> updates) { for (Map.Entry<String, Object> entry : updates.entrySet()) { updateInfo(ChildKey.fromString(entry.getKey()), entry.getValue()); } } void interrupt() { connection.interrupt(INTERRUPT_REASON); } void resume() { connection.resume(INTERRUPT_REASON); } public void addEventCallback(@NotNull EventRegistration eventRegistration) { List<? extends Event> events; ChildKey front = eventRegistration.getQuerySpec().getPath().getFront(); if (front != null && front.equals(Constants.DOT_INFO)) { events = this.infoSyncTree.addEventRegistration(eventRegistration); } else { events = this.serverSyncTree.addEventRegistration(eventRegistration); } this.postEvents(events); } public void keepSynced(QuerySpec query, boolean keep) { assert query.getPath().isEmpty() || !query.getPath().getFront().equals(Constants.DOT_INFO); serverSyncTree.keepSynced(query, keep); } // Transaction code PersistentConnection getConnection() { return connection; } private void updateInfo(ChildKey childKey, Object value) { if (childKey.equals(Constants.DOT_INFO_SERVERTIME_OFFSET)) { serverClock.setOffset((Long) value); } Path path = new Path(Constants.DOT_INFO, childKey); try { Node node = NodeUtilities.NodeFromJSON(value); infoData.update(path, node); List<? extends Event> events = this.infoSyncTree.applyServerOverwrite(path, node); this.postEvents(events); } catch (DatabaseException e) { operationLogger.error("Failed to parse info update", e); } } private long getNextWriteId() { return this.nextWriteId++; } private void runOnDisconnectEvents() { Map<String, Object> serverValues = ServerValues.generateServerValues(serverClock); SparseSnapshotTree resolvedTree = ServerValues.resolveDeferredValueTree(this.onDisconnect, serverValues); final List<Event> events = new ArrayList<>(); resolvedTree.forEachTree( Path.getEmptyPath(), new SparseSnapshotTree.SparseSnapshotTreeVisitor() { @Override public void visitTree(Path prefixPath, Node node) { events.addAll(serverSyncTree.applyServerOverwrite(prefixPath, node)); Path affectedPath = abortTransactions(prefixPath, DatabaseError.OVERRIDDEN_BY_SET); rerunTransactions(affectedPath); } }); onDisconnect = new SparseSnapshotTree(); this.postEvents(events); } private void warnIfWriteFailed(String writeType, Path path, DatabaseError error) { // DATA_STALE is a normal, expected error during transaction processing. if (error != null && !(error.getCode() == DatabaseError.DATA_STALE || error.getCode() == DatabaseError.WRITE_CANCELED)) { operationLogger.warn(writeType + " at " + path.toString() + " failed: " + error.toString()); } } public void startTransaction(Path path, final Transaction.Handler handler, boolean applyLocally) { if (operationLogger.logsDebug()) { operationLogger.debug("transaction: " + path); } if (dataLogger.logsDebug()) { operationLogger.debug("transaction: " + path); } if (this.ctx.isPersistenceEnabled() && !loggedTransactionPersistenceWarning) { loggedTransactionPersistenceWarning = true; transactionLogger.info( "runTransaction() usage detected while persistence is enabled. Please be aware that " + "transactions *will not* be persisted across database restarts. See " + "https: + "#section-handling-transactions-offline for more details."); } // make sure we're listening on this node // Note: we can't do this asynchronously. To preserve event ordering, // it has to be done in this block. This is ok, this block is // guaranteed to be our own event loop DatabaseReference watchRef = InternalHelpers.createReference(this, path); ValueEventListener listener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { // No-op. We don't care, this is just to make sure we have a listener outstanding } @Override public void onCancelled(DatabaseError error) { // Also a no-op? We'll cancel the transaction in this case } }; addEventCallback(new ValueEventRegistration(this, listener, watchRef.getSpec())); TransactionData transaction = new TransactionData( path, handler, listener, TransactionStatus.INITIALIZING, applyLocally, nextTransactionOrder()); // Run transaction initially. Node currentState = this.getLatestState(path); transaction.currentInputSnapshot = currentState; MutableData mutableCurrent = InternalHelpers.createMutableData(currentState); DatabaseError error = null; Transaction.Result result; try { result = handler.doTransaction(mutableCurrent); if (result == null) { throw new NullPointerException("Transaction returned null as result"); } } catch (Throwable e) { error = DatabaseError.fromException(e); result = Transaction.abort(); } if (!result.isSuccess()) { // Abort the transaction transaction.currentOutputSnapshotRaw = null; transaction.currentOutputSnapshotResolved = null; final DatabaseError innerClassError = error; final DataSnapshot snap = InternalHelpers.createDataSnapshot( watchRef, IndexedNode.from(transaction.currentInputSnapshot)); postEvent( new Runnable() { @Override public void run() { handler.onComplete(innerClassError, false, snap); } }); } else { // Mark as run and add to our queue. transaction.status = TransactionStatus.RUN; Tree<List<TransactionData>> queueNode = transactionQueueTree.subTree(path); List<TransactionData> nodeQueue = queueNode.getValue(); if (nodeQueue == null) { nodeQueue = new ArrayList<>(); } nodeQueue.add(transaction); queueNode.setValue(nodeQueue); Map<String, Object> serverValues = ServerValues.generateServerValues(serverClock); Node newNodeUnresolved = result.getNode(); Node newNode = ServerValues.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues); transaction.currentOutputSnapshotRaw = newNodeUnresolved; transaction.currentOutputSnapshotResolved = newNode; transaction.currentWriteId = this.getNextWriteId(); List<? extends Event> events = this.serverSyncTree.applyUserOverwrite( path, newNodeUnresolved, newNode, transaction.currentWriteId, /*visible=*/ applyLocally, /*persist=*/ false); this.postEvents(events); sendAllReadyTransactions(); } } private Node getLatestState(Path path) { return this.getLatestState(path, new ArrayList<Long>()); } private Node getLatestState(Path path, List<Long> excudeSets) { Node state = this.serverSyncTree.calcCompleteEventCache(path, excudeSets); if (state == null) { state = EmptyNode.Empty(); } return state; } public void setHijackHash(boolean hijackHash) { this.hijackHash = hijackHash; } private void sendAllReadyTransactions() { Tree<List<TransactionData>> node = transactionQueueTree; pruneCompletedTransactions(node); sendReadyTransactions(node); } private void sendReadyTransactions(Tree<List<TransactionData>> node) { List<TransactionData> queue = node.getValue(); if (queue != null) { queue = buildTransactionQueue(node); assert queue.size() > 0; // Sending zero length transaction queue Boolean allRun = true; for (TransactionData transaction : queue) { if (transaction.status != TransactionStatus.RUN) { allRun = false; break; } } // If they're all run (and not sent), we can send them. Else, we must wait. if (allRun) { sendTransactionQueue(queue, node.getPath()); } } else if (node.hasChildren()) { node.forEachChild( new Tree.TreeVisitor<List<TransactionData>>() { @Override public void visitTree(Tree<List<TransactionData>> tree) { sendReadyTransactions(tree); } }); } } private void sendTransactionQueue(final List<TransactionData> queue, final Path path) { // Mark transactions as sent and increment retry count! List<Long> setsToIgnore = new ArrayList<>(); for (TransactionData txn : queue) { setsToIgnore.add(txn.currentWriteId); } Node latestState = this.getLatestState(path, setsToIgnore); Node snapToSend = latestState; String latestHash = "badhash"; if (!hijackHash) { latestHash = latestState.getHash(); } for (TransactionData txn : queue) { assert txn.status == TransactionStatus.RUN; // sendTransactionQueue: items in queue should all be run.' txn.status = TransactionStatus.SENT; txn.retryCount++; Path relativePath = Path.getRelative(path, txn.path); // If we've gotten to this point, the output snapshot must be defined. snapToSend = snapToSend.updateChild(relativePath, txn.currentOutputSnapshotRaw); } Object dataToSend = snapToSend.getValue(true); final Repo repo = this; // Send the put. connection.compareAndPut( path.asList(), dataToSend, latestHash, new RequestResultCallback() { @Override public void onRequestResult(String optErrorCode, String optErrorMessage) { DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage); warnIfWriteFailed("Transaction", path, error); List<Event> events = new ArrayList<>(); if (error == null) { List<Runnable> callbacks = new ArrayList<>(); for (final TransactionData txn : queue) { txn.status = TransactionStatus.COMPLETED; events.addAll( serverSyncTree.ackUserWrite( txn.currentWriteId, /*revert=*/ false, /*persist=*/ false, serverClock)); // We never unset the output snapshot, and given that this // transaction is complete, it should be set Node node = txn.currentOutputSnapshotResolved; final DataSnapshot snap = InternalHelpers.createDataSnapshot( InternalHelpers.createReference(repo, txn.path), IndexedNode.from(node)); callbacks.add( new Runnable() { @Override public void run() { txn.handler.onComplete(null, true, snap); } }); // Remove the outstanding value listener that we added removeEventCallback( new ValueEventRegistration( Repo.this, txn.outstandingListener, QuerySpec.defaultQueryAtPath(txn.path))); } // Now remove the completed transactions pruneCompletedTransactions(transactionQueueTree.subTree(path)); // There may be pending transactions that we can now send sendAllReadyTransactions(); repo.postEvents(events); // Finally, run the callbacks for (int i = 0; i < callbacks.size(); ++i) { postEvent(callbacks.get(i)); } } else { // transactions are no longer sent. Update their status appropriately if (error.getCode() == DatabaseError.DATA_STALE) { for (TransactionData transaction : queue) { if (transaction.status == TransactionStatus.SENT_NEEDS_ABORT) { transaction.status = TransactionStatus.NEEDS_ABORT; } else { transaction.status = TransactionStatus.RUN; } } } else { for (TransactionData transaction : queue) { transaction.status = TransactionStatus.NEEDS_ABORT; transaction.abortReason = error; } } // since we reverted mergedData, we should re-run any remaining // transactions and raise events rerunTransactions(path); } } }); } private void pruneCompletedTransactions(Tree<List<TransactionData>> node) { List<TransactionData> queue = node.getValue(); if (queue != null) { int i = 0; while (i < queue.size()) { TransactionData transaction = queue.get(i); if (transaction.status == TransactionStatus.COMPLETED) { queue.remove(i); } else { i++; } } if (queue.size() > 0) { node.setValue(queue); } else { node.setValue(null); } } node.forEachChild( new Tree.TreeVisitor<List<TransactionData>>() { @Override public void visitTree(Tree<List<TransactionData>> tree) { pruneCompletedTransactions(tree); } }); } private long nextTransactionOrder() { return transactionOrder++; } private Path rerunTransactions(Path changedPath) { Tree<List<TransactionData>> rootMostTransactionNode = getAncestorTransactionNode(changedPath); Path path = rootMostTransactionNode.getPath(); List<TransactionData> queue = buildTransactionQueue(rootMostTransactionNode); rerunTransactionQueue(queue, path); return path; } private void rerunTransactionQueue(List<TransactionData> queue, Path path) { if (queue.isEmpty()) { return; // Nothing to do! } // Queue up the callbacks and fire them after cleaning up all of our transaction state, since // the callback could trigger more transactions or sets List<Runnable> callbacks = new ArrayList<>(); // Ignore, by default, all of the sets in this queue, since we're re-running all of them. // However, we want to include the results of new sets triggered as part of this re-run, so we // don't want to ignore a range, just these specific sets. List<Long> setsToIgnore = new ArrayList<>(); for (TransactionData transaction : queue) { setsToIgnore.add(transaction.currentWriteId); } for (final TransactionData transaction : queue) { Path relativePath = Path.getRelative(path, transaction.path); boolean abortTransaction = false; DatabaseError abortReason = null; List<Event> events = new ArrayList<>(); assert relativePath != null; // rerunTransactionQueue: relativePath should not be null. if (transaction.status == TransactionStatus.NEEDS_ABORT) { abortTransaction = true; abortReason = transaction.abortReason; if (abortReason.getCode() != DatabaseError.WRITE_CANCELED) { events.addAll( serverSyncTree.ackUserWrite( transaction.currentWriteId, /*revert=*/ true, /*persist=*/ false, serverClock)); } } else if (transaction.status == TransactionStatus.RUN) { if (transaction.retryCount >= TRANSACTION_MAX_RETRIES) { abortTransaction = true; abortReason = DatabaseError.fromStatus(TRANSACTION_TOO_MANY_RETRIES); events.addAll( serverSyncTree.ackUserWrite( transaction.currentWriteId, /*revert=*/ true, /*persist=*/ false, serverClock)); } else { // This code reruns a transaction Node currentNode = this.getLatestState(transaction.path, setsToIgnore); transaction.currentInputSnapshot = currentNode; MutableData mutableCurrent = InternalHelpers.createMutableData(currentNode); DatabaseError error = null; Transaction.Result result; try { result = transaction.handler.doTransaction(mutableCurrent); } catch (Throwable e) { error = DatabaseError.fromException(e); result = Transaction.abort(); } if (result.isSuccess()) { final Long oldWriteId = transaction.currentWriteId; Map<String, Object> serverValues = ServerValues.generateServerValues(serverClock); Node newDataNode = result.getNode(); Node newNodeResolved = ServerValues.resolveDeferredValueSnapshot(newDataNode, serverValues); transaction.currentOutputSnapshotRaw = newDataNode; transaction.currentOutputSnapshotResolved = newNodeResolved; transaction.currentWriteId = this.getNextWriteId(); // Mutates setsToIgnore in place setsToIgnore.remove(oldWriteId); events.addAll( serverSyncTree.applyUserOverwrite( transaction.path, newDataNode, newNodeResolved, transaction.currentWriteId, transaction.applyLocally, /*persist=*/ false)); events.addAll( serverSyncTree.ackUserWrite( oldWriteId, /*revert=*/ true, /*persist=*/ false, serverClock)); } else { // The user aborted the transaction. It's not an error, so we don't need to send them // one abortTransaction = true; abortReason = error; events.addAll( serverSyncTree.ackUserWrite( transaction.currentWriteId, /*revert=*/ true, /*persist=*/ false, serverClock)); } } } this.postEvents(events); if (abortTransaction) { // Abort transaction.status = TransactionStatus.COMPLETED; final DatabaseReference ref = InternalHelpers.createReference(this, transaction.path); // We set this field immediately, so it's safe to cast to an actual snapshot Node lastInput = transaction.currentInputSnapshot; // TODO: In the future, perhaps this should just be KeyIndex? final DataSnapshot snapshot = InternalHelpers.createDataSnapshot(ref, IndexedNode.from(lastInput)); // Removing a callback can trigger pruning which can muck with mergedData/visibleData (as it // prunes data). So defer removing the callback until later. this.scheduleNow( new Runnable() { @Override public void run() { removeEventCallback( new ValueEventRegistration( Repo.this, transaction.outstandingListener, QuerySpec.defaultQueryAtPath(transaction.path))); } }); final DatabaseError callbackError = abortReason; callbacks.add( new Runnable() { @Override public void run() { transaction.handler.onComplete(callbackError, false, snapshot); } }); } } // Clean up completed transactions. pruneCompletedTransactions(transactionQueueTree); // Now fire callbacks, now that we're in a good, known state. for (int i = 0; i < callbacks.size(); ++i) { postEvent(callbacks.get(i)); } // Try to send the transaction result to the server. sendAllReadyTransactions(); } private Tree<List<TransactionData>> getAncestorTransactionNode(Path path) { Tree<List<TransactionData>> transactionNode = transactionQueueTree; while (!path.isEmpty() && transactionNode.getValue() == null) { transactionNode = transactionNode.subTree(new Path(path.getFront())); path = path.popFront(); } return transactionNode; } private List<TransactionData> buildTransactionQueue(Tree<List<TransactionData>> transactionNode) { List<TransactionData> queue = new ArrayList<>(); aggregateTransactionQueues(queue, transactionNode); Collections.sort(queue); return queue; } private void aggregateTransactionQueues( final List<TransactionData> queue, Tree<List<TransactionData>> node) { List<TransactionData> childQueue = node.getValue(); if (childQueue != null) { queue.addAll(childQueue); } node.forEachChild( new Tree.TreeVisitor<List<TransactionData>>() { @Override public void visitTree(Tree<List<TransactionData>> tree) { aggregateTransactionQueues(queue, tree); } }); } private Path abortTransactions(Path path, final int reason) { Path affectedPath = getAncestorTransactionNode(path).getPath(); if (transactionLogger.logsDebug()) { operationLogger.debug( "Aborting transactions for path: " + path + ". Affected: " + affectedPath); } Tree<List<TransactionData>> transactionNode = transactionQueueTree.subTree(path); transactionNode.forEachAncestor( new Tree.TreeFilter<List<TransactionData>>() { @Override public boolean filterTreeNode(Tree<List<TransactionData>> tree) { abortTransactionsAtNode(tree, reason); return false; } }); abortTransactionsAtNode(transactionNode, reason); transactionNode.forEachDescendant( new Tree.TreeVisitor<List<TransactionData>>() { @Override public void visitTree(Tree<List<TransactionData>> tree) { abortTransactionsAtNode(tree, reason); } }); return affectedPath; } private void abortTransactionsAtNode(Tree<List<TransactionData>> node, int reason) { List<TransactionData> queue = node.getValue(); List<Event> events = new ArrayList<>(); if (queue != null) { List<Runnable> callbacks = new ArrayList<>(); final DatabaseError abortError; if (reason == DatabaseError.OVERRIDDEN_BY_SET) { abortError = DatabaseError.fromStatus(TRANSACTION_OVERRIDE_BY_SET); } else { hardAssert( reason == DatabaseError.WRITE_CANCELED, "Unknown transaction abort reason: " + reason); abortError = DatabaseError.fromCode(DatabaseError.WRITE_CANCELED); } int lastSent = -1; for (int i = 0; i < queue.size(); ++i) { final TransactionData transaction = queue.get(i); if (transaction.status == TransactionStatus.SENT_NEEDS_ABORT) { // No-op. Already marked } else if (transaction.status == TransactionStatus.SENT) { assert lastSent == i - 1; // All SENT items should be at beginning of queue. lastSent = i; // Mark transaction for abort when it comes back. transaction.status = TransactionStatus.SENT_NEEDS_ABORT; transaction.abortReason = abortError; } else { assert transaction.status == TransactionStatus.RUN; // Unexpected transaction status in abort // We can abort this immediately. removeEventCallback( new ValueEventRegistration( Repo.this, transaction.outstandingListener, QuerySpec.defaultQueryAtPath(transaction.path))); if (reason == DatabaseError.OVERRIDDEN_BY_SET) { events.addAll( serverSyncTree.ackUserWrite( transaction.currentWriteId, /*revert=*/ true, /*persist=*/ false, serverClock)); } else { hardAssert( reason == DatabaseError.WRITE_CANCELED, "Unknown transaction abort reason: " + reason); // If it was cancelled, it was already removed from the sync tree } callbacks.add( new Runnable() { @Override public void run() { transaction.handler.onComplete(abortError, false, null); } }); } } if (lastSent == -1) { // We're not waiting for any sent transactions. We can clear the queue node.setValue(null); } else { // Remove the transactions we aborted node.setValue(queue.subList(0, lastSent + 1)); } // Now fire the callbacks. this.postEvents(events); for (Runnable r : callbacks) { postEvent(r); } } } // Package private for testing purposes only SyncTree getServerSyncTree() { return serverSyncTree; } // Package private for testing purposes only SyncTree getInfoSyncTree() { return infoSyncTree; } private enum TransactionStatus { INITIALIZING, // We've run the transaction and updated transactionResultData_ with the result, but it isn't // currently sent to the server. // A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected // due to mismatched hash. RUN, // We've run the transaction and sent it to the server and it's currently outstanding (hasn't // come back as accepted or rejected yet). SENT, // Temporary state used to mark completed transactions (whether successful or aborted). The // transaction will be removed when we get a chance to prune completed ones. COMPLETED, // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() // call that was made). If it comes back as unsuccessful, we'll abort it. SENT_NEEDS_ABORT, // Temporary state used to mark transactions that need to be aborted. NEEDS_ABORT } private static class TransactionData implements Comparable<TransactionData> { private Path path; private Transaction.Handler handler; private ValueEventListener outstandingListener; private TransactionStatus status; private long order; private boolean applyLocally; private int retryCount; private DatabaseError abortReason; private long currentWriteId; private Node currentInputSnapshot; private Node currentOutputSnapshotRaw; private Node currentOutputSnapshotResolved; private TransactionData( Path path, Transaction.Handler handler, ValueEventListener outstandingListener, TransactionStatus status, boolean applyLocally, long order) { this.path = path; this.handler = handler; this.outstandingListener = outstandingListener; this.status = status; this.retryCount = 0; this.applyLocally = applyLocally; this.order = order; this.abortReason = null; this.currentInputSnapshot = null; this.currentOutputSnapshotRaw = null; this.currentOutputSnapshotResolved = null; } @Override public int compareTo(TransactionData o) { if (order < o.order) { return -1; } else if (order == o.order) { return 0; } else { return 1; } } } }
package com.inari.firefly.graphics.scene; import java.util.Set; import com.inari.commons.JavaUtils; import com.inari.commons.lang.functional.Callback; import com.inari.commons.lang.indexed.IIndexedTypeKey; import com.inari.firefly.component.attr.AttributeKey; import com.inari.firefly.component.attr.AttributeMap; import com.inari.firefly.system.FFContext; import com.inari.firefly.system.component.SystemComponent; public abstract class Scene extends SystemComponent { public static final SystemComponentKey<Scene> TYPE_KEY = SystemComponentKey.create( Scene.class ); public static final AttributeKey<Boolean> RUN_AGAIN = AttributeKey.createBoolean( "runAgain", Scene.class ); public static final Set<AttributeKey<?>> ATTRIBUTE_KEYS = JavaUtils.<AttributeKey<?>>unmodifiableSet( RUN_AGAIN ); boolean runAgain; Callback callback; protected boolean running = false; protected boolean paused = false; protected Scene( int index ) { super( index ); runAgain = true; } @Override public final IIndexedTypeKey indexedTypeKey() { return TYPE_KEY; } public final boolean isRunAgain() { return runAgain; } public final void setRunAgain( boolean runAgain ) { this.runAgain = runAgain; } public abstract void run( final FFContext context ); public abstract void reset( final FFContext context ); public abstract void update( final FFContext context ); public void dispose( final FFContext context ) { reset( context ); dispose(); } @Override public Set<AttributeKey<?>> attributeKeys() { return JavaUtils.unmodifiableSet( super.attributeKeys(), ATTRIBUTE_KEYS ); } @Override public void fromAttributes( AttributeMap attributes ) { super.fromAttributes( attributes ); runAgain = attributes.getValue( RUN_AGAIN, runAgain ); } @Override public void toAttributes( AttributeMap attributes ) { super.toAttributes( attributes ); attributes.put( RUN_AGAIN, runAgain ); } }
package com.jcabi.mysql.maven.plugin; import com.jcabi.aspects.Loggable; import com.jcabi.log.Logger; import com.jcabi.log.VerboseProcess; import com.jcabi.log.VerboseRunnable; import java.io.File; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import javax.validation.constraints.NotNull; import lombok.EqualsAndHashCode; import lombok.ToString; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.CharEncoding; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; /** * Running instances of MySQL. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 0.1 * @checkstyle ClassDataAbstractionCoupling (500 lines) * @checkstyle MultipleStringLiterals (500 lines) */ @ToString @EqualsAndHashCode(of = "processes") @Loggable(Loggable.INFO) @SuppressWarnings("PMD.DoNotUseThreads") final class Instances { /** * User. */ private static final String USER = "root"; /** * Password. */ private static final String PASSWORD = "root"; /** * Database name. */ private static final String DBNAME = "root"; /** * Running processes. */ private final transient ConcurrentMap<Integer, Process> processes = new ConcurrentHashMap<Integer, Process>(0); /** * Start a new one at this port. * @param port The port to start at * @param dist Path to MySQL distribution * @param target Where to keep temp data * @throws IOException If fails to start */ public void start(final int port, @NotNull final File dist, @NotNull final File target) throws IOException { if (target.exists()) { FileUtils.deleteDirectory(target); Logger.info(this, "deleted %s directory", target); } if (target.mkdirs()) { Logger.info(this, "created %s directory", target); } new File(target, "temp").mkdirs(); final File socket = new File(target, "mysql.sock"); final ProcessBuilder builder = this.builder( dist, "bin/mysqld", "--lc-messages-dir=./share", "--general_log", "--console", "--innodb_use_native_aio=0", "--innodb_buffer_pool_size=64M", "--innodb_log_file_size=64M", "--explicit_defaults_for_timestamp", "--log_warnings", "--binlog-ignore-db=data", String.format("--basedir=%s", dist), String.format("--datadir=%s", this.data(dist, target)), String.format("--tmpdir=%s/temp", target), String.format("--socket=%s", socket), String.format("--pid-file=%s/mysql.pid", target), String.format("--port=%d", port) ).redirectErrorStream(true); builder.environment().put("MYSQL_HOME", dist.getAbsolutePath()); final Process proc = builder.start(); final Thread thread = new Thread( new VerboseRunnable( new Callable<Void>() { @Override public Void call() throws Exception { new VerboseProcess(proc).stdout(); return null; } } ) ); thread.setDaemon(true); thread.start(); this.processes.put(port, proc); this.configure(dist, port, this.waitFor(socket, port)); Runtime.getRuntime().addShutdownHook( new Thread( new Runnable() { @Override public void run() { Instances.this.stop(port); } } ) ); } /** * Stop a running one at this port. * @param port The port to stop at */ public void stop(final int port) { final Process proc = this.processes.get(port); if (proc == null) { throw new IllegalArgumentException( String.format( "No MySQL instances running on port %d", port ) ); } proc.destroy(); } /** * Prepare and return data directory. * @param dist Path to MySQL distribution * @param target Where to create it * @return Directory created * @throws IOException If fails */ private File data(final File dist, final File target) throws IOException { final File dir = new File(target, "data"); if (SystemUtils.IS_OS_WINDOWS) { FileUtils.copyFile( new File(dist, "my-default.ini"), new File(dist, "support-files/my-default.cnf") ); } new VerboseProcess( this.builder( dist, "scripts/mysql_install_db", "--no-defaults", "--force", "--explicit_defaults_for_timestamp", String.format("--datadir=%s", dir) ) ).stdout(); return dir; } /** * Wait for this file to become available. * @param socket The file to wait for * @param port Port to wait for * @return The same socket, but ready for usage * @throws IOException If fails */ private File waitFor(final File socket, final int port) throws IOException { final long start = System.currentTimeMillis(); long age = 0; while (true) { if (socket.exists()) { Logger.info( this, "socket %s is available after %[ms]s of waiting", socket, age ); break; } if (Instances.isOpen(port)) { Logger.info( this, "port %s is available after %[ms]s of waiting", port, age ); break; } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new IllegalStateException(ex); } age = System.currentTimeMillis() - start; if (age > TimeUnit.MINUTES.toMillis(1)) { throw new IOException( Logger.format( "socket %s is not available after %[ms]s of waiting", socket, age ) ); } } return socket; } /** * Configure the running MySQL server. * @param dist Directory with MySQL distribution * @param port The port it's running on * @param socket Socket of it * @throws IOException If fails */ private void configure(final File dist, final int port, final File socket) throws IOException { new VerboseProcess( this.builder( dist, "bin/mysqladmin", String.format("--port=%d", port), String.format("--user=%s", Instances.USER), String.format("--socket=%s", socket), "--host=127.0.0.1", "password", Instances.PASSWORD ) ).stdout(); final Process process = this.builder( dist, "bin/mysql", String.format("--port=%d", port), String.format("--user=%s", Instances.USER), String.format("--password=%s", Instances.PASSWORD), String.format("--socket=%s", socket) ).start(); final PrintWriter writer = new PrintWriter( new OutputStreamWriter( process.getOutputStream(), CharEncoding.UTF_8 ) ); writer.print("CREATE DATABASE "); writer.print(Instances.DBNAME); writer.println(";"); writer.close(); new VerboseProcess(process).stdout(); } /** * Make process builder with this commands. * @param dist Distribution directory * @param name Name of the cmd to run * @param cmds Commands * @return Process builder */ private ProcessBuilder builder(final File dist, final String name, final String... cmds) { String label = name; final Collection<String> commands = new LinkedList<String>(); if (!new File(dist, label).exists()) { label = String.format("%s.exe", name); if (!new File(dist, label).exists()) { label = String.format("%s.pl", name); commands.add("perl"); } } commands.add(new File(dist, label).getAbsolutePath()); commands.addAll(Arrays.asList(cmds)); Logger.info(this, "$ %s", StringUtils.join(commands, " ")); return new ProcessBuilder() .command(commands.toArray(new String[commands.size()])) .directory(dist); } /** * Port is open. * @param port The port to check * @return TRUE if it's open */ private static boolean isOpen(final int port) { boolean open; try { new Socket((String) null, port); open = true; } catch (IOException ex) { open = false; } return open; } }
package com.joelhockey.smartcard; import com.joelhockey.codec.Buf; import com.joelhockey.codec.Hex; public class SmartcardUtil { /** * Format APDU. * @param cla cla * @param ins ins * @param p1 p1 * @param p2 p2 * @param data data * @param le le * @return formatted APDU */ public static byte[] formatAPDU(int cla, int ins, int p1, int p2, byte[] data, Integer le) { int lc = data == null ? 0 : data.length; byte[] lcbuf; // holds Lc - 1 or 3 bytes byte[] lebuf = null; // holds Le, 0, 1, or 2 bytes if (lc <= 255) { // single byte Lc and Le lcbuf = new byte[] {(byte) lc}; if (le != null) { lebuf = new byte[] {(byte) le.intValue()}; } } else { // extended lengths (3 bytes for Lc, 2 bytes for Le) lcbuf = new byte[] {0, (byte) (lc >> 8), (byte) lc}; if (le != null) { lebuf = new byte[] {(byte) (le.intValue() >> 8), (byte) le.intValue()}; } } return Buf.cat(new byte[] {(byte) cla, (byte) ins, (byte) p1, (byte) p2}, lcbuf, data, lebuf); } /** * Translate from {@link Smartcard#transmit(byte[])} * to {@link Smartcard#transmit(int, int, int, int, byte[], Integer)}. * <pre> * Command APDU encoding options: * * case 1: |CLA|INS|P1 |P2 | len = 4 * case 2s: |CLA|INS|P1 |P2 |LE | len = 5 * case 3s: |CLA|INS|P1 |P2 |LC |...BODY...| len = 6..260 * case 4s: |CLA|INS|P1 |P2 |LC |...BODY...|LE | len = 7..261 * case 2e: |CLA|INS|P1 |P2 |00 |LE1|LE2| len = 7 * case 3e: |CLA|INS|P1 |P2 |00 |LC1|LC2|...BODY...| len = 8..65542 * case 4e: |CLA|INS|P1 |P2 |00 |LC1|LC2|...BODY...|LE1|LE2| len =10..65544 * * LE, LE1, LE2 may be 0x00. * LC must not be 0x00 and LC1|LC2 must not be 0x00|0x00 * </pre> * @param card card to call {@link Smartcard#transmit(int, int, int, int, byte[], Integer)} * @param apdu apdu * @return APDURes from invoking {@link Smartcard#transmit(byte[])} * @throws SmartcardException if error */ public static APDURes transmit(Smartcard card, byte[] apdu) throws SmartcardException { if (apdu == null || apdu.length < 4) { throw new SmartcardException("APDU must be at least 4 bytes, got apdu: " + Hex.b2s(apdu)); } int cla = apdu[0] & 0xff; int ins = apdu[1] & 0xff; int p1 = apdu[2] & 0xff; int p2 = apdu[3] & 0xff; // case 1: |CLA|INS|P1 |P2 | len = 4 if (apdu.length == 4) { return card.transmit(cla, ins, p1, p2, null, null); // case 2s: |CLA|INS|P1 |P2 |LE | len = 5 } else if (apdu.length == 5) { return card.transmit(cla, ins, p1, p2, null, apdu[4] & 0xff); } Integer le = null; int lc = apdu[4] & 0xff; if (lc > 0) { // case 3s: |CLA|INS|P1 |P2 |LC |...BODY...| len = 6..260 if (apdu.length == 5 + lc) { le = null; // case 4s: |CLA|INS|P1 |P2 |LC |...BODY...|LE | len = 7..261 } else if (apdu.length == 6 + lc) { le = Integer.valueOf(apdu[apdu.length - 1] & 0xff); // error } else { throw new SmartcardException(String.format( "Invalid APDU with single byte lc, lc=%d, expected apdu.length of lc + (5 or 6), got %d, apdu: %s", lc, apdu.length, Hex.b2s(apdu))); } byte[] data = new byte[lc]; System.arraycopy(apdu, 5, data, 0, data.length); return card.transmit(cla, ins, p1, p2, data, le); } // case 2e: |CLA|INS|P1 |P2 |00 |LE1|LE2| len = 7 lc = (apdu[5] & 0xff) << 8 | (apdu[6] & 0xff); if (apdu.length == 7) { return card.transmit(cla, ins, p1, p2, null, lc); // case 3e: |CLA|INS|P1 |P2 |00 |LC1|LC2|...BODY...| len = 8..65542 } else if (apdu.length == lc + 8) { le = null; // case 4e: |CLA|INS|P1 |P2 |00 |LC1|LC2|...BODY...|LE1|LE2| len =10..65544 } else if (apdu.length == lc + 10) { le = (apdu[apdu.length - 2] & 0xff) << 8 | (apdu[apdu.length - 1] & 0xff); // error } else { throw new SmartcardException(String.format( "Invalid APDU with double byte lc, lc=%d, expected apdu.length of lc + (8 or 10), got %d, apdu: %s", lc, apdu.length, Hex.b2s(apdu))); } byte[] data = new byte[lc]; java.lang.System.arraycopy(apdu, 7, data, 0, data.length); return card.transmit(cla, ins, p1, p2, data, le); } }
package com.sciul.cloud_configurator.dsl; import com.sciul.cloud_configurator.Provider; import javax.json.JsonObject; public class Route extends Resource { private final String destinationCidrBlock; private final String routeTableId; private final String idType; private final String idValue; private final boolean dependsOn; private final String dependOnId; public Route(String name, String routeTableId, String gatewayId, String instanceId, ResourceList resourceList) { this.resourceList = resourceList; setName(name); destinationCidrBlock = "0.0.0.0/0"; String vpcGatewayAttachmentId = resourceList.getName() + "-VPC-GW"; this.routeTableId = routeTableId; if (gatewayId != null) { idType = "GatewayId"; idValue = gatewayId; dependsOn = true; dependOnId = vpcGatewayAttachmentId; } else { dependsOn = false; dependOnId = null; idType = "InstanceId"; idValue = instanceId; } } @Override public JsonObject toJson(Provider provider) { return provider.createRoute(this); } @Override public Route tag(String name, String value) { tags.put(name, value); return this; } public String getDestinationCidrBlock() { return destinationCidrBlock; } public String getRouteTableId() { return routeTableId; } public String getIdType() { return idType; } public String getIdValue() { return idValue; } public boolean isDependsOn() { return dependsOn; } public String getDependOnId() { return dependOnId; } }
package com.tkhoon.framework; public interface FrameworkConstant { String DEFAULT_CHARSET = "UTF-8"; String APP_HOME_PAGE = "app.home_page"; String APP_JSP_PATH = "app.jsp_path"; String APP_WWW_PATH = "app.www_path"; String DEFAULT_SERVLET_NAME = "default"; String JSP_SERVLET_NAME = "jsp"; String UPLOAD_SERVLET_NAME = "upload"; String FAVICON_ICO_URL = "/favicon.ico"; String UPLOAD_SERVLET_URL = "/upload.do"; String UPLOAD_BASE_PATH = "upload/"; String UPLOAD_PATH_NAME = "path"; String UPLOAD_INPUT_NAME = "file"; String UPLOAD_FILE_NAME = "file_name"; String UPLOAD_FILE_TYPE = "file_type"; String UPLOAD_FILE_SIZE = "file_size"; String PLUGIN_PACKAGE = "com.tkhoon.plugin"; }
package com.uwetrottmann.trakt5.enums; /** * By default, all methods will return minimal info for movies, shows, episodes, and users. Minimal info is typically * all you need to match locally cached items and includes the title, year, and ids. However, you can request different * extended levels of information. */ public enum Extended implements TraktEnum { /** Complete info for an item. */ FULL("full"), /** Only works with sync watchedShows. */ NOSEASONS("noseasons"), /** Only works with seasons/summary */ EPISODES("episodes"), /** Only works with seasons/summary */ FULLEPISODES("full,episodes"); private final String value; Extended(String value) { this.value = value; } @Override public String toString() { return value; } }
package crazypants.enderio.conduit.gas; import mekanism.api.gas.GasStack; import mekanism.api.gas.IGasHandler; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; import cpw.mods.fml.common.ModAPIManager; import cpw.mods.fml.common.Optional.Method; import crazypants.enderio.conduit.IConduitBundle; import crazypants.enderio.config.Config; import crazypants.util.BlockCoord; public final class GasUtil { private static boolean useCheckPerformed = false; private static boolean isGasConduitEnabled = false; public static boolean isGasConduitEnabled() { if(!useCheckPerformed) { if(Config.isGasConduitEnabled) { isGasConduitEnabled = ModAPIManager.INSTANCE.hasAPI("MekanismAPI|gas"); } else { isGasConduitEnabled = false; } useCheckPerformed = true; } return isGasConduitEnabled; } @Method(modid = "MekanismAPI|gas") public static IGasHandler getExternalGasHandler(IBlockAccess world, BlockCoord bc) { IGasHandler con = getGasHandler(world, bc); return (con != null && !(con instanceof IConduitBundle)) ? con : null; } @Method(modid = "MekanismAPI|gas") public static IGasHandler getGasHandler(IBlockAccess world, BlockCoord bc) { return getGasHandler(world, bc.x, bc.y, bc.z); } @Method(modid = "MekanismAPI|gas") public static IGasHandler getGasHandler(IBlockAccess world, int x, int y, int z) { TileEntity te = world.getTileEntity(x, y, z); return getGasHandler(te); } @Method(modid = "MekanismAPI|gas") public static IGasHandler getGasHandler(TileEntity te) { if(te instanceof IGasHandler) { return (IGasHandler) te; } return null; } @Method(modid = "MekanismAPI|gas") public static boolean isGasValid(GasStack gas) { if(gas != null) { String name = gas.getGas().getLocalizedName(); if(name != null && !name.trim().isEmpty()) { return true; } } return false; } private GasUtil() { } }
package de.aikiit.mailversendala.csv; import com.google.common.collect.Lists; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVRecord; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.io.Reader; import java.util.List; import java.util.Locale; import java.util.Optional; public class CsvParser { private static final Logger LOG = LogManager.getLogger(CsvParser.class); private final Optional<Reader> reader; public CsvParser(Optional<Reader> csvInput) { this.reader = csvInput; } public List<Mailing> parse(Optional<String> language) throws IOException { List<Mailing> results = Lists.newArrayList(); if (!language.isPresent()) { LOG.info("Will parse for all languages, which may mean more mails being sent out."); } if (reader.isPresent() && reader.get().ready()) { Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(reader.get()); records.forEach(record -> results.add(Mailing.builder().email(record.get(Headers.EMAIL)).firstname(record.get(Headers.FIRSTNAME)).language(record.get(Headers.LANGUAGE)).surname(record.get(Headers.SURNAME)).build()) ); } Mailing mailing = Mailing.builder().email("my@mail.com").firstname("Your name").surname("Is my name").language(Locale.GERMAN.getLanguage()).build(); LOG.info("Parsed mailing: {}", mailing); results.add(mailing); return results; } }
package de.csdev.ebus.command; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.csdev.ebus.command.IEBusCommandMethod.Type; import de.csdev.ebus.command.datatypes.EBusTypeException; import de.csdev.ebus.command.datatypes.IEBusComplexType; import de.csdev.ebus.command.datatypes.IEBusType; import de.csdev.ebus.command.datatypes.ext.EBusTypeBytes; import de.csdev.ebus.core.EBusConsts; import de.csdev.ebus.core.EBusDataException; import de.csdev.ebus.core.EBusReceiveStateMachine; import de.csdev.ebus.utils.EBusUtils; /** * @author Christian Sowada - Initial contribution * */ public class EBusCommandUtils { private final static Logger logger = LoggerFactory.getLogger(EBusCommandUtils.class); /** * @param data * @return * @throws EBusDataException */ public static byte[] checkRawTelegram(byte[] data) throws EBusDataException { EBusReceiveStateMachine machine = new EBusReceiveStateMachine(); // init machine machine.update(EBusConsts.SYN); for (byte b : data) { machine.update(b); } return machine.getTelegramData(); } /** * Reverse an escaped SYN or EXSCAPE back to its decoded value * * @param reversedByte The byte 0x00 or 0x01 to reverse * @return */ public static byte unescapeSymbol(byte reversedByte) { return reversedByte == (byte) 0x00 ? EBusConsts.ESCAPE : reversedByte == (byte) 0x01 ? EBusConsts.SYN : reversedByte; } /** * Reverse an escaped SYN or EXSCAPE back to its decoded value * * @param b The byte to escape * @return A escaped byte if required or the parameter byte as array */ public static byte[] escapeSymbol(byte b) { if (b == EBusConsts.ESCAPE) { return EBusConsts.ESCAPE_REPLACEMENT; } else if (b == EBusConsts.SYN) { return EBusConsts.SYN_REPLACEMENT; } else { return new byte[] { b }; } } /** * Build a complete telegram for master/slave, master/master and broadcasts * * @param source * @param target * @param command * @param masterData * @param slaveData * @return * @throws EBusTypeException */ public static ByteBuffer buildCompleteTelegram(byte source, byte target, byte[] command, byte[] masterData, byte[] slaveData) throws EBusTypeException { boolean isMastereMaster = EBusUtils.isMasterAddress(target); boolean isBroadcast = target == EBusConsts.BROADCAST_ADDRESS; boolean isMasterSlave = !isMastereMaster && !isBroadcast; ByteBuffer buf = ByteBuffer.allocate(50); buf.put(buildPartMasterTelegram(source, target, command, masterData)); // if used compute a complete telegram if (isMasterSlave && slaveData != null) { ByteBuffer slaveTelegramPart = buildPartSlave(slaveData); buf.put(slaveTelegramPart); buf.put(EBusConsts.ACK_OK); buf.put(EBusConsts.SYN); } if (isMastereMaster) { buf.put(EBusConsts.ACK_OK); buf.put(EBusConsts.SYN); } if (isBroadcast) { buf.put(EBusConsts.SYN); } // set limit and reset position buf.limit(buf.position()); buf.position(0); return buf; } /** * Builds an escaped master telegram part or if slaveData is used a complete telegram incl. master ACK and SYN * * @param source * @param target * @param command * @param masterData * @return * @throws EBusTypeException */ public static ByteBuffer buildPartMasterTelegram(byte source, byte target, byte[] command, byte[] masterData) throws EBusTypeException { ByteBuffer buf = ByteBuffer.allocate(50); buf.put(source); // QQ - Source buf.put(target); // ZZ - Target buf.put(command); // PB SB - Command buf.put((byte) masterData.length); // NN - Length, will be set later // add the escaped bytes for (byte b : masterData) { buf.put(escapeSymbol(b)); } // calculate crc byte crc8 = EBusUtils.crc8(buf.array(), buf.position()); buf.put(escapeSymbol(crc8)); // set limit and reset position buf.limit(buf.position()); buf.position(0); return buf; } /** * Build an escaped telegram part for a slave answer * * @param slaveData * @return * @throws EBusTypeException */ public static ByteBuffer buildPartSlave(byte[] slaveData) throws EBusTypeException { ByteBuffer buf = ByteBuffer.allocate(50); buf.put(EBusConsts.ACK_OK); // ACK // if payload available if (slaveData != null && slaveData.length > 0) { buf.put((byte) slaveData.length); // NN - Length // add the escaped bytes for (byte b : slaveData) { buf.put(escapeSymbol(b)); } // calculate crc byte crc8 = EBusUtils.crc8(buf.array(), buf.position()); // add the crc, maybe escaped buf.put(escapeSymbol(crc8)); } else { // only set len = 0 buf.put((byte) 0x00); // NN - Length } // set limit and reset position buf.limit(buf.position()); buf.position(0); return buf; } /** * @param commandMethod * @param values * @return * @throws EBusTypeException */ public static ByteBuffer composeMasterData(IEBusCommandMethod commandMethod, Map<String, Object> values) throws EBusTypeException { ByteBuffer buf = ByteBuffer.allocate(50); Map<Integer, IEBusComplexType<?>> complexTypes = new HashMap<Integer, IEBusComplexType<?>>(); if (commandMethod.getMasterTypes() != null) { for (IEBusValue entry : commandMethod.getMasterTypes()) { IEBusType<?> type = entry.getType(); byte[] b = null; // use the value from the values map if set if (values != null && values.containsKey(entry.getName())) { b = type.encode(values.get(entry.getName())); } else { if (type instanceof IEBusComplexType) { // add the complex to the list for post processing complexTypes.put(buf.position(), (IEBusComplexType<?>) type); // add placeholder b = new byte[entry.getType().getTypeLength()]; } else { b = type.encode(entry.getDefaultValue()); } } if (b == null) { throw new RuntimeException("Encoded value is null! " + type.toString()); } // buf.p buf.put(b); // len += type.getTypeLength(); } } // replace the placeholders with the complex values if (!complexTypes.isEmpty()) { int orgPos = buf.position(); buf.limit(buf.position()); for (Entry<Integer, IEBusComplexType<?>> entry : complexTypes.entrySet()) { // jump to position buf.position(entry.getKey()); // put new value buf.put(entry.getValue().encodeComplex(buf)); } buf.position(orgPos); } // reset pos to zero and set the new limit buf.limit(buf.position()); buf.position(0); return buf; } public static ByteBuffer buildMasterTelegram(IEBusCommandMethod commandMethod, Byte source, Byte target, Map<String, Object> values) throws EBusTypeException { return buildMasterTelegram(commandMethod, source, target, values, false); } /** * @param commandMethod * @param source * @param target * @param values * @param skipAddressChecks * @return * @throws EBusTypeException */ public static ByteBuffer buildMasterTelegram(IEBusCommandMethod commandMethod, Byte source, Byte target, Map<String, Object> values, boolean skipAddressChecks) throws EBusTypeException { if (source == null && commandMethod.getSourceAddress() != null) { source = commandMethod.getSourceAddress(); } if (target == null && commandMethod.getDestinationAddress() != null) { target = commandMethod.getDestinationAddress(); } if (commandMethod == null) { throw new IllegalArgumentException("Parameter command is null!"); } if (source == null) { throw new IllegalArgumentException("Parameter source is null!"); } if (target == null) { throw new IllegalArgumentException("Parameter target is null!"); } Byte targetChecked = target; if (!skipAddressChecks) { if (commandMethod.getType().equals(Type.BROADCAST)) { if (target != EBusConsts.BROADCAST_ADDRESS) { targetChecked = EBusConsts.BROADCAST_ADDRESS; logger.warn("Replace target address {} with valid broadcast address FE !", EBusUtils.toHexDumpString(target)); } } else if (commandMethod.getType().equals(Type.MASTER_MASTER)) { if (!EBusUtils.isMasterAddress(target)) { targetChecked = EBusUtils.getMasterAddress(target); logger.warn("Replace slave target address {} with valid master address {}!", EBusUtils.toHexDumpString(target), EBusUtils.toHexDumpString(targetChecked)); } } else if (commandMethod.getType().equals(Type.MASTER_SLAVE)) { if (EBusUtils.isMasterAddress(target)) { targetChecked = EBusUtils.getSlaveAddress(target); logger.warn("Replace master target address {} with valid slave address {}!", EBusUtils.toHexDumpString(target), EBusUtils.toHexDumpString(targetChecked)); } } } byte[] data = EBusUtils.toByteArray(composeMasterData(commandMethod, values)); ByteBuffer byteBuffer = buildPartMasterTelegram(source, targetChecked, commandMethod.getCommand(), data); return byteBuffer; } /** * Apply all post number operations like multiply, range check etc. * * @param decode * @param ev * @return */ private static Object applyNumberOperations(Object decode, IEBusValue ev) { if (ev instanceof EBusCommandValue) { EBusCommandValue nev = (EBusCommandValue) ev; if (decode instanceof BigDecimal) { BigDecimal multiply = (BigDecimal) decode; if (nev.getFactor() != null) { multiply = multiply.multiply(nev.getFactor()); decode = multiply; } if (nev.getMin() != null && multiply.compareTo(nev.getMin()) == -1) { logger.debug("Value {} with {} is smaller then allowed {}", new Object[] { ev.getName(), multiply, nev.getMax() }); decode = null; } if (nev.getMax() != null && multiply.compareTo(nev.getMax()) == 1) { logger.debug("Value {} with {} is larger then allowed {}", new Object[] { ev.getName(), multiply, nev.getMax() }); decode = null; } } } return decode; } /** * @param values * @param data * @param result * @param pos * @return * @throws EBusTypeException */ private static int decodeValueList(List<IEBusValue> values, byte[] data, HashMap<String, Object> result, int pos) throws EBusTypeException { if (values != null) { for (IEBusValue ev : values) { byte[] src = null; Object decode = null; // use the raw buffer up to this position, used for custom crc calculation etc. // see kw-crc type if (ev.getType() instanceof IEBusComplexType) { decode = ((IEBusComplexType<?>) ev.getType()).decodeComplex(data, pos); } else { // default encoding src = new byte[ev.getType().getTypeLength()]; System.arraycopy(data, pos - 1, src, 0, src.length); decode = ev.getType().decode(src); } // not allowed for complex types! if (ev instanceof IEBusNestedValue && src != null) { IEBusNestedValue evc = (IEBusNestedValue) ev; if (evc.hasChildren()) { for (IEBusValue child : evc.getChildren()) { Object decode2 = child.getType().decode(src); if (StringUtils.isNotEmpty(child.getName())) { decode2 = applyNumberOperations(decode2, ev); result.put(child.getName(), decode2); } } } } if (StringUtils.isNotEmpty(ev.getName())) { decode = applyNumberOperations(decode, ev); result.put(ev.getName(), decode); } pos += ev.getType().getTypeLength(); } } return pos; } /** * @param commandChannel * @param data * @return * @throws EBusTypeException */ public static Map<String, Object> decodeTelegram(IEBusCommandMethod commandChannel, byte[] data) throws EBusTypeException { HashMap<String, Object> result = new HashMap<String, Object>(); int pos = 6; if (commandChannel == null) { throw new IllegalArgumentException("Parameter command is null!"); } pos = decodeValueList(commandChannel.getMasterTypes(), data, result, pos); pos += 3; pos = decodeValueList(commandChannel.getSlaveTypes(), data, result, pos); return result; } /** * @param commandChannel * @return */ public static ByteBuffer getMasterTelegramMask(IEBusCommandMethod commandChannel) { // byte len = 0; ByteBuffer buf = ByteBuffer.allocate(50); buf.put(commandChannel.getSourceAddress() == null ? (byte) 0x00 : (byte) 0xFF); // QQ - Source buf.put(commandChannel.getDestinationAddress() == null ? (byte) 0x00 : (byte) 0xFF); // ZZ - Target buf.put(new byte[] { (byte) 0xFF, (byte) 0xFF }); // PB SB - Command buf.put((byte) 0xFF); // NN - Length if (commandChannel.getMasterTypes() != null) { for (IEBusValue entry : commandChannel.getMasterTypes()) { IEBusType<?> type = entry.getType(); if (entry.getName() == null && type instanceof EBusTypeBytes && entry.getDefaultValue() != null) { for (int i = 0; i < type.getTypeLength(); i++) { buf.put((byte) 0xFF); } } else { for (int i = 0; i < type.getTypeLength(); i++) { buf.put((byte) 0x00); } } } } buf.put((byte) 0x00); // Master CRC // set limit and reset position buf.limit(buf.position()); buf.position(0); return buf; } }
package de.domisum.lib.animulus.npc; import de.domisum.lib.animulus.AnimulusLib; import de.domisum.lib.animulus.listener.NPCInteractPacketListener; import de.domisum.lib.auxilium.util.java.annotations.APIUsage; import de.domisum.lib.auxiliumspigot.util.LocationUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.plugin.java.JavaPlugin; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class NPCManager implements Listener { // CONSTANTS private static final int MS_PER_TICK = 50; private static final int CHECK_PLAYER_DISTANCE_TICK_INTERVAL = 20; // REFERENCES private NPCInteractPacketListener npcInteractPacketListener; // STATUS private ScheduledFuture<?> updatingTask; private int updateCount; private Map<Integer, StateNPC> npcs = new ConcurrentHashMap<>(); // <entityId, npc> private List<StateNPC> npcsToRemove = new CopyOnWriteArrayList<>(); /*private List<Long> lastNPCUpdateDurations = new ArrayList<>();*/ // CONSTRUCTOR public NPCManager() { registerListener(); startUpdatingTask(); } private void registerListener() { this.npcInteractPacketListener = new NPCInteractPacketListener(); JavaPlugin instance = AnimulusLib.getInstance().getPlugin(); instance.getServer().getPluginManager().registerEvents(this, instance); } public void terminate() { if(this.npcInteractPacketListener != null) { this.npcInteractPacketListener.terminate(); this.npcInteractPacketListener = null; } stopUpdatingTask(); terminateNPCs(); } private void terminateNPCs() { for(StateNPC npc : this.npcs.values()) npc.terminate(); this.npcs.clear(); } // GETTERS @APIUsage public int getUpdateCount() { return this.updateCount; } public StateNPC getNPC(int entityId) { return this.npcs.get(entityId); } @APIUsage public StateNPC getNPC(String id) { for(StateNPC npc : this.npcs.values()) if(npc.getId().equals(id)) return npc; return null; } // CHANGERS @APIUsage public void addNPC(StateNPC npc) { // this sets the entity id, so do this first npc.initialize(); this.npcs.put(npc.getEntityId(), npc); } @APIUsage public void removeNPC(StateNPC npc) { this.npcsToRemove.add(npc); npc.terminate(); } // TICKING private void startUpdatingTask() { Runnable run = ()-> { try { update(); } catch(Exception e) { e.printStackTrace(); } }; ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1); this.updatingTask = executor.scheduleWithFixedDelay(run, 0, MS_PER_TICK, TimeUnit.MILLISECONDS); } private void stopUpdatingTask() { this.updatingTask.cancel(true); this.updatingTask = null; } private void update() { /*long startNano = System.nanoTime();*/ for(StateNPC toRemove : this.npcsToRemove) this.npcs.values().remove(toRemove); this.npcsToRemove.clear(); for(StateNPC npc : this.npcs.values()) { if((this.updateCount%CHECK_PLAYER_DISTANCE_TICK_INTERVAL) == 0) npc.updateVisibleForPlayers(); if(npc.isVisibleToSomebody() && LocationUtil.isChunkLoaded(npc.getLocation())) try { npc.update(); } catch(Exception e) { e.printStackTrace(); removeNPC(npc); } } this.updateCount++; // benchmarking /*long endNano = System.nanoTime(); long durationNano = endNano-startNano; this.lastNPCUpdateDurations.add(durationNano); if(this.lastNPCUpdateDurations.size() > 20*60) this.lastNPCUpdateDurations.remove(0);*/ } // EVENTS @EventHandler public void playerJoin(PlayerQuitEvent event) { for(StateNPC npc : this.npcs.values()) npc.updateVisibilityForPlayer(event.getPlayer()); } @EventHandler public void playerQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); for(StateNPC npc : this.npcs.values()) npc.becomeInvisibleFor(player, false); } @EventHandler public void playerRespawn(PlayerRespawnEvent event) { Player player = event.getPlayer(); // this is needed since the world is sent anew when the player respawns // delay because this event is called before the respawn and the location is not right Runnable run = ()-> { for(StateNPC npc : this.npcs.values()) { npc.becomeInvisibleFor(player, true); npc.updateVisibilityForPlayer((player)); } }; Bukkit.getScheduler().runTaskLater(AnimulusLib.getInstance().getPlugin(), run, 1); } }
package de.htw_berlin.HoboOthello.GUI; import de.htw_berlin.HoboOthello.Core.Field; import de.htw_berlin.HoboOthello.Core.Player; import sun.audio.AudioPlayer; import sun.audio.AudioStream; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ComponentListener; import java.io.InputStream; public class Gameview extends JFrame { private static final long serialVersionUID = 1L; private String blackPlayerTyp = "BLACK"; private String whitePlayerTyp = "WHITE"; private JLabel whiteScore = new JLabel(whitePlayerTyp); private JLabel blackScore = new JLabel(blackPlayerTyp); private JLabel whosTurn = new JLabel(); private JPanel scorePanel; private JPanel actionPanel; private JPanel eastPanel; private JPanel westPanel; private JPanel boardPanel; private Color backgroundColor; private JButton[][] fieldView; private JButton showHint; private JButton goHobo; private JMenuItem[] toogleMenu; private JMenu gameMenu; private JMenuItem closeGame; private JMenuItem newGame; private JMenu aboutMenu; private JMenuItem aboutItem; Font font18 = new Font("Courier new", Font.BOLD, 18); Font font14 = new Font("Courier new", Font.BOLD, 14); //Create the Stones private ImageIcon white; private ImageIcon black; private ImageIcon grey; private ImageIcon hint; private int var; private int varSmall; /* * values to scale the center panel if window size changes */ int trueWidth; int trueHeight; int newWidth; int newHeight; /** * Constructor to create the gui */ public Gameview(int boardSize) { /* * sets up the main frame of the game */ this.setTitle("HoboOthello"); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(800, 800); this.setLayout(new BorderLayout()); this.setVisible(true); this.backgroundColor = new Color(0, 150, 0); /* * MenuBar and menu components */ gameMenu = new JMenu("Datei"); closeGame = new JMenuItem("Exit"); newGame = new JMenuItem("New Game"); aboutMenu = new JMenu("About"); aboutItem = new JMenuItem("About"); gameMenu.add(newGame); gameMenu.add(closeGame); aboutMenu.add(aboutItem); toogleMenu = new JMenuItem[3]; toogleMenu[0] = newGame; toogleMenu[1] = closeGame; toogleMenu[2] = aboutItem; /* * create a board. board is the center panel. adding buttons to the board */ boardPanel = new JPanel(); boardPanel.setLayout(new GridLayout(boardSize, boardSize)); //boardPanel.setBorder(BorderFactory.createEtchedBorder()); fieldView = new JButton[boardSize][boardSize]; for (int x = 0; x < fieldView.length; x++) { for (int y = 0; y < fieldView.length; y++) { fieldView[x][y] = new JButton(); fieldView[x][y].setBackground(backgroundColor); //fieldView[x][y].setBorder(BorderFactory.createLineBorder(Color.BLACK, 1)); boardPanel.add(fieldView[x][y]).setVisible(true); //fieldView[x][y].setBorder(null); //fieldView[x][y].setBackground(null); } } /* * the action panel which holds the hint button */ actionPanel = new JPanel(); //actionPanel.setBorder(BorderFactory.createEtchedBorder()); // a frame around the panel showHint = new JButton(" Hint? "); goHobo = new JButton ("Go Hobo"); actionPanel.add(showHint); actionPanel.add(goHobo); /* * the score panel to display the actual score */ scorePanel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 2; c.gridy = 0; scorePanel.add(whiteScore, c); c.gridx = 2; c.gridy = 1; scorePanel.add(blackScore, c); whosTurn.setPreferredSize(new Dimension(220, 30)); whosTurn.setFont(font18); c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.PAGE_END; c.weighty = 1.0; c.gridwidth = 2; c.gridx = 1; c.gridy = 2; scorePanel.add(whosTurn, c); /* * filler spaces for the right and left hand side */ eastPanel = new JPanel(); westPanel = new JPanel(); /* * BorderLayout dimensions of the Center Panel * DO NOT CHANGE THIS */ actionPanel.setPreferredSize(new Dimension(0, 58)); scorePanel.setPreferredSize(new Dimension(0, 78)); westPanel.setPreferredSize(new Dimension(92, 0)); eastPanel.setPreferredSize(new Dimension(92, 0)); actionPanel.setBackground(new Color(120, 160, 160)); scorePanel.setBackground(new Color(120, 160, 160)); westPanel.setBackground(new Color(120, 160, 160)); eastPanel.setBackground(new Color(120, 160, 160)); boardPanel.setBackground(new Color(120, 160, 160)); /* * adding all elements to the main frame */ this.getContentPane().add(scorePanel, BorderLayout.NORTH); this.getContentPane().add(boardPanel, BorderLayout.CENTER); this.getContentPane().add(actionPanel, BorderLayout.SOUTH); this.getContentPane().add(eastPanel, BorderLayout.EAST); this.getContentPane().add(westPanel, BorderLayout.WEST); /* * adding the menu bar to the main frame */ this.setJMenuBar(new JMenuBar()); this.getJMenuBar().add(gameMenu); this.getJMenuBar().add(aboutMenu); /* * initialise all stones */ grey = new ImageIcon(this.getClass().getResource("greybutton.png")); white = new ImageIcon(this.getClass().getResource("whitebutton.png")); black = new ImageIcon(this.getClass().getResource("blackbutton.png")); hint = new ImageIcon(this.getClass().getResource("hint.png")); setupScaleFactors(fieldView.length); setupBlackImageIcon(var); setupGreyImageIcon(var); setUpWhiteImageIcon(var); } /** * all methods to add ActionListeners to the board */ public void addBoardListener(ActionListener listenerForFieldButton) { for (int x = 0; x < fieldView.length; x++) { for (int y = 0; y < fieldView.length; y++) { fieldView[x][y].addActionListener(listenerForFieldButton); } } } public void addMenuListener(ActionListener listenerForMenuClick) { for (int i = 0; i < toogleMenu.length; i++) { toogleMenu[i].addActionListener(listenerForMenuClick); } } public void addHintListener(ActionListener listenerForHintClick) { this.showHint.addActionListener(listenerForHintClick); } public void addSizeListener(ComponentListener listenerForReSize) { this.getContentPane().addComponentListener(listenerForReSize); } public void addHoboListener(ActionListener listenerForGoHobo) { this.goHobo.addActionListener(listenerForGoHobo); } /** * Getter for the board to check which Button was clicked * and to check the length of the board (6, 8, 10) * used in GameController -> inner Class BoardListener */ public JButton getFieldView(int x, int y) { return fieldView[x][y]; } public int getFieldViewLength() { return fieldView.length; } public JMenuItem getToogleMenu(int nbr) { return toogleMenu[nbr]; } public JButton getShowHint() { return showHint; } public JButton getGoHobo() { return goHobo; } public void displayErrorMessage(String errorMessage) { JOptionPane.showMessageDialog(this, errorMessage); } /** * update a Field in GameView * * @param field The field which should be update */ //TODO This method calls non GUI Parameters : remove from GUI public void updateBoardFields(Field field) { Color color = backgroundColor; if (field.isOccupiedByStone()) { switch (field.getStone().getColor()) { case BLACK: changeStone(1, field.getX(), field.getY()); //color = Color.BLACK; break; case WHITE: changeStone(0, field.getX(), field.getY()); //color = Color.WHITE; break; } } if (field.isPossibleMove()) { changeStone(2, field.getX(), field.getY()); //color = Color.blue; } //fieldView[field.getX()][field.getY()].setBackground(color); } public void updateBoardPlayerPoints(de.htw_berlin.HoboOthello.Core.Color color, int points) { if (color == de.htw_berlin.HoboOthello.Core.Color.BLACK) { this.blackScore.setText(this.blackPlayerTyp + " " + points); this.blackScore.setFont(font14); this.blackScore.setForeground(Color.BLACK); } else { this.whiteScore.setText(this.whitePlayerTyp + " " + points); this.whiteScore.setFont(font14); this.whiteScore.setForeground(Color.WHITE); } } /** * Show the current Player Name (White or Black) * * @param currentPlayerName String which can be Black or White */ public void updateCurrentPlayer(String currentPlayerName) { // TODO: this is an check for equality of the objectid if (currentPlayerName == "WHITE") { this.whosTurn.setText("Players turn: " + currentPlayerName); this.whosTurn.setForeground(Color.WHITE); } else //(currentPlayerName == "Black") { this.whosTurn.setText("Players turn: " + currentPlayerName); this.whosTurn.setForeground(Color.BLACK); } /* else { this.whosTurn.setText("Players turn: " + currentPlayerName); this.whosTurn.setForeground(Color.BLACK); } */ } public void setPlayerTyp(Player blackPlayer, Player whitePlayer) { switch (blackPlayer.getPlayerType()) { case DESKTOP: this.blackPlayerTyp = "HUMAN"; break; case KI_LEVEL1: this.blackPlayerTyp = "KI 1"; break; case KI_LEVEL2: this.blackPlayerTyp = "KI 2"; break; case KI_LEVEL3: this.blackPlayerTyp = "KI 3"; break; case NETWORK_SERVER: this.blackPlayerTyp = "NETWORK SERVER"; break; } switch (whitePlayer.getPlayerType()) { case DESKTOP: this.whitePlayerTyp = "HUMAN"; break; case KI_LEVEL1: this.whitePlayerTyp = "KI 1"; break; case KI_LEVEL2: this.whitePlayerTyp = "KI 2"; break; case KI_LEVEL3: this.whitePlayerTyp = "KI 3"; break; case NETWORK_CLIENT: this.whitePlayerTyp = "NETWORK CLIENT"; break; } } /** * Show the best possible move for the current player * * @param field */ public void showHint(Field field) { this.fieldView[field.getX()][field.getY()].setIcon(null); this.changeStone(3, field.getX(), field.getY()); //fieldView[field.getX()][field.getY()].setBackground(Color.MAGENTA); } /** * @param stone can be 0, 1, 2, 3 * whereas 0=white, 1=black, 2=grey, 3=hint * @param x: the row designator * @param y: the column designator */ public void changeStone(int stone, int x, int y) { if (stone == 0) { playPloppSound(); fieldView[x][y].setIcon(white); } else if (stone == 1) { playPloppSound(); fieldView[x][y].setIcon(black); } else if (stone == 2) { playPloppSound(); fieldView[x][y].setIcon(grey); } else if (stone == 3) { Image hintImage = hint.getImage(); Image newHint = hintImage.getScaledInstance(varSmall, varSmall, java.awt.Image.SCALE_SMOOTH); hint = new ImageIcon(newHint); playPloppSound(); fieldView[x][y].setIcon(hint); } } private void setupScaleFactors(int scale) { var = (int) (60 * 0.88); varSmall = (int) (60 * 0.48); switch (scale) { case 6: { var = (int) (100 * 0.88); varSmall = (int) (100 * 0.48); break; } case 8: { varSmall = (int) (75 * 0.48); var = (int) (75 * 0.88); break; } case 10: { varSmall = (int) (60 * 0.48); var = (int) (60 * 0.88); break; } default: System.out.println("Ups! Something went wrong"); break; } } private void setupGreyImageIcon(int varSmall) { Image greyImage = grey.getImage(); Image newGrey = greyImage.getScaledInstance(varSmall, varSmall, Image.SCALE_SMOOTH); grey = new ImageIcon(newGrey); } private void setupBlackImageIcon(int var) { Image blackImage = black.getImage(); Image newBlack = blackImage.getScaledInstance(var, var, Image.SCALE_SMOOTH); black = new ImageIcon(newBlack); } private void setUpWhiteImageIcon(int var) { Image whiteImage = white.getImage(); Image newWhite = whiteImage.getScaledInstance(var, var, Image.SCALE_SMOOTH); white = new ImageIcon(newWhite); } /* * adapt values width and height to changes of the size of the frame */ public void getTrueSize(int width, int height) { this.trueHeight = height; this.trueWidth = width; int frameSize; //extra variable for calculation issues if (this.trueHeight >= this.trueWidth) { frameSize = (int) ((double) this.trueWidth * 0.885); } else { frameSize = (int) ((double) this.trueHeight * 0.83); // the int value of the pixels used for the this.newWidth = (this.trueWidth - frameSize) / 2; this.newHeight = (this.trueHeight - frameSize) / 2; } } /* * to resize if the frame size is being changed */ public void reSize(){ this.getTrueSize(this.getContentPane().getWidth(), this.getContentPane().getHeight()); this.actionPanel.setPreferredSize(new Dimension(trueWidth,newHeight)); this.scorePanel.setPreferredSize(new Dimension(trueWidth,newHeight)); this.eastPanel.setPreferredSize(new Dimension(newWidth,trueHeight)); this.westPanel.setPreferredSize(new Dimension(newWidth,trueHeight)); } public void playHoboGiggle() { try { InputStream inputStream = this.getClass().getResourceAsStream("Giggle.wav"); AudioStream audioStream = new AudioStream(inputStream); AudioPlayer.player.start(audioStream); } catch (Exception e){ //...to be filled } } public void playExitSound() { try { InputStream inputStream = this.getClass().getResourceAsStream("ExitCrash.wav"); AudioStream audioStream = new AudioStream(inputStream); AudioPlayer.player.start(audioStream); } catch (Exception e){ //...to be filled } } public void playPloppSound() { try { InputStream inputStream = this.getClass().getResourceAsStream("Drop.wav"); AudioStream audioStream = new AudioStream(inputStream); AudioPlayer.player.start(audioStream); } catch (Exception e){ //...to be filled } } }
package de.tbressler.quadratum.logic; import de.tbressler.quadratum.model.GameBoard; import de.tbressler.quadratum.model.Player; import de.tbressler.quadratum.model.Square; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static java.util.Objects.requireNonNull; /** * The game logic. * * @author Tobias Bressler * @version 1.0 */ public class GameLogic { /*The game board. */ private final GameBoard gameBoard; /* The player logic of player1. */ private final IPlayerLogic playerLogic1; /* The player logic of player2. */ private final IPlayerLogic playerLogic2; /* Player of player logic 1. */ private final Player player1; /* Player of player logic 2. */ private final Player player2; /* The squares. */ private Set<Square> squares = new HashSet<>(); /* The active player. */ private Player activePlayer; /* Is true if the game was started, otherwise false. */ private boolean isStarted = false; /* The listeners. */ private List<IGameLogicListener> listeners = new ArrayList<>(); /** * Creates the game logic. * * @param gameBoard The game board, must not be null. * @param playerLogic1 The logic for player 1, must not be null. * @param playerLogic2 The logic for player 2, must not be null. */ public GameLogic(GameBoard gameBoard, IPlayerLogic playerLogic1, IPlayerLogic playerLogic2) { this.gameBoard = requireNonNull(gameBoard); this.playerLogic1 = requireNonNull(playerLogic1); this.playerLogic2 = requireNonNull(playerLogic2); this.player1 = requireNonNull(playerLogic1.getPlayer()); this.player2 = requireNonNull(playerLogic2.getPlayer()); checkPlayers(gameBoard, player1, player2); } /* Checks if players of player logic and game board are corrent. */ private void checkPlayers(GameBoard gameBoard, Player player1, Player player2) { if (player1.equals(player2)) throw new AssertionError("playerLogic1 and playerLogic2 uses the same player!"); if ((!player1.equals(gameBoard.getPlayer1())) || (!player2.equals(gameBoard.getPlayer2()))) throw new AssertionError("Players of logic and game board doesn't match!"); } /** * Starts the game. Clears the game board if a game was started before. * * @param player The active player, who can do the first turn. Must not be null. */ public void startGame(Player player) { checkStartGamePrecondition(player); gameBoard.clear(); squares.clear(); isStarted = true; setActivePlayerTo(player); fireOnGameStarted(player); } /* Checks if the active player is valid. */ private void checkStartGamePrecondition(Player activePlayer) { if (!(requireNonNull(activePlayer).equals(player1) || requireNonNull(activePlayer).equals(player2))) throw new AssertionError("Player is unknown at the game board!"); } /* Notifies the game board listeners that the game has started. */ private void fireOnGameStarted(Player activePlayer) { for (IGameLogicListener listener : listeners) listener.onGameStarted(activePlayer); } /* Changes the active player to the given player. */ private void setActivePlayerTo(Player player) { this.activePlayer = player; fireOnActivePlayerChanged(player); } /* Notifies all listeners that the active player has changed. */ private void fireOnActivePlayerChanged(Player player) { for (IGameLogicListener listener: listeners) listener.onActivePlayerChanged(player); } /** * Returns the active player or null if the game has not started yet. * * @return The active player or null. */ public Player getActivePlayer() { return activePlayer; } /** * Returns true if the game was started, otherwise the method returns false. * * @return true if the game was started, otherwise false. */ public boolean isStarted() { return isStarted; } /** * Returns the game board. * * @return The game board, never null. */ public GameBoard getGameBoard() { return gameBoard; } /** * Returns all found squares of the current game. * * @return A set of squares or an empty set. */ public Set<Square> getSquares() { return squares; } /** * Adds a listener to the game logic. * * @param listener the listener, must not be null. */ public void addGameLogicListener(IGameLogicListener listener) { listeners.add(requireNonNull(listener)); } /** * Removes a listener from the game logic. * * @param listener the listener, must not be null. */ public void removeGameLogicListener(IGameLogicListener listener) { listeners.remove(requireNonNull(listener)); } }
package edu.hm.hafner.analysis; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; /** * Computes old, new, and fixed issues based on the reports of two consecutive static analysis runs for the same * software artifact. * * @author Ullrich Hafner */ public class IssueDifference { private final Report newIssues; private final Report fixedIssues; private final Report outstandingIssues; private final Map<Integer, List<Issue>> referencesByHash; private final Map<String, List<Issue>> referencesByFingerprint; /** * Creates a new instance of {@link IssueDifference}. * * @param currentIssues * the issues of the current report * @param referenceId * ID identifying the reference report * @param referenceIssues * the issues of a previous report (reference) */ public IssueDifference(final Report currentIssues, final String referenceId, final Report referenceIssues) { newIssues = currentIssues.copy(); fixedIssues = referenceIssues.copy(); outstandingIssues = new Report(); referencesByHash = new HashMap(); referencesByFingerprint = new HashMap(); for (Issue issue : fixedIssues) { addIssueToMap(referencesByHash, issue.hashCode(), issue); addIssueToMap(referencesByFingerprint, issue.getFingerprint(), issue); } List<UUID> removed = matchIssuesByEquals(currentIssues); Report secondPass = currentIssues.copy(); removed.forEach(secondPass::remove); matchIssuesByFingerprint(secondPass); newIssues.forEach(issue -> issue.setReference(referenceId)); } private List<UUID> matchIssuesByEquals(final Report currentIssues) { List<UUID> removedIds = new ArrayList<>(); for (Issue current : currentIssues) { List<Issue> equalIssues = findReferenceByEquals(current); if (!equalIssues.isEmpty()) { removedIds.add(remove(current, selectIssueWithSameFingerprint(current, equalIssues))); } } return removedIds; } private void matchIssuesByFingerprint(final Report currentIssues) { for (Issue current : currentIssues) { findReferenceByFingerprint(current).ifPresent(issue -> remove(current, issue)); } } private <K> void addIssueToMap(final Map<K, List<Issue>> map, final K key, final Issue issue) { List<Issue> issues = map.get(key); if (issues == null) { issues = new ArrayList(); map.put(key, issues); } issues.add(issue); } private <K> void removeIssueFromMap(final Map<K, List<Issue>> map, final K key, final Issue issue) { List<Issue> issues = map.get(key); issues.remove(issue); if (issues.isEmpty()) { map.remove(key); } } private UUID remove(final Issue current, final Issue oldIssue) { UUID id = current.getId(); Issue issueWithLatestProperties = newIssues.remove(id); issueWithLatestProperties.setReference(oldIssue.getReference()); outstandingIssues.add(issueWithLatestProperties); fixedIssues.remove(oldIssue.getId()); removeIssueFromMap(referencesByFingerprint, oldIssue.getFingerprint(), oldIssue); removeIssueFromMap(referencesByHash, oldIssue.hashCode(), oldIssue); return id; } private Issue selectIssueWithSameFingerprint(final Issue current, final List<Issue> equalIssues) { return equalIssues.stream() .filter(issue -> issue.getFingerprint().equals(current.getFingerprint())) .findFirst() .orElse(equalIssues.get(0)); } private Optional<Issue> findReferenceByFingerprint(final Issue current) { List<Issue> references = referencesByFingerprint.get(current.getFingerprint()); if (references != null) { return Optional.of(references.get(0)); } return Optional.empty(); } private List<Issue> findReferenceByEquals(final Issue current) { List<Issue> references = referencesByHash.get(current.hashCode()); List<Issue> equalIssues = new ArrayList<>(); if (references != null) { for (Issue reference : references) { if (current.equals(reference)) { equalIssues.add(reference); } } } return equalIssues; } /** * Returns the outstanding issues. I.e. all issues, that are part of the previous report and that are still part of * the current report. * * @return the outstanding issues */ public Report getOutstandingIssues() { return outstandingIssues; } /** * Returns the new issues. I.e. all issues, that are part of the current report but that have not been shown up in * the previous report. * * @return the new issues */ public Report getNewIssues() { return newIssues; } /** * Returns the fixed issues. I.e. all issues, that are part of the previous report but that are not present in the * current report anymore. * * @return the fixed issues */ public Report getFixedIssues() { return fixedIssues; } }
package hudson.plugins.ec2.ssh; import hudson.FilePath; import hudson.Util; import hudson.ProxyConfiguration; import hudson.model.Descriptor; import hudson.model.TaskListener; import hudson.plugins.ec2.*; import hudson.remoting.Channel; import hudson.remoting.Channel.Listener; import hudson.slaves.CommandLauncher; import hudson.slaves.ComputerLauncher; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.net.InetSocketAddress; import java.net.Proxy; import java.nio.charset.StandardCharsets; import java.util.logging.Level; import java.util.logging.Logger; import jenkins.model.Jenkins; import org.apache.commons.io.IOUtils; import com.amazonaws.AmazonClientException; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.KeyPair; import com.trilead.ssh2.Connection; import com.trilead.ssh2.HTTPProxyData; import com.trilead.ssh2.SCPClient; import com.trilead.ssh2.ServerHostKeyVerifier; import com.trilead.ssh2.Session; /** * {@link ComputerLauncher} that connects to a Unix slave on EC2 by using SSH. * * @author Kohsuke Kawaguchi */ public class EC2UnixLauncher extends EC2ComputerLauncher { private static final Logger LOGGER = Logger.getLogger(EC2UnixLauncher.class.getName()); private static final String BOOTSTRAP_AUTH_SLEEP_MS = "jenkins.ec2.bootstrapAuthSleepMs"; private static final String BOOTSTRAP_AUTH_TRIES= "jenkins.ec2.bootstrapAuthTries"; private static final String READINESS_SLEEP_MS = "jenkins.ec2.readinessSleepMs"; private static final String READINESS_TRIES= "jenkins.ec2.readinessTries"; private static int bootstrapAuthSleepMs = 30000; private static int bootstrapAuthTries = 30; private static int readinessSleepMs = 1000; private static int readinessTries = 120; static { String prop = System.getProperty(BOOTSTRAP_AUTH_SLEEP_MS); if (prop != null) bootstrapAuthSleepMs = Integer.parseInt(prop); prop = System.getProperty(BOOTSTRAP_AUTH_TRIES); if (prop != null) bootstrapAuthTries = Integer.parseInt(prop); prop = System.getProperty(READINESS_TRIES); if (prop != null) readinessTries = Integer.parseInt(prop); prop = System.getProperty(READINESS_SLEEP_MS); if (prop != null) readinessSleepMs = Integer.parseInt(prop); } private final int FAILED = -1; protected void log(Level level, EC2Computer computer, TaskListener listener, String message) { EC2Cloud cloud = computer.getCloud(); if (cloud != null) cloud.log(LOGGER, level, listener, message); } protected void logException(EC2Computer computer, TaskListener listener, String message, Throwable exception) { EC2Cloud cloud = computer.getCloud(); if (cloud != null) cloud.log(LOGGER, Level.WARNING, listener, message, exception); } protected void logInfo(EC2Computer computer, TaskListener listener, String message) { log(Level.INFO, computer, listener, message); } protected void logWarning(EC2Computer computer, TaskListener listener, String message) { log(Level.WARNING, computer, listener, message); } protected String buildUpCommand(EC2Computer computer, String command) { String remoteAdmin = computer.getRemoteAdmin(); if (remoteAdmin != null && !remoteAdmin.equals("root")) { command = computer.getRootCommandPrefix() + " " + command; } return command; } @Override protected void launchScript(EC2Computer computer, TaskListener listener) throws IOException, AmazonClientException, InterruptedException { final Connection conn; Connection cleanupConn = null; // java's code path analysis for final // doesn't work that well. boolean successful = false; PrintStream logger = listener.getLogger(); EC2AbstractSlave node = computer.getNode(); if(node == null) { throw new IllegalStateException(); } if (node instanceof EC2Readiness) { EC2Readiness readinessNode = (EC2Readiness) node; int tries = readinessTries; while (tries if (readinessNode.isReady()) { break; } logInfo(computer, listener, "Node still not ready. Current status: " + readinessNode.getEc2ReadinessStatus()); Thread.sleep(readinessSleepMs); } if (!readinessNode.isReady()) { throw new AmazonClientException("Node still not ready, timed out after " + (readinessTries * readinessSleepMs / 1000) + "s with status " + readinessNode.getEc2ReadinessStatus()); } } logInfo(computer, listener, "Launching instance: " + node.getInstanceId()); try { boolean isBootstrapped = bootstrap(computer, listener); if (isBootstrapped) { // connect fresh as ROOT logInfo(computer, listener, "connect fresh as root"); cleanupConn = connectToSsh(computer, listener); KeyPair key = computer.getCloud().getKeyPair(); if (!cleanupConn.authenticateWithPublicKey(computer.getRemoteAdmin(), key.getKeyMaterial().toCharArray(), "")) { logWarning(computer, listener, "Authentication failed"); return; // failed to connect as root. } } else { logWarning(computer, listener, "bootstrapresult failed"); return; // bootstrap closed for us. } conn = cleanupConn; SCPClient scp = conn.createSCPClient(); String initScript = node.initScript; String tmpDir = (Util.fixEmptyAndTrim(node.tmpDir) != null ? node.tmpDir : "/tmp"); logInfo(computer, listener, "Creating tmp directory (" + tmpDir + ") if it does not exist"); conn.exec("mkdir -p " + tmpDir, logger); if (initScript != null && initScript.trim().length() > 0 && conn.exec("test -e ~/.hudson-run-init", logger) != 0) { logInfo(computer, listener, "Executing init script"); scp.put(initScript.getBytes("UTF-8"), "init.sh", tmpDir, "0700"); Session sess = conn.openSession(); sess.requestDumbPTY(); // so that the remote side bundles stdout // and stderr sess.execCommand(buildUpCommand(computer, tmpDir + "/init.sh")); sess.getStdin().close(); // nothing to write here sess.getStderr().close(); // we are not supposed to get anything // from stderr IOUtils.copy(sess.getStdout(), logger); int exitStatus = waitCompletion(sess); if (exitStatus != 0) { logWarning(computer, listener, "init script failed: exit code=" + exitStatus); return; } sess.close(); logInfo(computer, listener, "Creating ~/.hudson-run-init"); // Needs a tty to run sudo. sess = conn.openSession(); sess.requestDumbPTY(); // so that the remote side bundles stdout // and stderr sess.execCommand(buildUpCommand(computer, "touch ~/.hudson-run-init")); sess.getStdin().close(); // nothing to write here sess.getStderr().close(); // we are not supposed to get anything // from stderr IOUtils.copy(sess.getStdout(), logger); exitStatus = waitCompletion(sess); if (exitStatus != 0) { logWarning(computer, listener, "init script failed: exit code=" + exitStatus); return; } sess.close(); } // TODO: parse the version number. maven-enforcer-plugin might help executeRemote(computer, conn, "java -fullversion", "sudo yum install -y java-1.8.0-openjdk.x86_64", logger, listener); executeRemote(computer, conn, "which scp", "sudo yum install -y openssh-clients", logger, listener); // Always copy so we get the most recent slave.jar logInfo(computer, listener, "Copying remoting.jar to: " + tmpDir); scp.put(Jenkins.get().getJnlpJars("remoting.jar").readFully(), "remoting.jar", tmpDir); final String jvmopts = node.jvmopts; final String prefix = computer.getSlaveCommandPrefix(); final String suffix = computer.getSlaveCommandSuffix(); final String remoteFS = node.getRemoteFS(); String launchString = prefix + " java " + (jvmopts != null ? jvmopts : "") + " -jar " + tmpDir + "/remoting.jar -workDir " + remoteFS + suffix; // launchString = launchString.trim(); SlaveTemplate slaveTemplate = computer.getSlaveTemplate(); if (slaveTemplate != null && slaveTemplate.isConnectBySSHProcess()) { File identityKeyFile = createIdentityKeyFile(computer); try { // Obviously the master must have an installed ssh client. String sshClientLaunchString = String.format("ssh -o StrictHostKeyChecking=no -i %s %s@%s -p %d %s", identityKeyFile.getAbsolutePath(), node.remoteAdmin, getEC2HostAddress(computer), node.getSshPort(), launchString); logInfo(computer, listener, "Launching remoting agent (via SSH client process): " + sshClientLaunchString); CommandLauncher commandLauncher = new CommandLauncher(sshClientLaunchString, null); commandLauncher.launch(computer, listener); } finally { if(!identityKeyFile.delete()) { LOGGER.log(Level.WARNING, "Failed to delete identity key file"); } } } else { logInfo(computer, listener, "Launching remoting agent (via Trilead SSH2 Connection): " + launchString); final Session sess = conn.openSession(); sess.execCommand(launchString); computer.setChannel(sess.getStdout(), sess.getStdin(), logger, new Listener() { @Override public void onClosed(Channel channel, IOException cause) { sess.close(); conn.close(); } }); } successful = true; } finally { if (cleanupConn != null && !successful) cleanupConn.close(); } } private boolean executeRemote(EC2Computer computer, Connection conn, String checkCommand, String command, PrintStream logger, TaskListener listener) throws IOException, InterruptedException { logInfo(computer, listener,"Verifying: " + checkCommand); if (conn.exec(checkCommand, logger) != 0) { logInfo(computer, listener, "Installing: " + command); if (conn.exec(command, logger) != 0) { logWarning(computer, listener, "Failed to install: " + command); return false; } } return true; } private File createIdentityKeyFile(EC2Computer computer) throws IOException { String privateKey = computer.getCloud().getPrivateKey().getPrivateKey(); File tempFile = File.createTempFile("ec2_", ".pem"); try { FileOutputStream fileOutputStream = new FileOutputStream(tempFile); OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8); try { writer.write(privateKey); writer.flush(); } finally { writer.close(); fileOutputStream.close(); } FilePath filePath = new FilePath(tempFile); filePath.chmod(0400); // octal file mask - readonly by owner return tempFile; } catch (Exception e) { if (!tempFile.delete()) { LOGGER.log(Level.WARNING, "Failed to delete identity key file"); } throw new IOException("Error creating temporary identity key file for connecting to EC2 agent.", e); } } private boolean bootstrap(EC2Computer computer, TaskListener listener) throws IOException, InterruptedException, AmazonClientException { logInfo(computer, listener, "bootstrap()"); Connection bootstrapConn = null; try { int tries = bootstrapAuthTries; boolean isAuthenticated = false; logInfo(computer, listener, "Getting keypair..."); KeyPair key = computer.getCloud().getKeyPair(); logInfo(computer, listener, "Using key: " + key.getKeyName() + "\n" + key.getKeyFingerprint() + "\n" + key.getKeyMaterial().substring(0, 160)); while (tries logInfo(computer, listener, "Authenticating as " + computer.getRemoteAdmin()); try { bootstrapConn = connectToSsh(computer, listener); isAuthenticated = bootstrapConn.authenticateWithPublicKey(computer.getRemoteAdmin(), key.getKeyMaterial().toCharArray(), ""); } catch(IOException e) { logException(computer, listener, "Exception trying to authenticate", e); bootstrapConn.close(); } if (isAuthenticated) { break; } logWarning(computer, listener, "Authentication failed. Trying again..."); Thread.sleep(bootstrapAuthSleepMs); } if (!isAuthenticated) { logWarning(computer, listener, "Authentication failed"); return false; } } finally { if (bootstrapConn != null) { bootstrapConn.close(); } } return true; } private Connection connectToSsh(EC2Computer computer, TaskListener listener) throws AmazonClientException, InterruptedException { final EC2AbstractSlave node = computer.getNode(); final long timeout = node == null ? 0L : node.getLaunchTimeoutInMillis(); final long startTime = System.currentTimeMillis(); while (true) { try { long waitTime = System.currentTimeMillis() - startTime; if (timeout > 0 && waitTime > timeout) { throw new AmazonClientException("Timed out after " + (waitTime / 1000) + " seconds of waiting for ssh to become available. (maximum timeout configured is " + (timeout / 1000) + ")"); } String host = getEC2HostAddress(computer); if ((node instanceof EC2SpotSlave) && computer.getInstanceId() == null) { // getInstanceId() on EC2SpotSlave can return null if the spot request doesn't yet know // the instance id that it is starting. Continue to wait until the instanceId is set. logInfo(computer, listener, "empty instanceId for Spot Slave."); throw new IOException("goto sleep"); } if ("0.0.0.0".equals(host)) { logWarning(computer, listener, "Invalid host 0.0.0.0, your host is most likely waiting for an ip address."); throw new IOException("goto sleep"); } int port = computer.getSshPort(); Integer slaveConnectTimeout = Integer.getInteger("jenkins.ec2.slaveConnectTimeout", 10000); logInfo(computer, listener, "Connecting to " + host + " on port " + port + ", with timeout " + slaveConnectTimeout + "."); Connection conn = new Connection(host, port); ProxyConfiguration proxyConfig = Jenkins.get().proxy; Proxy proxy = proxyConfig == null ? Proxy.NO_PROXY : proxyConfig.createProxy(host); if (!proxy.equals(Proxy.NO_PROXY) && proxy.address() instanceof InetSocketAddress) { InetSocketAddress address = (InetSocketAddress) proxy.address(); HTTPProxyData proxyData = null; if (null != proxyConfig.getUserName()) { proxyData = new HTTPProxyData(address.getHostName(), address.getPort(), proxyConfig.getUserName(), proxyConfig.getPassword()); } else { proxyData = new HTTPProxyData(address.getHostName(), address.getPort()); } conn.setProxyData(proxyData); logInfo(computer, listener, "Using HTTP Proxy Configuration"); } // currently OpenSolaris offers no way of verifying the host // certificate, so just accept it blindly, // hoping that no man-in-the-middle attack is going on. conn.connect(new ServerHostKeyVerifier() { public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception { return true; } }, slaveConnectTimeout, slaveConnectTimeout); logInfo(computer, listener, "Connected via SSH."); return conn; // successfully connected } catch (IOException e) { // keep retrying until SSH comes up logInfo(computer, listener, "Failed to connect via ssh: " + e.getMessage()); logInfo(computer, listener, "Waiting for SSH to come up. Sleeping 5."); Thread.sleep(5000); } } } private String getEC2HostAddress(EC2Computer computer) throws InterruptedException { Instance instance = computer.updateInstanceDescription(); ConnectionStrategy strategy = computer.getSlaveTemplate().connectionStrategy; return EC2HostAddressProvider.unix(instance, strategy); } private int waitCompletion(Session session) throws InterruptedException { // I noticed that the exit status delivery often gets delayed. Wait up // to 1 sec. for (int i = 0; i < 10; i++) { Integer r = session.getExitStatus(); if (r != null) return r; Thread.sleep(100); } return -1; } @Override public Descriptor<ComputerLauncher> getDescriptor() { throw new UnsupportedOperationException(); } }
package info.faceland.strife.util; import org.bukkit.Material; import org.bukkit.entity.Item; import org.bukkit.inventory.ItemStack; public class ItemTypeUtil { public static boolean isArmor(Material material) { String name = material.name(); return name.contains("HELMET") || name.contains("CHESTPLATE") || name.contains("LEGGINGS") || name.contains("BOOTS"); } public static boolean isMeleeWeapon(Material material) { String name = material.name(); return name.endsWith("SWORD") || name.endsWith("AXE") || name.endsWith("HOE"); } public static boolean isWand(ItemStack is) { if (is.getType() != Material.WOOD_SWORD) { return false; } if (!is.hasItemMeta()) { return false; } if (is.getItemMeta().getLore().get(1) == null) { return false; } return is.getItemMeta().getLore().get(1).endsWith("Wand"); } public static boolean isValidMageOffhand(ItemStack stack) { if (stack.getType() == Material.BOOK || stack.getType() == Material.SHIELD || stack.getType() == Material.POTATO_ITEM) { return true; } return false; } public static double getDualWieldEfficiency(ItemStack mainHandItemStack, ItemStack offHandItemStack) { if (mainHandItemStack == null || mainHandItemStack.getType() == Material.AIR) { return 1.0; } if (isWand(mainHandItemStack)) { return isValidMageOffhand(offHandItemStack) ? 1D : 0D; } if (isMeleeWeapon(mainHandItemStack.getType())) { if (offHandItemStack.getType() == Material.POTATO || offHandItemStack.getType() == Material.SHIELD) { return 1D; } if (isMeleeWeapon(offHandItemStack.getType()) || offHandItemStack.getType() == Material.BOW) { return 0.3D; } return 0D; } if (mainHandItemStack.getType() == Material.BOW) { return offHandItemStack.getType() == Material.ARROW ? 1D : 0D; } return 0D; } }
package info.tehnut.xtones.block; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import net.minecraft.block.Block; import net.minecraft.block.BlockDirectional; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.state.BlockFaceShape; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.Constants.BlockFlags; import java.util.Random; public final class FlatLampBlock extends BlockDirectional { private static final ImmutableMap<EnumFacing, AxisAlignedBB> SHAPES = Maps.immutableEnumMap(ImmutableMap.<EnumFacing, AxisAlignedBB>builder() .put(EnumFacing.UP, new AxisAlignedBB(0.0, 0.0, 0.0, 1.0, 0.1875, 1.0)) .put(EnumFacing.DOWN, new AxisAlignedBB(0.0, 0.8125, 0.0, 1.0, 1.0, 1.0)) .put(EnumFacing.NORTH, new AxisAlignedBB(0.0, 0.0, 0.8125, 1.0, 1.0, 1.0)) .put(EnumFacing.EAST, new AxisAlignedBB(0.0, 0.0, 0.0, 0.1875, 1.0, 1.0)) .put(EnumFacing.SOUTH, new AxisAlignedBB(0.0, 0.0, 0.0, 1.0, 1.0, 0.1875)) .put(EnumFacing.WEST, new AxisAlignedBB(0.8125, 0.0, 0.0, 1.0, 1.0, 1.0)) .build()); private static final IProperty<Boolean> ACTIVE = PropertyBool.create("active"); public FlatLampBlock() { super(Material.GLASS); this.setLightOpacity(0); this.setDefaultState(this.getDefaultState() .withProperty(ACTIVE, false) .withProperty(FACING, EnumFacing.UP)); } @Override @Deprecated public int getLightValue(final IBlockState state) { return state.getValue(ACTIVE) ? 15 : 0; } @Override @Deprecated public BlockFaceShape getBlockFaceShape(final IBlockAccess access, final IBlockState state, final BlockPos pos, final EnumFacing facing) { return state.getValue(FACING) == facing.getOpposite() ? BlockFaceShape.SOLID : BlockFaceShape.UNDEFINED; } @Override @Deprecated public AxisAlignedBB getBoundingBox(final IBlockState state, final IBlockAccess source, final BlockPos pos) { return SHAPES.get(state.getValue(FACING)); } @Override public void onBlockAdded(final World world, final BlockPos pos, final IBlockState state) { if (!world.isRemote) { final boolean powered = world.isBlockPowered(pos); if (state.getValue(ACTIVE) != powered) { world.setBlockState(pos, state.withProperty(ACTIVE, powered), BlockFlags.SEND_TO_CLIENTS); } } } @Override @Deprecated public void neighborChanged(final IBlockState state, final World world, final BlockPos pos, final Block blockIn, final BlockPos fromPos) { final boolean active = state.getValue(ACTIVE); final boolean powered = world.isBlockPowered(pos); if (active && !powered) { world.scheduleUpdate(pos, this, BlockFlags.NO_RERENDER); } else if (!active && powered) { world.setBlockState(pos, state.withProperty(ACTIVE, true), BlockFlags.SEND_TO_CLIENTS); } final EnumFacing facing = state.getValue(FACING); if (!world.isSideSolid(pos.offset(facing.getOpposite()), facing, false)) { this.dropBlockAsItem(world, pos, state, 0); world.setBlockToAir(pos); } } @Override public boolean doesSideBlockRendering(final IBlockState state, final IBlockAccess access, final BlockPos pos, final EnumFacing side) { final EnumFacing facing = state.getValue(FACING); if (side != facing.getOpposite()) { final IBlockState other = access.getBlockState(pos.offset(side)); return this == other.getBlock() && facing.getAxis() == other.getValue(FACING).getAxis(); } return true; } @Override public boolean canPlaceBlockOnSide(final World world, final BlockPos pos, final EnumFacing side) { final BlockPos offset = pos.offset(side.getOpposite()); return BlockFaceShape.SOLID == world.getBlockState(offset).getBlockFaceShape(world, offset, side); } @Override @Deprecated public IBlockState getStateFromMeta(final int meta) { final boolean active = meta >> 0b11 == 1; final EnumFacing facing = EnumFacing.values()[meta & 0b111]; return this.getDefaultState().withProperty(FACING, facing).withProperty(ACTIVE, active); } @Override public int getMetaFromState(final IBlockState state) { final int active = (state.getValue(ACTIVE) ? 1 : 0) << 0b11; final int facing = state.getValue(FACING).ordinal(); return facing | active; } @Override public void updateTick(final World world, final BlockPos pos, final IBlockState state, final Random rand) { if (!world.isRemote && state.getValue(ACTIVE) && !world.isBlockPowered(pos)) { world.setBlockState(pos, state.withProperty(ACTIVE, false), BlockFlags.SEND_TO_CLIENTS); } } @Override public IBlockState getStateForPlacement(final World world, final BlockPos pos, final EnumFacing facing, final float hitX, final float hitY, final float hitZ, final int meta, final EntityLivingBase placer, final EnumHand hand) { return this.getDefaultState().withProperty(FACING, facing); } @Override @Deprecated public boolean isOpaqueCube(final IBlockState state) { return false; } @Override @Deprecated public boolean isFullCube(final IBlockState state) { return false; } @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, ACTIVE, FACING); } }
package innovimax.mixthem.io; import innovimax.mixthem.interfaces.IInputLine; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Random; /** * <p>Reads lines from a character-input file.</p> * <p>This is the default implementation of IInputLine.</p> * @see IInputLine * @author Innovimax * @version 1.0 */ public class DefaultLineReader implements IInputLine { private final static int DEFAULT_RANDOM_SEED = 1789; private final Path path; private final BufferedReader reader; private final boolean first; private Random random; private boolean jump; /** * Creates a line reader. * @param input The input file to be read * @param first True is this reader is the first one for mixing * @throws IOException - If an I/O error occurs */ public DefaultLineReader(File input, boolean first) throws IOException { this.path = input.toPath(); this.reader = Files.newBufferedReader(path, StandardCharsets.UTF_8); this.first = first; this.random = new Random(DEFAULT_RANDOM_SEED); this.jump = !first; } @Override public void initSeed(int seed) { this.random = new Random(seed); } @Override public boolean hasLine() throws IOException { return this.reader.ready(); } @Override public String nextLine(ReadType type) throws IOException { String line = null; if (hasLine()) { switch (type) { case _REGULAR: line = this.reader.readLine(); break; case _ALT_SIMPLE: if (!this.jump) { line = this.reader.readLine(); } else { this.reader.readLine(); } this.jump = !this.jump; break; case _ALT_RANDOM: if (random.nextBoolean() == this.first) { line = this.reader.readLine(); } else { this.reader.readLine(); } break; } } return line; } @Override public void close() throws IOException { this.reader.close(); } }
package io.luna.game.model.mobile; import io.luna.LunaContext; import io.luna.game.model.Direction; import io.luna.game.model.Entity; import io.luna.game.model.EntityType; import io.luna.game.model.Position; import io.luna.game.model.mobile.attr.AttributeMap; import io.luna.game.model.mobile.update.UpdateFlagHolder; import io.luna.game.model.mobile.update.UpdateFlagHolder.UpdateFlag; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; public abstract class MobileEntity extends Entity { /** * An {@link AttributeMap} instance assigned to this {@code MobileEntity}. */ protected final AttributeMap attributes = new AttributeMap(); /** * An {@link UpdateFlagHolder} instance assigned to this {@code MobileEntity}. */ protected final UpdateFlagHolder updateFlags = new UpdateFlagHolder(); /** * The {@link SkillSet} for this {@code MobileEntity}. */ protected final SkillSet skills = new SkillSet(this); /** * The {@link WalkingQueue} assigned to this {@code MobileEntity}. */ private final WalkingQueue walkingQueue = new WalkingQueue(this); /** * The index of this mob in its list. */ private int index = -1; /** * The walking direction of this {@code MobileEntity}. */ private Direction walkingDirection = Direction.NONE; /** * The running direction of this {@code MobileEntity}. */ private Direction runningDirection = Direction.NONE; /** * If this {@code MobileEntity} is teleporting. */ private boolean teleporting = true; /** * The {@link Animation} to perform this cycle. */ private Animation animation; /** * The {@link Position} to face this cycle. */ private Position facePosition; /** * The chat to forcibly display this cycle. */ private String forceChat; /** * The {@link Graphic} to perform this cycle. */ private Graphic graphic; /** * The {@code MobileEntity} to interact with this cycle. */ private int interactionIndex = -1; /** * The primary {@link Hit} to display this cycle. */ private Hit primaryHit; /** * The secondary {@link Hit} to perform this cycle. */ private Hit secondaryHit; /** * Creates a new {@link MobileEntity}. * * @param context The context to be managed in. */ public MobileEntity(LunaContext context) { super(context); } /** * Clears flags specific to certain types of {@code MobileEntity}s. */ public abstract void reset(); /** * Teleports this {@code MobileEntity} to {@code position}. * * @param position The {@link Position} to teleport to. */ public final void teleport(Position position) { setPosition(position); teleporting = true; walkingQueue.clear(); } /** * Perform {@code animation} on this cycle. * * @param newAnimation The {@link Animation} to perform this cycle. */ public final void animation(Animation newAnimation) { if (animation == null || animation.getPriority().getValue() <= newAnimation.getPriority().getValue()) { animation = requireNonNull(newAnimation); updateFlags.flag(UpdateFlag.ANIMATION); } } /** * Face {@code facePosition} on this cycle. * * @param facePosition The {@link Position} to face this cycle. */ public final void face(Position facePosition) { this.facePosition = requireNonNull(facePosition); updateFlags.flag(UpdateFlag.FACE_POSITION); } /** * Force the chat message {@code forceChat} on this cycle. * * @param forceChat The chat to forcibly display this cycle. */ public final void forceChat(String forceChat) { this.forceChat = requireNonNull(forceChat); updateFlags.flag(UpdateFlag.FORCE_CHAT); } /** * Perform {@code graphic} on this cycle. * * @param graphic The {@link Graphic} to perform this cycle. */ public final void graphic(Graphic graphic) { this.graphic = requireNonNull(graphic); updateFlags.flag(UpdateFlag.GRAPHIC); } /** * Interact with {@code entity} on this cycle. * * @param entity The {@code MobileEntity} to interact with this cycle. */ public final void interact(MobileEntity entity) { this.interactionIndex = entity == null ? 65535 : entity.type() == EntityType.PLAYER ? entity.index + 32768 : entity.index; updateFlags.flag(UpdateFlag.INTERACTION); } /** * Display {@code primaryHit} on this cycle. * * @param primaryHit The primary {@link Hit} to display this cycle. */ private void primaryHit(Hit primaryHit) { this.primaryHit = requireNonNull(primaryHit); updateFlags.flag(UpdateFlag.PRIMARY_HIT); } /** * Display {@code secondaryHit} on this cycle. * * @param secondaryHit The secondary {@link Hit} to display this cycle. */ private void secondaryHit(Hit secondaryHit) { this.secondaryHit = requireNonNull(secondaryHit); updateFlags.flag(UpdateFlag.SECONDARY_HIT); } /** * @return The index of this {@link MobileEntity} in its list. */ public final int getIndex() { return index; } /** * Sets the value for {@link #index}, cannot be below {@code 1} unless the value is {@code -1}. */ public final void setIndex(int index) { if (index != -1) { checkArgument(index >= 1, "index < 1"); } this.index = index; } /** * Clears all of the various flags for this cycle. */ public final void clearFlags() { reset(); teleporting = false; animation = null; forceChat = null; facePosition = null; interactionIndex = -1; primaryHit = null; secondaryHit = null; updateFlags.clear(); } /** * Retrieves a skill from the backing {@link SkillSet}. */ public Skill skill(int id) { return skills.getSkill(id); } /** * @return The {@link AttributeMap} instance assigned to this {@code MobileEntity}. */ public final AttributeMap attrMap() { return attributes; } /** * @return The {@link UpdateFlagHolder} instance assigned to this {@code MobileEntity}. */ public final UpdateFlagHolder getUpdateFlags() { return updateFlags; } /** * @return The walking direction of this {@code MobileEntity}. */ public final Direction getWalkingDirection() { return walkingDirection; } /** * Sets the value for {@link #walkingDirection}. */ public final void setWalkingDirection(Direction walkingDirection) { this.walkingDirection = walkingDirection; } /** * @return The running direction of this {@code MobileEntity}. */ public Direction getRunningDirection() { return runningDirection; } /** * Sets the value for {@link #runningDirection}. */ public void setRunningDirection(Direction runningDirection) { this.runningDirection = runningDirection; } /** * @return {@code true} if this {@code MobileEntity} is teleporting, {@code false} otherwise. */ public final boolean isTeleporting() { return teleporting; } /** * @return The {@link Animation} to perform this cycle. */ public final Animation getAnimation() { return animation; } /** * @return The {@link Position} to face this cycle. */ public final Position getFacePosition() { return facePosition; } /** * @return The chat to forcibly display this cycle. */ public final String getForceChat() { return forceChat; } /** * @return The {@link Graphic} to perform this cycle.. */ public final Graphic getGraphic() { return graphic; } /** * @return The {@code MobileEntity} to interact with this cycle. */ public final int getInteractionIndex() { return interactionIndex; } /** * @return The primary {@link Hit} to display this cycle. */ public final Hit getPrimaryHit() { return primaryHit; } /** * @return The secondary {@link Hit} to display this cycle. */ public final Hit getSecondaryHit() { return secondaryHit; } /** * @return The {@link WalkingQueue} assigned to this {@code MobileEntity}. */ public WalkingQueue getWalkingQueue() { return walkingQueue; } /** * @return The {@link SkillSet} for this {@code MobileEntity}. */ public SkillSet getSkills() { return skills; } /** * @return The combat level of this {@code MobileEntity}. */ public int getCombatLevel() { return skills.getCombatLevel(); } }
package org.nnsoft.shs; /** * Exception thrown when an {@link HttpServer} instance fails on configuring phase. */ public final class InitException extends SHSException { private static final long serialVersionUID = -4615674360135156439L; /** * Constructs a new exception with the specified detail message * * @param messageTemplate a format string * @param args Arguments referenced by the format specifiers in the format string * @see String#format(String, Object...) */ public InitException( String messageTemplate, Object... args ) { super( messageTemplate, args ); } /** * Constructs a new exception with the specified detail message and cause. * * @param message the detail message * @param cause current exception cause */ public InitException( String message, Throwable cause ) { super( message, cause ); } }
package logbook.internal.gui; import java.awt.GraphicsConfiguration; import java.awt.Rectangle; import java.awt.Robot; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.util.List; import javax.imageio.ImageIO; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javafx.animation.Animation; import javafx.animation.Animation.Status; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener.Change; import javafx.collections.ObservableList; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.geometry.Point2D; import javafx.scene.Cursor; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckMenuItem; import javafx.scene.control.Label; import javafx.scene.control.MenuButton; import javafx.scene.control.ScrollPane; import javafx.scene.control.ToggleGroup; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.stage.Window; import javafx.stage.WindowEvent; import logbook.internal.gui.ScreenCapture.ImageData; public class CaptureController extends WindowController { @FXML private MenuButton config; @FXML private CheckMenuItem cyclic; @FXML private ToggleGroup cut; @FXML private Button capture; @FXML private Button save; @FXML private Label message; @FXML private ScrollPane imageParent; @FXML private ImageView image; private ObservableList<ImageData> images = FXCollections.observableArrayList(); private ScreenCapture sc; private Timeline timeline = new Timeline(); @FXML void initialize() { ImageIO.setUseCache(false); this.image.fitWidthProperty().bind(this.imageParent.widthProperty()); this.image.fitHeightProperty().bind(this.imageParent.heightProperty()); this.images.addListener(this::viewImage); } @FXML void cutNone(ActionEvent event) { this.sc.setCutRect(ScreenCapture.CutType.NONE.getAngle()); } @FXML void cutUnit(ActionEvent event) { this.sc.setCutRect(ScreenCapture.CutType.UNIT.getAngle()); } @FXML void cutUnitWithoutShip(ActionEvent event) { this.sc.setCutRect(ScreenCapture.CutType.UNIT_WITHOUT_SHIP.getAngle()); } @FXML void detect(ActionEvent event) { this.detectAction(); } @FXML void detectManual(ActionEvent event) { this.detectManualAction(); } @FXML void cyclic(ActionEvent event) { if (this.timeline.getStatus() == Status.RUNNING) { this.timeline.stop(); } if (this.cyclic.isSelected()) { this.capture.setText(""); } else { this.capture.setText(""); } } @FXML void capture(ActionEvent event) { if (this.cyclic.isSelected()) { if (this.timeline.getStatus() == Status.RUNNING) { this.timeline.stop(); this.capture.setText(""); } else { this.timeline.setCycleCount(Animation.INDEFINITE); this.timeline.getKeyFrames().clear(); this.timeline.getKeyFrames() .add(new KeyFrame(javafx.util.Duration.millis(100), this::captureAction)); this.timeline.play(); this.capture.setText(""); this.getWindow().addEventHandler(WindowEvent.WINDOW_HIDDEN, this::onclose); } } else { this.captureAction(event); } } @FXML void save(ActionEvent event) { try { InternalFXMLLoader.showWindow("logbook/gui/capturesave.fxml", this.getWindow(), "", controller -> { ((CaptureSaveController) controller).setItems(this.images); }, null); } catch (Exception ex) { LoggerHolder.LOG.error("", ex); } } @Override public void setWindow(Stage window) { super.setWindow(window); this.detectAction(); } private void detectAction() { try { GraphicsConfiguration gc = this.currentGraphicsConfiguration(); Robot robot = new Robot(gc.getDevice()); BufferedImage image = robot.createScreenCapture(gc.getBounds()); Rectangle relative = ScreenCapture.detectGameScreen(image, 800, 480); Rectangle screenBounds = gc.getBounds(); this.setBounds(robot, relative, screenBounds); } catch (Exception e) { LoggerHolder.LOG.error("", e); } } private Point2D start; private Point2D end; private void detectManualAction() { try { GraphicsConfiguration gcnf = this.currentGraphicsConfiguration(); Robot robot = new Robot(gcnf.getDevice()); BufferedImage bufferedImage = robot.createScreenCapture(gcnf.getBounds()); WritableImage image = SwingFXUtils.toFXImage(bufferedImage, null); Stage stage = new Stage(); Group root = new Group(); Canvas canvas = new Canvas(); canvas.widthProperty().bind(stage.widthProperty()); canvas.heightProperty().bind(stage.heightProperty()); canvas.setCursor(Cursor.CROSSHAIR); GraphicsContext gc = canvas.getGraphicsContext2D(); gc.setStroke(Color.BLACK); gc.setLineWidth(1); gc.setLineDashes(5, 5); canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, e -> { this.start = new Point2D(e.getX(), e.getY()); }); canvas.addEventFilter(MouseEvent.MOUSE_DRAGGED, e -> { gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); Point2D now = new Point2D(e.getX(), e.getY()); double x = Math.min(this.start.getX(), now.getX()) + 0.5; double y = Math.min(this.start.getY(), now.getY()) + 0.5; double w = Math.abs(this.start.getX() - now.getX()); double h = Math.abs(this.start.getY() - now.getY()); gc.strokeRect(x, y, w, h); }); canvas.addEventHandler(MouseEvent.MOUSE_RELEASED, e -> { this.end = new Point2D(e.getX(), e.getY()); if (!this.start.equals(this.end)) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.initOwner(stage); alert.setTitle(""); alert.setHeaderText(""); alert.setContentText(""); if (alert.showAndWait().orElse(null) == ButtonType.OK) { int x = (int) Math.min(this.start.getX(), this.end.getX()); int y = (int) Math.min(this.start.getY(), this.end.getY()); int w = (int) Math.abs(this.start.getX() - this.end.getX()); int h = (int) Math.abs(this.start.getY() - this.end.getY()); Rectangle tmp = getTrimSize(bufferedImage.getSubimage(x, y, w, h)); Rectangle relative = new Rectangle( (int) (x + tmp.getX()), (int) (y + tmp.getY()), (int) tmp.getWidth(), (int) tmp.getHeight()); Rectangle screenBounds = gcnf.getBounds(); this.setBounds(robot, relative, screenBounds); stage.setFullScreen(false); } } gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); }); root.getChildren().addAll(new ImageView(image), canvas); stage.setScene(new Scene(root)); stage.setTitle(""); stage.setFullScreenExitHint(" [Esc]"); stage.setFullScreen(true); stage.fullScreenProperty().addListener((ov, o, n) -> { if (!n) stage.close(); }); stage.setAlwaysOnTop(true); stage.show(); } catch (Exception e) { LoggerHolder.LOG.error("", e); } } private void captureAction(ActionEvent event) { try { if (this.sc != null) { this.sc.capture(); } } catch (Exception e) { LoggerHolder.LOG.error("", e); } } /** * * * @param event WindowEvent */ private void onclose(WindowEvent event) { this.images.clear(); this.timeline.stop(); } /** * * * @param image */ private void viewImage(Change<? extends ImageData> change) { while (change.next()) { if (change.wasAdded()) { List<? extends ImageData> images = change.getAddedSubList(); byte[] data = images.get(images.size() - 1).getImage(); this.image.setImage(new Image(new ByteArrayInputStream(data))); } } } private static final int WHITE = java.awt.Color.WHITE.getRGB(); /** * * * @param image * @return */ public static Rectangle getTrimSize(BufferedImage image) { int width = image.getWidth(); int height = image.getHeight(); int startwidth = width / 2; int startheightTop = (height / 3) * 2; int startheightButton = height / 3; int x = 0; int y = 0; int w = 0; int h = 0; for (int i = 0; i < width; i++) { if (image.getRGB(i, startheightTop) != WHITE) { x = i; break; } } for (int i = 0; i < width; i++) { if (image.getRGB(i, startheightButton) != WHITE) { x = Math.min(x, i); break; } } for (int i = 0; i < height; i++) { if (image.getRGB(startwidth, i) != WHITE) { y = i; break; } } for (int i = width - 1; i >= 0; i if (image.getRGB(i, startheightTop) != WHITE) { w = (i - x) + 1; break; } } for (int i = width - 1; i >= 0; i if (image.getRGB(i, startheightButton) != WHITE) { w = Math.max(w, (i - x) + 1); break; } } for (int i = height - 1; i >= 0; i if (image.getRGB(startwidth, i) != WHITE) { h = (i - y) + 1; break; } } if ((w == 0) || (h == 0)) { return new Rectangle(0, 0, image.getWidth(), image.getHeight()); } else { return new Rectangle(x, y, w, h); } } private void setBounds(Robot robot, Rectangle relative, Rectangle screenBounds) { if (relative != null) { Rectangle fixed = new Rectangle(relative.x + screenBounds.x, relative.y + screenBounds.y, relative.width, relative.height); String text = "(" + (int) fixed.getMinX() + "," + (int) fixed.getMinY() + ")"; this.message.setText(text); this.capture.setDisable(false); this.config.setDisable(false); this.sc = new ScreenCapture(robot, fixed); this.sc.setItems(this.images); } else { this.message.setText(""); this.capture.setDisable(true); this.config.setDisable(true); this.sc = null; } } private GraphicsConfiguration currentGraphicsConfiguration() { Window window = this.getWindow(); int x = (int) window.getX(); int y = (int) window.getY(); return ScreenCapture.detectScreenDevice(x, y); } private static class LoggerHolder { private static final Logger LOG = LogManager.getLogger(CaptureController.class); } }
package com.isawabird; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.isawabird.db.DBHandler; import com.isawabird.parse.ParseUtils; import com.isawabird.parse.extra.SyncUtils; public class BirdListActivity extends Activity { private EditText mNewListNameText; private TextView mNewListCancelButton; private TextView mNewListSaveButton; private TextView mListInfo; private View mNewListView; private ListView mBirdListView; private ListAdapter mListAdapter; private ViewGroup currRow; private ViewGroup defaultRow; private ImageView activeImageView; private ImageView currentImageView; private int deleteBirdListPosition; private int checkedBirdListPosition; private InputMethodManager keyboardManager; private DBHandler dh; private enum LIST_ACTION { ADD_LIST, RENAME_LIST }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mylists); dh = DBHandler.getInstance(getApplicationContext()); mBirdListView = (ListView) findViewById(R.id.mylistView); mNewListSaveButton = (TextView) findViewById(R.id.btn_new_list_save); mNewListCancelButton = (TextView) findViewById(R.id.btn_new_list_cancel); mNewListNameText = (EditText) findViewById(R.id.editText_new_list_name); mNewListView = (View) findViewById(R.id.layout_new_list); mListInfo = (TextView) findViewById(R.id.mylistview_info); mListInfo.setTypeface(Utils.getOpenSansLightTypeface(BirdListActivity.this)); keyboardManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); mNewListCancelButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { keyboardManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); mNewListNameText.setText(""); mNewListView.setVisibility(View.GONE); } }); mNewListSaveButton.setTag(R.string.key_list_type, LIST_ACTION.ADD_LIST); // TODO: Read more fields from user to create a new list mNewListSaveButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { keyboardManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); String listName = mNewListNameText.getText().toString(); if (listName.isEmpty()) { Toast.makeText(BirdListActivity.this, "Name cannot be empty", Toast.LENGTH_SHORT).show(); return; } LIST_ACTION type = (LIST_ACTION) mNewListSaveButton.getTag(R.string.key_list_type); Log.e(Consts.TAG, "saving + " + type); BirdList list; if (LIST_ACTION.RENAME_LIST.equals(type)) { int position = (Integer) mNewListSaveButton.getTag(R.string.key_list_position); list = mListAdapter.birdLists.get(position); list.setListName(listName); new UpdateBirdListAsyncTask().execute(list); } else { list = new BirdList(listName); new AddBirdListAsyncTask().execute(list); } } }); mListAdapter = new ListAdapter(this, null); mBirdListView.setAdapter(mListAdapter); mBirdListView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Bundle b = new Bundle(); b.putString("listName", mListAdapter.birdLists.get(position).getListName()); Intent mySightingIntent = new Intent(getApplicationContext(), SightingsActivity.class); mySightingIntent.putExtras(b); startActivity(mySightingIntent); } }); registerForContextMenu(mBirdListView); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.list_context_menu, menu); } DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: if (deleteBirdListPosition == -1) return; new DeleteListAsyncTask().execute(deleteBirdListPosition); break; case DialogInterface.BUTTON_NEGATIVE: deleteBirdListPosition = -1; break; } } }; @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case R.id.action_delete_list: deleteBirdListPosition = info.position; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener) .show(); return true; case R.id.action_rename_list: mNewListSaveButton.setTag(R.string.key_list_type, LIST_ACTION.RENAME_LIST); mNewListSaveButton.setTag(R.string.key_list_position, info.position); mNewListNameText.setText(mListAdapter.birdLists.get(info.position).getListName()); if (mNewListNameText.requestFocus()) { keyboardManager.showSoftInput(mNewListNameText, 0); } mNewListView.setVisibility(View.VISIBLE); return true; case R.id.action_set_default: BirdList list = mListAdapter.birdLists.get(info.position); Utils.setCurrentList(list.getListName(), list.getId()); currRow = (ViewGroup) mBirdListView.getChildAt(info.position); defaultRow = (ViewGroup) mBirdListView.getChildAt(checkedBirdListPosition); ; activeImageView = (ImageView) defaultRow.getChildAt(1); currentImageView = (ImageView) currRow.getChildAt(1); activeImageView.setVisibility(View.INVISIBLE); currentImageView.setVisibility(View.VISIBLE); checkedBirdListPosition = info.position; return true; default: return super.onContextItemSelected(item); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.list_activity_actions, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_add_list: mNewListSaveButton.setTag(R.string.key_list_type, LIST_ACTION.ADD_LIST); // show 'add new list' view mNewListView.setVisibility(View.VISIBLE); if (mNewListNameText.requestFocus()) { keyboardManager.showSoftInput(mNewListNameText, 0); } return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onResume() { super.onResume(); new QueryBirdListAsyncTask().execute(); } public class ListAdapter extends ArrayAdapter<BirdList> { private TextView mListNameText; private TextView mCountForEachList; private ImageView mActiveImage; public ArrayList<BirdList> birdLists; public ListAdapter(Context context, ArrayList<BirdList> birdLists) { super(context, R.layout.mylists_row, birdLists); this.birdLists = birdLists; } @Override public int getCount() { if (birdLists == null) return 0; return birdLists.size(); } @Override public View getView(final int position, View convertView, ViewGroup parent) { View rowView = convertView; if (rowView == null) { LayoutInflater inflater = getLayoutInflater(); rowView = inflater.inflate(R.layout.mylists_row, parent, false); } mListNameText = (TextView) rowView.findViewById(R.id.mylistsItem_name); mListNameText.setTypeface(Utils.getOpenSansLightTypeface(BirdListActivity.this)); mCountForEachList = (TextView) rowView.findViewById(R.id.mylistsItem_count); mCountForEachList.setTypeface(Utils.getOpenSansLightTypeface(BirdListActivity.this)); mActiveImage = (ImageView) rowView.findViewById(R.id.mylistItem_image); String listName = birdLists.get(position).getListName(); mListNameText.setText(listName); try { mCountForEachList.setText("" + dh.getBirdCountByListId(dh.getListIDByName(listName))); } catch (ISawABirdException e) { e.printStackTrace(); Log.i(Consts.TAG, "No list with " + listName + " found."); Log.i(Consts.TAG, e.getMessage()); } if (birdLists.get(position).getId() == Utils.getCurrentListID()) { checkedBirdListPosition = position; mActiveImage.setVisibility(View.VISIBLE); } else { mActiveImage.setVisibility(View.INVISIBLE); } return rowView; } } private class AddBirdListAsyncTask extends AsyncTask<BirdList, String, BirdList> { @Override protected BirdList doInBackground(BirdList... params) { if (params == null || params.length == 0) return null; long result = -1; try { result = DBHandler.getInstance(getApplicationContext()).addBirdList(params[0], true); } catch (ISawABirdException e) { e.printStackTrace(); if (e.getErrorCode() == ISawABirdException.ERR_LIST_ALREADY_EXISTS) { publishProgress("List already exists. Specify a different name"); } } if (result == -1) return null; params[0].setId(result); return params[0]; } @Override protected void onProgressUpdate(String... values) { Toast.makeText(getApplicationContext(), values[0], Toast.LENGTH_SHORT).show(); } @Override protected void onPostExecute(BirdList result) { if (result != null) { Toast.makeText(getBaseContext(), "Added new list :: " + mNewListNameText.getText(), Toast.LENGTH_SHORT).show(); mNewListNameText.setText(""); mNewListView.setVisibility(View.GONE); if (mListAdapter.birdLists == null) { mListAdapter.birdLists = new ArrayList<BirdList>(); } mListAdapter.birdLists.add(0, result); mListAdapter.notifyDataSetChanged(); } } } private class UpdateBirdListAsyncTask extends AsyncTask<BirdList, String, BirdList> { @Override protected BirdList doInBackground(BirdList... params) { if (params == null || params.length == 0) return null; DBHandler dh = DBHandler.getInstance(getApplicationContext()); BirdList list = dh.getBirdListByName(params[0].getListName()); if (list != null) { publishProgress("List already exists. Specify a different name"); return null; } dh.updateBirdList(params[0].getId(), params[0]); return params[0]; } @Override protected void onProgressUpdate(String... values) { Toast.makeText(getApplicationContext(), values[0], Toast.LENGTH_SHORT).show(); } @Override protected void onPostExecute(BirdList result) { if (result != null) { mNewListNameText.setText(""); mNewListView.setVisibility(View.GONE); LIST_ACTION type = (LIST_ACTION) mNewListSaveButton.getTag(R.string.key_list_type); if (LIST_ACTION.RENAME_LIST.equals(type)) { int position = (Integer) mNewListSaveButton.getTag(R.string.key_list_position); mListAdapter.birdLists.get(position).setListName(result.getListName()); } else { if (mListAdapter.birdLists == null) { mListAdapter.birdLists = new ArrayList<BirdList>(); } mListAdapter.birdLists.add(0, result); } mListAdapter.notifyDataSetChanged(); } } } private class QueryBirdListAsyncTask extends AsyncTask<Void, Void, ArrayList<BirdList>> { protected ArrayList<BirdList> doInBackground(Void... params) { DBHandler dh = DBHandler.getInstance(getApplicationContext()); dh = DBHandler.getInstance(getApplicationContext()); return dh.getBirdLists(ParseUtils.getCurrentUsername()); } protected void onPostExecute(ArrayList<BirdList> result) { if (result == null || result.size() == 0) { return; } Log.i(Consts.TAG, "List count: " + result.size()); mListAdapter.birdLists = result; mListAdapter.notifyDataSetChanged(); } } private class DeleteListAsyncTask extends AsyncTask<Integer, String, Integer> { protected Integer doInBackground(Integer... params) { if (params[0] == -1) return -1; BirdList list = mListAdapter.birdLists.get(params[0]); if (list == null) return -1; DBHandler dh = DBHandler.getInstance(getApplicationContext()); dh.deleteList(list.getId()); return params[0]; } @Override protected void onPostExecute(Integer position) { int pos = position; if (position != -1) { mListAdapter.birdLists.remove(pos); if (checkedBirdListPosition == position && mListAdapter.birdLists.size() > 0) { BirdList list = mListAdapter.birdLists.get(0); Utils.setCurrentList(list.getListName(), list.getId()); } mListAdapter.notifyDataSetChanged(); deleteBirdListPosition = -1; SyncUtils.triggerRefresh(); } if (mListAdapter.birdLists.size() == 0) { DBHandler dh = DBHandler.getInstance(getApplicationContext()); try { if (Utils.getCurrentListID() == -1) { // create one based on todays date BirdList list = new BirdList(new SimpleDateFormat("dd MMM yyyy").format(new Date())); long result = dh.addBirdList(list, true); list.setId(result); Utils.setCurrentList(list.getListName(), list.getId()); mListAdapter.birdLists.add(0, list); mListAdapter.notifyDataSetChanged(); SyncUtils.triggerRefresh(); } } catch (ISawABirdException e) { Log.e(Consts.TAG, e.getMessage()); } } } } }
package me.zero.client.api.util.render; import net.minecraft.client.renderer.GlStateManager; import org.lwjgl.BufferUtils; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import static org.lwjgl.opengl.GL11.*; public class GlUtils { /** * Credits to Halalaboos */ public static int applyTexture(int texId, File file, int filter, int wrap) throws IOException { applyTexture(texId, ImageIO.read(file), filter, wrap); return texId; } /** * Credits to Halalaboos */ public static int applyTexture(int texId, BufferedImage image, int filter, int wrap) { int[] pixels = new int[image.getWidth() * image.getHeight()]; image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth()); ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4); for (int y = 0; y < image.getHeight(); y++) { for (int x = 0; x < image.getWidth(); x++) { int pixel = pixels[y * image.getWidth() + x]; buffer.put((byte) ((pixel >> 16) & 0xFF)); buffer.put((byte) ((pixel >> 8) & 0xFF)); buffer.put((byte) (pixel & 0xFF)); buffer.put((byte) ((pixel >> 24) & 0xFF)); } } buffer.flip(); applyTexture(texId, image.getWidth(), image.getHeight(), buffer, filter, wrap); return texId; } /** * Credits to Halalaboos */ public static int applyTexture(int texId, int width, int height, ByteBuffer pixels, int filter, int wrap) { glBindTexture(GL_TEXTURE_2D, texId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); glBindTexture(GL_TEXTURE_2D, 0); return texId; } /** * Sets the color from a hex value * * @since 1.0 * * @param hex The hex value */ public static void glColor(int hex) { float[] color = getColor(hex); GlStateManager.color(color[0], color[1], color[2], color[3]); } /** * Parses the RGBA values from a hex value * * @since 1.0 * * @param hex The hex value * @return The parsed RGBA array */ public static float[] getColor(int hex) { return new float[] { (hex >> 16 & 255) / 255F, (hex >> 8 & 255) / 255F, (hex & 255) / 255F, (hex >> 24 & 255) / 255F }; } /** * Parses the hex value from RGB/RGBA values * * @since 1.0 * * @param color The RGB/RGBA array * @return The parsed hex value */ public static int getColor(float[] color) { int r = (int) (color[0] * 255F); int g = (int) (color[1] * 255F); int b = (int) (color[2] * 255F); int a = color.length == 4 ? (int) (color[3] * 255F) : 255; return ((a & 0xFF) << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF); } /** * Rotates on the X axis at the X, Y, and Z * coordinates that are provided. * * @since 1.0 * * @param angle The amount being rotated * @param x The x position being rotated on * @param y The y position being rotated on * @param z The z position being rotated on */ public static void rotateX(float angle, double x, double y, double z) { glTranslated(x, y, z); glRotated(angle, 1, 0, 0); glTranslated(-x, -y, -z); } /** * Rotates on the Y axis at the X, Y, and Z * coordinates that are provided. * * @since 1.0 * * @param angle The amount being rotated * @param x The x position being rotated on * @param y The y position being rotated on * @param z The z position being rotated on */ public static void rotateY(float angle, double x, double y, double z) { glTranslated(x, y, z); glRotated(angle, 0, 1, 0); glTranslated(-x, -y, -z); } /** * Rotates on the Z axis at the X, Y, and Z * coordinates that are provided. * * @since 1.0 * * @param angle The amount being rotated * @param x The x position being rotated on * @param y The y position being rotated on * @param z The z position being rotated on */ public static void rotateZ(float angle, double x, double y, double z) { glTranslated(x, y, z); glRotated(angle, 0, 0, 1); glTranslated(-x, -y, -z); } /** * Gets the Model View Matrix as a FloatBuffer * * @since 1.0 * * @return The Model View Matrix */ public static FloatBuffer getModelViewMatrix() { FloatBuffer modelview = BufferUtils.createFloatBuffer(16); glGetFloat(GL_MODELVIEW_MATRIX, modelview); return modelview; } /** * Gets the Projection Matrix as a FloatBuffer * * @since 1.0 * * @return The Projection Matrix */ public static FloatBuffer getProjectionMatrix() { FloatBuffer projection = BufferUtils.createFloatBuffer(16); glGetFloat(GL_PROJECTION_MATRIX, projection); return projection; } /** * Gets the Render Viewport as an IntegerBuffer * * @since 1.0 * * @return The Viewport */ public static IntBuffer getViewport() { IntBuffer viewport = BufferUtils.createIntBuffer(16); glGetInteger(GL_VIEWPORT, viewport); return viewport; } }
package com.parrot.arsdk.arsal; /** * Root class for all C data that may pass through different libs of AR.SDK<br> * <br> * AR.SDK Is mainly implemented in C, and thus libs often use C structures to hold data.<br> * This is a wrapper class onto these kind of data, so java can pass them around libs without copy into JVM memory space. */ public class ARNativeData { /* DEFAULT VALUES */ /** * Tag for ARSALPrint prints */ private static final String TAG = ARNativeData.class.getSimpleName(); /** * Default size for native data */ public static final int DEFAULT_SIZE = 128; /* INTERNAL REPRESENTATION */ /** * Storage of the C Pointer */ protected long pointer; /** * Storage of the allocated size of the C Pointer */ protected int capacity; /** * How many bytes are used in the buffer */ protected int used; /** * Check validity before all native calls */ protected boolean valid; /** * Dummy throwable to keep the constructors call stack */ private Throwable constructorCallStack; /* CONSTRUCTORS */ /** * Generic constructor<br> * This constructor allocate a <code>ARNativeData</code> with the given capacity * @param size Initial capacity of the <code>ARNativeData</code> */ public ARNativeData (int size) { this.pointer = allocateData (size); this.capacity = 0; this.valid = false; if (this.pointer != 0) { this.capacity = size; this.valid = true; } this.used = 0; this.constructorCallStack = new Throwable(); } /** * Default size constructor * This constructor allocate a <code>ARNativeData</code> with the default capacity */ public ARNativeData () { this (DEFAULT_SIZE); } /** * Copy constructor<br> * This constructor creates a new <code>ARNativeData</code> with a capacity<br> * equal to the original objects data size * @param data The original <code>ARNativeData</code> to copy */ public ARNativeData (ARNativeData data) { this (data.getDataSize ()); if (! copyData (pointer, capacity, data.getData (), data.getDataSize ())) { dispose (); } } /** * Copy constructor, with specified allocation size<br> * This constructor creates a new <code>ARNativeData</code> with a capacity<br> * equal to the greatest value between the specified <code>capacity</code> and the original<br> * object data size * @param data The original <code>ARNativeData</code> to copy * @param capacity The minimum capacity in bytes for this <code>ARNativeData</code> */ public ARNativeData (ARNativeData data, int capacity) { int totalSize = data.getDataSize (); if (capacity > totalSize) { totalSize = capacity; } this.pointer = allocateData (totalSize); this.capacity = 0; this.valid = false; if (this.pointer != 0) { this.capacity = totalSize; this.valid = true; } this.used = 0; this.constructorCallStack = new Throwable(); if (! copyData (this.pointer, this.capacity, data.getData (), data.getDataSize ())) { dispose (); } } /* DESTRUCTOR */ protected void finalize () throws Throwable { try { if (valid) { ARSALPrint.w (TAG, this + ": Finalize error -> dispose () was not called !", this.constructorCallStack); dispose (); } } finally { super.finalize (); } } /* TO STRING */ /** * Gets a <code>String</code> representation of the <code>ARNativeData</code> * @return A human-readable description of the <code>ARNativeData</code> */ public String toString () { return "" + this.getClass().getSimpleName() + " { Valid : " + valid + " | " + "Used/Capacity (bytes) : " + used + "/" + capacity + " | " + "C Pointer : " + pointer + " }"; } /* IMPLEMENTATION */ /** * Checks the object validity * @return <code>true</code> if the object is valid (buffer properly alloc and usable)<br><code>false</code> if the object is invalid (alloc error, disposed object) */ public boolean isValid () { return valid; } /** * Sets the used size of the <code>ARNativeData</code> * @param size New used size of the command * @return <code>true</code> if the size was set<br><code>false</code> if the size was invalid (bigger than capacity) or if the <code>ARNativeData</code> is invalid */ public boolean setUsedSize (int size) { if ((! valid) || (size > capacity)) return false; this.used = size; return true; } /** * Gets the capacity of the <code>ARNativeData</code><br> * This function returns 0 (no capacity) if the data is not valid * @return Capacity of the native data buffer */ public int getCapacity () { if (valid) return capacity; return 0; } /** * Gets the C data pointer (equivalent C type : uint8_t *)<br> * This function returns 0 (C-NULL) if the data is not valid (i.e. disposed or uninitialized) * @return Native data pointer */ public long getData () { if (valid) return pointer; return 0; } /** * Get the C data size (in bytes)<br> * This function returns 0 (no data) if the data is not valid * @return Size of the native data */ public int getDataSize () { if (valid) return used; return 0; } /** * Gets a byte array which is a copy of the C native data<br> * This function allow Java code to access (but not modify) the content of the <code>ARNativeData</code><br> * This function creates a new byte [], and thus should not be called in a loop * @return A Java copy of the native data (byte equivalent) */ public byte [] getByteData () { if (valid) return generateByteArray (pointer, capacity, used); return null; } /** * Marks a native data as unused (so C-allocated memory can be freed)<br> * A disposed data is marked as invalid */ public void dispose () { if (valid) freeData (pointer); this.valid = false; this.pointer = 0; this.capacity = 0; this.used = 0; } /** * Ensures the capacity is at least the minimum capacity set. * @warning if the capacity is least of minimumCapacity, the buffer will try to be re-allocated * @param minimumCapacity minimum capacity to ensure * @return <code>true</code> if the capacity is at least minimumCapacity <br><code>false</code> if the reallocation of the buffer with at least the minimum capacity has failed * */ public boolean ensureCapacityIsAtLeast (int minimumCapacity) { boolean retVal = false; long newPointer = 0; if (this.capacity >= minimumCapacity) { retVal = true; } else { newPointer = reallocateData (this.pointer, minimumCapacity); if (newPointer != 0) { this.capacity = minimumCapacity; this.pointer = newPointer; retVal = true; } /* else retVal = false */ } return retVal; } /* NATIVE FUNCTIONS */ /** * Memory allocation in native memory space<br> * Allocates a memory buffer of size <code>capacity</code> and return its C-Pointer * @param capacity Size, in bytes, of the buffer to allocate * @return C-Pointer on the buffer, or 0 (C-NULL) if the alloc failed */ private native long allocateData (int capacity); /** * Memory reallocation in native memory space<br> * Reallocates a memory buffer of size <code>capacity</code> and return its C-Pointer * @param pointer native pointer to reallocate * @param capacity Size, in bytes, of the new buffer to reallocated * @return C-Pointer on the new buffer, or 0 (C-NULL) if the realloc failed */ private native long reallocateData (long pointer, int capacity); /** * Memory release in native memory space<br> * Frees a memory buffer from its C-Pointer<br> * This call is needed because JVM do not know about native memory allocs * @param data C-Pointer on the buffer to free */ private native void freeData (long data); /** * Copy data to a byte array<br> * This function is needed to implement the <code>getByteData</code> function * @param data C-Pointer to the internal buffer * @param capacity Capacity of the internal buffer (avoid overflows) * @param used Used bytes in the internal buffer (size to copy) * @return A byte array, which content is the byte-equal copy of the native buffer */ private native byte [] generateByteArray (long data, int capacity, int used); /** * Copy data from another <code>ARNativeData</code><br> * This function is used in the copy constructors. * @param dst C-Pointer on this object's internal buffer * @param dstCapacity Capacity of this object's internal buffer * @param src C-Pointer on the initial object's internal buffer * @param srcLen Used bytes in the initial object's internal buffer * @return <code>true</code> if the copy was done without error<br><code>false</code> if an error occured. In this case, the content of the internal buffer is undefined, so <code>used</code> should be set to zero */ private native boolean copyData (long dst, int dstCapacity, long src, int srcLen); }
package net.fortuna.ical4j.vcard; import net.fortuna.ical4j.vcard.Group.Id; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class GroupRegistry { private static final Log LOG = LogFactory.getLog(GroupRegistry.class); private final Map<Id, Group> defaultGroups; private final Map<String, Group> extendedGroups; public GroupRegistry() { defaultGroups = new HashMap<Id, Group>(); defaultGroups.put(Id.HOME, Group.HOME); defaultGroups.put(Id.WORK, Group.WORK); extendedGroups = new ConcurrentHashMap<String, Group>(); } /** * @param value a string representation of a group identifier * @return a registered group with the specified identifier. If no such group * is found null is returned */ public Group getGroup(final String value) { Id id = null; try { id = Id.valueOf(value); } catch (final Exception ignored) { } if (id != null) { return defaultGroups.get(id); } return extendedGroups.get(value); } /** * Registers a non-standard group. * @param extendedName the extended name of the group * @param group the group */ public void register(final String extendedName, final Group group) { extendedGroups.put(extendedName, group); } }
/* Author : Michael Aldridge Class : CS2336 Section: 001 Assignment: 5 Instructions: Compile with javac inToPost.java; run as java inToPost; This implementation will make an attempt to calculate all expressions that are calculable. Expressions containing variable components will not be calculated. Multi-digit integer input is accepted. */ import java.util.Scanner; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; public class inToPost { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); String infixInput = ""; System.out.print("Please input a valid infix expression: "); infixInput = kbd.next(); eqMan expressionManager = new eqMan(); //tokenize the input Queue<QType> infix = expressionManager.tokenize(infixInput); //shunt through the yard to create postfix Queue<QType> postfix = expressionManager.shunt(infix); System.out.println("Infix expression: " + infixInput); System.out.println("Postfix expression: " + expressionManager.getPostFix(postfix)); if(expressionManager.hasVar(postfix)) { System.out.println("This expression has variable terms, evaluation not possible."); } else { System.out.println("This expression is solvable, answer is: " + expressionManager.calculate(postfix)); } } } class eqMan { public boolean hasVar(Queue<QType> exp) { Queue<QType> temp = new LinkedList<QType>(exp); QType current; while(!temp.isEmpty()) { current = temp.poll(); if(current.type == QType.Type.VARIABLE) { return true; } } return false; //no variables, safe to evaluate } public String getPostFix(Queue<QType> exp) { Queue<QType> rpn = new LinkedList<QType>(exp); StringBuilder out = new StringBuilder(); while(!rpn.isEmpty()) { QType token = rpn.poll(); switch(token.type) { case OPERAND: out.append(token.value); break; case VARIABLE: out.append(token.var); break; case OPERATOR: char c = '|'; switch(token.op) { case ADD: c='+'; break; case SUB: c='-'; break; case MUL: c='*'; break; case DIV: c='/'; break; case EXP: c='^'; break; } out.append(c); } out.append(" "); } return out.toString(); } public double calculate(Queue<QType> postfix) { Stack<Double> evalStack = new Stack<Double>(); QType token; while(!postfix.isEmpty()) { token = postfix.poll(); switch(token.type) { case OPERAND: evalStack.push((double)(token.value)); break; case OPERATOR: double a,b; a = evalStack.pop(); b = evalStack.pop(); switch(token.op) { case ADD: evalStack.push(a+b); break; case SUB: evalStack.push(b-a); break; case MUL: evalStack.push(a*b); break; case DIV: evalStack.push(b/a); break; case EXP: evalStack.push(Math.pow(b,a)); break; } } } //if everything has gone right, the answer is on evalStack return evalStack.pop(); } public int getOpPriority(QType.OP op) { switch(op) { case ADD: case SUB: return 1; case MUL: case DIV: return 2; case EXP: return 3; case LPR: case RPR: return 0; } return -1; //never should make it to here } public Queue<QType> shunt(Queue<QType> expression) { Queue<QType> rpnExpression = new LinkedList<QType>(); Stack<QType> opStack = new Stack<QType>(); while(!expression.isEmpty()) { QType currentToken = expression.poll(); switch(currentToken.type) { case OPERAND: //if it is an operand, add it to the stack rpnExpression.add(currentToken); break; case VARIABLE: //if it is a variable, it is just an operand rpnExpression.add(currentToken); break; case OPERATOR: //if it is an operator, we need to know if it is an lparen if(currentToken.op == QType.OP.LPR) { //push the paren on to the opstack and descend opStack.push(currentToken); } else if(currentToken.op == QType.OP.RPR) { //if right paren, pop all ops from the stack while(opStack.peek().op != QType.OP.LPR) { rpnExpression.add(opStack.pop()); } opStack.pop(); //get rid of the lparen sitting on the stack } else { while(!opStack.empty() && getOpPriority(currentToken.op) <= getOpPriority(opStack.peek().op)) { //if precidence is correct, pop to stack rpnExpression.add(opStack.pop()); } opStack.push(currentToken); } break; default: System.out.println("EXPRESSION NOT MATHEMATICALLY VALID"); break; } } //return any remaining operators while(!opStack.isEmpty()) { rpnExpression.add(opStack.pop()); } return rpnExpression; } public Queue<QType> tokenize(String eq) { Queue<QType> tokens = new LinkedList<QType>(); String operators = "+-*/^()"; //remove all whitespace eq = eq.replaceAll("\\s",""); for(int i=0; i<eq.length(); i++) { if(operators.contains(Character.toString(eq.charAt(i)))) { //catch operators switch(Character.toString(eq.charAt(i))) { case "+": tokens.add(toQ(QType.OP.ADD)); break; case "-": tokens.add(toQ(QType.OP.SUB)); break; case "*": tokens.add(toQ(QType.OP.MUL)); break; case "/": tokens.add(toQ(QType.OP.DIV)); break; case "^": tokens.add(toQ(QType.OP.EXP)); break; case "(": tokens.add(toQ(QType.OP.LPR)); break; case ")": tokens.add(toQ(QType.OP.RPR)); break; } } else if(Character.isDigit(eq.charAt(i))) { int j = i; int num = 0; while(Character.isDigit(eq.charAt(i))) { //get char, mul by 10 num=num*10+Character.getNumericValue(eq.charAt(i)); if(i+1<eq.length()) { if(Character.isDigit(eq.charAt(i+1))) { i++; } else { break; } } else { break; } } tokens.add(toQ(num)); } else { tokens.add(toQ(eq.charAt(i))); } } return tokens; } //convenience functions to build Tokens public QType toQ(QType.OP o) { QType temp = new QType(); temp.type = QType.Type.OPERATOR; temp.op = o; return temp; } public QType toQ(char v) { QType temp = new QType(); temp.type = QType.Type.VARIABLE; temp.var = v; return temp; } public QType toQ(int i) { QType temp = new QType(); temp.type = QType.Type.OPERAND; temp.value = i; return temp; } } class QType { public enum Type {OPERATOR, OPERAND, VARIABLE}; public enum OP {ADD, SUB, MUL, DIV, EXP, LPR, RPR}; public Type type; public int value; public char var; public OP op; public String toString() { StringBuilder out = new StringBuilder(); out.append("Type: " + type + " Value: "); switch(type) { case OPERATOR: out.append(op); break; case OPERAND: out.append(value); break; case VARIABLE: out.append(var); break; } return out.toString(); } }
package net.glowstone.block.blocktype; import java.util.Collection; import java.util.Collections; import net.glowstone.GlowWorld; import net.glowstone.block.GlowBlock; import net.glowstone.block.GlowBlockState; import net.glowstone.block.entity.BedEntity; import net.glowstone.block.entity.BlockEntity; import net.glowstone.block.entity.state.GlowBed; import net.glowstone.chunk.GlowChunk; import net.glowstone.entity.GlowPlayer; import org.bukkit.DyeColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Biome; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Creature; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.PigZombie; import org.bukkit.inventory.ItemStack; import org.bukkit.material.Bed; import org.bukkit.material.MaterialData; import org.bukkit.util.Vector; public class BlockBed extends BlockType { /** * Helper method for set whether the specified bed blocks are occupied. * * @param head head of the bed * @param foot foot of the bed * @param occupied if the bed is occupied by a player */ public static void setOccupied(GlowBlock head, GlowBlock foot, boolean occupied) { byte headData = head.getData(); byte footData = foot.getData(); head.setData((byte) (occupied ? headData | 0x4 : headData & ~0x4)); foot.setData((byte) (occupied ? footData | 0x4 : footData & ~0x4)); } /** * Return whether the specified bed block is occupied. * * @param block part of the bed * @return true if this bed is occupied, false if it is not */ public static boolean isOccupied(GlowBlock block) { return (block.getData() & 0x4) == 0x4; } /** * Returns the head of a bed given one of its blocks. * * @param block part of the bed * @return The head of the bed */ public static GlowBlock getHead(GlowBlock block) { MaterialData data = block.getState().getData(); if (!(data instanceof Bed)) { return null; } Bed bed = (Bed) data; if (bed.isHeadOfBed()) { return block; } else { return block.getRelative(bed.getFacing()); } } /** * Returns the foot of a bed given one of its blocks. * * @param block part of the bed * @return The foot of the bed */ public static GlowBlock getFoot(GlowBlock block) { MaterialData data = block.getState().getData(); if (!(data instanceof Bed)) { return null; } Bed bed = (Bed) data; if (bed.isHeadOfBed()) { return block.getRelative(bed.getFacing().getOppositeFace()); } else { return block; } } @Override public Collection<ItemStack> getDrops(GlowBlock block, ItemStack tool) { return Collections.singletonList(new ItemStack(Material.BED, 1, (((GlowBed) block.getState()).getColor().getWoolData()))); } @Override public void onNearBlockChanged(GlowBlock block, BlockFace face, GlowBlock changedBlock, Material oldType, byte oldData, Material newType, byte newData) { if (changedBlock.equals(getHead(block)) || changedBlock.equals(getFoot(block))) { if (newType == Material.AIR) { block.setType(Material.AIR); } } } /** * Returns whether a player can spawn within a block of specified material. * * @param material the material * @return Whether spawning is possible */ public static boolean isValidSpawn(Material material) { switch (material) { case AIR: case SAPLING: case POWERED_RAIL: case DETECTOR_RAIL: case LONG_GRASS: case DEAD_BUSH: case YELLOW_FLOWER: case RED_ROSE: case BROWN_MUSHROOM: case RED_MUSHROOM: case TORCH: case REDSTONE_WIRE: case CROPS: case RAILS: case LEVER: case REDSTONE_TORCH_OFF: case REDSTONE_TORCH_ON: case STONE_BUTTON: case SNOW: case SUGAR_CANE_BLOCK: case DIODE_BLOCK_OFF: case DIODE_BLOCK_ON: case VINE: case TRIPWIRE_HOOK: case TRIPWIRE: case FLOWER_POT: case WOOD_BUTTON: case SKULL: case GOLD_PLATE: case IRON_PLATE: case REDSTONE_COMPARATOR_OFF: case REDSTONE_COMPARATOR_ON: case ACTIVATOR_RAIL: case CARPET: case DOUBLE_PLANT: return true; default: return false; } } /** * Returns an 'empty' block next to the bed used to put the player at when they exit a bed or * respawn. * * @param head head of the bed * @param foot foot of the bed * @return Exit block or {@code null} if all spots are blocked */ public static Block getExitLocation(GlowBlock head, GlowBlock foot) { // First check blocks near head for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { Block b = head.getRelative(x, 0, z); boolean floorValid = b.getRelative(BlockFace.DOWN).getType().isSolid(); boolean bottomValid = isValidSpawn(b.getType()); boolean topValid = isValidSpawn(b.getRelative(BlockFace.UP).getType()); if (floorValid && bottomValid && topValid) { return b; } } } // Then check the last three blocks near foot BlockFace face = head.getFace(foot); int modX = face.getModX(); int modZ = face.getModZ(); for (int x = modX == 0 ? -1 : modX; x <= (modX == 0 ? 1 : modX); x++) { for (int z = modZ == 0 ? -1 : modZ; z <= (modZ == 0 ? 1 : modZ); z++) { Block b = foot.getRelative(x, 0, z); boolean floorValid = b.getRelative(BlockFace.DOWN).getType().isSolid(); boolean bottomValid = isValidSpawn(b.getType()); boolean topValid = isValidSpawn(b.getRelative(BlockFace.UP).getType()); if (floorValid && bottomValid && topValid) { return b; } } } return null; } @Override public void placeBlock(GlowPlayer player, GlowBlockState state, BlockFace face, ItemStack holding, Vector clickedLoc) { BlockFace direction = getOppositeBlockFace(player.getLocation(), false).getOppositeFace(); if (state.getBlock().getRelative(direction).getType() == Material.AIR && state.getBlock() .getRelative(direction).getRelative(BlockFace.DOWN).getType().isSolid()) { super.placeBlock(player, state, face, holding, clickedLoc); MaterialData data = state.getData(); if (data instanceof Bed) { ((Bed) data).setFacingDirection(direction); ((Bed) data).setHeadOfBed(false); state.setData(data); } else { warnMaterialData(Bed.class, data); } } } @Override public BlockEntity createBlockEntity(GlowChunk chunk, int cx, int cy, int cz) { return new BedEntity(chunk.getBlock(cx, cy, cz)); } @Override public void afterPlace(GlowPlayer player, GlowBlock block, ItemStack holding, GlowBlockState oldState) { if (block.getType() == Material.BED_BLOCK) { GlowBed bed = (GlowBed) block.getState(); bed.setColor(DyeColor.getByWoolData(holding.getData().getData())); bed.update(true); BlockFace direction = ((Bed) bed.getData()).getFacing(); GlowBlock headBlock = block.getRelative(direction); headBlock.setType(Material.BED_BLOCK); GlowBed headBlockState = (GlowBed) headBlock.getState(); headBlockState.setColor(DyeColor.getByWoolData(holding.getData().getData())); MaterialData data = headBlockState.getData(); ((Bed) data).setHeadOfBed(true); ((Bed) data).setFacingDirection(direction); headBlockState.setData(data); headBlockState.update(true); } } @Override public boolean blockInteract(GlowPlayer player, GlowBlock block, BlockFace face, Vector clickedLoc) { GlowWorld world = player.getWorld(); MaterialData data = block.getState().getData(); if (!(data instanceof Bed)) { warnMaterialData(Bed.class, data); return false; } block = getHead(block); // Disallow sleeping in nether and end biomes Biome biome = block.getBiome(); if (biome == Biome.HELL || biome == Biome.SKY) { // Set off an explosion at the bed slightly stronger than TNT world.createExplosion(block.getLocation(), 5F, true); return true; } // Sleeping is only possible during the night or a thunderstorm // Tick values for day/night time taken from the minecraft wiki if (world.getTime() < 12541 || world.getTime() > 23458 || world.isThundering()) { player.sendMessage("You can only sleep at night"); return true; } if (isOccupied(block)) { player.sendMessage("This bed is occupied."); return true; } if (!isWithinDistance(player, block, 3, 2, 3)) { return true; // Distance between player and bed is too great, fail silently } for (LivingEntity e : world.getLivingEntities()) { // Check for hostile mobs relative to the block below the head of the bed if (e instanceof Creature && (e.getType() != EntityType.PIG_ZOMBIE || ((PigZombie) e) .isAngry()) && isWithinDistance(e, block.getRelative(BlockFace.DOWN), 8, 5, 8)) { player.sendMessage("You may not rest now, there are monsters nearby"); return true; } } player.enterBed(block); return true; } /** * Checks whether the entity is within the specified distance from the block. * * @param entity the entity * @param block the block * @param x maximum distance on x axis * @param y maximum distance on y axis * @param z maximum distance on z axis * @return Whether the entity is within distance */ private boolean isWithinDistance(Entity entity, Block block, int x, int y, int z) { Location loc = entity.getLocation(); return Math.abs(loc.getX() - block.getX()) <= x && Math.abs(loc.getY() - block.getY()) <= y && Math.abs(loc.getZ() - block.getZ()) <= z; } }
package net.glowstone.entity.passive; import com.flowpowered.networking.Message; import net.glowstone.entity.meta.MetadataIndex; import net.glowstone.entity.meta.MetadataMap; import net.glowstone.inventory.GlowHorseInventory; import net.glowstone.net.message.play.entity.EntityMetadataMessage; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.AnimalTamer; import org.bukkit.entity.EntityType; import org.bukkit.entity.Horse; import org.bukkit.inventory.HorseInventory; import java.util.List; import java.util.Random; import java.util.UUID; public class GlowHorse extends GlowTameable implements Horse { private Variant variant = Variant.values()[new Random().nextInt(2)]; private Color horseColor = Color.values()[new Random().nextInt(6)]; private Style horseStyle = Style.values()[new Random().nextInt(3)]; private boolean hasChest; private int domestication; private int maxDomestication; private double jumpStrength; private boolean eatingHay; private boolean hasReproduced; private int temper; private UUID ownerUUID; private HorseInventory inventory = new GlowHorseInventory(this); public GlowHorse(Location location) { this(location, null); setSize(1.4F, 1.6F); } protected GlowHorse(Location location, AnimalTamer owner) { super(location, EntityType.HORSE, owner); if (owner != null) this.ownerUUID = owner.getUniqueId(); } @Override public Variant getVariant() { return this.variant; } @Override public void setVariant(Variant variant) { this.variant = variant; } @Override public Color getColor() { return horseColor; } @Override public void setColor(Color color) { this.horseColor = color; } @Override public Style getStyle() { return horseStyle; } @Override public void setStyle(Style style) { this.horseStyle = style; } @Override public boolean isCarryingChest() { return hasChest; } @Override public void setCarryingChest(boolean b) { if (b) { // TODO Manipulate the HorseInventory somehow } this.hasChest = b; } @Override public int getDomestication() { return domestication; } @Override public void setDomestication(int i) { this.domestication = i; } @Override public int getMaxDomestication() { return maxDomestication; } @Override public void setMaxDomestication(int i) { this.maxDomestication = i; } @Override public double getJumpStrength() { return jumpStrength; } @Override public void setJumpStrength(double v) { this.jumpStrength = v; } @Override public HorseInventory getInventory() { return inventory; } public void setInventory(HorseInventory inventory) { this.inventory = inventory; } public boolean isEatingHay() { return eatingHay; } public void setEatingHay(boolean eatingHay) { this.eatingHay = eatingHay; } public boolean hasReproduced() { return hasReproduced; } public void setHasReproduced(boolean hasReproduced) { this.hasReproduced = hasReproduced; } public int getTemper() { return temper; } public void setTemper(int temper) { this.temper = temper; } public UUID getOwnerUUID() { return ownerUUID; } public void setOwnerUUID(UUID ownerUUID) { this.ownerUUID = ownerUUID; } @Override public List<Message> createSpawnMessage() { List<Message> messages = super.createSpawnMessage(); MetadataMap map = new MetadataMap(GlowHorse.class); map.set(MetadataIndex.HORSE_TYPE, (byte) this.getVariant().ordinal()); map.set(MetadataIndex.HORSE_FLAGS, getHorseFlags()); map.set(MetadataIndex.HORSE_STYLE, getHorseStyleData()); map.set(MetadataIndex.HORSE_ARMOR, getHorseArmorData()); messages.add(new EntityMetadataMessage(id, map.getEntryList())); return messages; } private int getHorseFlags() { int value = 0; if (isTamed()) { value |= 0x02; } if (getInventory() != null && getInventory().getSaddle() != null) { value |= 0x04; } if (hasChest) { value |= 0x08; } if (hasReproduced) { value |= 0x10; } if (isEatingHay()) { value |= 0x20; } return value; } private int getHorseStyleData() { return this.horseColor.ordinal() & 0xFF | this.horseStyle.ordinal() << 8; } private int getHorseArmorData() { if (getInventory().getArmor() != null) { if (getInventory().getArmor().getType() == Material.DIAMOND_BARDING) { return 3; } else if (getInventory().getArmor().getType() == Material.GOLD_BARDING) { return 2; } else if (getInventory().getArmor().getType() == Material.IRON_BARDING) { return 1; } } return 0; } }
package net.gpedro.integrations.slack; import com.google.gson.JsonObject; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class SlackApi { private String service; public SlackApi(String service) { if (service == null) { throw new IllegalArgumentException( "Missing WebHook URL Configuration @ SlackApi"); } else if (!service.startsWith("https://hooks.slack.com/services/")) { throw new IllegalArgumentException( "Invalid Service URL. WebHook URL Format: https://hooks.slack.com/services/{id_1}/{id_2}/{token}"); } this.service = service; } /** * Prepare Message and send to Slack */ public void call(SlackMessage message) { if (message != null) { this.send(message.prepare()); } } private String send(JsonObject message) { HttpURLConnection connection = null; try { // Create connection final URL url = new URL(this.service); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setConnectTimeout(5000); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); final String payload = "payload=" + URLEncoder.encode(message.toString(), "UTF-8"); // Send request final DataOutputStream wr = new DataOutputStream( connection.getOutputStream()); wr.writeBytes(payload); wr.flush(); wr.close(); // Get Response final InputStream is = connection.getInputStream(); final BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); return response.toString(); } catch (Exception e) { throw new RuntimeException(e); } finally { if (connection != null) { connection.disconnect(); } } } }
package net.gtaun.wl.common.dialog; import org.apache.commons.lang3.StringUtils; public final class DialogUtils { public static String rightPad(String str, int size, int tabSize) { return str + StringUtils.repeat('\t', (size - str.length() + (tabSize-1)) / tabSize); } private DialogUtils() { } }
package net.imagej.legacy; import java.awt.GraphicsEnvironment; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import net.imagej.DatasetService; import net.imagej.display.DatasetView; import net.imagej.display.ImageDisplay; import net.imagej.display.ImageDisplayService; import net.imagej.display.OverlayService; import net.imagej.legacy.plugin.LegacyCommand; import net.imagej.legacy.plugin.LegacyPluginFinder; import net.imagej.legacy.ui.LegacyUI; import net.imagej.options.OptionsChannels; import net.imagej.patcher.LegacyEnvironment; import net.imagej.patcher.LegacyInjector; import net.imagej.threshold.ThresholdService; import net.imagej.ui.viewer.image.ImageDisplayViewer; import org.scijava.Priority; import org.scijava.app.StatusService; import org.scijava.command.Command; import org.scijava.command.CommandInfo; import org.scijava.command.CommandService; import org.scijava.display.DisplayService; import org.scijava.display.event.DisplayActivatedEvent; import org.scijava.display.event.input.KyPressedEvent; import org.scijava.display.event.input.KyReleasedEvent; import org.scijava.event.EventHandler; import org.scijava.event.EventService; import org.scijava.input.Accelerator; import org.scijava.input.KeyCode; import org.scijava.log.LogService; import org.scijava.menu.MenuService; import org.scijava.module.Module; import org.scijava.module.ModuleInfo; import org.scijava.module.ModuleService; import org.scijava.options.OptionsService; import org.scijava.options.event.OptionsEvent; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import org.scijava.plugin.PluginInfo; import org.scijava.plugin.PluginService; import org.scijava.service.AbstractService; import org.scijava.service.Service; import org.scijava.ui.ApplicationFrame; import org.scijava.ui.UIService; import org.scijava.ui.UserInterface; import org.scijava.ui.viewer.DisplayWindow; import org.scijava.util.ColorRGB; import org.scijava.welcome.event.WelcomeEvent; /** * Default service for working with legacy ImageJ 1.x. * <p> * The legacy service overrides the behavior of various legacy ImageJ methods, * inserting seams so that (e.g.) the modern UI is aware of legacy ImageJ events * as they occur. * </p> * <p> * It also maintains an image map between legacy ImageJ {@link ij.ImagePlus} * objects and modern ImageJ {@link ImageDisplay}s. * </p> * <p> * In this fashion, when a legacy command is executed on a {@link ImageDisplay}, * the service transparently translates it into an {@link ij.ImagePlus}, and vice * versa, enabling backward compatibility with legacy commands. * </p> * * @author Barry DeZonia * @author Curtis Rueden * @author Johannes Schindelin * @author Mark Hiner */ @Plugin(type = Service.class, priority = Priority.NORMAL_PRIORITY + 1) public final class DefaultLegacyService extends AbstractService implements LegacyService { static { LegacyInjector.preinit(); } @Parameter private OverlayService overlayService; @Parameter private LogService log; @Parameter private EventService eventService; @Parameter private PluginService pluginService; @Parameter private CommandService commandService; @Parameter private OptionsService optionsService; @Parameter private ImageDisplayService imageDisplayService; @Parameter private DisplayService displayService; @Parameter private ThresholdService thresholdService; @Parameter private DatasetService datasetService; @Parameter private MenuService menuService; @Parameter private ModuleService moduleService; @Parameter private StatusService statusService; private UIService uiService; private static DefaultLegacyService instance; private static Throwable instantiationStackTrace; /** Mapping between modern and legacy image data structures. */ private LegacyImageMap imageMap; /** Method of synchronizing modern & legacy options. */ private OptionsSynchronizer optionsSynchronizer; /** Keep references to ImageJ 1.x separate */ private IJ1Helper ij1Helper; public IJ1Helper getIJ1Helper() { return ij1Helper; } private ThreadLocal<Boolean> isProcessingEvents = new ThreadLocal<Boolean>(); private Set<String> legacyCompatibleCommands = new HashSet<String>(); // -- LegacyService methods -- @Override public LogService log() { return log; } @Override public StatusService status() { return statusService; } @Override public synchronized LegacyImageMap getImageMap() { if (imageMap == null) imageMap = new LegacyImageMap(this); return imageMap; } @Override public OptionsSynchronizer getOptionsSynchronizer() { return optionsSynchronizer; } @Override public void runLegacyCommand(final String ij1ClassName, final String argument) { final String arg = argument == null ? "" : argument; final Map<String, Object> inputMap = new HashMap<String, Object>(); inputMap.put("className", ij1ClassName); inputMap.put("arg", arg); commandService.run(LegacyCommand.class, true, inputMap); } public Object runLegacyCompatibleCommand(final String commandClass) { if (!legacyCompatibleCommands.contains(commandClass)) { return null; } return commandService.run(commandClass, true, new Object[0]); } @Override public void syncActiveImage() { final ImageDisplay activeDisplay = imageDisplayService.getActiveImageDisplay(); ij1Helper.syncActiveImage(activeDisplay); } @Override public boolean isInitialized() { return instance != null; } @Override public void syncColors() { final DatasetView view = imageDisplayService.getActiveDatasetView(); if (view == null) return; final OptionsChannels channels = getChannels(); final ColorRGB fgColor = view.getColor(channels.getFgValues()); final ColorRGB bgColor = view.getColor(channels.getBgValues()); optionsSynchronizer.colorOptions(fgColor, bgColor); } @Override public boolean isLegacyMode() { return ij1Helper != null && ij1Helper.isVisible(); } @Override public void toggleLegacyMode(final boolean wantIJ1) { toggleLegacyMode(wantIJ1, false); } public synchronized void toggleLegacyMode(final boolean wantIJ1, final boolean initializing) { // TODO: hide/show Brightness/Contrast, Color Picker, Command Launcher, etc if (!initializing) { if (uiService() != null) { // hide/show the IJ2 main window final UserInterface ui = uiService.getDefaultUI(); if (ui != null && ui instanceof LegacyUI) { UserInterface modern = null; for (final UserInterface ui2 : uiService.getAvailableUIs()) { if (ui2 == ui) continue; modern = ui2; break; } if (modern == null) { log.error("No modern UI available"); return; } final ApplicationFrame frame = ui.getApplicationFrame(); ApplicationFrame modernFrame = modern.getApplicationFrame(); if (!wantIJ1 && modernFrame == null) { modern.show(); modernFrame = modern.getApplicationFrame(); } if (frame == null || modernFrame == null) { log.error("Application frame missing: " + frame + " / " + modernFrame); return; } frame.setVisible(wantIJ1); modernFrame.setVisible(!wantIJ1); } else { final ApplicationFrame appFrame = ui == null ? null : ui.getApplicationFrame(); if (appFrame == null) { if (ui != null && !wantIJ1) uiService.showUI(); } else { appFrame.setVisible(!wantIJ1); } } } // TODO: move this into the LegacyImageMap's toggleLegacyMode, passing // the uiService // hide/show the IJ2 datasets corresponding to legacy ImagePlus instances for (final ImageDisplay display : getImageMap().getImageDisplays()) { final ImageDisplayViewer viewer = (ImageDisplayViewer) uiService.getDisplayViewer(display); if (viewer == null) continue; final DisplayWindow window = viewer.getWindow(); if (window != null) window.showDisplay(!wantIJ1); } } // hide/show IJ1 main window ij1Helper.setVisible(wantIJ1); if (wantIJ1 && !initializing) { optionsSynchronizer.updateLegacyImageJSettingsFromModernImageJ(); } getImageMap().toggleLegacyMode(wantIJ1); } @Override public String getLegacyVersion() { return ij1Helper.getVersion(); } // -- Service methods -- @Override public void initialize() { checkInstance(); optionsSynchronizer = new OptionsSynchronizer(optionsService); try { final ClassLoader loader = getClass().getClassLoader(); final boolean ij1Initialized = LegacyEnvironment.isImageJ1Initialized(loader); if (!ij1Initialized) { getLegacyEnvironment(loader).newImageJ1(true); } ij1Helper = new IJ1Helper(this); } catch (final Throwable t) { throw new RuntimeException("Failed to instantiate IJ1.", t); } synchronized (DefaultLegacyService.class) { checkInstance(); instance = this; instantiationStackTrace = new Throwable("Initialized here:"); LegacyInjector.installHooks(getClass().getClassLoader(), new DefaultLegacyHooks(this, ij1Helper)); } ij1Helper.initialize(); SwitchToModernMode.registerMenuItem(); addNonLegacyCommandsToMenu(); // discover legacy plugins final boolean enableBlacklist = true; addLegacyCommands(enableBlacklist); } // -- Package protected events processing methods -- /** * NB: This method is not intended for public consumption. It is really * intended to be "jar protected". It is used to toggle a {@link ThreadLocal} * flag as to whether or not legacy UI components are in the process of * handling {@code StatusEvents}. * <p> * USE AT YOUR OWN RISK! * </p> * * @return the old processing value */ public boolean setProcessingEvents(boolean processing) { boolean result = isProcessingEvents(); if (result != processing) { isProcessingEvents.set(processing); } return result; } /** * {@link ThreadLocal} check to see if components are in the middle of * processing events. * * @return True iff this thread is already processing events through the * {@code DefaultLegacyService}. */ public boolean isProcessingEvents() { Boolean result = isProcessingEvents.get(); return result == Boolean.TRUE; } // -- Disposable methods -- @Override public void dispose() { ij1Helper.dispose(); LegacyInjector.installHooks(getClass().getClassLoader(), null); synchronized(DefaultLegacyService.class) { instance = null; instantiationStackTrace = null; } } // -- Event handlers -- /** * Keeps the active legacy {@link ij.ImagePlus} in sync with the active modern * {@link ImageDisplay}. */ @EventHandler protected void onEvent(final DisplayActivatedEvent event) { syncActiveImage(); } @EventHandler protected void onEvent(final OptionsEvent event) { optionsSynchronizer.updateModernImageJSettingsFromLegacyImageJ(); } @EventHandler protected void onEvent(final KyPressedEvent event) { final KeyCode code = event.getCode(); if (code == KeyCode.SPACE) ij1Helper.setKeyDown(KeyCode.SPACE.getCode()); if (code == KeyCode.ALT) ij1Helper.setKeyDown(KeyCode.ALT.getCode()); if (code == KeyCode.SHIFT) ij1Helper.setKeyDown(KeyCode.SHIFT.getCode()); if (code == KeyCode.CONTROL) ij1Helper.setKeyDown(KeyCode.CONTROL.getCode()); if (ij1Helper.isMacintosh() && code == KeyCode.META) { ij1Helper.setKeyDown(KeyCode.CONTROL.getCode()); } } @EventHandler protected void onEvent(final KyReleasedEvent event) { final KeyCode code = event.getCode(); if (code == KeyCode.SPACE) ij1Helper.setKeyUp(KeyCode.SPACE.getCode()); if (code == KeyCode.ALT) ij1Helper.setKeyUp(KeyCode.ALT.getCode()); if (code == KeyCode.SHIFT) ij1Helper.setKeyUp(KeyCode.SHIFT.getCode()); if (code == KeyCode.CONTROL) ij1Helper.setKeyUp(KeyCode.CONTROL.getCode()); if (ij1Helper.isMacintosh() && code == KeyCode.META) { ij1Helper.setKeyUp(KeyCode.CONTROL.getCode()); } } @EventHandler protected void onEvent(final WelcomeEvent event) { commandService.run(ImageJ2Options.class, true); } // -- pre-initialization /** * Makes sure that the ImageJ 1.x classes are patched. * <p> * We absolutely require that the LegacyInjector did its job before we use the * ImageJ 1.x classes. * </p> * <p> * Just loading the {@link DefaultLegacyService} class is not enough; it will * not necessarily get initialized. So we provide this method just to force * class initialization (and thereby the LegacyInjector to patch ImageJ 1.x). * </p> * * @deprecated use {@link LegacyInjector#preinit()} instead */ public static void preinit() { try { getLegacyEnvironment(Thread.currentThread().getContextClassLoader()); } catch (Throwable t) { t.printStackTrace(); } } private static LegacyEnvironment getLegacyEnvironment(final ClassLoader loader) throws ClassNotFoundException { final boolean headless = GraphicsEnvironment.isHeadless(); final LegacyEnvironment ij1 = new LegacyEnvironment(loader, headless); ij1.disableInitializer(); ij1.noPluginClassLoader(); ij1.applyPatches(); return ij1; } // -- helpers -- /** * Returns the legacy service associated with the ImageJ 1.x instance in the * current class loader. This method is intended to be used by the * {@link CodeHacker}; it is invoked by the javassisted methods. * * @return the legacy service */ public static DefaultLegacyService getInstance() { return instance; } /** * @throws UnsupportedOperationException if the singleton * {@code DefaultLegacyService} already exists. */ private void checkInstance() { if (instance != null) { throw new UnsupportedOperationException( "Cannot instantiate more than one DefaultLegacyService", instantiationStackTrace); } } private OptionsChannels getChannels() { return optionsService.getOptions(OptionsChannels.class); } @SuppressWarnings("unused") private void updateMenus(final boolean enableBlacklist) { pluginService.reloadPlugins(); addLegacyCommands(enableBlacklist); } private void addLegacyCommands(final boolean enableBlacklist) { final LegacyPluginFinder finder = new LegacyPluginFinder(log, menuService.getMenu(), enableBlacklist); final ArrayList<PluginInfo<?>> plugins = new ArrayList<PluginInfo<?>>(); finder.findPlugins(plugins); pluginService.addPlugins(plugins); } // -- Menu population -- /** * Adds all {@link LegacyCompatibleCommand}s to the ImageJ1 menus. The * nested menu structure of each {@code LegacyCompatibleCommand} is * preserved. */ private void addNonLegacyCommandsToMenu() { List<CommandInfo> commands = commandService.getCommandsOfType(Command.class); legacyCompatibleCommands = new HashSet<String>(); for (final Iterator<CommandInfo> iter = commands.iterator(); iter.hasNext(); ) { final CommandInfo info = iter.next(); if (info.getMenuPath().size() == 0 || info.is("no-legacy")) { iter.remove(); } else { legacyCompatibleCommands.add(info.getDelegateClassName()); } } ij1Helper.addMenuItems(commands); } boolean handleShortcut(final String accelerator) { final Accelerator acc = Accelerator.create(accelerator); if (acc == null) return false; final ModuleInfo module = moduleService.getModuleForAccelerator(acc); if (module == null || module.is("no-legacy")) return false; moduleService.run(module, true); return true; } public synchronized UIService uiService() { if (uiService == null) uiService = getContext().getService(UIService.class); return uiService; } }
package net.imagej.ops.create; import net.imagej.ops.Op; import net.imagej.ops.Ops; import net.imglib2.img.planar.PlanarImgFactory; import net.imglib2.type.Type; import net.imglib2.type.numeric.real.FloatType; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; /** * Creates a default image. If outType is not passed it is set to a default of * FloatType. If fac is not passed in it is set to a default of * PlanarImgFactory. * * @author bnorthan * @param <V> */ @Plugin(type = Op.class, name = Ops.CreateImg.NAME) public class DefaultCreateImg<V extends Type<V>> extends AbstractCreateImg<V, FloatType, PlanarImgFactory<FloatType>> implements Ops.CreateImg { @Parameter private long[] dims; public void run() { createOutputImg(dims, fac, outType, new PlanarImgFactory<FloatType>(), new FloatType()); } }
package net.ucanaccess.converters; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.ucanaccess.jdbc.UcanaccessConnection; import com.healthmarketscience.jackcess.Database; public class SQLConverter { private static final Pattern QUOTE_G_PATTERN = Pattern .compile("\'(((([^'])*('')*))*)\'"); private static final Pattern DOUBLE_QUOTE_G_PATTERN = Pattern .compile("\"(((([^\"])*(\"\")*))*)\""); private static final Pattern FIND_LIKE_PATTERN = Pattern .compile("[\\s\\(]*([\\w\\.]*)([\\s\\)]*)(?i)like\\s*\\'(.*)'"); private static final Pattern ACCESS_LIKE_CHARINTERVAL_PATTERN = Pattern .compile("\\[[a-zA-Z]\\-[a-zA-Z]\\]|\\[\\![a-zA-Z]\\-[a-zA-Z]\\]"); private static final Pattern ACCESS_LIKE_ESCAPE_PATTERN = Pattern .compile("\\[[\\*|_| private static final Pattern FROM_PATTERN = Pattern .compile("\\w*(?i)from\\w*"); private static final String WA_CURRENT_USER = "(\\W)(?i)currentUser\\s*\\("; private static List<String> waFunctions=new ArrayList<String>(); private static final String DIGIT_STARTING_IDENTIFIERS = "(\\W)(([0-9])+([_a-zA-Z])+)(\\W)"; private static final String UNDERSCORE_IDENTIFIERS = "(\\W)((_)+([_a-zA-Z])+)(\\W)"; private static final String XESCAPED = "(\\W)((?i)_)(\\W)"; private static final String TYPES_TRANSLATE = "(\\W)(?i)_(\\W)"; private static final String DATE_ACCESS_FORMAT = "(0[1-9]|[1-9]|1[012])/(0[1-9]|[1-9]|[12][0-9]|3[01])/(\\d\\d\\d\\d)"; private static final String DATE_FORMAT = "(\\d\\d\\d\\d)-(0[1-9]|[1-9]|1[012])-(0[1-9]|[1-9]|[12][0-9]|3[01])"; private static final String HHMMSS_ACCESS_FORMAT = "(0[0-9]|1[0-9]|2[0-4]):([0-5][0-9]):([0-5][0-9])"; private static final String DFUNCTIONS_WHERE="(?i)_\\s*\\(\\s*[\'\"](.*)[\'\"]\\,\\s*[\'\"](.*)[\'\"]\\,\\s*[\'\"](.*)[\'\"]\\s*\\)"; private static final String DFUNCTIONS_NO_WHERE="(?i)_\\s*\\(\\s*[\'\"](.*)[\'\"]\\,\\s*[\'\"](.*)[\'\"]\\s*\\)"; private static final List<String> DFUNCTIONLIST=Arrays.asList("COUNT","MAX","MIN","SUM","AVG","LAST","FIRST"); public static final String BIG_BANG = "1899-12-30"; private static ArrayList<String> whiteSpaceTables=new ArrayList<String>(); private static final List<String> XESCAPED_IDENTIFIERS=Arrays.asList( "APPLICATION", "ASSISTANT", "CONTAINER", "DESCRIPTION", "DOCUMENT", "ECHO", "FIELD", "FIELDS", "FILLCACHE", "FORM", "FORMS", "IDLE", "IMP", "LASTMODIFIED", "LEVEL", "MACRO", "MATCH", "NAME", "NEWPASSWORD", "OFF", "OPTION", "OWNERACCESS", "PARAMETER", "PARAMETERS", "PARTIAL", "PERCENT", "PROPERTY", "QUIT", "REFRESH", "REFRESHLINK", "REPAINT", "REPORT", "REPORTS", "REQUERY", "SCREEN", "SECTION", "SETFOCUS", "SETOPTION", "TABLEDEF", "TABLEDEFS", "VAR", "VARP", "WORKSPACE"); private static final List<String> KEYWORDLIST=Arrays.asList("AT", "BOTH", "CORRESPONDING", "LEADING"); private static boolean supportsAccessLike=true; public static enum DDLType { CREATE_TABLE_AS_SELECT( Pattern .compile("\\s*(?i)create\\s*(?i)table\\s*(([_a-zA-Z0-9])*)\\s*(?)AS\\s*\\(\\s*(?)SELECT")), CREATE_TABLE(Pattern.compile("\\s*(?i)create\\s*(?i)table\\s*(([_a-zA-Z0-9])*)")), DROP_TABLE( Pattern .compile("\\s*(?i)drop\\s*(?i)table\\s*(([_a-zA-Z0-9])*)")); private Pattern pattern; private DDLType(Pattern pattern) { this.pattern = pattern; } public boolean in(DDLType... types) { for (DDLType type : types) { if (this.equals(type)) { return true; } } return false; } public static DDLType getDDLType(String s) { DDLType[] dts = DDLType.values(); for (DDLType cand : dts) { if (cand.pattern.matcher(s).find()) { return cand; } } return null; } public String getDBObjectName(String s) { Matcher m = pattern.matcher(s); if (m.find()) { return m.group(1); } return null; } } static void addWAFunctionName(String name){ waFunctions.add(name); } public static DDLType getDDLType(String s) { return DDLType.getDDLType(s); } private static String replaceWorkAroundFunctions(String sql) { for (String waFun:waFunctions){ sql=sql.replaceAll("(\\W)(?i)"+waFun+"\\s*\\(", "$1"+waFun+"WA("); } sql=sql.replaceAll("(\\W)(?i)STDEV\\s*\\(", "$1STDDEV_SAMP("); sql=sql.replaceAll("(\\W)(?i)STDEVP\\s*\\(", "$1STDDEV_POP("); sql=sql.replaceAll("(\\W)(?i)VAR\\s*\\(", "$1VAR_SAMP("); sql=sql.replaceAll("(\\W)(?i)VARP\\s*\\(", "$1VAR_POP("); //StDevP return sql.replaceAll(WA_CURRENT_USER,"$1user("); } public static String convertSQL(String sql, boolean creatingQuery) { return convertSQL( sql, null, creatingQuery); } public static String convertSQL(String sql,UcanaccessConnection conn, boolean creatingQuery) { sql=sql+" "; sql = convertAccessDate(sql); sql = replaceWorkAroundFunctions(sql); sql = convertDFunctions(sql); sql = escape(sql); sql = convertLike(sql); sql=replaceWhiteSpaceTables(sql); sql=replaceDistinctRow(sql); if(!creatingQuery){ Pivot.checkAndRefreshPivot(sql,conn); } sql = sql.trim(); return sql; } private static String replaceDistinctRow(String sql) { return sql.replaceAll("\\s+(?i)distinctrow\\s+", " DISTINCT "); } static void addWhiteSpaceTables(String name) { name=basicEscapingIdentifier(name); if(whiteSpaceTables.contains(name)) return; for(String alrIn:whiteSpaceTables){ if(name.contains(alrIn)){ whiteSpaceTables.add(whiteSpaceTables.indexOf(alrIn),name); return; } } whiteSpaceTables.add(name); } public static String convertSQL(String sql) { return convertSQL(sql,null, false); } public static String convertSQL(String sql, UcanaccessConnection conn) { return convertSQL(sql,conn, false); } public static String convertAccessDate(String sql) { sql = sql.replaceAll("#" + DATE_ACCESS_FORMAT + "#", "Timestamp'$3-$1-$2 00:00:00'") //FORMAT MM/dd/yyyy .replaceAll( "#" + DATE_ACCESS_FORMAT + "\\s*(" + HHMMSS_ACCESS_FORMAT + ") "Timestamp'$3-$1-$2 $4'").replaceAll( "#" + DATE_ACCESS_FORMAT + "\\s*(" + HHMMSS_ACCESS_FORMAT + ")\\s*(?i)AM "Timestamp'$3-$1-$2 $4'").replaceAll( "#" + DATE_ACCESS_FORMAT + "\\s*(" + HHMMSS_ACCESS_FORMAT + ")\\s*(?i)PM "Timestamp'$3-$1-$2 $4'+ 12 Hour ") //FORMAT yyyy-MM-dd .replaceAll("#" + DATE_FORMAT + "#", "Timestamp'$1-$2-$3 00:00:00'") .replaceAll( "#" + DATE_FORMAT + "\\s*(" + HHMMSS_ACCESS_FORMAT + ") "Timestamp'$1-$2-$3 $4'").replaceAll( "#" + DATE_FORMAT + "\\s*(" + HHMMSS_ACCESS_FORMAT + ")\\s*(?i)AM "Timestamp'$1-$2-$3 $4'").replaceAll( "#" + DATE_FORMAT + "\\s*(" + HHMMSS_ACCESS_FORMAT + ")\\s*(?i)PM "Timestamp'$1-$2-$3 $4'+ 12 Hour ") .replaceAll( "#(" + HHMMSS_ACCESS_FORMAT + ")#", "Timestamp'" + BIG_BANG + " $1'") .replaceAll( "#(" + HHMMSS_ACCESS_FORMAT + ")\\s*(?i)AM#", "Timestamp'" + BIG_BANG + " $1'") .replaceAll( "#(" + HHMMSS_ACCESS_FORMAT + ")\\s*(?i)PM#", "Timestamp'" + BIG_BANG + " $1'+ 12 Hour"); ; return sql; } private static String replaceWhiteSpaceTables(String sql){ String[] sqls=sql.split("'",-1); StringBuffer sb=new StringBuffer(); String cm=""; for(int i=0;i<sqls.length;++i){ sb.append(cm).append(i%2==0?replaceWhiteSpaceTables0(sqls[i]):sqls[i]); cm="'"; } return sb.toString(); } private static String replaceWhiteSpaceTables0(String sql){ if(whiteSpaceTables.size()==0){ return sql; } StringBuffer sb=new StringBuffer(" ("); String or=""; for(String bst:whiteSpaceTables){ sb.append(or).append("(?i)"+bst); or="|"; } //workaround o.o. and l.o. for(String bst:whiteSpaceTables){ String dw=bst.replaceAll(" ", " "); sb.append(or).append("(?i)"+dw); } sb.append(")"); sql=sql.replaceAll(sb.toString()," \"$1\""); return sql; } public static String escapeKeywords(String sql){ for(String bst:KEYWORDLIST){ sql=sql.replaceAll("(\\W)(?i)"+bst+"(\\W)"," $1\""+bst+"\"$2"); } return sql; } private static String convertIdentifiers(String sql) { int init; while ((init = sql.indexOf("[")) != -1) { int end = sql.indexOf("]"); if(end<init)return sql; String content=basicEscapingIdentifier(sql.substring(init + 1, end)).toUpperCase(); String subs=content.indexOf(" ")>0?"\"":" "; sql = sql.substring(0, init) + subs +content + subs + sql.substring(end + 1); } return sql; } private static String convertIdentifiersSWDigit(String sql) { String sqlc= convertIdentifiers(sql) .replaceAll(DIGIT_STARTING_IDENTIFIERS, "$1Z_" + "$2$5") .replaceAll(UNDERSCORE_IDENTIFIERS, "$1Z" + "$2$5"); for (String xidt:XESCAPED_IDENTIFIERS){ sqlc=sqlc.replaceAll(XESCAPED.replaceAll("_",xidt), "$1X" + "$2$3"); } return sqlc; } private static String escape(String sql) { Pattern pd = DOUBLE_QUOTE_G_PATTERN; Pattern ps = QUOTE_G_PATTERN; int li = Math.max(sql.lastIndexOf("\""), sql.lastIndexOf("'")); boolean enddq = sql.endsWith("\"") || sql.endsWith("'"); String suff = enddq ? "" : sql.substring(li + 1); suff = suff.replaceAll("&", "||"); suff = convertIdentifiersSWDigit(suff); String tsql = enddq ? sql : sql.substring(0, li + 1); Matcher md = pd.matcher(tsql); Matcher ms = ps.matcher(tsql); boolean fd = md.find(); boolean fs = ms.find(); if (fd || fs) { boolean inid = !fs || (fd && md.start(0) < ms.start(0)); String group, str; Matcher mcr = inid ? md : ms; group = mcr.group(1); if (inid) group = group.replaceAll("'", "''").replaceAll("\"\"", "\""); str = tsql.substring(0, mcr.start(0)); str = str.replaceAll("&", "||"); str = convertIdentifiersSWDigit(str); tsql = str + "'" + group + "'" + escape(tsql.substring(mcr.end(0))); } else { tsql = convertIdentifiersSWDigit(tsql); } return tsql + suff; } public static String basicEscapingIdentifier(String name) { if (name.startsWith("~")) return null; String escaped = Database .escapeIdentifier(name//.replaceAll(" ", "_") .replaceAll("[/\\\\$%^:]", "_").replaceAll("~", "M_").replaceAll("\\.", "_")); if (Character.isDigit(escaped.charAt(0))) { escaped = "Z_" + escaped; } if (escaped.charAt(0)=='_') { escaped = "Z" + escaped; } return escaped.toUpperCase(); } public static String escapeIdentifier(String name) { String escaped=basicEscapingIdentifier(name); if(escaped==null)return null; if(escaped.indexOf(" ")>0){ escaped="\""+escaped+"\""; } return escaped; } private static String convertCreateTable(String sql, Map<String, String> types2Convert) { // padding for detecting the right exception sql += " "; for (Map.Entry<String, String> entry : types2Convert.entrySet()) { sql = sql.replaceAll(TYPES_TRANSLATE .replaceAll("_", entry.getKey()), "$1" + entry.getValue() + "$2"); sql = sql.replaceAll("(\\W)(?i)VARCHAR\\s*w*(\\)|,)","$1VARCHAR(255)$2"); } return sql; } private static String convertDFunctions(String sql) { boolean hasFrom=FROM_PATTERN.matcher(sql).find(); String init=hasFrom?" (SELECT ":""; String end=hasFrom?" ) ":""; for(String s:DFUNCTIONLIST){ sql=sql.replaceAll( DFUNCTIONS_WHERE.replaceFirst("_", "D"+s), init+s+"($1) FROM $2 WHERE $3 "+end); sql=sql.replaceAll( DFUNCTIONS_NO_WHERE.replaceFirst("_", "D"+s), init+s+"($1) FROM $2 "+end); } return sql; } public static String convertCreateTable(String sql) { return convertCreateTable(sql, TypesMap.getAccess2HsqlTypesMap()); } public static boolean checkDDL(String sql) { if (sql == null) return false; else { String lcsql = sql.toLowerCase().trim(); return lcsql.startsWith("create ") || lcsql.startsWith("alter ") || lcsql.startsWith("drop "); } } private static String convertLike(String sql) { Pattern ptfl = FIND_LIKE_PATTERN; Matcher matcher = ptfl.matcher(sql); if (matcher.find()) { return sql.substring(0, matcher.start(1)) + convertLike(matcher.group(1), matcher.group(2), matcher .group(3)) + convertLike(sql.substring(matcher.end(0))); } else return sql; } private static String convert2RegexMatches(String likeContent){ Pattern ptn=ACCESS_LIKE_ESCAPE_PATTERN; Matcher mtc=ptn.matcher(likeContent); if(mtc.find()){ return convert2RegexMatches(likeContent.substring(0, mtc.start(0)))+ mtc.group(0).substring(1, 2)+ convert2RegexMatches(likeContent.substring( mtc.end(0))); } return likeContent.replaceAll("#", "\\\\d").replaceAll("\\*", ".*").replaceAll("_", ".").replaceAll( "(\\[)\\!(\\w\\-\\w\\])", "$1^$2") + "')"; } private static String convert2LikeCondition(String likeContent){ Pattern ptn=ACCESS_LIKE_ESCAPE_PATTERN; Matcher mtc=ptn.matcher(likeContent); if(mtc.find()){ return convert2LikeCondition(likeContent.substring(0, mtc.start(0)))+ mtc.group(0).substring(1, 2)+ convert2LikeCondition(likeContent.substring( mtc.end(0))); } return likeContent.replaceAll("\\*", "%").replaceAll("\\?", "_"); } private static String convertLike(String conditionField, String closePar, String likeContent) { Pattern inter = ACCESS_LIKE_CHARINTERVAL_PATTERN; if (likeContent.indexOf("#") >= 0 || inter.matcher(likeContent).find()) { return "REGEXP_MATCHES(" + conditionField + ",'" + convert2RegexMatches( likeContent) + closePar + " "; } return " " + conditionField + " like '" + convert2LikeCondition(likeContent) + "'"; } public static boolean isSupportsAccessLike() { return supportsAccessLike; } public static void setSupportsAccessLike(boolean supportsAccessLike) { SQLConverter.supportsAccessLike = supportsAccessLike; } }
package nl.it.fixx.moknj.builders; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import nl.it.fixx.moknj.bal.AssetBal; import nl.it.fixx.moknj.bal.EmployeeBal; import nl.it.fixx.moknj.bal.LinkBal; import nl.it.fixx.moknj.bal.MainAccessBal; import nl.it.fixx.moknj.bal.RecordBal; import nl.it.fixx.moknj.bal.UserBal; import nl.it.fixx.moknj.domain.core.field.FieldDetail; import nl.it.fixx.moknj.domain.core.field.FieldValue; import nl.it.fixx.moknj.domain.core.global.GlobalGraphDate; import nl.it.fixx.moknj.domain.core.global.GlobalGraphView; import nl.it.fixx.moknj.domain.core.global.GlobalMenuType; import nl.it.fixx.moknj.domain.core.graph.Graph; import nl.it.fixx.moknj.domain.core.graph.GraphData; import nl.it.fixx.moknj.domain.core.menu.Menu; import nl.it.fixx.moknj.domain.core.record.Record; import nl.it.fixx.moknj.domain.core.template.Template; import nl.it.fixx.moknj.domain.core.user.User; import nl.it.fixx.moknj.domain.modules.asset.Asset; import nl.it.fixx.moknj.domain.modules.asset.AssetLink; import nl.it.fixx.moknj.repository.RepositoryFactory; import nl.it.fixx.moknj.util.DateUtil; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is used to group the graph data for display in the UI * * @author adriaan */ public class GraphBuilder { private static final Logger LOG = LoggerFactory.getLogger(GraphBuilder.class); private final String token; private final RepositoryFactory factory; private DateTime endDate; private DateTime startDate; private static final String MDL_ASSET_DEFAULT = "Asset"; private static final String MDL_EMPLOYEE_DEFAULT = "Employee"; private static final String MDL_ASSET_STATUS_IN = "In"; private static final String MDL_ASSET_STATUS_OUT = "Out"; public GraphBuilder(RepositoryFactory factory, String token) { this.factory = factory; this.token = token; } private final String FMT_CREATED_DATE = "yyyy-MM-dd HH:mm"; private final String FMT_FILTER_DATE = "yyyy-MM-dd"; private final String FMT_MONTH_NAME = "MMM"; private final String FMT_DAY_NAME = "EEE"; /** * Generates the graph data! * * @param graphInfo * @return * @throws Exception */ public GraphData buildGraphData(Graph graphInfo) throws Exception { try { GraphData data = new GraphData(); // get all records for template. if (graphInfo != null) { // LOG.info("Graph Name : " + graphInfo.getName()); // Business access layer. RecordBal recordBal = null; Menu menu = new MainAccessBal(factory).getMenu(graphInfo.getMenuId(), token); for (Template template : menu.getTemplates()) { if (template.getId().equals(graphInfo.getTemplateId())) { if (GlobalMenuType.GBL_MT_ASSET.equals(menu.getMenuType())) { recordBal = new AssetBal(factory); } else if (GlobalMenuType.GBL_MT_EMPLOYEE.equals(menu.getMenuType())) { recordBal = new EmployeeBal(factory); } /** * below is where the date logic is generated or x - * axis focus labels. This is where you will start * seeing dragons beware of purple! */ // X-AXIS Label Logic if (recordBal != null) { List records = recordBal.getAll(template.getId(), menu.getId(), token); // duplicate records for all entries which have the same id. // Basically a left join... if (GlobalGraphDate.GBL_FOCUS_ASSET_IN_OUT_DATE.equals(graphInfo.getGraphDateType())) { List<Asset> inOutAssetJoinList = new ArrayList<>(); for (Object record : records) { if (record instanceof Asset) { Asset asset = (Asset) record; // gets all the checked in/out records for asset. List<AssetLink> links = new LinkBal(factory).getAllAssetLinksByAssetId(asset.getId(), token); for (AssetLink link : links) { // create new instance of asset... prototype pattern would be nice here... Asset newAsset = new Asset(); if (link.getAssetId().equals(asset.getId())) { DateTime date = DateUtil.parseJavaScriptDateTime(link.getDate()); String freeDate = new SimpleDateFormat( FMT_CREATED_DATE ).format(date.plusDays(1).toDate()); newAsset.setFreeDate(freeDate); newAsset.setFreeValue(link.isChecked() ? MDL_ASSET_STATUS_OUT : MDL_ASSET_STATUS_IN); newAsset.setCreatedBy(asset.getCreatedBy()); newAsset.setCreatedDate(asset.getCreatedDate()); newAsset.setDetails(asset.getDetails()); newAsset.setLastModifiedBy(asset.getLastModifiedBy()); newAsset.setLastModifiedDate(asset.getLastModifiedDate()); newAsset.setMenuScopeIds(asset.getMenuScopeIds()); newAsset.setResourceId(asset.getResourceId()); newAsset.setTypeId(asset.getTypeId()); inOutAssetJoinList.add(newAsset); } } } } records = inOutAssetJoinList; } // This is used to bypass the filterdate and filter rule logic boolean bypassDateRulle = false; if (GlobalGraphDate.GBL_FOCUS_NO_DATE_RULE.equals(graphInfo.getGraphDateType())) { if (!GlobalGraphView.GBL_OFTD.equals(graphInfo.getGraphView())) { bypassDateRulle = true; } } if (!bypassDateRulle) { endDate = DateUtil.parseJavaScriptDateTime(graphInfo.getGraphDate()); startDate = new DateTime(); //javascript is one day off todo with date type UCT endDate = endDate.plusDays(1); } else { startDate = new DateTime(); endDate = new DateTime(); } List<String> xAxisLabels = new ArrayList<>(); boolean xAxisSwapped = false; if (null != graphInfo.getGraphView()) { switch (graphInfo.getGraphView()) { case GBL_MTMTFY: { xAxisLabels = DateUtil.geMonthsForYear(endDate.getYear()); initialiseYearDates(); } break; case GBL_MTMFD: { xAxisLabels = DateUtil.geMonthsForDate(endDate); initialiseMonthDates(); } break; case GBL_DOWFY: { xAxisLabels = DateUtil.getDaysOfWeek(endDate); initialiseYearDates(); } break; case GBL_DOWFM: { xAxisLabels = DateUtil.getDaysOfWeek(endDate); initialiseMonthDates(); } break; case GBL_OFTD: DateTime today = new DateTime(); xAxisLabels.add(today.toLocalDate().toString(FMT_FILTER_DATE)); // Set end and start date to today/current date endDate = today; startDate = today; break; case GBL_SMTEOM: { getXAxisLabels(xAxisLabels, graphInfo, template); xAxisSwapped = true; initialiseMonthDates(); } break; case GBL_SYTEOY: { getXAxisLabels(xAxisLabels, graphInfo, template); xAxisSwapped = true; initialiseYearDates(); } break; case GBL_SYTD: { // SWOPS THE data set for x axis labels getXAxisLabels(xAxisLabels, graphInfo, template); xAxisSwapped = true; String startDateStr = endDate.getYear() + "-01-01"; LocalDate localstratDate = new LocalDate(startDateStr); startDate = localstratDate.toDateTimeAtStartOfDay(); } break; default: break; } } // LOG.info("Type : " + graphInfo.getGraphView().getDisplayName()); // LOG.info("End Date : " + endDate.toString(FMT_FILTER_DATE)); // LOG.info("Start Date : " + startDate.toString(FMT_FILTER_DATE)); String endDateStr = new SimpleDateFormat(FMT_FILTER_DATE).format(endDate.toDate()); DateTime endDateRule = DateUtil.parseDate(endDateStr, FMT_FILTER_DATE); String startDateStr = new SimpleDateFormat(FMT_FILTER_DATE).format(startDate.toDate()); DateTime startDateRule = DateUtil.parseDate(startDateStr, FMT_FILTER_DATE); Set<String> yAxisLabels = new HashSet<>(); if (null != graphInfo.getGraphFocus()) { switch (graphInfo.getGraphFocus()) { case GBL_FOCUS_CREATED_BY: for (User user : new UserBal(factory).getAll()) { if (user.isSystemUser()) { yAxisLabels.add(user.getUserName()); } } break; case GBL_FOCUS_FREE_FIELD: if (graphInfo.getFreefieldId() != null) { for (FieldDetail field : template.getDetails()) { if (field.getId().equals(graphInfo.getFreefieldId())) { String drpValue = field.getName(); int n = drpValue.indexOf(":"); String name = drpValue.substring(0, n - 1); String array = drpValue.substring(n + 1, drpValue.length()); String jsonStr = "{\"" + name + "\":" + array + "}"; JSONObject json = (JSONObject) JSONValue.parse(jsonStr); List<String> drpValues = (List<String>) json.get(name); if (GlobalGraphDate.GBL_FOCUS_ASSET_IN_OUT_DATE.equals(graphInfo.getGraphDateType())) { for (String value : drpValues) { yAxisLabels.add(value + "-" + MDL_ASSET_STATUS_IN); yAxisLabels.add(value + "-" + MDL_ASSET_STATUS_OUT); } } else { for (String value : drpValues) { yAxisLabels.add(value); } } break; } } } break; case GBL_FOCUS_IN_AND_OUT: yAxisLabels.add(MDL_ASSET_STATUS_IN); yAxisLabels.add(MDL_ASSET_STATUS_OUT); break; case GBL_FOCUS_DEFAULT: if (GlobalMenuType.GBL_MT_ASSET.equals(menu.getMenuType())) { yAxisLabels.add(MDL_ASSET_DEFAULT); } else if (GlobalMenuType.GBL_MT_EMPLOYEE.equals(menu.getMenuType())) { yAxisLabels.add(MDL_EMPLOYEE_DEFAULT); } break; default: break; } } if (xAxisSwapped) { yAxisLabels = new HashSet<>(); if (GlobalMenuType.GBL_MT_ASSET.equals(menu.getMenuType())) { yAxisLabels.add(MDL_ASSET_DEFAULT); } else if (GlobalMenuType.GBL_MT_EMPLOYEE.equals(menu.getMenuType())) { yAxisLabels.add(MDL_EMPLOYEE_DEFAULT); } } int[][] yxData = new int[yAxisLabels.size()][xAxisLabels.size()]; String[] yAxis = yAxisLabels.toArray(new String[yAxisLabels.size()]); String[] xAxis = xAxisLabels.toArray(new String[xAxisLabels.size()]); for (Object record : records) { Record recodValue = (Record) record; // y- axis value should come here String yAxisValue = null; if (null != graphInfo.getGraphFocus()) { switch (graphInfo.getGraphFocus()) { case GBL_FOCUS_CREATED_BY: String createdBy = recodValue.getCreatedBy(); yAxisValue = createdBy; break; case GBL_FOCUS_FREE_FIELD: for (FieldValue field : recodValue.getDetails()) { if (field.getId().equals(graphInfo.getFreefieldId())) { String value = field.getValue(); if (GlobalGraphDate.GBL_FOCUS_ASSET_IN_OUT_DATE.equals(graphInfo.getGraphDateType())) { if (MDL_ASSET_STATUS_IN.equals(recodValue.getFreeValue())) { yAxisValue = value + "-" + MDL_ASSET_STATUS_IN; } else if (MDL_ASSET_STATUS_OUT.equals(recodValue.getFreeValue())) { yAxisValue = value + "-" + MDL_ASSET_STATUS_OUT; } } else { yAxisValue = value; } break; } } break; case GBL_FOCUS_IN_AND_OUT: // use record object as value (asset) lost its // asset fields in casting. if (record instanceof Asset) { Asset asset = (Asset) record; // null check for assignment // null == in // not null == out if (GlobalGraphDate.GBL_FOCUS_ASSET_IN_OUT_DATE.equals(graphInfo.getGraphDateType())) { yAxisValue = asset.getFreeValue(); } else if (!GlobalGraphDate.GBL_FOCUS_ASSET_IN_OUT_DATE.equals(graphInfo.getGraphDateType())) { if (asset.getResourceId() != null && !asset.getResourceId().trim().isEmpty()) { yAxisValue = MDL_ASSET_STATUS_OUT; } else { yAxisValue = MDL_ASSET_STATUS_IN; } } } break; case GBL_FOCUS_DEFAULT: default: if (GlobalMenuType.GBL_MT_ASSET.equals(menu.getMenuType())) { yAxisValue = MDL_ASSET_DEFAULT; } else if (GlobalMenuType.GBL_MT_EMPLOYEE.equals(menu.getMenuType())) { yAxisValue = MDL_EMPLOYEE_DEFAULT; } break; } } if (yAxisValue == null) { if (GlobalMenuType.GBL_MT_ASSET.equals(menu.getMenuType())) { yAxisValue = MDL_ASSET_DEFAULT; } else if (GlobalMenuType.GBL_MT_EMPLOYEE.equals(menu.getMenuType())) { yAxisValue = MDL_EMPLOYEE_DEFAULT; } } // Calculate date filter DateTime recodDateTime = new DateTime(); if (null != graphInfo.getGraphDateType()) { switch (graphInfo.getGraphDateType()) { case GBL_FOCUS_LAST_MODIFIED: recodDateTime = DateUtil.parseDate(recodValue.getLastModifiedDate(), FMT_CREATED_DATE); break; case GBL_FOCUS_ASSET_IN_OUT_DATE: recodDateTime = DateUtil.parseDate(recodValue.getFreeDate(), FMT_CREATED_DATE); break; case GBL_FOCUS_CREATED_DATE: recodDateTime = DateUtil.parseDate(recodValue.getCreatedDate(), FMT_CREATED_DATE); break; case GBL_FOCUS_FREE_FIELD: for (FieldValue field : recodValue.getDetails()) { if (field.getId().equals(graphInfo.getFreeDateFieldId())) { recodDateTime = DateUtil.parseJavaScriptDateTime(field.getValue()); break; } } break; default: recodDateTime = DateUtil.parseDate(recodValue.getCreatedDate(), FMT_CREATED_DATE); break; } } else { recodDateTime = DateUtil.parseDate(recodValue.getCreatedDate(), FMT_CREATED_DATE); } String recordDateStr = new SimpleDateFormat(FMT_FILTER_DATE).format(recodDateTime.toDate()); DateTime recordDate = DateUtil.parseDate(recordDateStr, FMT_FILTER_DATE); LOG.info("recordDate : " + recordDate.toString(FMT_FILTER_DATE)); // Check if view date and record date is in correct range // AKA date rule implementation. if ( // Before Date comparison (End Date) (recordDate.isBefore(endDateRule) || recordDate.isEqual(endDateRule)) && // After Date comparison (Start Date) (recordDate.isAfter(startDateRule) || recordDate.isEqual(startDateRule)) // Bypass date || bypassDateRulle) { LocalDate local = recordDate.toLocalDate(); String xAxisValue = ""; if (null != graphInfo.getGraphView()) { switch (graphInfo.getGraphView()) { case GBL_OFTD: xAxisValue = local.toString(FMT_FILTER_DATE); break; case GBL_MTMTFY: case GBL_MTMFD: xAxisValue = local.toString(FMT_MONTH_NAME); break; case GBL_DOWFY: case GBL_DOWFM: xAxisValue = local.toString(FMT_DAY_NAME); break; default: // SWAP DATA HERE xAxisValue = yAxisValue; if (GlobalMenuType.GBL_MT_ASSET.equals(menu.getMenuType())) { yAxisValue = MDL_ASSET_DEFAULT; } else if (GlobalMenuType.GBL_MT_EMPLOYEE.equals(menu.getMenuType())) { yAxisValue = MDL_EMPLOYEE_DEFAULT; } break; } } for (int y = 0; y < yAxis.length; y++) { String yAxisFocus = yAxis[y]; // LOG.info("yAxisFocus : " + yAxisFocus); // LOG.info("yAxisValue : " + yAxisValue); if (yAxisFocus.equals(yAxisValue)) { int[] dataSet = yxData[y]; for (int x = 0; x < xAxis.length; x++) { String xAxisFocus = xAxis[x]; // LOG.info("xAxisFocus : " + xAxisFocus); // LOG.info("xAxisValue : " + xAxisValue); if (xAxisFocus.equals(xAxisValue)) { dataSet[x] += 1; yxData[y] = dataSet; } } } } } } // Set grpah data for page display data.setGraphTitle(graphInfo.getName()); data.setGraphData(yxData); data.setXlabels(xAxis); data.setYlabels(yAxis); return data; } } } } return data; } catch (Exception e) { LOG.error("error while get graph data", e); throw e; } } private void getXAxisLabels(List<String> xAxis, Graph graphInfo, Template temp) throws Exception { try { if (null != graphInfo.getGraphFocus()) { switch (graphInfo.getGraphFocus()) { case GBL_FOCUS_CREATED_BY: new UserBal(factory).getAll().stream().filter((user) -> (user.isSystemUser())).forEach((user) -> { xAxis.add(user.getUserName()); }); break; case GBL_FOCUS_IN_AND_OUT: xAxis.add(MDL_ASSET_STATUS_IN); xAxis.add(MDL_ASSET_STATUS_OUT); break; case GBL_FOCUS_FREE_FIELD: if (graphInfo.getFreefieldId() != null) { for (FieldDetail field : temp.getDetails()) { if (field.getId().equals(graphInfo.getFreefieldId())) { String drpValue = field.getName(); int n = drpValue.indexOf(":"); String name = drpValue.substring(0, n - 1); String array = drpValue.substring(n + 1, drpValue.length()); String jsonStr = "{\"" + name + "\":" + array + "}"; JSONObject json = (JSONObject) JSONValue.parse(jsonStr); List<String> xlabels = (List<String>) json.get(name); if (GlobalGraphDate.GBL_FOCUS_ASSET_IN_OUT_DATE.equals(graphInfo.getGraphDateType())) { for (String value : xlabels) { xAxis.add(value + "-" + MDL_ASSET_STATUS_IN); xAxis.add(value + "-" + MDL_ASSET_STATUS_OUT); } } else { for (String value : xlabels) { xAxis.add(value); } } break; } } } break; case GBL_FOCUS_DEFAULT: Menu menu = new MainAccessBal(factory).getMenu(graphInfo.getMenuId(), token); if (GlobalMenuType.GBL_MT_ASSET.equals(menu.getMenuType())) { xAxis.add(MDL_ASSET_DEFAULT); } else if (GlobalMenuType.GBL_MT_EMPLOYEE.equals(menu.getMenuType())) { xAxis.add(MDL_EMPLOYEE_DEFAULT); } break; default: break; } } } catch (Exception e) { LOG.error("error while get x axis", e); throw e; } } /** * Initializes the start date and end date for a year * * @param endDate * @param startDate */ private void initialiseYearDates() throws Exception { try { String endDateStr = endDate.getYear() + "-12-31"; LocalDate localDateEnd = new LocalDate(endDateStr); endDate = localDateEnd.toDateTimeAtStartOfDay(); String startDateStr = endDate.getYear() + "-01-01"; LocalDate localstratDate = new LocalDate(startDateStr); startDate = localstratDate.toDateTimeAtStartOfDay(); } catch (Exception e) { LOG.error("error while get graph year dates", e); throw e; } } /** * Initializes the start date and end date for a month * * @param endDate * @param startDate */ private void initialiseMonthDates() throws Exception { try { String endDateStr = endDate.getYear() + "-" + endDate.getMonthOfYear() + "-" + endDate.dayOfMonth().getMaximumValue(); LocalDate localEndDate = new LocalDate(endDateStr); endDate = localEndDate.toDateTimeAtStartOfDay(); String startDateStr = endDate.getYear() + "-" + endDate.getMonthOfYear() + "-" + endDate.dayOfMonth().getMinimumValue(); LocalDate localStartDate = new LocalDate(startDateStr); startDate = localStartDate.toDateTimeAtStartOfDay(); } catch (Exception e) { LOG.error("error while month dates", e); throw e; } } }
package oe.maven.plugins.revision; import java.io.File; import java.util.HashSet; import java.util.Set; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory; import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory; import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl; import org.tmatesoft.svn.core.internal.wc.admin.SVNEntry; import org.tmatesoft.svn.core.wc.ISVNStatusHandler; import org.tmatesoft.svn.core.wc.SVNClientManager; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNStatus; import org.tmatesoft.svn.core.wc.SVNStatusClient; import org.tmatesoft.svn.core.wc.SVNStatusType; import org.tmatesoft.svn.core.wc.SVNWCUtil; /** * Retrieves the status and revision number of the Subversion working copy directory. * * @goal revision * @phase initialize * @requiresProject */ public class RevisionMojo extends AbstractMojo { static { DAVRepositoryFactory.setup(); // http, https SVNRepositoryFactoryImpl.setup(); // svn, svn+xxx FSRepositoryFactory.setup(); // file } /** * The maven project. * * @parameter expression="${project}" * @readonly */ private MavenProject project; /** * The Subversion working copy directory. * The plugin will evaluate the aggregated status and revision number of this directory and its contents. * * @parameter expression="${workingCopyDirectory}" default-value="${basedir}" * @required */ private File workingCopyDirectory; /** * The name of the property that will contain the root of the remote repository of the working copy directory * entry. * * @parameter expression="${repositoryPropertyName}" default-value="workingCopyDirectory.repository" */ private String repositoryPropertyName; /** * The name of the property that will contain the path of the working copy directory entry relative * to the root of the remote repository. * * @parameter expression="${pathPropertyName}" default-value="workingCopyDirectory.path" */ private String pathPropertyName; /** * The name of the property that will contain the aggregated status and revision number of the working copy * directory. * * @parameter expression="${revisionPropertyName}" default-value="workingCopyDirectory.revision" */ private String revisionPropertyName; /** * The name of the property that will contain the aggregated status and revision number of the working copy * directory. * <p/> * This property will contain only characters allowed in the file names. * * @parameter expression="${fileNameSafeRevisionPropertyName}" default-value="workingCopyDirectory.fileNameSafeRevision" */ private String fileNameSafeRevisionPropertyName; /** * Whether to report the mixed revisions information. If set to {@code false} then only the maximum revision number * will be reported. * * @parameter expression="${reportMixedRevisions}" default-value="true" */ private boolean reportMixedRevisions; /** * Whether to report the status information. If set to {@code false} then only the revision number will be * reported. * * @parameter expression="${reportStatus}" default-value="true" */ private boolean reportStatus; /** * Whether to collect the status information on items that are not under version control. * * @parameter expression="${reportUnversioned}" default-value="true" */ private boolean reportUnversioned; /** * Whether to collect the status information on items that were set to be ignored. * * @parameter expression="${reportIgnored}" default-value="false" */ private boolean reportIgnored; /** * Whether to check the remote repository and report if the local items are out-of-date. * * @parameter expression="${reportOutOfDate}" default-value="false" */ private boolean reportOutOfDate; /** * Provides detailed messages while this goal is running. * * @parameter expression="${verbose}" default-value="false" */ private boolean verbose; public void execute() throws MojoExecutionException, MojoFailureException { if ( verbose ) { getLog().info( "${workingCopyDirectory}: " + workingCopyDirectory ); getLog().info( "report mixed revisions: " + reportMixedRevisions ); getLog().info( "report status: " + reportStatus ); getLog().info( "report unversioned: " + reportUnversioned ); getLog().info( "report ignored: " + reportIgnored ); getLog().info( "report out-of-date: " + reportOutOfDate ); } try { String repository; String path; String revision; String fileNameSafeRevision; if ( SVNWCUtil.isVersionedDirectory( workingCopyDirectory ) ) { SVNClientManager clientManager = SVNClientManager.newInstance(); SVNStatusClient statusClient = clientManager.getStatusClient(); SVNEntry entry = statusClient.doStatus( workingCopyDirectory, false ).getEntry(); repository = entry.getRepositoryRoot(); path = entry.getURL().substring( repository.length() ); if ( path.startsWith( "/" ) ) { path = path.substring( 1 ); } StatusCollector statusCollector = new StatusCollector(); statusClient.doStatus( workingCopyDirectory, SVNRevision.HEAD, SVNDepth.INFINITY, reportOutOfDate, true, reportIgnored, false, statusCollector, null ); revision = statusCollector.getStatus( StatusCharacters.STANDARD ); fileNameSafeRevision = statusCollector.getStatus( StatusCharacters.FILE_NAME_SAFE ); } else { repository = ""; path = ""; revision = "unversioned"; fileNameSafeRevision = revision; } project.getProperties().setProperty( repositoryPropertyName, repository ); project.getProperties().setProperty( pathPropertyName, path ); project.getProperties().setProperty( revisionPropertyName, revision ); project.getProperties().setProperty( fileNameSafeRevisionPropertyName, fileNameSafeRevision ); if ( verbose ) { getLog().info( "${" + repositoryPropertyName + "} is set to \"" + repository + '\"' ); getLog().info( "${" + pathPropertyName + "} is set to \"" + path + '\"' ); getLog().info( "${" + revisionPropertyName + "} is set to \"" + revision + '\"' ); getLog().info( "${" + fileNameSafeRevisionPropertyName + "} is set to \"" + fileNameSafeRevision + '\"' ); } } catch ( SVNException e ) { throw new MojoExecutionException( e.getMessage(), e ); } } private final class StatusCollector implements ISVNStatusHandler { private long maximumRevisionNumber; private long minimumRevisionNumber; private Set<SVNStatusType> localStatusTypes; private boolean remoteChanges; private StatusCollector() { maximumRevisionNumber = Long.MIN_VALUE; minimumRevisionNumber = Long.MAX_VALUE; localStatusTypes = new HashSet<SVNStatusType>(); } public void handleStatus( SVNStatus status ) { SVNStatusType contentsStatusType = status.getContentsStatus(); localStatusTypes.add( contentsStatusType ); long revisionNumber = status.getRevision().getNumber(); if ( revisionNumber >= 0L ) { maximumRevisionNumber = Math.max( maximumRevisionNumber, revisionNumber ); } if ( revisionNumber > 0L ) { minimumRevisionNumber = Math.min( minimumRevisionNumber, revisionNumber ); } SVNStatusType propertiesStatusType = status.getPropertiesStatus(); localStatusTypes.add( propertiesStatusType ); boolean remoteStatusTypes = !SVNStatusType.STATUS_NONE.equals( status.getRemotePropertiesStatus() ) || !SVNStatusType.STATUS_NONE.equals( status.getRemoteContentsStatus() ); remoteChanges = remoteChanges || remoteStatusTypes; if ( verbose ) { StringBuilder buffer = new StringBuilder(); buffer.append( status.getContentsStatus().getCode() ).append( status.getPropertiesStatus().getCode() ); buffer.append( remoteStatusTypes ? '*' : ' ' ); buffer.append( ' ' ).append( String.format( "%6d", status.getRevision().getNumber() ) ); buffer.append( ' ' ).append( status.getFile() ); getLog().info( buffer.toString() ); } } public String getStatus( StatusCharacters statusCharacters ) { Set<SVNStatusType> tempStatusTypes = new HashSet<SVNStatusType>( localStatusTypes ); StringBuilder result = new StringBuilder(); if ( maximumRevisionNumber != Long.MIN_VALUE ) { result.append( 'r' ).append( maximumRevisionNumber ); if ( minimumRevisionNumber != maximumRevisionNumber && reportMixedRevisions ) { result.append( '-' ).append( 'r' ).append( minimumRevisionNumber ); } } if ( reportStatus ) { tempStatusTypes.remove( SVNStatusType.STATUS_NONE ); tempStatusTypes.remove( SVNStatusType.STATUS_NORMAL ); if ( !tempStatusTypes.isEmpty() ) { result.append( statusCharacters.separator ); } if ( tempStatusTypes.remove( SVNStatusType.STATUS_MODIFIED ) ) { result.append( statusCharacters.modified ); } if ( tempStatusTypes.remove( SVNStatusType.STATUS_ADDED ) ) { result.append( statusCharacters.added ); } if ( tempStatusTypes.remove( SVNStatusType.STATUS_DELETED ) ) { result.append( statusCharacters.deleted ); } if ( tempStatusTypes.remove( SVNStatusType.STATUS_UNVERSIONED ) && reportUnversioned ) { result.append( statusCharacters.unversioned ); } if ( tempStatusTypes.remove( SVNStatusType.STATUS_MISSING ) ) { result.append( statusCharacters.missing ); } if ( tempStatusTypes.remove( SVNStatusType.STATUS_REPLACED ) ) { result.append( statusCharacters.replaced ); } if ( tempStatusTypes.remove( SVNStatusType.STATUS_CONFLICTED ) ) { result.append( statusCharacters.conflicted ); } if ( tempStatusTypes.remove( SVNStatusType.STATUS_OBSTRUCTED ) ) { result.append( statusCharacters.obstructed ); } if ( tempStatusTypes.remove( SVNStatusType.STATUS_IGNORED ) && reportIgnored ) { result.append( statusCharacters.ignored ); } if ( tempStatusTypes.remove( SVNStatusType.STATUS_INCOMPLETE ) ) { result.append( statusCharacters.incomplete ); } if ( tempStatusTypes.remove( SVNStatusType.STATUS_EXTERNAL ) ) { result.append( statusCharacters.external ); } if ( !tempStatusTypes.isEmpty() ) { getLog().warn( "unprocessed svn statuses: " + tempStatusTypes ); } if ( remoteChanges && reportOutOfDate ) { result.append( statusCharacters.outOfDate ); } } return result.toString(); } } private static final class StatusCharacters { public static final StatusCharacters STANDARD = new StatusCharacters( ' ', SVNStatusType.STATUS_MODIFIED.getCode(), SVNStatusType.STATUS_ADDED.getCode(), SVNStatusType.STATUS_DELETED.getCode(), SVNStatusType.STATUS_UNVERSIONED.getCode(), SVNStatusType.STATUS_MISSING.getCode(), SVNStatusType.STATUS_REPLACED.getCode(), SVNStatusType.STATUS_CONFLICTED.getCode(), SVNStatusType.STATUS_OBSTRUCTED.getCode(), SVNStatusType.STATUS_IGNORED.getCode(), SVNStatusType.STATUS_INCOMPLETE.getCode(), SVNStatusType.STATUS_EXTERNAL.getCode(), '*' ); public static final StatusCharacters FILE_NAME_SAFE = new StatusCharacters( '-', SVNStatusType.STATUS_MODIFIED.getCode(), SVNStatusType.STATUS_ADDED.getCode(), SVNStatusType.STATUS_DELETED.getCode(), 'u', // SVNStatusType.STATUS_UNVERSIONED.getCode(), 'm', // SVNStatusType.STATUS_MISSING.getCode(), SVNStatusType.STATUS_REPLACED.getCode(), SVNStatusType.STATUS_CONFLICTED.getCode(), 'o', // SVNStatusType.STATUS_OBSTRUCTED.getCode(), SVNStatusType.STATUS_IGNORED.getCode(), 'i', // SVNStatusType.STATUS_INCOMPLETE.getCode(), SVNStatusType.STATUS_EXTERNAL.getCode(), 'd' ); public final char separator; public final char modified; public final char added; public final char deleted; public final char unversioned; public final char missing; public final char replaced; public final char conflicted; public final char obstructed; public final char ignored; public final char incomplete; public final char external; public final char outOfDate; private StatusCharacters( char separator, char modified, char added, char deleted, char unversioned, char missing, char replaced, char conflicted, char obstructed, char ignored, char incomplete, char external, char outOfDate ) { this.separator = separator; this.modified = modified; this.added = added; this.deleted = deleted; this.unversioned = unversioned; this.missing = missing; this.replaced = replaced; this.conflicted = conflicted; this.obstructed = obstructed; this.ignored = ignored; this.incomplete = incomplete; this.external = external; this.outOfDate = outOfDate; } } }
package org.almibe.codeeditor; import javafx.application.Platform; import javafx.scene.Parent; import javafx.scene.web.WebView; import java.util.Arrays; import java.util.Queue; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; public class CodeMirrorEditor implements CodeEditor { private final WebView webView; private AtomicBoolean isEditorInitialized = new AtomicBoolean(false); private final Queue<Runnable> queue = new LinkedBlockingQueue<>(); private ScheduledExecutorService executor; public CodeMirrorEditor() { webView = new WebView(); } @Override public void init(Runnable... runAfterLoading) { queue.addAll(Arrays.asList(runAfterLoading)); try { webView.getEngine().load(CodeMirrorEditor.class.getResource("codemirror/editor.html").toURI().toString()); } catch (Exception ex) { throw new RuntimeException(ex); } webView.getEngine().setOnError(event -> { throw new RuntimeException(event.getException()); }); executor = Executors.newSingleThreadScheduledExecutor(); ScheduledFuture future = executor.scheduleWithFixedDelay(new Init(), 0, 100, TimeUnit.MILLISECONDS); } public class Init implements Runnable { private final String command = "init();"; @Override public void run() { Platform.runLater(() -> { try { webView.getEngine().executeScript("CodeMirror;"); webView.getEngine().executeScript(this.command); executor.shutdown(); executor = null; while(!queue.isEmpty()) { Runnable runnable = queue.remove(); Platform.runLater(runnable); } isEditorInitialized.set(true); } catch (Exception ex) { //do nothing } }); } } @Override public String getContent() { return (String) webView.getEngine().executeScript("codeMirror.getValue();"); } @Override public void setContent(String newContent, boolean markClean) { String escapedContent = JsString.quote(newContent); Platform.runLater(() -> { webView.getEngine().executeScript("codeMirror.setValue(" + escapedContent + ");"); if (markClean) { this.markClean(); } }); } @Override public boolean isClean() { return (boolean) webView.getEngine().executeScript("codeMirror.isClean();"); } @Override public void markClean() { webView.getEngine().executeScript("codeMirror.markClean();"); } @Override public Position getCursorPosition() { String position = (String) webView.getEngine().executeScript(""); return null; } @Override public void setCursorPosition(Position position) { Platform.runLater(() -> { webView.getEngine().executeScript(""); }); } @Override public boolean isEditorInitialized() { return isEditorInitialized.get(); } @Override public Parent getWidget() { return this.webView; } @Override public boolean isReadOnly() { return (Boolean) webView.getEngine().executeScript("codeMirror.getOption('readOnly');"); } @Override public void setReadOnly(boolean readOnly) { Platform.runLater(() -> { webView.getEngine().executeScript("codeMirror.setOption('readOnly', " + readOnly + ");"); }); } @Override public String getMode() { return (String) webView.getEngine().executeScript("codeMirror.getOption('mode');"); } @Override public void setMode(String mode) { Platform.runLater(() -> { webView.getEngine().executeScript("setMode(\"" + mode + "\");"); }); } // @Override // public void includeJSModules(String[] modules, Runnable runnable) { // //TODO test this // //fetchCodeEditorObject().call("importJSModules", modules, runnable); @Override public String getTheme() { return (String) webView.getEngine().executeScript("codeMirror.getOption('theme');"); } @Override public void setTheme(String theme, String... cssFile) { String argument = "'" + theme + "'"; if(cssFile != null && cssFile.length > 0) { String cssFileArgument = ""; for(String file : cssFile) { cssFileArgument += ", '" + file + "'"; } argument += cssFileArgument; } final String finalArg = argument; Platform.runLater(() -> { webView.getEngine().executeScript("setTheme(" + finalArg + ");"); }); } @Override public void runWhenReady(Runnable runnable) { // if(isEditorInitialized) { // runnable.run(); // } else { queue.add(runnable); handleQueue(); } private void handleQueue() { if(isEditorInitialized.get()) { while(!queue.isEmpty()) { Runnable runnable = queue.remove(); Platform.runLater(runnable); } } } }
package org.analogweb.core.response; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import org.analogweb.Renderable; import org.analogweb.Headers; import org.analogweb.RenderableHolder; import org.analogweb.RequestContext; import org.analogweb.Response; import org.analogweb.ResponseContext; import org.analogweb.WebApplicationException; import org.analogweb.util.StringUtils; /** * @author snowgoose */ public enum HttpStatus implements Renderable, RenderableHolder { CONTINUE(100,"Continue"), SWITCHING_PROTOCOLS(101,"Switching Protocols"), PROCESSING(102,"Processing"), OK(200,"OK"), CREATED(201,"Created"), ACCEPTED(202,"Accepted"), NON_AUTHORITATIVE_INFORMATION(203,"Non-Authoritative Information"), NO_CONTENT(204,"No Content"), RESET_CONTENT(205,"Reset Content"), PARTIAL_CONTENT(206,"Partial Content"), MULTI_STATUS(207,"Multi Status"), ALREADY_REPORTED(208,"Already Reported"), IM_USED(226,"IM Used"), MULTIPLE_CHOICES(300,"Multiple Choices"), MOVED_PERMANENTLY(301,"Moved Permanently"), FOUND(302,"Found"), SEE_OTHER(303,"See Other"), NOT_MODIFIED(304,"Not Modified"), USE_PROXY(305,"Use Proxy"), TEMPORARY_REDIRECT(307,"Temporary Redirect"), BAD_REQUEST(400,"Bad Request"), UNAUTHORIZED(401,"Unauthorized"), PAYMENT_REQUIRED(402,"Payment Required"), FORBIDDEN(403,"Forbidden"), NOT_FOUND(404,"Not Found"), METHOD_NOT_ALLOWED(405,"Method Not Allowed"), NOT_ACCEPTABLE(406,"Not Acceptable"), PROXY_AUTHENTICATION_REQUIRED(407,"Proxy Authentication Required"), REQUEST_TIMEOUT(408,"Request Timeout"), CONFLICT(409,"Conflict"), GONE(410,"Gone"), LENGTH_REQUIRED(411,"Length Required"), PRECONDITION_FAILED(412,"Precondition Failed"), REQUEST_ENTITY_TOO_LARGE(413,"Payload Too Large"), REQUEST_URI_TOO_LONG(414,"URI Too Long"), UNSUPPORTED_MEDIA_TYPE(415,"Unsupported Media Type"), REQUESTED_RANGE_NOT_SATISFIABLE(416,"Range Not Satisfiable"), EXPECTATION_FAILED(417,"Expectation Failed"), INSUFFICIENT_SPACE_ON_RESOURCE(419,"Insufficient Space On Resource"), METHOD_FAILURE(420,"Method Failure"), DESTINATION_LOCKED(421,"Destination Locked"), UNPROCESSABLE_ENTITY(422,"Unprocessable Entity"), LOCKED(423,"Locked"), FAILED_DEPENDENCY(424,"Failed Dependency"), UPGRADE_REQUIRED(426,"Upgrade Required"), INTERNAL_SERVER_ERROR(500,"Internal Server Error"), NOT_IMPLEMENTED(501,"Not Implemented"), BAD_GATEWAY(502,"Bad Gateway"), SERVICE_UNAVAILABLE(503,"Service Unavailable"), GATEWAY_TIMEOUT(504,"Gateway Timeout"), HTTP_VERSION_NOT_SUPPORTED(505,"HTTP Version Not Supported"), VARIANT_ALSO_NEGOTIATES(506,"Variant Also Negotiates"), INSUFFICIENT_STORAGE(507,"Insufficient Storage"), LOOP_DETECTED(508,"Loop Detected"), NOT_EXTENDED(510,"Not Extended"); private int statusCode; private String phrase; private String reason; private Map<String, String> responseHeaders; private Renderable actuallyRenderable; HttpStatus(final int statusCode,final String phrase) { this.statusCode = statusCode; this.phrase = phrase; } @Override public Response render(RequestContext context, ResponseContext responseContext) throws IOException, WebApplicationException { String reason = getReason(); Response response = Response.EMPTY; if (StringUtils.isNotEmpty(reason)) { response = Text.with(reason).render(context, responseContext); } else { Renderable preRenderDirection = getRenderable(); if (preRenderDirection != null) { response = preRenderDirection.render(context, responseContext); } } Headers headers = responseContext.getResponseHeaders(); Map<String, String> headersMap = getResponseHeaders(); if (headersMap != null) { for (Entry<String, String> e : headersMap.entrySet()) { headers.putValue(e.getKey(), e.getValue()); } } responseContext.setStatus(getStatusCode()); return response; } public static HttpStatus valueOf(int statusCode) { for (HttpStatus status : values()) { if (statusCode == status.getStatusCode()) { return status; } } // TODO replace message code. throw new IllegalArgumentException("invalid http status code " + statusCode); } public int getStatusCode() { return this.statusCode; } public String getPhrase() { return this.phrase; } public String getReason() { return this.reason; } public HttpStatus byReasonOf(String reason) { this.reason = reason; return this; } public HttpStatus withHeader(Map<String, String> responseHeaders) { this.responseHeaders = responseHeaders; return this; } public Map<String, String> getResponseHeaders() { return this.responseHeaders; } public HttpStatus with(Renderable direction) { this.actuallyRenderable = direction; return this; } @Override public Renderable getRenderable() { return this.actuallyRenderable; } }
package yuku.alkitab.yes; import android.util.Log; import java.io.FileInputStream; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import yuku.alkitab.yes.YesFile.PericopeData.Entry; import yuku.bintex.BintexWriter; public class YesFile { private static final byte FILE_VERSI = 0x01; private static final String TAG = YesFile.class.getSimpleName(); byte[] FILE_HEADER = {(byte) 0x98, 0x58, 0x0d, 0x0a, 0x00, 0x5d, (byte) 0xe0, FILE_VERSI}; public Seksi[] xseksi; public interface Seksi { byte[] nama(); IsiSeksi isi(); } public abstract class SeksiBernama implements Seksi { private byte[] nama; public SeksiBernama(String nama) { try { this.nama = nama.getBytes("ascii"); //$NON-NLS-1$ } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override final public byte[] nama() { return nama; } } public interface IsiSeksi { void toBytes(BintexWriter writer) throws Exception; } public static abstract class InfoEdisi implements IsiSeksi { public int versi; // 1; 2 tambah encoding dan keterangan public String nama; public String shortName; public String longName; public String keterangan; public String locale; public int nkitab; public int perikopAda; // 0=ga ada, selain 0: nomer versi perikopIndex dan perikopBlok_ public int encoding; // 1 = ascii; 2 = utf-8 @Override public void toBytes(BintexWriter writer) throws Exception { writer.writeShortString("versi"); //$NON-NLS-1$ writer.writeInt(versi); if (nama != null) { writer.writeShortString("nama"); //$NON-NLS-1$ writer.writeShortString(nama); } writer.writeShortString("judul"); //$NON-NLS-1$ writer.writeShortString(longName); if (shortName != null) { writer.writeShortString("shortName"); //$NON-NLS-1$ writer.writeShortString(shortName); } writer.writeShortString("keterangan"); //$NON-NLS-1$ writer.writeLongString(keterangan); writer.writeShortString("nkitab"); //$NON-NLS-1$ writer.writeInt(nkitab); writer.writeShortString("perikopAda"); //$NON-NLS-1$ writer.writeInt(perikopAda); writer.writeShortString("encoding"); // mulai versi 2 ada. //$NON-NLS-1$ writer.writeInt(encoding); if (locale != null) { writer.writeShortString("locale"); writer.writeShortString(locale); } writer.writeShortString("end"); //$NON-NLS-1$ } } public static class Kitab { public int versi; // 1; 2 mulai ada pdbBookNumber public int pos; public int pdbBookNumber; public String nama; public String judul; public int npasal; public int[] nayat; public int ayatLoncat; public int[] pasal_offset; public int encoding; public int offset; public void toBytes(BintexWriter writer) throws Exception { writer.writeShortString("versi"); //$NON-NLS-1$ writer.writeInt(versi); writer.writeShortString("pos"); //$NON-NLS-1$ writer.writeInt(pos); writer.writeShortString("nama"); //$NON-NLS-1$ writer.writeShortString(nama); writer.writeShortString("judul"); //$NON-NLS-1$ writer.writeShortString(judul); writer.writeShortString("npasal"); //$NON-NLS-1$ writer.writeInt(npasal); writer.writeShortString("nayat"); //$NON-NLS-1$ for (int a: nayat) { writer.writeUint8(a); } writer.writeShortString("ayatLoncat"); //$NON-NLS-1$ writer.writeInt(ayatLoncat); writer.writeShortString("pasal_offset"); //$NON-NLS-1$ for (int a: pasal_offset) { writer.writeInt(a); } if (encoding != 0) { writer.writeShortString("encoding"); //$NON-NLS-1$ writer.writeInt(encoding); } writer.writeShortString("offset"); //$NON-NLS-1$ writer.writeInt(offset); if (pdbBookNumber != 0) { writer.writeShortString("pdbBookNumber"); //$NON-NLS-1$ writer.writeInt(pdbBookNumber); } writer.writeShortString("end"); //$NON-NLS-1$ } public static void nullToBytes(BintexWriter writer) throws Exception { writer.writeShortString("end"); //$NON-NLS-1$ } } public static class InfoKitab implements IsiSeksi { public Kitab[] xkitab; @Override public void toBytes(BintexWriter writer) throws Exception { for (Kitab kitab: xkitab) { if (kitab != null) { kitab.toBytes(writer); } else { Kitab.nullToBytes(writer); } } } } public static class Teks implements IsiSeksi { private final String encoding; public Teks(String encoding) { this.encoding = encoding; } int ayatLoncat = 0; public String[] xisi; @Override public void toBytes(BintexWriter writer) throws Exception { if (ayatLoncat != 0) { throw new RuntimeException("ayatLoncat ga 0"); //$NON-NLS-1$ } for (String isi: xisi) { writer.writeRaw(isi.getBytes(encoding)); writer.writeUint8('\n'); } } } public static class NemplokSeksi implements IsiSeksi { private String nf; public NemplokSeksi(String nf) { this.nf = nf; } @Override public void toBytes(BintexWriter writer) throws Exception { FileInputStream in = new FileInputStream(nf); byte[] b = new byte[10000]; while (true) { int r = in.read(b); if (r <= 0) break; writer.writeRaw(b, 0, r); } in.close(); } } public static class PerikopBlok implements IsiSeksi { private final PericopeData data; public PerikopBlok(PericopeData data) { this.data = data; } @Override public void toBytes(BintexWriter writer) throws Exception { int offsetAwalSeksi = writer.getPos(); for (Entry entry: data.entries) { int offsetAwalEntri = writer.getPos(); /* * Blok { * uint8 versi = 2 * lstring judul * uint8 nparalel * sstring[nparalel] xparalel * } * * // OR * * Blok { * uint8 versi = 3 * autostring judul * uint8 nparalel * autostring[nparalel] xparalel * } */ writer.writeUint8(entry.block.version); // versi if (entry.block.version == 2) { writer.writeLongString(entry.block.title); // judul writer.writeUint8(entry.block.parallels == null? 0: entry.block.parallels.size()); // nparalel if (entry.block.parallels != null) { // xparalel for (String paralel: entry.block.parallels) { writer.writeShortString(paralel); } } } else if (entry.block.version == 3) { writer.writeAutoString(entry.block.title); // judul writer.writeUint8(entry.block.parallels == null? 0: entry.block.parallels.size()); // nparalel if (entry.block.parallels != null) { // xparalel for (String paralel: entry.block.parallels) { writer.writeAutoString(paralel); } } } else { throw new RuntimeException("pericope entry.block.version " + entry.block.version + " not supported yet"); } entry.block._offset = offsetAwalEntri - offsetAwalSeksi; } } } public static class PerikopIndex implements IsiSeksi { private final PericopeData data; public PerikopIndex(PericopeData data) { this.data = data; } @Override public void toBytes(BintexWriter writer) throws Exception { writer.writeInt(data.entries.size()); // nentri for (Entry entry: data.entries) { if (entry.block._offset == -1) { throw new RuntimeException("offset entri perikop belum dihitung"); // $NON-NLS-1$ } writer.writeInt(entry.ari); writer.writeInt(entry.block._offset); } } } public static class PericopeData { public static class Entry { public int ari; public Block block; } public static class Block { public int version; public String title; public List<String> parallels; int _offset = -1; public void addParallel(String parallel) { if (parallels == null) parallels = new ArrayList<String>(); parallels.add(parallel); } } public List<Entry> entries; public void addEntry(Entry e) { if (entries == null) entries = new ArrayList<Entry>(); entries.add(e); } } public void output(RandomAccessFile file) throws Exception { RandomOutputStream ros = new RandomOutputStream(file); BintexWriter os2 = new BintexWriter(ros); os2.writeRaw(FILE_HEADER); long pos = file.getFilePointer(); for (Seksi seksi: xseksi) { pos = file.getFilePointer(); { byte[] nama = seksi.nama(); if (bisaLog()) Log.d(TAG, "[pos=" + pos + "] tulis nama seksi: " + new String(nama)); //$NON-NLS-1$//$NON-NLS-2$ os2.writeRaw(nama); } pos = file.getFilePointer(); { byte[] palsu = {-1, -1, -1, -1}; if (bisaLog()) Log.d(TAG, "[pos=" + pos + "] tulis placeholder ukuran"); //$NON-NLS-1$ //$NON-NLS-2$ os2.writeRaw(palsu); } int posSebelumIsi = os2.getPos(); if (bisaLog()) Log.d(TAG, "[pos=" + file.getFilePointer() + "] tulis isi seksi"); //$NON-NLS-1$ //$NON-NLS-2$ seksi.isi().toBytes(os2); int posSesudahIsi = os2.getPos(); int ukuranIsi = posSesudahIsi - posSebelumIsi; if (bisaLog()) Log.d(TAG, "[pos=" + file.getFilePointer() + "] isi seksi selesai ditulis, sebesar " + ukuranIsi); //$NON-NLS-1$//$NON-NLS-2$ long posUntukMelanjutkan = file.getFilePointer(); { file.seek(pos); if (bisaLog()) Log.d(TAG, "[pos=" + pos + "] tulis ukuran: " + ukuranIsi); //$NON-NLS-1$//$NON-NLS-2$ os2.writeInt(ukuranIsi); } file.seek(posUntukMelanjutkan); } pos = file.getFilePointer(); if (bisaLog()) Log.d(TAG, "[pos=" + pos + "] tulis penanda tidak ada seksi lagi (____________)"); //$NON-NLS-1$//$NON-NLS-2$ os2.writeRaw("____________".getBytes("ascii")); //$NON-NLS-1$ //$NON-NLS-2$ os2.close(); pos = file.getFilePointer(); if (bisaLog()) Log.d(TAG, "[pos=" + pos + "] selesai"); //$NON-NLS-1$//$NON-NLS-2$ } static Boolean bisaLog = null; private static boolean bisaLog() { if (bisaLog == null) { try { Class.forName("android.util.Log"); bisaLog = true; } catch (Exception e) { bisaLog = false; } } return bisaLog; } }
package org.foobar.minesweeper.model; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkState; import com.google.common.eventbus.EventBus; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import static java.util.EnumSet.of; import java.util.List; import java.util.Queue; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.Logger; import org.foobar.minesweeper.event.BoardChangeEvent; import org.foobar.minesweeper.event.CellChangeEvent; import static org.foobar.minesweeper.model.SquareType.FLAG; /** * * @author User */ public final class Minefield { public enum State { /** * The game was reset. */ START, /** * The game is in progress. */ PLAYING, /** * The game has been lost. */ LOST, /** * The game has been won. */ WON; } static class Entry { final int row; final int column; final Square cell; Entry(int row, int column, Square cell) { this.row = row; this.column = column; this.cell = cell; } } private static final EnumSet<State> playStates = of(State.START, State.PLAYING); private static final Logger logger = Logger.getLogger("org.foobar.minesweeper.model.minefield"); private final int rows; private final int columns; private final int mines; private final Square[][] table; private final EventBus eventBus; private final Queue<Entry> queue = new ArrayDeque<>(200); private State gameState; private boolean isGameOver; private int emptySquares; /** * * @param rows * @param columns * @param mines * @param eventBus */ public Minefield(EventBus eventBus, int rows, int columns, int mines) { this.eventBus = eventBus; this.rows = rows; this.columns = columns; this.mines = mines; table = new Square[rows + 2][columns + 2]; initialize(); log(); } public Minefield(EventBus eventBus) { this(eventBus, 10, 10, 10); } public boolean canFlag(int row, int column) { return !isGameOver && !getSquareAt(row, column).hasMineCount(); } /** * * @param row * @param column * @return */ public boolean canReveal(int row, int column) { return !isGameOver && getSquareAt(row, column).isRevealable(); } /** * * * @return */ public boolean isGameOver() { return isGameOver; } /** * Gets the current game state. * * @return the current game state. */ public State getGameState() { return gameState; } /** * * @param row * @param column * @return */ public SquareType getSquareAt(int row, int column) { checkElementIndex(row, rows); checkElementIndex(column, columns); return table[row + 1][column + 1].getType(); } /** * Gets the number of columns in the minefield. * * @return the number of columns in the minefield. */ public int getColumnCount() { return columns; } /** * Gets number of mines * * @return the mines */ public int getMines() { return mines; } /** * Gets number of rows * * @return number of rows */ public int getRowCount() { return rows; } public void restart() { initialize(); eventBus.post(BoardChangeEvent.INSTANCE); } /** * Reveals a cell at row and column. If the cell is a mine, the game is * over. If the game is over or the cell is flagged, the method returns. * * <p>Calling this method repeatedly with the same row and column will no * have no effect until restart() is called.</p> * * @param row the row whose cell will be revealed. * @param column the column whose cell will be revealed. * * @throws IndexOutOfBoundsException if (@code row} is negative or greater * than or equal to {@code getRowCount()} * @throws IndexOutOfBoundsException if (@code column) is negative or greater * than or equal to {@code getColumnCount()} */ public void reveal(int row, int column) { checkElementIndex(row, rows); checkElementIndex(column, columns); row++; column++; Square cell = table[row][column]; if (!playStates.contains(gameState) || !cell.isRevealable()) { return; } reveal(new Entry(row, column, cell)); } /** * * @param row the row whose flag will be toggled. * @param column the column whose flag will be toggled. * * @throws IndexOutOfBoundsException if (@code row} is negative or greater * than or equal to {@code getRowCount()} * @throws IndexOutOfBoundsException if (@code column) is negative or greater * than or equal to {@code getColumnCount()} */ public void revealNearby(int row, int column) { Entry entry = getEntry(row, column); checkState(playStates.contains(gameState) && entry.cell.getType().hasMineCount()); int nearbyFlags = 0; Iterable<Entry> neighbors = findNeighbors(entry.row, entry.column); for (Entry i : neighbors) { if (i.cell.getType() == FLAG) { nearbyFlags++; } } if (nearbyFlags == entry.cell.getType().getMineCount()) { for (Entry i : neighbors) { if (i.cell.isRevealable()) { reveal(entry); } } } } /** * Toggles the flag state of the cell at row and column. If the game is over * or the cell cannot be flagged (or unflagged), the method returns. * * @param row the row whose flag will be toggled. * @param column the column whose flag will be toggled. * * @throws IndexOutOfBoundsException if (@code row} is negative or greater * than or equal to {@code getRowCount()} * @throws IndexOutOfBoundsException if (@code column) is negative or greater * than or equal to {@code getColumnCount()} */ public void toggleFlag(int row, int column) { checkElementIndex(row, rows); checkElementIndex(column, columns); Square cell = table[row + 1][column + 1]; cell.toggleFlag(); eventBus.post(new CellChangeEvent(row, column, cell.getType())); } private Entry getEntry(int row, int column) { checkElementIndex(row, rows); checkElementIndex(column, columns); row++; column++; return new Entry(row, column, table[row][column]); } private void initialize() { emptySquares = rows * columns; gameState = State.START; isGameOver = false; Square edge = new Square(); edge.revealNumber(); for (int i = 1; i < rows + 1; i++) { table[i][0] = new Square(edge); table[i][columns + 1] = new Square(edge); for (int j = 1; j < columns + 1; j++) { table[i][j] = new Square(); } } for (int i = 0; i < columns + 2; i++) { table[0][i] = new Square(edge); } for (int i = 0; i < columns + 2; i++) { table[rows + 1][i] = new Square(edge); } } private void reveal(Entry e) { if (gameState == State.START) { gameState = State.PLAYING; plantMines(e.row, e.column); } if (e.cell.isMine()) { e.cell.setHitMine(); for (int r = 1; r < rows + 1; r++) { for (int c = 1; c < columns + 1; c++) { table[r][c].onGameLost(); } } isGameOver = true; gameState = State.LOST; eventBus.post(BoardChangeEvent.INSTANCE); eventBus.post(gameState); } else { assert queue.isEmpty(); queue.add(e); Entry pos; while ((pos = queue.poll()) != null) { pos.cell.revealNumber(); enqueueNearby(pos); } eventBus.post(BoardChangeEvent.INSTANCE); } } private void enqueueNearby(Entry pos) { if (pos.cell.getType().getMineCount() == 0) { for (Entry value : findNeighbors(pos.row, pos.column)) { if (!value.cell.getType().hasMineCount()) { queue.add(value); } } } } private Iterable<Entry> findNeighbors(int row, int column) { assert row > 0 && row <= rows : "invalid row: " + row; assert column > 0 && column <= columns : "invalid column: " + column; List<Entry> neighbors = new ArrayList<>(8); for(int c = column - 1; c <= column + 1; c++) { neighbors.add(new Entry(row + 1, c, table[row + 1][c])); } for(int c = column - 1; c <= column + 1; c++) { neighbors.add(new Entry(row - 1, c, table[row - 1][c])); } neighbors.add(new Entry(row, column - 1, table[row][column - 1])); neighbors.add(new Entry(row, column + 1, table[row][column + 1])); return neighbors; } private void plantMines(int exceptRow, int exceptColumn) { List<Entry> list = new ArrayList<>(rows * columns); for (int r = 1; r < rows + 1; r++) { for (int c = 1; c < columns + 1; c++) { if (exceptRow != r || exceptColumn != c) { list.add(new Entry(r, c, table[r][c])); } } } Collections.shuffle(list); for (Entry origin : list.subList(0, mines)) { origin.cell.setMine(); for (Entry i : findNeighbors(origin.row, origin.column)) { i.cell.incrementMineCount(); } } for (Entry i : list) { if (!i.cell.hasNearbyMines() || !i.cell.isMine()) { emptySquares } } } private void log() { logger.addHandler(new ConsoleHandler()); logger.setLevel(Level.ALL); StringBuilder builder = new StringBuilder(); builder.append("DEBUG\n"); for (Square[] row : table) { for (Square cell : row) { builder.append(cell.isMine() ? '*' : '.'); } builder.append("\n"); } logger.info(builder.toString()); builder = new StringBuilder(); for (Square[] row : table) { for (Square cell : row) { builder.append(cell.debugNumbers()); builder.append(' '); } builder.append("\n"); } logger.info(builder.toString()); builder = new StringBuilder(); builder.append("DEBUG\n"); for (Square[] row : table) { for (Square cell : row) { builder.append(cell.getType().getMineCountOr(2)); } builder.append("\n"); } System.out.println(builder.toString()); } private Square lookupCell(int row, int column) { return table[row + 1][column + 1]; } }
package org.jfree.chart.plot; /** * Used to indicate the style for the lines linking pie sections to their * corresponding labels. * * @since 1.0.10 */ public enum PieLabelLinkStyle { /** STANDARD. */ STANDARD, /** QUAD_CURVE. */ QUAD_CURVE, /** CUBIC_CURVE. */ CUBIC_CURVE }
package org.komamitsu.fluency.sender; import org.komamitsu.fluency.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicReference; public class TCPSender implements Sender { private static final Logger LOG = LoggerFactory.getLogger(TCPSender.class); private static final Charset CHARSET_FOR_ERRORLOG = Charset.forName("UTF-8"); private final AtomicReference<SocketChannel> channel = new AtomicReference<SocketChannel>(); private final String host; private final int port; private final byte[] optionBuffer = new byte[256]; private final AckTokenSerDe ackTokenSerDe = new MessagePackAckTokenSerDe(); public String getHost() { return host; } public int getPort() { return port; } public TCPSender(String host, int port) throws IOException { this.port = port; this.host = host; } public TCPSender(int port) throws IOException { this(Constants.DEFAULT_HOST, port); } public TCPSender(String host) throws IOException { this(host, Constants.DEFAULT_PORT); } public TCPSender() throws IOException { this(Constants.DEFAULT_HOST, Constants.DEFAULT_PORT); } private SocketChannel getOrOpenChannel() throws IOException { if (channel.get() == null) { SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(host, port)); socketChannel.socket().setTcpNoDelay(true); socketChannel.socket().setSoTimeout(5000); channel.set(socketChannel); } return channel.get(); } @Override public synchronized void send(ByteBuffer data) throws IOException { try { LOG.trace("send(): sender.host={}, sender.port={}", getHost(), getPort()); getOrOpenChannel().write(data); } catch (IOException e) { channel.set(null); throw e; } } @Override public synchronized void send(List<ByteBuffer> dataList) throws IOException { for (ByteBuffer data : dataList) { send(data); } } @Override public synchronized void sendWithAck(List<ByteBuffer> dataList, byte[] ackToken) throws IOException { send(dataList); send(ByteBuffer.wrap(ackTokenSerDe.pack(ackToken))); ByteBuffer byteBuffer = ByteBuffer.wrap(optionBuffer); // TODO: Set timeout getOrOpenChannel().read(byteBuffer); byte[] unpackedToken = ackTokenSerDe.unpack(optionBuffer); if (!Arrays.equals(ackToken, unpackedToken)) { throw new UnmatchedAckException("Ack tokens don't matched: expected=" + new String(ackToken, CHARSET_FOR_ERRORLOG) + ", got=" + new String(unpackedToken, CHARSET_FOR_ERRORLOG)); } } @Override public synchronized void close() throws IOException { SocketChannel socketChannel; if ((socketChannel = channel.getAndSet(null)) != null) { socketChannel.close(); } } public static class UnmatchedAckException extends IOException { public UnmatchedAckException(String message) { super(message); } } }
package org.mybatis.jpetstore.domain; import java.io.Serializable; import java.math.BigDecimal; public class Calculate implements Serializable { public void hello() { System.out.println("JPET Store Application"); System.out.println("Class name: Calculate.java"); System.out.println("Hello World"); System.out.println("Making a new Entry at Sun Mar 12 11:00:00 UTC 2017"); System.out.println("Sun Mar 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016"); System.out.println("Fri Dec 2 12:52:58 UTC 2016"); } } //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck
package org.ndexbio.common.access; import org.ndexbio.common.exceptions.NdexException; import org.ndexbio.orientdb.NdexSchemaManager; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.dictionary.ODictionary; import com.orientechnologies.orient.core.record.impl.ODocument; public class NdexDatabase { private NdexAOrientDBConnectionPool pool; private ODatabaseDocumentTx ndexDatabase; // this connection is used for transactions in this database object. private ODictionary dictionary; private static final String sequenceKey="NdexSeq"; private static final String seqField= "f1"; private int batchCounter; private long internalCounterBase; private static final int blockSize = 50; private ODocument vdoc; static private String URIPrefix = null; public NdexDatabase(String HostURI) throws NdexException { pool = NdexAOrientDBConnectionPool.getInstance(); ndexDatabase = pool.acquire(); dictionary = ndexDatabase.getDictionary(); NdexSchemaManager.INSTANCE.init(ndexDatabase); vdoc = (ODocument) dictionary.get(sequenceKey); if (vdoc == null ) { ndexDatabase.commit(); internalCounterBase = 1; vdoc = new ODocument(seqField, internalCounterBase); // + blockSize); // ids start with 1. vdoc = vdoc.save(); dictionary.put(sequenceKey, vdoc); ndexDatabase.commit(); } batchCounter=blockSize; URIPrefix = HostURI; } static public String getURIPrefix () { return URIPrefix; } public synchronized long getNextId() { if ( batchCounter == blockSize) { vdoc.reload(); internalCounterBase = vdoc.field(seqField); batchCounter = 0 ; vdoc = vdoc.field(seqField, internalCounterBase + blockSize).save(); dictionary.put(sequenceKey, vdoc); commit(); // System.out.println("New batch in id sequence:" + internalCounterBase ); } long rvalue = internalCounterBase + batchCounter; batchCounter++; return rvalue; } public synchronized void resetIdCounter() { vdoc.field(seqField,0); } public void close () { // vdoc.save(); ndexDatabase.commit(); ndexDatabase.close(); } public void commit() { ndexDatabase.commit(); // ndexDatabase.begin(); } public ODatabaseDocumentTx getAConnection() { return pool.acquire(); } // public ODatabaseDocumentTx getTransactionConnection() {return ndexDatabase;} }
package org.ndexbio.rest.client; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.UUID; import org.apache.commons.codec.binary.Base64; import org.ndexbio.model.object.NdexObject; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; /** * Simple REST Client for NDEX web service. * * TODO: support user authentication! * */ public class NdexRestClient { // for authorization String _username = null; String _password = null; UUID _userUid = null; String _baseroute = null; public NdexRestClient(String username, String password, String route) { super(); System.out.println("Starting init of NDExRestClient "); _baseroute = route; _username = username; _password = password; System.out.println("init of NDExRestClient with " + _baseroute + " " + _username + " " + password); } public NdexRestClient(String username, String password) { super(); System.out.println("Starting init of NDExRestClient "); // Default to localhost, standard location for testing _baseroute = "http://localhost:8080/ndexbio-rest"; _username = username; _password = password; System.out.println("init of NDExRestClient with " + _baseroute + " " + _username + " " + password); } private void addBasicAuth(HttpURLConnection con) { String credentials = _username + ":" + _password; String basicAuth = "Basic " + new String(new Base64().encode(credentials.getBytes())); con.setRequestProperty("Authorization", basicAuth); } public void setCredential(String username, String password) { this._username = username; this._password = password; } /* * GET */ public JsonNode get(final String route, final String query) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; try { ObjectMapper mapper = new ObjectMapper(); con = getReturningConnection(route, query); input = con.getInputStream(); JsonNode result = null; if (null != input) { result = mapper.readTree(input); return result; } throw new IOException("failed to connect to ndex"); } finally { if ( input != null) input.close(); if ( con != null) con.disconnect(); } } public NdexObject getNdexObject( final String route, final String query, final Class<? extends NdexObject> mappedClass) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; try { ObjectMapper mapper = new ObjectMapper(); con = getReturningConnection(route, query); input = con.getInputStream(); if (null != input){ return mapper.readValue(input, mappedClass); } throw new IOException("failed to connect to ndex"); } finally { if (null != input) input.close(); if ( con != null ) con.disconnect(); } } public List<? extends NdexObject> getNdexObjectList( final String route, final String query, final Class<? extends NdexObject> mappedClass) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; try { ObjectMapper mapper = new ObjectMapper(); JavaType type = mapper.getTypeFactory(). constructCollectionType(List.class, mappedClass); con = getReturningConnection(route, query); input = con.getInputStream(); if (null != input){ return mapper.readValue(input, type); } throw new IOException("failed to connect to ndex"); } finally { if (null != input) input.close(); if ( con != null) con.disconnect(); } } public HttpURLConnection getReturningConnection(final String route, final String query) throws IOException { URL request = new URL(_baseroute + route + query); System.out.println("GET (returning connection) URL = " + request); HttpURLConnection con = (HttpURLConnection) request.openConnection(); addBasicAuth(con); return con; } /* * PUT */ public JsonNode put( final String route, final JsonNode putData) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; try { ObjectMapper mapper = new ObjectMapper(); con = putReturningConnection(route, putData); input = con.getInputStream(); // TODO 401 error handling return mapper.readTree(input); } finally { if (null != input) input.close(); if ( con != null ) con.disconnect(); } } public NdexObject putNdexObject( final String route, final JsonNode putData, final Class<? extends NdexObject> mappedClass) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; try { ObjectMapper mapper = new ObjectMapper(); con = putReturningConnection(route, putData); input = con.getInputStream(); if (null != input){ return mapper.readValue(input, mappedClass); } throw new IOException("failed to connect to ndex"); } finally { if (null != input) input.close(); if ( con != null) con.disconnect(); } } public HttpURLConnection putReturningConnection(final String route, final Object putData) throws JsonProcessingException, IOException { URL request = new URL(_baseroute + route); System.out.println("PUT (returning connection) URL = " + request); ObjectMapper objectMapper = new ObjectMapper(); HttpURLConnection con = (HttpURLConnection) request.openConnection(); addBasicAuth(con); con.setDoOutput(true); con.setRequestMethod("PUT"); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Accept", "application/json"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); String putDataString = objectMapper.writeValueAsString(putData); out.write(putDataString); out.flush(); out.close(); return con; } /* * POST */ public JsonNode post( final String route, final JsonNode postData) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; try { ObjectMapper mapper = new ObjectMapper(); con = postReturningConnection(route, postData); input = con.getInputStream(); JsonNode result = null; if (null != input) { result = mapper.readTree(input); return result; } throw new IOException("failed to connect to ndex"); } finally { if (null != input) input.close(); if ( con != null) con.disconnect(); } } public NdexObject postNdexObject( final String route, final JsonNode postData, final Class<? extends NdexObject> mappedClass) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; try { ObjectMapper mapper = new ObjectMapper(); con = postReturningConnection(route, postData); input = con.getInputStream(); if (null != input){ return mapper.readValue(input, mappedClass); } throw new IOException("failed to connect to ndex"); } finally { if (null != input) input.close(); if ( con != null ) con.disconnect(); } } public List <? extends NdexObject> postNdexObjectList( final String route, final JsonNode postData, final Class<? extends NdexObject> mappedClass) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; try { ObjectMapper mapper = new ObjectMapper(); JavaType type = mapper.getTypeFactory(). constructCollectionType(List.class, mappedClass); con = postReturningConnection(route, postData); input = con.getInputStream(); if (null != input){ return mapper.readValue(input, type); } throw new IOException("failed to connect to ndex"); } finally { if (null != input) input.close(); if ( con != null ) con.disconnect(); } } public HttpURLConnection postReturningConnection(String route, JsonNode postData) throws JsonProcessingException, IOException { URL request = new URL(_baseroute + route); System.out.println("POST (returning connection) URL = " + request); HttpURLConnection con = (HttpURLConnection) request.openConnection(); String postDataString = postData.toString(); con.setDoOutput(true); con.setDoInput(true); con.setInstanceFollowRedirects(false); con.setRequestMethod("POST"); // con.setRequestProperty("Content-Type", // "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("charset", "utf-8"); con.setRequestProperty("Content-Length", "" + Integer.toString(postDataString.getBytes().length)); con.setUseCaches(false); addBasicAuth(con); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(postDataString); wr.flush(); wr.close(); return con; } /* * DELETE */ public JsonNode delete(final String route) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; ObjectMapper mapper = new ObjectMapper(); URL request = new URL(_baseroute + route); try { con = (HttpURLConnection) request.openConnection(); addBasicAuth(con); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestMethod("DELETE"); input = con.getInputStream(); JsonNode result = null; if (null != input) { result = mapper.readTree(input); return result; } throw new IOException("failed to connect to ndex"); } finally { if (null != input) input.close(); if ( con != null) con.disconnect(); } } /* * Getters and Setters */ public String getUsername() { return _username; } public void setUsername(String _username) { this._username = _username; } public String getPassword() { return _password; } public void setPassword(String _password) { this._password = _password; } public String getBaseroute() { return _baseroute; } public void setBaseroute(String _baseroute) { this._baseroute = _baseroute; } public UUID getUserUid() { return _userUid; } public void setUserUid(UUID _userUid) { this._userUid = _userUid; } }
package org.nsponline.calendar.misc; import org.nsponline.calendar.store.*; import javax.servlet.http.HttpServletRequest; import java.io.PrintWriter; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; /** * Main method to track general info about a resort (patrol) Not backed by a table. But stores * general display info about all patrols * @author Steve Gledhill */ @SuppressWarnings({"SqlNoDataSourceInspection", "AccessStaticViaInstance", "SqlDialectInspection"}) public class PatrolData { private static final int MIN_LOG_LEVEL = Logger.DEBUG; private static String MYSQL_ADDRESS = "ip-172-31-62-158.ec2.internal"; //private ip PRODUCTION. must match /etc/my.cnf public final static Boolean USING_TESTING_ADDRESS = false; //used in MonthlyCalendar will add a "TESTING" to the calendar page static { //noinspection ConstantConditions if (USING_TESTING_ADDRESS) { MYSQL_ADDRESS = "ip-172-31-62-143.ec2.internal"; //private ip TESTING. must match /etc/my.cnf } } // private final static String MYSQL_ADDRESS = "127.0.0.1"; //local laptop. must match /etc/my.cnf private final static String backDoorFakeFirstName = "System"; private final static String backDoorFakeLastName = "Administrator"; private final static String backDoorEmail = "Steve@Gledhills.com"; static public HashMap<String, ResortData> resortMap = new HashMap<String, ResortData>(); static private final int IMG_HEIGHT = 80; static { resortMap.put("Afton", new ResortData("Afton", "Afton Alps", null, "http: resortMap.put("AlpineMt", new ResortData("AlpineMt", "Alpine Mt", null, "http: resortMap.put("Andes", new ResortData("Andes", "Andes Tower Hills", null, "http: resortMap.put("BigHorn", new ResortData("BigHorn", "Big Horn", "BigHornSkiPatrolDirector@gmail.com", "https: resortMap.put("Brighton", new ResortData("Brighton", "Brighton", "brightonskipatrol@gmail.com", "http: resortMap.put("BuenaVista", new ResortData("BuenaVista", "Buena Vista", null, "http: resortMap.put("CoffeeMill", new ResortData("CoffeeMill", "CoffeeMill", null, "https://cm-skipatrol.org/", "/images/CoffeeMillLogo.png", IMG_HEIGHT, 87)); resortMap.put("DetroitMountain",new ResortData("DetroitMountain", "Detroit Mountain", null, "http://detroitmountain.com/", "/images/DetroitMountain.png", 73, 121)); resortMap.put("DevilsHead", new ResortData("DevilsHead", "Devil's Head", "tim.theisen@ieee.org", "https: resortMap.put("ElmCreek", new ResortData("ElmCreek", "Elm Creek Park", null, "https: resortMap.put("GrandTarghee", new ResortData("GrandTarghee", "Grand Targhee", null, "http: resortMap.put("GreatDivide", new ResortData("GreatDivide", "Great Divide", null, "http: resortMap.put("HermonMountain", new ResortData("HermonMountain", "Hermon Mountain", null, "http: resortMap.put("Hesperus", new ResortData("Hesperus", "Hesperus", null, "http: resortMap.put("HiddenValley", new ResortData("HiddenValley", "Hidden Valley", null, "http: resortMap.put("HylandHills", new ResortData("HylandHills", "Hyland Hills Park", null, " https://threeriversparks.org/parks/hyland-lake-park/hyland-hills-ski-area.aspx", "/images/ThreeRivers.jpg", IMG_HEIGHT, 80)); resortMap.put("IFNordic", new ResortData("IFNordic", "IF Nordic", null, "", "/images/IFNordic.gif", IMG_HEIGHT, 80)); resortMap.put("KellyCanyon", new ResortData("KellyCanyon", "Kelly Canyon", null, "http: resortMap.put("LonesomePine", new ResortData("LonesomePine", "Lonesome Pine Trails", null, "http: resortMap.put("LeeCanyon", new ResortData("LeeCanyon", "Lee Canyon", "schedule@leecanyonskipatrol.org", "http: resortMap.put("MagicMountain", new ResortData("MagicMountain", "Magic Mountain", null, "http: resortMap.put("psiaMagicMountain", new ResortData("psiaMagicMountain", "Magic Mountain Snowsports School", null, "http: resortMap.put("MountKato", new ResortData("MountKato", "Mount Kato", null, "http: resortMap.put("MountPleasant", new ResortData("MountPleasant", "Mount Pleasant", "dfarbotnik@gmail.com", "http: resortMap.put("NorwayMountain", new ResortData("NorwayMountain", "Norway Mountain", null, "http: resortMap.put("PaidSnowCreek", new ResortData("PaidSnowCreek", "Paid SnowCreek", null, "http: resortMap.put("ParkCity", new ResortData("ParkCity", "PCM-Canyons", "dukespeer@gmail.com", "http: resortMap.put("PebbleCreek", new ResortData("PebbleCreek", "Pebble Creek", null, "http: resortMap.put("PineCreek", new ResortData("PineCreek", "Pine Creek", null, "http: resortMap.put("PineMountain", new ResortData("PineMountain", "Pine Mountain", "schedule@PineMountainSkiPatrol.com", "http: resortMap.put("psiaPineMountain",new ResortData("psiaPineMountain", "Pine Mountain (Ski Instructors)", "jwkluth@gmail.com", "http: resortMap.put("Plattekill", new ResortData("Plattekill", "Plattekill Mountain", null, "http://plattekill.com/", "/images/PlattekillLogo.png", IMG_HEIGHT, 147)); resortMap.put("Pomerelle", new ResortData("Pomerelle", "Pomerelle", null, "http: resortMap.put("RMSP", new ResortData("RMSP", "Ragged Mountain", null, "http: resortMap.put("Sample", new ResortData("Sample", "Sample Resort", null, "http: //snobowl //snowbird (hosts) resortMap.put("Snowbowl", new ResortData("Snowbowl", "Snowbowl", null, "http: resortMap.put("SnowCreek", new ResortData("SnowCreek", "SnowCreek", null, "http: resortMap.put("SnowKing", new ResortData("SnowKing", "SnowKing", null, "http: resortMap.put("SoldierHollow", new ResortData("SoldierHollow", "Soldier Hollow", null, "http://utaholympiclegacy.org/soldier-hollow/", "/images/SOHO_II.jpg", IMG_HEIGHT, 60)); resortMap.put("SoldierMountain", new ResortData("SoldierMountain", "Soldier Mountain", null, "http: //uop resortMap.put("WelchVillage", new ResortData("WelchVillage", "Welch Village", null, "http: resortMap.put("WhitePine", new ResortData("WhitePine", "White Pine", "gawilson@wyoming.com", "http: resortMap.put("WildMountain", new ResortData("WildMountain", "Wild Mountain", null, "http: resortMap.put("Willamette", new ResortData("Willamette", "Willamette Backcountry", null, "http: } // final static String JDBC_DRIVER = "org.gjt.mm.mysql.Driver"; //todo change July 32 2015 private final static String JDBC_DRIVER = "com.mysql.jdbc.Driver"; public final static String newShiftStyle = "--New Shift Style // create a Mountain Standard Time time zone public final static String NEW_SHIFT_STYLE = "--New Shift Style public final static int MAX_PATROLLERS = 400; //todo hack fix me public final static String SERVLET_URL = "/calendar-1/"; public final static boolean FETCH_MIN_DATA = false; public final static boolean FETCH_ALL_DATA = true; //all the folowing instance variables must be initialized in the constructor // private Connection connection; private Connection connection; // private ResultSet rosterResults; // private ResultSet assignmentResults; //todo get rid of this global !!! private PreparedStatement shiftStatement; private boolean fetchFullData; private String localResort; private SessionData sessionData; private Logger LOG; public PatrolData(boolean readAllData, String myResort, SessionData sessionData, final Logger parentLogger) { LOG = new Logger(PatrolData.class, parentLogger, myResort, MIN_LOG_LEVEL); this.sessionData = sessionData; // rosterResults = null; // assignmentResults = null; shiftStatement = null; localResort = myResort; fetchFullData = readAllData; try { Class.forName(JDBC_DRIVER).newInstance(); } catch (Exception e) { logError("Cannot load the driver, reason:" + e.toString()); logError("Most likely the Java class path is incorrect."); //todo do something here. besides throw a NPE later return; } connection = getConnection(localResort, sessionData); if (connection == null) //error was already displayed, if null { logError("getConnection(" + localResort + ", sessionData) failed."); //todo do something here. besides throw a NPE later } } //end PatrolData constructor public Connection getConnection() { return connection; } public static Connection getConnection(String resort, SessionData sessionData) { //todo get rid of static !!!!!!!!!! Connection conn = null; try { conn = java.sql.DriverManager.getConnection(getJDBC_URL(resort), sessionData.getDbUser(), sessionData.getDbPassword()); debugOutStatic(sessionData, "PatrolData.connection " + ((conn == null) ? "FAILED" : "SUCCEEDED") + " for " + getJDBC_URL(resort)); } catch (Exception e) { logErrorStatic(sessionData, "Error: " + e.getMessage() + " connecting to table:" + resort); java.lang.Thread.currentThread().dumpStack(); } return conn; } public ResultSet resetAssignments() { try { String selectAllAssignmentsByDateSQLString = Assignments.getSelectAllAssignmentsByDateSQLString(localResort); LOG.info("resetAssignments: " + selectAllAssignmentsByDateSQLString); PreparedStatement assignmentsStatement = connection.prepareStatement(selectAllAssignmentsByDateSQLString); return assignmentsStatement.executeQuery(); } catch (Exception e) { logError(" Error (line 167) resetting Assignments table query:" + e.getMessage()); return null; } //end try } public Assignments readNextAssignment(ResultSet assignmentResults) { //todo srg fix all callers to this. it is returning things out of order. use readSortedAssignments // Map<Thread, StackTraceElement[]> threadMap = Thread.getAllStackTraces(); // Thread currentThread = Thread.currentThread(); // if (threadMap.get(currentThread) != null) { // logger("[1]" + threadMap.get(currentThread)[1].toString()); // logger("[2]" + threadMap.get(currentThread)[2].toString()); // logger("[3]" + threadMap.get(currentThread)[3].toString()); // logger("[4]" + threadMap.get(currentThread)[4].toString()); // logger("[5]" + threadMap.get(currentThread)[5].toString()); // logger("[6]" + threadMap.get(currentThread)[6].toString()); Assignments ns = null; try { if (assignmentResults.next()) { //todo uses global :-( ns = new Assignments(LOG); ns.read(sessionData, assignmentResults); } } catch (SQLException e) { LOG.logException("Cannot read Assignment:", e); return null; } return ns; } public ResultSet resetRoster() { try { String sqlQuery = "SELECT * FROM roster ORDER BY LastName, FirstName"; LOG.logSqlStatement(sqlQuery); PreparedStatement rosterStatement = connection.prepareStatement(sqlQuery); return rosterStatement.executeQuery(); } catch (Exception e) { LOG.logException("Error reseting roster table ", e); return null; } //end try } public ResultSet resetRoster(String sort) { try { PreparedStatement rosterStatement = connection.prepareStatement("SELECT * FROM roster ORDER BY " + sort); return rosterStatement.executeQuery(); } catch (Exception e) { LOG.logException("Error resetting roster table ", e); return null; } //end try } public void resetShiftDefinitions() { try { shiftStatement = connection.prepareStatement("SELECT * FROM shiftdefinitions ORDER BY \"" + ShiftDefinitions.tags[0] + "\""); //sort by default key shiftStatement.executeQuery(); //todo ignore return ??? } catch (Exception e) { LOG.logException("Error resetting Shifts table exception=", e); } //end try } public boolean writeDirectorSettings(DirectorSettings ds) { return ds.write(connection); } public DirectorSettings readDirectorSettings() { DirectorSettings ds = new DirectorSettings(localResort, LOG); final ResultSet directorResults = ds.reset(connection); try { if (directorResults.next()) { ds.read(directorResults); } else { LOG.error("ERROR: directorResults.next() failed:"); } } catch (Exception e) { LOG.logException("Cannot read DirectorSettings:", e); return null; } return ds; } public ArrayList<ShiftDefinitions> readShiftDefinitions() { ArrayList<ShiftDefinitions> shiftDefinitions = new ArrayList<ShiftDefinitions>(); try { String qryString = "SELECT * FROM `shiftdefinitions` ORDER BY `shiftdefinitions`.`EventName` ASC"; LOG.logSqlStatement(qryString); PreparedStatement assignmentsStatement = connection.prepareStatement(qryString); ResultSet assignmentResults = assignmentsStatement.executeQuery(); while (assignmentResults.next()) { ShiftDefinitions ns = new ShiftDefinitions(LOG); ns.read(assignmentResults); // logger(".. NextShifts-" + ns.toString()); shiftDefinitions.add(ns); } } catch (Exception e) { LOG.logException(" Error (line 279) resetting Assignments table ", e); } //end try return shiftDefinitions; } public void decrementShift(ShiftDefinitions ns) { LOG.debug("decrement shift:" + ns); int i = ns.getEventIndex(); LOG.debug("event index =" + i); if (i == 0) { return; } deleteShift(ns); ns.setEventName(Assignments.createAssignmentName(ns.parsedEventName(), i - 1)); writeShift(ns); } public void deleteShift(ShiftDefinitions ns) { String qryString = ns.getDeleteSQLString(localResort); LOG.info("deleteShift: " + qryString); try { PreparedStatement sAssign = connection.prepareStatement(qryString); sAssign.executeUpdate(); ns.setExists(false); } catch (Exception e) { LOG.logException("Cannot delete Shift, reason: ",e); } } public boolean writeShift(ShiftDefinitions ns) { String qryString; if (ns.exists()) { qryString = ns.getUpdateShiftDefinitionsQueryString(localResort); } else { qryString = ns.getInsertShiftDefinitionsQueryString(localResort); } LOG.info("writeShift: " + qryString); try { PreparedStatement sAssign = connection.prepareStatement(qryString); sAssign.executeUpdate(); ns.setExists(true); } catch (SQLException e) { logError( " failed writeShift, exception=" + e.getMessage()); return true; } return false; } public void close() { try { LOG.debug("-- close connection"); if (connection != null) { connection.close(); //let it close in finalizer ?? } } catch (Exception e) { LOG.logException(" Error closing connection:", e); Thread.currentThread().dumpStack(); } //end try } // end close public Roster nextMember(String defaultString, ResultSet rosterResults) { Roster member = null; try { if (rosterResults.next()) { member = new Roster(LOG); //"&nbsp;" is the default member.readFullFromRoster(rosterResults, defaultString); } //end if } catch (SQLException e) { member = null; LOG.logException("Failed nextMember, reason:", e); Thread.currentThread().dumpStack(); } //end try return member; } //end nextMember public Roster getMemberByID(String szMemberID) { Roster member; String str = "SELECT * FROM roster WHERE IDNumber =" + szMemberID; LOG.logSqlStatement(str); if (szMemberID == null || szMemberID.length() <= 3) { LOG.error("called getMemberByID with invalid memberID=[" + szMemberID + "]"); return null; } else if (szMemberID.equals(sessionData.getBackDoorUser())) { member = new Roster(LOG); //"&nbsp;" is the default member.setLast(backDoorFakeLastName); member.setFirst(backDoorFakeFirstName); member.setEmail(backDoorEmail); member.setID("000000"); member.setDirector("yes"); return member; } try { PreparedStatement rosterStatement = connection.prepareStatement(str); ResultSet rosterResults = rosterStatement.executeQuery(); while (rosterResults.next()) { int id = rosterResults.getInt("IDNumber"); String str1 = id + ""; //noinspection Duplicates if (str1.equals(szMemberID)) { member = new Roster(LOG); //"&nbsp;" is the default if (fetchFullData) { member.readFullFromRoster(rosterResults, ""); } else { member.readPartialFromRoster(rosterResults, ""); } return member; } } //end while } catch (Exception e) { LOG.logException("Error in getMemberByID memberID=[" + szMemberID + "] ", e); //noinspection AccessStaticViaInstance Thread.currentThread().dumpStack(); } //end try return null; //failed } //end getMemberByID public Roster getMemberByEmail(String szEmail) { Roster member; String str = "SELECT * FROM roster WHERE email =\"" + szEmail + "\""; LOG.logSqlStatement(str); try { PreparedStatement rosterStatement = connection.prepareStatement(str); ResultSet rosterResults = rosterStatement.executeQuery(); if (rosterResults.next()) { member = new Roster(LOG); //"&nbsp;" is the default if (fetchFullData) { member.readFullFromRoster(rosterResults, ""); } else { member.readPartialFromRoster(rosterResults, ""); } return member; } //end while } catch (Exception e) { LOG.logException("Error in getMemberByEmail(" + szEmail + "): ", e); } //end try return null; //failure } //end getMemberByID public Roster getMemberByName2(String szFullName) { return getMemberByLastNameFirstName(szFullName); } //end getMemberByName public Roster getMemberByLastNameFirstName(String szFullName) { Roster member; String str = "SELECT * FROM roster"; LOG.logSqlStatement(str); try { PreparedStatement rosterStatement = connection.prepareStatement(str); ResultSet rosterResults = rosterStatement.executeQuery(); while (rosterResults.next()) { // int id = rosterResults.getInt("IDNumber"); String str1 = rosterResults.getString("LastName").trim() + ", " + rosterResults.getString("FirstName").trim(); //Log.log("getMemberByLastNameFirstName: (" + szFullName + ") (" + str1 + ") cmp=" + str1.equals(szFullName)); //noinspection Duplicates if (str1.equals(szFullName)) { member = new Roster(LOG); //"&nbsp;" is the default if (fetchFullData) { member.readFullFromRoster(rosterResults, ""); } else { member.readPartialFromRoster(rosterResults, ""); } return member; } } //end while } catch (SQLException e) { logError("(" + localResort + ") failed getMemberByLastNameFirstName(" + szFullName + "):" + e.getMessage()); Thread.currentThread().dumpStack(); } return null; //not found (or error) } public static int StringToIndex(String temp) { int i; try { i = Integer.parseInt(temp); } catch (Exception e) { char ch = temp.charAt(0); i = ch - 'A' + 10; } return i; } public static String IndexToString(int i) { String val; if (i < 10) { val = i + ""; //force automatic conversion of integer to string } else { val = String.valueOf((char) ('A' + i - 10)); } return val; } public Assignments readAssignment(String myDate) { //formmat yyyy-mm-dd_p Assignments ns; try { String queryString = "SELECT * FROM assignments WHERE Date=\'" + myDate + "\'"; LOG.logSqlStatement(queryString); PreparedStatement assignmentsStatementLocal = connection.prepareStatement(queryString); ResultSet assignmentResultsLocal = assignmentsStatementLocal.executeQuery(); if (assignmentResultsLocal.next()) { ns = new Assignments(LOG); ns.read(sessionData, assignmentResultsLocal); LOG.logSqlStatement(queryString); return ns; } } catch (SQLException e) { logError("failed readAssignment, reason:" + e.getMessage()); return null; } return null; } public boolean writeAssignment(Assignments ns) { String qryString; if (ns.exists()) { qryString = ns.getUpdateQueryString(sessionData); } else { qryString = ns.getInsertQueryString(sessionData); } try { PreparedStatement sAssign = connection.prepareStatement(qryString); sAssign.executeUpdate(); } catch (SQLException e) { logError("(" + localResort + ") failed writeAssignment, reason:" + e.getMessage()); return true; } return false; } // decrementAssignment - change 2015-10-06_2 to 2015-10-06_1 (delete _2 and write _1) // 2015-10-06_0 is ignored public void decrementAssignment(Assignments ns) { LOG.info("decrement Assignment:" + ns); int i = ns.getDatePos(); //1 based if (i < 1) //#'s are 0 based, can't decrement pos 0 { return; } deleteAssignment(ns); String qry2String = ShiftDefinitions.createShiftName(ns.getDateOnly(), i - 1); ns.setDate(qry2String); writeAssignment(ns); } // deleteShift - DELETE Shift assignment for a specified date and index public void deleteAssignment(Assignments ns) { String qryString = ns.getDeleteSQLString(sessionData); LOG.info("deleteAssignment" + qryString); try { PreparedStatement sAssign = connection.prepareStatement(qryString); sAssign.executeUpdate(); ns.setExisted(false); } catch (SQLException e) { logError("(" + localResort + ") failed deleteAssignment, reason:" + e.getMessage()); } } // AddShiftsToDropDown static public void AddShiftsToDropDown(PrintWriter out, ArrayList shifts, String selectedShift) { String lastName = ""; String parsedName; String selected = ""; if (selectedShift == null) { selected = " selected"; } out.println(" <option" + selected + ">" + NEW_SHIFT_STYLE + "</option>"); for (Object shift : shifts) { ShiftDefinitions data = (ShiftDefinitions) shift; parsedName = data.parsedEventName(); if (parsedName.equals(selectedShift)) { selected = " selected"; } else { selected = ""; } if (!parsedName.equals(lastName)) { out.println("<option" + selected + ">" + parsedName + "</option>"); lastName = parsedName; } } } // countDropDown static private void countDropDown(PrintWriter out, String szName, int value) { out.println("<select size=\"1\" name=\"" + szName + "\">"); for (int i = Math.min(1, value); i <= Assignments.MAX_ASSIGNMENT_SIZE; ++i) { if (i == value) { out.println("<option selected>" + i + "</option>"); } else { out.println("<option>" + i + "</option>"); } } out.println(" </select>"); } // AddShiftsToTable static public void AddShiftsToTable(PrintWriter out, ArrayList shifts, String selectedShift) { int validShifts = 0; for (Object shift : shifts) { ShiftDefinitions data = (ShiftDefinitions) shift; String parsedName = data.parsedEventName(); if (parsedName.equals(selectedShift)) { //name is if the format of startTime_0, endTime_0, count_0, startTime_1, endTime_1, count_1, etc // delete_0, delete_1 //shiftCount out.println("<tr>"); //delete button // out.println("<td width=\"103\"><input onClick=\"DeleteBtn()\" type=\"button\" value=\"Delete\" name=\"delete_"+validShifts+"\"></td>"); out.println("<td><input type='submit' value='Delete' name='delete_" + validShifts + "'></td>"); out.println("<td>Start: <input type='text' onKeyDown='javascript:return captureEnter(event.keyCode)' name='startTime_" + validShifts + "' size='7' value='" + data.getStartString() + "'></td>"); out.println("<td>End: <input type='text' onKeyDown='javascript:return captureEnter(event.keyCode)' name='endTime_" + validShifts + "' size='7' value='" + data.getEndString() + "'></td>"); out.println("<td>Patroller&nbsp;Count:&nbsp;"); // out.println("<input type=\"text\" name=\"count_"+validShifts+"\" size=\"4\" value=\""+data.getCount()+"\">"); countDropDown(out, "count_" + validShifts, data.getCount()); out.println("</td>"); //add Day/Seing/Night shift out.println("<td>&nbsp;"); out.println("<select size=1 name='shift_" + validShifts + "'>"); //Log.log("in AddShiftsToTable, data.getType()="+data.getType()); for (int shiftType = 0; shiftType < Assignments.MAX_SHIFT_TYPES; ++shiftType) { String sel = (data.getType() == shiftType) ? "selected" : ""; out.println("<option " + sel + ">" + Assignments.getShiftName(shiftType) + "</option>"); } out.println("</select>"); out.println("</td>"); out.println("</tr>"); ++validShifts; } } out.println("<INPUT TYPE=\"HIDDEN\" NAME=\"shiftCount\" VALUE=\"" + validShifts + "\">"); } // AddAssignmentsToTable static public void AddAssignmentsToTable(PrintWriter out, ArrayList parameterAssignments) { int validShifts = 0; for (Object parameterAssignment : parameterAssignments) { Assignments data = (Assignments) parameterAssignment; // String parsedName = data.getEventName(); int useCount = data.getUseCount("???"); //get # of patrollers actually assigned to this shift (warn if deleteing!) // if(parsedName.equals(selectedShift)) { //name is if the format of startTime_0, endTime_0, count_0, startTime_1, endTime_1, count_1, etc // delete_0, delete_1 //shiftCount out.println("<tr>"); //delete button // out.println("<td width=\"103\"><input onClick=\"DeleteBtn()\" type=\"button\" value=\"Delete\" name=\"delete_"+validShifts+"\"></td>"); out.println("<td><input type=\"submit\" value=\"Delete\" onclick=\"return confirmShiftDelete(" + useCount + ")\" name=\"delete_" + validShifts + "\"></td>"); out.println("<td>Start: <input type=\"text\" name=\"startTime_" + validShifts + "\" onKeyDown=\"javascript:return captureEnter(event.keyCode)\" size=\"7\" value=\"" + data.getStartingTimeString() + "\"></td>"); out.println("<td>End: <input type=\"text\" name=\"endTime_" + validShifts + "\" onKeyDown=\"javascript:return captureEnter(event.keyCode)\" size=\"7\" value=\"" + data.getEndingTimeString() + "\"></td>"); out.println("<td>Patroller&nbsp;Count:&nbsp;"); // out.println("<input type=\"text\" name=\"count_"+validShifts+"\" size=\"4\" value=\""+data.getCount()+"\">"); countDropDown(out, "count_" + validShifts, data.getCount()); out.println("</td>"); //add Day/Seing/Night shift out.println("<td>&nbsp;&nbsp; "); out.println("<select size=1 name='shift_" + validShifts + "'>"); //Log.log("in AddAssignmentsToTable, data.getType()="+data.getType()); for (int shiftType = 0; shiftType < Assignments.MAX_SHIFT_TYPES; ++shiftType) { String sel = (data.getType() == shiftType) ? "selected" : ""; out.println("<option " + sel + ">" + Assignments.getShiftName(shiftType) + "</option>"); } out.println("</select>"); out.println("</td>"); out.println("</tr>"); ++validShifts; } out.println("<INPUT TYPE='HIDDEN\' NAME='shiftCount' VALUE='" + validShifts + "'>"); } static public boolean isValidResort(String resort) { return resortMap.containsKey(resort); } static public ResortData getResortInfo(String theResort) { return resortMap.get(theResort); } public ResortData getResortInfo() { return resortMap.get(localResort); } public static String getResortFullName(String resort) { if (resortMap.containsKey(resort)) { //resort string is same as db name, value is full resort string return resortMap.get(resort).getResortFullName(); } Logger.logStatic("**** Error, unknown resort (" + resort + ")"); Thread.currentThread().dumpStack(); return "Error, invalid resort (" + resort + ")"; } private static String getJDBC_URL(String resort) { String jdbcLoc = "jdbc:mysql://" + MYSQL_ADDRESS + "/"; if (isValidResort(resort)) { return jdbcLoc + resort; } logger(resort, "****** Error, unknown resort (" + resort + ")"); Thread.currentThread().dumpStack(); return "invalidResort"; } public boolean insertNewIndividualAssignment( NewIndividualAssignment newIndividualAssignment) { String qryString = newIndividualAssignment.getInsertSQLString(sessionData); LOG.info("insertNewIndividualAssignment" + qryString); try { PreparedStatement sAssign = connection.prepareStatement(qryString); sAssign.executeUpdate(); } catch (SQLException e) { LOG.logException("Cannot insert newIndividualAssignment", e); return false; } return true; } public boolean updateNewIndividualAssignment(NewIndividualAssignment newIndividualAssignment) { String qryString = newIndividualAssignment.getUpdateSQLString(sessionData); LOG.info("updateNewIndividualAssignment: " + qryString); try { PreparedStatement sAssign = connection.prepareStatement(qryString); sAssign.executeUpdate(); } catch (SQLException e) { logError("(" + localResort + ") Cannot update newIndividualAssignment, reason:" + e.getMessage()); return false; } return true; } public HashMap<String, NewIndividualAssignment> readNewIndividualAssignments(int year, int month, int day) { //formmat yyyy-mm-dd_i_n HashMap<String, NewIndividualAssignment> results = new HashMap<String, NewIndividualAssignment>(); String key = NewIndividualAssignment.buildKey(year, month, day, -1, -1); key += "%"; //SELECT * FROM `newindividualassignment` WHERE `date_shift_pos` LIKE "2009-02-07%" try { String queryString = "SELECT * FROM `newindividualassignment` WHERE `date_shift_pos` LIKE \'" + key + "\'"; debugOut("readNewIndividualAssignments: " + queryString); PreparedStatement assignmentsStatement = connection.prepareStatement(queryString); ResultSet assignmentResults = assignmentsStatement.executeQuery(); while (assignmentResults.next()) { NewIndividualAssignment newIndividualAssignment = new NewIndividualAssignment(); newIndividualAssignment.read(sessionData, assignmentResults); debugOut(newIndividualAssignment.toString()); results.put(newIndividualAssignment.getDateShiftPos(), newIndividualAssignment); } } catch (SQLException e) { logError("(" + localResort + ") readNewIndividualAssignments" + e.getMessage()); return null; } return results; } // private void logger(String message) { // if (sessionData != null && sessionData.getRequest() != null) { // Logger.printToLogFileStatic(sessionData.getRequest(), localResort, sessionData.getLoggedInUserId(), message); // else { // logger(localResort, "THIS SHOULD NEVER HAPPEN. PatrolData@782, " + message); public static void logger(String myResort, String message) { Logger.printToLogFileStatic(null, myResort, message); } public void deleteNewIndividualAssignment(NewIndividualAssignment newIndividualAssignment) { String qryString = newIndividualAssignment.getDeleteSQLString(sessionData); LOG.logSqlStatement(qryString); try { PreparedStatement sAssign = connection.prepareStatement(qryString); sAssign.executeUpdate(); //can throw exception newIndividualAssignment.setExisted(false); } catch (Exception e) { Logger.logStatic("(" + localResort + ") Cannot delete Shift, reason:" + e.toString()); } } public ArrayList<Assignments> readAllSortedAssignments(String patrollerId) { String dateMask = "20%"; //WHERE `date_shift_pos` LIKE '2015-10-%' // logger("readSortedAssignments(" + dateMask + ")"); ArrayList<Assignments> monthAssignments = new ArrayList<Assignments>(); try { String qryString = "SELECT * FROM `assignments` WHERE Date like '" + dateMask + "' ORDER BY Date"; LOG.logSqlStatement(qryString); PreparedStatement assignmentsStatement = connection.prepareStatement(qryString); ResultSet assignmentResults = assignmentsStatement.executeQuery(); // int cnt = 1; while (assignmentResults.next()) { Assignments assignments = new Assignments(LOG); assignments.read(sessionData, assignmentResults); if (assignments.includesPatroller(patrollerId)) { // logger("(" + (cnt++) + ") NextAssignment-" + ns.toString()); monthAssignments.add(assignments); } } } catch (Exception e) { LOG.logException(" Error (line 821) resetting Assignments table", e); } //end try return monthAssignments; } public ArrayList<Assignments> readSortedAssignments(String patrollerId, int year, int month) { ArrayList<Assignments> unFilteredAssignments = readSortedAssignments(year, month); return filterAssignments(patrollerId, unFilteredAssignments); } public ArrayList<Assignments> readSortedAssignments(String patrollerId, int year, int month, int day) { ArrayList<Assignments> unFilteredAssignments = readSortedAssignments(year, month, day); return filterAssignments(patrollerId, unFilteredAssignments); } private ArrayList<Assignments> filterAssignments(String patrollerId, ArrayList<Assignments> unFilteredAssignments) { ArrayList<Assignments> filteredAssignments = new ArrayList<Assignments>(); for (Assignments eachAssignment : unFilteredAssignments) { if (eachAssignment.includesPatroller(patrollerId)) { filteredAssignments.add(eachAssignment); } } return filteredAssignments; } public ArrayList<Assignments> readSortedAssignments(int year, int month) { String dateMask = String.format("%4d-%02d-", year, month) + "%"; // logger(" readSortedAssignments(" + dateMask + ")"); ArrayList<Assignments> monthAssignments = new ArrayList<Assignments>(); try { String qryString = "SELECT * FROM `assignments` WHERE Date like '" + dateMask + "' ORDER BY Date"; LOG.logSqlStatement(qryString); PreparedStatement assignmentsStatement = connection.prepareStatement(qryString); ResultSet assignmentResults = assignmentsStatement.executeQuery(); while (assignmentResults.next()) { Assignments ns = new Assignments(LOG); ns.read(sessionData, assignmentResults); // logger(".. NextAssignment-" + ns.toString()); monthAssignments.add(ns); } } catch (Exception e) { LOG.logException("Error (line 864) resetting Assignments table", e); } //end try return monthAssignments; } public ArrayList<Assignments> readSortedAssignments(int year, int month, int day) { String dateMask = String.format("%4d-%02d-%02d_", year, month, day) + "%"; // logger(" readSortedAssignments(" + dateMask + ")"); ArrayList<Assignments> monthAssignments = new ArrayList<Assignments>(); try { String qryString = "SELECT * FROM `assignments` WHERE Date like '" + dateMask + "' ORDER BY Date"; LOG.logSqlStatement(qryString); PreparedStatement assignmentsStatement = connection.prepareStatement(qryString); ResultSet assignmentResults = assignmentsStatement.executeQuery(); while (assignmentResults.next()) { Assignments ns = new Assignments(LOG); ns.read(sessionData, assignmentResults); // logger(".. NextAssignment-" + ns.toString()); monthAssignments.add(ns); } } catch (Exception e) { LOG.logException("Error (line 887) resetting Assignments table", e); } //end try return monthAssignments; } private void debugOut(String msg) { LOG.debug(msg); } private void logError(String msg) { LOG.error(msg); } private static void debugOutStatic(SessionData sessionData, String msg) { // if (MIN_LOG_LEVEL == Logger.DEBUG) { String localResort = sessionData == null ? "noLoggedInResort" : sessionData.getLoggedInResort(); HttpServletRequest request = sessionData == null ? null : sessionData.getRequest(); Logger.printToLogFileStatic(request, localResort, msg); } private static void logErrorStatic(SessionData sessionData, String msg) { String localResort = sessionData == null ? "noLoggedInResort" : sessionData.getLoggedInResort(); HttpServletRequest request = sessionData == null ? null : sessionData.getRequest(); Logger.printToLogFileStatic(request, localResort, msg); } public static boolean isValidLogin(PrintWriter out, String resort, String ID, String pass, SessionData sessionData) { Logger logErr = new Logger(PatrolData.class, sessionData.getRequest(), "???", resort, MIN_LOG_LEVEL); boolean validLogin = false; ResultSet rs; //Log.log("LoginHelp: isValidLogin("+resort + ", "+ID+", "+pass+")"); if (ID == null || pass == null) { logErr.error("Login Failed: either ID (" + ID + ") or Password not supplied"); return false; } try { //noinspection unused Driver drv = (Driver) Class.forName(PatrolData.JDBC_DRIVER).newInstance(); } catch (Exception e) { logErr.logException("LoginHelp: Cannot find mysql driver:", e); return false; } if (ID.equalsIgnoreCase(sessionData.getBackDoorUser()) && pass.equalsIgnoreCase(sessionData.getBackDoorPassword())) { return true; } // Try to connect to the database try { // Change MyDSN, myUsername and myPassword to your specific DSN Connection c = PatrolData.getConnection(resort, sessionData); @SuppressWarnings("SqlNoDataSourceInspection") String szQuery = "SELECT * FROM roster WHERE IDNumber = \"" + ID + "\""; logErr.info(szQuery); @SuppressWarnings("SpellCheckingInspection") PreparedStatement sRost = c.prepareStatement(szQuery); if (sRost == null) { return false; } rs = sRost.executeQuery(); if (rs != null && rs.next()) { //will only loop 1 time String originalPassword = rs.getString("password"); String lastName = rs.getString("LastName"); String firstName = rs.getString("FirstName"); String emailAddress = rs.getString("email"); originalPassword = originalPassword.trim(); lastName = lastName.trim(); pass = pass.trim(); boolean hasPassword = (originalPassword.length() > 0); if (hasPassword) { if (originalPassword.equalsIgnoreCase(pass)) { validLogin = true; } } else { if (lastName.equalsIgnoreCase(pass)) { validLogin = true; } } if (validLogin) { Logger.printToLogFileStatic(sessionData.getRequest(), sessionData.getLoggedInResort(), "Login Sucessful: " + firstName + " " + lastName + ", " + ID + " (" + resort + ") " + emailAddress); } else { Logger.printToLogFileStatic(sessionData.getRequest(), sessionData.getLoggedInResort(), "Login Failed: ID=[" + ID + "] LastName=[" + lastName + "] suppliedPass=[" + pass + "] dbPass[" + originalPassword + "]"); } } else { Logger.printToLogFileStatic(sessionData.getRequest(), sessionData.getLoggedInResort(), "Login Failed: memberId not found [" + ID + "]"); } c.close(); } catch (Exception e) { out.println("Error connecting or reading table:" + e.getMessage()); //message on browser Logger.printToLogFileStatic(sessionData.getRequest(), sessionData.getLoggedInResort(), "LoginHelp. Error connecting or reading table:" + e.getMessage()); } //end try return validLogin; } }
package org.threadly.litesockets.tcp; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.SocketChannel; import java.util.ArrayDeque; import java.util.Deque; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSession; import org.threadly.concurrent.future.ListenableFuture; import org.threadly.concurrent.future.SettableListenableFuture; import org.threadly.litesockets.Client; import org.threadly.litesockets.SocketExecuter; import org.threadly.litesockets.WireProtocol; import org.threadly.litesockets.utils.MergedByteBuffers; import org.threadly.litesockets.utils.SimpleByteStats; import org.threadly.util.ArgumentVerifier; import org.threadly.util.Clock; import org.threadly.util.Pair; /** * This is a generic Client for TCP connections. This client can be either from the "client" side or * from a client from a {@link TCPServer}, and both function the same way. * */ public class TCPClient extends Client { /** * The default SocketConnection time out (10 seconds). */ public static final int DEFAULT_SOCKET_TIMEOUT = 10000; /** * Default max buffer size (64k). Read and write buffers are independent of each other. */ public static final int DEFAULT_MAX_BUFFER_SIZE = 65536; /** * Minimum allowed readBuffer (4k). If the readBuffer is lower then this we will create a new one. */ public static final int MIN_READ_BUFFER_SIZE = 4096; /** * When we hit the minimum read buffer size we will create a new one of this size (64k). */ public static final int NEW_READ_BUFFER_SIZE = 65536; public static final int MIN_WRITE_BUFFER_SIZE = 8192; public static final int MAX_COMBINED_WRITE_BUFFER_SIZE = 65536; private final MergedByteBuffers readBuffers = new MergedByteBuffers(); private final MergedByteBuffers writeBuffers = new MergedByteBuffers(); private final Deque<Pair<Long, SettableListenableFuture<Long>>> writeFutures = new ArrayDeque<Pair<Long, SettableListenableFuture<Long>>>(); protected final String host; protected final int port; protected final long startTime = Clock.lastKnownForwardProgressingMillis(); protected final AtomicBoolean startedConnection = new AtomicBoolean(false); protected final SettableListenableFuture<Boolean> connectionFuture = new SettableListenableFuture<Boolean>(false); protected final SocketExecuter sei; protected final Executor cexec; protected final SocketChannel channel; protected volatile int maxConnectionTime = DEFAULT_SOCKET_TIMEOUT; protected volatile int maxBufferSize = DEFAULT_MAX_BUFFER_SIZE; protected volatile int minAllowedReadBuffer = MIN_READ_BUFFER_SIZE; protected volatile int newReadBuffer = NEW_READ_BUFFER_SIZE; protected volatile Closer closer; protected volatile Reader reader; protected volatile long connectExpiresAt = -1; protected ClientByteStats stats = new ClientByteStats(); protected AtomicBoolean closed = new AtomicBoolean(false); protected final InetSocketAddress remoteAddress; private volatile ByteBuffer currentWriteBuffer = ByteBuffer.allocate(0); private ByteBuffer readByteBuffer = ByteBuffer.allocate(NEW_READ_BUFFER_SIZE); private volatile SSLProcessor sslProcessor; /** * This creates TCPClient with a connection to the specified port and IP. This connection is not is not * yet made {@link #connect()} must be called which will do the actual connect. * * @param sei The {@link SocketExecuter} implementation this client will use. * @param host The hostname or IP address to connect this client too. * @param port The port to connect this client too. * @throws IOException - This is thrown if there are any problems making the socket. */ public TCPClient(SocketExecuter sei, String host, int port) throws IOException { this.sei = sei; this.host = host; this.port = port; this.channel = SocketChannel.open(); channel.configureBlocking(false); cexec = sei.getExecutorFor(this); remoteAddress = new InetSocketAddress(host, port); } /** * <p>This creates a TCPClient based off an already existing {@link SocketChannel}. * This {@link SocketChannel} must already be connected.</p> * * @param sei the {@link SocketExecuter} to use for this client. * @param channel the {@link SocketChannel} to use for this client. * @throws IOException if there is anything wrong with the {@link SocketChannel} this will be thrown. */ public TCPClient(SocketExecuter sei, SocketChannel channel) throws IOException { this.sei = sei; cexec = sei.getExecutorFor(this); if(! channel.isOpen()) { throw new ClosedChannelException(); } connectionFuture.setResult(true); host = channel.socket().getInetAddress().getHostAddress(); port = channel.socket().getPort(); if(channel.isBlocking()) { channel.configureBlocking(false); } this.channel = channel; remoteAddress = (InetSocketAddress) channel.socket().getRemoteSocketAddress(); startedConnection.set(true); } @Override public void setConnectionTimeout(int timeout) { ArgumentVerifier.assertNotNegative(timeout, "Timeout"); this.maxConnectionTime = timeout; } @Override public ListenableFuture<Boolean> connect(){ if(startedConnection.compareAndSet(false, true)) { try { channel.connect(new InetSocketAddress(host, port)); connectExpiresAt = maxConnectionTime + Clock.lastKnownForwardProgressingMillis(); sei.setClientOperations(this); sei.watchFuture(connectionFuture, maxConnectionTime); } catch (Exception e) { connectionFuture.setFailure(e); close(); } } return connectionFuture; } @Override protected void setConnectionStatus(Throwable t) { if(t != null) { if(connectionFuture.setFailure(t)) { close(); } } else { connectionFuture.setResult(true); } } @Override public boolean hasConnectionTimedOut() { if(! startedConnection.get()) { return false; } if(channel.isConnected()) { return false; } return Clock.lastKnownForwardProgressingMillis() > connectExpiresAt; } @Override public int getTimeout() { return maxConnectionTime; } @Override protected SocketChannel getChannel() { return channel; } @Override protected Socket getSocket() { return channel.socket(); } @Override public boolean isClosed() { return closed.get(); } @Override public void close() { if(closed.compareAndSet(false, true)) { sei.setClientOperations(this); synchronized(writeBuffers) { for(Pair<Long, SettableListenableFuture<Long>> p: this.writeFutures) { p.getRight().setFailure(new ClosedChannelException()); } writeFutures.clear(); writeBuffers.discard(this.writeBuffers.remaining()); } try { channel.close(); } catch (IOException e) { //we dont care } finally { final Closer lcloser = closer; if(lcloser != null && this.cexec != null) { cexec.execute(new Runnable() { @Override public void run() { lcloser.onClose(TCPClient.this); }}); } } } } @Override public void setReader(final Reader reader) { if(! closed.get()) { this.reader = reader; synchronized(readBuffers) { if(this.readBuffers.remaining() > 0) { cexec.execute(new Runnable() { @Override public void run() { reader.onRead(TCPClient.this); }}); } } } } @Override public Reader getReader() { return reader; } @Override public void setCloser(final Closer closer) { if(! closed.get()) { this.closer = closer; } else { cexec.execute(new Runnable() { @Override public void run() { closer.onClose(TCPClient.this); }}); } } @Override public Closer getCloser() { return closer; } @Override public WireProtocol getProtocol() { return WireProtocol.TCP; } @Override public SimpleByteStats getStats() { return stats; } @Override protected boolean canRead() { if(readBuffers.remaining() > maxBufferSize) { return false; } return true; } @Override protected boolean canWrite() { return writeBuffers.remaining() > 0 ; } @Override protected ByteBuffer provideReadByteBuffer() { if(readByteBuffer.remaining() < minAllowedReadBuffer) { readByteBuffer = ByteBuffer.allocate(DEFAULT_MAX_BUFFER_SIZE); } return readByteBuffer; } @Override public int getReadBufferSize() { return this.readBuffers.remaining(); } @Override public int getWriteBufferSize() { return this.writeBuffers.remaining(); } @Override public int getMaxBufferSize() { return this.maxBufferSize; } @Override public Executor getClientsThreadExecutor() { return this.cexec; } @Override public SocketExecuter getClientsSocketExecuter() { return sei; } @Override public void setMaxBufferSize(int size) { ArgumentVerifier.assertNotNegative(size, "size"); maxBufferSize = size; if(channel.isConnected()) { this.sei.setClientOperations(this); synchronized (writeBuffers) { writeBuffers.notifyAll(); } } } @Override public MergedByteBuffers getRead() { MergedByteBuffers mbb = null; synchronized(readBuffers) { if(readBuffers.remaining() == 0) { return null; } mbb = readBuffers.duplicateAndClean(); if(sslProcessor != null && sslProcessor.handShakeStarted()) { mbb = sslProcessor.doRead(mbb); } } if(mbb.remaining() >= maxBufferSize) { sei.setClientOperations(this); } return mbb; } @Override protected void addReadBuffer(ByteBuffer bb) { stats.addRead(bb.remaining()); synchronized(readBuffers) { int start = readBuffers.remaining(); final Reader lreader = reader; readBuffers.add(bb); if(readBuffers.remaining() > 0 && start == 0 && lreader != null){ cexec.execute(new Runnable() { @Override public void run() { lreader.onRead(TCPClient.this); }}); } } } @Override public ListenableFuture<?> write(ByteBuffer bb) { if(isClosed()) { throw new IllegalStateException("Cannot write to closed client!"); } synchronized(writeBuffers) { boolean needNotify = ! canWrite(); SettableListenableFuture<Long> slf = new SettableListenableFuture<Long>(); if(sslProcessor != null && sslProcessor.handShakeStarted()) { writeBuffers.add(sslProcessor.write(bb)); } else { writeBuffers.add(bb); } this.writeFutures.add(new Pair<Long, SettableListenableFuture<Long>>(writeBuffers.getTotalConsumedBytes()+writeBuffers.remaining(), slf)); if(needNotify && sei != null && channel.isConnected()) { sei.setClientOperations(this); } return slf; } } @Override protected ByteBuffer getWriteBuffer() { if(currentWriteBuffer.remaining() != 0) { return currentWriteBuffer; } synchronized(writeBuffers) { //This is to keep from doing a ton of little writes if we can. We will try to //do at least 8k at a time, and up to 65k if we are already having to combine buffers if(writeBuffers.nextPopSize() < MIN_WRITE_BUFFER_SIZE && writeBuffers.remaining() > writeBuffers.nextPopSize()) { if(writeBuffers.remaining() < MAX_COMBINED_WRITE_BUFFER_SIZE) { currentWriteBuffer = writeBuffers.pull(writeBuffers.remaining()); } else { currentWriteBuffer = writeBuffers.pull(MAX_COMBINED_WRITE_BUFFER_SIZE); } } else { currentWriteBuffer = writeBuffers.pop(); } } return currentWriteBuffer; } @Override protected void reduceWrite(int size) { synchronized(writeBuffers) { stats.addWrite(size); if(currentWriteBuffer.remaining() == 0) { while(this.writeFutures.peekFirst() != null && writeFutures.peekFirst().getLeft() <= writeBuffers.getTotalConsumedBytes()) { Pair<Long, SettableListenableFuture<Long>> p = writeFutures.pollFirst(); if(!p.getRight().isDone()) { p.getRight().setResult(p.getLeft()); } } } } } /** * Implementation of the SimpleByteStats. */ private static class ClientByteStats extends SimpleByteStats { public ClientByteStats() { super(); } @Override protected void addWrite(int size) { ArgumentVerifier.assertNotNegative(size, "size"); super.addWrite(size); } @Override protected void addRead(int size) { ArgumentVerifier.assertNotNegative(size, "size"); super.addRead(size); } } @Override public InetSocketAddress getRemoteSocketAddress() { return remoteAddress; } @Override public InetSocketAddress getLocalSocketAddress() { if(this.channel != null) { return (InetSocketAddress) channel.socket().getLocalSocketAddress(); } return null; } @Override public String toString() { return "TCPClient:FROM:"+getLocalSocketAddress()+":TO:"+getRemoteSocketAddress(); } @Override public boolean setSocketOption(SocketOption so, int value) { try{ switch(so) { case TCP_NODELAY: { this.channel.socket().setTcpNoDelay(value == 1); return true; } case SEND_BUFFER_SIZE: { this.channel.socket().setSendBufferSize(value); return true; } case RECV_BUFFER_SIZE: { this.channel.socket().setReceiveBufferSize(value); return true; } default: return false; } } catch(Exception e) { } return false; } public void setSSLEngine(SSLEngine ssle) { sslProcessor = new SSLProcessor(this, ssle); } public boolean isEncrypted() { if(sslProcessor == null) { return false; } return sslProcessor.isEncrypted(); } public ListenableFuture<SSLSession> startSSL() { if(sslProcessor != null) { ListenableFuture<SSLSession> lf = sslProcessor.doHandShake(); return lf; } throw new IllegalStateException("Must Set the SSLEngine before starting Encryption!"); } }
package org.whitesource.docker; import org.whitesource.contracts.PluginInfo; public class DockerAgentInfo implements PluginInfo { private static final String AGENT_TYPE = "docker-agent"; private static final String AGENT_VERSION = "2.6.4"; private static final String PLUGIN_VERSION = "18.2.2"; @Override public String getAgentType() { return AGENT_TYPE; } @Override public String getAgentVersion() { return AGENT_VERSION; } @Override public String getPluginVersion() { return PLUGIN_VERSION; } }
package permafrost.tundra.lang; import com.wm.data.IData; import org.xml.sax.SAXParseException; import java.util.Arrays; import java.util.Collection; /** * A collection of convenience methods for working with exceptions. */ public class ExceptionHelper { /** * Disallow instantiation of this class. */ private ExceptionHelper() {} /** * Throws a new BaseException whose message is constructed from the given * list of causes. * * @param causes The list of exceptions which caused this new BaseException to be thrown. * @throws BaseException Always throws a new BaseException using the given list of causes. */ public static void raise(Throwable ... causes) throws BaseException { raise(getMessage(causes)); } /** * Throws a new BaseException whose message is constructed from the given * list of causes. * * @param causes The list of exceptions which caused this new BaseException to be thrown. * @throws BaseException Always throws a new BaseException using the given list of causes. */ public static void raise(Collection<Throwable> causes) throws BaseException { raise(getMessage(causes == null ? null : causes.toArray(new Throwable[causes.size()]))); } /** * Throws a new BaseException whose message is constructed from the given * cause. * * @param message A message describing why this new BaseException was thrown. * @param cause The exception which caused this new BaseException to be thrown. * @throws BaseException Always throws a new BaseException using the given message and cause. */ public static void raise(String message, Throwable cause) throws BaseException { throw new BaseException(message, cause); } /** * Throws a new BaseException whose message is constructed from the given * cause, unless the cause is already a BaseException in which case it is * rethrown without modification. * * @param cause The exception which caused this new BaseException to * be thrown. * @throws BaseException The given Throwable if it is already a BaseException, * otherwise a new BaseException constructed with the * given Throwable as its cause. */ public static void raise(Throwable cause) throws BaseException { if (cause instanceof BaseException) { throw (BaseException)cause; } else { throw new BaseException(cause); } } /** * Throws a new BaseException with the given message. * * @param message A message describing why this new BaseException was thrown. * @throws BaseException Always throws a new BaseException using the given message. */ public static void raise(String message) throws BaseException { throw new BaseException(message); } /** * Throws a new BaseException. * * @throws BaseException Always throws a new BaseException. */ public static void raise() throws BaseException { throw new BaseException(); } /** * Returns a message describing the given exception. * * @param exception An exception whose message is to be retrieved. * @return A message describing the given exception. */ public static String getMessage(Throwable exception) { if (exception == null) return ""; StringBuilder builder = new StringBuilder(); builder.append(exception.getClass().getName()); builder.append(": "); builder.append(exception.getMessage()); if (exception instanceof SAXParseException) { SAXParseException parseException = (SAXParseException)exception; //builder.append(" (Line ").append("" + ex.getLineNumber()).append(", Column ").append("" + ex.getColumnNumber()).append(")"); builder.append(String.format(" (Line %d, Column %d)", parseException.getLineNumber(), parseException.getColumnNumber())); } return builder.toString(); } /** * Returns a message describing the given list of exceptions. * * @param exceptions A list of exceptions whose messages are to be retrieved. * @return A message describing all exceptions in the given list. */ public static String getMessage(Collection<Throwable> exceptions) { if (exceptions == null) return ""; return getMessage(exceptions.toArray(new Throwable[exceptions.size()])); } /** * Returns a message describing the given list of exceptions. * * @param exceptions A list of exceptions whose messages are to be retrieved. * @return A message describing all exceptions in the given list. */ public static String getMessage(Throwable ... exceptions) { return ArrayHelper.join(getMessages(exceptions), "\n"); } /** * Returns a message describing the given list of exceptions. * * @param exceptions A list of exceptions whose messages are to be retrieved. * @return A message describing all exceptions in the given list. */ public static Collection<String> getMessages(Collection<Throwable> exceptions) { if (exceptions == null) return null; return Arrays.asList(getMessages(exceptions.toArray(new Throwable[exceptions.size()]))); } /** * Returns a message describing the given list of exceptions. * * @param exceptions A list of exceptions whose messages are to be retrieved. * @return A message describing all exceptions in the given list. */ public static String[] getMessages(Throwable ... exceptions) { if (exceptions == null) return null; String[] messages = new String[exceptions.length]; for (int i = 0; i < exceptions.length; i++) { if (exceptions[i] != null) { messages[i] = String.format("[%d] %s", i, getMessage(exceptions[i])); } } return messages; } /** * Returns the call stack associated with the given exception as an IData[] document list. * * @param exception An exception to retrieve the call stack from. * @return The call stack associated with the given exception as an IData[] document list. */ public static IData[] getStackTrace(Throwable exception) { if (exception == null) return null; return StackTraceElementHelper.toIDataArray(exception.getStackTrace()); } }
package pixlepix.auracascade.item; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import pixlepix.auracascade.data.AuraQuantity; import pixlepix.auracascade.data.EnumAura; import pixlepix.auracascade.data.recipe.PylonRecipe; import pixlepix.auracascade.data.recipe.PylonRecipeComponent; import pixlepix.auracascade.data.recipe.PylonRecipeRegistry; import pixlepix.auracascade.registry.BlockRegistry; import pixlepix.auracascade.registry.ITTinkererItem; import pixlepix.auracascade.registry.ThaumicTinkererRecipe; import java.util.ArrayList; import java.util.List; public class ItemMaterial extends Item implements ITTinkererItem { public static String[] names = new String[]{"ingot", "gem", "prism"}; public EnumAura aura; //0 = Ingot //1 = Gem //2 = Prism (Only 1 color) //Note that the prism only comes in "White" color //Left like this as multicolored prisms are planned in the future public int materialIndex; public ItemMaterial(EnumAura aura, int materialIndex) { super(); this.aura = aura; this.materialIndex = materialIndex; } public ItemMaterial(MaterialPair materialPair) { this(materialPair.aura, materialPair.materialIndex); } public ItemMaterial() { this(EnumAura.WHITE_AURA, 2); } public static ItemMaterial getItemFromSpecs(MaterialPair pair) { List<Item> blockList = BlockRegistry.getItemFromClass(ItemMaterial.class); for (Item b : blockList) { ItemMaterial itemMaterial = (ItemMaterial) b; if (pair.aura == itemMaterial.aura && pair.materialIndex == itemMaterial.materialIndex) { return itemMaterial; } } return null; } @Override public ArrayList<Object> getSpecialParameters() { ArrayList<Object> result = new ArrayList<Object>(); for (int i = 0; i < 2; i++) { for (EnumAura auraCons : EnumAura.values()) { result.add(new MaterialPair(auraCons, i)); } } return result; } @Override public String getItemName() { return names[materialIndex] + aura.name; } @Override public boolean shouldRegister() { return true; } @Override public boolean shouldDisplayInTab() { return true; } @Override public ThaumicTinkererRecipe getRecipeItem() { if (materialIndex == 1) { PylonRecipeRegistry.registerRecipe(new PylonRecipe( new ItemStack(this), new PylonRecipeComponent(new AuraQuantity(EnumAura.WHITE_AURA, 600000), new ItemStack(Items.diamond)), new PylonRecipeComponent(new AuraQuantity(EnumAura.WHITE_AURA, 50000), new ItemStack(getItemFromSpecs(new MaterialPair(aura, 0)))), new PylonRecipeComponent(new AuraQuantity(EnumAura.WHITE_AURA, 50000), new ItemStack(getItemFromSpecs(new MaterialPair(aura, 0)))), new PylonRecipeComponent(new AuraQuantity(EnumAura.WHITE_AURA, 50000), new ItemStack(getItemFromSpecs(new MaterialPair(aura, 0)))))); } return null; } //Private class for constructor public static class MaterialPair { private final EnumAura aura; private final int materialIndex; public MaterialPair(EnumAura aura, int materialIndex) { this.aura = aura; this.materialIndex = materialIndex; } } }
package pl.domzal.junit.docker.rule; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Level; import org.junit.Rule; import org.junit.rules.ExternalResource; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.spotify.docker.client.DefaultDockerClient; import com.spotify.docker.client.DockerCertificateException; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerClient.ListImagesParam; import com.spotify.docker.client.DockerClient.LogsParam; import com.spotify.docker.client.DockerException; import com.spotify.docker.client.ImageNotFoundException; import com.spotify.docker.client.LogStream; import com.spotify.docker.client.messages.ContainerConfig; import com.spotify.docker.client.messages.ContainerCreation; import com.spotify.docker.client.messages.ContainerInfo; import com.spotify.docker.client.messages.ContainerState; import com.spotify.docker.client.messages.HostConfig; import com.spotify.docker.client.messages.Image; import com.spotify.docker.client.messages.NetworkSettings; import com.spotify.docker.client.messages.PortBinding; import pl.domzal.junit.wait.WaitForUnit; import pl.domzal.junit.wait.WaitForUnit.WaitForCondition; public class DockerRule extends ExternalResource { private static Logger log = LoggerFactory.getLogger(DockerRule.class); private static final int STOP_TIMEOUT = 5; private final DockerClient dockerClient; private ContainerCreation container; private final DockerRuleBuiler builder; private Map<String, List<PortBinding>> containerPorts; public DockerRule(DockerRuleBuiler builder) { this.builder = builder; String imageNameWithTag = imageNameWithTag(builder.imageName()); HostConfig hostConfig = HostConfig.builder() .publishAllPorts(true) .binds(builder.binds()) .extraHosts(builder.extraHosts()) .build(); ContainerConfig containerConfig = ContainerConfig.builder() .hostConfig(hostConfig) .image(imageNameWithTag) .networkDisabled(false) .cmd(builder.cmd()).build(); try { dockerClient = DefaultDockerClient.fromEnv().build(); if (builder.imageAlwaysPull() || ! imageAvaliable(dockerClient, imageNameWithTag)) { dockerClient.pull(imageNameWithTag); } container = dockerClient.createContainer(containerConfig); log.info("container {} started, id {}", imageNameWithTag, container.id()); } catch (ImageNotFoundException e) { throw new ImagePullException(String.format("Image '%s' not found", imageNameWithTag), e); } catch (DockerException | InterruptedException | DockerCertificateException e) { throw new IllegalStateException(e); } } public static DockerRuleBuiler builder() { return new DockerRuleBuiler(); } @Override protected void before() throws Throwable { super.before(); dockerClient.startContainer(container.id()); log.debug("{} started", container.id()); ContainerInfo inspectContainer = dockerClient.inspectContainer(container.id()); log.debug("{} inspect", container.id()); containerPorts = inspectContainer.networkSettings().ports(); if (builder.waitForMessage()!=null) { waitForMessage(); } logMappings(dockerClient); } private boolean imageAvaliable(DockerClient dockerClient, String imageName) throws DockerException, InterruptedException { String imageNameWithTag = imageNameWithTag(imageName); List<Image> listImages = dockerClient.listImages(ListImagesParam.danglingImages(false)); for (Image image : listImages) { if (image.repoTags().contains(imageNameWithTag)) { log.debug("image '{}' found", imageNameWithTag); return true; } } log.debug("image '{}' not found", imageNameWithTag); return false; } private String imageNameWithTag(String imageName) { if (! StringUtils.contains(imageName, ':')) { return imageName + ":latest"; } else { return imageName; } } private void waitForMessage() throws TimeoutException, InterruptedException { final String waitForMessage = builder.waitForMessage(); log.info("{} waiting for log message '{}'", container.id(), waitForMessage); new WaitForUnit(TimeUnit.SECONDS, 30, new WaitForCondition(){ @Override public boolean isConditionMet() { return getLog().contains(waitForMessage); } @Override public String timeoutMessage() { return String.format("Timeout waiting for '%s'", waitForMessage); } }).startWaiting(); log.debug("{} message '{}' found", container.id(), waitForMessage); } @Override protected void after() { super.after(); try { ContainerState state = dockerClient.inspectContainer(container.id()).state(); log.debug("container state: {}", state); if (state.running()) { dockerClient.stopContainer(container.id(), STOP_TIMEOUT); log.info("{} stopped", container.id()); } if (!builder.keepContainer()) { dockerClient.removeContainer(container.id(), true); log.info("{} deleted", container.id()); } } catch (DockerException e) { throw new IllegalStateException(e); } catch (InterruptedException e) { throw new IllegalStateException(e); } } public final String getDockerHost() { return dockerClient.getHost(); } /** * Get host dynamic port given container port was mapped to. * * @param containerPort Container port. Typically it matches Dockerfile EXPOSE directive. * @return Host port conteiner port is exposed on. */ public final String getExposedContainerPort(String containerPort) { String key = containerPort + "/tcp"; List<PortBinding> list = containerPorts.get(key); if (list == null || list.size() == 0) { throw new IllegalStateException(String.format("%s is not exposed", key)); } if (list.size() == 0) { throw new IllegalStateException(String.format("binding list for %s is empty", key)); } if (list.size() > 1) { throw new IllegalStateException(String.format("binding list for %s is longer than 1", key)); } return list.get(0).hostPort(); } private void logMappings(DockerClient dockerClient) throws DockerException, InterruptedException { ContainerInfo inspectContainer = dockerClient.inspectContainer(container.id()); NetworkSettings networkSettings = inspectContainer.networkSettings(); log.info("{} exposed ports: {}", container.id(), networkSettings.ports()); } /** * Stop and wait till given string will show in container output. * * @param searchString String to wait for in container output. * @param waitTime Wait time. * @throws TimeoutException On wait timeout. */ public void waitFor(final String searchString, int waitTime) throws TimeoutException, InterruptedException { new WaitForUnit(TimeUnit.SECONDS, waitTime, TimeUnit.SECONDS, 1, new WaitForCondition() { @Override public boolean isConditionMet() { return StringUtils.contains(getLog(), searchString); } @Override public String tickMessage() { return String.format("wait for '%s' in log", searchString); } @Override public String timeoutMessage() { return String.format("container log: \n%s", getLog()); } }) .setLogLevelBeginEnd(Level.DEBUG) .setLogLevelProgress(Level.TRACE) .startWaiting(); } /** * Wait for container exit. Please note this is blocking call. */ public void waitForExit() throws InterruptedException { try { dockerClient.waitContainer(container.id()); } catch (DockerException e) { throw new IllegalStateException(e); } } /** * Container log. */ public String getLog() { try (LogStream stream = dockerClient.logs(container.id(), LogsParam.stdout(), LogsParam.stderr());) { String fullLog = stream.readFully(); if (log.isTraceEnabled()) { log.trace("{} full log: {}", container.id(), StringUtils.replace(fullLog, "\n", "|")); } return fullLog; } catch (DockerException | InterruptedException e) { throw new IllegalStateException(e); } } /** * Id of container. */ String getContainerId() { return container.id(); } /** * {@link DockerClient} for direct container manipulation. */ DockerClient getDockerClient() { return dockerClient; } }
package programminglife.model.drawing; import programminglife.model.Dummy; import programminglife.model.Node; import programminglife.model.XYCoordinate; import programminglife.utility.Console; import java.util.*; /** * A part of a {@link programminglife.model.Graph}. It uses a centerNode and a radius. * Roughly, every node reachable within radius steps from centerNode is included in this graph. * When updating the centerNode or the radius, it also updates the Nodes within this SubGraph. */ public class SubGraph { /** * The amount of padding between layers (horizontal padding). */ private static final int LAYER_PADDING = 20; /** * The amount of padding between nodes within a Layer (vertical padding). */ private static final int LINE_PADDING = 30; private LinkedHashMap<Node, DrawableNode> nodes; private DrawableNode centerNode; private boolean layout; /** * The radius around the center node. Eventually, * this SubGraph should only include nodes with a *longest* path of at most radius. * Radius is zero-based, i.e. a radius of 0 is only the centerNode, * radius of 1 is centerNode plus all its children and parents, etc. */ private int radius; // TODO: cache topological sorting (inside topoSort(), only recalculate when adding / removing nodes) // important: directly invalidate cache (set to null), because otherwise removed nodes // can't be garbage collected until next call to topoSort() /** * Create a SubGraph using a centerNode and a radius around that centerNode. * This SubGraph will include all Nodes within radius steps to a parent, * and then another 2radius steps to a child, and symmetrically the same with children / parents reversed. * @param centerNode The centerNode * @param radius The radius */ public SubGraph(DrawableNode centerNode, int radius) { // TODO // tactic: first go to all parents at exactly radius, then find all children of those parents this.centerNode = centerNode; this.radius = radius; this.layout = false; // TODO: also go from all parents to children within 2*radius + 1; and vice-versa from children. this.nodes = findParents(centerNode, radius); this.nodes.putAll(findChildren(centerNode, radius)); if (!this.nodes.containsKey(centerNode.getNode())) { this.nodes.put(centerNode.getNode(), centerNode); } } // TODO: change findParents and findChildren to reliably only find nodes with a *longest* path of at most radius. // (maybe give that their own method, or possibly two methods with a // boolean flag for using longest or shortest path as determining factor for the radius) /** * Find the parents for a single {@link DrawableNode} up to radius. * This method returns a set with all nodes with a shortest path of at most radius. * @param node The node to start from. * @param radius Number indicating the number of steps to take. * @return A set of all ancestors within radius steps. */ private LinkedHashMap<Node, DrawableNode> findParents(DrawableNode node, int radius) { Set<DrawableNode> nodeSet = new HashSet<>(); nodeSet.add(node); return findParents(nodeSet, radius); } /** * Find the parents for a set of {@link DrawableNode DrawableNodes} up to radius. * This method returns a set with all nodes with a shortest * path of at most radius to at least one of the nodes in the set. * @param nodes The set of nodes to start from. * @param radius Number indicating the number of steps to take. * @return A set of all ancestors within radius steps. */ private LinkedHashMap<Node, DrawableNode> findParents(Set<DrawableNode> nodes, int radius) { LinkedHashMap<Node, DrawableNode> found = new LinkedHashMap<>(); for (DrawableNode node : nodes) { findParents(found, node, radius); } return found; } /** * Find the parents for a single {@link DrawableNode} up to radius. * This method returns a set with all nodes with a shortest path of at most radius. * @param found The Set of nodes that have been found. Nodes found by this method will be added to the set. * @param node The node to start from. * @param radius Number indicating the number of steps to take. */ private void findParents(LinkedHashMap<Node, DrawableNode> found, DrawableNode node, int radius) { // TODO: improve datastructure so that parents can be safely skipped if already found // it can currently not safely be skipped: 0-1-2-3-4 // assuming radius 3, if you find the nodes in the order 0, 1, 2, 3, // you cannot skip 3 as that would then miss 4 (which is also within radius 3, via 0-1-3-4) //Also check the childeren if one of the nodes has not been added yet. if (this.radius <= 0) { return; } for (Node child : node.getChildren()) { if (!found.containsKey(child)) { found.put(child, new DrawableNode(child)); findChildren(found, found.get(child), 2 * this.radius - radius - 1); } } if (radius <= 0) { return; } radius--; // decrease radius once instead of multiple times within the loop; for (Node parent : node.getParents()) { if (!found.containsKey(parent)) { found.put(parent, new DrawableNode(parent)); findParents(found, found.get(parent), radius); } } } /** * Find the parents for a single {@link DrawableNode} up to radius. * This method returns a set with all nodes with a shortest path of at most radius. * @param node The node to start from. * @param radius Number indicating the number of steps to take. * @return A set of all ancestors within radius steps. */ private LinkedHashMap<Node, DrawableNode> findChildren(DrawableNode node, int radius) { Set<DrawableNode> nodeSet = new HashSet<>(); nodeSet.add(node); return findChildren(nodeSet, radius); } /** * Find the parents for a set of {@link DrawableNode DrawableNodes} up to radius. * This method returns a set with all nodes with a shortest * path of at most radius to at least one of the nodes in the set. * @param nodes The set of nodes to start from. * @param radius Number indicating the number of steps to take. * @return A set of all ancestors within radius steps. */ private LinkedHashMap<Node, DrawableNode> findChildren(Set<DrawableNode> nodes, int radius) { LinkedHashMap<Node, DrawableNode> found = new LinkedHashMap<>(); //Put all node that are already found by findparents into the find. for (DrawableNode node: nodes) { found.put(node.getNode(), node); } for (DrawableNode node : nodes) { findChildren(found, node, radius); } return found; } /** * Find the parents for a single {@link DrawableNode} up to radius. * This method returns a set with all nodes with a shortest path of at most radius. * @param found The Set of nodes that have been found. Nodes found by this method will be added to the set. * @param node The node to start from. * @param radius Number indicating the number of steps to take. */ private void findChildren(LinkedHashMap<Node, DrawableNode> found, DrawableNode node, int radius) { // TODO: improve datastructure so that parents can be safely skipped if already found // it can currently not safely be skipped: 0-1-2-3-4 // assuming radius 3, if you find the nodes in the order 0, 1, 2, 3, // you cannot skip 3 as that would then miss 4 (which is also within radius 3, via 0-1-3-4) if (this.radius <= 0) { return; } for (Node parent : node.getParents()) { if (!found.containsKey(parent)) { found.put(parent, new DrawableNode(parent)); findParents(found, found.get(parent), 2 * this.radius - radius - 1); } } if (radius <= 0) { return; } radius--; // decrease radius once instead of multiple times within the loop; for (Node child : node.getChildren()) { if (!found.containsKey(child)) { found.put(child, new DrawableNode(child)); findChildren(found, found.get(child), radius); } } } /** * Draw this SubGraph on the screen. */ public void draw() { } /** * Find out which {@link Drawable} is at the given location. * @param loc The location to search for Drawables. * @return The {@link Drawable} that is on top at the given location. */ public Drawable atLocation(XYCoordinate loc) { return this.atLocation(loc.getX(), loc.getY()); } /** * Find out which {@link Drawable} is at the given location. * @param x The x coordinate * @param y The y coordinate * @return The {@link Drawable} that is on top at the given location. */ public Drawable atLocation(double x, double y) { // TODO: implement; throw new Error("Not implemented yet"); } /** * Lay out the {@link Drawable Drawables} in this SubGraph. */ public void layout() { if (layout) { return; } List<Layer> layers = findLayers(); createDummyNodes(layers); sortWithinLayers(layers); int x = 50; int size = 1; for (Layer layer : layers) { int newSize = layer.size(); int diff = Math.abs(newSize - size); int y = 50; x += LAYER_PADDING * 0.1 * newSize; x += LAYER_PADDING * 0.6 * diff; for (DrawableNode d : layer) { if (d.getNode() instanceof Dummy) { d.setLocation(new XYCoordinate(x, y + 5)); } else { d.setLocation(new XYCoordinate(x, y)); } y += LINE_PADDING; } x += layer.getWidth() + LAYER_PADDING * 0.1 * newSize; size = newSize; } layout = true; // TODO: translate so that the centerNode is at 0,0; } /** * Create Dummy nodes for layers to avoid more crossing edges. * @param layers {@link List} representing all layers to be drawn. */ private void createDummyNodes(List<Layer> layers) { int dummyId = -1; Layer current = new Layer(); for (Layer next : layers) { for (DrawableNode node : current) { for (DrawableNode child : this.getChildren(node)) { if (!next.contains(child)) { DrawableNode dummy = new DrawableNode( new Dummy(dummyId, child.getNode(), node.getLink(child), node.getNode()) ); dummyId node.replaceChild(child, dummy); child.replaceParent(node, dummy); dummy.setWidth(next.getWidth()); this.nodes.put(dummy.getNode(), dummy); next.add(dummy); } } } current = next; } } /** * Put all nodes in {@link Layer Layers}. This method is used when {@link #layout() laying out} the graph. * This will put each node in a Layer one higher than each of its parents. * @return A {@link List} of Layers with all the nodes (all nodes are divided over the Layers). */ private List<Layer> findLayers() { long startTime = System.nanoTime(); List<DrawableNode> sorted = topoSort(); long finishTime = System.nanoTime(); long differenceTime = finishTime - startTime; long milisecondTime = differenceTime / 1000000; Console.println("TIMERINO OF TOPOSORTERINO: " + milisecondTime); Console.println("Amount of nodes: " + sorted.size()); Map<DrawableNode, Integer> nodeLevel = new HashMap<>(); List<Layer> layerList = new ArrayList<>(); for (DrawableNode node : sorted) { int maxParentLevel = -1; for (DrawableNode parent : this.getParents(node)) { Integer parentLevel = nodeLevel.get(parent); if (parentLevel == null) { continue; } else if (maxParentLevel < parentLevel) { maxParentLevel = parentLevel; } } maxParentLevel++; // we want this node one level higher than the highest parent. nodeLevel.put(node, maxParentLevel); if (layerList.size() <= maxParentLevel) { layerList.add(new Layer()); } layerList.get(maxParentLevel).add(node); } return layerList; } /** * Get the parents of {@link DrawableNode} node. * @param node The {@link DrawableNode} to get * @return A {@link Collection} of {@link DrawableNode} */ public Collection<DrawableNode> getParents(DrawableNode node) { Collection<DrawableNode> parents = new LinkedHashSet<>(); for (Node parentNode : node.getParents()) { if (this.nodes.containsKey(parentNode)) { parents.add(this.nodes.get(parentNode)); } } return parents; } /** * Get the children of {@link DrawableNode} node. * @param node The {@link DrawableNode} to get * @return A {@link Collection} of {@link DrawableNode} */ public Collection<DrawableNode> getChildren(DrawableNode node) { Collection<DrawableNode> children = new LinkedHashSet<>(); for (Node childNode : node.getChildren()) { if (this.nodes.containsKey(childNode)) { children.add(this.nodes.get(childNode)); } } return children; } /** * Sort each Layer to minimize edge crossings between the Layers. * @param layers The layers to sort. */ private void sortWithinLayers(List<Layer> layers) { ListIterator<Layer> nextIter = layers.listIterator(); // find a layer with a single node Layer prev = null; while (nextIter.hasNext()) { prev = nextIter.next(); if (prev.size() == 1) { break; } } Layer next = prev; ListIterator<Layer> prevIter = layers.listIterator(nextIter.previousIndex()); while (nextIter.hasNext()) { Layer layer = nextIter.next(); layer.sort(this, prev, true); prev = layer; } while (prevIter.hasPrevious()) { Layer layer = prevIter.previous(); layer.sort(this, next, false); next = layer; } } /** * Topologically sort the nodes from this graph. * * Assumption: graph is a DAG. * @return a topologically sorted list of nodes */ public List<DrawableNode> topoSort() { // topo sorted list ArrayList<DrawableNode> res = new ArrayList<>(this.nodes.size()); // nodes that have not yet been added to the list. LinkedHashSet<DrawableNode> found = new LinkedHashSet<>(); // tactic: // take any node. see if any parents were not added yet. // If so, clearly that parent needs to be added first. Continue searching from parent. // If not, we found a node that can be next in the ordering. Add it to the list. // Repeat until all nodes are added to the list. for (DrawableNode n : this.nodes.values()) { if (!found.add(n)) { continue; } topoSortFromNode(res, found, n); } // TODO: use better strategy // 1 O(1) create sorted set of (number, node) pairs (sort by number) // 2 O(n) for each node, add to set as (node.parents.size(), node) // 3 O(n+m) for each node in the list { // 3.1 O(1) remove first pair from list (assert that number = 0), add node to resultList. // 3.2 O((deg(v)) for each child of node, decrease number by one (make sure that list is still sorted!). // done. // TODO: add a test that this works. see assert below. // assert that list is sorted? // create set found // for each node: add to found, check if any of children in found. If yes, fail. // if none of the children for all nodes were in found: pass. assert (res.size() == this.nodes.size()); return res; } /** * Toposort all ancestors of a node. * @param result The reult list to which these nodes will be added, * @param found The nodes that have already been found, * @param node The node to start seaching from. */ private void topoSortFromNode(ArrayList<DrawableNode> result, LinkedHashSet<DrawableNode> found, DrawableNode node) { for (Node parent : node.getParents()) { DrawableNode drawableParent = this.nodes.get(parent); if (drawableParent != null && found.add(drawableParent)) { topoSortFromNode(result, found, drawableParent); } } result.add(node); } /** * Set the centerNode of this SubGraph. * Nodes that are now outside the radius of this SubGraph will be removed, * and Nodes that are now inside will be added. * @param centerNode The new centerNode. */ public void setCenterNode(Node centerNode) { // TODO // drop nodes that are now outside radius // include nodes that have come into radius // drop nodes that are only connected via nodes now outside radius? } /** * Set the radius of this SubGraph. * Nodes that are now outside the radius of this SubGraph will be removed, * and Nodes that are now inside will be added. * @param radius The new radius. */ public void setRadius(int radius) { // TODO // when getting bigger: include new nodes // when getting smaller: drop nodes outside new radius. } public LinkedHashMap<Node, DrawableNode> getNodes() { return this.nodes; } }
package redis.clients.jedis; import java.nio.ByteBuffer; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; public class BinaryJedisCluster implements BinaryJedisCommands, BasicCommands, JedisClusterBinaryScriptingCommands { public static final short HASHSLOTS = 16384; protected static final int DEFAULT_TIMEOUT = 1; protected static final int DEFAULT_MAX_REDIRECTIONS = 5; protected int timeout; protected int maxRedirections; protected JedisClusterConnectionHandler connectionHandler; public BinaryJedisCluster(Set<HostAndPort> nodes, int timeout) { this(nodes, timeout, DEFAULT_MAX_REDIRECTIONS); } public BinaryJedisCluster(Set<HostAndPort> nodes) { this(nodes, DEFAULT_TIMEOUT); } public BinaryJedisCluster(Set<HostAndPort> jedisClusterNode, int timeout, int maxRedirections) { this.connectionHandler = new JedisSlotBasedConnectionHandler( jedisClusterNode); this.timeout = timeout; this.maxRedirections = maxRedirections; } @Override public String set(final byte[] key, final byte[] value) { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.set(key, value); } }.runBinary(key); } @Override public byte[] get(final byte[] key) { return new JedisClusterCommand<byte[]>(connectionHandler, timeout, maxRedirections) { @Override public byte[] execute(Jedis connection) { return connection.get(key); } }.runBinary(key); } @Override public Boolean exists(final byte[] key) { return new JedisClusterCommand<Boolean>(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute(Jedis connection) { return connection.exists(key); } }.runBinary(key); } @Override public Long persist(final byte[] key) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.persist(key); } }.runBinary(key); } @Override public String type(final byte[] key) { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.type(key); } }.runBinary(key); } @Override public Long expire(final byte[] key, final int seconds) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.expire(key, seconds); } }.runBinary(key); } @Override public Long expireAt(final byte[] key, final long unixTime) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.expireAt(key, unixTime); } }.runBinary(key); } @Override public Long ttl(final byte[] key) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.ttl(key); } }.runBinary(key); } @Override public Boolean setbit(final byte[] key, final long offset, final boolean value) { return new JedisClusterCommand<Boolean>(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute(Jedis connection) { return connection.setbit(key, offset, value); } }.runBinary(key); } @Override public Boolean setbit(final byte[] key, final long offset, final byte[] value) { return new JedisClusterCommand<Boolean>(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute(Jedis connection) { return connection.setbit(key, offset, value); } }.runBinary(key); } @Override public Boolean getbit(final byte[] key, final long offset) { return new JedisClusterCommand<Boolean>(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute(Jedis connection) { return connection.getbit(key, offset); } }.runBinary(key); } @Override public Long setrange(final byte[] key, final long offset, final byte[] value) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.setrange(key, offset, value); } }.runBinary(key); } @Override public byte[] getrange(final byte[] key, final long startOffset, final long endOffset) { return new JedisClusterCommand<byte[]>(connectionHandler, timeout, maxRedirections) { @Override public byte[] execute(Jedis connection) { return connection.getrange(key, startOffset, endOffset); } }.runBinary(key); } @Override public byte[] getSet(final byte[] key, final byte[] value) { return new JedisClusterCommand<byte[]>(connectionHandler, timeout, maxRedirections) { @Override public byte[] execute(Jedis connection) { return connection.getSet(key, value); } }.runBinary(key); } @Override public Long setnx(final byte[] key, final byte[] value) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.setnx(key, value); } }.runBinary(key); } @Override public String setex(final byte[] key, final int seconds, final byte[] value) { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.setex(key, seconds, value); } }.runBinary(key); } @Override public Long decrBy(final byte[] key, final long integer) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.decrBy(key, integer); } }.runBinary(key); } @Override public Long decr(final byte[] key) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.decr(key); } }.runBinary(key); } @Override public Long incrBy(final byte[] key, final long integer) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.incrBy(key, integer); } }.runBinary(key); } @Override public Long incr(final byte[] key) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.incr(key); } }.runBinary(key); } @Override public Long append(final byte[] key, final byte[] value) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.append(key, value); } }.runBinary(key); } @Override public byte[] substr(final byte[] key, final int start, final int end) { return new JedisClusterCommand<byte[]>(connectionHandler, timeout, maxRedirections) { @Override public byte[] execute(Jedis connection) { return connection.substr(key, start, end); } }.runBinary(key); } @Override public Long hset(final byte[] key, final byte[] field, final byte[] value) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.hset(key, field, value); } }.runBinary(key); } @Override public byte[] hget(final byte[] key, final byte[] field) { return new JedisClusterCommand<byte[]>(connectionHandler, timeout, maxRedirections) { @Override public byte[] execute(Jedis connection) { return connection.hget(key, field); } }.runBinary(key); } @Override public Long hsetnx(final byte[] key, final byte[] field, final byte[] value) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.hsetnx(key, field, value); } }.runBinary(key); } @Override public String hmset(final byte[] key, final Map<byte[], byte[]> hash) { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.hmset(key, hash); } }.runBinary(key); } @Override public List<byte[]> hmget(final byte[] key, final byte[]... fields) { return new JedisClusterCommand<List<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public List<byte[]> execute(Jedis connection) { return connection.hmget(key, fields); } }.runBinary(key); } @Override public Long hincrBy(final byte[] key, final byte[] field, final long value) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.hincrBy(key, field, value); } }.runBinary(key); } @Override public Boolean hexists(final byte[] key, final byte[] field) { return new JedisClusterCommand<Boolean>(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute(Jedis connection) { return connection.hexists(key, field); } }.runBinary(key); } @Override public Long hdel(final byte[] key, final byte[]... field) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.hdel(key, field); } }.runBinary(key); } @Override public Long hlen(final byte[] key) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.hlen(key); } }.runBinary(key); } @Override public Set<byte[]> hkeys(final byte[] key) { return new JedisClusterCommand<Set<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public Set<byte[]> execute(Jedis connection) { return connection.hkeys(key); } }.runBinary(key); } @Override public Collection<byte[]> hvals(final byte[] key) { return new JedisClusterCommand<Collection<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public Collection<byte[]> execute(Jedis connection) { return connection.hvals(key); } }.runBinary(key); } @Override public Map<byte[], byte[]> hgetAll(final byte[] key) { return new JedisClusterCommand<Map<byte[], byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public Map<byte[], byte[]> execute(Jedis connection) { return connection.hgetAll(key); } }.runBinary(key); } @Override public Long rpush(final byte[] key, final byte[]... args) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.rpush(key, args); } }.runBinary(key); } @Override public Long lpush(final byte[] key, final byte[]... args) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.lpush(key, args); } }.runBinary(key); } @Override public Long llen(final byte[] key) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.llen(key); } }.runBinary(key); } @Override public List<byte[]> lrange(final byte[] key, final long start, final long end) { return new JedisClusterCommand<List<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public List<byte[]> execute(Jedis connection) { return connection.lrange(key, start, end); } }.runBinary(key); } @Override public String ltrim(final byte[] key, final long start, final long end) { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.ltrim(key, start, end); } }.runBinary(key); } @Override public byte[] lindex(final byte[] key, final long index) { return new JedisClusterCommand<byte[]>(connectionHandler, timeout, maxRedirections) { @Override public byte[] execute(Jedis connection) { return connection.lindex(key, index); } }.runBinary(key); } @Override public String lset(final byte[] key, final long index, final byte[] value) { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.lset(key, index, value); } }.runBinary(key); } @Override public Long lrem(final byte[] key, final long count, final byte[] value) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.lrem(key, count, value); } }.runBinary(key); } @Override public byte[] lpop(final byte[] key) { return new JedisClusterCommand<byte[]>(connectionHandler, timeout, maxRedirections) { @Override public byte[] execute(Jedis connection) { return connection.lpop(key); } }.runBinary(key); } @Override public byte[] rpop(final byte[] key) { return new JedisClusterCommand<byte[]>(connectionHandler, timeout, maxRedirections) { @Override public byte[] execute(Jedis connection) { return connection.rpop(key); } }.runBinary(key); } @Override public Long sadd(final byte[] key, final byte[]... member) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.sadd(key, member); } }.runBinary(key); } @Override public Set<byte[]> smembers(final byte[] key) { return new JedisClusterCommand<Set<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public Set<byte[]> execute(Jedis connection) { return connection.smembers(key); } }.runBinary(key); } @Override public Long srem(final byte[] key, final byte[]... member) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.srem(key, member); } }.runBinary(key); } @Override public byte[] spop(final byte[] key) { return new JedisClusterCommand<byte[]>(connectionHandler, timeout, maxRedirections) { @Override public byte[] execute(Jedis connection) { return connection.spop(key); } }.runBinary(key); } @Override public Long scard(final byte[] key) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.scard(key); } }.runBinary(key); } @Override public Boolean sismember(final byte[] key, final byte[] member) { return new JedisClusterCommand<Boolean>(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute(Jedis connection) { return connection.sismember(key, member); } }.runBinary(key); } @Override public byte[] srandmember(final byte[] key) { return new JedisClusterCommand<byte[]>(connectionHandler, timeout, maxRedirections) { @Override public byte[] execute(Jedis connection) { return connection.srandmember(key); } }.runBinary(key); } @Override public Long strlen(final byte[] key) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.strlen(key); } }.runBinary(key); } @Override public Long zadd(final byte[] key, final double score, final byte[] member) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.zadd(key, score, member); } }.runBinary(key); } @Override public Long zadd(final byte[] key, final Map<byte[], Double> scoreMembers) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.zadd(key, scoreMembers); } }.runBinary(key); } @Override public Set<byte[]> zrange(final byte[] key, final long start, final long end) { return new JedisClusterCommand<Set<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public Set<byte[]> execute(Jedis connection) { return connection.zrange(key, start, end); } }.runBinary(key); } @Override public Long zrem(final byte[] key, final byte[]... member) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.zrem(key, member); } }.runBinary(key); } @Override public Double zincrby(final byte[] key, final double score, final byte[] member) { return new JedisClusterCommand<Double>(connectionHandler, timeout, maxRedirections) { @Override public Double execute(Jedis connection) { return connection.zincrby(key, score, member); } }.runBinary(key); } @Override public Long zrank(final byte[] key, final byte[] member) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.zrank(key, member); } }.runBinary(key); } @Override public Long zrevrank(final byte[] key, final byte[] member) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.zrevrank(key, member); } }.runBinary(key); } @Override public Set<byte[]> zrevrange(final byte[] key, final long start, final long end) { return new JedisClusterCommand<Set<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public Set<byte[]> execute(Jedis connection) { return connection.zrevrange(key, start, end); } }.runBinary(key); } @Override public Set<Tuple> zrangeWithScores(final byte[] key, final long start, final long end) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, timeout, maxRedirections) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrangeWithScores(key, start, end); } }.runBinary(key); } @Override public Set<Tuple> zrevrangeWithScores(final byte[] key, final long start, final long end) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, timeout, maxRedirections) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrevrangeWithScores(key, start, end); } }.runBinary(key); } @Override public Long zcard(final byte[] key) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.zcard(key); } }.runBinary(key); } @Override public Double zscore(final byte[] key, final byte[] member) { return new JedisClusterCommand<Double>(connectionHandler, timeout, maxRedirections) { @Override public Double execute(Jedis connection) { return connection.zscore(key, member); } }.runBinary(key); } @Override public List<byte[]> sort(final byte[] key) { return new JedisClusterCommand<List<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public List<byte[]> execute(Jedis connection) { return connection.sort(key); } }.runBinary(key); } @Override public List<byte[]> sort(final byte[] key, final SortingParams sortingParameters) { return new JedisClusterCommand<List<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public List<byte[]> execute(Jedis connection) { return connection.sort(key, sortingParameters); } }.runBinary(key); } @Override public Long zcount(final byte[] key, final double min, final double max) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.zcount(key, min, max); } }.runBinary(key); } @Override public Long zcount(final byte[] key, final byte[] min, final byte[] max) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.zcount(key, min, max); } }.runBinary(key); } @Override public Set<byte[]> zrangeByScore(final byte[] key, final double min, final double max) { return new JedisClusterCommand<Set<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public Set<byte[]> execute(Jedis connection) { return connection.zrangeByScore(key, min, max); } }.runBinary(key); } @Override public Set<byte[]> zrangeByScore(final byte[] key, final byte[] min, final byte[] max) { return new JedisClusterCommand<Set<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public Set<byte[]> execute(Jedis connection) { return connection.zrangeByScore(key, min, max); } }.runBinary(key); } @Override public Set<byte[]> zrevrangeByScore(final byte[] key, final double max, final double min) { return new JedisClusterCommand<Set<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public Set<byte[]> execute(Jedis connection) { return connection.zrevrangeByScore(key, max,min); } }.runBinary(key); } @Override public Set<byte[]> zrangeByScore(final byte[] key, final double min, final double max, final int offset, final int count) { return new JedisClusterCommand<Set<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public Set<byte[]> execute(Jedis connection) { return connection.zrangeByScore(key, min, max, offset, count); } }.runBinary(key); } @Override public Set<byte[]> zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min) { return new JedisClusterCommand<Set<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public Set<byte[]> execute(Jedis connection) { return connection.zrevrangeByScore(key, max, min); } }.runBinary(key); } @Override public Set<byte[]> zrangeByScore(final byte[] key, final byte[] min, final byte[] max, final int offset, final int count) { return new JedisClusterCommand<Set<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public Set<byte[]> execute(Jedis connection) { return connection.zrangeByScore(key, min, max, offset, count); } }.runBinary(key); } @Override public Set<byte[]> zrevrangeByScore(final byte[] key, final double max, final double min, final int offset, final int count) { return new JedisClusterCommand<Set<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public Set<byte[]> execute(Jedis connection) { return connection.zrevrangeByScore(key, max, min, offset, count); } }.runBinary(key); } @Override public Set<Tuple> zrangeByScoreWithScores(final byte[] key, final double min, final double max) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, timeout, maxRedirections) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrangeByScoreWithScores(key, min, max); } }.runBinary(key); } @Override public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, timeout, maxRedirections) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrevrangeByScoreWithScores(key, max, min); } }.runBinary(key); } @Override public Set<Tuple> zrangeByScoreWithScores(final byte[] key, final double min, final double max, final int offset, final int count) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, timeout, maxRedirections) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrangeByScoreWithScores(key, min, max, offset, count); } }.runBinary(key); } @Override public Set<byte[]> zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min, final int offset, final int count) { return new JedisClusterCommand<Set<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public Set<byte[]> execute(Jedis connection) { return connection.zrevrangeByScore(key, max, min, offset, count); } }.runBinary(key); } @Override public Set<Tuple> zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, timeout, maxRedirections) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrangeByScoreWithScores(key, min, max); } }.runBinary(key); } @Override public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, final byte[] max, final byte[] min) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, timeout, maxRedirections) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrevrangeByScoreWithScores(key, max, min); } }.runBinary(key); } @Override public Set<Tuple> zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max, final int offset, final int count) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, timeout, maxRedirections) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrangeByScoreWithScores(key, min, max, offset, count); } }.runBinary(key); } @Override public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, final double max, final double min, final int offset, final int count) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, timeout, maxRedirections) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrevrangeByScoreWithScores(key, max, min, offset, count); } }.runBinary(key); } @Override public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, final byte[] max, final byte[] min, final int offset, final int count) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, timeout, maxRedirections) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrevrangeByScoreWithScores(key, max, min, offset, count); } }.runBinary(key); } @Override public Long zremrangeByRank(final byte[] key, final long start, final long end) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.zremrangeByRank(key, start, end); } }.runBinary(key); } @Override public Long zremrangeByScore(final byte[] key, final double start, final double end) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.zremrangeByScore(key, start, end); } }.runBinary(key); } @Override public Long zremrangeByScore(final byte[] key, final byte[] start, final byte[] end) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.zremrangeByScore(key, start, end); } }.runBinary(key); } @Override public Long linsert(final byte[] key, final Client.LIST_POSITION where, final byte[] pivot, final byte[] value) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.linsert(key, where, pivot, value); } }.runBinary(key); } @Override public Long lpushx(final byte[] key, final byte[]... arg) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.lpushx(key, arg); } }.runBinary(key); } @Override public Long rpushx(final byte[] key, final byte[]... arg) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.rpushx(key, arg); } }.runBinary(key); } @Override public List<byte[]> blpop(final byte[] arg) { return new JedisClusterCommand<List<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public List<byte[]> execute(Jedis connection) { return connection.blpop(arg); } }.runBinary(null); } @Override public List<byte[]> brpop(final byte[] arg) { return new JedisClusterCommand<List<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public List<byte[]> execute(Jedis connection) { return connection.brpop(arg); } }.runBinary(null); } @Override public Long del(final byte[] key) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.del(key); } }.runBinary(key); } @Override public byte[] echo(final byte[] arg) { return new JedisClusterCommand<byte[]>(connectionHandler, timeout, maxRedirections) { @Override public byte[] execute(Jedis connection) { return connection.echo(arg); } }.runBinary(null); } @Override public Long move(final byte[] key, final int dbIndex) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.move(key, dbIndex); } }.runBinary(key); } @Override public Long bitcount(final byte[] key) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.bitcount(key); } }.runBinary(key); } @Override public Long bitcount(final byte[] key, final long start, final long end) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.bitcount(key, start, end); } }.runBinary(key); } @Override public String ping() { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.ping(); } }.run(null); } @Override public String quit() { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.quit(); } }.run(null); } @Override public String flushDB() { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.flushDB(); } }.run(null); } @Override public Long dbSize() { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.dbSize(); } }.run(null); } @Override public String select(final int index) { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.select(index); } }.run(null); } @Override public String flushAll() { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.flushAll(); } }.run(null); } @Override public String auth(final String password) { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.auth(password); } }.run(null); } @Override public String save() { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.save(); } }.run(null); } @Override public String bgsave() { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.bgsave(); } }.run(null); } @Override public String bgrewriteaof() { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.bgrewriteaof(); } }.run(null); } @Override public Long lastsave() { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.lastsave(); } }.run(null); } @Override public String shutdown() { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.shutdown(); } }.run(null); } @Override public String info() { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.info(); } }.run(null); } @Override public String info(final String section) { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.info(section); } }.run(null); } @Override public String slaveof(final String host, final int port) { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.slaveof(host, port); } }.run(null); } @Override public String slaveofNoOne() { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.slaveofNoOne(); } }.run(null); } @Override public Long getDB() { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.getDB(); } }.run(null); } @Override public String debug(final DebugParams params) { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.debug(params); } }.run(null); } @Override public String configResetStat() { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.configResetStat(); } }.run(null); } public Map<String, JedisPool> getClusterNodes() { return connectionHandler.getNodes(); } @Override public Long waitReplicas(int replicas, long timeout) { // TODO Auto-generated method stub return null; } @Override public Object eval(final byte[] script, final byte[] keyCount, final byte[]... params) { return new JedisClusterCommand<Object>(connectionHandler, timeout, maxRedirections) { @Override public Object execute(Jedis connection) { return connection.eval(script, keyCount, params); } }.runBinary(ByteBuffer.wrap(keyCount).getInt(), params); } @Override public Object eval(final byte[] script, final int keyCount, final byte[]... params) { return new JedisClusterCommand<Object>(connectionHandler, timeout, maxRedirections) { @Override public Object execute(Jedis connection) { return connection.eval(script, keyCount, params); } }.runBinary(keyCount, params); } @Override public Object eval(final byte[] script, final List<byte[]> keys, final List<byte[]> args) { return new JedisClusterCommand<Object>(connectionHandler, timeout, maxRedirections) { @Override public Object execute(Jedis connection) { return connection.eval(script, keys, args); } }.runBinary(keys.size(), keys.toArray(new byte[keys.size()][])); } @Override public Object eval(final byte[] script, byte[] key) { return new JedisClusterCommand<Object>(connectionHandler, timeout, maxRedirections) { @Override public Object execute(Jedis connection) { return connection.eval(script); } }.runBinary(key); } @Override public Object evalsha(final byte[] script, byte[] key) { return new JedisClusterCommand<Object>(connectionHandler, timeout, maxRedirections) { @Override public Object execute(Jedis connection) { return connection.evalsha(script); } }.runBinary(key); } @Override public Object evalsha(final byte[] sha1, final List<byte[]> keys, final List<byte[]> args) { return new JedisClusterCommand<Object>(connectionHandler, timeout, maxRedirections) { @Override public Object execute(Jedis connection) { return connection.evalsha(sha1, keys, args); } }.runBinary(keys.size(), keys.toArray(new byte[keys.size()][])); } @Override public Object evalsha(final byte[] sha1, final int keyCount, final byte[]... params) { return new JedisClusterCommand<Object>(connectionHandler, timeout, maxRedirections) { @Override public Object execute(Jedis connection) { return connection.evalsha(sha1, keyCount, params); } }.runBinary(keyCount, params); } @Override public List<Long> scriptExists(final byte[] key, final byte[][] sha1) { return new JedisClusterCommand<List<Long>>(connectionHandler, timeout, maxRedirections) { @Override public List<Long> execute(Jedis connection) { return connection.scriptExists(sha1); } }.runBinary(key); } @Override public byte[] scriptLoad(final byte[] script, final byte[] key) { return new JedisClusterCommand<byte[]>(connectionHandler, timeout, maxRedirections) { @Override public byte[] execute(Jedis connection) { return connection.scriptLoad(script); } }.runBinary(key); } @Override public String scriptFlush(final byte[] key) { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.scriptFlush(); } }.runBinary(key); } @Override public String scriptKill(byte[] key) { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.scriptKill(); } }.runBinary(key); } }
package refinedstorage.api.util; import net.minecraft.item.ItemStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collection; /** * An item stack list. */ public interface IItemStackList { /** * Adds a stack to the list, will merge it with another stack if it already exists in the list. * * @param stack the stack */ void add(ItemStack stack); /** * Decrements the count of that stack in the list. * * @param stack the stack * @param removeIfReachedZero true to remove the stack if the count reaches 0, false otherwise * @return whether the remove was successful */ boolean remove(@Nonnull ItemStack stack, boolean removeIfReachedZero); /** * Returns a stack. * * @param stack the stack to search for * @param flags the flags to compare on, see {@link refinedstorage.api.storage.CompareUtils} * @return the stack, or null if no stack was found */ @Nullable ItemStack get(@Nonnull ItemStack stack, int flags); /** * Returns a stack. * * @param hash the hash of the stack to search for, see {@link refinedstorage.api.network.NetworkUtils#getItemStackHashCode(ItemStack)} * @return the stack, or null if no stack was found */ @Nullable ItemStack get(int hash); /** * Clears the list. */ void clear(); /** * @return true if the list is empty, false otherwise */ boolean isEmpty(); /** * @return a collection of stacks in this list */ @Nonnull Collection<ItemStack> getStacks(); /** * @return a new copy of this list, with the stacks in it copied as well */ @Nonnull IItemStackList copy(); }
package seedu.address.model.activity.task; import java.util.Calendar; import java.util.Objects; import seedu.address.commons.util.CollectionUtil; import seedu.address.model.activity.Activity; import seedu.address.model.activity.Name; import seedu.address.model.activity.ReadOnlyActivity; import seedu.address.model.activity.Reminder; import seedu.address.model.tag.UniqueTagList; public class Task extends Activity implements ReadOnlyTask { private DueDate duedate; private Priority priority; private boolean isCompleted; /** * Every field must be present and not null. */ public Task(Name name, DueDate dueDate, Priority priority, Reminder reminder, UniqueTagList tags) { super(name, reminder, tags); assert !CollectionUtil.isAnyNull(dueDate, priority); this.duedate = dueDate; this.priority = priority; this.isCompleted = false; } /** * Copy constructor. */ public Task(ReadOnlyTask source) { this(source.getName(), source.getDueDate(), source.getPriority(), source.getReminder(), source.getTags()); } @Override public DueDate getDueDate() { return duedate; } public void setDueDate(DueDate duedate) { this.duedate = duedate; } @Override public Priority getPriority() { return priority; } public void setPriority(Priority priority) { this.priority = priority; } @Override public boolean getCompletionStatus() { return isCompleted; } public void setCompletionStatus(boolean isComplete) { this.isCompleted = isComplete; } @Override public String toStringCompletionStatus() { if(isCompleted) { return "Completed"; } else if(!isCompleted && passedDueDate()){ return "Passed Due Date"; } return ""; } public boolean passedDueDate() { if(duedate.value == null) { return false; } else if(duedate.value.before(Calendar.getInstance())) { return true; } return false; } @Override public boolean equals(Object other) { if (this.getClass() != other.getClass()) { return false; } else { return other == this // short circuit if same object || (other instanceof ReadOnlyActivity // instanceof handles nulls && ((Task) other).getName().equals(this.getName()) // state checks here onwards && ((Task) other).getDueDate().equals(this.getDueDate()) && ((Task) other).getPriority().equals(this.getPriority()) && ((Task) other).getReminder().equals(this.getReminder())); } } @Override public int hashCode() { // use this method for custom fields hashing instead of implementing your own return Objects.hash(name, duedate, priority, reminder, tags); } @Override public String toString() { return getAsText(); } }
package seedu.tasklist.model.task; import seedu.tasklist.commons.util.CollectionUtil; import seedu.tasklist.model.tag.UniqueTagList; /** * Represents a Floating Task in the task list. * Guarantees: details are present and not null, field values are validated. */ public class FloatingTask implements ReadOnlyFloatingTask { private Name name; private Comment comment; private Priority priority; private Status status; private UniqueTagList tags; /** * Every field must be present and not null. */ public FloatingTask(Name name, Comment comment, Priority priority, Status status, UniqueTagList tags) { assert !CollectionUtil.isAnyNull(name, comment, priority,status, tags); this.name = name; this.comment = comment; this.priority = priority; this.status = status; this.tags = new UniqueTagList(tags); // protect internal tags from changes in the arg list } /** * Creates a copy of the given ReadOnlyTask. */ public FloatingTask(ReadOnlyFloatingTask source) { this(source.getName(), source.getComment(), source.getPriority(), source.getStatus(), source.getTags()); } @Override public Name getName() { return name; } @Override public Comment getComment() { return comment; } @Override public UniqueTagList getTags() { return tags; } public Priority getPriority() { return priority; } public Status getStatus() { return status; } }
package seedu.tasklist.model.task; import seedu.tasklist.model.tag.UniqueTagList; /** * A read-only immutable interface for a Task in the task list. * Implementations should guarantee: details are present and not null, field values are validated. */ public interface ReadOnlyTask { TaskDetails getTaskDetails(); StartTime getStartTime(); EndTime getEndTime(); Priority getPriority(); String getRecurringFrequency(); int getUniqueID(); boolean isFloating(); boolean isOverDue(); boolean isComplete(); boolean isRecurring(); boolean isToday(); boolean isTomorrow(); boolean isEvent(); /** * The returned TagList is a deep copy of the internal TagList, * changes on the returned list will not affect the person's internal tags. */ UniqueTagList getTags(); /** * Returns true if both have the same state. (interfaces cannot override .equals) */ default boolean isSameStateAs(ReadOnlyTask other) { return other == this // short circuit if same object || (other != null // this is first to avoid NPE below && other.getTaskDetails().equals(this.getTaskDetails()) // state checks here onwards && other.getStartTime().equals(this.getStartTime()) && other.getEndTime().equals(this.getEndTime()) && other.getPriority().equals(this.getPriority()) && (other.isRecurring() == this.isRecurring()) && other.getRecurringFrequency().equals(this.getRecurringFrequency()) && (other.getUniqueID()==this.getUniqueID())); } /** * Formats the person as text, showing all contact details. */ default String getAsText() { final StringBuilder builder = new StringBuilder(); builder.append(getTaskDetails()+ "\n") .append("Starts:\t") .append(getStartTime().toCardString() + "\t") .append("Ends:\t") .append(getEndTime().toCardString()+ "\n") .append("Priority:\t") .append(getPriority()+ "\n"); getTags().forEach(builder::append); return builder.toString(); } /** * Returns a string representation of this Person's tags */ default String tagsString() { final StringBuffer buffer = new StringBuffer(); final String separator = ", "; getTags().forEach(tag -> buffer.append(tag).append(separator)); if (buffer.length() == 0) { return ""; } else { return buffer.substring(0, buffer.length() - separator.length()); } } }
package seedu.taskmanager.model.task; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import seedu.taskmanager.commons.exceptions.IllegalValueException; /** * Represents a Task's start date in the task manager. Guarantees: immutable; is * valid as declared in {@link #isValidStartDate(String)} */ public class StartDate extends Date { private static final SimpleDateFormat sdfInput = new SimpleDateFormat("dd/MM/yyyy"); public static final String MESSAGE_STARTDATE_CONSTRAINTS = "Start date should be of dd/mm/yyyy format " + "or can be empty"; public static final String STARTDATE_VALIDATION_REGEX = "(^$)|(^(3[01]|[12][0-9]|0[1-9])/(1[0-2]|0[1-9])" + "/[0-9]{4}$)"; // @@author A0140032E public StartDate(String startDate) throws IllegalValueException { super(startDateConstructor(startDate)); } private static long startDateConstructor(String startDate) throws IllegalValueException { assert startDate != null; try { if (!isValidStartDate(startDate)) { throw new IllegalValueException(MESSAGE_STARTDATE_CONSTRAINTS); } if (startDate.trim().equals("")) { Calendar cal = Calendar.getInstance(); return cal.getTimeInMillis(); } return sdfInput.parse(startDate).getTime(); } catch (IllegalValueException | ParseException e) { throw new IllegalValueException(MESSAGE_STARTDATE_CONSTRAINTS); } } // @@author /** * Returns true if a given string is a valid task start date. */ public static boolean isValidStartDate(String test) { return test.matches(STARTDATE_VALIDATION_REGEX); } // @@author A0140032E @Override public String toString() { return sdfInput.format(this); } // @@author @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof StartDate // instanceof handles nulls && this.toString().equals(((StartDate) other).toString())); // state // check } @Override public int hashCode() { return toString().hashCode(); } }
package stream.flarebot.flarebot.util; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import org.json.JSONObject; import stream.flarebot.flarebot.FlareBot; import javax.annotation.ParametersAreNonnullByDefault; import java.io.IOException; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.Socket; import java.net.URL; public class WebUtils { public static MediaType APPLICATION_JSON = MediaType.parse("application/json"); private static final Callback defaultCallback = new Callback() { @Override @ParametersAreNonnullByDefault public void onFailure(Call call, IOException e) { FlareBot.LOGGER.error("Error for " + call.request().method() + " request to " + call.request().url(), e); } @Override @ParametersAreNonnullByDefault public void onResponse(Call call, Response response) throws IOException { response.close(); FlareBot.LOGGER.debug("Reponse for " + call.request().method() + " request to " + call.request().url()); } }; public static Response post(String url, MediaType type, String body) throws IOException { Request.Builder request = new Request.Builder().url(url); RequestBody requestBody = RequestBody.create(type, body); request = request.post(requestBody); return post(request); } public static Response post(Request.Builder builder) throws IOException { return FlareBot.getOkHttpClient().newCall(builder.build()).execute(); } public static Response get(String url) throws IOException { return get(new Request.Builder().url(url)); } public static Response get(Request.Builder builder) throws IOException { return FlareBot.getOkHttpClient().newCall(builder.get().build()).execute(); } public static void postAsync(Request.Builder builder) { FlareBot.getOkHttpClient().newCall(builder.build()).enqueue(defaultCallback); } public static boolean pingHost(String host, int timeout) { return pingHost(host, 80, timeout); } public static boolean pingHost(String host, int port, int timeout) { String hostname; try { hostname = new URL(host).getHost(); } catch (MalformedURLException e) { return false; } try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(hostname, port), timeout); return true; } catch (IOException e) { return false; // Either timeout or unreachable or failed DNS lookup. } } }
package tech.aroma.data.sql.serializers; import tech.sirwellington.alchemy.annotations.access.Internal; import tech.sirwellington.alchemy.annotations.access.NonInstantiable; /** * Contains the internal structure of the SQL Tables * used to serialize Aroma objects. * * @author SirWellington */ @Internal @NonInstantiable final class Tables { @NonInstantiable static final class Applications { final static String APP_ID = "app_id"; final static String APP_NAME = "app_name"; } @NonInstantiable static final class Messages { static final String TABLE_NAME = "Messages"; static final String TABLE_NAME_TOTALS_BY_APP = "Messages_Totals_By_App"; static final String TABLE_NAME_TOTALS_BY_TITLE = "Messages_Totals_By_Title"; static final String MESSAGE_ID = "message_id"; static final String TITLE = "title"; static final String BODY = "body"; static final String PRIORITY = "priority"; static final String TIME_CREATED = "time_created"; static final String TIME_RECEIVED = "time_received"; static final String HOSTNAME = "hostname"; static final String IP_ADDRESS = "ip_address"; static final String DEVICE_NAME = "device_name"; static final String APP_ID = Applications.APP_ID; static final String APP_NAME = Applications.APP_NAME; static final String TOTAL_MESSAGES = "total_messages"; static final String REQUEST_TIME = "request_time"; } @NonInstantiable static class Organizations { static final String TABLE_NAME = "Organizations"; static final String TABLE_NAME_MEMBERS = "Organizations_Members"; static final String ORG_ID = "org_id"; static final String ORG_NAME = "org_name"; static final String OWNERS = "owners"; static final String ICON_LINK = "icon_link"; static final String INDUSTRY = "industry"; static final String EMAIL = "contact_email"; static final String GITHUB_PROFILE = "github_profile"; static final String STOCK_NAME = "stock_name"; static final String TIER = "tier"; static final String DESCRIPTION = "description"; static final String WEBSITE = "website"; static final String USER_ID = "user_id"; static final String USER_FIRST_NAME = "user_first_name"; static final String USER_MIDDLE_NAME = "user_middle_name"; static final String USER_LAST_NAME = "user_last_name"; static final String USER_ROLES = "user_roles"; static final String USER_EMAIL = "user_email"; } static class Tokens { static final String TABLE_NAME = "Tokens"; static final String TABLE_NAME_BY_OWNER = "Tokens_By_Owner"; static final String TOKEN_ID = "token_id"; static final String OWNER_ID = "owner_id"; static final String OWNER_NAME = "owner_name"; static final String FEATURES = "features"; static final String TIME_OF_EXPIRATION = "time_of_expiration"; static final String TIME_OF_CREATION = "time_of_creation"; static final String ORG_ID = "organization_id"; static final String TOKEN_TYPE = "token_type"; static final String TOKEN_STATUS = "token_status"; } }
package tigase.cluster.repo; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import tigase.db.DBInitException; import tigase.db.DataRepository; import tigase.db.Repository; import tigase.db.RepositoryFactory; /** * Class description * * * @version 5.2.0, 13/03/09 * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> */ @Repository.Meta( supportedUris = { "jdbc:[^:]+:.*" } ) public class ClConSQLRepository extends ClConConfigRepository implements ClusterRepoConstants { /** * Private logger for class instances. */ private static final Logger log = Logger.getLogger(ClConSQLRepository.class.getName()); /* @formatter:off */ private static final String GET_ITEM_QUERY = "select " + HOSTNAME_COLUMN + ", " + PASSWORD_COLUMN + ", " + LASTUPDATE_COLUMN + ", " + PORT_COLUMN + ", " + CPU_USAGE_COLUMN + ", " + MEM_USAGE_COLUMN + " from " + TABLE_NAME + " where " + HOSTNAME_COLUMN + " = ?"; private static final String GET_ALL_ITEMS_QUERY = "select " + HOSTNAME_COLUMN + ", " + PASSWORD_COLUMN + ", " + LASTUPDATE_COLUMN + ", " + PORT_COLUMN + ", " + CPU_USAGE_COLUMN + ", " + MEM_USAGE_COLUMN + " from " + TABLE_NAME; private static final String DELETE_ITEM_QUERY = "delete from " + TABLE_NAME + " where (" + HOSTNAME_COLUMN + " = ?)"; private static final String CREATE_TABLE_QUERY_MYSQL = "create table " + TABLE_NAME + " (" + " " + HOSTNAME_COLUMN + " varchar(255) not null," + " " + PASSWORD_COLUMN + " varchar(255) not null," + " " + LASTUPDATE_COLUMN + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP," + " " + PORT_COLUMN + " int," + " " + CPU_USAGE_COLUMN + " double precision unsigned not null," + " " + MEM_USAGE_COLUMN + " double precision unsigned not null," + " primary key(" + HOSTNAME_COLUMN + "))" + " ENGINE=InnoDB default character set utf8 ROW_FORMAT=DYNAMIC"; private static final String CREATE_TABLE_QUERY = "create table " + TABLE_NAME + " (" + " " + HOSTNAME_COLUMN + " varchar(512) not null," + " " + PASSWORD_COLUMN + " varchar(255) not null," + " " + LASTUPDATE_COLUMN + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP," + " " + PORT_COLUMN + " int," + " " + CPU_USAGE_COLUMN + " double precision not null," + " " + MEM_USAGE_COLUMN + " double precision not null," + " primary key(" + HOSTNAME_COLUMN + "))"; private static final String CREATE_TABLE_QUERY_SQLSERVER = "create table [dbo].[" + TABLE_NAME + "] (" + " " + HOSTNAME_COLUMN + " nvarchar(512) not null," + " " + PASSWORD_COLUMN + " nvarchar(255) not null," + " " + LASTUPDATE_COLUMN + " [datetime] NULL," + " " + PORT_COLUMN + " int," + " " + CPU_USAGE_COLUMN + " double precision not null," + " " + MEM_USAGE_COLUMN + " double precision not null," + " CONSTRAINT [PK_" + TABLE_NAME + "] PRIMARY KEY CLUSTERED ( [" + HOSTNAME_COLUMN + "] ASC ) ON [PRIMARY], " + " CONSTRAINT [IX_" + TABLE_NAME + "_" + HOSTNAME_COLUMN + "] UNIQUE NONCLUSTERED ( [" + HOSTNAME_COLUMN + "] ASC ) ON [PRIMARY] " + ") ON [PRIMARY]" + "ALTER TABLE [dbo].[" + TABLE_NAME + "] ADD CONSTRAINT " + "[DF_" + TABLE_NAME + "_" + LASTUPDATE_COLUMN + "] DEFAULT (getdate()) FOR [" + LASTUPDATE_COLUMN + "] "; private static final String INSERT_ITEM_QUERY = "insert into " + TABLE_NAME + " (" + HOSTNAME_COLUMN + ", " + PASSWORD_COLUMN + ", " + LASTUPDATE_COLUMN + ", " + PORT_COLUMN + ", " + CPU_USAGE_COLUMN + ", " + MEM_USAGE_COLUMN + ") " + " (select ?, ?, CURRENT_TIMESTAMP, ?, ?, ? from " + TABLE_NAME + " WHERE " + HOSTNAME_COLUMN + "=? HAVING count(*)=0)"; private static final String UPDATE_ITEM_QUERY = "update " + TABLE_NAME + " set " + HOSTNAME_COLUMN + "= ?, " + PASSWORD_COLUMN + "= ?, " + LASTUPDATE_COLUMN + " = CURRENT_TIMESTAMP," + PORT_COLUMN + "= ?, " + CPU_USAGE_COLUMN + "= ?, " + MEM_USAGE_COLUMN + "= ? " + " where " + HOSTNAME_COLUMN + "= ?" ; /* @formatter:on */ private DataRepository data_repo = null; @Override public void destroy() { // This implementation of ClConConfigRepository is using shared connection // pool to database which is cached by RepositoryFactory and maybe be used // in other places, so we can not destroy it. super.destroy(); } @Override public void getDefaults(Map<String, Object> defs, Map<String, Object> params) { super.getDefaults(defs, params); String repo_uri = RepositoryFactory.DERBY_REPO_URL_PROP_VAL; if (params.get(RepositoryFactory.GEN_USER_DB_URI) != null) { repo_uri = (String) params.get(RepositoryFactory.GEN_USER_DB_URI); } defs.put(REPO_URI_PROP_KEY, repo_uri); } @Override public void initRepository(String conn_str, Map<String, String> params) throws DBInitException { super.initRepository(conn_str, params); try { data_repo = RepositoryFactory.getDataRepository(null, conn_str, params); checkDB(); // data_repo.initPreparedStatement(CHECK_TABLE_QUERY, CHECK_TABLE_QUERY); data_repo.initPreparedStatement(GET_ITEM_QUERY, GET_ITEM_QUERY); data_repo.initPreparedStatement(GET_ALL_ITEMS_QUERY, GET_ALL_ITEMS_QUERY); data_repo.initPreparedStatement(INSERT_ITEM_QUERY, INSERT_ITEM_QUERY); data_repo.initPreparedStatement(UPDATE_ITEM_QUERY, UPDATE_ITEM_QUERY); data_repo.initPreparedStatement(DELETE_ITEM_QUERY, DELETE_ITEM_QUERY); } catch (Exception e) { log.log(Level.WARNING, "Problem initializing database: ", e); } } @Override public void removeItem( String key ) { super.removeItem( key ); try { PreparedStatement removeItem = data_repo.getPreparedStatement( null, DELETE_ITEM_QUERY ); synchronized ( removeItem ) { removeItem.setString( 1, key ); removeItem.executeUpdate(); } } catch (SQLException e) { log.log(Level.WARNING, "Problem removing elements from DB: ", e); } } @Override public void storeItem(ClusterRepoItem item) { try { PreparedStatement updateItemSt = data_repo.getPreparedStatement(null, UPDATE_ITEM_QUERY); PreparedStatement insertItemSt = data_repo.getPreparedStatement(null, INSERT_ITEM_QUERY); // relatively most DB compliant UPSERT synchronized (updateItemSt) { updateItemSt.setString(1, item.getHostname()); updateItemSt.setString(2, item.getPassword()); updateItemSt.setInt(3, item.getPortNo()); updateItemSt.setFloat(4, item.getCpuUsage()); updateItemSt.setFloat(5, item.getMemUsage()); updateItemSt.setString(6, item.getHostname()); updateItemSt.executeUpdate(); } synchronized (insertItemSt) { insertItemSt.setString(1, item.getHostname()); insertItemSt.setString(2, item.getPassword()); insertItemSt.setInt(3, item.getPortNo()); insertItemSt.setFloat(4, item.getCpuUsage()); insertItemSt.setFloat(5, item.getMemUsage()); insertItemSt.setString(6, item.getHostname()); insertItemSt.executeUpdate(); } } catch (SQLException e) { log.log(Level.WARNING, "Problem getting elements from DB: ", e); } } @Override public void reload() { super.reload(); ResultSet rs = null; try { PreparedStatement getAllItemsSt = data_repo.getPreparedStatement(null, GET_ALL_ITEMS_QUERY); synchronized (getAllItemsSt) { rs = getAllItemsSt.executeQuery(); while (rs.next()) { ClusterRepoItem item = getItemInstance(); item.setHostname(rs.getString(HOSTNAME_COLUMN)); item.setPassword(rs.getString(PASSWORD_COLUMN)); item.setLastUpdate(rs.getTimestamp(LASTUPDATE_COLUMN).getTime()); item.setPort(rs.getInt(PORT_COLUMN)); item.setCpuUsage(rs.getFloat(CPU_USAGE_COLUMN)); item.setMemUsage(rs.getFloat(MEM_USAGE_COLUMN)); itemLoaded(item); } } } catch (SQLException e) { log.log(Level.WARNING, "Problem getting elements from DB: ", e); } finally { data_repo.release(null, rs); } } @Override public void setProperties(Map<String, Object> properties) { super.setProperties(properties); } @Override public void store() { // Do nothing everything is written on demand to DB } /** * Performs database check, creates missing schema if necessary * * @throws SQLException */ private void checkDB() throws SQLException { ResultSet rs = null; Statement st = null; DataRepository.dbTypes databaseType = data_repo.getDatabaseType(); String createTableQuery; switch ( databaseType ) { case mysql: createTableQuery = CREATE_TABLE_QUERY_MYSQL; break; case jtds: case sqlserver: createTableQuery = CREATE_TABLE_QUERY_SQLSERVER; break; default: createTableQuery = CREATE_TABLE_QUERY; break; } try { if (!data_repo.checkTable(TABLE_NAME)) { log.info("DB for external component is not OK, creating missing tables..."); st = data_repo.createStatement(null); st.executeUpdate(createTableQuery); log.info("DB for external component created OK"); } } finally { data_repo.release(st, rs); rs = null; st = null; } } } //~ Formatted in Tigase Code Convention on 13/03/11
package tigase.server.xmppserver.proc; import tigase.server.Packet; import tigase.server.xmppserver.CID; import tigase.server.xmppserver.S2SIOService; import tigase.xml.Element; import java.io.IOException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.Queue; /** * Created: Dec 9, 2010 2:01:01 PM * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public class StartTLS extends S2SAbstractProcessor { private static final Logger log = Logger.getLogger(StartTLS.class.getName()); private static final Element features = new Element(START_TLS_EL, new String[] { "xmlns" }, new String[] { START_TLS_NS }); private static final Element features_required = new Element(START_TLS_EL, new Element[] { new Element( "required" ) }, new String[] { "xmlns" }, new String[] { START_TLS_NS }); private static final Element starttls_el = new Element(START_TLS_EL, new String[] { "xmlns" }, new String[] { START_TLS_NS }); private static final Element proceed_el = new Element(PROCEED_TLS_EL, new String[] { "xmlns" }, new String[] { START_TLS_NS }); @Override public int order() { return Order.StartTLS.ordinal(); } /** * Method description * * * @param p * @param serv * @param results * * */ @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { if (p.isElement(START_TLS_EL, START_TLS_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Sending packet: {1}", new Object[] { serv, proceed_el }); } handler.writeRawData(serv, proceed_el.toString()); try { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Starting TLS handshaking server side.", serv); } serv.getSessionData().put("TLS", "TLS"); serv.startTLS(false, handler.isTlsWantClientAuthEnabled()); } catch (IOException ex) { log.log(Level.INFO, "Problem with TLS initialization.", ex); } return true; } if (p.isElement(PROCEED_TLS_EL, START_TLS_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Received TLS proceed.", serv); } try { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Starting TLS handshaking client side.", serv); } serv.getSessionData().put("TLS", "TLS"); serv.startTLS(true, handler.isTlsWantClientAuthEnabled()); } catch (IOException ex) { log.log(Level.INFO, "Problem with TLS initialization.", ex); } return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received: {1}", new Object[] { serv, p }); } CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Sending packet: {1}", new Object[] { serv, starttls_el }); } handler.writeRawData(serv, starttls_el.toString()); return true; } } return false; } /** * Method description * * * * @param serv * @param results */ @Override public void streamFeatures(S2SIOService serv, List<Element> results) { if (!serv.getSessionData().containsKey("TLS")) { CID cid = (CID) serv.getSessionData().get("cid"); if (cid != null && !skipTLSForHost(cid.getRemoteHost()) && handler.isTlsRequired(cid.getLocalHost())) { results.add(features_required); } else { results.add(features); } } } } //~ Formatted in Tigase Code Convention on 13/02/16
// jTDS JDBC Driver for Microsoft SQL Server // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package net.sourceforge.jtds.jdbcx; import java.sql.*; import java.util.*; import javax.sql.*; import net.sourceforge.jtds.jdbc.*; import net.sourceforge.jtds.jdbcx.proxy.*; /** * * @version $Id: PooledConnection.java,v 1.5 2004-07-23 12:19:08 bheineman Exp $ */ public class PooledConnection implements javax.sql.PooledConnection { private final ArrayList _listeners = new ArrayList(); private Connection _connection; private ConnectionProxy _connectionProxy = null; public PooledConnection(Connection connection) { _connection = connection; } /** * Adds the specified listener to the list. * * @see #fireConnectionEvent * @see #removeConnectionEventListener */ public synchronized void addConnectionEventListener(ConnectionEventListener listener) { _listeners.add(listener); } /** * Closes the database connection. * * @throws SQLException if an error occurs */ public synchronized void close() throws SQLException { _connection.close(); _connection = null; // Garbage collect the connection fireConnectionEvent(false, null); } /** * Fires a new connection event on all listeners. * * @param closed <code>true</code> if <code>close</code> has been called on the * connection; <code>false</code> if the <code>sqlException</code> represents * an error where the connection may not longer be used. * @param sqlException the SQLException to pass to the listeners */ public synchronized void fireConnectionEvent(boolean closed, SQLException sqlException) { if (_listeners.size() > 0) { ConnectionEvent connectionEvent = new ConnectionEvent(this, sqlException); Iterator iterator = _listeners.iterator(); while (iterator.hasNext()) { ConnectionEventListener listener = (ConnectionEventListener) iterator.next(); if (closed) { listener.connectionClosed(connectionEvent); } else { listener.connectionErrorOccurred(connectionEvent); } } } } /** * Returns a ConnectionProxy. * * @throws SQLException if an error occurs */ public synchronized Connection getConnection() throws SQLException { if (_connection == null) { fireConnectionEvent(false, new SQLException(Support.getMessage("error.jdbcx.conclosed"), "08003")); return null; } if (_connectionProxy != null) { _connectionProxy.close(); } // Sould the SQLException be captured here for safety in the future even though // no SQLException is being thrown by the ConnectionProxy at the moment??? _connectionProxy = new ConnectionProxy(this, _connection); return _connectionProxy; } /** * Removes the specified listener from the list. * * @see #addConnectionEventListener * @see #fireConnectionEvent */ public synchronized void removeConnectionEventListener(ConnectionEventListener listener) { _listeners.remove(listener); } }
package unit; import org.testng.Assert; import org.testng.annotations.Test; import com.coveros.selenified.tools.General; import java.io.File; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; public class GeneralTest { @Test public void listFilesForFolderTest() { Assert.assertTrue(General.listFilesForFolder(null).isEmpty()); Assert.assertEquals(General.listFilesForFolder(null), new ArrayList<String>()); Assert.assertTrue(General.listFilesForFolder(new File("/bad-folder")).isEmpty()); Assert.assertEquals(General.listFilesForFolder(new File("/bad-folder")), new ArrayList<String>()); } @Test public void listFilesForFolderDirectoryTest() { List<String> files = General.listFilesForFolder(new File("./src/test/java")); Assert.assertEquals(files.size(), 32); Assert.assertTrue(files.contains("." + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + "integration" + File.separator + "ActionDoIT.java")); Assert.assertTrue(files.contains("." + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + "integration" + File.separator + "ActionGetIT.java")); Assert.assertTrue(files.contains("." + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + "integration" + File.separator + "ActionIsIT.java")); Assert.assertTrue(files.contains("." + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + "integration" + File.separator + "ActionSwitchIT.java")); Assert.assertTrue(files.contains("." + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + "integration" + File.separator + "ActionWaitIT.java")); Assert.assertTrue(files.contains("." + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + "integration" + File.separator + "AssertIT.java")); Assert.assertTrue(files.contains("." + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + "integration" + File.separator + "NoBrowserIT.java")); Assert.assertTrue(files.contains("." + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + "integration" + File.separator + "NoLoadIT.java")); Assert.assertTrue(files.contains("." + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + "unit" + File.separator + "ExceptionTest.java")); Assert.assertTrue(files.contains("." + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + "unit" + File.separator + "ElementTest.java")); Assert.assertTrue(files.contains("." + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + "unit" + File.separator + "GeneralTest.java")); Assert.assertTrue(files.contains("." + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + "unit" + File.separator + "OutputFileTest.java")); Assert.assertTrue(files.contains("." + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + "unit" + File.separator + "SelenifiedTest.java")); Assert.assertTrue(files.contains("." + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + "unit" + File.separator + "TestSetupTest.java")); } @Test public void padRightSpaceTest() { Assert.assertEquals(General.padRightSpace(null, 0), ""); Assert.assertEquals(General.padRightSpace(null, 5), " "); Assert.assertEquals(General.padRightSpace("", 0), ""); Assert.assertEquals(General.padRightSpace("", 5), " "); Assert.assertEquals(General.padRightSpace("A", 0), "A"); Assert.assertEquals(General.padRightSpace("A", 5), "A "); } @Test public void padRightZerosTest() { Assert.assertEquals(General.padRightZeros(1, 0), "1"); Assert.assertEquals(General.padRightZeros(1, 5), "10000"); } @Test public void padRightIntegerTest() { Assert.assertEquals(General.padRight(1, 0, "Z"), "1"); Assert.assertEquals(General.padRight(1, 5, "Z"), "1ZZZZ"); } @Test public void padRightStringTest() { Assert.assertEquals(General.padRight(null, 0, "Z"), ""); Assert.assertEquals(General.padRight(null, 5, "Z"), "ZZZZZ"); Assert.assertEquals(General.padRight("", 0, "Z"), ""); Assert.assertEquals(General.padRight("", 5, "Z"), "ZZZZZ"); Assert.assertEquals(General.padRight("A", 0, "Z"), "A"); Assert.assertEquals(General.padRight("A", 5, "Z"), "AZZZZ"); } @Test public void padLeftSpaceTest() { Assert.assertEquals(General.padLeftSpace(null, 0), ""); Assert.assertEquals(General.padLeftSpace(null, 5), " "); Assert.assertEquals(General.padLeftSpace("", 0), ""); Assert.assertEquals(General.padLeftSpace("", 5), " "); Assert.assertEquals(General.padLeftSpace("A", 0), "A"); Assert.assertEquals(General.padLeftSpace("A", 5), " A"); } @Test public void padLeftZerosTest() { Assert.assertEquals(General.padLeftZeros(1, 0), "1"); Assert.assertEquals(General.padLeftZeros(1, 5), "00001"); } @Test public void padLeftIntegerTest() { Assert.assertEquals(General.padLeft(1, 0, "Z"), "1"); Assert.assertEquals(General.padLeft(1, 5, "Z"), "ZZZZ1"); } @Test public void padLeftStringTest() { Assert.assertEquals(General.padLeft(null, 0, "Z"), ""); Assert.assertEquals(General.padLeft(null, 5, "Z"), "ZZZZZ"); Assert.assertEquals(General.padLeft("", 0, "Z"), ""); Assert.assertEquals(General.padLeft("", 5, "Z"), "ZZZZZ"); Assert.assertEquals(General.padLeft("A", 0, "Z"), "A"); Assert.assertEquals(General.padLeft("A", 5, "Z"), "ZZZZA"); } @Test public void reverseItTest() { Assert.assertEquals(General.reverseIt(null), null); Assert.assertEquals(General.reverseIt(""), ""); Assert.assertEquals(General.reverseIt("ABC"), "CBA"); } @Test public void getRandomCharTest() { Assert.assertEquals(General.getRandomChar().length(), 1); Assert.assertTrue(General.getRandomChar().matches("^[A-Za-z0-9]$")); } @Test public void getRandomStringTest() { Assert.assertEquals(General.getRandomString().length(), 32); Assert.assertTrue(General.getRandomString().matches("^[A-Za-z0-9]{32}$")); } @Test public void getRandomStringLengthTest() { Assert.assertEquals(General.getRandomString(0).length(), 0); Assert.assertEquals(General.getRandomString(0), ""); Assert.assertEquals(General.getRandomString(999).length(), 999); Assert.assertTrue(General.getRandomString(999).matches("^[A-Za-z0-9]{999}$")); Assert.assertEquals(General.getRandomString(-1).length(), 0); Assert.assertEquals(General.getRandomString(-1), ""); } @Test public void getRandomIntTest() { Assert.assertEquals(General.getRandomInt().length(), 9); Assert.assertTrue(General.getRandomInt().matches("^[0-9]{9}$")); } @Test public void doesArrayContainTest() { String strings[] = { "hello", "world" }; Assert.assertTrue(General.doesArrayContain(strings, "hello")); Assert.assertFalse(General.doesArrayContain(strings, "HELLO")); Assert.assertFalse(General.doesArrayContain(strings, "")); Object integers[] = { 0, 1, 2, 3 }; Assert.assertTrue(General.doesArrayContain(integers, 0)); Assert.assertFalse(General.doesArrayContain(integers, "HELLO")); Assert.assertFalse(General.doesArrayContain(integers, 4)); } @Test public void getRandomIntLengthTest() { Assert.assertEquals(General.getRandomInt(0).length(), 0); Assert.assertEquals(General.getRandomInt(0), ""); Assert.assertEquals(General.getRandomInt(999).length(), 999); Assert.assertTrue(General.getRandomInt(999).matches("^[0-9]{999}$")); Assert.assertEquals(General.getRandomInt(-1).length(), 0); Assert.assertEquals(General.getRandomInt(-1), ""); } @Test public void removeNonWordCharactersTest() { Assert.assertEquals(General.removeNonWordCharacters(null), null); Assert.assertEquals(General.removeNonWordCharacters(""), ""); Assert.assertEquals(General.removeNonWordCharacters("hello world"), "helloworld"); Assert.assertEquals(General.removeNonWordCharacters("hello-world"), "helloworld"); Assert.assertEquals(General.removeNonWordCharacters("hello_world"), "helloworld"); Assert.assertEquals(General.removeNonWordCharacters("hello`~!@#$%^&*()world"), "helloworld"); Assert.assertEquals(General.removeNonWordCharacters("hello[]\\{}|;':\",./<>?world"), "helloworld"); } @Test public void wordToSentenceTest() { Assert.assertEquals(General.wordToSentence(null), null); Assert.assertEquals(General.wordToSentence("hello world"), "Hello World"); Assert.assertEquals(General.wordToSentence("helloWorld"), "Hello World"); Assert.assertEquals(General.wordToSentence("hello_world"), "Hello _ World"); Assert.assertEquals(General.wordToSentence("123helloWorld"), "123 Hello World"); Assert.assertEquals(General.wordToSentence("hello123world"), "Hello 123 World"); Assert.assertEquals(General.wordToSentence("helloWorld123"), "Hello World 123"); } @Test public void capitalizeFirstLettersTest() { Assert.assertEquals(General.capitalizeFirstLetters(null), null); Assert.assertEquals(General.capitalizeFirstLetters("hello world"), "Hello World"); Assert.assertEquals(General.capitalizeFirstLetters("helloWorld"), "HelloWorld"); Assert.assertEquals(General.capitalizeFirstLetters("hello_world"), "Hello_World"); Assert.assertEquals(General.capitalizeFirstLetters("123helloWorld"), "123HelloWorld"); Assert.assertEquals(General.capitalizeFirstLetters("hello123world"), "Hello123World"); Assert.assertEquals(General.capitalizeFirstLetters("helloWorld123"), "HelloWorld123"); } @Test public void getTestNameTest(Method method) { Assert.assertEquals(General.getTestName(method.getName(), "Python"), "getTestNameTestWithOptionPython"); Assert.assertEquals(General.getTestName(method.getName(), "public"), "getTestNameTest"); Assert.assertEquals(General.getTestName(method), "unit_GeneralTest_getTestNameTest"); Assert.assertEquals(General.getTestName("", "UnitTests", "helloWorld"), "UnitTests_helloWorld"); Assert.assertEquals(General.getTestName("", "UnitTests", "helloWorld", "python"), "UnitTests_helloWorldWithOptionPython"); Assert.assertEquals(General.getTestName("", "UnitTests", "helloWorld", "visual basic"), "UnitTests_helloWorldWithOptionVisualbasic"); Assert.assertEquals(General.getTestName("", "UnitTests", "helloWorld", "Python"), "UnitTests_helloWorldWithOptionPython"); Assert.assertEquals(General.getTestName("", "UnitTests", "helloWorld", "Python", "Perl"), "UnitTests_helloWorldWithOptionPythonPerl"); Assert.assertEquals( General.getTestName("", "UnitTests", "helloWorld", "Python", "Perl", "Bash", "Java", "Ruby", "Groovy", "Javascript", "PHP", "Scala", "Fortan", "Lisp", "COBOL", "Erlang", "Pacal", "Haskell", "Swift", "Elixir", "BASIC", "Tcl", "Rust", "Visual Basic", "Ceylon", "Cobra", "Forth", "Curry", "COMOL", "Gosu", "Powershell", "Squeak", "Gambas"), "UnitTests_helloWorldWithOptionPythonPerlBashJavaRubyGroovyJavascriptPHPScalaFortanLispCOBOLErlangPacalHaskellSwiftElixirBASICTclRustVisualBasicCeylonCobraForthCurryCOMOLGosuPowershellSqueakGambas"); String testName = General.getTestName("helloWorld", "PythonPerlBashJavaRubyGroovyJavascriptPHPScalaFortanLispCOBOLErlangPacalHaskellSwiftElixirBASICTclRustVisualBasicCeylonCobraForthCurryCOMOLGosuPowershellSqueakGambasEuphoriaFantomAssembly"); Assert.assertTrue(testName.matches("helloWorld@[0-9a-f]+$")); testName = General.getTestName("", "UnitTests", "helloWorld", "Python", "Perl", "Bash", "Java", "Ruby", "Groovy", "Javascript", "PHP", "Scala", "Fortan", "Lisp", "COBOL", "Erlang", "Pacal", "Haskell", "Swift", "Elixir", "BASIC", "Tcl", "Rust", "Visual Basic", "Ceylon", "Cobra", "Forth", "Curry", "COMOL", "Gosu", "Powershell", "Squeak", "Gambas", "Euphoria", "Fantom", "Assembly"); Assert.assertTrue(testName.matches("^UnitTests_helloWorld@[0-9a-f]+$")); } @Test public void parseMapTest() { Map<String, String> map = General.parseMap("A=B&C=D&E=F"); Assert.assertTrue(map.containsKey("A")); Assert.assertEquals("B", map.get("A")); Assert.assertTrue(map.containsKey("C")); Assert.assertEquals("D", map.get("C")); Assert.assertTrue(map.containsKey("E")); Assert.assertEquals("F", map.get("E")); } }
package com.precious.calccedo.handlers; import com.precious.calccedo.Calccedo; import com.precious.calccedo.configuration.Configuration; import java.util.ArrayList; /** * * @author Ibrahim Abdsaid Hanna * ibrahim.seniore@gmail.com */ public class CalccedoHandler extends Calccedo implements Handler { private ArrayList<Character> list; private ArrayList<Character> list2; public CalccedoHandler(){ list=new ArrayList<>(); list.add('S'); list.add('C'); list.add('T'); list.add('L'); list.add('<'); list.add('('); list2=new ArrayList<>(); list2.add('/'); list2.add('%'); list2.add('+'); list2.add('-'); list2.add('*'); list2.add('^'); list2.add('n'); list2.add('s'); list2.add('g'); list2.add('<'); list2.add('('); init(); } private Quote parsePartethis(String formula) { int offsetA=0; int offsetZ=0; for(int i=formula.length()-1;i>=0;i if(formula.charAt(i)=='('){ offsetA=i; for(int j=i;j<formula.length();j++){ if(formula.charAt(j)==')'){ offsetZ=j; i=-1; break; } } } } if(offsetA==0){ return new Quote(formula.substring(offsetA, offsetZ+1), offsetA, offsetZ+1); } else{ try{ if(formula.substring(offsetA-3, offsetA).equals("Sin")){ return new Quote("Sin", formula.substring(offsetA, offsetZ+1),offsetA, offsetZ+1); } else if(formula.substring(offsetA-3, offsetA).equals("Cos")){ return new Quote("Cos", formula.substring(offsetA, offsetZ+1), offsetA, offsetZ+1); } else if(formula.substring(offsetA-3, offsetA).equals("Tan")){ return new Quote("Tan", formula.substring(offsetA, offsetZ+1), offsetA, offsetZ+1); } else if(formula.substring(offsetA-3, offsetA).equals("Log")){ return new Quote("Log", formula.substring(offsetA, offsetZ+1), offsetA, offsetZ+1); } else{ return new Quote(formula.substring(offsetA, offsetZ+1), offsetA, offsetZ+1); } } catch(Exception ex){ return new Quote(formula.substring(offsetA, offsetZ+1), offsetA, offsetZ+1); } } } private String obtainQuoteOperand(String digits){ if(digits.equals("Sin")){ return "Sin"; } else if(digits.equals("Cos")){ return "Cos"; } if(digits.equals("Tan")){ return "Tan"; } if(digits.equals("Log")){ return "Log"; } else{ return ""; } } @Override public boolean isNumber(char c){ if(c=='.'){ return true; } try{ Integer.parseInt(""+c); return true; } catch(Exception ex){ return false; } } @Override public String optimizeFormula(String formula) { String newformula=""; for(int i=0;i<formula.length();i++){ if(list.contains(formula.charAt(i)) && i>0){ if(list2.contains(formula.charAt(i-1)) && i>0){ newformula=newformula+formula.charAt(i); } else{ newformula=newformula+"*"+formula.charAt(i); } } else if(isNumber(formula.charAt(i))){ if(i>0&&(formula.charAt(i-1)==')'||formula.charAt(i-1)=='>')){ newformula=newformula+"*"+formula.charAt(i); } else{ newformula=newformula+formula.charAt(i); } } else{ newformula=newformula+formula.charAt(i); } } if(Configuration.deepTracing) System.out.println("optinmization is >>>>>>>>>>>"+newformula); return newformula; } @Override public boolean initValidation(String formula) { if(!formula.contains("(")&&!formula.contains("<")&&!formula.contains(">")&&!formula.contains(")")){ return true; } int openedPartethis=0; int openedRoot=0; for(int i=0;i<formula.length();i++){ if(formula.charAt(i)=='('){ openedPartethis++; } if(formula.charAt(i)==')'){ openedPartethis } if(openedPartethis<0){ return false; } if(formula.charAt(i)=='<'){ openedRoot++; } if(formula.charAt(i)=='>'){ openedRoot } if(openedRoot<0){ return false; } } return openedPartethis==0 && openedRoot==0 ; } @Override public String calculate(String formula) { //String result="Denmark Copenhagn Crossworkers"; // validate formula if(!initValidation(formula)) return "error"; // optimize formula formula=optimizeFormula(formula); // calculate inside partethis String firstProcess= calculatePartethis(formula); if(firstProcess.equals("error")){ return "error"; } // include final formula inside partetehis to process it // second peocess is the final process in calccedo, just because conatins only +,- String secondProcess= calculatePartethis("("+firstProcess+")"); if(secondProcess.equals("error")){ return "error"; } return secondProcess; } private String calculatePartethis(String formula){ Quote quote; SubFormula subFormula; QuoteResult quoteResult; while(formula.contains("(")){ quote=parsePartethis(formula); subFormula=new SubFormula(quote); quoteResult=subFormula.getQuoteResult(); if(quoteResult==null){ return "error"; } else{ formula=formula.substring(0,quoteResult.offsetA)+quoteResult.result+formula.substring(quoteResult.offsetZ,formula.length()); } } if(Configuration.deepTracing) System.out.println("formula after parsing partethis"+formula); return formula; } @Override public boolean isNumber(String quote) { try{ Double.parseDouble(quote); return true; } catch(Exception ex){ if(Configuration.deepTracing){ // System.err.println(ex+"\n just dummy exception do in behind while validating Numbers\n"); System.out.println("\nCalccedo Info: this is just info to help developers how Calccedo Library work"); System.out.println("Info quote "+quote+", cannot wrapped to Double, so it will complete loop until finishing operations \n"); } return false; } } }
package net.minecraftforge.common; import java.io.*; import java.text.DateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.CharMatcher; import com.google.common.base.Splitter; import com.google.common.collect.Maps; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.Loader; import cpw.mods.fml.relauncher.FMLInjectionData; import net.minecraft.block.Block; import net.minecraft.item.Item; import static net.minecraftforge.common.Property.Type.*; /** * This class offers advanced configurations capabilities, allowing to provide * various categories for configuration variables. */ public class Configuration { private static boolean[] configMarkers = new boolean[Item.itemsList.length]; private static final int ITEM_SHIFT = 256; private static final int MAX_BLOCKS = 4096; public static final String CATEGORY_GENERAL = "general"; public static final String CATEGORY_BLOCK = "block"; public static final String CATEGORY_ITEM = "item"; public static final String ALLOWED_CHARS = "._-"; public static final String DEFAULT_ENCODING = "UTF-8"; public static final String CATEGORY_SPLITTER = "."; public static final String NEW_LINE; private static final Pattern CONFIG_START = Pattern.compile("START: \"([^\\\"]+)\""); private static final Pattern CONFIG_END = Pattern.compile("END: \"([^\\\"]+)\""); public static final CharMatcher allowedProperties = CharMatcher.JAVA_LETTER_OR_DIGIT.or(CharMatcher.anyOf(ALLOWED_CHARS)); private static Configuration PARENT = null; File file; public Map<String, ConfigCategory> categories = new TreeMap<String, ConfigCategory>(); private Map<String, Configuration> children = new TreeMap<String, Configuration>(); private boolean caseSensitiveCustomCategories; public String defaultEncoding = DEFAULT_ENCODING; private String fileName = null; public boolean isChild = false; static { Arrays.fill(configMarkers, false); NEW_LINE = System.getProperty("line.separator"); } public Configuration(){} /** * Create a configuration file for the file given in parameter. */ public Configuration(File file) { this.file = file; String basePath = ((File)(FMLInjectionData.data()[6])).getAbsolutePath().replace(File.separatorChar, '/').replace("/.", ""); String path = file.getAbsolutePath().replace(File.separatorChar, '/').replace("/./", "/").replace(basePath, ""); if (PARENT != null) { PARENT.setChild(path, this); isChild = true; } else { fileName = path; load(); } } public Configuration(File file, boolean caseSensitiveCustomCategories) { this(file); this.caseSensitiveCustomCategories = caseSensitiveCustomCategories; } /** * Gets or create a block id property. If the block id property key is * already in the configuration, then it will be used. Otherwise, * defaultId will be used, except if already taken, in which case this * will try to determine a free default id. */ public Property getBlock(String key, int defaultID) { return getBlock(CATEGORY_BLOCK, key, defaultID, null); } public Property getBlock(String key, int defaultID, String comment) { return getBlock(CATEGORY_BLOCK, key, defaultID, comment); } public Property getBlock(String category, String key, int defaultID) { return getBlockInternal(category, key, defaultID, null, 256, Block.blocksList.length); } public Property getBlock(String category, String key, int defaultID, String comment) { return getBlockInternal(category, key, defaultID, comment, 256, Block.blocksList.length); } /** * Special version of getBlock to be used when you want to garentee the ID you get is below 256 * This should ONLY be used by mods who do low level terrain generation, or ones that add new * biomes. * EXA: ExtraBiomesXL * * Specifically, if your block is used BEFORE the Chunk is created, and placed in the terrain byte array directly. * If you add a new biome and you set the top/filler block, they need to be <256, nothing else. * * If you're adding a new ore, DON'T call this function. * * Normal mods such as '50 new ores' do not need to be below 256 so should use the normal getBlock */ public Property getTerrainBlock(String category, String key, int defaultID, String comment) { return getBlockInternal(category, key, defaultID, comment, 0, 256); } private Property getBlockInternal(String category, String key, int defaultID, String comment, int lower, int upper) { Property prop = get(category, key, -1, comment); if (prop.getInt() != -1) { configMarkers[prop.getInt()] = true; return prop; } else { if (defaultID < lower) { FMLLog.warning( "Mod attempted to get a block ID with a default in the Terrain Generation section, " + "mod authors should make sure there defaults are above 256 unless explicitly needed " + "for terrain generation. Most ores do not need to be below 256."); FMLLog.warning("Config \"%s\" Category: \"%s\" Key: \"%s\" Default: %d", fileName, category, key, defaultID); defaultID = upper - 1; } if (Block.blocksList[defaultID] == null && !configMarkers[defaultID]) { prop.value = Integer.toString(defaultID); configMarkers[defaultID] = true; return prop; } else { for (int j = upper - 1; j > 0; j { if (Block.blocksList[j] == null && !configMarkers[j]) { prop.value = Integer.toString(j); configMarkers[j] = true; return prop; } } throw new RuntimeException("No more block ids available for " + key); } } } public Property getItem(String key, int defaultID) { return getItem(CATEGORY_ITEM, key, defaultID, null); } public Property getItem(String key, int defaultID, String comment) { return getItem(CATEGORY_ITEM, key, defaultID, comment); } public Property getItem(String category, String key, int defaultID) { return getItem(category, key, defaultID, null); } public Property getItem(String category, String key, int defaultID, String comment) { Property prop = get(category, key, -1, comment); int defaultShift = defaultID + ITEM_SHIFT; if (prop.getInt() != -1) { configMarkers[prop.getInt() + ITEM_SHIFT] = true; return prop; } else { if (defaultID < MAX_BLOCKS - ITEM_SHIFT) { FMLLog.warning( "Mod attempted to get a item ID with a default value in the block ID section, " + "mod authors should make sure there defaults are above %d unless explicitly needed " + "so that all block ids are free to store blocks.", MAX_BLOCKS - ITEM_SHIFT); FMLLog.warning("Config \"%s\" Category: \"%s\" Key: \"%s\" Default: %d", fileName, category, key, defaultID); } if (Item.itemsList[defaultShift] == null && !configMarkers[defaultShift] && defaultShift >= Block.blocksList.length) { prop.value = Integer.toString(defaultID); configMarkers[defaultShift] = true; return prop; } else { for (int x = Item.itemsList.length - 1; x >= ITEM_SHIFT; x { if (Item.itemsList[x] == null && !configMarkers[x]) { prop.value = Integer.toString(x - ITEM_SHIFT); configMarkers[x] = true; return prop; } } throw new RuntimeException("No more item ids available for " + key); } } } public Property get(String category, String key, int defaultValue) { return get(category, key, defaultValue, null); } public Property get(String category, String key, int defaultValue, String comment) { Property prop = get(category, key, Integer.toString(defaultValue), comment, INTEGER); if (!prop.isIntValue()) { prop.value = Integer.toString(defaultValue); } return prop; } public Property get(String category, String key, boolean defaultValue) { return get(category, key, defaultValue, null); } public Property get(String category, String key, boolean defaultValue, String comment) { Property prop = get(category, key, Boolean.toString(defaultValue), comment, BOOLEAN); if (!prop.isBooleanValue()) { prop.value = Boolean.toString(defaultValue); } return prop; } public Property get(String category, String key, double defaultValue) { return get(category, key, defaultValue, null); } public Property get(String category, String key, double defaultValue, String comment) { Property prop = get(category, key, Double.toString(defaultValue), comment, DOUBLE); if (!prop.isDoubleValue()) { prop.value = Double.toString(defaultValue); } return prop; } public Property get(String category, String key, String defaultValue) { return get(category, key, defaultValue, null); } public Property get(String category, String key, String defaultValue, String comment) { return get(category, key, defaultValue, comment, STRING); } public Property get(String category, String key, String[] defaultValue) { return get(category, key, defaultValue, null); } public Property get(String category, String key, String[] defaultValue, String comment) { return get(category, key, defaultValue, comment, STRING); } public Property get(String category, String key, int[] defaultValue) { return get(category, key, defaultValue, null); } public Property get(String category, String key, int[] defaultValue, String comment) { String[] values = new String[defaultValue.length]; for (int i = 0; i < defaultValue.length; i++) { values[i] = Integer.toString(defaultValue[i]); } Property prop = get(category, key, values, comment, INTEGER); if (!prop.isIntList()) { prop.valueList = values; } return prop; } public Property get(String category, String key, double[] defaultValue) { return get(category, key, defaultValue, null); } public Property get(String category, String key, double[] defaultValue, String comment) { String[] values = new String[defaultValue.length]; for (int i = 0; i < defaultValue.length; i++) { values[i] = Double.toString(defaultValue[i]); } Property prop = get(category, key, values, comment, DOUBLE); if (!prop.isDoubleList()) { prop.valueList = values; } return prop; } public Property get(String category, String key, boolean[] defaultValue) { return get(category, key, defaultValue, null); } public Property get(String category, String key, boolean[] defaultValue, String comment) { String[] values = new String[defaultValue.length]; for (int i = 0; i < defaultValue.length; i++) { values[i] = Boolean.toString(defaultValue[i]); } Property prop = get(category, key, values, comment, BOOLEAN); if (!prop.isBooleanList()) { prop.valueList = values; } return prop; } public Property get(String category, String key, String defaultValue, String comment, Property.Type type) { if (!caseSensitiveCustomCategories) { category = category.toLowerCase(Locale.ENGLISH); } ConfigCategory cat = getCategory(category); if (cat.containsKey(key)) { Property prop = cat.get(key); if (prop.getType() == null) { prop = new Property(prop.getName(), prop.value, type); cat.set(key, prop); } prop.comment = comment; return prop; } else if (defaultValue != null) { Property prop = new Property(key, defaultValue, type); cat.set(key, prop); prop.comment = comment; return prop; } else { return null; } } public Property get(String category, String key, String[] defaultValue, String comment, Property.Type type) { if (!caseSensitiveCustomCategories) { category = category.toLowerCase(Locale.ENGLISH); } ConfigCategory cat = getCategory(category); if (cat.containsKey(key)) { Property prop = cat.get(key); if (prop.getType() == null) { prop = new Property(prop.getName(), prop.value, type); cat.set(key, prop); } prop.comment = comment; return prop; } else if (defaultValue != null) { Property prop = new Property(key, defaultValue, type); prop.comment = comment; cat.set(key, prop); return prop; } else { return null; } } public boolean hasCategory(String category) { return categories.get(category) != null; } public boolean hasKey(String category, String key) { ConfigCategory cat = categories.get(category); return cat != null && cat.containsKey(key); } public void load() { if (PARENT != null && PARENT != this) { return; } BufferedReader buffer = null; UnicodeInputStreamReader input = null; try { if (file.getParentFile() != null) { file.getParentFile().mkdirs(); } if (!file.exists() && !file.createNewFile()) { return; } if (file.canRead()) { input = new UnicodeInputStreamReader(new FileInputStream(file), defaultEncoding); defaultEncoding = input.getEncoding(); buffer = new BufferedReader(input); String line; ConfigCategory currentCat = null; Property.Type type = null; ArrayList<String> tmpList = null; int lineNum = 0; String name = null; while (true) { lineNum++; line = buffer.readLine(); if (line == null) { break; } Matcher start = CONFIG_START.matcher(line); Matcher end = CONFIG_END.matcher(line); if (start.matches()) { fileName = start.group(1); categories = new TreeMap<String, ConfigCategory>(); continue; } else if (end.matches()) { fileName = end.group(1); Configuration child = new Configuration(); child.categories = categories; this.children.put(fileName, child); continue; } int nameStart = -1, nameEnd = -1; boolean skip = false; boolean quoted = false; for (int i = 0; i < line.length() && !skip; ++i) { if (Character.isLetterOrDigit(line.charAt(i)) || ALLOWED_CHARS.indexOf(line.charAt(i)) != -1 || (quoted && line.charAt(i) != '"')) { if (nameStart == -1) { nameStart = i; } nameEnd = i; } else if (Character.isWhitespace(line.charAt(i))) { // ignore space charaters } else { switch (line.charAt(i)) { case ' skip = true; continue; case '"': if (quoted) { quoted = false; } if (!quoted && nameStart == -1) { quoted = true; } break; case '{': name = line.substring(nameStart, nameEnd + 1); String qualifiedName = ConfigCategory.getQualifiedName(name, currentCat); ConfigCategory cat = categories.get(qualifiedName); if (cat == null) { currentCat = new ConfigCategory(name, currentCat); categories.put(qualifiedName, currentCat); } else { currentCat = cat; } name = null; break; case '}': if (currentCat == null) { throw new RuntimeException(String.format("Config file corrupt, attepted to close to many categories '%s:%d'", fileName, lineNum)); } currentCat = currentCat.parent; break; case '=': name = line.substring(nameStart, nameEnd + 1); if (currentCat == null) { throw new RuntimeException(String.format("'%s' has no scope in '%s:%d'", name, fileName, lineNum)); } Property prop = new Property(name, line.substring(i + 1), type, true); i = line.length(); currentCat.set(name, prop); break; case ':': type = Property.Type.tryParse(line.substring(nameStart, nameEnd + 1).charAt(0)); nameStart = nameEnd = -1; break; case '<': if (tmpList != null) { throw new RuntimeException(String.format("Malformed list property \"%s:%d\"", fileName, lineNum)); } name = line.substring(nameStart, nameEnd + 1); if (currentCat == null) { throw new RuntimeException(String.format("'%s' has no scope in '%s:%d'", name, fileName, lineNum)); } tmpList = new ArrayList<String>(); skip = true; break; case '>': if (tmpList == null) { throw new RuntimeException(String.format("Malformed list property \"%s:%d\"", fileName, lineNum)); } currentCat.set(name, new Property(name, tmpList.toArray(new String[tmpList.size()]), type)); name = null; tmpList = null; type = null; break; default: throw new RuntimeException(String.format("Unknown character '%s' in '%s:%d'", line.charAt(i), fileName, lineNum)); } } } if (quoted) { throw new RuntimeException(String.format("Unmatched quote in '%s:%d'", fileName, lineNum)); } else if (tmpList != null && !skip) { tmpList.add(line.trim()); } } } } catch (IOException e) { e.printStackTrace(); } finally { if (buffer != null) { try { buffer.close(); } catch (IOException e){} } if (input != null) { try { input.close(); } catch (IOException e){} } } } public void save() { if (PARENT != null && PARENT != this) { PARENT.save(); return; } try { if (file.getParentFile() != null) { file.getParentFile().mkdirs(); } if (!file.exists() && !file.createNewFile()) { return; } if (file.canWrite()) { FileOutputStream fos = new FileOutputStream(file); BufferedWriter buffer = new BufferedWriter(new OutputStreamWriter(fos, defaultEncoding)); buffer.write("# Configuration file" + NEW_LINE + NEW_LINE); if (children.isEmpty()) { save(buffer); } else { for (Map.Entry<String, Configuration> entry : children.entrySet()) { buffer.write("START: \"" + entry.getKey() + "\"" + NEW_LINE); entry.getValue().save(buffer); buffer.write("END: \"" + entry.getKey() + "\"" + NEW_LINE + NEW_LINE); } } buffer.close(); fos.close(); } } catch (IOException e) { e.printStackTrace(); } } private void save(BufferedWriter out) throws IOException { //For compatiblitties sake just in case, Thanks Atomic, to be removed next MC version //TO-DO: Remove next MC version Object[] categoryArray = categories.values().toArray(); for (Object o : categoryArray) { if (o instanceof TreeMap) { TreeMap treeMap = (TreeMap)o; ConfigCategory converted = new ConfigCategory(file.getName()); FMLLog.warning("Forge found a Treemap saved for Configuration file " + file.getName() + ", this is deprecated behaviour!"); for (Object key : treeMap.keySet()) { FMLLog.warning("Converting Treemap to ConfigCategory, key: " + key + ", property value: " + ((Property)treeMap.get(key)).value); converted.set((String)key, (Property)treeMap.get(key)); } categories.values().remove(o); categories.put(file.getName(), converted); } } for (ConfigCategory cat : categories.values()) { if (!cat.isChild()) { cat.write(out, 0); out.newLine(); } } } public ConfigCategory getCategory(String category) { ConfigCategory ret = categories.get(category); if (ret == null) { if (category.contains(CATEGORY_SPLITTER)) { String[] hierarchy = category.split("\\"+CATEGORY_SPLITTER); ConfigCategory parent = categories.get(hierarchy[0]); if (parent == null) { parent = new ConfigCategory(hierarchy[0]); categories.put(parent.getQualifiedName(), parent); } for (int i = 1; i < hierarchy.length; i++) { String name = ConfigCategory.getQualifiedName(hierarchy[i], parent); ConfigCategory child = categories.get(name); if (child == null) { child = new ConfigCategory(hierarchy[i], parent); categories.put(name, child); } ret = child; parent = child; } } else { ret = new ConfigCategory(category); categories.put(category, ret); } } return ret; } public void addCustomCategoryComment(String category, String comment) { if (!caseSensitiveCustomCategories) category = category.toLowerCase(Locale.ENGLISH); getCategory(category).setComment(comment); } private void setChild(String name, Configuration child) { if (!children.containsKey(name)) { children.put(name, child); } else { Configuration old = children.get(name); child.categories = old.categories; child.fileName = old.fileName; } } public static void enableGlobalConfig() { PARENT = new Configuration(new File(Loader.instance().getConfigDir(), "global.cfg")); PARENT.load(); } public static class UnicodeInputStreamReader extends Reader { private final InputStreamReader input; private final String defaultEnc; public UnicodeInputStreamReader(InputStream source, String encoding) throws IOException { defaultEnc = encoding; String enc = encoding; byte[] data = new byte[4]; PushbackInputStream pbStream = new PushbackInputStream(source, data.length); int read = pbStream.read(data, 0, data.length); int size = 0; int bom16 = (data[0] & 0xFF) << 8 | (data[1] & 0xFF); int bom24 = bom16 << 8 | (data[2] & 0xFF); int bom32 = bom24 << 8 | (data[3] & 0xFF); if (bom24 == 0xEFBBBF) { enc = "UTF-8"; size = 3; } else if (bom16 == 0xFEFF) { enc = "UTF-16BE"; size = 2; } else if (bom16 == 0xFFFE) { enc = "UTF-16LE"; size = 2; } else if (bom32 == 0x0000FEFF) { enc = "UTF-32BE"; size = 4; } else if (bom32 == 0xFFFE0000) //This will never happen as it'll be caught by UTF-16LE, { //but if anyone ever runs across a 32LE file, i'd like to disect it. enc = "UTF-32LE"; size = 4; } if (size < read) { pbStream.unread(data, size, read - size); } this.input = new InputStreamReader(pbStream, enc); } public String getEncoding() { return input.getEncoding(); } @Override public int read(char[] cbuf, int off, int len) throws IOException { return input.read(cbuf, off, len); } @Override public void close() throws IOException { input.close(); } } }
package net.silentchaos512.lib.item; import java.util.List; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.silentchaos512.lib.SilentLib; import net.silentchaos512.lib.registry.IHasSubtypes; import net.silentchaos512.lib.registry.IRegistryObject; import net.silentchaos512.lib.util.LocalizationHelper; public class ItemBlockSL extends ItemBlock { protected String blockName = "null"; protected String unlocalizedName = "null"; protected String modId = "null"; public ItemBlockSL(Block block) { super(block); setMaxDamage(0); if (block instanceof IHasSubtypes) { setHasSubtypes(((IHasSubtypes) block).hasSubtypes()); } if (block instanceof IRegistryObject) { IRegistryObject obj = (IRegistryObject) block; blockName = obj.getName(); unlocalizedName = "tile." + obj.getFullName(); modId = obj.getModId(); } } @Override public int getMetadata(int meta) { return meta; } @Override public void addInformation(ItemStack stack, EntityPlayer player, List<String> list, boolean advanced) { // Get tooltip from block? (New method) int length = list.size(); block.addInformation(stack, player, list, advanced); // If block doesn't add anything, use the old method. if (length == list.size()) { LocalizationHelper loc = SilentLib.instance.getLocalizationHelperForMod(modId); if (loc != null) { String name = getNameForStack(stack); list.addAll(loc.getBlockDescriptionLines(name)); } } } @Override public String getUnlocalizedName(ItemStack stack) { return unlocalizedName + (hasSubtypes ? stack.getItemDamage() : ""); } public String getNameForStack(ItemStack stack) { return blockName + (hasSubtypes ? stack.getItemDamage() : ""); } }
package me.coley.recaf.ui.component.list; import java.awt.Color; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; import org.objectweb.asm.Type; import me.coley.recaf.Recaf; import me.coley.recaf.config.impl.ConfTheme; import me.coley.recaf.config.impl.ConfUI; import me.coley.recaf.ui.Fonts; /** * @author Matt * * @param <T> */ public interface RenderFormatter<T> extends ListCellRenderer<T> { /** * Sets the desired look of the list. * * @param list * List to apply style to. */ default void formatList(JList<?> list) { list.setBackground(Color.decode(getTheme().listBackground)); } /** * Sets the desired look of the lavel. * * @param label * Label to apply style to. * @param selected * If label is selected or not. */ default void formatLabel(JLabel label, boolean selected) { label.setFont(Fonts.monospace); label.setOpaque(true); label.setBorder(BorderFactory.createEtchedBorder()); if (selected) { label.setBackground(Color.decode(getTheme().listItemSelected)); } else { label.setBackground(Color.decode(getTheme().listItemBackground)); } } /** * HTML escape '&amp;', '&lt;' and '&gt;'. * * @param s * Text to escape * @return Text with amp, lt, and gt escaped correctly. */ default String escape(String s) { return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"); } /** * Converts a given type to a string. * * @param type * The type object. * @return String representation of the type object. */ default String getTypeStr(Type type) { return getTypeStr(type, null); } /** * Converts a given type to a string. Output will be simplified if enabled * in passed options. * * @param type * The type object. * @param options * Options object. * @return String representation of the type object. * @see me.coley.recaf.config.UiConfig */ default String getTypeStr(Type type, ConfUI options) { String s = type.getDescriptor(); // Check if field type. If so, then format as class name. if (!s.contains("(") && (s.length() == 1 || s.startsWith("L") || s.startsWith("["))) { s = type.getClassName(); } if(s == null) { Recaf.INSTANCE.logging.warn("Type " + type + " has no descriptor or class"); s = "" + type; } // If simplification is on, substring away package. if (options != null && options.opcodeSimplifyDescriptors && s.contains(".")) { s = s.substring(s.lastIndexOf(".") + 1); } // Return name in internal style return s.replace(".", "/"); } /** * Italicize the given text. * * @param input * Text to italicize. * @return HTML markup to italicize the text. */ default String italic(String input) { return "<i>" + input + "</i>"; } /** * Bold the given text. * * @param input * Text to bold. * @return HTML markup with the text bolded. */ default String bold(String input) { return "<b>" + input + "</b>"; } /** * Color the given text. * * @param color * The color to turn the text, must be a valid HTML color. * @param input * The text to color. * @return HTML markup with the text colored appropriately. */ default String color(String color, String input) { return "<font color=\"" + color + "\">" + input + "</font>"; } /** * @return Colors instance. */ default ConfTheme getTheme() { return Recaf.INSTANCE.configs.theme; } }
package com.anton.fastcloud.natives; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class Natives { public static final String[] LIB_NAMES = {"libnatives.so"}; public static void init() { try { Path tempDirPath = Files.createTempDirectory("fastcloud-natives"); for (String libName : LIB_NAMES) { Path libPath = tempDirPath.resolve(libName); Files.copy(Natives.class.getResourceAsStream("/" + libName), libPath); System.load(libPath.toString()); if (!libPath.toFile().delete()) { throw new IOException("Can't remove temp files"); } } if (!tempDirPath.toFile().delete()) { throw new IOException("Can't remove temp files"); } } catch (IOException e) { throw new RuntimeException(e); } } }
package net.mcft.copy.betterstorage.blocks; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.mcft.copy.betterstorage.BetterStorage; import net.mcft.copy.betterstorage.ItemIdentifier; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; /** Holds data for a single crate pile, a multi-block * structure made from individual crate blocks */ public class CratePileData implements Iterable<ItemStack> { public final CratePileCollection collection; public final int id; private Map<ItemIdentifier, ItemStack> contents = new HashMap<ItemIdentifier, ItemStack>(); private ItemStack[] contentsArray; private int numCrates = 0; private int numSlots = 0; private boolean destroyed = false; /** An inventory interface built for machines accessing the crate pile. */ public final IInventory blockView = new InventoryCrateBlockView(this); /** Returns the number of crates attached. */ public int getNumCrates() { return numCrates; } /** Returns the maximum number of slots. */ public int getCapacity() { return numCrates * TileEntityCrate.slotsPerCrate; } /** Returns the number of unique items. */ public int getNumItems() { return contents.size(); } /** Returns the number of slots occupied. */ public int getOccupiedSlots() { return numSlots; } /** Returns the number of slots free. Negative if there's any overflow. */ public int getFreeSlots() { return getCapacity() - getOccupiedSlots(); } public CratePileData(CratePileCollection collection, int id, int numCrates) { this.collection = collection; this.id = id; this.numCrates = numCrates; } public boolean canAdd(TileEntityCrate crate) { return true; } public void addCrate(TileEntityCrate crate) { numCrates++; markDirty(); } public void removeCrate(TileEntityCrate crate) { if (--numCrates <= 0) { collection.removeCratePile(this); destroyed = true; } else markDirty(); } // For safety reasons, these functions don't // return the original item stacks publicly. /** Returns an ItemStack from the contents, null if none was found. */ private ItemStack getItemStack(ItemIdentifier item, boolean copy) { if (item == null) return null; ItemStack stack = contents.get(item); return (copy ? ItemStack.copyItemStack(stack) : stack); } /** Returns an ItemStack from the contents, null if none was found. */ public ItemStack getItemStack(ItemIdentifier item) { return getItemStack(item, true); } /** Returns an ItemStack from the contents, null if none was found. */ private ItemStack getItemStack(ItemStack item, boolean copy) { if (item == null) return null; return getItemStack(new ItemIdentifier(item), copy); } /** Returns an ItemStack from the contents, null if none was found. */ public ItemStack getItemStack(ItemStack item) { return getItemStack(item, true); } /** Returns an ItemStack from the contents. */ public ItemStack getItemStack(int index) { if (index < 0 || index >= getNumItems()) return null; return contentsArray[index]; } /** Returns the number of items of this type in the contents. */ public int getItemCount(ItemIdentifier item) { ItemStack stack = getItemStack(item); return ((stack != null) ? stack.stackSize : 0); } /** Returns the number of items of this type in the contents. */ public int getItemCount(ItemStack item) { return getItemCount(new ItemIdentifier(item)); } /** Tries to add a stack to the contents. <br> * Returns what could not be added, null if there was no overflow. */ public ItemStack addItems(ItemStack stack) { if (stack == null) return null; ItemStack overflow = null; int space = spaceForItem(stack); if (space > 0) { if (space < stack.stackSize) overflow = stack.splitStack(stack.stackSize - space); ItemStack contentsStack = getItemStack(stack, false); int stacksBefore; // If there's no such item in contents yet, add it. if (contentsStack == null) { stacksBefore = 0; contentsStack = stack.copy(); contents.put(new ItemIdentifier(contentsStack), contentsStack); updateContentsArray(); // Otherwise just increase the stack size. } else { stacksBefore = calcNumStacks(contentsStack); contentsStack.stackSize += stack.stackSize; } int stacksAfter = calcNumStacks(contentsStack); numSlots += (stacksAfter - stacksBefore); } else overflow = stack; markDirty(); return overflow; } /** Tries to add some stacks to the contents. <br> * Returns what could not be added. */ public List<ItemStack> addItems(Collection<ItemStack> stacks) { List<ItemStack> overflow = new ArrayList<ItemStack>(); for (ItemStack stack : stacks) { ItemStack overflowStack = addItems(stack); if (overflowStack != null) overflow.add(overflowStack); } return overflow; } /** Removes and returns a specific amount of items. <br> * Returns less than the requested amount when there's * not enough, or null if there's none at all. */ public ItemStack removeItems(ItemIdentifier item, int amount) { ItemStack stack = getItemStack(item, false); if (stack == null) return null; if (amount <= 0) return null; int stacksBefore = calcNumStacks(stack); int stacksAfter; if (amount < stack.stackSize) { stack.stackSize -= amount; stacksAfter = calcNumStacks(stack); stack = stack.copy(); stack.stackSize = amount; } else { contents.remove(item); updateContentsArray(); stacksAfter = 0; } numSlots -= (stacksBefore - stacksAfter); markDirty(); return stack; } /** Removes and returns a specific amount of items. <br> * Returns less than the requested amount when there's * not enough, or null if there's none at all. */ public ItemStack removeItems(ItemStack item, int amount) { if (item == null) return null; return removeItems(new ItemIdentifier(item), amount); } /** Removes and returns a specific amount of items. <br> * Returns less than the requested amount when there's * not enough, or null if there's none at all. */ public ItemStack removeItems(ItemStack stack) { if (stack == null) return null; return removeItems(stack, stack.stackSize); } /** Returns how much space there is left for a specific item. */ public int spaceForItem(ItemIdentifier item) { if (item == null) return 0; int stackLimit = item.getItem().getItemStackLimit(); int space = getFreeSlots() * stackLimit; ItemStack stack = getItemStack(item); if (stack != null) space += (calcNumStacks(stack) * stackLimit) - stack.stackSize; return space; } /** Returns how much space there is left for a specific item. */ public int spaceForItem(ItemStack item) { if (item == null) return 0; return spaceForItem(new ItemIdentifier(item)); } private void updateContentsArray() { contentsArray = contents.values().toArray(new ItemStack[getNumItems()]); } /** Gets the number of stacks this ItemStack * would split into under normal circumstances. */ public static int calcNumStacks(ItemStack stack) { return ItemIdentifier.calcNumStacks(stack.getItem(), stack.stackSize); } /** Marks the pile data as dirty so it gets saved. */ public void markDirty() { if (destroyed) return; collection.markDirty(this); } @Override public Iterator<ItemStack> iterator() { return contents.values().iterator(); } /** Picks random items from the pile. <br> * Each stack has a chance to get picked. */ public List<ItemStack> pickItemStacks(int amount) { amount = Math.min(amount, getOccupiedSlots()); if (amount <= 0) return new ArrayList<ItemStack>(); int totalStacks = 0; List<ItemStack> stacks = new ArrayList<ItemStack>(); for (ItemStack contentsStack : this) { int numStacks = ItemIdentifier.calcNumStacks(contentsStack); for (int i = 0; i < numStacks; i++) { ItemStack stack = contentsStack.copy(); int maxStackSize = stack.getMaxStackSize(); int max = Math.min(contentsStack.stackSize - maxStackSize * i, maxStackSize); stack.stackSize = Math.min(stack.stackSize, max); stacks.add(stack); } totalStacks += numStacks; } List<ItemStack> resultStacks = new ArrayList<ItemStack>(); for (int i = 0; i < amount; i++) resultStacks.add(stacks.remove(BetterStorage.random.nextInt(stacks.size()))); return resultStacks; } /** Picks and removes random items from the pile. <br> * Each stack has a chance to get picked. */ public List<ItemStack> pickAndRemoveItemStacks(int amount) { List<ItemStack> stacks = pickItemStacks(amount); for (ItemStack stack : stacks) removeItems(stack); return stacks; } }
package nitezh.ministock.domain; import android.content.Context; import org.json.JSONException; import org.json.JSONObject; import java.text.NumberFormat; import java.text.ParseException; import java.text.RuleBasedCollator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import nitezh.ministock.DialogTools; import nitezh.ministock.Storage; import nitezh.ministock.UserData; import nitezh.ministock.utils.Cache; import nitezh.ministock.utils.CurrencyTools; import nitezh.ministock.utils.NumberTools; public class PortfolioStockRepository { public static final String PORTFOLIO_JSON = "portfolioJson"; public static final String WIDGET_JSON = "widgetJson"; public HashMap<String, StockQuote> stocksQuotes = new HashMap<>(); public HashMap<String, PortfolioStock> portfolioStocksInfo = new HashMap<>(); public Set<String> widgetsStockSymbols = new HashSet<>(); private static final HashMap<String, PortfolioStock> mPortfolioStocks = new HashMap<>(); private static boolean mDirtyPortfolioStockMap = true; private Storage mAppStorage; public PortfolioStockRepository(Storage appStorage, Cache cache, WidgetRepository widgetRepository) { this.mAppStorage = appStorage; this.widgetsStockSymbols = widgetRepository.getWidgetsStockSymbols(); this.portfolioStocksInfo = getPortfolioStocksInfo(widgetsStockSymbols); this.stocksQuotes = getStocksQuotes(appStorage, cache, widgetRepository); } private HashMap<String, StockQuote> getStocksQuotes(Storage appStorage, Cache cache, WidgetRepository widgetRepository) { Set<String> symbolSet = portfolioStocksInfo.keySet(); return new StockQuoteRepository(appStorage, cache, widgetRepository) .getQuotes(Arrays.asList(symbolSet.toArray(new String[symbolSet.size()])), false); } private HashMap<String, PortfolioStock> getPortfolioStocksInfo(Set<String> symbols) { HashMap<String, PortfolioStock> stocks = this.getStocks(); for (String symbol : symbols) { if (!stocks.containsKey(symbol)) { stocks.put(symbol, null); } } return stocks; } public List<Map<String, String>> getDisplayInfo() { NumberFormat numberFormat = NumberFormat.getInstance(); List<Map<String, String>> info = new ArrayList<>(); for (String symbol : this.getSortedSymbols()) { StockQuote quote = this.stocksQuotes.get(symbol); PortfolioStock stock = this.getStock(symbol); Map<String, String> itemInfo = new HashMap<>(); populateDisplayNames(quote, stock, itemInfo); // Get the current price if we have the data String currentPrice = populateDisplayCurrentPrice(quote, itemInfo); if (hasInfoForStock(stock)) { String buyPrice = stock.getPrice(); itemInfo.put("buyPrice", buyPrice); itemInfo.put("date", stock.getDate()); populateDisplayHighLimit(stock, itemInfo); populateDisplayLowLimit(stock, itemInfo); itemInfo.put("quantity", stock.getQuantity()); populateDisplayLastChange(numberFormat, symbol, quote, stock, itemInfo); populateDisplayTotalChange(numberFormat, symbol, stock, itemInfo, currentPrice, buyPrice); populateDisplayHoldingValue(numberFormat, symbol, stock, itemInfo, currentPrice); } itemInfo.put("symbol", symbol); info.add(itemInfo); } return info; } private boolean hasInfoForStock(PortfolioStock stock) { return !stock.getPrice().equals(""); } private void populateDisplayHighLimit(PortfolioStock stock, Map<String, String> itemInfo) { String limitHigh = NumberTools.decimalPlaceFormat(stock.getHighLimit()); itemInfo.put("limitHigh", limitHigh); } private void populateDisplayLowLimit(PortfolioStock stock, Map<String, String> itemInfo) { String limitLow = NumberTools.decimalPlaceFormat(stock.getLowLimit()); itemInfo.put("limitLow", limitLow); } private void populateDisplayHoldingValue(NumberFormat numberFormat, String symbol, PortfolioStock stock, Map<String, String> itemInfo, String currentPrice) { String holdingValue = ""; try { Double holdingQuanta = NumberTools.parseDouble(stock.getQuantity()); Double holdingPrice = numberFormat.parse(currentPrice).doubleValue(); holdingValue = CurrencyTools.addCurrencyToSymbol(String.format("%.0f", (holdingQuanta * holdingPrice)), symbol); } catch (Exception ignored) { } itemInfo.put("holdingValue", holdingValue); } private void populateDisplayLastChange(NumberFormat numberFormat, String symbol, StockQuote quote, PortfolioStock stock, Map<String, String> itemInfo) { String lastChange = ""; try { if (quote != null) { lastChange = quote.getPercent(); try { Double change = numberFormat.parse(quote.getChange()).doubleValue(); Double totalChange = NumberTools.parseDouble(stock.getQuantity()) * change; lastChange += " / " + CurrencyTools.addCurrencyToSymbol(String.format("%.0f", (totalChange)), symbol); } catch (Exception ignored) { } } } catch (Exception ignored) { } itemInfo.put("lastChange", lastChange); } private void populateDisplayTotalChange(NumberFormat numberFormat, String symbol, PortfolioStock stock, Map<String, String> itemInfo, String currentPrice, String buyPrice) { // Calculate total change, including percentage String totalChange = ""; try { Double price = numberFormat.parse(currentPrice).doubleValue(); Double buy = Double.parseDouble(buyPrice); Double totalPercentChange = price - buy; totalChange = String.format("%.0f", 100 * totalPercentChange / buy) + "%"; // Calculate change try { Double quanta = NumberTools.parseDouble(stock.getQuantity()); totalChange += " / " + CurrencyTools.addCurrencyToSymbol(String.format("%.0f", quanta * totalPercentChange), symbol); } catch (Exception ignored) { } } catch (Exception ignored) { } itemInfo.put("totalChange", totalChange); } private String populateDisplayCurrentPrice(StockQuote quote, Map<String, String> itemInfo) { String currentPrice = ""; if (quote != null) currentPrice = quote.getPrice(); itemInfo.put("currentPrice", currentPrice); return currentPrice; } private void populateDisplayNames(StockQuote quote, PortfolioStock stock, Map<String, String> itemInfo) { String name = "No description"; if (quote != null) { if (!stock.getCustomName().equals("")) { name = stock.getCustomName(); itemInfo.put("customName", name); } if (name.equals("")) { name = quote.getName(); } } itemInfo.put("name", name); } private PortfolioStock getStock(String symbol) { PortfolioStock stock = this.portfolioStocksInfo.get(symbol); if (stock == null) { stock = new PortfolioStock(symbol, "", "", "", "", "", "", null); } this.portfolioStocksInfo.put(symbol, stock); return stock; } // Problem with empty stocks in portofolio public void backupPortfolio(Context context) { // Convert current portfolioStockInfo to JSONO-Object persist(); // Write JSONO-Object to internal app storage this.mAppStorage.putString(PORTFOLIO_JSON, getStocksJson().toString()).apply(); String rawJson = this.mAppStorage.getString(PORTFOLIO_JSON, ""); UserData.writeExternalStorage(context, rawJson, PORTFOLIO_JSON); DialogTools.showSimpleDialog(context, "PortfolioActivity backed up", "Your portfolio settings have been backed up to internal mAppStorage."); } /* * prblem with getstocks() -> getStocksJson() storage */ public void restorePortfolio(Context context) { mDirtyPortfolioStockMap = true; String rawJson = UserData.readExternalStorage(context, PORTFOLIO_JSON); this.mAppStorage.putString(PORTFOLIO_JSON, rawJson).apply(); persist(); this.portfolioStocksInfo = getStocks(); DialogTools.showSimpleDialog(context, "PortfolioActivity restored", "Your portfolio settings have been restored from internal mAppStorage."); } public JSONObject getStocksJson() { JSONObject stocksJson = new JSONObject(); try { stocksJson = new JSONObject(this.mAppStorage.getString(PORTFOLIO_JSON, "")); } catch (JSONException ignored) { } return stocksJson; } public HashMap<String, PortfolioStock> getStocks() { if (!mDirtyPortfolioStockMap) { return mPortfolioStocks; } mPortfolioStocks.clear(); // Use the Json data if present Iterator keys; JSONObject json = this.getStocksJson(); keys = json.keys(); while (keys.hasNext()) { String key = keys.next().toString(); JSONObject itemJson = new JSONObject(); try { itemJson = json.getJSONObject(key); } catch (JSONException ignored) { } HashMap<PortfolioField, String> stockInfoMap = new HashMap<>(); for (PortfolioField f : PortfolioField.values()) { String data = ""; try { if (!itemJson.get(f.name()).equals("empty")) { data = itemJson.get(f.name()).toString(); } } catch (JSONException ignored) { } stockInfoMap.put(f, data); } PortfolioStock stock = new PortfolioStock(key, stockInfoMap.get(PortfolioField.PRICE), stockInfoMap.get(PortfolioField.DATE), stockInfoMap.get(PortfolioField.QUANTITY), stockInfoMap.get(PortfolioField.LIMIT_HIGH), stockInfoMap.get(PortfolioField.LIMIT_LOW), stockInfoMap.get(PortfolioField.CUSTOM_DISPLAY), stockInfoMap.get(PortfolioField.SYMBOL_2)); mPortfolioStocks.put(key, stock); } mDirtyPortfolioStockMap = false; return mPortfolioStocks; } public void persist() { JSONObject json = new JSONObject(); for (String symbol : this.portfolioStocksInfo.keySet()) { PortfolioStock item = this.portfolioStocksInfo.get(symbol); if (!item.isEmpty()) { try { json.put(symbol, item.toJson()); } catch (JSONException ignored) { } } } this.mAppStorage.putString(PORTFOLIO_JSON, json.toString()); this.mAppStorage.apply(); mDirtyPortfolioStockMap = true; } public HashMap<String, PortfolioStock> getStocksForSymbols(List<String> symbols) { HashMap<String, PortfolioStock> stocksForSymbols = new HashMap<>(); HashMap<String, PortfolioStock> stocks = this.getStocks(); for (String symbol : symbols) { PortfolioStock stock = stocks.get(symbol); if (stock != null && !stock.isEmpty()) { stocksForSymbols.put(symbol, stock); } } return stocksForSymbols; } public List<String> getSortedSymbols() { ArrayList<String> symbols = new ArrayList<>(); for (String key : this.portfolioStocksInfo.keySet()) { symbols.add(key); } try { // Ensure symbols beginning with ^ appear first Collections.sort(symbols, new RuleBasedCollator("< '^' < a")); } catch (ParseException ignored) { } return symbols; } public void updateStock(String symbol, String price, String date, String quantity, String limitHigh, String limitLow, String customDisplay) { PortfolioStock portfolioStock = new PortfolioStock(symbol, price, date, quantity, limitHigh, limitLow, customDisplay, null); this.portfolioStocksInfo.put(symbol, portfolioStock); } public void updateStock(String symbol) { this.updateStock(symbol, "", "", "", "", "", ""); } public void removeUnused() { for (String symbol : this.portfolioStocksInfo.keySet()) { String price = this.portfolioStocksInfo.get(symbol).getPrice(); if ((price == null || price.equals("")) && !this.widgetsStockSymbols.contains(symbol)) { this.portfolioStocksInfo.remove(symbol); } } } public void saveChanges() { this.removeUnused(); this.persist(); } public enum PortfolioField { PRICE, DATE, QUANTITY, LIMIT_HIGH, LIMIT_LOW, CUSTOM_DISPLAY, SYMBOL_2 } }
package org.biojava.bio.program.hmmer; import org.biojava.bio.dp.*; import org.biojava.bio.dp.onehead.*; import java.io.*; import java.util.*; import org.biojava.bio.dist.*; import org.biojava.bio.symbol.*; import org.biojava.bio.seq.*; import org.biojava.bio.seq.db.*; import org.biojava.bio.seq.io.*; import org.biojava.utils.*; import org.biojava.bio.*; /** A class for parsing in Hmmer markov models from HMM_ls files generated by HMMER training * note that this class is still currently experimental. * @author Lachlan Coin */ public class HmmerProfileParser{ /** Returns a profile HMM representing the core HMMER hmm * @param inputfile the file which contains the Profile HMM data, as output by HMMER - e.g. HMM_ls */ public static HmmerProfileHMM parse(File inputfile){ HmmerProfileParser hmmP = new HmmerProfileParser(inputfile.toString()); hmmP.parseModel(inputfile); hmmP.setProfileHMM(); return hmmP.getModel(); } /** Returns the full markov model - including the core model + J,C,N loop states. * @param inputfile the file which contains the Profile HMM data, as output by HMMER - e.g. HMM_ls */ public static FullHmmerProfileHMM parseFull(File inputfile){ HmmerProfileParser hmmP = new HmmerProfileParser(inputfile.toString()); hmmP.parseModel(inputfile); hmmP.setProfileHMM(); hmmP.initialiseFullProfileHMM(); hmmP.setFullProfileHMM(); return hmmP.getFullModel(); } private String domain1; private HmmerProfileParser(String domain){ this.domain1 = domain; } HmmerModel hmm; private static final double sumCheckThreshold = 0.001; HmmerProfileHMM getModel(){ return hmm.hmm; } FullHmmerProfileHMM getFullModel(){ return hmm.hmm_full; } void initialiseFullProfileHMM(){ hmm.initialiseFullProfileHMM(); } void setProfileHMM(){ hmm.setProfileHMM(); } void setFullProfileHMM(){ hmm.setFullProfileHMM(); } private void parseModel(File inputFile){ System.out.println("Parsing model "+inputFile); try{ BufferedReader in = new BufferedReader(new FileReader(inputFile)); boolean inModel=false; int seq_pos=1; int rel_pos=0; String s = new String(); while((s = in.readLine())!= null){ if(s.startsWith("//")) break; if(!inModel){ if(s.startsWith("LENG")) { int[] a = parseString(s.substring(5),1); hmm = new HmmerModel(a[0]); } else if(s.startsWith("NULE")) hmm.setNullEmissions(s.substring(5)); else if(s.startsWith("NULT")) hmm.setNullTransitions(s.substring(5)); else if(s.startsWith("XT")) hmm.setSpecialTransitions(s.substring(5)); else if(s.startsWith("HMM ")){ inModel=true; hmm.setAlphList(s.substring(7)); in.readLine(); hmm.setBeginTransition(in.readLine()); } } else{ if(rel_pos==0){ hmm.setEmissions(s.substring(7), seq_pos); } else if(rel_pos==1 && seq_pos==1){ hmm.setInsertEmissions(s.substring(7)); } else if(rel_pos==2){ hmm.setTransitions(s.substring(7), seq_pos); } rel_pos++; if(rel_pos==3){ rel_pos=0; seq_pos++; } } } in.close(); } catch(Throwable t){ t.printStackTrace(); } } static int[] parseString(String s, int len){ String[] s1 = parseStringA(s,len); int[] s2 = new int[len]; for(int i=0; i<s1.length; i++){ if(s1[i].indexOf("*")!= -1) s2[i] = Integer.MIN_VALUE; else s2[i] = Integer.parseInt(s1[i]); } return s2; } static String[] parseStringA(String s, int len){ String[] s2 = new String[len]; StringTokenizer st = new StringTokenizer(s); int i=0; while(st.hasMoreTokens() && i<len){ s2[i] = st.nextToken(); i++; } return s2; } /** An intermediate class to store the parsed data */ class HmmerModel{ /** Maps the null emission probabilities to symbols */ int[] nullEmissions; /** Maps the null transition probabilities */ int[] nullTransitions; /**A map of emission probabilities along the sequence. */ int[][] emissions; int[] insertEmissions; int[][] transitions; int[] beginTransition; int[] specialTransitions; Symbol[] alphList; Alphabet alph; HmmerProfileHMM hmm; FullHmmerProfileHMM hmm_full; HmmerModel(int length){ System.out.println("Constructing base model"); nullEmissions = new int[20]; nullTransitions = new int[2]; emissions = new int[length][20]; insertEmissions = new int[20]; specialTransitions = new int[8]; transitions = new int[length+1][9]; alphList = new Symbol[21]; alph = ProteinTools.getAlphabet(); initialiseProfileHMM(); } void setAlphList(String s){ try{ String[] list = parseStringA(s,20); SymbolTokenization tokenizer = alph.getTokenization("token"); for(int i=0; i<list.length;i++){ alphList[i] = tokenizer.parseToken(list[i]); } alphList[list.length] = tokenizer.parseToken("U"); } catch(Throwable t){ t.printStackTrace(); } } void setEmissions(String s, int pos){ emissions[pos-1] = parseString(s,20); } void setNullEmissions(String s){ nullEmissions = parseString(s,20); } void setInsertEmissions(String s){ insertEmissions = parseString(s,20); } void setNullTransitions(String s){ nullTransitions = parseString(s,2); } void setTransitions(String s, int pos){ transitions[pos] = parseString(s,9); } void setBeginTransition(String s){ transitions[0]= parseString(s,3); } void setSpecialTransitions(String s){ specialTransitions = parseString(s,8); } void initialiseProfileHMM(){ try{ DistributionFactory matchFactory = DistributionFactory.DEFAULT; DistributionFactory insertFactory = DistributionFactory.DEFAULT; hmm = new HmmerProfileHMM(alph, emissions.length, matchFactory, insertFactory, domain1); } catch(Throwable t){ t.printStackTrace(); } } void initialiseFullProfileHMM(){ try{ hmm_full = new FullHmmerProfileHMM(hmm); } catch(Throwable t){ t.printStackTrace(); } } private void validateDistributionSum(Distribution dist) throws Exception{ Iterator iter = ((FiniteAlphabet)dist.getAlphabet()).iterator(); double sum=0.0; while(iter.hasNext()){ Symbol to = (Symbol) iter.next(); sum += dist.getWeight(to); //System.out.println(to.getName()+" "+dist.getWeight(to)); } //System.out.println("//"); validateSum(sum); } private void addProbability(Distribution dist, State state, double prob) throws Exception{ if(Double.isNaN(dist.getWeight(state))) dist.setWeight(state,0); Iterator iter = ((FiniteAlphabet)dist.getAlphabet()).iterator(); while(iter.hasNext()){ Symbol to = (Symbol) iter.next(); double currentP = dist.getWeight(to); dist.setWeight(to,currentP*(1-prob)); } dist.setWeight(state, dist.getWeight(state)+prob); validateDistributionSum(dist); } private void checkTransitionSum() throws Exception{ for (int i=0; i<=hmm.columns();i++){ validateDistributionSum(hmm.getWeights(hmm.getMatch(i))); if(i>0 && i<hmm.columns()){ validateDistributionSum(hmm.getWeights(hmm.getInsert(i))); validateDistributionSum(hmm.getWeights(hmm.getDelete(i))); } } } private void validateSum(double sum) throws Exception{ if(Math.abs(sum-1.0)>sumCheckThreshold) throw new Exception("Distribution does not sum to 1. Sums to "+sum); } /** Modifies HMM search for partial hits, by dividing probability by 2 at * each point and adding transition to end state */ void addProfileHMMTransitions() throws Exception{ for(int i=1; i<=hmm.columns(); i++){ if(i>1){ hmm.createTransition(hmm.magicalState(), hmm.getMatch(i)); } if(i<hmm.columns()){ hmm.createTransition(hmm.getMatch(i), hmm.magicalState()); } } } /** Modifies HMM search for partial hits, by dividing probability by 2 at * each point and adding transition to end state */ void modifyProbabilities() throws Exception{ for(int i=1; i<=hmm.columns(); i++){ if(i>1){ addProbability(hmm.getWeights(hmm.magicalState()), hmm.getMatch(i), 0.5); } if(i<hmm.columns()){ addProbability(hmm.getWeights(hmm.getMatch(i)), hmm.magicalState(), 0.5); } } } void setBeginEnd() throws Exception{ Distribution dist = hmm.getWeights(hmm.magicalState()); for(int i=1; i<=hmm.columns(); i++){ EmissionState match = hmm.getMatch(i); Distribution match_dist = hmm.getWeights(match); dist.setWeight(match, convertToProb(transitions[i][7])); match_dist.setWeight(hmm.magicalState(),convertToProb(transitions[i][8])); } } void setFullProfileHMM(){ try{ Distribution dist = hmm_full.getWeights(hmm_full.magicalState()); dist.setWeight(hmm_full.nState(), 1.0); dist = hmm_full.getWeights(hmm_full.nState()); dist.setWeight(hmm_full.hmm(), convertToProb(specialTransitions[0])); dist.setWeight(hmm_full.nState(), convertToProb(specialTransitions[1])); dist = hmm_full.getWeights(hmm_full.hmm()); dist.setWeight(hmm_full.cState(), convertToProb(specialTransitions[2])); dist.setWeight(hmm_full.jState(), convertToProb(specialTransitions[3])); dist = hmm_full.getWeights(hmm_full.cState()); dist.setWeight(hmm_full.magicalState(), convertToProb(specialTransitions[4])); dist.setWeight(hmm_full.cState(), convertToProb(specialTransitions[5])); dist = hmm_full.getWeights(hmm_full.jState()); dist.setWeight(hmm_full.hmm(), convertToProb(specialTransitions[6])); dist.setWeight(hmm_full.jState(), convertToProb(specialTransitions[7])); } catch(Throwable t){ t.printStackTrace(); } } void setProfileHMM(){ try{ for(int i=0; i<=hmm.columns(); i++){ EmissionState match = hmm.getMatch(i); Distribution dist = hmm.getWeights(match); if(i<hmm.columns()){ dist.setWeight(hmm.getMatch(i+1), convertToProb(transitions[i][0])); if(i>=1){ dist.setWeight(hmm.getInsert(i), convertToProb(transitions[i][1])); } dist.setWeight(hmm.getDelete(i+1), convertToProb(transitions[i][2])); } else{ dist.setWeight(hmm.magicalState(),1.0); } } for(int i=1; i<hmm.columns(); i++){ EmissionState insert = hmm.getInsert(i); Distribution dist = hmm.getWeights(insert); dist.setWeight(hmm.getMatch(i+1), convertToProb(transitions[i][3])); dist.setWeight(insert, convertToProb(transitions[i][4])); } for(int i=1; i<hmm.columns(); i++){ DotState delete = hmm.getDelete(i); Distribution dist = hmm.getWeights(delete); dist.setWeight(hmm.getMatch(i+1), convertToProb(transitions[i][5])); dist.setWeight(hmm.getDelete(i+1), convertToProb(transitions[i][6])); } setBeginEnd(); checkTransitionSum(); // setting emission probabilities Distribution insertEmission = hmm.getInsert(1).getDistribution(); Distribution nullModel = DistributionFactory.DEFAULT.createDistribution(alph); for (int j=0; j<alphList.length; j++){ double prob; double null_prob; if(j<alphList.length-1){ prob = convertToProb(insertEmissions[j], nullEmissions[j]); null_prob = convertToProb(nullEmissions[j],0); } else{ prob = 0.0; null_prob = 0.0; } insertEmission.setWeight(alphList[j],prob); nullModel.setWeight(alphList[j],null_prob); } insertEmission.setNullModel(nullModel); validateDistributionSum(insertEmission); //System.out.println("NULL MODEL!!!!!"); validateDistributionSum(nullModel); for(int i=1; i<=hmm.columns(); i++){ Distribution matchEmission = hmm.getMatch(i).getDistribution(); if(i>1 && i<hmm.columns()) hmm.getInsert(i).setDistribution(insertEmission); for (int j=0; j<alphList.length; j++){ double prob; if(j<alphList.length-1) prob = convertToProb(emissions[i-1][j],nullEmissions[j]); else prob = 0.0; matchEmission.setWeight(alphList[j],prob); } validateDistributionSum(matchEmission); matchEmission.setNullModel(nullModel); //System.out.println("NULL MODEL!!!!!"); validateDistributionSum(matchEmission.getNullModel()); } //modifyProbabilities(); } catch(Throwable t){ t.printStackTrace(); } } private double convertToProb(int score){ double result=0.0; if(score!=Integer.MIN_VALUE){ result = 1*Math.pow(2.0,((double) score/1000)); } return result; } private double convertToProb(int score, int nullscore){ double result=0.0; if(score!=Integer.MIN_VALUE){ double background = 0.05*Math.pow(2.0,((double) nullscore/1000)); //result = background; result = background*Math.pow(2.0,((double) score/1000)); //System.out.println(score+ " "+nullscore+" "+result); } return result; } } }
package org.nschmidt.ldparteditor.data; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Stack; import java.util.TreeSet; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector4f; import org.nschmidt.ldparteditor.composites.Composite3D; import org.nschmidt.ldparteditor.enums.View; import org.nschmidt.ldparteditor.helpers.math.MathHelper; import org.nschmidt.ldparteditor.helpers.math.ThreadsafeHashMap; import org.nschmidt.ldparteditor.logger.NLogger; import org.nschmidt.ldparteditor.opengl.GLMatrixStack; import org.nschmidt.ldparteditor.opengl.GLShader; import org.nschmidt.ldparteditor.opengl.OpenGLRenderer33; /** * New OpenGL 3.3 high performance render function for the model (VAO accelerated) * @author nils * */ public class GL33ModelRenderer { boolean isPaused = false; private final Composite3D c3d; private final OpenGLRenderer33 renderer; public GL33ModelRenderer(Composite3D c3d) { this.c3d = c3d; this.renderer = (OpenGLRenderer33) c3d.getRenderer(); } // FIXME needs concept implementation! // --v Here I try to use only one(!) VAO for the price of letting an asynchronous thread doing the buffer data generation! // This is super-fast! // However, TEXMAP/!LPE PNG will require a multi-VAO solution (all non-TEXMAP/PNG stuff can still be rendered with one VAO). private int vao; private int vbo; private int vaoGlyphs; private int vboGlyphs; private int vaoLines; private int vboLines; private int vaoTempLines; private int vboTempLines; private int vaoVertices; private int vboVertices; private int vaoSelectionLines; private int vboSelectionLines; private int vaoCondlines; private int vboCondlines; private volatile Lock lock = new ReentrantLock(); private static volatile Lock static_lock = new ReentrantLock(); private static volatile AtomicInteger idGen = new AtomicInteger(0); private static volatile AtomicInteger idCount = new AtomicInteger(0); private static volatile CopyOnWriteArrayList<Integer> idList = new CopyOnWriteArrayList<>(); private volatile AtomicBoolean calculateCondlineControlPoints = new AtomicBoolean(true); private volatile TreeSet<Vertex> pureCondlineControlPoints = new TreeSet<>(); private volatile float[] dataTriangles = null; private volatile float[] dataLines = new float[]{0f}; private volatile float[] dataTempLines = new float[]{0f}; private volatile float[] dataGlyphs = new float[]{0f}; private volatile float[] dataVertices = null; private volatile float[] dataCondlines = new float[]{0f}; private volatile float[] dataSelectionLines = new float[]{0f}; private volatile int solidTriangleSize = 0; private volatile int transparentTriangleOffset = 0; private volatile int transparentTriangleSize = 0; private volatile int lineSize = 0; private volatile int tempLineSize = 0; private volatile int glyphSize = 0; private volatile int vertexSize = 0; private volatile int condlineSize = 0; private volatile int selectionSize = 0; private volatile boolean usesTEXMAP = false; private volatile boolean usesPNG = false; private volatile AtomicBoolean isRunning = new AtomicBoolean(true); public void init() { vao = GL30.glGenVertexArrays(); vbo = GL15.glGenBuffers(); GL30.glBindVertexArray(vao); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, 0); GL20.glEnableVertexAttribArray(1); GL20.glVertexAttribPointer(1, 3, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, 3 * 4); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, (3 + 3) * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL30.glBindVertexArray(0); vaoGlyphs = GL30.glGenVertexArrays(); vboGlyphs = GL15.glGenBuffers(); GL30.glBindVertexArray(vaoGlyphs); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboGlyphs); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, 0); GL20.glEnableVertexAttribArray(1); GL20.glVertexAttribPointer(1, 3, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, 3 * 4); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, (3 + 3) * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL30.glBindVertexArray(0); vaoLines = GL30.glGenVertexArrays(); vboLines = GL15.glGenBuffers(); GL30.glBindVertexArray(vaoLines); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboLines); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, (3 + 4) * 4, 0); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, (3 + 4) * 4, 3 * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL30.glBindVertexArray(0); vaoTempLines = GL30.glGenVertexArrays(); vboTempLines = GL15.glGenBuffers(); GL30.glBindVertexArray(vaoTempLines); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboTempLines); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, (3 + 4) * 4, 0); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, (3 + 4) * 4, 3 * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL30.glBindVertexArray(0); vaoVertices = GL30.glGenVertexArrays(); vboVertices = GL15.glGenBuffers(); GL30.glBindVertexArray(vaoVertices); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboVertices); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, (3 + 4) * 4, 0); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, (3 + 4) * 4, 3 * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL30.glBindVertexArray(0); vaoSelectionLines = GL30.glGenVertexArrays(); vboSelectionLines = GL15.glGenBuffers(); GL30.glBindVertexArray(vaoSelectionLines); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboSelectionLines); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, (3 + 4) * 4, 0); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, (3 + 4) * 4, 3 * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL30.glBindVertexArray(0); vaoCondlines = GL30.glGenVertexArrays(); vboCondlines = GL15.glGenBuffers(); GL30.glBindVertexArray(vaoCondlines); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboCondlines); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 15 * 4, 0); GL20.glEnableVertexAttribArray(1); GL20.glVertexAttribPointer(1, 3, GL11.GL_FLOAT, false, 15 * 4, 3 * 4); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 3, GL11.GL_FLOAT, false, 15 * 4, 6 * 4); GL20.glEnableVertexAttribArray(3); GL20.glVertexAttribPointer(3, 3, GL11.GL_FLOAT, false, 15 * 4, 9 * 4); GL20.glEnableVertexAttribArray(4); GL20.glVertexAttribPointer(4, 3, GL11.GL_FLOAT, false, 15 * 4, 12 * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL30.glBindVertexArray(0); new Thread(new Runnable() { @Override public void run() { float[] normal; final Vector4f Nv = new Vector4f(0, 0, 0, 1f); final Matrix4f Mm = new Matrix4f(); Matrix4f.setIdentity(Mm); final Set<GData> selectionSet = new HashSet<GData>(); final ArrayList<GDataAndWinding> dataInOrder = new ArrayList<>(); final HashMap<GData, Vertex[]> vertexMap = new HashMap<>(); final HashMap<GData, float[]> normalMap = new HashMap<>(); final HashMap<GData, GData> transformMap = new HashMap<>(); final ThreadsafeHashMap<GData1, Matrix4f> CACHE_viewByProjection = new ThreadsafeHashMap<GData1, Matrix4f>(1000); final HashMap<GData1, Matrix4f> matrixMap = new HashMap<>(); final Integer myID = idGen.getAndIncrement(); matrixMap.put(View.DUMMY_REFERENCE, View.ID); idList.add(myID); while (isRunning.get()) { boolean myTurn; try { myTurn = myID == idList.get(idCount.get()); } catch (IndexOutOfBoundsException iob) { try { Thread.sleep(10); } catch (InterruptedException e) {} continue; } if (!myTurn) { try { Thread.sleep(10); } catch (InterruptedException e) {} continue; } try { static_lock.lock(); final long start = System.currentTimeMillis(); // First we have to get links to the sets from the model final DatFile df = c3d.getLockableDatFileReference(); // Just to speed up things in some cases... if (!df.isDrawSelection()) { continue; // static_lock.unlock(); on finally } final VertexManager vm = df.getVertexManager(); final Lock maniLock = vm.getManifestationLock(); // For the declared vertices, we have to use shallow copy maniLock.lock(); final List<Vertex> vertices = new ArrayList<>(vm.vertexLinkedToPositionInFile.size()); vertices.addAll(vm.vertexLinkedToPositionInFile.keySet()); maniLock.unlock(); if (calculateCondlineControlPoints.compareAndSet(true, false)) { CompletableFuture.runAsync( () -> { final TreeSet<Vertex> tmpPureCondlineControlPoints = new TreeSet<>(); for (Vertex v : vertices) { Set<VertexManifestation> manis = vm.vertexLinkedToPositionInFile.get(v); if (manis != null) { boolean pureControlPoint = true; maniLock.lock(); for (VertexManifestation m : manis) { if (m.getPosition() < 2 || m.getGdata().type() != 5) { pureControlPoint = false; break; } } maniLock.unlock(); if (pureControlPoint) { tmpPureCondlineControlPoints.add(v); } } } pureCondlineControlPoints = tmpPureCondlineControlPoints; calculateCondlineControlPoints.set(true); }); } // The links are sufficient final Set<GData> selectedData = vm.selectedData; final Set<Vertex> selectedVertices = vm.selectedVertices; final Set<Vertex> hiddenVertices = vm.hiddenVertices; final ThreadsafeHashMap<GData2, Vertex[]> lines = vm.lines; final ThreadsafeHashMap<GData3, Vertex[]> triangles = vm.triangles; final ThreadsafeHashMap<GData4, Vertex[]> quads = vm.quads; final ThreadsafeHashMap<GData5, Vertex[]> condlines = vm.condlines; // Build the list of the data from the datfile dataInOrder.clear(); vertexMap.clear(); normalMap.clear(); transformMap.clear(); selectionSet.clear(); CACHE_viewByProjection.clear(); { boolean[] special = loadBFCinfo(dataInOrder, vertexMap, matrixMap, df, lines, triangles, quads, condlines); usesPNG = special[0]; usesTEXMAP = special[1]; } final int renderMode = c3d.getRenderMode(); final int lineMode = c3d.getLineMode(); final boolean condlineMode = renderMode == 6; final boolean hideCondlines = !condlineMode && lineMode > 1; final boolean hideLines = !condlineMode && lineMode > 2; final float zoom = c3d.getZoom(); final Matrix4f viewport = c3d.getViewport(); int local_triangleSize = 0; int local_lineSize = 0; int local_condlineSize = 0; int local_tempLineSize = 0; int local_verticesSize = vertices.size(); int local_glyphSize = 0; int local_selectionLineSize = 0; int triangleVertexCount = 0; int lineVertexCount = 0; int condlineVertexCount = 0; int tempLineVertexCount = 0; int glyphVertexCount = 0; int selectionLineVertexCount = 0; // Only do "heavy" CPU condline computing with the special condline mode // (if the condline was not shown before) if (condlineMode) { dataInOrder.parallelStream().forEach((GDataAndWinding gw) -> { GData gd = gw.data; if (gd.type() == 5) { ((GData5) gd).isShown(viewport, CACHE_viewByProjection, zoom); } }); } // Calculate the buffer sizes // Lines are never transparent! for (GDataAndWinding gw : dataInOrder) { GData tgd = gw.data; if (!tgd.visible) { continue; } final boolean selected = selectedData.contains(tgd); // FIXME If anything is transformed, transform it here (transformMap) // and update the vertex positions (vertexMap) and normals for it (normalMap) final GData gd = tgd; if (selected) { selectionSet.add(gd); } switch (gd.type()) { case 2: if (hideLines) { continue; } final GData2 gd2 = (GData2) gd; if (gd2.isLine) { local_lineSize += 14; lineVertexCount += 2; } else { int[] distanceMeterSize = gd2.getDistanceMeterDataSize(); local_glyphSize += distanceMeterSize[0]; glyphVertexCount += distanceMeterSize[1]; local_tempLineSize += distanceMeterSize[2]; tempLineVertexCount += distanceMeterSize[3]; } continue; case 3: final GData3 gd3 = (GData3) gd; if (gd3.isTriangle) { switch (renderMode) { case 0: case 1: local_triangleSize += 60; triangleVertexCount += 6; continue; default: continue; } } else { int[] protractorSize = gd3.getProtractorDataSize(); local_glyphSize += protractorSize[0]; glyphVertexCount += protractorSize[1]; local_tempLineSize += protractorSize[2]; tempLineVertexCount += protractorSize[3]; } continue; case 4: switch (renderMode) { case 0: case 1: local_triangleSize += 120; triangleVertexCount += 12; continue; default: continue; } case 5: if (hideCondlines) { continue; } // Condlines are tricky, since I have to calculate their visibility local_condlineSize += 30; condlineVertexCount += 2; continue; default: continue; } } // for GL_TRIANGLES float[] triangleData = new float[local_triangleSize]; float[] glyphData = new float[local_glyphSize]; // for GL_LINES float[] lineData = new float[local_lineSize]; float[] condlineData = new float[local_condlineSize]; float[] tempLineData = new float[local_tempLineSize]; // for GL_POINTS float[] vertexData = new float[local_verticesSize * 7]; // Build the vertex array { final float r = View.vertex_Colour_r[0]; final float g = View.vertex_Colour_g[0]; final float b = View.vertex_Colour_b[0]; final float r2 = View.vertex_selected_Colour_r[0]; final float g2 = View.vertex_selected_Colour_g[0]; final float b2 = View.vertex_selected_Colour_b[0]; int i = 0; for(Vertex v : vertices) { vertexData[i] = v.x; vertexData[i + 1] = v.y; vertexData[i + 2] = v.z; if (selectedVertices.contains(v)) { vertexData[i + 3] = r2; vertexData[i + 4] = g2; vertexData[i + 5] = b2; vertexData[i + 6] = 7f; } else { vertexData[i + 3] = r; vertexData[i + 4] = g; vertexData[i + 5] = b; if (c3d.isShowingCondlineControlPoints()) { vertexData[i + 6] = hiddenVertices.contains(v) ? 0f : 7f; } else { vertexData[i + 6] = hiddenVertices.contains(v) || pureCondlineControlPoints.contains(v) ? 0f : 7f; } } i += 7; } } Vertex[] v; int triangleIndex = 0; int lineIndex = 0; int condlineIndex = 0; int tempLineIndex = 0; int glyphIndex = 0; // Iterate the objects and generate the buffer data // TEXMAP and Real Backface Culling are quite "the same", but they need different vertex normals / materials for (GDataAndWinding gw : dataInOrder) { final GData gd = transformMap.getOrDefault(gw.data, gw.data); if (!gd.visible) { continue; } final boolean transformed = gd != gw.data; switch (gd.type()) { case 2: if (hideLines) { continue; } GData2 gd2 = (GData2) gd; v = vertexMap.get(gd); if (gd2.isLine) { pointAt7(0, v[0].x, v[0].y, v[0].z, lineData, lineIndex); pointAt7(1, v[1].x, v[1].y, v[1].z, lineData, lineIndex); if (renderMode != 1) { colourise7(0, 2, gd2.r, gd2.g, gd2.b, 7f, lineData, lineIndex); } else { final float r = MathHelper.randomFloat(gd2.ID, 0); final float g = MathHelper.randomFloat(gd2.ID, 1); final float b = MathHelper.randomFloat(gd2.ID, 2); colourise7(0, 2, r, g, b, 7f, lineData, lineIndex); } lineIndex += 2; } else { int[] inc = gd2.insertDistanceMeter(v, glyphData, tempLineData, glyphIndex, tempLineIndex); tempLineIndex += inc[0]; glyphIndex += inc[1]; } continue; case 3: GData3 gd3 = (GData3) gd; v = vertexMap.get(gd); if (gd3.isTriangle) { float xn, yn, zn; if ((normal = normalMap.get(gd)) != null) { xn = normal[0]; yn = normal[1]; zn = normal[2]; } else { Nv.x = gd3.xn; Nv.y = gd3.yn; Nv.z = gd3.zn; Nv.w = 1f; Matrix4f loc = matrixMap.get(gd3.parent); Matrix4f.transform(loc, Nv, Nv); xn = Nv.x - loc.m30; yn = Nv.y - loc.m31; zn = Nv.z - loc.m32; } switch (renderMode) { case 0: { pointAt(0, v[0].x, v[0].y, v[0].z, triangleData, triangleIndex); pointAt(1, v[1].x, v[1].y, v[1].z, triangleData, triangleIndex); pointAt(2, v[2].x, v[2].y, v[2].z, triangleData, triangleIndex); pointAt(3, v[0].x, v[0].y, v[0].z, triangleData, triangleIndex); pointAt(4, v[2].x, v[2].y, v[2].z, triangleData, triangleIndex); pointAt(5, v[1].x, v[1].y, v[1].z, triangleData, triangleIndex); colourise(0, 6, gd3.r, gd3.g, gd3.b, gd3.visible ? gd3.a : 0f, triangleData, triangleIndex); if (gw.negativeDeterminant) { normal(0, 3, xn, yn, zn, triangleData, triangleIndex); normal(3, 3, -xn, -yn, -zn, triangleData, triangleIndex); } else { normal(0, 3, -xn, -yn, -zn, triangleData, triangleIndex); normal(3, 3, xn, yn, zn, triangleData, triangleIndex); } triangleIndex += 6; continue; } case 1: { final float r = MathHelper.randomFloat(gd3.ID, 0); final float g = MathHelper.randomFloat(gd3.ID, 1); final float b = MathHelper.randomFloat(gd3.ID, 2); pointAt(0, v[0].x, v[0].y, v[0].z, triangleData, triangleIndex); pointAt(1, v[1].x, v[1].y, v[1].z, triangleData, triangleIndex); pointAt(2, v[2].x, v[2].y, v[2].z, triangleData, triangleIndex); pointAt(3, v[0].x, v[0].y, v[0].z, triangleData, triangleIndex); pointAt(4, v[2].x, v[2].y, v[2].z, triangleData, triangleIndex); pointAt(5, v[1].x, v[1].y, v[1].z, triangleData, triangleIndex); colourise(0, 6, r, g, b, gd3.visible ? gd3.a : 0f, triangleData, triangleIndex); if (gw.negativeDeterminant) { normal(0, 3, xn, yn, zn, triangleData, triangleIndex); normal(3, 3, -xn, -yn, -zn, triangleData, triangleIndex); } else { normal(0, 3, -xn, -yn, -zn, triangleData, triangleIndex); normal(3, 3, xn, yn, zn, triangleData, triangleIndex); } triangleIndex += 6; continue; } default: continue; } } else { int[] inc = gd3.insertProtractor(v, glyphData, tempLineData, glyphIndex, tempLineIndex); triangleIndex += inc[0]; tempLineIndex += inc[1]; } continue; case 4: float xn, yn, zn; v = vertexMap.get(gd); GData4 gd4 = (GData4) gd; if ((normal = normalMap.get(gd)) != null) { xn = normal[0]; yn = normal[1]; zn = normal[2]; } else { Nv.x = gd4.xn; Nv.y = gd4.yn; Nv.z = gd4.zn; Nv.w = 1f; Matrix4f loc = matrixMap.get(gd4.parent); Matrix4f.transform(loc, Nv, Nv); Nv.x = Nv.x - loc.m30; Nv.y = Nv.y - loc.m31; Nv.z = Nv.z - loc.m32; xn = Nv.x; yn = Nv.y; zn = Nv.z; } switch (renderMode) { case 0: { pointAt(0, v[0].x, v[0].y, v[0].z, triangleData, triangleIndex); pointAt(1, v[1].x, v[1].y, v[1].z, triangleData, triangleIndex); pointAt(2, v[2].x, v[2].y, v[2].z, triangleData, triangleIndex); pointAt(3, v[2].x, v[2].y, v[2].z, triangleData, triangleIndex); pointAt(4, v[3].x, v[3].y, v[3].z, triangleData, triangleIndex); pointAt(5, v[0].x, v[0].y, v[0].z, triangleData, triangleIndex); pointAt(6, v[0].x, v[0].y, v[0].z, triangleData, triangleIndex); pointAt(7, v[3].x, v[3].y, v[3].z, triangleData, triangleIndex); pointAt(8, v[2].x, v[2].y, v[2].z, triangleData, triangleIndex); pointAt(9, v[2].x, v[2].y, v[2].z, triangleData, triangleIndex); pointAt(10, v[1].x, v[1].y, v[1].z, triangleData, triangleIndex); pointAt(11, v[0].x, v[0].y, v[0].z, triangleData, triangleIndex); colourise(0, 12, gd4.r, gd4.g, gd4.b, gd4.visible ? gd4.a : 0f, triangleData, triangleIndex); if (gw.negativeDeterminant) { normal(0, 6, xn, yn, zn, triangleData, triangleIndex); normal(6, 6, -xn, -yn, -zn, triangleData, triangleIndex); } else { normal(0, 6, -xn, -yn, -zn, triangleData, triangleIndex); normal(6, 6, xn, yn, zn, triangleData, triangleIndex); } triangleIndex += 12; continue; } case 1: { final float r = MathHelper.randomFloat(gd4.ID, 0); final float g = MathHelper.randomFloat(gd4.ID, 1); final float b = MathHelper.randomFloat(gd4.ID, 2); pointAt(0, v[0].x, v[0].y, v[0].z, triangleData, triangleIndex); pointAt(1, v[1].x, v[1].y, v[1].z, triangleData, triangleIndex); pointAt(2, v[2].x, v[2].y, v[2].z, triangleData, triangleIndex); pointAt(3, v[2].x, v[2].y, v[2].z, triangleData, triangleIndex); pointAt(4, v[3].x, v[3].y, v[3].z, triangleData, triangleIndex); pointAt(5, v[0].x, v[0].y, v[0].z, triangleData, triangleIndex); pointAt(6, v[0].x, v[0].y, v[0].z, triangleData, triangleIndex); pointAt(7, v[3].x, v[3].y, v[3].z, triangleData, triangleIndex); pointAt(8, v[2].x, v[2].y, v[2].z, triangleData, triangleIndex); pointAt(9, v[2].x, v[2].y, v[2].z, triangleData, triangleIndex); pointAt(10, v[1].x, v[1].y, v[1].z, triangleData, triangleIndex); pointAt(11, v[0].x, v[0].y, v[0].z, triangleData, triangleIndex); colourise(0, 12, r, g, b, gd4.visible ? gd4.a : 0f, triangleData, triangleIndex); if (gw.negativeDeterminant) { normal(0, 6, xn, yn, zn, triangleData, triangleIndex); normal(6, 6, -xn, -yn, -zn, triangleData, triangleIndex); } else { normal(0, 6, -xn, -yn, -zn, triangleData, triangleIndex); normal(6, 6, xn, yn, zn, triangleData, triangleIndex); } triangleIndex += 12; continue; } default: continue; } case 5: if (hideCondlines) { continue; } GData5 gd5 = (GData5) gd; v = vertexMap.get(gd); pointAt15(0, v[0].x, v[0].y, v[0].z, condlineData, condlineIndex); pointAt15(1, v[1].x, v[1].y, v[1].z, condlineData, condlineIndex); controlPointAt15(0, 0, v[1].x, v[1].y, v[1].z, condlineData, condlineIndex); controlPointAt15(0, 1, v[2].x, v[2].y, v[2].z, condlineData, condlineIndex); controlPointAt15(0, 2, v[3].x, v[3].y, v[3].z, condlineData, condlineIndex); controlPointAt15(1, 0, v[0].x, v[0].y, v[0].z, condlineData, condlineIndex); controlPointAt15(1, 1, v[2].x, v[2].y, v[2].z, condlineData, condlineIndex); controlPointAt15(1, 2, v[3].x, v[3].y, v[3].z, condlineData, condlineIndex); if (condlineMode) { if (gd5.wasShown()) { colourise15(0, 2, View.condline_shown_Colour_r[0], View.condline_shown_Colour_g[0], View.condline_shown_Colour_b[0], condlineData, condlineIndex); } else { colourise15(0, 2, View.condline_hidden_Colour_r[0], View.condline_hidden_Colour_g[0], View.condline_hidden_Colour_b[0], condlineData, condlineIndex); } } else { if (renderMode != 1) { colourise15(0, 2, gd5.r, gd5.g, gd5.b, condlineData, condlineIndex); } else { final float r = MathHelper.randomFloat(gd5.ID, 0); final float g = MathHelper.randomFloat(gd5.ID, 1); final float b = MathHelper.randomFloat(gd5.ID, 2); colourise15(0, 2, r, g, b, condlineData, condlineIndex); } } condlineIndex += 2; continue; default: continue; } } lock.lock(); dataTriangles = triangleData; solidTriangleSize = triangleVertexCount; transparentTriangleSize = 0; transparentTriangleOffset = 0; vertexSize = local_verticesSize; dataVertices = vertexData; lineSize = lineVertexCount; dataLines = lineData; condlineSize = condlineVertexCount; dataCondlines = condlineData; tempLineSize = tempLineVertexCount; dataTempLines = tempLineData; selectionSize = 0; lock.unlock(); if (NLogger.DEBUG) { System.out.println("Processing time: " + (System.currentTimeMillis() - start)); //$NON-NLS-1$ } } catch (Exception ex) { if (NLogger.DEBUG) { System.out.println("Exception: " + ex.getMessage()); //$NON-NLS-1$ } } finally { static_lock.unlock(); } if (idCount.incrementAndGet() >= idList.size()) { idCount.set(0); } } idCount.set(0); idList.remove(myID); idCount.set(0); } }).start(); } public void dispose() { isRunning.set(false); GL30.glDeleteVertexArrays(vao); GL15.glDeleteBuffers(vbo); GL30.glDeleteVertexArrays(vaoVertices); GL15.glDeleteBuffers(vboVertices); GL30.glDeleteVertexArrays(vaoLines); GL15.glDeleteBuffers(vboLines); GL30.glDeleteVertexArrays(vaoTempLines); GL15.glDeleteBuffers(vboTempLines); GL30.glDeleteVertexArrays(vaoGlyphs); GL15.glDeleteBuffers(vboGlyphs); GL30.glDeleteVertexArrays(vaoSelectionLines); GL15.glDeleteBuffers(vboSelectionLines); GL30.glDeleteVertexArrays(vaoCondlines); GL15.glDeleteBuffers(vboCondlines); } private int ts, ss, to, vs, ls, tls, gs, sls, cls; public void draw(GLMatrixStack stack, GLShader mainShader, GLShader condlineShader, boolean drawSolidMaterials, DatFile df) { Matrix4f vm = c3d.getViewport(); Matrix4f ivm = c3d.getViewport_Inverse(); if (dataTriangles == null || dataLines == null || dataVertices == null) { return; } final float zoom = c3d.getZoom(); // TODO Draw !LPE PNG VAOs here if (usesPNG) { } // TODO Draw !TEXMAP VAOs here if (usesTEXMAP) { } if (drawSolidMaterials) { GL30.glBindVertexArray(vaoGlyphs); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboGlyphs); lock.lock(); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, dataGlyphs, GL15.GL_STATIC_DRAW); gs = glyphSize; lock.unlock(); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, 0); GL20.glEnableVertexAttribArray(1); GL20.glVertexAttribPointer(1, 3, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, 3 * 4); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, (3 + 3) * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL30.glBindVertexArray(vao); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); lock.lock(); // I can't use glBufferSubData() it creates a memory leak!!! GL15.glBufferData(GL15.GL_ARRAY_BUFFER, dataTriangles, GL15.GL_STATIC_DRAW); ss = solidTriangleSize; to = transparentTriangleOffset; ts = transparentTriangleSize; ls = lineSize; tls = tempLineSize; sls = selectionSize; lock.unlock(); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, 0); GL20.glEnableVertexAttribArray(1); GL20.glVertexAttribPointer(1, 3, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, 3 * 4); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, (3 + 3) * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); } GL30.glBindVertexArray(vao); if (c3d.isLightOn()) { mainShader.setFactor(.9f); } else { mainShader.setFactor(1f); } // Transparent and solid parts are at a different location in the buffer if (drawSolidMaterials) { GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, ss); if (ls > 0) { GL30.glBindVertexArray(vaoLines); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboLines); lock.lock(); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, dataLines, GL15.GL_STATIC_DRAW); ls = lineSize; lock.unlock(); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, (3 + 4) * 4, 0); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, (3 + 4) * 4, 3 * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL11.glLineWidth(View.lineWidthGL[0]); Vector4f tr = new Vector4f(vm.m30, vm.m31, vm.m32 + 330f * zoom, 1f); Matrix4f.transform(ivm, tr, tr); stack.glPushMatrix(); stack.glTranslatef(tr.x, tr.y, tr.z); GL11.glDrawArrays(GL11.GL_LINES, 0, ls); stack.glPopMatrix(); } if (tls > 0) { GL30.glBindVertexArray(vaoTempLines); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboTempLines); lock.lock(); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, dataTempLines, GL15.GL_STATIC_DRAW); tls = tempLineSize; lock.unlock(); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, (3 + 4) * 4, 0); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, (3 + 4) * 4, 3 * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL11.glLineWidth(View.lineWidthGL[0]); Vector4f tr = new Vector4f(vm.m30, vm.m31, vm.m32 + 330f * zoom, 1f); Matrix4f.transform(ivm, tr, tr); stack.glPushMatrix(); stack.glTranslatef(tr.x, tr.y, tr.z); GL11.glDrawArrays(GL11.GL_LINES, 0, tls); stack.glPopMatrix(); } mainShader.setFactor(1f); } else { GL11.glDrawArrays(GL11.GL_TRIANGLES, to, ts); mainShader.setFactor(1f); if (c3d.isShowingVertices()) { GL30.glBindVertexArray(vaoVertices); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboVertices); lock.lock(); // I can't use glBufferSubData() it creates a memory leak!!! GL15.glBufferData(GL15.GL_ARRAY_BUFFER, dataVertices, GL15.GL_STATIC_DRAW); vs = vertexSize; lock.unlock(); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, (3 + 4) * 4, 0); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, (3 + 4) * 4, 3 * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); if (c3d.isShowingHiddenVertices()) { mainShader.setFactor(.5f); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDrawArrays(GL11.GL_POINTS, 0, vs); GL11.glEnable(GL11.GL_DEPTH_TEST); mainShader.setFactor(1f); } Vector4f tr = new Vector4f(vm.m30, vm.m31, vm.m32 + 330f * zoom, 1f); Matrix4f.transform(ivm, tr, tr); stack.glPushMatrix(); stack.glTranslatef(tr.x, tr.y, tr.z); GL11.glDrawArrays(GL11.GL_POINTS, 0, vs); stack.glPopMatrix(); } } // Draw condlines here if (drawSolidMaterials) { condlineShader.use(); stack.setShader(condlineShader); GL20.glUniform1f(condlineShader.getUniformLocation("showAll"), c3d.getLineMode() == 1 ? 1f : 0f); //$NON-NLS-1$ GL20.glUniform1f(condlineShader.getUniformLocation("condlineMode"), c3d.getRenderMode() == 6 ? 1f : 0f); //$NON-NLS-1$ GL30.glBindVertexArray(vaoCondlines); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboCondlines); lock.lock(); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, dataCondlines, GL15.GL_STATIC_DRAW); cls = condlineSize; lock.unlock(); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 15 * 4, 0); GL20.glEnableVertexAttribArray(1); GL20.glVertexAttribPointer(1, 3, GL11.GL_FLOAT, false, 15 * 4, 3 * 4); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 3, GL11.GL_FLOAT, false, 15 * 4, 6 * 4); GL20.glEnableVertexAttribArray(3); GL20.glVertexAttribPointer(3, 3, GL11.GL_FLOAT, false, 15 * 4, 9 * 4); GL20.glEnableVertexAttribArray(4); GL20.glVertexAttribPointer(4, 3, GL11.GL_FLOAT, false, 15 * 4, 12 * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); Vector4f tr = new Vector4f(vm.m30, vm.m31, vm.m32 + 330f * zoom, 1f); Matrix4f.transform(ivm, tr, tr); stack.glPushMatrix(); stack.glTranslatef(tr.x, tr.y, tr.z); GL11.glLineWidth(View.lineWidthGL[0]); GL11.glDrawArrays(GL11.GL_LINES, 0, cls); stack.glPopMatrix(); mainShader.use(); stack.setShader(mainShader); } else { GL11.glDisable(GL11.GL_DEPTH_TEST); // Draw lines from the selection if (sls > 0) { GL30.glBindVertexArray(vaoSelectionLines); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboSelectionLines); lock.lock(); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, dataSelectionLines, GL15.GL_STATIC_DRAW); sls = selectionSize; lock.unlock(); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, (3 + 4) * 4, 0); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, (3 + 4) * 4, 3 * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL11.glDrawArrays(GL11.GL_LINES, 0, sls); } // TODO Draw glyphs here if (gs > 0) { GL30.glBindVertexArray(vaoGlyphs); stack.glPushMatrix(); GL11.glDisable(GL11.GL_CULL_FACE); stack.glMultMatrixf(renderer.getRotationInverse()); GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, gs); GL11.glEnable(GL11.GL_CULL_FACE); stack.glPopMatrix(); } GL11.glEnable(GL11.GL_DEPTH_TEST); } GL30.glBindVertexArray(0); } private boolean[] loadBFCinfo( final ArrayList<GDataAndWinding> dataInOrder, final HashMap<GData, Vertex[]> vertexMap, final HashMap<GData1, Matrix4f> matrixMap, final DatFile df, final ThreadsafeHashMap<GData2, Vertex[]> lines, final ThreadsafeHashMap<GData3, Vertex[]> triangles, final ThreadsafeHashMap<GData4, Vertex[]> quads, final ThreadsafeHashMap<GData5, Vertex[]> condlines) { final boolean[] result = new boolean[2]; boolean hasTEXMAP = false; boolean hasPNG = false; Stack<GData> stack = new Stack<>(); Stack<Byte> tempWinding = new Stack<>(); Stack<Boolean> tempInvertNext = new Stack<>(); Stack<Boolean> tempInvertNextFound = new Stack<>(); Stack<Boolean> tempNegativeDeterminant = new Stack<>(); boolean isCertified = true; GData gd = df.getDrawChainStart(); byte localWinding = BFC.NOCERTIFY; int accumClip = 0; boolean globalInvertNext = false; boolean globalInvertNextFound = false; boolean globalNegativeDeterminant = false; // The BFC logic/state machine is not correct yet? (for BFC no-certify). while ((gd = gd.next) != null || !stack.isEmpty()) { if (gd == null) { if (accumClip > 0) { accumClip } gd = stack.pop(); localWinding = tempWinding.pop(); isCertified = localWinding != BFC.NOCERTIFY; globalInvertNext = tempInvertNext.pop(); globalInvertNextFound = tempInvertNextFound.pop(); globalNegativeDeterminant = tempNegativeDeterminant.pop(); continue; } Vertex[] verts = null; switch (gd.type()) { case 1: final GData1 gd1 = ((GData1) gd); matrixMap.put(gd1, gd1.productMatrix); stack.push(gd); isCertified = localWinding != BFC.NOCERTIFY; tempWinding.push(localWinding); tempInvertNext.push(globalInvertNext); tempInvertNextFound.push(globalInvertNextFound); tempNegativeDeterminant.push(globalNegativeDeterminant); if (accumClip > 0) { accumClip++; } globalInvertNextFound = false; localWinding = BFC.NOCERTIFY; globalNegativeDeterminant = globalNegativeDeterminant ^ gd1.negativeDeterminant; gd = gd1.myGData; continue; case 6: if (!isCertified) { continue; } if (accumClip > 0) { switch (((GDataBFC) gd).type) { case BFC.CCW_CLIP: if (accumClip == 1) accumClip = 0; localWinding = BFC.CCW; continue; case BFC.CLIP: if (accumClip == 1) accumClip = 0; continue; case BFC.CW_CLIP: if (accumClip == 1) accumClip = 0; localWinding = BFC.CW; continue; default: continue; } } else { switch (((GDataBFC) gd).type) { case BFC.CCW: localWinding = BFC.CCW; continue; case BFC.CCW_CLIP: localWinding = BFC.CCW; continue; case BFC.CW: localWinding = BFC.CW; continue; case BFC.CW_CLIP: localWinding = BFC.CW; continue; case BFC.INVERTNEXT: boolean validState = false; GData g = gd.next; while (g != null && g.type() < 2) { if (g.type() == 1) { if (g.visible) validState = true; break; } else if (!g.toString().trim().isEmpty()) { break; } g = g.next; } if (validState) { globalInvertNext = !globalInvertNext; globalInvertNextFound = true; } continue; case BFC.NOCERTIFY: localWinding = BFC.NOCERTIFY; continue; case BFC.NOCLIP: if (accumClip == 0) accumClip = 1; continue; default: continue; } } case 2: verts = lines.get(gd); if (verts != null) { vertexMap.put(gd, verts); dataInOrder.add(new GDataAndWinding(gd, localWinding, globalNegativeDeterminant, globalInvertNext)); } continue; case 3: verts = triangles.get(gd); if (verts != null) { vertexMap.put(gd, verts); dataInOrder.add(new GDataAndWinding(gd, localWinding, globalNegativeDeterminant, globalInvertNext)); } continue; case 4: verts = quads.get(gd); if (verts != null) { vertexMap.put(gd, verts); dataInOrder.add(new GDataAndWinding(gd, localWinding, globalNegativeDeterminant, globalInvertNext)); } continue; case 5: verts = condlines.get(gd); if (verts != null) { vertexMap.put(gd, verts); dataInOrder.add(new GDataAndWinding(gd, localWinding, globalNegativeDeterminant, globalInvertNext)); } continue; case 9: hasTEXMAP = true; continue; case 10: hasPNG = true; continue; default: continue; } } result[0] = hasPNG; result[1] = hasTEXMAP; return result; } private void normal(int offset, int times, float xn, float yn, float zn, float[] vertexData, int i) { for (int j = 0; j < times; j++) { int pos = (offset + i + j) * 10; vertexData[pos + 3] = xn; vertexData[pos + 4] = yn; vertexData[pos + 5] = zn; } } private void colourise(int offset, int times, float r, float g, float b, float a, float[] vertexData, int i) { for (int j = 0; j < times; j++) { int pos = (offset + i + j) * 10; vertexData[pos + 6] = r; vertexData[pos + 7] = g; vertexData[pos + 8] = b; vertexData[pos + 9] = a; } } private void colourise7(int offset, int times, float r, float g, float b, float a, float[] vertexData, int i) { for (int j = 0; j < times; j++) { int pos = (offset + i + j) * 7; vertexData[pos + 3] = r; vertexData[pos + 4] = g; vertexData[pos + 5] = b; vertexData[pos + 6] = a; } } private void colourise15(int offset, int times, float r, float g, float b, float[] vertexData, int i) { for (int j = 0; j < times; j++) { int pos = (offset + i + j) * 15; vertexData[pos + 12] = r; vertexData[pos + 13] = g; vertexData[pos + 14] = b; } } private void pointAt(int offset, float x, float y, float z, float[] vertexData, int i) { int pos = (offset + i) * 10; vertexData[pos] = x; vertexData[pos + 1] = y; vertexData[pos + 2] = z; } private void pointAt7(int offset, float x, float y, float z, float[] vertexData, int i) { int pos = (offset + i) * 7; vertexData[pos] = x; vertexData[pos + 1] = y; vertexData[pos + 2] = z; } private void pointAt15(int offset, float x, float y, float z, float[] vertexData, int i) { int pos = (offset + i) * 15; vertexData[pos] = x; vertexData[pos + 1] = y; vertexData[pos + 2] = z; } private void controlPointAt15(int offset, int offset2, float x, float y, float z, float[] vertexData, int i) { int pos = (offset + i) * 15 + 3 * offset2; vertexData[pos + 3] = x; vertexData[pos + 4] = y; vertexData[pos + 5] = z; } class GDataAndWinding { final GData data; final byte winding; final boolean negativeDeterminant; final boolean invertNext; public GDataAndWinding(GData gd, byte bfc, boolean negDet, boolean iNext) { data = gd; winding = bfc; negativeDeterminant = negDet; invertNext = iNext; } } }
package org.owasp.esapi.reference; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.owasp.esapi.ESAPI; import org.owasp.esapi.HTTPUtilities; import org.owasp.esapi.Logger; import org.owasp.esapi.Randomizer; import org.owasp.esapi.User; import org.owasp.esapi.errors.AccessControlException; import org.owasp.esapi.errors.AuthenticationAccountsException; import org.owasp.esapi.errors.AuthenticationCredentialsException; import org.owasp.esapi.errors.AuthenticationException; import org.owasp.esapi.errors.AuthenticationLoginException; import org.owasp.esapi.errors.EncryptionException; public class FileBasedAuthenticator implements org.owasp.esapi.Authenticator { /** Key for user in session */ protected static final String USER = "ESAPIUserSessionKey"; /** The logger. */ private final Logger logger = ESAPI.getLogger("Authenticator"); /** The file that contains the user db */ private File userDB = null; /** How frequently to check the user db for external modifications */ private long checkInterval = 60 * 1000; /** The last modified time we saw on the user db. */ private long lastModified = 0; /** The last time we checked if the user db had been modified externally */ private long lastChecked = 0; private final int MAX_ACCOUNT_NAME_LENGTH = 250; /** * Fail safe main program to add or update an account in an emergency. * <P> * Warning: this method does not perform the level of validation and checks * generally required in ESAPI, and can therefore be used to create a username and password that do not comply * with the username and password strength requirements. * <P> * Example: Use this to add the alice account with the admin role to the users file: * <PRE> * * java -Dorg.owasp.esapi.resources="/path/resources" -classpath esapi.jar org.owasp.esapi.Authenticator alice password admin * * </PRE> * * @param args * the arguments (username, password, role) * @throws Exception * the exception */ public static void main(String[] args) throws Exception { if (args.length != 3) { System.out.println("Usage: Authenticator accountname password role"); return; } FileBasedAuthenticator auth = new FileBasedAuthenticator(); String accountName = args[0].toLowerCase(); String password = args[1]; String role = args[2]; DefaultUser user = (DefaultUser) auth.getUser(args[0]); if (user == null) { user = new DefaultUser(accountName); String newHash = auth.hashPassword(password, accountName); auth.setHashedPassword(user, newHash); user.addRole(role); user.enable(); user.unlock(); auth.userMap.put(new Long(user.getAccountId()), user); System.out.println("New user created: " + accountName); auth.saveUsers(); System.out.println("User account " + user.getAccountName() + " updated"); } else { System.err.println("User account " + user.getAccountName() + " already exists!"); } } /** * Add a hash to a User's hashed password list. This method is used to store a user's old password hashes * to be sure that any new passwords are not too similar to old passwords. * * @param user * the user to associate with the new hash * @param hash * the hash to store in the user's password hash list */ private void setHashedPassword(User user, String hash) { List hashes = getAllHashedPasswords(user, true); hashes.add( 0, hash); if (hashes.size() > ESAPI.securityConfiguration().getMaxOldPasswordHashes() ) hashes.remove( hashes.size() - 1 ); logger.info(Logger.SECURITY, true, "New hashed password stored for " + user.getAccountName() ); } /** * Return the specified User's current hashed password. * * @param user * this User's current hashed password will be returned * @return * the specified User's current hashed password */ String getHashedPassword(User user) { List hashes = getAllHashedPasswords(user, false); return (String) hashes.get(0); } /** * Set the specified User's old password hashes. This will not set the User's current password hash. * * @param user * the User's whose old password hashes will be set * @param oldHashes * a list of the User's old password hashes * */ void setOldPasswordHashes(User user, List oldHashes) { List hashes = getAllHashedPasswords(user, true); if (hashes.size() > 1) hashes.removeAll(hashes.subList(1, hashes.size()-1)); hashes.addAll(oldHashes); } /** * Returns all of the specified User's hashed passwords. If the User's list of passwords is null, * and create is set to true, an empty password list will be associated with the specified User * and then returned. If the User's password map is null and create is set to false, an exception * will be thrown. * * @param user * the User whose old hashes should be returned * @param create * true - if no password list is associated with this user, create one * false - if no password list is associated with this user, do not create one * @return * a List containing all of the specified User's password hashes */ List getAllHashedPasswords(User user, boolean create) { List hashes = (List) passwordMap.get(user); if (hashes != null) return hashes; if (create) { hashes = new ArrayList(); passwordMap.put(user, hashes); return hashes; } throw new RuntimeException("No hashes found for " + user.getAccountName() + ". Is User.hashcode() and equals() implemented correctly?"); } /** * Get a List of the specified User's old password hashes. This will not return the User's current * password hash. * * @param user * he user whose old password hashes should be returned * @return * the specified User's old password hashes */ List getOldPasswordHashes(User user) { List hashes = getAllHashedPasswords(user, false); if (hashes.size() > 1) return Collections.unmodifiableList(hashes.subList(1, hashes.size()-1)); return Collections.EMPTY_LIST; } /** The user map. */ private Map userMap = new HashMap(); // Map<User, List<String>>, where the strings are password hashes, with the current hash in entry 0 private Map passwordMap = new Hashtable(); /** * The currentUser ThreadLocal variable is used to make the currentUser available to any call in any part of an * application. Otherwise, each thread would have to pass the User object through the calltree to any methods that * need it. Because we want exceptions and log calls to contain user data, that could be almost anywhere. Therefore, * the ThreadLocal approach simplifies things greatly. <P> As a possible extension, one could create a delegation * framework by adding another ThreadLocal to hold the delegating user identity. */ private ThreadLocalUser currentUser = new ThreadLocalUser(); private class ThreadLocalUser extends InheritableThreadLocal { public Object initialValue() { return User.ANONYMOUS; } public User getUser() { return (User)super.get(); } public void setUser(User newUser) { super.set(newUser); } }; public FileBasedAuthenticator() { } /** * {@inheritDoc} */ public void clearCurrent() { currentUser.setUser(null); } /** * {@inheritDoc} */ public synchronized User createUser(String accountName, String password1, String password2) throws AuthenticationException { loadUsersIfNecessary(); if (accountName == null) { throw new AuthenticationAccountsException("Account creation failed", "Attempt to create user with null accountName"); } if (getUser(accountName) != null) { throw new AuthenticationAccountsException("Account creation failed", "Duplicate user creation denied for " + accountName); } verifyAccountNameStrength(accountName); if ( password1 == null ) { throw new AuthenticationCredentialsException( "Invalid account name", "Attempt to create account " + accountName + " with a null password" ); } verifyPasswordStrength(null, password1); if (!password1.equals(password2)) throw new AuthenticationCredentialsException("Passwords do not match", "Passwords for " + accountName + " do not match"); DefaultUser user = new DefaultUser(accountName); try { setHashedPassword( user, hashPassword(password1, accountName) ); } catch (EncryptionException ee) { throw new AuthenticationException("Internal error", "Error hashing password for " + accountName, ee); } userMap.put(new Long( user.getAccountId() ), user); logger.info(Logger.SECURITY, true, "New user created: " + accountName); saveUsers(); return user; } /** * {@inheritDoc} */ public boolean exists(String accountName) { return getUser(accountName) != null; } /** * {@inheritDoc} */ public String generateStrongPassword() { return generateStrongPassword(""); } /** * Generate a strong password that is not similar to the specified old password. * * @param oldPassword * the password to be compared to the new password for similarity * @return * a new strong password that is dissimilar to the specified old password */ private String generateStrongPassword(String oldPassword) { Randomizer r = ESAPI.randomizer(); int letters = r.getRandomInteger(4, 6); // inclusive, exclusive int digits = 7-letters; String passLetters = r.getRandomString(letters, DefaultEncoder.CHAR_PASSWORD_LETTERS ); String passDigits = r.getRandomString( digits, DefaultEncoder.CHAR_PASSWORD_DIGITS ); String passSpecial = r.getRandomString( 1, DefaultEncoder.CHAR_PASSWORD_SPECIALS ); String newPassword = passLetters + passSpecial + passDigits; return newPassword; } /** * {@inheritDoc} */ public void changePassword(User user, String currentPassword, String newPassword, String newPassword2) throws AuthenticationException { String accountName = user.getAccountName(); try { String currentHash = getHashedPassword(user); String verifyHash = hashPassword(currentPassword, accountName); if (!currentHash.equals(verifyHash)) { throw new AuthenticationCredentialsException("Password change failed", "Authentication failed for password change on user: " + accountName ); } if (newPassword == null || newPassword2 == null || !newPassword.equals(newPassword2)) { throw new AuthenticationCredentialsException("Password change failed", "Passwords do not match for password change on user: " + accountName ); } verifyPasswordStrength(currentPassword, newPassword); ((DefaultUser)user).setLastPasswordChangeTime(new Date()); String newHash = hashPassword(newPassword, accountName); if (getOldPasswordHashes(user).contains(newHash)) { throw new AuthenticationCredentialsException( "Password change failed", "Password change matches a recent password for user: " + accountName ); } setHashedPassword(user, newHash); logger.info(Logger.SECURITY, true, "Password changed for user: " + accountName ); } catch (EncryptionException ee) { throw new AuthenticationException("Password change failed", "Encryption exception changing password for " + accountName, ee); } } /** * {@inheritDoc} */ public boolean verifyPassword(User user, String password) { String accountName = user.getAccountName(); try { String hash = hashPassword(password, accountName); String currentHash = getHashedPassword(user); if (hash.equals(currentHash)) { ((DefaultUser)user).setLastLoginTime(new Date()); ((DefaultUser)user).setFailedLoginCount(0); logger.info(Logger.SECURITY, true, "Password verified for " + accountName ); return true; } } catch( EncryptionException e ) { logger.fatal(Logger.SECURITY, false, "Encryption error verifying password for " + accountName ); } logger.fatal(Logger.SECURITY, false, "Password verification failed for " + accountName ); return false; } /** * {@inheritDoc} */ public String generateStrongPassword(User user, String oldPassword) { String newPassword = generateStrongPassword(oldPassword); if (newPassword != null) logger.info(Logger.SECURITY, true, "Generated strong password for " + user.getAccountName()); return newPassword; } /** * {@inheritDoc} * * Returns the currently logged user as set by the setCurrentUser() methods. Must not log in this method because the * logger calls getCurrentUser() and this could cause a loop. * * */ public User getCurrentUser() { User user = (User) currentUser.get(); if (user == null) { user = User.ANONYMOUS; } return user; } /** * {@inheritDoc} */ public synchronized User getUser(long accountId) { if ( accountId == 0 ) { return User.ANONYMOUS; } loadUsersIfNecessary(); User user = (User) userMap.get(new Long( accountId )); return user; } /** * {@inheritDoc} */ public synchronized User getUser(String accountName) { if ( accountName == null ) { return User.ANONYMOUS; } loadUsersIfNecessary(); Iterator i = userMap.values().iterator(); while( i.hasNext() ) { User u = (User)i.next(); if ( u.getAccountName().equalsIgnoreCase(accountName) ) return u; } return null; } /** * Gets the user from session. * * @return * the user from session or null if no user is found in the session */ protected User getUserFromSession() { HttpSession session = ESAPI.httpUtilities().getCurrentRequest().getSession(false); if ( session == null ) return null; return (User)session.getAttribute(USER); } /** * Returns the user if a matching remember token is found, or null if the token * is missing, token is corrupt, token is expired, account name does not match * and existing account, or hashed password does not match user's hashed password. * * @return * the user if a matching remember token is found, or null if the token * is missing, token is corrupt, token is expired, account name does not match * and existing account, or hashed password does not match user's hashed password. */ protected DefaultUser getUserFromRememberToken() { Cookie token = ESAPI.httpUtilities().getCookie( ESAPI.currentRequest(), HTTPUtilities.REMEMBER_TOKEN_COOKIE_NAME ); if ( token == null ) { return null; } String[] data = null; try { data = ESAPI.encryptor().unseal( token.getValue() ).split( ":" ); } catch (EncryptionException e) { logger.warning(Logger.SECURITY, false, "Found corrupt or expired remember token" ); ESAPI.httpUtilities().killCookie( ESAPI.currentRequest(), ESAPI.currentResponse(), HTTPUtilities.REMEMBER_TOKEN_COOKIE_NAME ); return null; } if ( data.length != 3 ) { return null; } // data[0] is a random nonce, which can be ignored String username = data[1]; String password = data[2]; DefaultUser user = (DefaultUser) getUser( username ); if ( user == null ) { logger.warning( Logger.SECURITY, false, "Found valid remember token but no user matching " + username ); return null; } logger.warning( Logger.SECURITY, true, "Logging in user with remember token: " + user.getAccountName() ); try { user.loginWithPassword(password); } catch (AuthenticationException ae) { logger.warning( Logger.SECURITY, false, "Login via remember me cookie failed for user " + username, ae); ESAPI.httpUtilities().killCookie( ESAPI.currentRequest(), ESAPI.currentResponse(), HTTPUtilities.REMEMBER_TOKEN_COOKIE_NAME ); return null; } return user; } /** * {@inheritDoc} */ public synchronized Set getUserNames() { loadUsersIfNecessary(); HashSet results = new HashSet(); Iterator i = userMap.values().iterator(); while( i.hasNext() ) { User u = (User)i.next(); results.add( u.getAccountName() ); } return results; } /** * {@inheritDoc} */ public String hashPassword(String password, String accountName) throws EncryptionException { String salt = accountName.toLowerCase(); return ESAPI.encryptor().hash(password, salt); } /** * Load users if they haven't been loaded in a while. */ protected void loadUsersIfNecessary() { if (userDB == null) { userDB = new File((ESAPI.securityConfiguration()).getResourceDirectory(), "users.txt"); } // We only check at most every checkInterval milliseconds long now = System.currentTimeMillis(); if (now - lastChecked < checkInterval) { return; } lastChecked = now; if (lastModified == userDB.lastModified()) { return; } loadUsersImmediately(); } // file was touched so reload it protected void loadUsersImmediately() { synchronized( this ) { logger.trace(Logger.SECURITY, true, "Loading users from " + userDB.getAbsolutePath(), null); BufferedReader reader = null; try { HashMap map = new HashMap(); reader = new BufferedReader(new FileReader(userDB)); String line = null; while ((line = reader.readLine()) != null) { if (line.length() > 0 && line.charAt(0) != ' DefaultUser user = createUser(line); if (map.containsKey( new Long( user.getAccountId()))) { logger.fatal(Logger.SECURITY, false, "Problem in user file. Skipping duplicate user: " + user, null); } map.put( new Long( user.getAccountId() ), user); } } userMap = map; this.lastModified = System.currentTimeMillis(); logger.trace(Logger.SECURITY, true, "User file reloaded: " + map.size(), null); } catch (Exception e) { logger.fatal(Logger.SECURITY, false, "Failure loading user file: " + userDB.getAbsolutePath(), e); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { logger.fatal(Logger.SECURITY, false, "Failure closing user file: " + userDB.getAbsolutePath(), e); } } } } /** * Create a new user with all attributes from a String. The format is: * accountId | accountName | password | roles (comma separated) | unlocked | enabled | old password hashes (comma separated) | last host address | last password change time | last long time | last failed login time | expiration time | failed login count * This method verifies the account name and password strength, creates a new CSRF token, then returns the newly created user. * * @param line * parameters to set as attributes for the new User. * @return * the newly created User * * @throws AuthenticationException */ private DefaultUser createUser(String line) throws AuthenticationException { String[] parts = line.split(" *\\| *"); String accountIdString = parts[0]; long accountId = Long.parseLong(accountIdString); String accountName = parts[1]; verifyAccountNameStrength( accountName ); DefaultUser user = new DefaultUser( accountName ); user.accountId = accountId; String password = parts[2]; verifyPasswordStrength(null, password); setHashedPassword(user, password); String[] roles = parts[3].toLowerCase().split(" *, *"); for (int i=0; i<roles.length; i++) if (!"".equals(roles[i])) user.addRole(roles[i]); if (!"unlocked".equalsIgnoreCase(parts[4])) user.lock(); if ("enabled".equalsIgnoreCase(parts[5])) { user.enable(); } else { user.disable(); } // generate a new csrf token user.resetCSRFToken(); setOldPasswordHashes(user, Arrays.asList(parts[6].split(" *, *"))); user.setLastHostAddress("null".equals(parts[7]) ? null : parts[7]); user.setLastPasswordChangeTime(new Date( Long.parseLong(parts[8]))); user.setLastLoginTime(new Date( Long.parseLong(parts[9]))); user.setLastFailedLoginTime(new Date( Long.parseLong(parts[10]))); user.setExpirationTime(new Date( Long.parseLong(parts[11]))); user.setFailedLoginCount(Integer.parseInt(parts[12])); return user; } /** * Utility method to extract credentials and verify them. * * @param request * The current HTTP request * @param response * The HTTP response being prepared * @return * The user that successfully authenticated * * @throws AuthenticationException * if the submitted credentials are invalid. */ private User loginWithUsernameAndPassword(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { String username = request.getParameter(ESAPI.securityConfiguration().getUsernameParameterName()); String password = request.getParameter(ESAPI.securityConfiguration().getPasswordParameterName()); // if a logged-in user is requesting to login, log them out first User user = getCurrentUser(); if (user != null && !user.isAnonymous()) { logger.warning(Logger.SECURITY, true, "User requested relogin. Performing logout then authentication" ); user.logout(); } // now authenticate with username and password if (username == null || password == null) { if (username == null) { username = "unspecified user"; } throw new AuthenticationCredentialsException("Authentication failed", "Authentication failed for " + username + " because of null username or password"); } user = getUser(username); if (user == null) { throw new AuthenticationCredentialsException("Authentication failed", "Authentication failed because user " + username + " doesn't exist"); } user.loginWithPassword(password); request.setAttribute(user.getCSRFToken(), "authenticated"); return user; } /** * {@inheritDoc} */ public synchronized void removeUser(String accountName) throws AuthenticationException { loadUsersIfNecessary(); User user = getUser(accountName); if (user == null) { throw new AuthenticationAccountsException("Remove user failed", "Can't remove invalid accountName " + accountName); } userMap.remove( new Long( user.getAccountId() )); System.out.println("Removing user " +user.getAccountName()); passwordMap.remove(user.getAccountName()); saveUsers(); } /** * Saves the user database to the file system. In this implementation you must call save to commit any changes to * the user file. Otherwise changes will be lost when the program ends. * * @throws AuthenticationException * if the user file could not be written */ public synchronized void saveUsers() throws AuthenticationException { PrintWriter writer = null; try { writer = new PrintWriter(new FileWriter(userDB)); writer.println(" writer.println("# accountId | accountName | hashedPassword | roles | locked | enabled | csrfToken | oldPasswordHashes | lastPasswordChangeTime | lastLoginTime | lastFailedLoginTime | expirationTime | failedLoginCount"); writer.println(); saveUsers(writer); writer.flush(); logger.info(Logger.SECURITY, true, "User file written to disk" ); } catch (IOException e) { logger.fatal(Logger.SECURITY, false, "Problem saving user file " + userDB.getAbsolutePath(), e ); throw new AuthenticationException("Internal Error", "Problem saving user file " + userDB.getAbsolutePath(), e); } finally { if (writer != null) { writer.close(); lastModified = userDB.lastModified(); lastChecked = lastModified; } } } /** * Save users. * * @param writer * the print writer to use for saving */ protected synchronized void saveUsers(PrintWriter writer) { Iterator i = getUserNames().iterator(); while (i.hasNext()) { String accountName = (String) i.next(); DefaultUser u = (DefaultUser) getUser(accountName); if ( u != null && !u.isAnonymous() ) { writer.println(save(u)); } else { new AuthenticationCredentialsException("Problem saving user", "Skipping save of user " + accountName ); } } } /** * Save. * * @param user * the User to save * @return * a line containing properly formatted information to save regarding the user */ private String save(DefaultUser user) { StringBuffer sb = new StringBuffer(); sb.append( user.getAccountId() ); sb.append( " | " ); sb.append( user.getAccountName() ); sb.append( " | " ); sb.append( getHashedPassword(user) ); sb.append( " | " ); sb.append( dump(user.getRoles()) ); sb.append( " | " ); sb.append( user.isLocked() ? "locked" : "unlocked" ); sb.append( " | " ); sb.append( user.isEnabled() ? "enabled" : "disabled" ); sb.append( " | " ); sb.append( dump(getOldPasswordHashes(user)) ); sb.append( " | " ); sb.append( user.getLastHostAddress() ); sb.append( " | " ); sb.append( user.getLastPasswordChangeTime().getTime() ); sb.append( " | " ); sb.append( user.getLastLoginTime().getTime() ); sb.append( " | " ); sb.append( user.getLastFailedLoginTime().getTime() ); sb.append( " | " ); sb.append( user.getExpirationTime().getTime() ); sb.append( " | " ); sb.append( user.getFailedLoginCount() ); return sb.toString(); } /** * Dump a collection as a comma-separated list. * * @param c * the collection to convert to a comma separated list * * @return * a comma separated list containing the values in c */ private String dump( Collection c ) { StringBuffer sb = new StringBuffer(); Iterator i = c.iterator(); while ( i.hasNext() ) { String s = (String)i.next(); sb.append( s ); if ( i.hasNext() ) sb.append( ","); } return sb.toString(); } /** * {@inheritDoc} */ public User login(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if ( request == null || response == null ) { throw new AuthenticationCredentialsException( "Invalid request", "Request or response objects were null" ); } // if there's a user in the session then use that DefaultUser user = (DefaultUser)getUserFromSession(); // else if there's a remember token then use that if ( user == null ) { user = getUserFromRememberToken(); } // else try to verify credentials - throws exception if login fails if ( user == null ) { user = (DefaultUser)loginWithUsernameAndPassword(request, response); } // set last host address user.setLastHostAddress( request.getRemoteHost() ); // warn if this authentication request was not POST or non-SSL connection, exposing credentials or session id try { ESAPI.httpUtilities().assertSecureRequest( ESAPI.currentRequest() ); } catch( AccessControlException e ) { throw new AuthenticationException( "Attempt to login with an insecure request", e.getLogMessage(), e ); } // don't let anonymous user log in if (user.isAnonymous()) { user.logout(); throw new AuthenticationLoginException("Login failed", "Anonymous user cannot be set to current user. User: " + user.getAccountName() ); } // don't let disabled users log in if (!user.isEnabled()) { user.logout(); user.incrementFailedLoginCount(); user.setLastFailedLoginTime(new Date()); throw new AuthenticationLoginException("Login failed", "Disabled user cannot be set to current user. User: " + user.getAccountName() ); } // don't let locked users log in if (user.isLocked()) { user.logout(); user.incrementFailedLoginCount(); user.setLastFailedLoginTime(new Date()); throw new AuthenticationLoginException("Login failed", "Locked user cannot be set to current user. User: " + user.getAccountName() ); } // don't let expired users log in if (user.isExpired()) { user.logout(); user.incrementFailedLoginCount(); user.setLastFailedLoginTime(new Date()); throw new AuthenticationLoginException("Login failed", "Expired user cannot be set to current user. User: " + user.getAccountName() ); } // check session inactivity timeout if ( user.isSessionTimeout() ) { user.logout(); user.incrementFailedLoginCount(); user.setLastFailedLoginTime(new Date()); throw new AuthenticationLoginException("Login failed", "Session inactivity timeout: " + user.getAccountName() ); } // check session absolute timeout if ( user.isSessionAbsoluteTimeout() ) { user.logout(); user.incrementFailedLoginCount(); user.setLastFailedLoginTime(new Date()); throw new AuthenticationLoginException("Login failed", "Session absolute timeout: " + user.getAccountName() ); } // create new session for this User HttpSession session = request.getSession(); user.addSession( session ); session.setAttribute(USER, user); setCurrentUser(user); return user; } /** * {@inheritDoc} */ public void logout() { User user = getCurrentUser(); if ( user != null && !user.isAnonymous() ) { user.logout(); } } /** * {@inheritDoc} */ public void setCurrentUser(User user) { currentUser.setUser(user); } /** * {@inheritDoc} * * This implementation simply verifies that account names are at least 5 characters long. This helps to defeat a * brute force attack, however the real strength comes from the name length and complexity. * */ public void verifyAccountNameStrength(String newAccountName) throws AuthenticationException { if (newAccountName == null) { throw new AuthenticationCredentialsException("Invalid account name", "Attempt to create account with a null account name"); } if (!ESAPI.validator().isValidInput("verifyAccountNameStrength", newAccountName, "AccountName", MAX_ACCOUNT_NAME_LENGTH, false )) { throw new AuthenticationCredentialsException("Invalid account name", "New account name is not valid: " + newAccountName); } } /** * {@inheritDoc} * * This implementation checks: - for any 3 character substrings of the old password - for use of a length * * character sets > 16 (where character sets are upper, lower, digit, and special * */ public void verifyPasswordStrength(String oldPassword, String newPassword) throws AuthenticationException { if ( newPassword == null ) throw new AuthenticationCredentialsException("Invalid password", "New password cannot be null" ); // can't change to a password that contains any 3 character substring of old password if ( oldPassword != null ) { int length = oldPassword.length(); for (int i = 0; i < length - 2; i++) { String sub = oldPassword.substring(i, i + 3); if (newPassword.indexOf(sub) > -1 ) { throw new AuthenticationCredentialsException("Invalid password", "New password cannot contain pieces of old password" ); } } } // new password must have enough character sets and length int charsets = 0; for (int i = 0; i < newPassword.length(); i++) if (Arrays.binarySearch(DefaultEncoder.CHAR_LOWERS, newPassword.charAt(i)) > 0) { charsets++; break; } for (int i = 0; i < newPassword.length(); i++) if (Arrays.binarySearch(DefaultEncoder.CHAR_UPPERS, newPassword.charAt(i)) > 0) { charsets++; break; } for (int i = 0; i < newPassword.length(); i++) if (Arrays.binarySearch(DefaultEncoder.CHAR_DIGITS, newPassword.charAt(i)) > 0) { charsets++; break; } for (int i = 0; i < newPassword.length(); i++) if (Arrays.binarySearch(DefaultEncoder.CHAR_SPECIALS, newPassword.charAt(i)) > 0) { charsets++; break; } // calculate and verify password strength int strength = newPassword.length() * charsets; if (strength < 16) { throw new AuthenticationCredentialsException("Invalid password", "New password is not long and complex enough"); } } }
package org.pentaho.di.job.entries.dtdvalidator; import org.pentaho.di.i18n.BaseMessages; public class Messages { public static final String packageName = Messages.class.getPackage().getName(); public static String getString(String key) { return BaseMessages.getString(packageName, key); } public static String getString(String key, String param1) { return BaseMessages.getString(packageName, key, param1); } public static String getString(String key, String param1, String param2) { return BaseMessages.getString(packageName, key, param1, param2); } public static String getString(String key, String param1, String param2, String param3) { return BaseMessages.getString(packageName, key, param1, param2, param3); } public static String getString(String key, String param1, String param2, String param3, String param4) { return BaseMessages.getString(packageName, key, param1, param2, param3, param4); } public static String getString(String key, String param1, String param2, String param3, String param4, String param5) { return BaseMessages.getString(packageName, key, param1, param2, param3, param4, param5); } public static String getString(String key, String param1, String param2, String param3, String param4, String param5, String param6) { return BaseMessages.getString(packageName, key, param1, param2, param3, param4, param5, param6); } }
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: package org.sosy_lab.java_smt.api; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.Collection; import java.util.List; import java.util.Optional; import org.checkerframework.checker.nullness.qual.Nullable; import org.sosy_lab.java_smt.api.SolverContext.ProverOptions; /** * Super interface for {@link ProverEnvironment} and {@link InterpolatingProverEnvironment} that * provides only the common operations. In most cases, just use one of the two sub-interfaces */ public interface BasicProverEnvironment<T> extends AutoCloseable { String NO_MODEL_HELP = "Model computation failed. Are the pushed formulae satisfiable?"; /** * Push a backtracking point and add a formula to the current stack, asserting it. The return * value may be used to identify this formula later on in a query (this depends on the sub-type of * the environment). */ @Nullable @CanIgnoreReturnValue default T push(BooleanFormula f) throws InterruptedException { push(); return addConstraint(f); } /** * Remove one backtracking point/level from the current stack. This removes the latest level * including all of its formulas, i.e., all formulas that were added for this backtracking point. */ void pop(); /** Add a constraint to the latest backtracking point. */ @Nullable @CanIgnoreReturnValue T addConstraint(BooleanFormula constraint) throws InterruptedException; /** * Create a new backtracking point, i.e., a new level on the assertion stack. Each level can hold * several asserted formulas. * * <p>If formulas are added before creating the first backtracking point, they can not be removed * via a POP-operation. */ void push(); /** * Get the number of backtracking points/levels on the current stack. * * <p>Caution: This is the number of PUSH-operations, and not necessarily equal to the number of * asserted formulas. On any level there can be an arbitrary number of asserted formulas. Even * with size of 0, formulas can already be asserted (at bottom level). */ int size(); /** Check whether the conjunction of all formulas on the stack is unsatisfiable. */ boolean isUnsat() throws SolverException, InterruptedException; /** * Check whether the conjunction of all formulas on the stack together with the list of * assumptions is satisfiable. * * @param assumptions A list of literals. */ boolean isUnsatWithAssumptions(Collection<BooleanFormula> assumptions) throws SolverException, InterruptedException; /** * Get a satisfying assignment. This should be called only immediately after an {@link #isUnsat()} * call that returned <code>false</code>. A model might contain additional symbols with their * evaluation, if a solver uses its own temporary symbols. There should be at least a * value-assignment for each free symbol. */ Model getModel() throws SolverException; /** * Get a list of satisfying assignments. This is equivalent to <code> * ImmutableList.copyOf(getModel())</code>, but removes the need for calling {@link * Model#close()}. * * <p>Note that if you need to iterate multiple times over the model it may be more efficient to * use this method instead of {@link #getModel()} (depending on the solver). */ default ImmutableList<Model.ValueAssignment> getModelAssignments() throws SolverException { try (Model model = getModel()) { return model.asList(); } } /** * Get an unsat core. This should be called only immediately after an {@link #isUnsat()} call that * returned <code>false</code>. */ List<BooleanFormula> getUnsatCore(); /** * Returns an UNSAT core (if it exists, otherwise {@code Optional.empty()}), over the chosen * assumptions. Does NOT require the {@link ProverOptions#GENERATE_UNSAT_CORE} option to work. * * @param assumptions Selected assumptions * @return Empty optional if the constraints with assumptions are satisfiable, subset of * assumptions which is unsatisfiable with the original constraints otherwise. */ Optional<List<BooleanFormula>> unsatCoreOverAssumptions(Collection<BooleanFormula> assumptions) throws SolverException, InterruptedException; /** * Get statistics for a concrete ProverEnvironment in a solver. The returned mapping is intended * to provide solver-internal statistics for only this instance. The keys can differ between * individual solvers. * * <p>Calling the statistics several times for the same {@link ProverEnvironment}s returns * accumulated number, i.e., we currently do not provide any possibility to reset the statistics. * Calling the statistics for different {@link ProverEnvironment}s returns independent statistics. * * <p>We do not guarantee any specific key to be present, as this depends on the used solver. We * might even return an empty mapping if the solver does not support calling this method or is in * an invalid state. * * @see SolverContext#getStatistics() */ default ImmutableMap<String, String> getStatistics() { return ImmutableMap.of(); } /** * Closes the prover environment. The object should be discarded, and should not be used after * closing. The first call of this method will close the prover instance, further calls are * ignored. */ @Override void close(); /** * Get all satisfying assignments of the current environment with regard to a subset of terms, and * create a region representing all those models. * * @param important A set of (positive) variables appearing in the asserted queries. Only these * variables will appear in the region. * @return A region representing all satisfying models of the formula. */ <R> R allSat(AllSatCallback<R> callback, List<BooleanFormula> important) throws InterruptedException, SolverException; /** * Interface for the {@link #allSat} callback. * * @param <R> The result type of the callback, passed through by {@link #allSat}. */ interface AllSatCallback<R> { /** * Callback for each possible satisfying assignment to given {@code important} predicates. If * the predicate is assigned {@code true} in the model, it is returned as-is in the list, and * otherwise it is negated. * * <p>There is no guarantee that the list of model values corresponds to the list in {@link * BasicProverEnvironment#allSat}. We can reorder the variables or leave out values with a * freely chosen value. */ void apply(List<BooleanFormula> model); /** Returning the result generated after all the {@link #apply} calls went through. */ R getResult() throws InterruptedException; } }
package org.usfirst.frc.team2791.commands; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc.team2791.abstractSubsystems.AbstractShakerShooterArm; import org.usfirst.frc.team2791.util.ShakerCamera; import static org.usfirst.frc.team2791.robot.Robot.*; public class AutoLineUpShot extends ShakerCommand implements Runnable { //This will decide which case to run private static final int STAGE_ONE = 0; //use one frame to lineup to the target and shoot private static final int SINGLE_FRAME_SHOT = 1; //single frame no shoot private static final int SINGLE_FRAME_LINEUP = 2; //multiple frames and shoot private static final int MULTIPLE_FRAME_SHOOT = 3; //special case after shooting private static final int AFTER_SHOT_CLEANUP = 4; //reset for anything than ran private static final int GENERAL_RESET = 5; private static final double angleMaxOutput = 0.7; //Settings // to correct any curving of the shot leftward or right ward public static double shootOffset = 0.5; //Run method flags private static boolean useMultipleFrames = false; private static boolean shootAfterAligned = false; private static boolean quickLineUpShot = false; //internal values private double targetTurnAngle = 0; private ShakerCamera.ParticleReport currentTarget; private Timer totalTime; private double frames_used = 0; public AutoLineUpShot() { totalTime = new Timer(); } public void run() { while (running) { SmartDashboard.putNumber("Vision Shot stage: ", counter); switch (counter) { default: case STAGE_ONE: //reset the number of frames that have been used frames_used = 0; //get a new frame reUpdateCurrentTarget(); //reset encoders because that is what we used to turn driveTrain.resetEncoders(); /*prep the shot, runs the shooter wheels to setpoint saves time in firing the useMultipleFrames is there because we always fire if we're using multiple frames*/ if (shootAfterAligned || useMultipleFrames) shooterWheels.prepShot(); /*This decides what case to call depending on the flags that are set true; */ if (useMultipleFrames) { if (shootAfterAligned) counter = MULTIPLE_FRAME_SHOOT; else { printTimeStamp(); System.out.println( "We have no code to line up with multiple frame and not shoot. Shooting anyway."); counter = MULTIPLE_FRAME_SHOOT; } } else { if (shootAfterAligned) counter = SINGLE_FRAME_SHOT; else counter = SINGLE_FRAME_LINEUP; } totalTime.reset(); totalTime.start(); debugSystemOut(); break; case SINGLE_FRAME_SHOT: //uses the single frame and fires if (driveTrain.setAngle(targetTurnAngle, angleMaxOutput, true, true)) { //after the desired angle is reached it will do a complete shot shooterWheels.completeShot(); debugSystemOut(); counter = AFTER_SHOT_CLEANUP; } break; case SINGLE_FRAME_LINEUP: if (driveTrain.setAngle(targetTurnAngle, angleMaxOutput, true, true)) { debugSystemOut(); counter = GENERAL_RESET; } break; case MULTIPLE_FRAME_SHOOT: if (driveTrain.setAngle(targetTurnAngle, angleMaxOutput, true, true)) { reUpdateCurrentTarget(); double camera_error = currentTarget.optimalTurnAngle + shootOffset; double camera_error_threshold = 0.75; if (quickLineUpShot) camera_error_threshold = 1.5; if (Math.abs(camera_error) < camera_error_threshold) { printTimeStamp(); System.out.println("I've found a good angle and am " + "going to busy it while the shooter spins up."); shooterWheels.completeShot(); counter = AFTER_SHOT_CLEANUP; } else if (!(Math.abs(camera_error) < camera_error_threshold)) { printTimeStamp(); System.out.println("I am waiting on camera error"); //the error is still greater than the thresh so update then angle value targetTurnAngle = driveTrain.getAngle() + currentTarget.optimalTurnAngle + shootOffset; } } break; case AFTER_SHOT_CLEANUP: // keep the same angle until we are done shooting if (driveTrain.setAngle(targetTurnAngle, angleMaxOutput, true, true)) { if (!shooterWheels.getIfCompleteShot()) { printTimeStamp(); System.out.println("Done shooting and bringing arm down"); //once we are done shooting do a reset IntakeAndShooterSynergy.setPosition(AbstractShakerShooterArm.ShooterHeight.LOW); counter = GENERAL_RESET; } } break; case GENERAL_RESET: // reset everything printTimeStamp(); System.out.println("Finished auto line up and resetting."); System.out.println("I took " + frames_used + " frames to shoot"); reset(); break; } try { Thread.sleep(100);//Run @ a 100 hz } catch (InterruptedException e) { e.printStackTrace(); } } } /** * Through threading this method tells the camera thread to get * a new frame and then waits on it to process it, when the camera thread is * done it will send a notification to this thread which will then update the getTarget * <p> * This solves problems we had earlier about having the new frame be the same as the previous frame * it also lets us process the frame on the camera thread */ private void reUpdateCurrentTarget() { synchronized (cameraThread) { camera.getNextFrame(); try { cameraThread.wait(); } catch (InterruptedException e) { e.printStackTrace(); run(); } } currentTarget = camera.getTarget(); frames_used++; if (currentTarget == null) { System.out.println("Target Reports are empty so aborting."); counter = 40; return; } else // the target angle == current angle + targetAngleDiff + offset targetTurnAngle = driveTrain.getAngle() + currentTarget.optimalTurnAngle + shootOffset; } private void printTimeStamp() { System.out.print("TimeStamp: " + totalTime.get()); } private void debugSystemOut() { printTimeStamp(); System.out.println(" My target is: " + targetTurnAngle + " Current angle is: " + driveTrain.getAngle() + " Shooter offset is: " + shootOffset); } public void setUseMultipleFrames(boolean value) { //This will use multiple frames to lineup and fire useMultipleFrames = value; } public void setShootAfterAligned(boolean value) { //this will control whether to shoot after the lineup shootAfterAligned = value; } public void setQuickLineUpShot(boolean value) { //increases the camera error on the mutipleframe case for faster lineup quickLineUpShot = value; } public void start() { if (!running) { //sets the running boolean to true running = true; //puts camera into manual mode meaning take frame by frame when requested camera.setManualCapture(); //actually run the code... this should run on its own thread run(); } } public void reset() { //This sets the camera to automatically update to the dash again camera.setAutomaticCaptureAndUpdate(); //restart the totalTime that counts how long the whole process takes totalTime.reset(); totalTime.stop(); //set the running flag to false running = false; //reset the counter counter = STAGE_ONE; //stop all shooter stuff shooterWheels.resetShooterFlags(); //run method flags useMultipleFrames = false; shootAfterAligned = false; quickLineUpShot = false; driveTrain.forceBreakPID(); } public void updateSmartDash() { //This wasn't necessary either because we chose to spam System.out with info } public void debug() { //There was really nothing to put here....cuz who needs debugging } }
package soot.jimple.infoflow.data; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.jimple.infoflow.solver.IMemoryManager; /** * Memory manager implementation for FlowDroid * * @author Steven Arzt * */ public class FlowDroidMemoryManager implements IMemoryManager<Abstraction> { private final Logger logger = LoggerFactory.getLogger(getClass()); /** * Special class for encapsulating taint abstractions for a full equality * check including those fields (predecessor, etc.) that are normally left * out * * @author Steven Arzt * */ private class AbstractionCacheKey { private final Abstraction abs; public AbstractionCacheKey(Abstraction abs) { this.abs = abs; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * abs.hashCode(); result = prime * result + ((abs.getPredecessor() == null) ? 0 : abs.getPredecessor().hashCode()); result = prime * result + ((abs.getCurrentStmt() == null) ? 0 : abs.getCurrentStmt().hashCode()); result = prime * result + ((abs.getCorrespondingCallSite() == null) ? 0 : abs.getCorrespondingCallSite().hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AbstractionCacheKey other = (AbstractionCacheKey) obj; if (!abs.equals(other.abs)) return false; if (abs.getPredecessor() != other.abs.getPredecessor()) return false; if (abs.getCurrentStmt() != other.abs.getCurrentStmt()) return false; if (abs.getCorrespondingCallSite() != other.abs.getCorrespondingCallSite()) return false; return true; } } private ConcurrentMap<AccessPath, AccessPath> apCache = new ConcurrentHashMap<>(); private ConcurrentHashMap<AbstractionCacheKey, Abstraction> absCache = new ConcurrentHashMap<>(); private AtomicInteger reuseCounter = new AtomicInteger(); private final boolean tracingEnabled; private final PathDataErasureMode erasePathData; private boolean useAbstractionCache = false; /** * Supported modes that define which path tracking data shall be erased and * which shall be kept */ public enum PathDataErasureMode { /** * Keep all path tracking data. */ EraseNothing, /** * Keep only those path tracking items that are necessary for context- * sensitive path reconstruction. */ KeepOnlyContextData, /** * Erase all path tracking data. */ EraseAll } /** * Constructs a new instance of the AccessPathManager class */ public FlowDroidMemoryManager() { this(false, PathDataErasureMode.EraseNothing); } /** * Constructs a new instance of the AccessPathManager class * @param tracingEnabled True if performance tracing data shall be recorded * @param erasePathData Specifies whether data for tracking paths (current * statement, corresponding call site) shall be erased. */ public FlowDroidMemoryManager(boolean tracingEnabled, PathDataErasureMode erasePathData) { this.tracingEnabled = tracingEnabled; this.erasePathData = erasePathData; logger.info("Initializing FlowDroid memory manager..."); if (this.tracingEnabled) logger.info("FDMM: Tracing enabled. This may negatively affect performance."); if (this.erasePathData != PathDataErasureMode.EraseNothing) logger.info("FDMM: Path data erasure enabled"); } /** * Gets the cached equivalent of the given access path * @param ap The access path for which to get the cached equivalent * @return The cached equivalent of the given access path */ private AccessPath getCachedAccessPath(AccessPath ap) { AccessPath oldAP = apCache.putIfAbsent(ap, ap); if (oldAP == null) return ap; // We can re-use an old access path if (tracingEnabled && oldAP != ap) reuseCounter.incrementAndGet(); return oldAP; } /** * Gets a cached equivalent abstraction for the given abstraction if we have * one, otherwise returns null * @param abs The abstraction for which to perform a cache lookup * @return The cached abstraction equivalent to the given one of it exists, * otherwise null */ private Abstraction getCachedAbstraction(Abstraction abs) { Abstraction oldAbs = absCache.putIfAbsent(new AbstractionCacheKey(abs), abs); if (oldAbs != null && oldAbs != abs) if (tracingEnabled) reuseCounter.incrementAndGet(); return oldAbs; } /** * Gets the number of access paths that have been re-used through caching * @return The number of access paths that have been re-used through caching */ public int getReuseCount() { return this.reuseCounter.get(); } @Override public Abstraction handleMemoryObject(Abstraction obj) { if (useAbstractionCache) { // We check for a cached version of the complete abstraction Abstraction cachedAbs = getCachedAbstraction(obj); if (cachedAbs != null) return cachedAbs; } // We check for a cached version of the access path AccessPath newAP = getCachedAccessPath(obj.getAccessPath()); obj.setAccessPath(newAP); // If the abstraction just made a pass through the alias analysis // without any changes, we can throw away the middle men. // More precisely: Compact a -> r0 -> _r0 -> r0 to a -> r0. Abstraction pred = obj.getPredecessor(); if (obj.isAbstractionActive()) { Set<Abstraction> doneSet = new HashSet<>(); Abstraction curAbs = pred; while (curAbs != null && !curAbs.isAbstractionActive() && doneSet.add(curAbs)) { Abstraction predPred = curAbs.getPredecessor(); if (predPred != null && predPred.isAbstractionActive()) { if (predPred.equals(obj)) { pred = predPred.getPredecessor(); obj = predPred; } } else break; curAbs = predPred; } } // Erase path data if requested boolean doErase = erasePathData == PathDataErasureMode.EraseAll; if (erasePathData == PathDataErasureMode.KeepOnlyContextData && obj.getCorrespondingCallSite() == null && obj.getCurrentStmt() != null && !obj.getCurrentStmt().containsInvokeExpr()) { doErase = true; } if (doErase) { obj.setCurrentStmt(null); obj.setCorrespondingCallSite(null); } // We can shorten links while (obj.getNeighbors() == null && pred != null && pred.getNeighbors() == null && pred.getCorrespondingCallSite() == null && pred.getCurrentStmt() == null) { if (pred.getPredecessor() == null) { obj.setSourceContext(pred.getSourceContext()); obj.setPredecessor(null); pred = null; } else { pred = pred.getPredecessor(); obj.setPredecessor(pred); } } return obj; } @Override public Abstraction handleGeneratedMemoryObject(Abstraction input, Abstraction output) { // We we just pass the same object on, there is nothing to optimize if (input == output) { return output; } // If the flow function gave us a chain of abstractions, we can // compact it Abstraction pred = output.getPredecessor(); if (pred != null && pred != input) output.setPredecessor(input); // If the abstraction didn't change at all, we can use the old one if (input.equals(output)) { if (output.getCurrentStmt() == null || input.getCurrentStmt() == output.getCurrentStmt()) return input; if (input.getCurrentStmt() == null) { synchronized (input) { if (input.getCurrentStmt() == null) { input.setCurrentStmt(output.getCurrentStmt()); input.setCorrespondingCallSite(output.getCorrespondingCallSite()); return input; } } } } return output; } /** * Sets whether the memory manager shall use the abstraction cache * @param useAbstractionCache True if the abstraction cache shall be used, * otherwise false */ public void setUseAbstractionCache(boolean useAbstractionCache) { this.useAbstractionCache = useAbstractionCache; } }
package com.arturmkrtchyan.sizeof4j; import com.arturmkrtchyan.sizeof4j.util.JvmUtil; import org.junit.Test; import static org.junit.Assert.assertEquals; public class SizeOfTest { MemoryLayout memoryLayout = JvmUtil.memoryLayout(); @Test public void primitives() { assertEquals("booleanSize must be 1", 1, SizeOf.booleanSize()); assertEquals("byteSize must be 1", 1, SizeOf.byteSize()); assertEquals("shortSize must be 2", 2, SizeOf.shortSize()); assertEquals("charSize must be 2", 2, SizeOf.charSize()); assertEquals("intSize must be 4", 4, SizeOf.intSize()); assertEquals("floatSize must be 4", 4, SizeOf.floatSize()); assertEquals("longSize must be 8", 8, SizeOf.longSize()); assertEquals("doubleSize must be 8", 8, SizeOf.doubleSize()); } @Test public void objectShallowSize() { final Object testObj = new Object(); switch (memoryLayout) { case Layout32: assertEquals("Object size must be 8", 8, SizeOf.shallowSize(testObj)); break; case Layout64 : assertEquals("Object size must be 16", 16, SizeOf.shallowSize(testObj)); break; case LayoutCoops: assertEquals("Object size must be 16", 16, SizeOf.shallowSize(testObj)); break; } } @Test public void integerShallowSize() { final Integer testObj = new Integer(12); switch (memoryLayout) { case Layout32: assertEquals("Integer size must be 16", 16, SizeOf.shallowSize(testObj)); break; case Layout64 : assertEquals("Integer size must be 24", 24, SizeOf.shallowSize(testObj)); break; case LayoutCoops: assertEquals("Integer size must be 16", 16, SizeOf.shallowSize(testObj)); break; } } @Test public void stringShallowSize() { switch (memoryLayout) { case Layout32: assertEquals("String size must be 16", 16, SizeOf.shallowSize(String.class)); break; case Layout64 : assertEquals("String size must be 32", 32, SizeOf.shallowSize(String.class)); break; case LayoutCoops: assertEquals("String size must be 24", 24, SizeOf.shallowSize(String.class)); break; } } @Test public void emptyIntArrayShallowSize() { switch (memoryLayout) { case Layout32: assertEquals("int[] size must be 16", 16, SizeOf.shallowSize(int[].class)); break; case Layout64 : assertEquals("int[] size must be 24", 24, SizeOf.shallowSize(int[].class)); break; case LayoutCoops: assertEquals("int[] size must be 16", 16, SizeOf.shallowSize(int[].class)); break; } } @Test public void stringArrayShallowSize() { final String[] testObj = new String[] {"Hello", "World"}; switch (memoryLayout) { case Layout32: assertEquals("String[2] size must be 24", 24, SizeOf.shallowSize(testObj)); break; case Layout64 : assertEquals("String[2] size must be 40", 40, SizeOf.shallowSize(testObj)); break; case LayoutCoops: assertEquals("String[2] size must be 24", 24, SizeOf.shallowSize(testObj)); break; } } }
package com.github.timp.anagram; import junit.framework.TestCase; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Tests for the Dictionary class. */ public class DictionaryTest extends TestCase { public void testDictionaryConstructor() throws Exception { Dictionary it = new Dictionary(); // As some words share a key the size will be smaller // than the number of words in the dictionary assertTrue(it.size() < Dictionary.WORD_COUNT); // Initial size of word.txt derived dictionary: 195763 // manually cut down size, before abandoning: 191555 // using data/2of4brif.txt assertEquals(56370, it.size()); } /** Test to discover the best initial value for common words list. */ public void testLargestCommonKey() throws Exception { Dictionary it = new Dictionary(); String mostCommonKey = it.firstMostCommonKey(); assertEquals("aeprs", mostCommonKey); ArrayList<String> them = it.get(mostCommonKey).words(); assertEquals(7, them.size()); } /** * Test to discover the longest key in the dictionary. */ public void testFirstLongestKey() throws Exception { Dictionary it = new Dictionary(); String firstLongestKey = it.firstLongestKey(); assertEquals("aacceeeeghllmnooprrst", firstLongestKey); ArrayList<String> them = it.get(firstLongestKey).words(); assertEquals("[electroencephalograms]", them.toString()); assertEquals(21, firstLongestKey.length()); } /** The list of possibilities will itself if query is valid word. */ public void testSilentListen() throws Exception { Dictionary it = new Dictionary(); assertTrue(it.get("silent").words().contains("listen")); assertTrue(it.get("silent").words().contains("tinsel")); assertTrue(it.get("silent").words().contains("silent")); assertTrue(it.get("listen").words().contains("silent")); assertTrue(it.get("listen").words().contains("tinsel")); assertTrue(it.get("listen").words().contains("listen")); assertTrue(it.get("tinsel").words().contains("listen")); assertTrue(it.get("tinsel").words().contains("listen")); assertTrue(it.get("tinsel").words().contains("tinsel")); // if key is not a valid word it is not included in results assertEquals("[enlist, inlets, listen, silent, tinsel]", it.get("listne").words().toString()); assertFalse(it.get("listne").words().contains("listne")); } public void testOneLetterWords() throws Exception { Dictionary it = new Dictionary(); String them = ""; for (String word : it.keys()) { if (word.length() == 1 ) { them += word; } } assertEquals("ai", them); } public void testTwoLetterWords() throws Exception { Dictionary it = new Dictionary(); String them = ""; for (String word : it.keys()) { if (word.length() == 2 ) { them += word; them += ","; } } assertEquals("am,an,as,at,be,by,do,eh,em,er,ew,ex,ey,fi,fo,go,hi,in,ip,is,it,lo,my,no,or,os,ot,ox,pu,su,", them); } public void testCapitalised() { assertEquals("Fred", Dictionary.capitalised("fred")); } public void testOutput() throws Exception { Dictionary it = new Dictionary(); assertEquals("[]", it.output(new Tree<String>(null)).toString()); Tree<String> tree = new Tree<String>(null); Tree ant = tree.add("ant"); assertEquals("[Ant, Tan]", it.output(tree).toString()); ant.add("aet").add("act"); assertEquals("[" + "Ant Ate Act, " + "Ant Ate Cat, " + "Ant Eat Act, " + "Ant Eat Cat, " + "Ant Tea Act, " + "Ant Tea Cat, " + "Tan Ate Act, " + "Tan Ate Cat, " + "Tan Eat Act, " + "Tan Eat Cat, " + "Tan Tea Act, " + "Tan Tea Cat" + "]", it.output(tree).toString()); } public void testFileNotFound() throws IOException { try { Dictionary it = new Dictionary("FileNotFound"); fail("should have bombed"); } catch (IOException e) {} } }
package com.lynx.fqb.select; import static org.hamcrest.Matchers.*; import java.util.Calendar; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Optional; import org.junit.Assert; import org.junit.Test; import com.lynx.fqb.IntegrationTestBase; import com.lynx.fqb.Select; import com.lynx.fqb.entity.SellOrder; import com.lynx.fqb.entity.SellOrder_; import com.lynx.fqb.expression.Expressions; import com.lynx.fqb.order.Orders; import com.lynx.fqb.path.Paths; public class OrderedSelectITest extends IntegrationTestBase { @Test public void shouldSelectEntitiesSortedByAttributeAsc() { List<SellOrder> resultList = Select .from(SellOrder.class) .orderBy(Orders.of(Orders.asc(SellOrder_.id))) .getResultList(em); assertOrder(resultList, Comparator.comparing(SellOrder::getId)); } @Test public void shouldSelectEntitiesSortedByAttributeDesc() { List<SellOrder> resultList = Select .from(SellOrder.class) .orderBy(Orders.of(Orders.desc(SellOrder_.id))) .getResultList(em); assertOrder(resultList, Comparator.comparing(SellOrder::getId).reversed()); } @Test public void shouldSelectEntitiesSortedByPathAsc() { List<SellOrder> resultList = Select .from(SellOrder.class) .orderBy(Orders.of(Orders.asc(Paths.get(SellOrder_.id)))) .getResultList(em); assertOrder(resultList, Comparator.comparing(SellOrder::getId)); } @Test public void shouldSelectEntitiesSortedByPathDesc() { List<SellOrder> resultList = Select .from(SellOrder.class) .orderBy(Orders.of(Orders.desc(Paths.get(SellOrder_.id)))) .getResultList(em); assertOrder(resultList, Comparator.comparing(SellOrder::getId).reversed()); } @Test public void shouldSelectEntitiesSortedByExpressionAsc() { List<SellOrder> resultList = Select .from(SellOrder.class) .orderBy(Orders.of(Orders.asc(Expressions.ofAttr(SellOrder_.dueDate).andThen(Expressions.year())))) .getResultList(em); assertOrder(resultList, Comparator.comparing(o -> getYear(o.getDueDate()))); } @Test public void shouldSelectEntitiesSortedByExpressionDesc() { List<SellOrder> resultList = Select .from(SellOrder.class) .orderBy(Orders.of(Orders.desc(Expressions.ofAttr(SellOrder_.dueDate).andThen(Expressions.year())))) .getResultList(em); assertOrder(resultList, Comparator.comparing((SellOrder o) -> getYear(o.getDueDate())).reversed()); } @Test public void shouldSelectEntitiesSortedByParentPathAsc() { List<SellOrder> resultList = Select .from(SellOrder.class) .orderBy(Orders.of( Orders.asc(Paths.get(SellOrder_.id)), (cb, root) -> { return cb.asc(root.get(SellOrder_.dateCreate)); })) .getResultList(em); assertOrder( resultList, Comparator.comparing(SellOrder::getId).thenComparing(Comparator.comparing(SellOrder::getDateCreate))); } private void assertOrder(List<SellOrder> resultList, Comparator<SellOrder> comparator) { Assert.assertThat(resultList, contains(resultList.stream().sorted(comparator).toArray(SellOrder[]::new))); } private int getYear(Date date) { return Optional.ofNullable(date) .map(d -> { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.YEAR); }) .orElse(0); } }
package com.trevorgowing; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static com.trevorgowing.UrlStringBuilder.basedUrlBuilder; import static com.trevorgowing.UrlStringBuilder.emptyUrlBuilder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; @RunWith(JUnit4.class) public class UrlStringBuilderTests { private static final String BASE_URL = "http://trevorgowing.com"; @Test(expected = IllegalArgumentException.class) public void testConstructUrlStringBuilderWithNullBaseUrl_shouldThrowIllegalArgumentException() { // Exercise SUT basedUrlBuilder(null); } @Test public void testConstructUrlStringBuilderWithBaseUrl_shouldSetUrlToBaseUrl() { // Exercise SUT String actualUrl = basedUrlBuilder(BASE_URL).toString(); // Verify behaviour assertThat(actualUrl, is(BASE_URL)); } @Test(expected = IllegalArgumentException.class) public void testAppendPathWithNull_shouldThrowIllegalArgumentException() { // Exercise SUT emptyUrlBuilder().appendPath(null); } @Test public void testAppendPathWithEmptyString_shouldNotAppendBackslash() { // Exercise SUT String actualUrl = emptyUrlBuilder().appendPath("").toString(); // Verify behaviour assertThat(actualUrl, isEmptyString()); } @Test public void testAppendPathWithAStringPathExcludingABackslash_shouldAppendPathWithExactlyOneBackslash() { // Set up fixture String pathWithoutBackslash = "home"; String expectedUrl = "/home"; // Exercise SUT String actualUrl = emptyUrlBuilder().appendPath(pathWithoutBackslash).toString(); // Verify behaviour assertThat(actualUrl, is(expectedUrl)); } @Test public void testAppendPathWithAStringIncludingABackslash_shouldAppendPathWithExactlyOneBackslash() { // Set up fixture String pathWithBackslash = "/home"; // Exercise SUT String actualUrl = emptyUrlBuilder().appendPath(pathWithBackslash).toString(); // Verify behaviour assertThat(actualUrl, is(pathWithBackslash)); } @Test public void testAppendPathWithInt_shouldAppendPath() { // Exercise SUT String actualUrl = emptyUrlBuilder().appendPath(1).toString(); // Verify behaviour assertThat(actualUrl, is("/1")); } @Test public void testAppendPathWithLong_shouldAppendPath() { // Exercise SUT String actualUrl = emptyUrlBuilder().appendPath(1L).toString(); // Verify behaviour assertThat(actualUrl, is("/1")); } @Test(expected = IllegalArgumentException.class) public void testAppendQueryWithNullQueryName_shouldThrowIllegalArgumentException() { // Set up fixture String queryValue = "log"; // Exercise emptyUrlBuilder().appendQuery(null, queryValue); } @Test(expected = IllegalArgumentException.class) public void testAppendQueryWithNullQueryValue_shouldThrowIllegalArgumentException() { // Set up fixture String queryName = "log"; // Exercise SUT emptyUrlBuilder().appendQuery(queryName, null); } @Test public void testAppendQueryWithEmptyQueryName_shouldNotAppendQuery() { // Set up fixture String emptyQueryName = ""; String queryValue = "log"; // Exercise SUT String actualUrl = emptyUrlBuilder().appendQuery(emptyQueryName, queryValue).toString(); // Verify behaviour assertThat(actualUrl, isEmptyString()); } @Test public void testAppendQueryWithEmptyQueryValue_shouldNotAppendQuery() { // Set up fixture String queryName = "type"; String emptyQueryValue = ""; // Exercise SUT String actualUrl = emptyUrlBuilder().appendQuery(queryName, emptyQueryValue).toString(); // Verify behaviour assertThat(actualUrl, isEmptyString()); } @Test public void testAppendQueryWithValidFirstQuery_shouldAppendQueryWithLeadingQuestionMark() { // Set up fixture String queryName = "type"; String queryValue = "log"; String expectedUrl = "?" + queryName + "=" + queryValue; // Exercise SUT String actualUrl = emptyUrlBuilder().appendQuery(queryName, queryValue).toString(); // Verify behaviour assertThat(actualUrl, is(expectedUrl)); } @Test public void testAppendQueryWithValidSecondQuery_shouldAppendQueryWithLeadingAmpersand() { // Set up fixture UrlStringBuilder urlStringBuilder = emptyUrlBuilder().appendQuery("type", "log"); String secondQueryName = "date"; String secondQueryValue = "20170521"; String expectedUrl = "?type=log&date=20170521"; // Exercise SUT String actualUrl = urlStringBuilder.appendQuery(secondQueryName, secondQueryValue).toString(); // Very behaviour assertThat(actualUrl, is(expectedUrl)); } @Test public void testEqualsWithSameObject_shouldBeEqual() { // Set up fixture UrlStringBuilder urlStringBuilder = emptyUrlBuilder(); // Verify behaviour assertThat(urlStringBuilder.equals(urlStringBuilder), is(true)); } @Test public void testEqualsToNull_shouldNotBeEqual() { // Verify behaviour assertThat(emptyUrlBuilder().equals(null), is(false)); } @Test public void testEqualsWithObjectOfDifferentClass_shouldNotBeEqual() { // Verify behaviour assertThat(emptyUrlBuilder().equals(new Object()), is(false)); } @Test public void testEqualsWithDifferentUrls_shouldNotBeEqual() { // Set up fixture UrlStringBuilder urlStringBuilderOne = basedUrlBuilder(BASE_URL); UrlStringBuilder urlStringBuilderTwo = basedUrlBuilder("http://someotherdomain.com"); // Verify behaviour assertThat(urlStringBuilderOne.equals(urlStringBuilderTwo), is(false)); } @Test public void testEqualsWithTheSameUrls_shouldBeEqual() { // Set up fixture UrlStringBuilder urlStringBuilderOne = basedUrlBuilder(BASE_URL); UrlStringBuilder urlStringBuilderTwo = basedUrlBuilder(BASE_URL); // Verify behaviour assertThat(urlStringBuilderOne.equals(urlStringBuilderTwo), is(true)); } @Test public void testHashCodeWithDifferentUrls_shouldNotBeEqual() { // Set up fixture UrlStringBuilder urlStringBuilderOne = basedUrlBuilder(BASE_URL); UrlStringBuilder urlStringBuilderTwo = basedUrlBuilder("http://someotherdomain.com"); // Verify behaviour assertThat(urlStringBuilderOne.hashCode(), is(not(equalTo(urlStringBuilderTwo.hashCode())))); } @Test public void testHashCodeWithTheSameUrls_shouldBeEqual() { // Set up fixture UrlStringBuilder urlStringBuilderOne = basedUrlBuilder(BASE_URL); UrlStringBuilder urlStringBuilderTwo = basedUrlBuilder(BASE_URL); // Verify behaviour assertThat(urlStringBuilderOne.hashCode(), is(equalTo(urlStringBuilderTwo.hashCode()))); } }
package de.bmoth.modelchecker; import de.bmoth.parser.Parser; import de.bmoth.parser.ast.nodes.MachineNode; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ModelCheckerTest { private String dir = "src/test/resources/machines/"; @Test public void testSimpleModelsWithoutOperations() throws Exception { MachineNode simpleMachineWithViolation = Parser.getMachineFileAsSemanticAst(dir + "OnlyInitViolation.mch"); boolean result = ModelChecker.doModelCheck(simpleMachineWithViolation); assertEquals(false, result); MachineNode simpleMachineWithoutViolation = Parser.getMachineFileAsSemanticAst(dir + "OnlyInitNoViolation.mch"); result = ModelChecker.doModelCheck(simpleMachineWithoutViolation); assertEquals(true, result); } @Test public void testSubstitution() throws Exception { String machine = "MACHINE test \n"; machine += "VARIABLES x,y \n"; machine += "INVARIANT x:NATURAL & y : NATURAL \n"; machine += "INITIALISATION x,y:= 1,2 \n"; machine += "END"; MachineNode machineAsSemanticAst = Parser.getMachineAsSemanticAst(machine); ModelChecker.doModelCheck(machineAsSemanticAst); //TODO finish test } @Test public void testSimpleMachineWithOperations() throws Exception { String machine = "MACHINE SimpleMachine\n"; machine += "VARIABLES x\n"; machine += "INVARIANT x : NATURAL & x >= 0 & x <= 2\n"; machine += "INITIALISATION x := 0\n"; machine += "OPERATIONS\n"; machine += "\tInc = SELECT x < 2 THEN x := x + 1 END;\n"; machine += "\tDec = SELECT x > 0 THEN x := x - 1 END\n"; machine += "END"; boolean result = ModelChecker.doModelCheck(machine); assertEquals(true, result); } @Test public void testSimpleMachineWithOperations2() throws Exception { String machine = "MACHINE SimpleMachine\n"; machine += "VARIABLES x\n"; machine += "INVARIANT x : NATURAL & x >= 0 & x <= 2\n"; machine += "INITIALISATION x := 0\n"; machine += "OPERATIONS\n"; machine += "\tBlockSubstitution = BEGIN x := x + 1 END\n"; machine += "END"; boolean result = ModelChecker.doModelCheck(machine); // the operation BlockSubstitution will finally violate the invariant x<=2 assertEquals(false, result); } @Test public void testLeuschelPerformanceMachines1() throws Exception { MachineNode simpleMachineWithViolation = Parser.getMachineFileAsSemanticAst(dir + "/performance/CounterErr.mch"); boolean result = ModelChecker.doModelCheck(simpleMachineWithViolation); assertEquals(false, result); } @Test @Ignore public void testLeuschelPerformanceMachines2() throws Exception { MachineNode simpleMachineWithoutViolation = Parser.getMachineFileAsSemanticAst(dir + "/performance/SimpleSetIncrease.mch"); boolean result = ModelChecker.doModelCheck(simpleMachineWithoutViolation); assertEquals(false, result); } }
package io.teiler.api.service; import java.lang.reflect.Field; import org.junit.Assert; import org.junit.Test; public class GroupServiceTest { private static final String ENTROPY_BITS_CONSTANT_NAME = "ENTROPY_BITS_IN_ONE_CHARACTER"; private static final int ENTROPY_BITS_IN_ONE_CHARACTER_EXPECTED = 5; @Test public void testThatEntropyBitsAreStillSetToFive() throws NoSuchFieldException, IllegalAccessException { Field field = GroupService.class.getDeclaredField(ENTROPY_BITS_CONSTANT_NAME); Class<?> fieldType = field.getType(); field.setAccessible(true); // make sure we can access the value of the private field Assert.assertEquals(int.class, fieldType); Assert.assertEquals("You can't change mathematical facts.", ENTROPY_BITS_IN_ONE_CHARACTER_EXPECTED, field.getInt(null)); } }
package io.vertx.ext.consul.suite; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.http.HttpServerResponse; import io.vertx.ext.consul.ConsulClient; import io.vertx.ext.consul.ConsulClientOptions; import io.vertx.ext.consul.ConsulTestBase; import io.vertx.ext.consul.Utils; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Test; import org.junit.runner.RunWith; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * @author <a href="mailto:ruslan.sennov@gmail.com">Ruslan Sennov</a> */ @RunWith(VertxUnitRunner.class) public class BrokenConsul extends ConsulTestBase { @Test public void timeout(TestContext tc) { SlowHttpServer slowConsul = new SlowHttpServer(vertx, 10000); ConsulClient client = ctx.createClient(new ConsulClientOptions().setPort(slowConsul.port()).setTimeout(1000)); client.agentInfo(tc.asyncAssertFailure(t -> { ctx.closeClient(client); slowConsul.close(); tc.assertTrue(t.getMessage().contains("The timeout period of 1000ms")); })); } @Test public void closedConnection(TestContext tc) { BrokenHttpServer brokenConsul = new BrokenHttpServer(vertx); ConsulClient client = ctx.createClient(new ConsulClientOptions().setPort(brokenConsul.port())); client.agentInfo(tc.asyncAssertFailure(t -> { ctx.closeClient(client); brokenConsul.close(); tc.assertTrue(t.getMessage().contains("Connection was closed")); })); } static class SlowHttpServer extends CustomHttpServer { SlowHttpServer(Vertx vertx, long delay) { super(vertx, h -> vertx.setTimer(delay, t -> h.response().end())); } } static class BrokenHttpServer extends CustomHttpServer { BrokenHttpServer(Vertx vertx) { super(vertx, h -> { HttpServerResponse resp = h.response(); resp.putHeader(HttpHeaders.CONTENT_LENGTH, "10000").write("start and ... "); resp.close(); }); } } static class CustomHttpServer { private final HttpServer server; private final int port; CustomHttpServer(Vertx vertx, Handler<HttpServerRequest> handler) { this.port = Utils.getFreePort(); CountDownLatch latch = new CountDownLatch(1); this.server = vertx.createHttpServer() .requestHandler(handler) .listen(port, h -> latch.countDown()); try { latch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } int port() { return port; } void close() { server.close(); } } }
package net.folab.fo.runtime; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import java.lang.reflect.Field; import net.folab.fo.runtime._fo._lang.Boolean; import net.folab.fo.runtime._fo._lang.Integer; import org.junit.Test; import org.junit.Before; public class GeneratedCodeTest { private Class<?> genClass; @Before public void setUp() throws ClassNotFoundException { genClass = Class.forName("net.folab.fo.runtime._"); } @Test public void test() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { test("_a", Integer.valueOf(1)); test("_b", Integer.valueOf(2)); test("_c", Integer.valueOf(3)); test("_d", Integer.valueOf(4)); test("_e", Integer.valueOf(5)); test("_f", Boolean.FALSE); test("_t", Boolean.TRUE); } public <T extends Evaluable<T>> void test(String name, Evaluable<T> expected) throws NoSuchFieldException, IllegalAccessException { Field field = genClass.getField(name); @SuppressWarnings("unchecked") Evaluable<T> value = (Evaluable<T>) field.get(null); assertThat(value.evaluate(), is(expected)); } }
import java.util.*; import java.time.*; import org.junit.*; import org.hamcrest.Matcher; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import net.quasardb.qdb.ts.*; import net.quasardb.qdb.*; public class WriterTest { @Test public void canGetWriter() throws Exception { String alias = Helpers.createUniqueAlias(); Column[] definition = { new Column.Double (alias) }; Writer writer = Helpers.createTimeSeries(definition).tableWriter(); } @Test public void canFlushWriter() throws Exception { String alias = Helpers.createUniqueAlias(); Column[] definition = { new Column.Double (alias) }; Writer writer = Helpers.createTimeSeries(definition).tableWriter(); writer.flush(); } @Test public void canLookupTableOffsetById() throws Exception { Column[] columns = { new Column.Double(Helpers.createUniqueAlias()), new Column.Double(Helpers.createUniqueAlias()), new Column.Double(Helpers.createUniqueAlias()), new Column.Double(Helpers.createUniqueAlias()), new Column.Double(Helpers.createUniqueAlias()), new Column.Double(Helpers.createUniqueAlias()), new Column.Double(Helpers.createUniqueAlias()), new Column.Double(Helpers.createUniqueAlias()) }; Session session = Helpers.getSession(); Table table1 = Helpers.createTable(columns); Table table2 = Helpers.createTable(columns); Tables tables = new Tables(new Table[] {table1, table2}); Writer writer = Tables.writer(session, tables); assertThat(writer.tableIndexByName(table1.getName()), equalTo(0)); assertThat(writer.tableIndexByName(table2.getName()), equalTo(columns.length)); } @Test public void canCloseWriter() throws Exception { String alias = Helpers.createUniqueAlias(); Column[] definition = { new Column.Double (alias) }; Writer writer = Helpers.createTimeSeries(definition).tableWriter(); writer.close(); } @Test public void canInsertDoubleRow() throws Exception { String alias = Helpers.createUniqueAlias(); Column[] definition = { new Column.Double (alias) }; QdbTimeSeries series = Helpers.createTimeSeries(definition); Writer writer = series.tableWriter(); Value[] values = { Value.createDouble(Helpers.randomDouble()) }; Timespec timestamp = new Timespec(LocalDateTime.now()); Row row = new Row(timestamp, values); writer.append(row); writer.flush(); TimeRange[] ranges = { new TimeRange(timestamp, timestamp.plusNanos(1)) }; QdbDoubleColumnCollection results = series.getDoubles(alias, ranges); assertThat(results.size(), (is(1))); assertThat(results.get(0).getValue(), equalTo(values[0].getDouble())); } @Test public void canInsertMultipleDoubleRows() throws Exception { String alias = Helpers.createUniqueAlias(); Column[] definition = { new Column.Double (alias) }; QdbTimeSeries series = Helpers.createTimeSeries(definition); Writer writer = series.tableWriter(); int ROW_COUNT = 100000; Row[] rows = new Row[ROW_COUNT]; for (int i = 0; i < rows.length; ++i) { rows[i] = new Row (LocalDateTime.now(), new Value[] { Value.createDouble(Helpers.randomDouble())}); writer.append(rows[i]); } writer.flush(); TimeRange[] ranges = { new TimeRange(rows[0].getTimestamp(), new Timespec(rows[(rows.length - 1)].getTimestamp().asLocalDateTime().plusNanos(1))) }; QdbDoubleColumnCollection results = series.getDoubles(alias, ranges); assertThat(results.size(), (is(rows.length))); for (int i = 0; i < rows.length; ++i) { assertThat(results.get(i).getValue(), equalTo(rows[i].getValues()[0].getDouble())); } } @Test public void canInsertBlobRow() throws Exception { String alias = Helpers.createUniqueAlias(); Column[] definition = { new Column.Blob (alias) }; QdbTimeSeries series = Helpers.createTimeSeries(definition); Writer writer = series.tableWriter(); Value[] values = { Value.createSafeBlob(Helpers.createSampleData()) }; Timespec timestamp = new Timespec(LocalDateTime.now()); Row row = new Row(timestamp, values); writer.append(row); writer.flush(); TimeRange[] ranges = { new TimeRange(timestamp, timestamp.plusNanos(1)) }; QdbBlobColumnCollection results = series.getBlobs(alias, ranges); assertThat(results.size(), (is(1))); assertThat(results.get(0).getValue(), equalTo(values[0].getBlob())); } @Test public void canInsertMultipleColumns() throws Exception { String alias1 = Helpers.createUniqueAlias(); String alias2 = Helpers.createUniqueAlias(); Column[] definition = { new Column.Double (alias1), new Column.Blob (alias2) }; QdbTimeSeries series = Helpers.createTimeSeries(definition); Writer writer = series.tableWriter(); Value[] values = { Value.createDouble(Helpers.randomDouble()), Value.createBlob(Helpers.createSampleData()) }; Timespec timestamp = new Timespec(LocalDateTime.now()); writer.append(timestamp, values); writer.flush(); TimeRange[] ranges = { new TimeRange(timestamp, timestamp.plusNanos(1)) }; QdbDoubleColumnCollection results1 = series.getDoubles(alias1, ranges); QdbBlobColumnCollection results2 = series.getBlobs(alias2, ranges); assertThat(results1.size(), (is(1))); assertThat(results2.size(), (is(1))); assertThat(results1.get(0).getValue(), equalTo(values[0].getDouble())); assertThat(results2.get(0).getValue(), equalTo(values[1].getBlob())); } @Test public void canInsertMultipleTables() throws Exception { String alias1 = Helpers.createUniqueAlias(); String alias2 = Helpers.createUniqueAlias(); String alias3 = Helpers.createUniqueAlias(); String alias4 = Helpers.createUniqueAlias(); Column[] definition1 = { new Column.Double (alias1), new Column.Blob (alias2) }; Column[] definition2 = { new Column.Double (alias3), new Column.Blob (alias4) }; Table table1 = Helpers.createTable(definition1); Table table2 = Helpers.createTable(definition2); Writer writer = Tables.writer(Helpers.getSession(), new Tables(new Table[] {table1, table2})); Value[] values1 = { Value.createDouble(Helpers.randomDouble()), Value.createBlob(Helpers.createSampleData()) }; Value[] values2 = { Value.createDouble(Helpers.randomDouble()), Value.createBlob(Helpers.createSampleData()) }; Timespec timestamp = new Timespec(LocalDateTime.now()); writer.append(table1.getName(), timestamp, values1); writer.append(table2.getName(), timestamp, values2); writer.flush(); TimeRange[] ranges = { new TimeRange(timestamp, timestamp.plusNanos(1)) }; Reader reader1 = Table.reader(Helpers.getSession(), table1.getName(), ranges); Reader reader2 = Table.reader(Helpers.getSession(), table2.getName(), ranges); assertThat(reader1.hasNext(), (is(true))); assertThat(reader2.hasNext(), (is(true))); Row row1 = reader1.next(); Row row2 = reader2.next(); assertThat(reader1.hasNext(), (is(false))); assertThat(reader2.hasNext(), (is(false))); assertThat(row1.getTimestamp(), (equalTo(timestamp))); assertThat(row1.getValues(), (equalTo(values1))); assertThat(row2.getTimestamp(), (equalTo(timestamp))); assertThat(row2.getValues(), (equalTo(values2))); } @Test public void canInsertNullColumns() throws Exception { String alias1 = Helpers.createUniqueAlias(); String alias2 = Helpers.createUniqueAlias(); Column[] definition = { new Column.Double (alias1), new Column.Blob (alias2) }; QdbTimeSeries series = Helpers.createTimeSeries(definition); Writer writer = series.tableWriter(); Value[] values = { Value.createDouble(Helpers.randomDouble()), Value.createNull() }; Timespec timestamp = new Timespec(LocalDateTime.now()); Row row = new Row(timestamp, values); writer.append(row); writer.flush(); TimeRange[] ranges = { new TimeRange(timestamp, timestamp.plusNanos(1)) }; QdbDoubleColumnCollection results1 = series.getDoubles(alias1, ranges); QdbBlobColumnCollection results2 = series.getBlobs(alias2, ranges); assertThat(results1.size(), (is(1))); assertThat(results2.size(), (is(0))); assertThat(results1.get(0).getValue(), equalTo(values[0].getDouble())); } @Test public void canAddExtraColumnsAfterFlush() throws Exception { Session session = Helpers.getSession(); String alias1 = Helpers.createUniqueAlias(); String alias2 = Helpers.createUniqueAlias(); Column[] definition = { new Column.Double (alias1), new Column.Blob (alias2) }; Table table1 = Helpers.createTable(definition); Writer writer = Table.writer(session, table1); Timespec timestamp1 = new Timespec(LocalDateTime.now()); Timespec timestamp2 = timestamp1.plusNanos(1); Value[] values1 = { Value.createDouble(Helpers.randomDouble()), Value.createBlob(Helpers.createSampleData()) }; Value[] values2table1 = { Value.createDouble(Helpers.randomDouble()), Value.createBlob(Helpers.createSampleData()) }; Value[] values2table2 = { Value.createDouble(Helpers.randomDouble()), Value.createBlob(Helpers.createSampleData()) }; Value[] values2 = { values2table1[0], values2table1[1], values2table2[0], values2table2[1] }; Row row1 = new Row(timestamp1, values1); Row row2 = new Row(timestamp2, values2); writer.append(row1); writer.flush(); Table table2 = Helpers.createTable(definition); writer.extraTables(table2); writer.append(row2); writer.flush(); TimeRange[] ranges = { new TimeRange(timestamp1, timestamp1.plusNanos(2)) }; Reader reader1 = Table.reader(session, table1.getName(), ranges); assertThat(reader1.hasNext(), (is(true))); Row table1row1 = reader1.next(); assertThat(table1row1, (is(row1))); assertThat(reader1.hasNext(), (is(true))); Row table1row2 = reader1.next(); assertThat(Arrays.equals(table1row2.getValues(), values2table1), (is(true))); assertThat(table1row2.getTimestamp(), (is(timestamp2))); assertThat(reader1.hasNext(), (is(false))); Reader reader2 = Table.reader(session, table2.getName(), ranges); assertThat(reader2.hasNext(), (is(true))); Row table2row2 = reader2.next(); assertThat(Arrays.equals(table2row2.getValues(), values2table2), (is(true))); assertThat(table2row2.getTimestamp(), (is(timestamp2))); assertThat(reader2.hasNext(), (is(false))); } @Test public void writerIsFlushed_whenClosed() throws Exception { String alias = Helpers.createUniqueAlias(); Column[] definition = { new Column.Double (alias) }; QdbTimeSeries series = Helpers.createTimeSeries(definition); Writer writer = series.autoFlushTableWriter(); Value[] values = { Value.createDouble(Helpers.randomDouble()) }; Timespec timestamp = new Timespec(LocalDateTime.now()); Row row = new Row(timestamp, values); writer.append(row); writer.close(); TimeRange[] ranges = { new TimeRange(timestamp, timestamp.plusNanos(1)) }; QdbDoubleColumnCollection results = series.getDoubles(alias, ranges); assertThat(results.size(), (is(1))); assertThat(results.get(0).getValue(), equalTo(values[0].getDouble())); } @Test public void autoFlushWriter_isFlushed_whenThresholdReached() throws Exception { String alias = Helpers.createUniqueAlias(); Column[] definition = { new Column.Double (alias) }; QdbTimeSeries series = Helpers.createTimeSeries(definition); Writer writer = series.autoFlushTableWriter(2); Value[] values = { Value.createDouble(Helpers.randomDouble()) }; Timespec timestamp = new Timespec(LocalDateTime.now()); Row row = new Row(timestamp, values); writer.append(row); TimeRange[] ranges = { new TimeRange(timestamp, timestamp.plusNanos(1)) }; QdbDoubleColumnCollection results = series.getDoubles(alias, ranges); assertThat(results.size(), (is(0))); // Add another row, which should trigger flush writer.append(row); results = series.getDoubles(alias, ranges); assertThat(results.size(), (is(2))); assertThat(results.get(0).getValue(), equalTo(values[0].getDouble())); assertThat(results.get(1).getValue(), equalTo(values[0].getDouble())); } }
package net.sf.gaboto.entities.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Collection; import java.util.Iterator; import net.sf.gaboto.test.TimeUtils; import org.junit.BeforeClass; import org.junit.Test; import org.oucs.gaboto.GabotoConfiguration; import org.oucs.gaboto.GabotoLibrary; import org.oucs.gaboto.entities.GabotoEntity; import org.oucs.gaboto.entities.time.GabotoTimeBasedEntity; import org.oucs.gaboto.exceptions.EntityAlreadyExistsException; import org.oucs.gaboto.exceptions.EntityDoesNotExistException; import org.oucs.gaboto.exceptions.GabotoException; import org.oucs.gaboto.model.Gaboto; import org.oucs.gaboto.model.GabotoFactory; import org.oucs.gaboto.timedim.TimeInstant; import org.oucs.gaboto.timedim.TimeSpan; import uk.ac.ox.oucs.oxpoints.gaboto.entities.Building; import uk.ac.ox.oucs.oxpoints.gaboto.entities.Unit; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.vocabulary.DC_11; public class TestGaboto { @BeforeClass public static void setUp() throws Exception { GabotoLibrary.init(GabotoConfiguration.fromConfigFile()); } @Test (expected=EntityAlreadyExistsException.class) public void testAddDuplicate() throws GabotoException{ Gaboto oxp = GabotoFactory.getInMemoryGaboto(); Unit u = new Unit(); u.setUri(TimeUtils.generateRandomURI()); oxp.add(u); oxp.add(u); } @Test public void testAddRemove() throws GabotoException{ Gaboto oxp = GabotoFactory.getPersistentGaboto(); Gaboto oxp_m = GabotoFactory.getInMemoryGaboto(); Unit u = new Unit(); u.setUri(TimeUtils.generateRandomURI()); Building b = new Building(); b.setUri(TimeUtils.generateRandomURI()); b.setName("Abcdef"); // add entities oxp.add(u); oxp.add(b); // test if entities were added assertTrue(oxp_m.containsEntity(u)); assertTrue(oxp_m.containsEntity(b)); // remove entities oxp.remove(u); oxp.remove(b); // test if entities were removed assertTrue(! oxp_m.containsEntity(u)); assertTrue(! oxp_m.containsEntity(b)); } @Test public void testLoadEntity() throws GabotoException{ Gaboto oxp = GabotoFactory.getPersistentGaboto(); Gaboto oxp_m = GabotoFactory.getInMemoryGaboto(); String uri = TimeUtils.generateRandomURI(); Building b = new Building(); b.setUri(uri); b.setTimeSpan(new TimeSpan(500,1,1,200,10,10)); b.setName("Abcdef"); oxp.add(b); Building b_loaded = (Building) oxp_m.getEntity(uri, new TimeInstant(600,1,1)); assertNotNull("Should have found something", b_loaded); assertEquals(b_loaded.getName(), b.getName()); assertEquals(b_loaded.getTimeSpan(), b.getTimeSpan()); } @SuppressWarnings("unchecked") @Test public void testAddRemove2() throws GabotoException{ Gaboto oxp = GabotoFactory.getPersistentGaboto(); Unit u = new Unit(); u.setUri(TimeUtils.generateRandomURI()); // add entity oxp.add(u); Iterator it = oxp.getNamedGraphSet().findQuads(Node.ANY, Node.createURI(u.getUri()), Node.ANY, Node.ANY); assertTrue(it.hasNext()); // remove entity oxp.remove(u); it = oxp.getNamedGraphSet().findQuads(Node.ANY, Node.createURI(u.getUri()), Node.ANY, Node.ANY); assertTrue(! it.hasNext()); } @Test public void testGetEntityURIs() throws EntityDoesNotExistException{ Gaboto oxp = GabotoFactory.getInMemoryGaboto(); Collection<String> uris = oxp.getEntityURIsFor(DC_11.title); assertTrue(uris.size() > 0); int counter = 0; for(String u : uris){ if (counter++>30) continue; GabotoTimeBasedEntity tb = oxp.getEntityOverTime(u); Iterator<GabotoEntity> it = tb.iterator(); while(it.hasNext()){ GabotoEntity entity = it.next(); Object titleO = entity.getPropertyValue(DC_11.title); if(! (titleO instanceof String)) continue; String title = (String) titleO; assertTrue(oxp.getEntityURIsFor(DC_11.title, title).contains(u)); // time based Collection<GabotoTimeBasedEntity> tbEntities = oxp.loadEntitiesOverTimeWithProperty(DC_11.title, title); assertTrue(tbEntities.size() > 0); } } } }
package org.hibernate.examples; import lombok.extern.slf4j.Slf4j; import org.hibernate.examples.config.JpaHSqlConfiguration; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.persistence.EntityManagerFactory; /** * org.hibernate.examples.AbstractJpaTest * * @author sunghyouk.bae@gmail.com * @since 2013. 11. 27. 5:45 */ @Slf4j @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { JpaHSqlConfiguration.class }) public abstract class AbstractJpaTest { @Autowired protected EntityManagerFactory emf; }
package org.psjava.example; import junit.framework.Assert; import org.junit.Test; import org.psjava.algo.search.BinarySearchFirst; import org.psjava.algo.search.BinarySearchFirstFalse; import org.psjava.algo.search.BinarySearchFirstInArray; import org.psjava.algo.search.BinarySearchFirstTrue; import org.psjava.algo.search.BinarySearchLast; import org.psjava.algo.search.BinarySearchLastFalse; import org.psjava.algo.search.BinarySearchLastInArray; import org.psjava.algo.search.BinarySearchLastTrue; import org.psjava.ds.array.MutableArray; import org.psjava.ds.array.MutableArrayFromValues; import org.psjava.javautil.DefaultComparator; import org.psjava.javautil.ReversedComparator; import org.psjava.math.Function; import org.psjava.math.ns.IntegerNumberSystem; public class BinarySearchExample { @Test public void example() { // Search a value 5 in increasing int array. result is the position = 2 MutableArray<Integer> array1 = MutableArrayFromValues.create(1, 3, 5, 7, 9); int res1 = BinarySearchFirstInArray.search(array1, new DefaultComparator<Integer>(), 5, -1); // Following is an example for decresing array. // You can use the reversed comparator. MutableArray<Integer> array2 = MutableArrayFromValues.create(9, 7, 5, 3, 1); int res2 = BinarySearchFirstInArray.search(array2, ReversedComparator.wrap(new DefaultComparator<Integer>()), 3, -1); // You don't have to prepare an array. Any function is enough. int res3 = BinarySearchFirst.search(IntegerNumberSystem.getInstance(), new Function<Integer, Integer>() { @Override public Integer get(Integer input) { return input * 8; } }, new DefaultComparator<Integer>(), 100, 200, 888, -1); // And, there are many alternatives. check them BinarySearchFirst.class.getClass(); BinarySearchFirstTrue.class.getClass(); BinarySearchFirstFalse.class.getClass(); BinarySearchFirstInArray.class.getClass(); BinarySearchLast.class.getClass(); BinarySearchLastInArray.class.getClass(); BinarySearchLastTrue.class.getClass(); BinarySearchLastFalse.class.getClass(); // these are assertion Assert.assertEquals(2, res1); Assert.assertEquals(3, res2); Assert.assertEquals(111, res3); } }
package org.robolectric.res; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import org.robolectric.R; import org.robolectric.Robolectric; import org.robolectric.TestRunners; import org.robolectric.annotation.Values; import org.robolectric.tester.android.util.ResName; import org.robolectric.util.I18nException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Arrays; import static org.robolectric.Robolectric.shadowOf; import static org.robolectric.util.TestUtil.resourceFile; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.junit.Assert.*; @RunWith(TestRunners.WithDefaults.class) public class ResourceLoaderTest { private ResourcePath resourcePath; private ResourcePath systemResourcePath; @Before public void setUp() throws Exception { resourcePath = new ResourcePath(R.class, resourceFile("res"), resourceFile("assets")); systemResourcePath = AndroidResourcePathFinder.getSystemResourcePath(Robolectric.DEFAULT_SDK_VERSION, resourcePath); } @Test public void shouldLoadSystemResources() throws Exception { ResourceLoader resourceLoader = Robolectric.getShadowApplication().getResourceLoader(); String stringValue = resourceLoader.getStringValue(resourceLoader.getResourceExtractor().getResName(android.R.string.copy), ""); assertEquals("Copy", stringValue); ViewNode node = resourceLoader.getLayoutViewNode(new ResName("android:layout/simple_spinner_item"), ""); assertNotNull(node); } @Test public void shouldLoadLocalResources() throws Exception { ResourceLoader resourceLoader = new PackageResourceLoader(resourcePath); String stringValue = resourceLoader.getStringValue(resourceLoader.getResourceExtractor().getResName(R.string.copy), ""); assertEquals("Local Copy", stringValue); } @Test(expected=I18nException.class) public void shouldThrowExceptionOnI18nStrictModeInflateView() throws Exception { shadowOf(Robolectric.application).setStrictI18n(true); ResourceLoader resourceLoader = shadowOf(Robolectric.application).getResourceLoader(); ViewGroup vg = new FrameLayout(Robolectric.application); new RoboLayoutInflater(resourceLoader).inflateView(Robolectric.application, R.layout.text_views, vg, ""); } @Test(expected=I18nException.class) public void shouldThrowExceptionOnI18nStrictModeInflatePreferences() throws Exception { shadowOf(Robolectric.application).setStrictI18n(true); ResourceLoader resourceLoader = shadowOf(Robolectric.application).getResourceLoader(); resourceLoader.inflatePreferences(Robolectric.application, R.xml.preferences); } @Test @Values(qualifiers = "doesnotexist-land-xlarge") public void testChoosesLayoutBasedOnSearchPath_respectsOrderOfPath() throws Exception { ResourceLoader resourceLoader = Robolectric.getShadowApplication().getResourceLoader(); ViewGroup viewGroup = new FrameLayout(Robolectric.application); ViewGroup view = (ViewGroup) new RoboLayoutInflater(resourceLoader).inflateView(Robolectric.application, R.layout.different_screen_sizes, viewGroup, "doesnotexist-land-xlarge"); TextView textView = (TextView) view.findViewById(android.R.id.text1); assertThat(textView.getText().toString(), equalTo("land")); } @Test public void checkForPollution1() throws Exception { checkForPollutionHelper(); } @Test public void checkForPollution2() throws Exception { checkForPollutionHelper(); } private void checkForPollutionHelper() { ResourceLoader resourceLoader = Robolectric.getShadowApplication().getResourceLoader(); ViewGroup viewGroup = new FrameLayout(Robolectric.application); ViewGroup view = (ViewGroup) new RoboLayoutInflater(resourceLoader).inflateView(Robolectric.application, R.layout.different_screen_sizes, viewGroup, ""); TextView textView = (TextView) view.findViewById(android.R.id.text1); assertThat(textView.getText().toString(), equalTo("default")); Robolectric.shadowOf(Robolectric.getShadowApplication().getResources().getConfiguration()).overrideQualifiers("land"); // testing if this pollutes the other test } @Test public void testStringsAreResolved() throws Exception { ResourceLoader resourceLoader = Robolectric.getShadowApplication().getResourceLoader(); assertThat(Arrays.asList(resourceLoader.getStringArrayValue(resourceLoader.getResourceExtractor().getResName(R.array.items), "")), hasItems("foo", "bar")); } @Test public void testStringsAreWithReferences() throws Exception { ResourceLoader resourceLoader = Robolectric.getShadowApplication().getResourceLoader(); assertThat(Arrays.asList(resourceLoader.getStringArrayValue(resourceLoader.getResourceExtractor().getResName(R.array.greetings), "")), hasItems("hola", "Hello")); } @Test public void shouldAddAndroidToSystemStringArrayName() throws Exception { ResourceLoader resourceLoader = Robolectric.getShadowApplication().getResourceLoader(); assertThat(Arrays.asList(resourceLoader.getStringArrayValue(resourceLoader.getResourceExtractor().getResName(android.R.array.emailAddressTypes), "")), hasItems("Home", "Work", "Other", "Custom")); assertThat(Arrays.asList(resourceLoader.getStringArrayValue(resourceLoader.getResourceExtractor().getResName(R.array.emailAddressTypes), "")), hasItems("Doggy", "Catty")); } @Test public void testIntegersAreResolved() throws Exception { ResourceLoader resourceLoader = Robolectric.getShadowApplication().getResourceLoader(); assertThat(resourceLoader.getIntegerArrayValue(resourceLoader.getResourceExtractor().getResName(R.array.zero_to_four_int_array), ""), equalTo(new int[]{0, 1, 2, 3, 4})); } @Test public void testEmptyArray() throws Exception { ResourceLoader resourceLoader = Robolectric.getShadowApplication().getResourceLoader(); assertThat(resourceLoader.getIntegerArrayValue(resourceLoader.getResourceExtractor().getResName(R.array.empty_int_array), "").length, equalTo(0)); } @Test public void testIntegersWithReferences() throws Exception { ResourceLoader resourceLoader = Robolectric.getShadowApplication().getResourceLoader(); assertThat(resourceLoader.getIntegerArrayValue(resourceLoader.getResourceExtractor().getResName(R.array.with_references_int_array), ""), equalTo(new int[]{0, 2000, 1})); } @Test public void shouldLoadForAllQualifiers() throws Exception { ResourceLoader resourceLoader = new PackageResourceLoader(resourcePath); assertThat(resourceLoader.getStringValue(resourceLoader.getResourceExtractor().getResName(R.string.hello), ""), equalTo("Hello")); assertThat(resourceLoader.getStringValue(resourceLoader.getResourceExtractor().getResName(R.string.hello), "fr"), equalTo("Bonjour")); } }