answer
stringlengths
17
10.2M
package org.scijava.widget; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.WeakHashMap; import org.scijava.AbstractContextual; import org.scijava.Context; import org.scijava.ItemVisibility; import org.scijava.convert.ConvertService; import org.scijava.log.LogService; import org.scijava.module.MethodCallException; import org.scijava.module.Module; import org.scijava.module.ModuleItem; import org.scijava.module.ModuleService; import org.scijava.plugin.Parameter; import org.scijava.thread.ThreadService; import org.scijava.util.NumberUtils; import org.scijava.util.Types; /** * The backing data model for a particular {@link InputWidget}. * * @author Curtis Rueden */ public class DefaultWidgetModel extends AbstractContextual implements WidgetModel { private final InputPanel<?, ?> inputPanel; private final Module module; private final ModuleItem<?> item; private final List<?> objectPool; private final Map<Object, Object> convertedObjects; @Parameter private ThreadService threadService; @Parameter private ConvertService convertService; @Parameter private ModuleService moduleService; @Parameter(required = false) private LogService log; private boolean initialized; public DefaultWidgetModel(final Context context, final InputPanel<?, ?> inputPanel, final Module module, final ModuleItem<?> item, final List<?> objectPool) { setContext(context); this.inputPanel = inputPanel; this.module = module; this.item = item; this.objectPool = objectPool; convertedObjects = new WeakHashMap<>(); if (item.getValue(module) == null) { // assign the item's default value as the current value setValue(moduleService.getDefaultValue(item)); } } @Override public InputPanel<?, ?> getPanel() { return inputPanel; } @Override public Module getModule() { return module; } @Override public ModuleItem<?> getItem() { return item; } @Override public List<?> getObjectPool() { return objectPool; } @Override public String getWidgetLabel() { // Do this dynamically. Don't cache this result. // Some controls change their labels at runtime. final String label = item.getLabel(); if (label != null && !label.isEmpty()) return label; final String name = item.getName(); return name.substring(0, 1).toUpperCase() + name.substring(1); } @Override public boolean isStyle(final String style) { final String widgetStyle = getItem().getWidgetStyle(); if (widgetStyle == null) return style == null; for (final String s : widgetStyle.split(",")) { if (s.equals(style)) return true; } return false; } @Override public Object getValue() { final Object value = item.getValue(module); if (isMultipleChoice()) return ensureValidChoice(value); if (getObjectPool().size() > 0) return ensureValidObject(value); return value; } @Override public void setValue(final Object value) { final String name = item.getName(); if (Objects.equals(item.getValue(module), value)) return; // no change // Check if a converted value is present Object convertedInput = convertedObjects.get(value); if (convertedInput != null && Objects.equals(item.getValue(module), convertedInput)) { return; // no change } // Pass the value through the convertService convertedInput = convertService.convert(value, item.getType()); // If we get a different (converted) value back, cache it weakly. if (convertedInput != value) { convertedObjects.put(value, convertedInput); } module.setInput(name, convertedInput); if (initialized) { threadService.queue(() -> { callback(); inputPanel.refresh(); // must be on AWT thread? module.preview(); }); } } @Override public void callback() { try { item.callback(module); } catch (final MethodCallException exc) { if (log != null) log.error(exc); } } @Override public Number getMin() { final Number min = toNumber(item.getMinimumValue()); if (min != null) return min; return NumberUtils.getMinimumNumber(item.getType()); } @Override public Number getMax() { final Number max = toNumber(item.getMaximumValue()); if (max != null) return max; return NumberUtils.getMaximumNumber(item.getType()); } @Override public Number getSoftMin() { final Number softMin = toNumber(item.getSoftMinimum()); if (softMin != null) return softMin; return getMin(); } @Override public Number getSoftMax() { final Number softMax = toNumber(item.getSoftMaximum()); if (softMax != null) return softMax; return getMax(); } @Override public Number getStepSize() { final Number stepSize = toNumber(item.getStepSize()); if (stepSize != null) return stepSize; return NumberUtils.toNumber("1", item.getType()); } @Override public String[] getChoices() { final List<?> choicesList = item.getChoices(); final String[] choices = new String[choicesList.size()]; for (int i = 0; i < choices.length; i++) { choices[i] = choicesList.get(i).toString(); } return choices; } @Override public String getText() { final Object value = getValue(); if (value == null) return ""; final String text = value.toString(); if (text.equals("\0")) return ""; // render null character as empty return text; } @Override public boolean isMessage() { return getItem().getVisibility() == ItemVisibility.MESSAGE; } @Override public boolean isText() { return Types.isText(getItem().getType()); } @Override public boolean isCharacter() { return Types.isCharacter(getItem().getType()); } @Override public boolean isNumber() { return Types.isNumber(getItem().getType()); } @Override public boolean isBoolean() { return Types.isBoolean(getItem().getType()); } @Override public boolean isMultipleChoice() { final List<?> choices = item.getChoices(); return choices != null && !choices.isEmpty(); } @Override public boolean isType(final Class<?> type) { return type.isAssignableFrom(getItem().getType()); } @Override public void setInitialized(final boolean initialized) { this.initialized = initialized; } @Override public boolean isInitialized() { return initialized; } // -- Helper methods -- /** * For multiple choice widgets, ensures the value is a valid choice. * * @see #getChoices() * @see ChoiceWidget */ private Object ensureValidChoice(final Object value) { return ensureValid(value, Arrays.asList(getChoices())); } /** * For object widgets, ensures the value is a valid object. * * @see #getObjectPool() * @see ObjectWidget */ private Object ensureValidObject(final Object value) { return ensureValid(value, getObjectPool()); } /** Ensures the value is on the given list. */ private Object ensureValid(final Object value, final List<?> list) { for (final Object o : list) { if (o.equals(value)) return value; // value is valid // check if value was converted and cached final Object convertedValue = convertedObjects.get(o); if (convertedValue != null && value.equals(convertedValue)) { return convertedValue; } } // value is not valid; override with the first item on the list instead final Object validValue = list.get(0); // CTR TODO: Mutating the model in a getter is dirty. Find a better way? setValue(validValue); return validValue; } /** Converts the given object to a number matching the input type. */ private Number toNumber(final Object value) { final Class<?> type = item.getType(); final Class<?> saneType = Types.box(type); return NumberUtils.toNumber(value, saneType); } }
package org.orecruncher.dsurround; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import org.apache.commons.lang3.StringUtils; import org.orecruncher.dsurround.registry.config.Profiles; import org.orecruncher.lib.ConfigProcessor; import org.orecruncher.lib.ConfigProcessor.Category; import org.orecruncher.lib.ConfigProcessor.Comment; import org.orecruncher.lib.ConfigProcessor.DefaultValue; import org.orecruncher.lib.ConfigProcessor.Hidden; import org.orecruncher.lib.ConfigProcessor.LangKey; import org.orecruncher.lib.ConfigProcessor.Option; import org.orecruncher.lib.ConfigProcessor.RangeFloat; import org.orecruncher.lib.ConfigProcessor.RangeInt; import org.orecruncher.lib.ConfigProcessor.RestartRequired; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; public final class ModOptions { public static class Trace { public static final int SOUND_PLAY = 0x1; public static final int FOOTSTEP_ACOUSTIC = 0x2; }; public static final String CATEGORY_ASM = "asm"; public static final String CONFIG_ENABLE_WEATHER = "Enable Weather Control"; public static final String CONFIG_DISABLE_ARROW_CRITICAL_TRAIL = "Disable Arrow Critical Particle Trail"; public static final String CONFIG_DISABLE_POTION_ICONS = "Disable Potion Icons in Inventory Display"; @Category(CATEGORY_ASM) @LangKey("dsurround.cfg.asm.cat.ASM") @Comment("Controls ASM transforms Dynamic Surroundings performs at startup") public static class asm { public static String PATH = null; @Option(CONFIG_ENABLE_WEATHER) @DefaultValue("true") @LangKey("dsurround.cfg.asm.EnableWeather") @Comment("Enable ASM transformations to permit weather (rain, snow, splash, dust storms, auroras)") public static boolean enableWeatherASM = true; @Option(CONFIG_DISABLE_ARROW_CRITICAL_TRAIL) @DefaultValue("true") @LangKey("dsurround.cfg.asm.DisableArrow") @Comment("Disable particle trail left by an arrow when it flies") public static boolean disableArrowParticleTrail = true; @Option(CONFIG_DISABLE_POTION_ICONS) @DefaultValue("false") @LangKey("dsurround.cfg.asm.DisablePotionIcons") @Comment("Disable Potion Icons in Inventory Display") public static boolean disablePotionIconsInInventory = false; } public static final String CATEGORY_LOGGING_CONTROL = "logging"; public static final String CONFIG_ENABLE_ONLINE_VERSION_CHECK = "Enable Online Version Check"; public static final String CONFIG_ENABLE_DEBUG_LOGGING = "Enable Debug Logging"; public static final String CONFIG_REPORT_SERVER_STATS = "Report Server Stats"; public static final String CONFIG_DEBUG_FLAG_MASK = "Debug Flag Mask"; @Category(CATEGORY_LOGGING_CONTROL) @LangKey("dsurround.cfg.logging.cat.Logging") @Comment("Defines how Dynamic Surroundings logging will behave") public static class logging { public static String PATH = null; @Option(CONFIG_ENABLE_DEBUG_LOGGING) @DefaultValue("false") @LangKey("dsurround.cfg.logging.EnableDebug") @Comment("Enables/disables debug logging of the mod") @RestartRequired public static boolean enableDebugLogging = false; @Option(CONFIG_ENABLE_ONLINE_VERSION_CHECK) @DefaultValue("true") @LangKey("dsurround.cfg.logging.VersionCheck") @Comment("Enables/disables display of version check information") @RestartRequired public static boolean enableVersionChecking = true; @Option(CONFIG_REPORT_SERVER_STATS) @DefaultValue("false") @LangKey("dsurround.cfg.logging.ServerStats") @Comment("Enables/disables reporting of server stats") public static boolean reportServerStats = false; @Option(CONFIG_DEBUG_FLAG_MASK) @DefaultValue("0") @LangKey("dsurround.cfg.logging.FlagMask") @Comment("Bitmask for toggling various debug traces") @Hidden public static int debugFlagMask = 0; } public static final String CATEGORY_RAIN = "rain"; public static final String CONFIG_VANILLA_RAIN = "Use Vanilla Algorithms"; public static final String CONFIG_USE_VANILLA_RAIN_SOUND = "Use Vanilla Rain Sound"; public static final String CONFIG_ENABLE_BACKGROUND_THUNDER = "Enable Background Thunder"; public static final String CONFIG_THUNDER_THRESHOLD = "Rain Intensity for Background Thunder"; public static final String CONFIG_RAIN_RIPPLE_STYLE = "Style of rain water ripple"; public static final String CONFIG_MIN_RAIN_STRENGTH = "Default Minimum Rain Strength"; public static final String CONFIG_MAX_RAIN_STRENGTH = "Default Maximum Rain Strength"; @Category(CATEGORY_RAIN) @LangKey("dsurround.cfg.rain.cat.Rain") @Comment("Options that control rain effects in the client") public static class rain { public static String PATH = null; @Option(CONFIG_VANILLA_RAIN) @DefaultValue("false") @LangKey("dsurround.cfg.rain.VanillaRain") @Comment("Let Vanilla handle rain intensity and time windows") @RestartRequired public static boolean doVanillaRain = false; @Option(CONFIG_USE_VANILLA_RAIN_SOUND) @DefaultValue("false") @LangKey("dsurround.cfg.rain.UseVanillaSound") @Comment("Use the Vanilla rain sound rather than the modified one") @RestartRequired(server = true, world = true) public static boolean useVanillaRainSound = false; @Option(CONFIG_RAIN_RIPPLE_STYLE) @DefaultValue("0") @LangKey("dsurround.cfg.rain.RippleStyle") @RangeInt(min = 0, max = 3) @Comment("0: original round, 1: darker round, 2: square, 3: pixelated") public static int rainRippleStyle = 3; @Option(CONFIG_ENABLE_BACKGROUND_THUNDER) @DefaultValue("true") @LangKey("dsurround.cfg.rain.EnableThunder") @Comment("Allow background thunder when storming") public static boolean allowBackgroundThunder = true; @Option(CONFIG_THUNDER_THRESHOLD) @DefaultValue("0.75") @LangKey("dsurround.cfg.rain.ThunderThreshold") @RangeFloat(min = 0) @Comment("Minimum rain intensity level for background thunder to occur") public static float stormThunderThreshold = 0.75F; @Option(CONFIG_MIN_RAIN_STRENGTH) @DefaultValue("0.0") @LangKey("dsurround.cfg.rain.MinRainStrength") @RangeFloat(min = 0.0F, max = 1.0F) @Comment("Default minimum rain strength for a dimension") public static float defaultMinRainStrength = 0.0F; @Option(CONFIG_MAX_RAIN_STRENGTH) @DefaultValue("1.0") @LangKey("dsurround.cfg.rain.MaxRainStrength") @RangeFloat(min = 0.0F, max = 1.0F) @Comment("Default maximum rain strength for a dimension") public static float defaultMaxRainStrength = 1.0F; } public static final String CATEGORY_FOG = "fog"; public static final String CONFIG_ENABLE_FOG_PROCESSING = "Enable Fog Processing"; public static final String CONFIG_ENABLE_MORNING_FOG = "Morning Fog"; public static final String CONFIG_MORNING_FOG_CHANCE = "Morning Fog Chance"; public static final String CONFIG_ENABLE_WEATHER_FOG = "Weather Fog"; public static final String CONFIG_ENABLE_BEDROCK_FOG = "Bedrock Fog"; public static final String CONFIG_ALLOW_DESERT_FOG = "Desert Fog"; public static final String CONFIG_ENABLE_ELEVATION_HAZE = "Elevation Haze"; public static final String CONFIG_ENABLE_BIOME_FOG = "Biomes Fog"; @Category(CATEGORY_FOG) @LangKey("dsurround.cfg.fog.cat.Fog") @Comment("Options that control the various fog effects in the client") public static class fog { public static String PATH = null; @Option(CONFIG_ENABLE_FOG_PROCESSING) @DefaultValue("true") @LangKey("dsurround.cfg.fog.Enable") @Comment("Enable/disable fog processing") public static boolean enableFogProcessing = true; @Option(CONFIG_ENABLE_MORNING_FOG) @DefaultValue("true") @LangKey("dsurround.cfg.fog.EnableMorning") @Comment("Show morning fog that eventually burns off") public static boolean enableMorningFog = true; @Option(CONFIG_ENABLE_WEATHER_FOG) @DefaultValue("true") @LangKey("dsurround.cfg.fog.EnableWeather") @Comment("Increase fog based on the strength of rain") public static boolean enableWeatherFog = true; @Option(CONFIG_ENABLE_BEDROCK_FOG) @DefaultValue("true") @LangKey("dsurround.cfg.fog.EnableBedrock") @Comment("Increase fog at bedrock layers") public static boolean enableBedrockFog = true; @Option(CONFIG_ALLOW_DESERT_FOG) @DefaultValue("true") @LangKey("dsurround.cfg.fog.DesertFog") @Comment("Enable/disable desert fog when raining") public static boolean allowDesertFog = true; @Option(CONFIG_ENABLE_ELEVATION_HAZE) @DefaultValue("true") @LangKey("dsurround.cfg.fog.ElevationHaze") @Comment("Higher the player elevation the more haze that is experienced") public static boolean enableElevationHaze = true; @Option(CONFIG_ENABLE_BIOME_FOG) @DefaultValue("true") @LangKey("dsurround.cfg.fog.BiomeFog") @Comment("Enable biome specific fog density and color") public static boolean enableBiomeFog = true; @Option(CONFIG_MORNING_FOG_CHANCE) @DefaultValue("1") @RangeInt(min = 1, max = 10) @LangKey("dsurround.cfg.fog.MorningFogChance") @Comment("Chance morning fog will occurs expressed as 1 in N") public static int morningFogChance = 1; } public static final String CATEGORY_GENERAL = "general"; public static final String CONFIG_EXTERNAL_SCRIPTS = "External Configuration Files"; public static final String CONFIG_STARTUP_SOUND_LIST = "Startup Sound List"; public static final String CONFIG_HIDE_CHAT_NOTICES = "Hide Chat Notices"; public static final String CONFIG_ENABLE_CLIENT_CHUNK_CACHING = "Enable Client Chunk Caching"; @Category(CATEGORY_GENERAL) @LangKey("dsurround.cfg.general.cat.General") @Comment("Miscellaneous settings") public static class general { public static String PATH = null; @Option(CONFIG_HIDE_CHAT_NOTICES) @DefaultValue("false") @LangKey("dsurround.cfg.general.HideChat") @Comment("Toggles display of Dynamic Surroundings chat notices") public static boolean hideChatNotices = false; @Option(CONFIG_EXTERNAL_SCRIPTS) @DefaultValue("") @LangKey("dsurround.cfg.general.ExternalScripts") @Comment("Configuration files for customization") public static String[] externalScriptFiles = {}; @Option(CONFIG_STARTUP_SOUND_LIST) @DefaultValue("minecraft:entity.experience_orb.pickup,minecraft:entity.chicken.egg") @LangKey("dsurround.cfg.general.StartupSounds") @Comment("Possible sounds to play when client reaches main game menu") public static String[] startupSoundList = { "minecraft:entity.experience_orb.pickup", "minecraft:entity.chicken.egg" }; @Option(CONFIG_ENABLE_CLIENT_CHUNK_CACHING) @DefaultValue("true") @Comment("Enable/disable client side chunk caching for performance") @LangKey("dsurround.cfg.general.ChunkCaching") public static boolean enableClientChunkCaching = true; } public static final String CATEGORY_AURORA = "aurora"; public static final String CONFIG_AURORA_ENABLED = "Enabled"; public static final String CONFIG_AURORA_SHADER = "Use Shaders"; @Category(CATEGORY_AURORA) @LangKey("dsurround.cfg.aurora.cat.Aurora") @Comment("Options that control Aurora behavior and rendering") public static class aurora { public static String PATH = null; @Option(CONFIG_AURORA_ENABLED) @DefaultValue("true") @LangKey("dsurround.cfg.aurora.EnableAurora") @Comment("Enable/disable Aurora processing on server/client") public static boolean auroraEnable = true; @Option(CONFIG_AURORA_SHADER) @DefaultValue("true") @LangKey("dsurround.cfg.aurora.EnableShader") @Comment("Use shader when rendering aurora") @RestartRequired(world = true) public static boolean auroraUseShader = true; } public static final String CATEGORY_BIOMES = "biomes"; public static final String CONFIG_BIOME_SEALEVEL = "Overworld Sealevel Override"; public static final String CONFIG_BIOME_ALIASES = "Biomes Alias"; public static final String CONFIG_BIOME_DIM_BLACKLIST = "Dimension Blacklist"; @Category(CATEGORY_BIOMES) @LangKey("dsurround.cfg.biomes.cat.Biomes") @Comment("Options for controlling biome sound/effects") public static class biomes { public static String PATH = null; @Option(CONFIG_BIOME_SEALEVEL) @DefaultValue("0") @LangKey("dsurround.cfg.biomes.Sealevel") @RangeInt(min = 0, max = 255) @Comment("Sealevel to set for Overworld (0 use default for World)") public static int worldSealevelOverride = 0; @Option(CONFIG_BIOME_ALIASES) @DefaultValue("") @LangKey("dsurround.cfg.biomes.Aliases") @Comment("Biomes alias list") public static String[] biomeAliases = {}; @Option(CONFIG_BIOME_DIM_BLACKLIST) @DefaultValue("") @LangKey("dsurround.cfg.biomes.DimBlacklist") @Comment("Dimension IDs where biome sounds will not be played") public static String[] dimensionBlacklist = {}; } public static final String CATEGORY_EFFECTS = "effects"; public static final String CONFIG_FX_RANGE = "Special Effect Range"; public static final String CONFIG_DISABLE_SUSPEND = "Disable Water Suspend Particles"; public static final String CONFIG_WATERFALL_CUTOFF = "Waterfall Cutoff"; public static final String CONFIG_BLOCK_EFFECT_STEAM = "Enable Steam"; public static final String CONFIG_BLOCK_EFFECT_FIRE = "Enable FireJetEffect Jets"; public static final String CONFIG_BLOCK_EFFECT_BUBBLE = "Enable Bubbles"; public static final String CONFIG_BLOCK_EFFECT_DUST = "Enable DustJetEffect Motes"; public static final String CONFIG_BLOCK_EFFECT_FOUNTAIN = "Enable FountainJetEffect"; public static final String CONFIG_BLOCK_EFFECT_FIREFLY = "Enable Fireflies"; public static final String CONFIG_BLOCK_EFFECT_SPLASH = "Enable Water Splash"; public static final String CONFIG_ENABLE_POPOFFS = "Damage Popoffs"; public static final String CONFIG_SHOW_CRIT_WORDS = "Show Crit Words"; public static final String CONFIG_ENABLE_FOOTPRINTS = "Footprints"; public static final String CONFIG_FOOTPRINT_STYLE = "Footprint Style"; public static final String CONFIG_SHOW_BREATH = "Show Frost Breath"; @Category(CATEGORY_EFFECTS) @LangKey("dsurround.cfg.effects.cat.Effects") @Comment("Options for controlling various effects") public static class effects { public static String PATH = null; @Option(CONFIG_FX_RANGE) @DefaultValue("24") @LangKey("dsurround.cfg.effects.FXRange") @RangeInt(min = 16, max = 64) @Comment("Block radius/range around player for special effect application") public static int specialEffectRange = 24; @Option(CONFIG_DISABLE_SUSPEND) @DefaultValue("false") @LangKey("dsurround.cfg.effects.Suspend") @Comment("Enable/disable water depth particle effect") @RestartRequired(server = true) public static boolean disableWaterSuspendParticle = false; @Option(CONFIG_WATERFALL_CUTOFF) @DefaultValue("0") @LangKey("dsurround.cfg.effects.WaterfallCutoff") @RangeInt(min = 0, max = 10) @Comment("Waterfall strength below which sounds will not play") public static int waterfallCutoff = 0; @Option(CONFIG_BLOCK_EFFECT_STEAM) @DefaultValue("true") @LangKey("dsurround.cfg.effects.Steam") @Comment("Enable Steam Jets where lava meets water") public static boolean enableSteamJets = true; @Option(CONFIG_BLOCK_EFFECT_FIRE) @DefaultValue("true") @LangKey("dsurround.cfg.effects.Fire") @Comment("Enable FireJetEffect Jets in lava") public static boolean enableFireJets = true; @Option(CONFIG_BLOCK_EFFECT_BUBBLE) @DefaultValue("true") @LangKey("dsurround.cfg.effects.Bubble") @Comment("Enable BubbleJetEffect Jets under water") public static boolean enableBubbleJets = true; @Option(CONFIG_BLOCK_EFFECT_DUST) @DefaultValue("true") @LangKey("dsurround.cfg.effects.Dust") @Comment("Enable DustJetEffect motes dropping from blocks") public static boolean enableDustJets = true; @Option(CONFIG_BLOCK_EFFECT_FOUNTAIN) @DefaultValue("true") @LangKey("dsurround.cfg.effects.Fountain") @Comment("Enable FountainJetEffect jets") public static boolean enableFountainJets = true; @Option(CONFIG_BLOCK_EFFECT_FIREFLY) @DefaultValue("true") @LangKey("dsurround.cfg.effects.Fireflies") @Comment("Enable Firefly effect around plants") public static boolean enableFireflies = true; @Option(CONFIG_BLOCK_EFFECT_SPLASH) @DefaultValue("true") @LangKey("dsurround.cfg.effects.Splash") @Comment("Enable Water Splash effects when water spills down") public static boolean enableWaterSplash = true; @Option(CONFIG_ENABLE_POPOFFS) @DefaultValue("true") @LangKey("dsurround.cfg.effects.Popoffs") @Comment("Controls display of damage pop-offs when an entity is damaged") public static boolean enableDamagePopoffs = true; @Option(CONFIG_SHOW_CRIT_WORDS) @DefaultValue("true") @LangKey("dsurround.cfg.effects.CritWords") @Comment("Display random power word on critical hit") public static boolean showCritWords = true; @Option(CONFIG_ENABLE_FOOTPRINTS) @DefaultValue("true") @LangKey("dsurround.cfg.effects.Footprints") @Comment("Enable player footprints") public static boolean enableFootprints = true; @Option(CONFIG_FOOTPRINT_STYLE) @DefaultValue("6") @LangKey("dsurround.cfg.effects.FootprintStyle") @Comment("0: shoe print, 1: square print, 2: horse hoof, 3: bird, 4: paw, 5: solid square, 6: lowres square") @RangeInt(min = 0, max = 6) public static int footprintStyle = 6; @Option(CONFIG_SHOW_BREATH) @DefaultValue("true") @LangKey("dsurround.cfg.effects.ShowBreath") @Comment("Show player frost breath in cold weather") public static boolean showBreath = true; } public static final String CATEGORY_SOUND = "sound"; public static final String CONFIG_ENABLE_BATTLEMUSIC = "Battle Music"; public static final String CONFIG_ENABLE_BIOME_SOUNDS = "Enable Biomes Sounds"; public static final String CONFIG_MASTER_SOUND_FACTOR = "Master Sound Scale Factor"; public static final String CONFIG_AUTO_CONFIG_CHANNELS = "Autoconfigure Channels"; public static final String CONFIG_NORMAL_CHANNEL_COUNT = "Number Normal Channels"; public static final String CONFIG_STREAMING_CHANNEL_COUNT = "Number Streaming Channels"; public static final String CONFIG_STREAM_BUFFER_SIZE = "Stream Buffer Size"; public static final String CONFIG_STREAM_BUFFER_COUNT = "Number of Stream Buffers per Channel"; public static final String CONFIG_MUTE_WHEN_BACKGROUND = "Mute when Background"; public static final String CONFIG_ENABLE_JUMP_SOUND = "Jump Sound"; public static final String CONFIG_ENABLE_EQUIP_SOUND = "Equip Sound"; public static final String CONFIG_SWORD_AS_TOOL_EQUIP_SOUND = "Sword Equip as Tool"; public static final String CONFIG_ENABLE_CRAFTING_SOUND = "Crafting Sound"; public static final String CONFIG_FOOTSTEPS_QUAD = "Footsteps as Quadruped"; public static final String CONFIG_FOOTSTEPS_CADENCE = "First Person Footstep Cadence"; public static final String CONFIG_ENABLE_ARMOR_SOUND = "Armor Sound"; public static final String CONFIG_ENABLE_SWING_SOUND = "Swing Sound"; public static final String CONFIG_ENABLE_PUDDLE_SOUND = "Rain Puddle Sound"; public static final String CONFIG_SOUND_CULL_THRESHOLD = "Sound Culling Threshold"; public static final String CONFIG_THUNDER_VOLUME = "Thunder Volume"; public static final String CONFIG_SOUND_SETTINGS = "Sound Settings"; @Category(CATEGORY_SOUND) @LangKey("dsurround.cfg.sound.cat.Sound") @Comment("General options for defining sound effects") public static class sound { public static String PATH = null; @Option(CONFIG_ENABLE_BATTLEMUSIC) @DefaultValue("false") @LangKey("dsurround.cfg.sound.BattleMusic") @Comment("Enable/disable Battle Music") public static boolean enableBattleMusic = false; @Option(CONFIG_ENABLE_BIOME_SOUNDS) @DefaultValue("true") @LangKey("dsurround.cfg.sound.BiomeSounds") @Comment("Enable biome background and spot sounds") public static boolean enableBiomeSounds = true; @Option(CONFIG_AUTO_CONFIG_CHANNELS) @DefaultValue("true") @LangKey("dsurround.cfg.sound.AutoConfig") @Comment("Automatically configure sound channels") @RestartRequired(server = true) public static boolean autoConfigureChannels = true; @Option(CONFIG_NORMAL_CHANNEL_COUNT) @DefaultValue("28") @LangKey("dsurround.cfg.sound.NormalChannels") @RangeInt(min = 28, max = 255) @Comment("Number of normal sound channels to configure in the sound system (manual)") @RestartRequired(server = true) public static int normalSoundChannelCount = 28; @Option(CONFIG_STREAMING_CHANNEL_COUNT) @DefaultValue("4") @LangKey("dsurround.cfg.sound.StreamingChannels") @RangeInt(min = 4, max = 255) @Comment("Number of streaming sound channels to configure in the sound system (manual)") @RestartRequired(server = true) public static int streamingSoundChannelCount = 4; @Option(CONFIG_STREAM_BUFFER_SIZE) @DefaultValue("16") @LangKey("dsurround.cfg.sound.StreamBufferSize") @RangeInt(min = 0) @Comment("Size of a stream buffer in kilobytes (0: system default - usually 128K bytes)") @RestartRequired(server = true) public static int streamBufferSize = 16; @Option(CONFIG_STREAM_BUFFER_COUNT) @DefaultValue("0") @LangKey("dsurround.cfg.sound.StreamBufferCount") @RangeInt(min = 0, max = 8) @Comment("Number of stream buffers per channel (0: system default - usually 3 buffers)") @RestartRequired(server = true) public static int streamBufferCount = 0; @Option(CONFIG_MUTE_WHEN_BACKGROUND) @DefaultValue("true") @LangKey("dsurround.cfg.sound.Mute") @Comment("Mute sound when Minecraft is in the background") public static boolean muteWhenBackground = true; @Option(CONFIG_THUNDER_VOLUME) @DefaultValue("10000") @LangKey("dsurround.cfg.sound.ThunderVolume") @Comment("Sound Volume of Thunder") @RangeFloat(min = 15F, max = 10000F) public static float thunderVolume = 10000F; @Option(CONFIG_ENABLE_JUMP_SOUND) @DefaultValue("false") @LangKey("dsurround.cfg.sound.Jump") @Comment("Enable player Jump sound effect") public static boolean enableJumpSound = false; @Option(CONFIG_ENABLE_EQUIP_SOUND) @DefaultValue("true") @LangKey("dsurround.cfg.sound.Equip") @Comment("Enable Weapon/Tool Equip sound effect") public static boolean enableEquipSound = true; @Option(CONFIG_SWORD_AS_TOOL_EQUIP_SOUND) @DefaultValue("false") @LangKey("dsurround.cfg.sound.SwordEquipAsTool") @Comment("Enable Sword Equip sound as Tool") @RestartRequired(world = true, server = true) public static boolean swordEquipAsTool = false; @Option(CONFIG_ENABLE_CRAFTING_SOUND) @DefaultValue("true") @LangKey("dsurround.cfg.sound.Craft") @Comment("Enable Item Crafted sound effect") public static boolean enableCraftingSound = true; @Option(CONFIG_FOOTSTEPS_QUAD) @DefaultValue("false") @LangKey("dsurround.cfg.sound.FootstepQuad") @Comment("Simulate quadruped with Footstep effects (horse)") public static boolean foostepsQuadruped = false; @Option(CONFIG_FOOTSTEPS_CADENCE) @DefaultValue("true") @LangKey("dsurround.cfg.sound.FootstepCadence") @Comment("true to match first person arm swing; false to match 3rd person leg animation") public static boolean firstPersonFootstepCadence = true; @Option(CONFIG_ENABLE_ARMOR_SOUND) @DefaultValue("true") @LangKey("dsurround.cfg.sound.Armor") @Comment("Enable/disable armor sounds when moving") public static boolean enableArmorSounds = true; @Option(CONFIG_ENABLE_SWING_SOUND) @DefaultValue("true") @LangKey("dsurround.cfg.sound.Swing") @Comment("Enable/disable item swing sounds") public static boolean enableSwingSounds = true; @Option(CONFIG_ENABLE_PUDDLE_SOUND) @DefaultValue("true") @LangKey("dsurround.cfg.sound.Puddle") @Comment("Enable/disable rain puddle sound when moving in the rain") public static boolean enablePuddleSound = true; @Option(CONFIG_SOUND_CULL_THRESHOLD) @DefaultValue("20") @LangKey("dsurround.cfg.sound.CullInterval") @RangeInt(min = 0) @Comment("Ticks between culled sound events (0 to disable culling)") public static int soundCullingThreshold = 20; @Option(CONFIG_SOUND_SETTINGS) @Hidden @DefaultValue("minecraft:block.water.ambient cull,minecraft:block.lava.ambient cull,minecraft:entity.sheep.ambient cull,minecraft:entity.chicken.ambient cull,minecraft:entity.cow.ambient cull,minecraft:entity.pig.ambient cull,dsurround:bison block,dsurround:elephant block,dsurround:gnatt block,dsurround:insectbuzz block,dsurround:hiss block,dsurround:rattlesnake block") @LangKey("dsurround.cfg.sound.SoundSettings") @Comment("Configure how each individual sound will be handled") public static String[] soundSettings = { "minecraft:block.water.ambient cull", "minecraft:block.lava.ambient cull", "minecraft:entity.sheep.ambient cull", "minecraft:entity.chicken.ambient cull", "minecraft:entity.cow.ambient cull", "minecraft:entity.pig.ambient cull", "dsurround:bison block", "dsurround:elephant block", "dsurround:gnatt block", "dsurround:insectbuzz block", "dsurround:hiss block", "dsurround:rattlesnake block"}; } public static final String CATEGORY_PLAYER = "player"; public static final String CONFIG_SUPPRESS_POTION_PARTICLES = "Suppress Potion Particles"; public static final String CONFIG_HURT_THRESHOLD = "Hurt Threshold"; public static final String CONFIG_HUNGER_THRESHOLD = "Hunger Threshold"; @Category(CATEGORY_PLAYER) @LangKey("dsurround.cfg.player.cat.Player") @Comment("General options for defining sound and effects the player entity") public static class player { public static String PATH = null; @Option(CONFIG_SUPPRESS_POTION_PARTICLES) @DefaultValue("false") @LangKey("dsurround.cfg.player.PotionParticles") @Comment("Suppress player's potion particles from rendering") public static boolean suppressPotionParticles = false; @Option(CONFIG_HURT_THRESHOLD) @DefaultValue("0.25") @LangKey("dsurround.cfg.player.HurtThreshold") @Comment("Percentage of player health bar remaining to trigger player hurt sound (0 disable)") @RangeFloat(min = 0, max = 0.5F) public static float playerHurtThreshold = 0.25F; @Option(CONFIG_HUNGER_THRESHOLD) @DefaultValue("8") @LangKey("dsurround.cfg.player.HungerThreshold") @Comment("Amount of food bar remaining to trigger player hunger sound (0 disable)") @RangeInt(min = 0, max = 10) public static int playerHungerThreshold = 8; } public static final String CATEGORY_SPEECHBUBBLES = "speechbubbles"; public static final String CONFIG_OPTION_ENABLE_SPEECHBUBBLES = "Enable SpeechBubbles"; public static final String CONFIG_OPTION_ENABLE_ENTITY_CHAT = "Enable Entity Chat"; public static final String CONFIG_OPTION_SPEECHBUBBLE_DURATION = "Display Duration"; public static final String CONFIG_OPTION_SPEECHBUBBLE_RANGE = "Visibility Range"; public static final String CONFIG_OPTION_ANIMANIA_BADGES = "Animania Badges"; @Category(CATEGORY_SPEECHBUBBLES) @LangKey("dsurround.cfg.speech.cat.Speech") @Comment("Options for configuring SpeechBubbles") public static class speechbubbles { public static String PATH = null; @Option(CONFIG_OPTION_ENABLE_SPEECHBUBBLES) @DefaultValue("false") @LangKey("dsurround.cfg.speech.EnableSpeechBubbles") @Comment("Enables/disables speech bubbles above player heads") public static boolean enableSpeechBubbles = false; @Option(CONFIG_OPTION_ENABLE_ENTITY_CHAT) @DefaultValue("false") @LangKey("dsurround.cfg.speech.EnableEntityChat") @Comment("Enables/disables entity chat bubbles") public static boolean enableEntityChat = false; @Option(CONFIG_OPTION_SPEECHBUBBLE_DURATION) @DefaultValue("7") @LangKey("dsurround.cfg.speech.Duration") @RangeFloat(min = 5.0F, max = 15.0F) @Comment("Number of seconds to display speech before removing") public static float speechBubbleDuration = 7.0F; @Option(CONFIG_OPTION_SPEECHBUBBLE_RANGE) @DefaultValue("16") @LangKey("dsurround.cfg.speech.Range") @RangeInt(min = 16, max = 32) @Comment("Range at which a SpeechBubble is visible. Filtering occurs server side.") public static float speechBubbleRange = 16; @Option(CONFIG_OPTION_ANIMANIA_BADGES) @DefaultValue("true") @LangKey("dsurround.cfg.speech.AnimaniaBadges") @Comment("Enable/disable display of food/water badges over Animania mobs") @RestartRequired(world = true, server = true) public static boolean enableAnimaniaBadges = true; } public static final String CATEGORY_COMMANDS = "commands"; public static final String CONFIG_COMMANDS_DS = "/ds"; public static final String CONFIG_COMMANDS_CALC = "/calc"; public static final String CONFIG_COMMAND_NAME = "name"; public static final String CONFIG_COMMAND_ALIAS = "alias"; @Category(CATEGORY_COMMANDS) @LangKey("dsurround.cfg.commands.cat.Commands") @Comment("Options for configuring commands") @RestartRequired(server = true, world = true) public static class commands { public static String PATH = null; @Category(CONFIG_COMMANDS_DS) public static class ds { public static String PATH = null; @Option(CONFIG_COMMAND_NAME) @DefaultValue("ds") @LangKey("dsurround.cfg.commands.DS.Name") @Comment("Name of the command") public static String commandNameDS = "ds"; @Option(CONFIG_COMMAND_ALIAS) @DefaultValue("dsurround rain") @LangKey("dsurround.cfg.commands.DS.Alias") @Comment("Alias for the command") public static String commandAliasDS = "dsurround rain"; } @Category(CONFIG_COMMANDS_CALC) public static class calc { public static String PATH = null; @Option(CONFIG_COMMAND_NAME) @DefaultValue("calc") @LangKey("dsurround.cfg.commands.Calc.Name") @Comment("Name of the command") public static String commandNameCalc = "calc"; @Option(CONFIG_COMMAND_ALIAS) @DefaultValue("c math") @LangKey("dsurround.cfg.commands.Calc.Alias") @Comment("Alias for the command") public static String commandAliasCalc = "c math"; } } public static final String CATEGORY_PROFILES = "profiles"; @Category(CATEGORY_PROFILES) @LangKey("dsurround.cfg.profiles.cat.Profiles") @Comment("Enable/disable application of built in profiles") public static class profiles { public static String PATH = null; // Dynamically created during initialization } public static void load(final Configuration config) { ConfigProcessor.process(config, ModOptions.class); if (ModBase.config() != null) Profiles.tickle(); // Iterate through the config list looking for properties without // comments. These will be scrubbed. if (ModBase.config() != null) for (final String cat : config.getCategoryNames()) { scrubCategory(config.getCategory(cat)); } } private static void scrubCategory(final ConfigCategory category) { final List<String> killList = new ArrayList<>(); for (final Entry<String, Property> entry : category.entrySet()) if (StringUtils.isEmpty(entry.getValue().getComment())) killList.add(entry.getKey()); for (final String kill : killList) category.remove(kill); } }
// Package Declaration package me.iffa.bspace.commands; // bSpace Imports import me.iffa.bspace.Space; // Bukkit Imports import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; /** * Represents "/space help". * * @author iffa */ public class SpaceHelpCommand extends SpaceCommand { /** * Constructor of SpaceHelpCommand. * * @param plugin bSpace instance * @param sender Command sender * @param args Command arguments */ public SpaceHelpCommand(Space plugin, CommandSender sender, String[] args) { super(plugin, sender, args); } /** * Does the command. */ @Override public void command() { sender.sendMessage(ChatColor.GOLD + "[bSpace] Usage:"); sender.sendMessage(ChatColor.GRAY + " /space enter [world] - Go to space (default world or given one)"); sender.sendMessage(ChatColor.GRAY + " /space back - Leave space or go back where you were in space"); sender.sendMessage(ChatColor.GRAY + " /space list - Brings up a list of all space worlds"); sender.sendMessage(ChatColor.GRAY + " /space help - Brings up this help message"); sender.sendMessage(ChatColor.GRAY + " /space about [credits] - About bSpace"); sender.sendMessage(ChatColor.GRAY + "If you have questions, please visit " + ChatColor.GOLD + "bit.ly/banspace" + ChatColor.GRAY + "!"); sender.sendMessage(ChatColor.GRAY + "...or if you prefer IRC, #iffa or #bananacode (Espernet)"); } }
package de.boxxit.stasis; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.ServiceLoader; import java.util.TreeMap; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.serializers.MapSerializer; import de.boxxit.stasis.serializer.ArraysListSerializer; import de.boxxit.stasis.serializer.CollectionsSerializers; /** * User: Christian Fruth */ public class HttpRemoteConnection extends AbstractRemoteConnection { private static final String CONTENT_TYPE_KEY = "Content-Type"; private static final String REQUEST_METHOD = "POST"; private static final String LOGIN_FUNCTION = "login"; protected abstract static class Call<T> { public CallHandler<T> handler; protected Call() { } public void callWillBegin(Synchronizer synchronizer) { synchronizer.runLater(new Runnable() { @Override public void run() { handler.callWillBegin(); } }); } public void callSucceeded(final T value, Synchronizer synchronizer) { synchronizer.runLater(new Runnable() { @Override public void run() { handler.callWillFinish(); handler.callSucceeded(value); handler.callDidFinish(); } }); } public void callFailed(final Exception ex, Synchronizer synchronizer) { synchronizer.runLater(new Runnable() { @Override public void run() { handler.callWillFinish(); handler.callFailed(ex); handler.callDidFinish(); } }); } public abstract void execute(ConnectionWorker worker); } protected static class LoginCall extends Call<Void> { public String userName; public String password; public Map<String, Object> parameters; public LoginCall() { } @Override public void execute(ConnectionWorker worker) { worker.getConnection().invokeLogin(this); } } protected static class FunctionCall extends Call<Object> { public String name; public Object[] args; public FunctionCall() { } @Override public void execute(ConnectionWorker worker) { worker.getConnection().invokeFunction(this); } } private class ConnectionWorker implements Runnable { private ConnectionWorker() { } public HttpRemoteConnection getConnection() { return HttpRemoteConnection.this; } @Override public void run() { try { while (true) { Call<?> call = pendingCalls.take(); call.callWillBegin(synchronizer); call.execute(this); } } catch (InterruptedException ex) { ex.printStackTrace(); } } } private URL url; private final Kryo kryo; private final Output output = new Output(4096); private final Input input = new Input(4096); private final BlockingQueue<Call<?>> pendingCalls = new LinkedBlockingQueue<Call<?>>(); private final ResourceBundle resourceBundle = ResourceBundle.getBundle(HttpRemoteConnection.class.getPackage().getName() + ".errors"); private CookieManager cookieManager = new CookieManager(); private String activeUserName; private String activePassword; private Map<String, Object> activeRequest; private boolean gzipAvailable = false; private int timeout = 300000; { kryo = new Kryo(); kryo.setClassLoader(Thread.currentThread().getContextClassLoader()); kryo.addDefaultSerializer(Arrays.asList().getClass(), ArraysListSerializer.class); kryo.addDefaultSerializer(TreeMap.class, MapSerializer.class); kryo.addDefaultSerializer(Collections.unmodifiableList(new ArrayList<Object>()).getClass(), CollectionsSerializers.UnmodifiableListSerializer.class); kryo.addDefaultSerializer(Collections.unmodifiableList(new LinkedList<Object>()).getClass(), CollectionsSerializers.UnmodifiableListSerializer.class); // passenden Synchronizer finden Iterator<Synchronizer> serviceIter = ServiceLoader.load(Synchronizer.class).iterator(); if (serviceIter.hasNext()) { synchronizer = serviceIter.next(); } // Kommunikations-Thread starten Thread workerThread = new Thread(new ConnectionWorker(), "Statis:HttpRemoteConnection"); workerThread.setDaemon(true); workerThread.start(); } public HttpRemoteConnection(URL url) { this.url = url; this.state = ConnectionState.Unconnected; } public void setTimeout(int timeout) { this.timeout = timeout; } public CookieManager getCookieManager() { return cookieManager; } public void setCookieManager(CookieManager cookieManager) { this.cookieManager = cookieManager; } @Override public URL getUrl() { return url; } @Override @SuppressWarnings("rawtypes") public void setDefaultSerializer(Class<? extends Serializer> defaultSerializer) { kryo.setDefaultSerializer(defaultSerializer); } @Override public <T> void register(Class<T> type, int id) { kryo.register(type, id); } @Override public <T> void register(Class<T> type, Serializer<T> serializer) { kryo.register(type, serializer); } @Override public <T> void register(Class<T> type, Serializer<T> serializer, int id) { kryo.register(type, serializer, id); } @Override public void login(CallHandler<Void> handler, String userName, String password, Map<String, Object> parameters) { LoginCall newCall = new LoginCall(); newCall.userName = userName; newCall.password = password; newCall.parameters = parameters; newCall.handler = handler; this.userName = userName; this.password = password; this.parameters = parameters; pendingCalls.add(newCall); } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> void callAsync(CallHandler<T> handler, String name, Object... args) { FunctionCall newCall = new FunctionCall(); newCall.name = name; newCall.args = args; newCall.handler = (CallHandler)handler; pendingCalls.add(newCall); } @Override public <T> T callSync(String name, Object... args) throws Exception { return invokeFunction(name, args); } protected void invokeLogin(LoginCall call) { try { invokeLogin(call.userName, call.password, call.parameters, "loginFailed"); call.callSucceeded(null, synchronizer); } catch (Exception ex) { call.callFailed(ex, synchronizer); } } protected void invokeLogin(String userName, String password, Map<String, Object> request, String errorCode) throws Exception { if (request == null) { request = Collections.emptyMap(); } else if (!(request instanceof HashMap)) { request = new HashMap<String, Object>(request); } MethodResult methodResult = internalCall(LOGIN_FUNCTION, new Object[] { userName, password, request }); switch (methodResult.getType()) { case Value: { LoginResult loginResult = (LoginResult)methodResult.getResult(); if (loginResult.getAuthenticationResult() == AuthenticationResult.Authenticated) { Map<String, Object> newRequest = new HashMap<String, Object>(request); newRequest.putAll(loginResult.getLoginResponse()); this.activeUserName = userName; this.activePassword = password; this.activeRequest = newRequest; this.state = ConnectionState.Authenticated; } else { throw createAuthenticationException(errorCode, loginResult.getLoginResponse()); } break; } case Exception: throw (Exception)methodResult.getResult(); default: throw new IllegalArgumentException("empty return values"); } } protected void invokeFunction(FunctionCall call) { try { if ((state != ConnectionState.Authenticated) && (userName != null) && (password != null)) { invokeLogin(userName, password, parameters, "loginFailed"); } try { Object returnValue = internalFunctionCall(call.name, call.args); call.callSucceeded(returnValue, synchronizer); } catch (AuthenticationMissmatchException ex) { assert activeUserName != null : "activeUserName is null"; assert activePassword != null : "activePassword is null"; assert activeRequest != null : "activeRequest is null"; invokeLogin(activeUserName, activePassword, activeRequest, "loginRepeated"); Object returnValue = internalFunctionCall(call.name, call.args); call.callSucceeded(returnValue, synchronizer); } } catch (Exception ex) { call.callFailed(ex, synchronizer); } } protected <T> T invokeFunction(String name, Object[] args) throws Exception { if ((state != ConnectionState.Authenticated) && (userName != null) && (password != null)) { invokeLogin(userName, password, parameters, "loginFailed"); } try { return internalFunctionCall(name, args); } catch (AuthenticationMissmatchException ex) { assert activeUserName != null : "activeUserName is null"; assert activePassword != null : "activePassword is null"; assert activeRequest != null : "activeRequest is null"; invokeLogin(activeUserName, activePassword, activeRequest, "loginRepeated"); return internalFunctionCall(name, args); } } @SuppressWarnings("unchecked") protected <T> T internalFunctionCall(String name, Object[] args) throws Exception { MethodResult methodResult = internalCall(name, args); switch (methodResult.getType()) { case Value: return (T)methodResult.getResult(); case Exception: throw (Exception)methodResult.getResult(); default: return null; } } @SuppressWarnings("unchecked") protected MethodResult internalCall(String name, Object[] args) throws Exception { int tryCount = 0; while (true) { HttpURLConnection connection = null; try { connection = prepareConnection(); // Service-Namen und Parameter an den Server schreiben OutputStream outputStream; if (gzipAvailable) { connection.setRequestProperty(StasisUtils.CONTENT_ENCODING_KEY, StasisUtils.GZIP_ENCODING); outputStream = new GZIPOutputStream(connection.getOutputStream()); } else { outputStream = connection.getOutputStream(); } output.setOutputStream(outputStream); kryo.writeObject(output, new MethodCall(name, state == ConnectionState.Authenticated, args)); output.close(); output.setOutputStream(null); // Antwort erwarten String contentType = connection.getContentType(); if (!StasisConstants.CONTENT_TYPE.equals(contentType)) { boolean handled = false; if (handshakeHandler != null) { handled = handshakeHandler.handleResponse(connection, this, ++tryCount); } if (!handled) { throw createException("mimeTypeMissmatch"); } continue; } boolean gzipUsed = StasisUtils.isUsingGzipEncoding(connection.getHeaderField(StasisUtils.CONTENT_ENCODING_KEY)); cookieManager.storeCookies(connection); // Antwort lesen InputStream inputStream = connection.getInputStream(); if (gzipUsed) { gzipAvailable = true; inputStream = new GZIPInputStream(inputStream); } input.setInputStream(inputStream); // Antwort aus Datenstrom lesen return kryo.readObject(input, MethodResult.class); } finally { output.close(); output.setOutputStream(null); input.close(); input.setInputStream(null); if (connection != null) { connection.disconnect(); } } } } protected HttpURLConnection prepareConnection() throws IOException { HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod(REQUEST_METHOD); connection.setRequestProperty(CONTENT_TYPE_KEY, StasisConstants.CONTENT_TYPE); connection.setRequestProperty(StasisUtils.ACCEPT_ENCODING_KEY, StasisUtils.GZIP_ENCODING); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); cookieManager.setCookies(connection); return connection; } protected StasisException createException(String id) { String message; try { message = resourceBundle.getString(id); } catch (MissingResourceException ex) { message = " } return new StasisException(id, message); } protected StasisException createAuthenticationException(String id, Map<String, Object> userInfo) { String message = resourceBundle.getString(id); return new AuthenticationException(id, message, userInfo); } }
package org.tndata.android.compass.model; import android.content.Context; import android.widget.ImageView; import org.tndata.android.compass.R; import org.tndata.android.compass.util.ImageCache; import java.io.Serializable; import java.util.ArrayList; public class Goal extends TDCBase implements Serializable, Comparable<Goal> { private static final long serialVersionUID = 7109406671934150671L; private String subtitle = ""; private String outcome = ""; private String icon_url = ""; private ArrayList<Category> categories = new ArrayList<Category>(); private ArrayList<Behavior> behaviors = new ArrayList<Behavior>(); private double progress_value = 0.0; // Only used for UserGoals public Goal() { } public Goal(int id, int order, String title, String titleSlug, String description, String html_description, String subtitle, String outcome, String iconUrl) { super(id, title, titleSlug, description, html_description); this.subtitle = subtitle; this.outcome = outcome; this.icon_url = iconUrl; this.categories = new ArrayList<Category>(); } public Goal(int id, int order, String title, String titleSlug, String description, String html_description, String subtitle, String outcome, String iconUrl, ArrayList<Category> categories) { super(id, title, titleSlug, description, html_description); this.subtitle = subtitle; this.outcome = outcome; this.icon_url = iconUrl; this.categories = categories; } public String getOutcome() { return outcome; } public void setOutcome(String outcome) { this.outcome = outcome; } public String getSubtitle() { return subtitle; } public void setSubtitle(String subtitle) { this.subtitle = subtitle; } public String getIconUrl() { return icon_url; } public void setIconUrl(String icon_url) { this.icon_url = icon_url; } public ArrayList<Category> getCategories() { return categories; } public void setCategories(ArrayList<Category> categories) { this.categories = categories; } public ArrayList<Behavior> getBehaviors() { return behaviors; } public void setBehaviors(ArrayList<Behavior> behaviors) { this.behaviors = behaviors; } public void setProgressValue(double value) { this.progress_value = value; } public double getProgressValue() { return this.progress_value; } public int getProgressIcon() { double value = getProgressValue(); if (value < 0.125) { return R.drawable.compass_9_s; } else if (value < 0.25) { return R.drawable.compass_8_sse; } else if (value < 0.375) { return R.drawable.compass_7_se; } else if (value < 0.5) { return R.drawable.compass_6_ees; } else if (value < 0.625) { return R.drawable.compass_5_e; } else if (value < 0.75) { return R.drawable.compass_4_nee; } else if (value < 0.875) { return R.drawable.compass_3_ne; } else if (value < 0.95) { return R.drawable.compass_2_nne; } else { return R.drawable.compass_1_n; } } @Override public boolean equals(Object object) { boolean result = false; if (object == null) { result = false; } else if (object == this) { result = true; } else if (object instanceof Goal) { if (this.getId() == ((Goal) object).getId()) { result = true; } } return result; } @Override public int hashCode() { int hash = 3; hash = 7 * hash + this.getTitle().hashCode(); return hash; } @Override public int compareTo(Goal another) { if (getId() == another.getId()) { return 0; } else if (getId() < another.getId()) { return -1; } else return 1; } /** * Given a Context and an ImageView, load this Goal's icon (if the user has selected * no Behaviors) or load the goal's Progress Icons. * * @param context: an application context * @param imageView: an ImageView */ public void loadIconIntoView(Context context, ImageView imageView) { String iconUrl = getIconUrl(); if(iconUrl != null && !iconUrl.isEmpty()) { ImageCache.instance(context).loadBitmap(imageView, iconUrl, false); } /* // TODO: only show goal icons (above) until we figure out what to do here. if(getBehaviors().isEmpty()) { if(iconUrl != null && !iconUrl.isEmpty()) { ImageCache.instance(context).loadBitmap(imageView, iconUrl, false); } } else { imageView.setImageResource(getProgressIcon()); } */ } }
package org.peergreen.vaadin.diagram; import static com.vaadin.ui.DragAndDropWrapper.DragStartMode; import static java.lang.String.format; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.vaadin.event.Transferable; import com.vaadin.server.Sizeable; import com.vaadin.ui.Alignment; import com.vaadin.ui.Component; import com.vaadin.ui.DragAndDropWrapper; import com.vaadin.ui.GridLayout; import com.vaadin.ui.Image; import com.vaadin.ui.Window; /** * Toolbar will allow to drag and drop images on the diagram area and then * * @author Florent Benoit */ public class Toolbar extends Window { public static final int DEFAULT_NUMBER_OF_COLUMNS = 1; public static final int DEFAULT_DISPLAYED_ROWS = 6; public static final Integer IMAGE_LENGTH = 45; public static final int PADDING = 4; private final GridLayout layout; private final int columns; private final int rows; private int imageLength; private final List<ToolbarItem> items = new ArrayList<ToolbarItem>(); public Toolbar() { this(DEFAULT_NUMBER_OF_COLUMNS, DEFAULT_DISPLAYED_ROWS); } public Toolbar(int columns, final int rows) { super("Tools"); setModal(false); setClosable(false); setResizable(false); setDraggable(true); addStyleName("diagram-toolbar"); this.columns = columns; this.rows = rows; this.layout = new GridLayout(this.columns, 1); layout.setSizeFull(); layout.setDefaultComponentAlignment(Alignment.MIDDLE_CENTER); setContent(layout); setImageLength(IMAGE_LENGTH); } public void setImageLength(final int length) { imageLength = length; setWidth(columns * (imageLength + 10), Unit.PIXELS); redraw(); } public void addEntry(final ToolbarItem item) { items.add(item); addItemInLayout(item); } public void removeEntry(ToolbarItem item) { items.remove(item); redraw(); } private void redraw() { layout.removeAllComponents(); for (ToolbarItem item : items) { addItemInLayout(item); } } private void addItemInLayout(final ToolbarItem item) { // Append the item as last entry layout.addComponent(createDragEntry(item)); layout.setHeight(Math.min(rows, layout.getRows()) * (imageLength + PADDING), Unit.PIXELS); } private Component createDragEntry(final ToolbarItem item) { Entry entry = new Entry(item); DragAndDropWrapper drag = new DragAndDropWrapper(entry) { @Override public Transferable getTransferable(final Map<String, Object> variables) { variables.put("component-type", item.getName()); return super.getTransferable(variables); } }; drag.setSizeUndefined(); drag.setDragStartMode(DragStartMode.COMPONENT); return drag; } private class Entry extends Image { private Entry(ToolbarItem item) { setSource(item.getIconResource()); setWidth(imageLength, Unit.PIXELS); setHeight(imageLength, Unit.PIXELS); setDescription(format("%s (%s Wrapper)", item.getName(), item.getDescription())); } } }
package mod.uhcreloaded.rules; import mod.uhcreloaded.util.ConfigHandler; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.event.entity.player.EntityItemPickupEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; public class EnforceNoGhastTear { private boolean isGhastTear; private int tearAmount; @SubscribeEvent(priority = EventPriority.HIGH) public void onGhastDropsTears(EntityItemPickupEvent Evt) { if (!ConfigHandler.allowGhastTear) { if (Evt.item.getEntityItem().getItem().equals(Items.ghast_tear)) { Evt.setCanceled(true); isGhastTear = true; tearAmount = Evt.item.getEntityItem().stackSize; Evt.item.setDead(); } else { isGhastTear = false; } if (isGhastTear) { for (int a = 0; a < 1; a++) { if (tearAmount > 0){ EntityItem entityItem = Evt.entityPlayer.dropPlayerItemWithRandomChoice(new ItemStack(Items.gold_ingot, tearAmount), false); entityItem.setNoPickupDelay(); entityItem.setOwner(Evt.entityPlayer.getName()); } } } } } }
/* * This is free and unencumbered software released into the public domain. */ package org.wicketsample; import org.apache.log4j.Logger; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.link.Link; import javax.servlet.http.HttpServletRequest; /* import org.apache.directory.fortress.web.control.SecUtils; import org.apache.directory.fortress.core.AccessMgr; import org.apache.directory.fortress.realm.J2eePolicyMgr; import org.apache.wicket.spring.injection.annot.SpringBean; */ /** * Base class for wicketsample project. * * @author Shawn McKinney * @version $Rev$ */ public abstract class WicketSampleBasePage extends WebPage { // TODO STEP 8a: enable spring injection of fortress bean here: /* @SpringBean private AccessMgr accessMgr; @SpringBean private J2eePolicyMgr j2eePolicyMgr; */ public WicketSampleBasePage() { // TODO STEP 8b: uncomment call to enableFortress: /* try { SecUtils.enableFortress( this, ( HttpServletRequest ) getRequest().getContainerRequest(), j2eePolicyMgr, accessMgr ); } catch (org.apache.directory.fortress.core.SecurityException se) { String error = "WicketSampleBasePage caught security exception : " + se; LOG.warn( error ); } */ // TODO STEP 8c: change to FtBookmarkablePageLink: add( new BookmarkablePageLink( "page1.link", Page1.class ) ); add( new BookmarkablePageLink( "page2.link", Page2.class ) ); add( new BookmarkablePageLink( "page3.link", Page3.class ) ); final Link actionLink = new Link( "logout.link" ) { @Override public void onClick() { setResponsePage(LogoutPage.class); } }; add( actionLink ); add( new Label( "footer", "This is free and unencumbered software released into the public domain." ) ); } /** * Used by the child pages. * * @param target for modal panel * @param msg to log and display user info */ protected void logIt(AjaxRequestTarget target, String msg) { info( msg ); LOG.info( msg ); target.appendJavaScript(";alert('" + msg + "');"); } protected static final Logger LOG = Logger.getLogger( WicketSampleBasePage.class.getName() ); }
package cn.cerc.mis.ado; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; import cn.cerc.db.core.IHandle; import cn.cerc.db.core.ISession; public class FindOneBatch<T> implements IHandle { private Map<String, Optional<T>> buffer = new HashMap<>(); private FindOneSupplierImpl<Optional<T>> findOne; private FindAllSupplierImpl<T> findAll; private List<Object[]> keys; private int keysSize; private ISession session; private boolean active; public FindOneBatch(IHandle handle, FindOneSupplierImpl<Optional<T>> findOne) { this.setSession(handle.getSession()); this.findOne = findOne; } public void prepare(Object... keys) { if (keys.length == 0) throw new IllegalArgumentException("keys is null"); if (keysSize == 0) keysSize = keys.length; else if (keysSize != keys.length) throw new IllegalArgumentException("keys size not change"); this.keys().add(keys); active = false; } public List<Object[]> keys() { if (this.keys == null) this.keys = new ArrayList<>(); return keys; } // List<Object[]>List<String> public List<String> keyList() { List<String> items = new ArrayList<>(); if (keys != null && keys.size() > 0) { if (keysSize != 1) throw new IllegalArgumentException("keysLength != 1"); if (!(keys.get(0)[0] instanceof String)) throw new IllegalArgumentException("key not is String"); this.keys().forEach(item -> items.add((String) item[0])); } return items; } public void put(Optional<T> value, String... keys) { buffer.put(String.join(".", keys), value); } public Optional<T> get(String... keys) { init(); String key = String.join(".", keys); Optional<T> result = buffer.get(key); if (result == null) { result = findOne.get(keys); buffer.put(key, result); } return result; } public String getOrDefault(Function<? super T, String> mapper, String key) { Optional<T> entity = get(key); return entity.isEmpty() ? key : mapper.apply(entity.get()); } private void init() { if (active) return; if (keys != null && keys.size() > 0 && findAll != null) findAll.load(this); active = true; } public void onInit(FindAllSupplierImpl<T> findAll) { this.findAll = findAll; } @Override public ISession getSession() { return session; } @Override public void setSession(ISession session) { this.session = session; } }
package net.darkhax.bookshelf.data; import net.darkhax.bookshelf.lib.MCColor; import net.minecraft.client.renderer.color.IBlockColor; import net.minecraft.client.renderer.color.IItemColor; import net.minecraft.world.biome.BiomeColorHelper; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; /** * A client side only class, which contains references to reusable color handlers for items and * blocks. */ @SideOnly(Side.CLIENT) public class ColorHandlers { /** * A reusable color handler which uses the hash of * {@link net.minecraft.item.ItemStack#getDisplayName()}. */ public static IItemColor ITEM_DISPLAY_NAME = (stack, index) -> stack.getDisplayName().hashCode(); /** * A reusable color handler which uses the hash of * {@link net.minecraft.item.ItemStack#getUnlocalizedName()}. */ public static IItemColor ITEM_UNLOCALIZED_NAME = (stack, index) -> stack.getUnlocalizedName().hashCode(); /** * A reusable color handler which uses the hash of the * {@link net.minecraft.item.ItemStack#toString()}. */ public static IItemColor ITEM_TO_STRING = (stack, index) -> stack.toString().hashCode(); /** * A reusable color handler which uses the hash of the * {@link net.minecraft.item.Item#getRegistryName()}. */ public static IItemColor ITEM_IDENTIFIER = (stack, index) -> stack.getItem().getRegistryName().toString().hashCode(); /** * A reusable color handler which uses the hash of the * {@link net.minecraft.nbt.NBTTagCompound#toString()}. */ public static IItemColor ITEM_NBT = (stack, index) -> stack.getTagCompound().toString().hashCode(); /** * A reusable color handler which uses a MCColor which is read from * {@link net.minecraft.item.ItemStack#getTagCompound()}; */ public static IItemColor ITEM_MCCOLOR = (stack, index) -> MCColor.isAcceptable(stack) ? new MCColor(stack).getRGB() : MCColor.WHITE.getRGB(); // Blocks /** * A reusable color handler which uses a MCColor which is read from * {@link net.minecraft.tileentity.TileEntity#getTileData()}. */ public static IBlockColor BLOCK_MCCOLOR = (state, world, pos, index) -> MCColor.isAcceptable(world, pos) ? new MCColor(world, pos).getRGB() : MCColor.WHITE.getRGB(); /** * A reusable color handler which applies the foliage color for the biome. */ public static IBlockColor BLOCK_FOLIAGE = (state, world, pos, index) -> BiomeColorHelper.getFoliageColorAtPos(world, pos); /** * A reusable color handler which applies the grass color for the biome. */ public static IBlockColor BLOCK_GRASS = (state, world, pos, index) -> BiomeColorHelper.getGrassColorAtPos(world, pos); /** * A reusable color handler which applies the water color for the biome. */ public static IBlockColor BLOCK_WATER = (state, world, pos, index) -> BiomeColorHelper.getWaterColorAtPos(world, pos); }
package org.hanuna.gitalk.swing_ui; import org.hanuna.gitalk.graph.graph_elements.GraphElement; import org.hanuna.gitalk.printmodel.GraphPrintCell; import org.hanuna.gitalk.swing_ui.render.GraphCommitCellRender; import org.hanuna.gitalk.swing_ui.render.painters.GraphCellPainter; import org.hanuna.gitalk.swing_ui.render.painters.SimpleGraphCellPainter; import org.hanuna.gitalk.ui_controller.EventsController; import org.hanuna.gitalk.ui_controller.UI_Controller; import org.hanuna.gitalk.ui_controller.table_models.GraphCommitCell; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.LineBorder; import javax.swing.plaf.BorderUIResource; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; /** * @author erokhins */ public class UI_GraphTable extends JTable { private final UI_Controller ui_controller; private final GraphCellPainter graphPainter = new SimpleGraphCellPainter(); private final MouseAdapter mouseAdapter = new MyMouseAdapter(); public UI_GraphTable(UI_Controller ui_controller) { super(ui_controller.getGraphTableModel()); UIManager.put("Table.focusCellHighlightBorder", new BorderUIResource( new LineBorder(new Color(255,0,0, 0)))); this.ui_controller = ui_controller; prepare(); } private void prepare() { setDefaultRenderer(GraphCommitCell.class, new GraphCommitCellRender(graphPainter)); setRowHeight(GraphCommitCell.HEIGHT_CELL); setShowHorizontalLines(false); setIntercellSpacing(new Dimension(0, 0)); getColumnModel().getColumn(0).setPreferredWidth(700); getColumnModel().getColumn(1).setMinWidth(90); getColumnModel().getColumn(2).setMinWidth(90); addMouseMotionListener(mouseAdapter); addMouseListener(mouseAdapter); ui_controller.addControllerListener(new EventsController.ControllerListener() { @Override public void jumpToRow(int rowIndex) { scrollRectToVisible(getCellRect(rowIndex, 0, false)); setRowSelectionInterval(rowIndex, rowIndex); scrollRectToVisible(getCellRect(rowIndex, 0, false)); } @Override public void updateTable() { updateUI(); } }); } private class MyMouseAdapter extends MouseAdapter { @Nullable private GraphElement overCell(MouseEvent e) { int rowIndex = e.getY() / GraphCommitCell.HEIGHT_CELL; int y = e.getY() - rowIndex * GraphCommitCell.HEIGHT_CELL; int x = e.getX(); GraphCommitCell commitCell = (GraphCommitCell) UI_GraphTable.this.getModel().getValueAt(rowIndex, 0); GraphPrintCell row = commitCell.getPrintCell(); return graphPainter.mouseOver(row, x, y); } @Override public void mouseClicked(MouseEvent e) { ui_controller.click(overCell(e)); } @Override public void mouseMoved(MouseEvent e) { ui_controller.over(overCell(e)); } } }
package org.petapico.nanopub.indexer; import java.io.IOException; import java.io.InputStream; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.zip.GZIPInputStream; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.nanopub.MultiNanopubRdfHandler; import org.nanopub.Nanopub; import org.nanopub.NanopubUtils; import org.nanopub.MultiNanopubRdfHandler.NanopubHandler; import org.nanopub.extra.server.GetNanopub; import org.nanopub.extra.server.NanopubServerUtils; import org.nanopub.extra.server.ServerInfo; import org.nanopub.extra.server.ServerIterator; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; public class Indexer { public static final int SECTION_HEAD = 1; public static final int SECTION_ASSERTION = 2; public static final int SECTION_PROVENANCE = 3; public static final int SECTION_PUBINFO = 4; NanopubDatabase db = null; public static List<Nanopub> nanopubs; //used by the callback function of the MultiNanopubRdfHandler class -> can we do this better? public static void main(String[] args) { args = new String[3]; args[0] = "root"; args[1] = "admin"; args[2] = "true"; if (args.length < 2){ System.out.printf("Invalid arguments expected: dbusername, dbpassword\n"); System.exit(1); } while (true){ try { Indexer indexer = new Indexer(args[0], args[1]); indexer.run(); } catch (Exception E){ System.out.println("Run error"); System.out.println(E.getMessage()); } // sleep ? } } public Indexer(String dbusername, String dbpassword) throws ClassNotFoundException, SQLException { db = new NanopubDatabase(dbusername, dbpassword); } public void run() throws IOException, RDFHandlerException, Exception { ServerIterator serverIterator = new ServerIterator(); while (serverIterator.hasNext()) { ServerInfo si = serverIterator.next(); String serverName = si.getPublicUrl(); System.out.println("=========="); System.out.println("Server: " + serverName + "\n"); //retrieve server information (from server) int peerPageSize = si.getPageSize(); //nanopubs per page long peerNanopubNo = si.getNextNanopubNo(); //number of np's stored on the server long peerJid = si.getJournalId(); //journal identifier of the server System.out.printf("Info:\n %d peerpagesize\n %d peernanopubno\n %d peerjid\n\n", peerPageSize, peerNanopubNo, peerJid); //retrieve stored server information (from database) long dbNanopubNo = db.getNextNanopubNo(serverName); //number of np's stored according to db long dbJid = db.getJournalId(serverName); //journal identifier according to db System.out.printf("Db:\n %d dbnanopubno\n %d dbjid\n", dbNanopubNo, dbJid); System.out.println("==========\n"); //Start from the beginning if (dbJid != peerJid) { dbNanopubNo = 0; db.updateJournalId(serverName, peerJid); } long currentNanopub = dbNanopubNo; System.out.printf("Starting from: %d\n", currentNanopub); long start = System.currentTimeMillis(); try { while (currentNanopub < peerNanopubNo){ int addedNanopubs = 0; int page = (int) (currentNanopub / peerPageSize) + 1; // compute the starting page if ((peerNanopubNo - currentNanopub) < peerPageSize) { System.out.println("last bits"); List<String> nanopubsOnPage = NanopubServerUtils.loadNanopubUriList(si, page); for (String artifactCode : nanopubsOnPage) { Nanopub np = GetNanopub.get(artifactCode); int insertStatus = db.npInserted(artifactCode); if (insertStatus == -1){ // not inserted insertNpInDatabase(np, artifactCode, false); } else if (insertStatus == 0){ // started but not finished insertNpInDatabase(np, artifactCode, true); } addedNanopubs ++; } } else { addedNanopubs = insertNanopubsFromPage(page, serverName); // add all nanopubs from page } currentNanopub += addedNanopubs; if (addedNanopubs < peerPageSize && currentNanopub < peerNanopubNo) { System.out.println("ERROR not enough nanopubs found on page: " + page); break; } System.out.printf("page: %d (%d/%d)\n",page, currentNanopub, peerNanopubNo); } } catch (Exception E){ System.out.println( "ERROR" ); System.out.println(E.getMessage()); } finally { System.out.println( "Updating database ") ; db.updateNextNanopubNo(serverName, currentNanopub); } long end = System.currentTimeMillis(); System.out.printf("performance estimate: %d hours\n", ((end-start))/(1000 * 60 * 24)); } } public int insertNanopubsFromPage(int page, String server) throws Exception{ int coveredNanopubs = 0; getNanopubPackage(page, server); // fills the nanopub list if (nanopubs.size() == 0) { System.out.println("ERROR no nanopubs found on page " + page); return 0; } for (Nanopub np : nanopubs) { String artifactCode = np.getUri().toString(); int insertStatus = db.npInserted(artifactCode); if (insertStatus == -1){ // not inserted insertNpInDatabase(np, artifactCode, false); } else if (insertStatus == 0){ // started but not finished //System.out.printf("ignore insert: %s\n", artifactCode); insertNpInDatabase(np, artifactCode, true); } coveredNanopubs ++; } return coveredNanopubs; } public int insertNpInDatabase(Nanopub np, String artifactCode, boolean ignore) throws IOException, SQLException{ int totalURIs = 0; if (!ignore){ db.insertNp(artifactCode); } //totalURIs += insertStatementsInDB(np.getHead(), artifactCode, stmt, SECTION_HEAD); totalURIs += insertStatementsInDB(np.getAssertion(), artifactCode, SECTION_ASSERTION, ignore); totalURIs += insertStatementsInDB(np.getProvenance(), artifactCode, SECTION_PROVENANCE, ignore); totalURIs += insertStatementsInDB(np.getPubinfo(), artifactCode, SECTION_PUBINFO, ignore); db.updateNpFinished(artifactCode); return totalURIs; } public int insertStatementsInDB(Set<Statement> statements, String artifactCode, int sectionID, boolean ignore) throws IOException, SQLException{ Set<String> URIlist = new HashSet<String>(); for (Statement statement : statements){ Value object = statement.getObject(); URI predicate = statement.getPredicate(); Resource subject = statement.getSubject(); if (object instanceof URI){ String objectStr = object.stringValue(); URIlist.add(objectStr); } if (subject instanceof URI){ String subjectStr = subject.stringValue(); URIlist.add(subjectStr); } String predicateStr = predicate.toString(); URIlist.add(predicateStr); } PreparedStatement stmt; if (ignore){ stmt = db.getInsertIgnoreStmt(); } else { stmt = db.getInsertStmt(); } stmt.setString(2, artifactCode); stmt.setInt(3, sectionID); //insert URIlist in database for (String uri : URIlist){ stmt.setString(1, uri); stmt.executeUpdate(); } return URIlist.size(); } public void getNanopubPackage(int page, String server) throws Exception{ nanopubs = new ArrayList<Nanopub>(); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5 * 1000).build(); HttpClient c = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); String nanopubPackage = server + "package.gz?page=" + page; HttpGet get = new HttpGet(nanopubPackage); get.setHeader("Accept", "application/x-gzip"); HttpResponse resp = c.execute(get); InputStream in = null; try { if (wasSuccessful(resp)) { in = new GZIPInputStream(resp.getEntity().getContent()); } else { System.out.println("Failed. Trying uncompressed package..."); // This is for compability with older versions; to be removed at some point... get = new HttpGet(server + "package.gz?page=" + page); get.setHeader("Accept", "application/trig"); resp = c.execute(get); if (!wasSuccessful(resp)) { System.out.println("HTTP request failed: " + resp.getStatusLine().getReasonPhrase()); throw new RuntimeException(resp.getStatusLine().getReasonPhrase()); } in = resp.getEntity().getContent(); } MultiNanopubRdfHandler.process(RDFFormat.TRIG, in, new NanopubHandler() { @Override public void handleNanopub(Nanopub np) { try { Indexer.nanopubs.add(np); } catch (Exception ex) { throw new RuntimeException(ex); } } }); } finally { if (in != null){ in.close(); } } } private boolean wasSuccessful(HttpResponse resp) { int c = resp.getStatusLine().getStatusCode(); return c >= 200 && c < 300; } }
package net.dean.jraw.managers; import net.dean.jraw.*; import net.dean.jraw.http.AuthenticationMethod; import net.dean.jraw.http.NetworkException; import net.dean.jraw.http.RestResponse; import net.dean.jraw.models.FlairTemplate; import net.dean.jraw.models.Submission; import net.dean.jraw.models.Thing; import net.dean.jraw.models.attr.Votable; import net.dean.jraw.util.JrawUtils; import java.util.Map; public class ModerationManager extends AbstractManager { /** * Instantiates a new AbstractManager * * @param reddit The RedditClient to use */ public ModerationManager(RedditClient reddit) { super(reddit); } /** * Sets whether or not this submission should be marked as not safe for work * * @param s The submission to modify * @param nsfw Whether or not this submission is not safe for work * @throws net.dean.jraw.http.NetworkException If the request was not successful * @throws net.dean.jraw.ApiException If the API returned an error */ @EndpointImplementation({Endpoints.MARKNSFW, Endpoints.UNMARKNSFW}) public void setNsfw(Submission s, boolean nsfw) throws NetworkException, ApiException { // "/api/marknsfw" if nsfw == true, "/api/unmarknsfw" if nsfw == false genericPost(reddit.request() .endpoint(nsfw ? Endpoints.MARKNSFW : Endpoints.UNMARKNSFW) .post(JrawUtils.mapOf( "id", s.getFullName() )).build()); } /** * Deletes a submission that you posted * * @param thing The submission to delete * @param <T> The Votable Thing to delete * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ public <T extends Thing & Votable> void delete(T thing) throws NetworkException, ApiException { delete(thing.getFullName()); } /** * Deletes a comment or submission that the authenticated user posted. Note that this call will never fail, even if * the given fullname does not exist. * * @param fullname The fullname of the submission or comment to delete * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation(Endpoints.DEL) public void delete(String fullname) throws NetworkException, ApiException { genericPost(reddit.request() .endpoint(Endpoints.DEL) .post(JrawUtils.mapOf( "id", fullname )).build()); } /** * Set or unset a self post as a sticky. You must be a moderator of the subreddit the submission was posted in for * this request to complete successfully. * * @param s The submission to set as a sticky. Must be a self post * @param sticky Whether or not to set the submission as a stickied post * @throws NetworkException If the request was not successful * @throws ApiException If the Reddit API returned an error */ @EndpointImplementation(Endpoints.SET_SUBREDDIT_STICKY) public void setSticky(Thing s, boolean sticky) throws NetworkException, ApiException { genericPost(reddit.request() .endpoint(Endpoints.SET_SUBREDDIT_STICKY) .post(JrawUtils.mapOf( "api_type", "json", "id", s.getFullName(), "state", sticky )).build()); } @EndpointImplementation(Endpoints.APPROVE) public void approve(Thing s) throws NetworkException, ApiException { genericPost(reddit.request() .endpoint(Endpoints.APPROVE) .post(JrawUtils.mapOf( "api_type", "json", "id", s.getFullName() )).build()); } @EndpointImplementation(Endpoints.REMOVE) public void remove(Thing s, boolean spam) throws NetworkException, ApiException { genericPost(reddit.request() .endpoint(Endpoints.REMOVE) .post(JrawUtils.mapOf( "api_type", "json", "id", s.getFullName(), "spam", spam )).build()); } /** * Sets the flair for the currently authenticated user * @param subreddit The subreddit to set the flair on * @param template The template to use * @param text Optional text that will be used if the FlairTemplate's text is editable. If this is null and the * template is editable, the template's default text will be used. * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ public void setFlair(String subreddit, FlairTemplate template, String text) throws NetworkException, ApiException { setFlair(subreddit, template, text, (String) null); } /** * Sets the flair for a certain user. Must be a moderator of the subreddit if the user is not the currently * authenticated user. * * @param subreddit The subreddit to set the flair on * @param template The template to use * @param text Optional text that will be used if the FlairTemplate's text is editable. If this is null and the * template is editable, the template's default text will be used. * @param username The name of the user to set the flair for. If this is null the authenticated user's name will be * used. * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ public void setFlair(String subreddit, FlairTemplate template, String text, String username) throws NetworkException, ApiException { setFlair(subreddit, template, text, null, username); } /** * Sets the flair for a certain submission. If the currently authenticated user is <em>not</em> a moderator of the * subreddit where the submission was posted, then the user must have posted the submission. * * @param subreddit The subreddit to set the flair on * @param template The template to use * @param text Optional text that will be used if the FlairTemplate's text is editable. If this is null and the * template is editable, the template's default text will be used. * @param submission The submission to set the flair for * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ public void setFlair(String subreddit, FlairTemplate template, String text, Submission submission) throws NetworkException, ApiException { setFlair(subreddit, template, text, submission, null); } @EndpointImplementation(Endpoints.SELECTFLAIR) private void setFlair(String subreddit, FlairTemplate template, String text, Submission submission, String username) throws IllegalArgumentException, NetworkException, ApiException { if (subreddit == null) { throw new IllegalArgumentException("subreddit cannot be null"); } Map<String, String> args = JrawUtils.mapOf( "api_type", "json", "flair_template_id", template.getId() ); if (submission != null) { args.put("link", submission.getFullName()); } else { if (username == null) { if (reddit.getAuthenticationMethod() == AuthenticationMethod.NOT_YET) { throw new IllegalArgumentException("Not logged in and both submission and username were null"); } if (!reddit.hasActiveUserContext()) throw new IllegalStateException("Cannot set the flair for self because there is no active user context"); username = reddit.getAuthenticatedUser(); } args.put("name", username); } if (template.isTextEditable()) { if (text == null) { // Set default text flair if none is provided text = template.getText(); } args.put("text", text); } RestResponse response = reddit.execute(reddit.request() .post(args) .path("/r/" + subreddit + Endpoints.SELECTFLAIR.getEndpoint().getUri()) .build()); if (response.hasErrors()) { throw response.getError(); } } }
package ru.ifmo.ctddev.gmwcs.solver; import ilog.concert.IloException; import ilog.concert.IloLinearNumExpr; import ilog.concert.IloNumExpr; import ilog.concert.IloNumVar; import ilog.cplex.IloCplex; import org.jgrapht.UndirectedGraph; import org.jgrapht.alg.ConnectivityInspector; import ru.ifmo.ctddev.gmwcs.LDSU; import ru.ifmo.ctddev.gmwcs.Pair; import ru.ifmo.ctddev.gmwcs.TimeLimit; import ru.ifmo.ctddev.gmwcs.graph.Edge; import ru.ifmo.ctddev.gmwcs.graph.Node; import ru.ifmo.ctddev.gmwcs.graph.Unit; import java.io.IOException; import java.io.OutputStream; import java.util.*; public class RLTSolver implements Solver { public static final double EPS = 0.01; private IloCplex cplex; private Map<Node, IloNumVar> y; private Map<Edge, IloNumVar> w; private Map<Node, IloNumVar> v; private Map<Edge, Pair<IloNumVar, IloNumVar>> t; private Map<Edge, Pair<IloNumVar, IloNumVar>> x; private Map<Node, IloNumVar> x0; private Node root; private TimeLimit tl; private int threads; private boolean suppressOutput; private UndirectedGraph<Node, Edge> graph; private double minimum; private boolean toBreak; private SolutionCallback solutionCallback; public RLTSolver(boolean toBreak) { this.toBreak = toBreak; tl = new TimeLimit(Double.POSITIVE_INFINITY); threads = 1; this.minimum = -Double.MAX_VALUE; } public void setTimeLimit(TimeLimit tl) { this.tl = tl; } public void setThreadsNum(int threads) { if (threads < 1) { throw new IllegalArgumentException(); } this.threads = threads; } public void setRoot(Node root) { this.root = root; } @Override public List<Unit> solve(UndirectedGraph<Node, Edge> graph, LDSU<Unit> synonyms) throws SolverException { this.graph = graph; try { cplex = new IloCplex(); if (suppressOutput) { OutputStream nos = new OutputStream() { @Override public void write(int b) throws IOException { } }; cplex.setOut(nos); cplex.setWarning(nos); } IloCplex.ParameterSet parameters = new IloCplex.ParameterSet(); parameters.setParam(IloCplex.IntParam.Threads, threads); parameters.setParam(IloCplex.IntParam.ParallelMode, -1); parameters.setParam(IloCplex.IntParam.MIPOrdType, 3); if (tl.getRemainingTime() <= 0) { parameters.setParam(IloCplex.DoubleParam.TiLim, EPS); } else if (tl.getRemainingTime() != Double.POSITIVE_INFINITY) { parameters.setParam(IloCplex.DoubleParam.TiLim, tl.getRemainingTime()); } cplex.tuneParam(parameters); y = new LinkedHashMap<>(); w = new LinkedHashMap<>(); v = new LinkedHashMap<>(); t = new LinkedHashMap<>(); x = new LinkedHashMap<>(); x0 = new LinkedHashMap<>(); for (Node node : graph.vertexSet()) { String nodeName = Integer.toString(node.getNum() + 1); v.put(node, cplex.intVar(0, Integer.MAX_VALUE, "v" + nodeName)); y.put(node, cplex.boolVar("y" + nodeName)); x0.put(node, cplex.boolVar("x_0_" + (node.getNum() + 1))); } for (Edge edge : graph.edgeSet()) { Node from = graph.getEdgeSource(edge); Node to = graph.getEdgeTarget(edge); String edgeName = (from.getNum() + 1) + "_" + (to.getNum() + 1); w.put(edge, cplex.boolVar("w_" + edgeName)); IloNumVar in = cplex.intVar(0, Integer.MAX_VALUE, "t_" + (to.getNum() + 1) + "_" + (from.getNum() + 1)); IloNumVar out = cplex.intVar(0, Integer.MAX_VALUE, "t_" + (from.getNum() + 1) + "_" + (to.getNum() + 1)); t.put(edge, new Pair<>(in, out)); in = cplex.intVar(0, Integer.MAX_VALUE, "x_" + (to.getNum() + 1) + "_" + (from.getNum() + 1)); out = cplex.intVar(0, Integer.MAX_VALUE, "x_" + (from.getNum() + 1) + "_" + (to.getNum() + 1)); x.put(edge, new Pair<>(in, out)); } addConstraints(graph); addObjective(graph, synonyms); long timeBefore = System.currentTimeMillis(); if (solutionCallback != null) { cplex.use(new MIPCallback()); } if (toBreak && root == null) { breakSymmetry(cplex, graph); } boolean solFound = cplex.solve(); tl.spend(Math.min(tl.getRemainingTime(), (System.currentTimeMillis() - timeBefore) / 1000.0)); if (solFound) { List<Unit> result = new ArrayList<>(); for (Node node : graph.vertexSet()) { if (cplex.getValue(y.get(node)) > EPS) { result.add(node); } } for (Edge edge : graph.edgeSet()) { if (cplex.getValue(w.get(edge)) > EPS) { result.add(edge); } } if (Utils.sum(result, synonyms) < 0.0 && root == null) { result = null; } return result; } return null; } catch (IloException e) { throw new SolverException(); } finally { cplex.end(); } } private void breakSymmetry(IloCplex cplex, UndirectedGraph<Node, Edge> graph) throws IloException { int n = graph.vertexSet().size(); IloNumVar[] rootMul = new IloNumVar[n]; IloNumVar[] nodeMul = new IloNumVar[n]; PriorityQueue<Node> nodes = new PriorityQueue<>(); nodes.addAll(graph.vertexSet()); int k = nodes.size(); for (Node node : nodes) { nodeMul[k - 1] = cplex.intVar(0, n); rootMul[k - 1] = cplex.intVar(0, n); cplex.addEq(nodeMul[k - 1], cplex.prod(k, y.get(node))); cplex.addEq(rootMul[k - 1], cplex.prod(k, x0.get(node))); k } IloNumVar rootSum = cplex.intVar(0, n); cplex.addEq(rootSum, cplex.sum(rootMul)); for (int i = 0; i < n; i++) { cplex.addGe(rootSum, nodeMul[i]); } } public void setCallback(SolutionCallback callback) { this.solutionCallback = callback; } private void addObjective(UndirectedGraph<Node, Edge> graph, LDSU<Unit> synonyms) throws IloException { Map<Unit, IloNumVar> summands = new LinkedHashMap<>(); Set<Unit> toConsider = new LinkedHashSet<>(); toConsider.addAll(graph.vertexSet()); toConsider.addAll(graph.edgeSet()); Set<Unit> visited = new LinkedHashSet<>(); for (Unit unit : toConsider) { if (visited.contains(unit)) { continue; } visited.addAll(synonyms.listOf(unit)); List<Unit> eq = synonyms.listOf(unit); if (eq.size() == 1) { summands.put(unit, getVar(unit)); continue; } IloNumVar var = cplex.boolVar(); summands.put(unit, var); int num = eq.size(); for (Unit i : eq) { if (getVar(i) == null) { num } } IloNumVar[] args = new IloNumVar[num]; int j = 0; for (Unit anEq : eq) { if (getVar(anEq) == null) { continue; } args[j++] = getVar(anEq); } if (unit.getWeight() > 0) { cplex.addLe(var, cplex.sum(args)); } else { cplex.addGe(cplex.prod(eq.size() + 0.5, var), cplex.sum(args)); } } IloNumExpr sum = unitScalProd(summands.keySet(), summands); cplex.addGe(sum, minimum); cplex.addMaximize(sum); } private IloNumVar getVar(Unit unit) { return unit instanceof Node ? y.get(unit) : w.get(unit); } @Override public void suppressOutput() { suppressOutput = true; } private void addConstraints(UndirectedGraph<Node, Edge> graph) throws IloException { sumConstraints(graph); otherConstraints(graph); componentConstraints(graph); } private void componentConstraints(UndirectedGraph<Node, Edge> graph) throws IloException { ConnectivityInspector<Node, Edge> inspector = new ConnectivityInspector<>(graph); if (inspector.connectedSets().size() <= 1) { return; } int size = inspector.connectedSets().size(); IloNumVar[] terms = new IloNumVar[size]; for (int i = 0; i < size; i++) { terms[i] = or(inspector.connectedSets().get(i)); } cplex.addLazyConstraint(cplex.le(cplex.sum(terms), 1)); } private IloNumVar or(Set<? extends Unit> units) throws IloException { int size = units.size(); IloNumVar result = cplex.boolVar(); IloNumVar[] vars = new IloNumVar[size]; int i = 0; for (Unit unit : units) { vars[i++] = unit instanceof Node ? y.get(unit) : w.get(unit); } IloNumExpr sum = cplex.sum(vars); cplex.addLe(result, sum); cplex.addGe(cplex.prod(size + 0.5, result), sum); return result; } private void otherConstraints(UndirectedGraph<Node, Edge> graph) throws IloException { int n = graph.vertexSet().size(); for (Node node : graph.vertexSet()) { cplex.addLe(cplex.sum(cplex.prod(2, y.get(node)), cplex.negative(x0.get(node))), v.get(node)); IloNumExpr sub = cplex.negative(cplex.prod(n - 1, x0.get(node))); cplex.addLe(v.get(node), cplex.sum(cplex.prod(n, y.get(node)), sub)); } // (36), (39) for (Edge edge : graph.edgeSet()) { Pair<IloNumVar, IloNumVar> arcs = x.get(edge); Node from = graph.getEdgeSource(edge); Node to = graph.getEdgeTarget(edge); cplex.addLe(cplex.sum(arcs.first, arcs.second), w.get(edge)); cplex.addLe(w.get(edge), y.get(from)); cplex.addLe(w.get(edge), y.get(to)); } List<Pair<IloNumVar, IloNumVar>> xt = new ArrayList<>(); for (Edge edge : graph.edgeSet()) { xt.add(new Pair<>(x.get(edge).first, t.get(edge).first)); xt.add(new Pair<>(x.get(edge).second, t.get(edge).second)); } for (Pair<IloNumVar, IloNumVar> p : xt) { IloNumVar xi = p.first; IloNumVar ti = p.second; cplex.addLe(xi, ti); cplex.addLe(ti, cplex.prod(n - 1, xi)); } // (37), (38) for (Node node : graph.vertexSet()) { for (Edge edge : graph.edgesOf(node)) { IloNumVar xij, xji, tij, tji; if (graph.getEdgeSource(edge) == node) { xij = x.get(edge).first; xji = x.get(edge).second; tij = t.get(edge).first; tji = t.get(edge).second; } else { xij = x.get(edge).second; xji = x.get(edge).first; tij = t.get(edge).second; tji = t.get(edge).first; } cplex.addGe(cplex.sum(xji, v.get(node), cplex.negative(y.get(node))), cplex.sum(tij, tji)); IloNumExpr left = cplex.sum(v.get(node), cplex.negative(cplex.prod(n, y.get(node)))); IloNumExpr right = cplex.sum(cplex.prod(n - 1, xij), cplex.prod(n, xji)); cplex.addLe(cplex.sum(left, right), cplex.sum(tij, tji)); } } } private void sumConstraints(UndirectedGraph<Node, Edge> graph) throws IloException { cplex.addEq(cplex.sum(x0.values().toArray(new IloNumVar[0])), 1); if (root != null) { cplex.addEq(x0.get(root), 1); } // (32) (33) for (Node node : graph.vertexSet()) { Set<Edge> edges = graph.edgesOf(node); IloNumVar xSum[] = new IloNumVar[edges.size() + 1]; IloNumVar tSum[] = new IloNumVar[edges.size()]; int i = 0; for (Edge edge : edges) { if (graph.getEdgeSource(edge) == node) { xSum[i] = x.get(edge).first; tSum[i++] = t.get(edge).first; } else { xSum[i] = x.get(edge).second; tSum[i++] = t.get(edge).second; } } xSum[xSum.length - 1] = x0.get(node); cplex.addEq(cplex.sum(xSum), y.get(node)); cplex.addEq(cplex.sum(cplex.sum(xSum), cplex.sum(tSum)), v.get(node)); } } private IloLinearNumExpr unitScalProd(Set<? extends Unit> units, Map<? extends Unit, IloNumVar> vars) throws IloException { int n = units.size(); double[] coef = new double[n]; IloNumVar[] variables = new IloNumVar[n]; int i = 0; for (Unit unit : units) { coef[i] = unit.getWeight(); variables[i++] = vars.get(unit); } return cplex.scalProd(coef, variables); } public void setLB(double lb) { this.minimum = lb; } public static abstract class SolutionCallback { public abstract void main(List<Unit> solution); } private class MIPCallback extends IloCplex.IncumbentCallback { @Override protected void main() throws IloException { if (solutionCallback == null) { return; } List<Unit> result = new ArrayList<>(); for (Node node : graph.vertexSet()) { if (getValue(y.get(node)) > EPS) { result.add(node); } } for (Edge edge : graph.edgeSet()) { if (getValue(w.get(edge)) > EPS) { result.add(edge); } } solutionCallback.main(result); } } }
package org.phoenixframework.channels; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import com.squareup.okhttp.ResponseBody; import com.squareup.okhttp.ws.WebSocket; import com.squareup.okhttp.ws.WebSocketCall; import com.squareup.okhttp.ws.WebSocketListener; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSocketFactory; import okio.Buffer; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.logging.Level; import java.util.logging.Logger; public class Socket { private static final Logger LOG = Logger.getLogger(Socket.class.getName()); public static final int RECONNECT_INTERVAL_MS = 5000; private static final int DEFAULT_HEARTBEAT_INTERVAL = 7000; private final ObjectMapper objectMapper = new ObjectMapper(); private final OkHttpClient httpClient = new OkHttpClient(); private WebSocket webSocket = null; private String endpointUri = null; private final List<Channel> channels = new ArrayList<>(); private int heartbeatInterval; private boolean reconnectOnFailure = true; private Timer timer = null; private TimerTask reconnectTimerTask = null; private TimerTask heartbeatTimerTask = null; private Set<ISocketOpenCallback> socketOpenCallbacks = Collections.newSetFromMap(new WeakHashMap<ISocketOpenCallback, Boolean>()); private Set<ISocketCloseCallback> socketCloseCallbacks = Collections.newSetFromMap(new WeakHashMap<ISocketCloseCallback, Boolean>()); private Set<IErrorCallback> errorCallbacks = Collections.newSetFromMap(new WeakHashMap<IErrorCallback, Boolean>()); private Set<IMessageCallback> messageCallbacks = Collections.newSetFromMap(new WeakHashMap<IMessageCallback, Boolean>()); private int refNo = 1; /** * Annotated WS Endpoint. Private member to prevent confusion with "onConn*" registration methods. */ private PhoenixWSListener wsListener = new PhoenixWSListener(); private ConcurrentLinkedDeque<RequestBody> sendBuffer = new ConcurrentLinkedDeque<>(); public class PhoenixWSListener implements WebSocketListener { private PhoenixWSListener() { } @Override public void onOpen(final WebSocket webSocket, final Response response) { LOG.log(Level.FINE, "WebSocket onOpen: {0}", webSocket); Socket.this.webSocket = webSocket; cancelReconnectTimer(); startHeartbeatTimer(); for (final ISocketOpenCallback callback : socketOpenCallbacks) { callback.onOpen(); } Socket.this.flushSendBuffer(); } @Override public void onMessage(final ResponseBody payload) throws IOException { LOG.log(Level.FINE, "Envelope received: {0}", payload); try { if (payload.contentType() == WebSocket.TEXT) { final Envelope envelope = objectMapper.readValue(payload.byteStream(), Envelope.class); synchronized (channels) { for (final Channel channel : channels) { if (channel.isMember(envelope.getTopic())) { channel.trigger(envelope.getEvent(), envelope); } } } for (final IMessageCallback callback : messageCallbacks) { callback.onMessage(envelope); } } } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to read message payload", e); } finally { payload.close(); } } @Override public void onPong(final Buffer payload) { LOG.log(Level.INFO, "PONG received: {0}", payload); } @Override public void onClose(final int code, final String reason) { LOG.log(Level.FINE, "WebSocket onClose {0}/{1}", new Object[]{code, reason}); Socket.this.webSocket = null; for (final ISocketCloseCallback callback : socketCloseCallbacks) { callback.onClose(); } } @Override public void onFailure(final IOException e, final Response response) { LOG.log(Level.WARNING, "WebSocket connection error", e); try { for (final IErrorCallback callback : errorCallbacks) { //TODO if there are multiple errorCallbacks do we really want to trigger //the same channel error callbacks multiple times? triggerChannelError(); callback.onError(e.toString()); } } finally { // Assume closed on failure if(Socket.this.webSocket != null) { try { Socket.this.webSocket.close(1001 /*CLOSE_GOING_AWAY*/, "EOF received"); } catch (IOException ioe) { LOG.log(Level.WARNING, "Failed to explicitly close following failure"); } finally { Socket.this.webSocket = null; } } if (reconnectOnFailure) { scheduleReconnectTimer(); } } } } private void startHeartbeatTimer(){ Socket.this.heartbeatTimerTask = new TimerTask() { @Override public void run() { LOG.log(Level.FINE, "heartbeatTimerTask run"); if(Socket.this.isConnected()) { try { Envelope envelope = new Envelope("phoenix", "heartbeat", new ObjectNode(JsonNodeFactory.instance), Socket.this.makeRef()); Socket.this.push(envelope); } catch (Exception e) { LOG.log(Level.SEVERE, "Failed to send heartbeat", e); } } } }; timer.schedule(Socket.this.heartbeatTimerTask, Socket.this.heartbeatInterval, Socket.this.heartbeatInterval); } private void cancelHeartbeatTimer(){ if (Socket.this.heartbeatTimerTask != null) { Socket.this.heartbeatTimerTask.cancel(); } } /** * Sets up and schedules a timer task to make repeated reconnect attempts at configured intervals */ private void scheduleReconnectTimer() { cancelReconnectTimer(); cancelHeartbeatTimer(); Socket.this.reconnectTimerTask = new TimerTask() { @Override public void run() { LOG.log(Level.FINE, "reconnectTimerTask run"); try { Socket.this.connect(); } catch (Exception e) { LOG.log(Level.SEVERE, "Failed to reconnect to " + Socket.this.wsListener, e); } } }; timer.schedule(Socket.this.reconnectTimerTask, RECONNECT_INTERVAL_MS); } private void cancelReconnectTimer() { if (Socket.this.reconnectTimerTask != null) { Socket.this.reconnectTimerTask.cancel(); } } public Socket(final String endpointUri) throws IOException { this(endpointUri, DEFAULT_HEARTBEAT_INTERVAL); } public Socket(final String endpointUri, final int heartbeatIntervalInMs) throws IOException { LOG.log(Level.FINE, "PhoenixSocket({0})", endpointUri); this.endpointUri = endpointUri; this.heartbeatInterval = heartbeatIntervalInMs; this.timer = new Timer("Reconnect Timer for " + endpointUri); } public void disconnect() throws IOException { LOG.log(Level.FINE, "disconnect"); if (webSocket != null) { webSocket.close(1001 /*CLOSE_GOING_AWAY*/, "Disconnected by client"); } cancelHeartbeatTimer(); cancelReconnectTimer(); } public void connect() throws IOException { LOG.log(Level.FINE, "connect"); disconnect(); final String httpUrl = this.endpointUri.replaceFirst("^ws:", "http:").replaceFirst("^wss:", "https:"); final Request request = new Request.Builder().url(httpUrl).build(); final WebSocketCall wsCall = WebSocketCall.create(httpClient, request); wsCall.enqueue(wsListener); } /** * @return true if the socket connection is connected */ public boolean isConnected() { return webSocket != null; } /** * Retrieve a channel instance for the specified topic * * @param topic The channel topic * @param payload The message payload * @return A Channel instance to be used for sending and receiving events for the topic */ public Channel chan(final String topic, final JsonNode payload) { LOG.log(Level.FINE, "chan: {0}, {1}", new Object[]{topic, payload}); final Channel channel = new Channel(topic, payload, Socket.this); synchronized (channels) { channels.add(channel); } return channel; } /** * Removes the specified channel if it is known to the socket * * @param channel The channel to be removed */ public void remove(final Channel channel) { synchronized (channels) { for (final Iterator chanIter = channels.iterator(); chanIter.hasNext(); ) { if (chanIter.next() == channel) { chanIter.remove(); break; } } } } /** * Sends a message envelope on this socket * * @param envelope The message envelope * @return This socket instance * @throws IOException Thrown if the message cannot be sent */ public Socket push(final Envelope envelope) throws IOException { LOG.log(Level.FINE, "Pushing envelope: {0}", envelope); final ObjectNode node = objectMapper.createObjectNode(); node.put("topic", envelope.getTopic()); node.put("event", envelope.getEvent()); node.put("ref", envelope.getRef()); node.set("payload", envelope.getPayload() == null ? objectMapper.createObjectNode() : envelope.getPayload()); final String json = objectMapper.writeValueAsString(node); LOG.log(Level.FINE, "Sending JSON: {0}", json); RequestBody body = RequestBody.create(WebSocket.TEXT, json); if (this.isConnected()) { try { webSocket.sendMessage(body); } catch(IllegalStateException e) { LOG.log(Level.SEVERE, "Attempted to send push when socket is not open", e); } } else { this.sendBuffer.add(body); } return this; } /** * Register a callback for SocketEvent.OPEN events * * @param callback The callback to receive OPEN events * @return This Socket instance */ public Socket onOpen(final ISocketOpenCallback callback) { cancelReconnectTimer(); this.socketOpenCallbacks.add(callback); return this; } /** * Register a callback for SocketEvent.ERROR events * * @param callback The callback to receive CLOSE events * @return This Socket instance */ public Socket onClose(final ISocketCloseCallback callback) { this.socketCloseCallbacks.add(callback); return this; } /** * Register a callback for SocketEvent.ERROR events * * @param callback The callback to receive ERROR events * @return This Socket instance */ public Socket onError(final IErrorCallback callback) { this.errorCallbacks.add(callback); return this; } /** * Register a callback for SocketEvent.MESSAGE events * * @param callback The callback to receive MESSAGE events * @return This Socket instance */ public Socket onMessage(final IMessageCallback callback) { this.messageCallbacks.add(callback); return this; } @Override public String toString() { return "PhoenixSocket{" + "endpointUri='" + endpointUri + '\'' + ", channels=" + channels + ", refNo=" + refNo + ", webSocket=" + webSocket + '}'; } /** * Should the socket attempt to reconnect if websocket.onFailure is called. * @param reconnectOnFailure reconnect value */ public void reconectOnFailure(final boolean reconnectOnFailure) { this.reconnectOnFailure = reconnectOnFailure; } synchronized String makeRef() { int val = refNo++; if (refNo == Integer.MAX_VALUE) { refNo = 0; } return Integer.toString(val); } private void triggerChannelError() { for (final Channel channel : channels) { channel.trigger(ChannelEvent.ERROR.getPhxEvent(), null); } } public void setSSLSocketFactory(SSLSocketFactory sslSocketFactory) { httpClient.setSslSocketFactory(sslSocketFactory); } public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { httpClient.setHostnameVerifier(hostnameVerifier); } private void flushSendBuffer() { while (this.isConnected() && !this.sendBuffer.isEmpty()) { final RequestBody body = this.sendBuffer.removeFirst(); try { this.webSocket.sendMessage(body); } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to send payload {0}", body); } } } static String replyEventName(final String ref) { return "chan_reply_" + ref; } }
package net.galaxygaming.dispenser.game; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import net.galaxygaming.dispenser.GameDispenser; import net.galaxygaming.dispenser.task.GameRunnable; import net.galaxygaming.selection.Selection; import net.galaxygaming.util.FormatUtil; import net.galaxygaming.util.LocationUtil; import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.block.BlockState; import org.bukkit.block.Sign; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.metadata.MetadataValue; import org.bukkit.metadata.Metadatable; import org.bukkit.plugin.Plugin; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Score; import org.bukkit.scoreboard.Scoreboard; import com.google.common.collect.Lists; import net.galaxygaming.dispenser.game.GameLoader; /** * @author t7seven7t */ public abstract class GameBase implements Game { /** The current game state */ protected GameState state = GameState.INACTIVE; /** Name of this game instance */ private String name; /** List of players in this game */ private List<Player> players; /** List of component names for this game */ private List<String> components; /** * The maximum number of players the game can have. * A value of 0 will be interpreted as the maximum * that a list is capable of holding. */ protected int maximumPlayers; /** The minimum number of players before the game can start */ protected int minimumPlayers; /** The length of the countdown period in seconds */ protected int countdownDuration; /** The length of the game in seconds, if -1 the game will never end */ protected int gameTime; /** The option to use a built-in scoreboard */ protected boolean useScoreboard; /** The game's scoreboard */ protected Scoreboard board; /** The board's objective */ protected Objective objective; /** The scores to be set for player. Set to less than 1 to leave out of scoreboard */ protected int playerTagScore, playerCounterScore = 0; /** The scores to be set for the time remaining. Set to less than 1 to leave out of scoreboard */ protected int timeTagScore, timeCounterScore = 0; /** The last recorded amount of players in the game */ protected int lastPlayerCount; /** The last recorded time remaining */ protected int lastTimeRemaining; /** The length of the grace period in seconds */ protected int graceDuration; private GameType type; private GameLoader loader; private FileConfiguration config; private File configFile; private ClassLoader classLoader; private Logger logger; private GameDispenser plugin; Plugin fakePlugin; private Set<Location> signs; private int counter; private int tick; public final void addSign(Location location) { Validate.notNull(location, "Location cannot be null"); signs.add(location); new GameRunnable() { @Override public void run() { updateSigns(); } }.runTask(); } public final void removeSign(Location location) { signs.remove(location); } public final void updateSigns() { Iterator<Location> it = signs.iterator(); while (it.hasNext()) { Location loc = it.next(); BlockState state = loc.getBlock().getState(); if (!(state instanceof Sign)) { it.remove(); continue; } Sign sign = (Sign) state; sign.setLine(0, "[" + getType().toString() + "]"); sign.setLine(1, getName()); sign.setLine(2, getState().getFancyName()); sign.setLine(3, FormatUtil.format("{2}{0}/{1}", getPlayers().length, maximumPlayers, ChatColor.YELLOW)); } } protected final void addComponent(String componentName) { components.add(componentName); } @Override public final List<String> getComponents() { return Lists.newArrayList(components); } @Override public void broadcast(String message, Object... objects) { String formatted = FormatUtil.format("&6" + message, objects); for (Player player : players) { player.sendMessage(formatted); } } protected final ClassLoader getClassLoader() { return classLoader; } @Override public final FileConfiguration getConfig() { return this.config; } @Override public final void save() { List<String> signLocations = Lists.newArrayList(); for (Location location : signs) { signLocations.add(LocationUtil.serializeLocation(location)); } config.set("signs", signLocations); try { this.config.save(configFile); } catch (IOException e) { getLogger().log(Level.WARNING, "Error ocurred while saving config", e); } } /** * Gives the file associated with this game's config * @return config file */ protected final File getConfigFile() { return this.configFile; } @Override public final GameLoader getGameLoader() { return this.loader; } @Override public final Logger getLogger() { return this.logger; } @Override public final GameMetadata getMetadata(Metadatable object, String key) { for (MetadataValue v : object.getMetadata(key)) { if (v instanceof GameMetadata) { GameMetadata data = (GameMetadata) v; if (data.getOwningPlugin() == fakePlugin) { return data; } } } return null; } @Override public final void removeMetadata(Metadatable object, String key) { object.removeMetadata(key, fakePlugin); } @Override public final GameDispenser getPlugin() { return this.plugin; } @Override public final GameState getState() { return this.state; } @Override public final void setState(GameState state) { this.state = state; } @Override public final GameType getType() { return this.type; } @Override public final String getName() { return this.name; } @Override public final void setName(String name) { this.name = name; } @Override public final void startCountdown() { if (getState().ordinal() >= GameState.STARTING.ordinal()) { return; } setState(GameState.STARTING); updateSigns(); counter = countdownDuration; } @Override public final void start() { if (!isSetup()) { return; } if (graceDuration > 0) { counter = graceDuration; setState(GameState.GRACE); } else { counter = gameTime; setState(GameState.ACTIVE); } onStart(); updateSigns(); } @Override public final void tick() { if (getState().ordinal() > GameState.STARTING.ordinal() && isFinished()) { end(); return; } if (tick % 20 == 0 && counter > 0) { updateScoreboard(); if (counter % 60 == 0 || (counter < 60 && counter % 30 == 0) || (counter <= 5 && counter > 0)) { if (getState().ordinal() == GameState.STARTING.ordinal()) { broadcast(type.getMessages().getMessage("game.countdown.start")); } else if (getState().ordinal() > GameState.STARTING.ordinal()) { broadcast(type.getMessages().getMessage("game.countdown.end")); } } counter if (counter <= 0) { if (getState().ordinal() == GameState.STARTING.ordinal()) { start(); } else if (getState().ordinal() == GameState.GRACE.ordinal()) { setState(GameState.ACTIVE); } else if (getState().ordinal() > GameState.GRACE.ordinal()) { end(); } } } tick++; if (tick >= 20) tick = 0; onTick(); } @Override public final void end() { setState(GameState.INACTIVE); onEnd(); updateSigns(); for (Player player : Lists.newArrayList(players.iterator())) { removePlayer(player); } } @Override public final boolean addPlayer(Player player) { if (players.size() >= maximumPlayers && maximumPlayers > 0) { return false; } if (getState().ordinal() < GameState.STARTING.ordinal()) { setState(GameState.LOBBY); } players.add(player); GameManager.getInstance().addPlayerToGame(player, this); player.setMetadata("gameLastLocation", new GameFixedMetadata(this, player.getLocation().clone())); if (players.size() >= minimumPlayers) { startCountdown(); } onPlayerJoin(player); updateSigns(); updateScoreboard(); return true; } @Override public final void removePlayer(Player player) { GameManager.getInstance().removePlayerFromGame(player); players.remove(player); player.teleport((Location) getMetadata(player, "gameLastLocation").value()); removeMetadata(player, "gameLastLocation"); updateSigns(); updateScoreboard(); } @Override public final Player[] getPlayers() { return players.toArray(new Player[players.size()]); } /* Override the following methods and let * devs choose whether to use them */ @Override public void onLoad() {} @Override public void onStart() {} @Override public void onTick() {} @Override public void onEnd() {} @Override public void onPlayerJoin(Player player) {} @Override public void onPlayerLeave(Player player) {} @Override public boolean isFinished() { return false; } @Override public boolean setComponent(String componentName, Location location) { return false; } @Override public boolean setComponent(String componentName, Selection selection) { return false; } @Override public boolean setComponent(String componentName, String[] args) { return false; } @Override public final boolean equals(Object o) { if (o == null) { return false; } if (getClass() != o.getClass()) { return false; } if (getClass() == o.getClass()) { if (this.name.equalsIgnoreCase(((GameBase) o).name)) { return true; } } else if (o.getClass() == String.class) { if (this.name.equalsIgnoreCase((String) o)) { return true; } } return false; } @Override public final int hashCode() { return name.hashCode(); } public final InputStream getResource(String fileName) { Validate.notNull(fileName, "Filename cannot be null"); try { URL url = getClassLoader().getResource(fileName); if (url == null) { return null; } URLConnection connection = url.openConnection(); connection.setUseCaches(false); return connection.getInputStream(); } catch (IOException e) { return null; } } public GameBase() { final ClassLoader classLoader = this.getClass().getClassLoader(); if (!(classLoader instanceof GameClassLoader)) { throw new IllegalStateException("JavaGame requires " + GameClassLoader.class.getName()); } } final void initialize(String name, FileConfiguration config, GameLoader loader, File file, ClassLoader classLoader) { this.name = name; this.config = config; this.loader = loader; this.configFile = file; this.classLoader = classLoader; this.logger = new GameLogger(this, GameDispenser.getInstance()); this.players = Lists.newArrayList(); this.plugin = GameDispenser.getInstance(); this.fakePlugin = new FakePlugin(); this.type = GameType.get(config.getString("type")); this.components = Lists.newArrayList(); this.lastPlayerCount = getPlayers().length; getConfig().addDefault("minimum players", 2); getConfig().addDefault("maximum players", 0); getConfig().addDefault("countdown duration", 30); getConfig().addDefault("game time", -1); getConfig().addDefault("use scoreboard", true); getConfig().addDefault("grace duration", 5); minimumPlayers = getConfig().getInt("minimum players"); maximumPlayers = getConfig().getInt("maximum players"); countdownDuration = getConfig().getInt("countdown duration"); gameTime = getConfig().getInt("game time"); useScoreboard = getConfig().getBoolean("use scoreboard"); graceDuration = getConfig().getInt("grace duration"); this.lastTimeRemaining = counter; if (getConfig().isList("signs")) { for (String location : getConfig().getStringList("signs")) { signs.add(LocationUtil.deserializeLocation(location)); } } onLoad(); if (useScoreboard) { board = Bukkit.getScoreboardManager().getNewScoreboard(); objective = board.registerNewObjective (ChatColor.translateAlternateColorCodes('&', "&6&l" + getType().toString()), "dummy"); objective.setDisplaySlot(DisplaySlot.SIDEBAR); updateScoreboard(); } onLoad(); for (String key : getConfig().getDefaults().getKeys(false)) { if (getConfig().get(key, null) == null) { getConfig().set(key, getConfig().getDefaults().get(key)); } } } protected void updateScoreboard() { if (!useScoreboard) return; if (playerTagScore > 0) { Score score = objective.getScore(ChatColor.translateAlternateColorCodes('&', "&6&lPlayers")); if (score.getScore() != playerTagScore) score.setScore(playerTagScore); } if (playerCounterScore > 0) { board.resetScores(lastPlayerCount + ""); lastPlayerCount = getPlayers().length; objective.getScore(lastPlayerCount + "").setScore(playerCounterScore); } if (this.timeTagScore > 0) { Score score = objective.getScore(ChatColor.translateAlternateColorCodes('&', "&6&lTime")); if (score.getScore() != timeTagScore) score.setScore(timeTagScore); } if (timeCounterScore > 0) { board.resetScores(lastTimeRemaining + ""); lastTimeRemaining = counter; objective.getScore(lastTimeRemaining + "").setScore(timeCounterScore); } } protected void setBoardForAll() { for (Player player : getPlayers()) { if (player.getScoreboard() != board) player.setScoreboard(board); } } }
package scala.compat.java8; import scala.compat.java8.converterImpl.*; import scala.compat.java8.collectionImpl.*; import java.util.stream.*; import scala.compat.java8.runtime.CollectionInternals; /** * This class contains static utility methods for creating Java Streams from Scala Collections, similar * to the methods in {@code java.util.stream.StreamSupport} for other Java types. It is intended for * use from Java code. In Scala code, you can use the extension methods provided by * {@code scala.compat.java8.StreamConverters} instead. * * Streams created from immutable Scala collections are also immutable. Mutable collections should * not be modified concurrently. There are no guarantees for success or failure modes of existing * streams in case of concurrent modifications. */ public class ScalaStreamSupport { // Generic Streams // /** * Generates a Stream that traverses an IndexedSeq. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The IndexedSeq to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <T> Stream<T> stream(scala.collection.IndexedSeq<T> coll) { return StreamSupport.stream(new StepsAnyIndexedSeq<T>(coll, 0, coll.length()), false); } /** * Generates a Stream that traverses the keys of a scala.collection.immutable.HashMap. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The immutable.HashMap to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <K> Stream<K> streamKeys(scala.collection.immutable.HashMap<K, ? super Object> coll) { return StreamSupport.stream(new StepsAnyImmHashMapKey<K, Object>(coll, 0, coll.size()), false); } /** * Generates a Stream that traverses the values of a scala.collection.immutable.HashMap. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The immutable.HashMap to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <V> Stream<V> streamValues(scala.collection.immutable.HashMap<? super Object, V> coll) { return StreamSupport.stream(new StepsAnyImmHashMapValue<Object, V>(coll, 0, coll.size()), false); } /** * Generates a Stream that traverses the key-value pairs of a scala.collection.immutable.HashMap. * The key-value pairs are presented as instances of scala.Tuple2. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The immutable.HashMap to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <K, V> Stream< scala.Tuple2<K, V> > stream(scala.collection.immutable.HashMap<K, V> coll) { return StreamSupport.stream(new StepsAnyImmHashMap<K, V>(coll, 0, coll.size()), false); } /** * Generates a Stream that traverses a scala.collection.immutable.HashSet. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The immutable.HashSet to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <T> Stream<T> stream(scala.collection.immutable.HashSet<T> coll) { return StreamSupport.stream(new StepsAnyImmHashSet<T>(coll.iterator(), coll.size()), false); } /** * Generates a Stream that traverses the keys of a scala.collection.mutable.HashMap. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The mutable.HashMap to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <K> Stream<K> streamKeys(scala.collection.mutable.HashMap<K, ?> coll) { scala.collection.mutable.HashEntry[] tbl = CollectionInternals.getTable(coll); return StreamSupport.stream(new StepsAnyHashTableKey(tbl, 0, tbl.length), false); } /** * Generates a Stream that traverses the values of a scala.collection.mutable.HashMap. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The mutable.HashMap to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <V> Stream<V> streamValues(scala.collection.mutable.HashMap<? super Object, V> coll) { scala.collection.mutable.HashEntry[] tbl = CollectionInternals.getTable(coll); return StreamSupport.stream(new StepsAnyDefaultHashTableValue(tbl, 0, tbl.length), false); } /** * Generates a Stream that traverses the key-value pairs of a scala.collection.mutable.HashMap. * The key-value pairs are presented as instances of scala.Tuple2. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The mutable.HashMap to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <K, V> Stream< scala.Tuple2<K, V> > stream(scala.collection.mutable.HashMap<K, V> coll) { scala.collection.mutable.HashEntry< K, scala.collection.mutable.DefaultEntry<K, V> >[] tbl = CollectionInternals.getTable(coll); return StreamSupport.stream(new StepsAnyDefaultHashTable<K, V>(tbl, 0, tbl.length), false); } /** * Generates a Stream that traverses a scala.collection.mutable.HashSet. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The mutable.HashSet to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <T> Stream<T> stream(scala.collection.mutable.HashSet<T> coll) { Object[] tbl = CollectionInternals.getTable(coll); return StreamSupport.stream(new StepsAnyFlatHashTable<T>(tbl, 0, tbl.length), false); } /** * Generates a Stream that traverses a scala.collection.immutable.Vector. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The Vector to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <T> Stream<T> stream(scala.collection.immutable.Vector<T> coll) { return StreamSupport.stream(new StepsAnyVector<T>(coll, 0, coll.length()), false); } /** * Generates a Stream that traverses the keys of a scala.collection.Map. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the streamAccumulatedKeys method instead, but * note that this creates a new collection containing the Map's keys. * * @param coll The Map to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <K> Stream<K> streamKeys(scala.collection.Map<K, ?> coll) { return StreamSupport.stream(new StepsAnyIterator<K>(coll.keysIterator()), false); } /** * Generates a Stream that traverses the values of a scala.collection.Map. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the streamAccumulatedValues method instead, but * note that this creates a new collection containing the Map's values. * * @param coll The Map to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <V> Stream<V> streamValues(scala.collection.Map<?, V> coll) { return StreamSupport.stream(new StepsAnyIterator<V>(coll.valuesIterator()), false); } /** * Generates a Stream that traverses the key-value pairs of a scala.collection.Map. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the streamAccumulated method instead, but * note that this creates a new collection containing the Map's key-value pairs. * * @param coll The Map to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <K,V> Stream< scala.Tuple2<K, V> > stream(scala.collection.Map<K, V> coll) { return StreamSupport.stream(new StepsAnyIterator< scala.Tuple2<K, V> >(coll.iterator()), false); } /** * Generates a Stream that traverses a scala.collection.Iterator. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the streamAccumulated method instead, * but note that this creates a copy of the contents of the Iterator. * * @param coll The scala.collection.Iterator to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <T> Stream<T> stream(scala.collection.Iterator<T> coll) { return StreamSupport.stream(new StepsAnyIterator<T>(coll), false); } /** * Generates a Stream that traverses a scala.collection.Iterable. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the streamAccumulated method instead, * but note that this creates a copy of the contents of the Iterable * * @param coll The scala.collection.Iterable to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <T> Stream<T> stream(scala.collection.Iterable<T> coll) { return StreamSupport.stream(new StepsAnyIterator<T>(coll.iterator()), false); } /** * Generates a Stream that traverses any Scala collection by accumulating its entries * into a buffer class (Accumulator). * <p> * Both sequential and parallel operations will be efficient. * * @param coll The collection to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <T> Stream<T> streamAccumulated(scala.collection.TraversableOnce<T> coll) { scala.compat.java8.collectionImpl.Accumulator<T> acc = scala.compat.java8.collectionImpl.Accumulator.from(coll); return StreamSupport.stream(acc.spliterator(), false); } /** * Generates a Stream that traverses the keys of any Scala map by * accumulating those keys into a buffer class (Accumulator). * <p> * Both sequential and parallel operations will be efficient. * * @param coll The map containing keys to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <K> Stream<K> streamAccumulatedKeys(scala.collection.Map<K, ?> coll) { scala.compat.java8.collectionImpl.Accumulator<K> acc = scala.compat.java8.collectionImpl.Accumulator.from(coll.keysIterator()); return StreamSupport.stream(acc.spliterator(), false); } /** * Generates a Stream that traverses the values of any Scala map by * accumulating those values into a buffer class (Accumulator). * <p> * Both sequential and parallel operations will be efficient. * * @param coll The map containing values to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static <V> Stream<V> streamAccumulatedValues(scala.collection.Map<?, V> coll) { scala.compat.java8.collectionImpl.Accumulator<V> acc = scala.compat.java8.collectionImpl.Accumulator.from(coll.valuesIterator()); return StreamSupport.stream(acc.spliterator(), false); } // Double Streams // /** * Generates a DoubleStream that traverses an IndexedSeq of Doubles. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The IndexedSeq to traverse * @return A DoubleStream view of the collection which, by default, executes sequentially. */ public static DoubleStream doubleStream(scala.collection.IndexedSeq<Double> coll) { return StreamSupport.doubleStream(new StepsDoubleIndexedSeq(coll, 0, coll.length()), false); } /** * Generates a DoubleStream that traverses double-valued keys of a scala.collection.immutable.HashMap. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The immutable.HashMap to traverse * @return A DoubleStream view of the collection which, by default, executes sequentially. */ public static DoubleStream doubleStreamKeys(scala.collection.immutable.HashMap<Double, ? super Object> coll) { return StreamSupport.doubleStream(new StepsDoubleImmHashMapKey(coll, 0, coll.size()), false); } /** * Generates a DoubleStream that traverses double-valued values of a scala.collection.immutable.HashMap. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The immutable.HashMap to traverse * @return A DoubleStream view of the collection which, by default, executes sequentially. */ public static DoubleStream doubleStreamValues(scala.collection.immutable.HashMap<? super Object, Double> coll) { return StreamSupport.doubleStream(new StepsDoubleImmHashMapValue(coll, 0, coll.size()), false); } /** * Generates a DoubleStream that traverses a scala.collection.immutable.HashSet of Doubles. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The immutable.HashSet to traverse * @return A DoubleStream view of the collection which, by default, executes sequentially. */ public static DoubleStream doubleStream(scala.collection.immutable.HashSet<Double> coll) { scala.collection.Iterator iter = (scala.collection.Iterator)coll.iterator(); return StreamSupport.doubleStream(new StepsDoubleImmHashSet(iter, coll.size()), false); } /** * Generates a DoubleStream that traverses double-valued keys of a scala.collection.mutable.HashMap. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The mutable.HashMap to traverse * @return A DoubleStream view of the collection which, by default, executes sequentially. */ public static DoubleStream doubleStreamKeys(scala.collection.mutable.HashMap<Double, ?> coll) { scala.collection.mutable.HashEntry[] tbl = CollectionInternals.getTable(coll); return StreamSupport.doubleStream(new StepsDoubleHashTableKey(tbl, 0, tbl.length), false); } /** * Generates a DoubleStream that traverses double-valued values of a scala.collection.mutable.HashMap. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The mutable.HashMap to traverse * @return A DoubleStream view of the collection which, by default, executes sequentially. */ public static DoubleStream doubleStreamValues(scala.collection.mutable.HashMap<? super Object, Double> coll) { scala.collection.mutable.HashEntry[] tbl = CollectionInternals.getTable(coll); return StreamSupport.doubleStream(new StepsDoubleDefaultHashTableValue(tbl, 0, tbl.length), false); } /** * Generates a DoubleStream that traverses a scala.collection.mutable.HashSet of Doubles. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The mutable.HashSet to traverse * @return A DoubleStream view of the collection which, by default, executes sequentially. */ public static DoubleStream doubleStream(scala.collection.mutable.HashSet<Double> coll) { Object[] tbl = CollectionInternals.getTable(coll); return StreamSupport.doubleStream(new StepsDoubleFlatHashTable(tbl, 0, tbl.length), false); } /** * Generates a DoubleStream that traverses a scala.collection.immutable.Vector of Doubles. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The Vector to traverse * @return A DoubleStream view of the collection which, by default, executes sequentially. */ public static DoubleStream doubleStream(scala.collection.immutable.Vector<Double> coll) { scala.collection.immutable.Vector erased = (scala.collection.immutable.Vector)coll; return StreamSupport.doubleStream(new StepsDoubleVector(erased, 0, coll.length()), false); } /** * Generates a DoubleStream that traverses the double-valued keys of a scala.collection.Map. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the doubleStreamAccumulatedKeys method instead, but * note that this creates a new collection containing the Map's keys. * * @param coll The Map to traverse * @return A DoubleStream view of the collection which, by default, executes sequentially. */ public static DoubleStream doubleStreamKeys(scala.collection.Map<Double, ?> coll) { scala.collection.Iterator iter = (scala.collection.Iterator)coll.keysIterator(); return StreamSupport.doubleStream(new StepsDoubleIterator(iter), false); } /** * Generates a DoubleStream that traverses the double-valued values of a scala.collection.Map. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the doubleStreamAccumulatedValues method instead, but * note that this creates a new collection containing the Map's values. * * @param coll The Map to traverse * @return A DoubleStream view of the collection which, by default, executes sequentially. */ public static DoubleStream doubleStreamValues(scala.collection.Map<?, Double> coll) { scala.collection.Iterator iter = (scala.collection.Iterator)coll.valuesIterator(); return StreamSupport.doubleStream(new StepsDoubleIterator(iter), false); } /** * Generates a DoubleStream that traverses a double-valued scala.collection.Iterator. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the doubleStreamAccumulated method instead, * but note that this creates a copy of the contents of the Iterator. * * @param coll The scala.collection.Iterator to traverse * @return A DoubleStream view of the collection which, by default, executes sequentially. */ public static DoubleStream doubleStream(scala.collection.Iterator<Double> coll) { return StreamSupport.doubleStream(new StepsDoubleIterator((scala.collection.Iterator)coll), false); } /** * Generates a DoubleStream that traverses a double-valued scala.collection.Iterable. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the doubleStreamAccumulated method instead, * but note that this creates a copy of the contents of the Iterable. * * @param coll The scala.collection.Iterable to traverse * @return A DoubleStream view of the collection which, by default, executes sequentially. */ public static DoubleStream doubleStream(scala.collection.Iterable<Double> coll) { scala.collection.Iterator iter = (scala.collection.Iterator)coll.iterator(); return StreamSupport.doubleStream(new StepsDoubleIterator(iter), false); } /** * Generates a Stream that traverses any Scala collection by accumulating its entries * into a buffer class (Accumulator). * <p> * Both sequential and parallel operations will be efficient. * * @param coll The collection to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static DoubleStream doubleStreamAccumulated(scala.collection.TraversableOnce<Double> coll) { scala.compat.java8.collectionImpl.DoubleAccumulator acc = scala.compat.java8.collectionImpl.DoubleAccumulator.from((scala.collection.TraversableOnce)coll); return StreamSupport.doubleStream(acc.spliterator(), false); } /** * Generates a Stream that traverses the keys of any Scala map by * accumulating those keys into a buffer class (Accumulator). * <p> * Both sequential and parallel operations will be efficient. * * @param coll The map containing keys to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static DoubleStream doubleStreamAccumulatedKeys(scala.collection.Map<Double, ?> coll) { scala.compat.java8.collectionImpl.DoubleAccumulator acc = scala.compat.java8.collectionImpl.DoubleAccumulator.from((scala.collection.Iterator)coll.keysIterator()); return StreamSupport.doubleStream(acc.spliterator(), false); } /** * Generates a Stream that traverses the values of any Scala map by * accumulating those values into a buffer class (Accumulator). * <p> * Both sequential and parallel operations will be efficient. * * @param coll The map containing values to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static DoubleStream doubleStreamAccumulatedValues(scala.collection.Map<?, Double> coll) { scala.compat.java8.collectionImpl.DoubleAccumulator acc = scala.compat.java8.collectionImpl.DoubleAccumulator.from((scala.collection.Iterator)coll.valuesIterator()); return StreamSupport.doubleStream(acc.spliterator(), false); } // Int Streams // /** * Generates a IntStream that traverses a BitSet. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The BitSet to traverse * @return A IntStream view of the collection which, by default, executes sequentially. */ public static IntStream intStream(scala.collection.BitSet coll) { // Let the value class figure out the casting! scala.compat.java8.converterImpl.RichBitSetCanStep rbscs = new scala.compat.java8.converterImpl.RichBitSetCanStep(coll); return StreamSupport.intStream(rbscs.stepper(), false); } /** * Generates a IntStream that traverses a Range. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The Range to traverse * @return A IntStream view of the collection which, by default, executes sequentially. */ public static IntStream intStream(scala.collection.immutable.Range coll) { return StreamSupport.intStream(new scala.compat.java8.converterImpl.StepsIntRange(coll, 0, coll.length()), false); } /** * Generates a IntStream that traverses an IndexedSeq of Ints. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The IndexedSeq to traverse * @return A IntStream view of the collection which, by default, executes sequentially. */ public static IntStream intStream(scala.collection.IndexedSeq<Integer> coll) { return StreamSupport.intStream(new StepsIntIndexedSeq(coll, 0, coll.length()), false); } /** * Generates a IntStream that traverses int-valued keys of a scala.collection.immutable.HashMap. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The immutable.HashMap to traverse * @return A IntStream view of the collection which, by default, executes sequentially. */ public static IntStream intStreamKeys(scala.collection.immutable.HashMap<Integer, ? super Object> coll) { return StreamSupport.intStream(new StepsIntImmHashMapKey(coll, 0, coll.size()), false); } /** * Generates a IntStream that traverses int-valued values of a scala.collection.immutable.HashMap. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The immutable.HashMap to traverse * @return A IntStream view of the collection which, by default, executes sequentially. */ public static IntStream intStreamValues(scala.collection.immutable.HashMap<? super Object, Integer> coll) { return StreamSupport.intStream(new StepsIntImmHashMapValue(coll, 0, coll.size()), false); } /** * Generates a IntStream that traverses a scala.collection.immutable.HashSet of Ints. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The immutable.HashSet to traverse * @return A IntStream view of the collection which, by default, executes sequentially. */ public static IntStream intStream(scala.collection.immutable.HashSet<Integer> coll) { scala.collection.Iterator iter = (scala.collection.Iterator)coll.iterator(); return StreamSupport.intStream(new StepsIntImmHashSet(iter, coll.size()), false); } /** * Generates a IntStream that traverses int-valued keys of a scala.collection.mutable.HashMap. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The mutable.HashMap to traverse * @return A IntStream view of the collection which, by default, executes sequentially. */ public static IntStream intStreamKeys(scala.collection.mutable.HashMap<Integer, ?> coll) { scala.collection.mutable.HashEntry[] tbl = CollectionInternals.getTable(coll); return StreamSupport.intStream(new StepsIntHashTableKey(tbl, 0, tbl.length), false); } /** * Generates a IntStream that traverses int-valued values of a scala.collection.mutable.HashMap. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The mutable.HashMap to traverse * @return A IntStream view of the collection which, by default, executes sequentially. */ public static IntStream intStreamValues(scala.collection.mutable.HashMap<? super Object, Integer> coll) { scala.collection.mutable.HashEntry[] tbl = CollectionInternals.getTable(coll); return StreamSupport.intStream(new StepsIntDefaultHashTableValue(tbl, 0, tbl.length), false); } /** * Generates a IntStream that traverses a scala.collection.mutable.HashSet of Ints. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The mutable.HashSet to traverse * @return A IntStream view of the collection which, by default, executes sequentially. */ public static IntStream intStream(scala.collection.mutable.HashSet<Integer> coll) { Object[] tbl = CollectionInternals.getTable(coll); return StreamSupport.intStream(new StepsIntFlatHashTable(tbl, 0, tbl.length), false); } /** * Generates a IntStream that traverses a scala.collection.immutable.Vector of Ints. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The Vector to traverse * @return A IntStream view of the collection which, by default, executes sequentially. */ public static IntStream intStream(scala.collection.immutable.Vector<Integer> coll) { scala.collection.immutable.Vector erased = (scala.collection.immutable.Vector)coll; return StreamSupport.intStream(new StepsIntVector(erased, 0, coll.length()), false); } /** * Generates a IntStream that traverses the int-valued keys of a scala.collection.Map. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the intStreamAccumulatedKeys method instead, but * note that this creates a new collection containing the Map's keys. * * @param coll The Map to traverse * @return A IntStream view of the collection which, by default, executes sequentially. */ public static IntStream intStreamKeys(scala.collection.Map<Integer, ?> coll) { scala.collection.Iterator iter = (scala.collection.Iterator)coll.keysIterator(); return StreamSupport.intStream(new StepsIntIterator(iter), false); } /** * Generates a IntStream that traverses the int-valued values of a scala.collection.Map. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the intStreamAccumulatedValues method instead, but * note that this creates a new collection containing the Map's values. * * @param coll The Map to traverse * @return A IntStream view of the collection which, by default, executes sequentially. */ public static IntStream intStreamValues(scala.collection.Map<?, Integer> coll) { scala.collection.Iterator iter = (scala.collection.Iterator)coll.valuesIterator(); return StreamSupport.intStream(new StepsIntIterator(iter), false); } /** * Generates a IntStream that traverses a int-valued scala.collection.Iterator. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the intStreamAccumulated method instead, * but note that this creates a copy of the contents of the Iterator. * * @param coll The scala.collection.Iterator to traverse * @return A IntStream view of the collection which, by default, executes sequentially. */ public static IntStream intStream(scala.collection.Iterator<Integer> coll) { return StreamSupport.intStream(new StepsIntIterator((scala.collection.Iterator)coll), false); } /** * Generates a IntStream that traverses a int-valued scala.collection.Iterable. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the intStreamAccumulated method instead, * but note that this creates a copy of the contents of the Iterable. * * @param coll The scala.collection.Iterable to traverse * @return A IntStream view of the collection which, by default, executes sequentially. */ public static IntStream intStream(scala.collection.Iterable<Integer> coll) { scala.collection.Iterator iter = (scala.collection.Iterator)coll.iterator(); return StreamSupport.intStream(new StepsIntIterator(iter), false); } /** * Generates a Stream that traverses any Scala collection by accumulating its entries * into a buffer class (Accumulator). * <p> * Both sequential and parallel operations will be efficient. * * @param coll The collection to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static IntStream intStreamAccumulated(scala.collection.TraversableOnce<Integer> coll) { scala.compat.java8.collectionImpl.IntAccumulator acc = scala.compat.java8.collectionImpl.IntAccumulator.from((scala.collection.TraversableOnce)coll); return StreamSupport.intStream(acc.spliterator(), false); } /** * Generates a Stream that traverses the keys of any Scala map by * accumulating those keys into a buffer class (Accumulator). * <p> * Both sequential and parallel operations will be efficient. * * @param coll The map containing keys to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static IntStream intStreamAccumulatedKeys(scala.collection.Map<Integer, ?> coll) { scala.compat.java8.collectionImpl.IntAccumulator acc = scala.compat.java8.collectionImpl.IntAccumulator.from((scala.collection.Iterator)coll.keysIterator()); return StreamSupport.intStream(acc.spliterator(), false); } /** * Generates a Stream that traverses the values of any Scala map by * accumulating those values into a buffer class (Accumulator). * <p> * Both sequential and parallel operations will be efficient. * * @param coll The map containing values to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static IntStream intStreamAccumulatedValues(scala.collection.Map<?, Integer> coll) { scala.compat.java8.collectionImpl.IntAccumulator acc = scala.compat.java8.collectionImpl.IntAccumulator.from((scala.collection.Iterator)coll.valuesIterator()); return StreamSupport.intStream(acc.spliterator(), false); } // Long Streams // /** * Generates a LongStream that traverses an IndexedSeq of Longs. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The IndexedSeq to traverse * @return A LongStream view of the collection which, by default, executes sequentially. */ public static LongStream longStream(scala.collection.IndexedSeq<Long> coll) { return StreamSupport.longStream(new StepsLongIndexedSeq(coll, 0, coll.length()), false); } /** * Generates a LongStream that traverses long-valued keys of a scala.collection.immutable.HashMap. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The immutable.HashMap to traverse * @return A LongStream view of the collection which, by default, executes sequentially. */ public static LongStream longStreamKeys(scala.collection.immutable.HashMap<Long, ? super Object> coll) { return StreamSupport.longStream(new StepsLongImmHashMapKey(coll, 0, coll.size()), false); } /** * Generates a LongStream that traverses long-valued values of a scala.collection.immutable.HashMap. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The immutable.HashMap to traverse * @return A LongStream view of the collection which, by default, executes sequentially. */ public static LongStream longStreamValues(scala.collection.immutable.HashMap<? super Object, Long> coll) { return StreamSupport.longStream(new StepsLongImmHashMapValue(coll, 0, coll.size()), false); } /** * Generates a LongStream that traverses a scala.collection.immutable.HashSet of Longs. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The immutable.HashSet to traverse * @return A LongStream view of the collection which, by default, executes sequentially. */ public static LongStream longStream(scala.collection.immutable.HashSet<Long> coll) { scala.collection.Iterator iter = (scala.collection.Iterator)coll.iterator(); return StreamSupport.longStream(new StepsLongImmHashSet(iter, coll.size()), false); } /** * Generates a LongStream that traverses long-valued keys of a scala.collection.mutable.HashMap. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The mutable.HashMap to traverse * @return A LongStream view of the collection which, by default, executes sequentially. */ public static LongStream longStreamKeys(scala.collection.mutable.HashMap<Long, ?> coll) { scala.collection.mutable.HashEntry[] tbl = CollectionInternals.getTable(coll); return StreamSupport.longStream(new StepsLongHashTableKey(tbl, 0, tbl.length), false); } /** * Generates a LongStream that traverses long-valued values of a scala.collection.mutable.HashMap. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The mutable.HashMap to traverse * @return A LongStream view of the collection which, by default, executes sequentially. */ public static LongStream longStreamValues(scala.collection.mutable.HashMap<? super Object, Long> coll) { scala.collection.mutable.HashEntry[] tbl = CollectionInternals.getTable(coll); return StreamSupport.longStream(new StepsLongDefaultHashTableValue(tbl, 0, tbl.length), false); } /** * Generates a LongStream that traverses a scala.collection.mutable.HashSet of Longs. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The mutable.HashSet to traverse * @return A LongStream view of the collection which, by default, executes sequentially. */ public static LongStream longStream(scala.collection.mutable.HashSet<Long> coll) { Object[] tbl = CollectionInternals.getTable(coll); return StreamSupport.longStream(new StepsLongFlatHashTable(tbl, 0, tbl.length), false); } /** * Generates a LongStream that traverses a scala.collection.immutable.Vector of Longs. * <p> * Both sequential and parallel operations will be efficient. * * @param coll The Vector to traverse * @return A LongStream view of the collection which, by default, executes sequentially. */ public static LongStream longStream(scala.collection.immutable.Vector<Long> coll) { scala.collection.immutable.Vector erased = (scala.collection.immutable.Vector)coll; return StreamSupport.longStream(new StepsLongVector(erased, 0, coll.length()), false); } /** * Generates a LongStream that traverses the long-valued keys of a scala.collection.Map. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the longStreamAccumulatedKeys method instead, but * note that this creates a new collection containing the Map's keys. * * @param coll The Map to traverse * @return A LongStream view of the collection which, by default, executes sequentially. */ public static LongStream longStreamKeys(scala.collection.Map<Long, ?> coll) { scala.collection.Iterator iter = (scala.collection.Iterator)coll.keysIterator(); return StreamSupport.longStream(new StepsLongIterator(iter), false); } /** * Generates a LongStream that traverses the long-valued values of a scala.collection.Map. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the longStreamAccumulatedValues method instead, but * note that this creates a new collection containing the Map's values. * * @param coll The Map to traverse * @return A LongStream view of the collection which, by default, executes sequentially. */ public static LongStream longStreamValues(scala.collection.Map<?, Long> coll) { scala.collection.Iterator iter = (scala.collection.Iterator)coll.valuesIterator(); return StreamSupport.longStream(new StepsLongIterator(iter), false); } /** * Generates a LongStream that traverses a long-valued scala.collection.Iterator. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the longStreamAccumulated method instead, * but note that this creates a copy of the contents of the Iterator. * * @param coll The scala.collection.Iterator to traverse * @return A LongStream view of the collection which, by default, executes sequentially. */ public static LongStream longStream(scala.collection.Iterator<Long> coll) { return StreamSupport.longStream(new StepsLongIterator((scala.collection.Iterator)coll), false); } /** * Generates a LongStream that traverses a long-valued scala.collection.Iterable. * <p> * Only sequential operations will be efficient. * For efficient parallel operation, use the longStreamAccumulated method instead, * but note that this creates a copy of the contents of the Iterable. * * @param coll The scala.collection.Iterable to traverse * @return A LongStream view of the collection which, by default, executes sequentially. */ public static LongStream longStream(scala.collection.Iterable<Long> coll) { scala.collection.Iterator iter = (scala.collection.Iterator)coll.iterator(); return StreamSupport.longStream(new StepsLongIterator(iter), false); } /** * Generates a Stream that traverses any Scala collection by accumulating its entries * into a buffer class (Accumulator). * <p> * Both sequential and parallel operations will be efficient. * * @param coll The collection to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static LongStream longStreamAccumulated(scala.collection.TraversableOnce<Long> coll) { scala.compat.java8.collectionImpl.LongAccumulator acc = scala.compat.java8.collectionImpl.LongAccumulator.from((scala.collection.TraversableOnce)coll); return StreamSupport.longStream(acc.spliterator(), false); } /** * Generates a Stream that traverses the keys of any Scala map by * accumulating those keys into a buffer class (Accumulator). * <p> * Both sequential and parallel operations will be efficient. * * @param coll The map containing keys to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static LongStream longStreamAccumulatedKeys(scala.collection.Map<Long, ?> coll) { scala.compat.java8.collectionImpl.LongAccumulator acc = scala.compat.java8.collectionImpl.LongAccumulator.from((scala.collection.Iterator)coll.keysIterator()); return StreamSupport.longStream(acc.spliterator(), false); } /** * Generates a Stream that traverses the values of any Scala map by * accumulating those values into a buffer class (Accumulator). * <p> * Both sequential and parallel operations will be efficient. * * @param coll The map containing values to traverse * @return A Stream view of the collection which, by default, executes sequentially. */ public static LongStream longStreamAccumulatedValues(scala.collection.Map<?, Long> coll) { scala.compat.java8.collectionImpl.LongAccumulator acc = scala.compat.java8.collectionImpl.LongAccumulator.from((scala.collection.Iterator)coll.valuesIterator()); return StreamSupport.longStream(acc.spliterator(), false); } }
package net.imagej.ui.swing.updater; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import net.imagej.updater.Diff.Mode; import net.imagej.updater.FileObject; import net.imagej.updater.FileObject.Action; import net.imagej.updater.FileObject.Status; import net.imagej.updater.FilesCollection; import net.imagej.updater.FilesCollection.DependencyMap; import net.imagej.updater.FilesUploader; import net.imagej.updater.GroupAction; import net.imagej.updater.Installer; import net.imagej.updater.UploaderService; import net.imagej.updater.action.InstallOrUpdate; import net.imagej.updater.action.KeepAsIs; import net.imagej.updater.action.Uninstall; import net.imagej.updater.util.Progress; import net.imagej.updater.util.UpdateCanceledException; import net.imagej.updater.util.UpdaterUserInterface; import net.imagej.updater.util.UpdaterUtil; import org.scijava.Context; import org.scijava.log.LogService; import org.scijava.util.ProcessUtils; /** * TODO * * @author Johannes Schindelin */ @SuppressWarnings("serial") public class UpdaterFrame extends JFrame implements TableModelListener, ListSelectionListener { protected LogService log; private UploaderService uploaderService; protected FilesCollection files; protected JTextField searchTerm; protected JPanel searchPanel; protected ViewOptions viewOptions; protected JPanel viewOptionsPanel; protected JPanel chooseLabel; protected FileTable table; protected JLabel fileSummary; protected JPanel summaryPanel; protected JPanel rightPanel; protected FileDetails fileDetails; protected JPanel bottomPanel, bottomPanel2; protected JButton applyOrUpload, cancel, easy, updateSites; protected boolean easyMode; // For developers protected JButton showChanges, rebuildButton; protected boolean canUpload; protected final static String gitVersion; static { String version = null; try { version = ProcessUtils.exec(null, null, null, "git", "--version"); } catch (Throwable t) { /* ignore */ } gitVersion = version; } public UpdaterFrame(final LogService log, final UploaderService uploaderService, final FilesCollection files) { super("ImageJ Updater"); setPreferredSize(new Dimension(780, 560)); this.log = log; this.uploaderService = uploaderService; this.files = files; setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { quit(); } }); final JPanel leftPanel = new JPanel(); final GridBagLayout gb = new GridBagLayout(); leftPanel.setLayout(gb); final GridBagConstraints c = new GridBagConstraints(0, 0, // x, y 9, 1, // rows, cols 0, 0, // weightx, weighty GridBagConstraints.NORTHWEST, // anchor GridBagConstraints.HORIZONTAL, // fill new Insets(0, 0, 0, 0), 0, 0); // ipadx, ipady searchTerm = new JTextField(); searchTerm.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(final DocumentEvent e) { updateFilesTable(); } @Override public void removeUpdate(final DocumentEvent e) { updateFilesTable(); } @Override public void insertUpdate(final DocumentEvent e) { updateFilesTable(); } }); searchPanel = SwingTools.labelComponentRigid("Search:", searchTerm); gb.setConstraints(searchPanel, c); leftPanel.add(searchPanel); Component box = Box.createRigidArea(new Dimension(0, 10)); c.gridy = 1; gb.setConstraints(box, c); leftPanel.add(box); viewOptions = new ViewOptions(); viewOptions.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { updateFilesTable(); } }); viewOptionsPanel = SwingTools.labelComponentRigid("View Options:", viewOptions); c.gridy = 2; gb.setConstraints(viewOptionsPanel, c); leftPanel.add(viewOptionsPanel); box = Box.createRigidArea(new Dimension(0, 10)); c.gridy = 3; gb.setConstraints(box, c); leftPanel.add(box); // Create labels to annotate table chooseLabel = SwingTools.label("Please choose what you want to install/uninstall:", null); c.gridy = 4; gb.setConstraints(chooseLabel, c); leftPanel.add(chooseLabel); box = Box.createRigidArea(new Dimension(0, 5)); c.gridy = 5; gb.setConstraints(box, c); leftPanel.add(box); // Label text for file summaries fileSummary = new JLabel(); summaryPanel = SwingTools.horizontalPanel(); summaryPanel.add(fileSummary); summaryPanel.add(Box.createHorizontalGlue()); // Create the file table and set up its scrollpane table = new FileTable(this); table.getSelectionModel().addListSelectionListener(this); final JScrollPane fileListScrollpane = new JScrollPane(table); fileListScrollpane.getViewport().setBackground(table.getBackground()); c.gridy = 6; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; gb.setConstraints(fileListScrollpane, c); leftPanel.add(fileListScrollpane); box = Box.createRigidArea(new Dimension(0, 5)); c.gridy = 7; c.weightx = 0; c.weighty = 0; c.fill = GridBagConstraints.HORIZONTAL; gb.setConstraints(box, c); leftPanel.add(box); rightPanel = SwingTools.verticalPanel(); rightPanel.add(Box.createVerticalGlue()); fileDetails = new FileDetails(this); SwingTools.tab(fileDetails, "Details", "Individual file information", 350, 315, rightPanel); // TODO: put this into SwingTools, too rightPanel.add(Box.createRigidArea(new Dimension(0, 25))); final JPanel topPanel = SwingTools.horizontalPanel(); topPanel.add(leftPanel); topPanel.add(Box.createRigidArea(new Dimension(15, 0))); topPanel.add(rightPanel); topPanel.setBorder(BorderFactory.createEmptyBorder(20, 15, 5, 15)); bottomPanel2 = SwingTools.horizontalPanel(); bottomPanel = SwingTools.horizontalPanel(); bottomPanel.setBorder(BorderFactory.createEmptyBorder(5, 15, 15, 15)); bottomPanel.add(new FileActionButton(new KeepAsIs())); bottomPanel.add(Box.createRigidArea(new Dimension(15, 0))); bottomPanel.add(new FileActionButton(new InstallOrUpdate())); bottomPanel.add(Box.createRigidArea(new Dimension(15, 0))); bottomPanel.add(new FileActionButton(new Uninstall())); bottomPanel.add(Box.createHorizontalGlue()); // make sure that sezpoz finds the classes when triggered from the EDT final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); SwingTools.invokeOnEDT(new Runnable() { @Override public void run() { if (contextClassLoader != null) Thread.currentThread().setContextClassLoader(contextClassLoader); } }); // Button to start actions applyOrUpload = SwingTools.button("Apply changes", "Start installing/uninstalling/uploading files", new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (files.hasUploadOrRemove()) { new Thread() { @Override public void run() { try { upload(); } catch (final InstantiationException e) { log.error(e); error("Could not upload (possibly unknown protocol)"); } } }.start(); } else if (files.hasChanges()) { applyChanges(); } } }, bottomPanel); enableApplyOrUpload(); // Manage update sites updateSites = SwingTools.button("Manage update sites", "Manage multiple update sites for updating and uploading", new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { new SitesDialog(UpdaterFrame.this, UpdaterFrame.this.files).setVisible(true); } }, bottomPanel2); // TODO: unify upload & apply changes (probably apply changes first, then // upload) // includes button to upload to server if is a Developer using bottomPanel2.add(Box.createRigidArea(new Dimension(15, 0))); if (gitVersion != null) { bottomPanel2.add(Box.createRigidArea(new Dimension(15, 0))); showChanges = SwingTools.button("Show changes", "Show the differences to the uploaded version", new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { new Thread() { @Override public void run() { for (final FileObject file : table.getSelectedFiles()) try { final DiffFile diff = new DiffFile(files, file, Mode.LIST_FILES); diff.setLocationRelativeTo(UpdaterFrame.this); diff.setVisible(true); } catch (MalformedURLException e) { files.log.error(e); UpdaterUserInterface.get().error("There was a problem obtaining the remote version of " + file.getLocalFilename(true)); } } }.start(); } }, bottomPanel2); } bottomPanel2.add(Box.createHorizontalGlue()); bottomPanel.add(Box.createRigidArea(new Dimension(15, 0))); easy = SwingTools.button("Toggle easy mode", "Toggle between easy and verbose mode", new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { toggleEasyMode(); } }, bottomPanel); bottomPanel.add(Box.createRigidArea(new Dimension(15, 0))); cancel = SwingTools.button("Close", "Exit Update Manager", new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { quit(); } }, bottomPanel); getContentPane().setLayout( new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); getContentPane().add(topPanel); getContentPane().add(summaryPanel); getContentPane().add(bottomPanel); getContentPane().add(bottomPanel2); getRootPane().setDefaultButton(applyOrUpload); table.getModel().addTableModelListener(this); pack(); SwingTools.addAccelerator(cancel, (JComponent) getContentPane(), cancel .getActionListeners()[0], KeyEvent.VK_ESCAPE, 0); } @Override public void setVisible(final boolean visible) { if (!SwingUtilities.isEventDispatchThread()) { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { setVisible(visible); } }); } catch (InterruptedException e) { // ignore } catch (InvocationTargetException e) { log.error(e); } return; } showOrHide(); super.setVisible(visible); if (visible) { UpdaterUserInterface.get().addWindow(this); applyOrUpload.requestFocusInWindow(); } } @Override public void dispose() { UpdaterUserInterface.get().removeWindow(this); super.dispose(); } public Progress getProgress(final String title) { return new ProgressDialog(this, title); } /** * Sets the context class loader if necessary. * * If the current class cannot be found by the current Thread's context * class loader, we should tell the Thread about the class loader that * loaded this class. */ private void setClassLoaderIfNecessary() { ClassLoader thisLoader = getClass().getClassLoader(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); for (; loader != null; loader = loader.getParent()) { if (thisLoader == loader) return; } Thread.currentThread().setContextClassLoader(thisLoader); } /** Gets the uploader service associated with this updater frame. */ public UploaderService getUploaderService() { if (uploaderService == null) { setClassLoaderIfNecessary(); final Context context = new Context(UploaderService.class); uploaderService = context.getService(UploaderService.class); } return uploaderService; } @Override public void valueChanged(final ListSelectionEvent event) { filesChanged(); } List<FileActionButton> fileActions = new ArrayList<FileActionButton>(); private class FileActionButton extends JButton implements ActionListener { private GroupAction goal; public FileActionButton(final GroupAction goal) { super(goal.toString()); this.goal = goal; addActionListener(this); fileActions.add(this); } @Override public void actionPerformed(final ActionEvent e) { if (table.isEditing()) table.editingCanceled(null); for (final FileObject file : table.getSelectedFiles()) { goal.setAction(files, file); table.fireFileChanged(file); } filesChanged(); } public void enableIfValid() { boolean enable = true; int count = 0; for (final FileObject file : table.getSelectedFiles()) { count++; if (!goal.isValid(files, file)) { enable = false; break; } } setText(goal.getLabel(files, table.getSelectedFiles())); setEnabled(count > 0 && enable); } } public void addCustomViewOptions() { viewOptions.clearCustomOptions(); final Collection<String> names = files.getUpdateSiteNames(false); if (names.size() > 1) for (final String name : names) viewOptions.addCustomOption("View files of the '" + name + "' site", files.forUpdateSite(name)); } public void setViewOption(final ViewOptions.Option option) { SwingTools.invokeOnEDT(new Runnable() { @Override public void run() { viewOptions.setSelectedItem(option); updateFilesTable(); } }); } public void updateFilesTable() { SwingTools.invokeOnEDT(new Runnable() { @Override public void run() { Iterable<FileObject> view = viewOptions.getView(table); final Set<FileObject> selected = new HashSet<FileObject>(); for (final FileObject file : table.getSelectedFiles()) selected.add(file); table.clearSelection(); final String search = searchTerm.getText().trim(); if (!search.equals("")) view = FilesCollection.filter(search, view); // Directly update the table for display table.setFiles(view); for (int i = 0; i < table.getRowCount(); i++) if (selected.contains(table.getFile(i))) table.addRowSelectionInterval(i, i); } }); } public void applyChanges() { final ResolveDependencies resolver = new ResolveDependencies(this, files); if (!resolver.resolve()) return; new Thread() { @Override public void run() { install(); } }.start(); } private void quit() { if (files.hasChanges()) { if (!SwingTools.showQuestion(this, "Quit?", "You have specified changes. Are you sure you want to quit?")) return; } else try { files.write(); } catch (final Exception e) { error("There was an error writing the local metadata cache: " + e); } dispose(); } public void setEasyMode(final boolean easyMode) { this.easyMode = easyMode; showOrHide(); if (isVisible()) repaint(); } protected void showOrHide() { for (final FileActionButton action : fileActions) { action.setVisible(!easyMode); } searchPanel.setVisible(!easyMode); viewOptionsPanel.setVisible(!easyMode); chooseLabel.setVisible(!easyMode); summaryPanel.setVisible(!easyMode); rightPanel.setVisible(!easyMode); if (easyMode) bottomPanel.add(updateSites, 0); else bottomPanel2.add(updateSites, 0); final boolean uploadable = !easyMode && files.hasUploadableSites(); if (showChanges != null) showChanges.setVisible(!easyMode && gitVersion != null); if (rebuildButton != null) rebuildButton.setVisible(uploadable); easy.setText(easyMode ? "Advanced mode" : "Easy mode"); } public void toggleEasyMode() { setEasyMode(!easyMode); } public void install() { final Installer installer = new Installer(files, getProgress("Installing...")); try { installer.start(); updateFilesTable(); filesChanged(); files.write(); info("Updated successfully. Please restart ImageJ!"); dispose(); } catch (final UpdateCanceledException e) { // TODO: remove "update/" directory error("Canceled"); installer.done(); } catch (final Exception e) { log.error(e); // TODO: remove "update/" directory error("Installer failed: " + e); installer.done(); } } private Thread filesChangedWorker; public synchronized void filesChanged() { if (filesChangedWorker != null) return; filesChangedWorker = new Thread() { @Override public void run() { filesChangedWorker(); synchronized (UpdaterFrame.this) { filesChangedWorker = null; } } }; SwingUtilities.invokeLater(filesChangedWorker); } private void filesChangedWorker() { // TODO: once this is editable, make sure changes are committed fileDetails.reset(); for (final FileObject file : table.getSelectedFiles()) fileDetails.showFileDetails(file); if (fileDetails.getDocument().getLength() > 0 && table.areAllSelectedFilesUploadable()) fileDetails .setEditableForDevelopers(); for (final FileActionButton button : fileActions) button.enableIfValid(); if (showChanges != null) showChanges.setEnabled(table.getSelectedFiles().iterator().hasNext()); enableApplyOrUpload(); cancel.setText(files.hasChanges() || files.hasUpdateSitesChanges() ? "Cancel" : "Close"); int install = 0, uninstall = 0, upload = 0; long bytesToDownload = 0, bytesToUpload = 0; for (final FileObject file : files) switch (file.getAction()) { case INSTALL: case UPDATE: install++; bytesToDownload += file.filesize; break; case UNINSTALL: uninstall++; break; case UPLOAD: upload++; bytesToUpload += file.filesize; break; default: } int implicated = 0; final DependencyMap map = files.getDependencies(true); for (final FileObject file : map.keySet()) { implicated++; bytesToUpload += file.filesize; } String text = ""; if (install > 0) text += " install/update: " + install + (implicated > 0 ? "+" + implicated : "") + " (" + sizeToString(bytesToDownload) + ")"; if (uninstall > 0) text += " uninstall: " + uninstall; if (files.hasUploadableSites() && upload > 0) text += " upload: " + upload + " (" + sizeToString(bytesToUpload) + ")"; fileSummary.setText(text); } protected final static String[] units = { "B", "kB", "MB", "GB", "TB" }; public static String sizeToString(long size) { int i; for (i = 1; i < units.length && size >= 1l << (10 * i); i++); // do nothing if (--i == 0) return "" + size + units[i]; // round size *= 100; size >>= (10 * i); size += 5; size /= 10; return "" + (size / 10) + "." + (size % 10) + units[i]; } @Override public void tableChanged(final TableModelEvent e) { filesChanged(); } // checkWritable() is guaranteed to be called after Checksummer ran public void checkWritable() { if (UpdaterUtil.isProtectedLocation(files.prefix(""))) { error("<html><p width=400>Windows' security model for the directory '" + files.prefix("") + "' is incompatible with the ImageJ updater.</p>" + "<p>Please install ImageJ into a user-writable directory, e.g. onto the Desktop.</p></html>"); return; } String list = null; for (final FileObject object : files) { final File file = files.prefix(object); if (!file.exists() || file.canWrite()) continue; if (list == null) list = object.getFilename(); else list += ", " + object.getFilename(); } if (list != null) UpdaterUserInterface.get().info( "WARNING: The following files are set to read-only: '" + list + "'", "Read-only files"); } void markUploadable() { canUpload = true; enableApplyOrUpload(); } void enableApplyOrUpload() { if (files.hasUploadOrRemove()) { applyOrUpload.setEnabled(true); applyOrUpload.setText("Apply changes (upload)"); } else { applyOrUpload.setText("Apply changes"); applyOrUpload.setEnabled(files.hasChanges()); } } protected void upload() throws InstantiationException { final ResolveDependencies resolver = new ResolveDependencies(this, files, true); if (!resolver.resolve()) return; final String errors = files.checkConsistency(); if (errors != null) { error(errors); return; } final List<String> possibleSites = new ArrayList<String>(files.getSiteNamesToUpload()); if (possibleSites.size() == 0) { error("Huh? No upload site?"); return; } String updateSiteName; if (possibleSites.size() == 1) updateSiteName = possibleSites.get(0); else { updateSiteName = SwingTools.getChoice(this, possibleSites, "Which site do you want to upload to?", "Update site"); if (updateSiteName == null) return; } final FilesUploader uploader = new FilesUploader(uploaderService, files, updateSiteName, getProgress(null)); Progress progress = null; try { if (!uploader.login()) return; progress = getProgress("Uploading..."); uploader.upload(progress); for (final FileObject file : files.toUploadOrRemove()) if (file.getAction() == Action.UPLOAD) { file.markUploaded(); file.setStatus(Status.INSTALLED); } else { file.markRemoved(files); } updateFilesTable(); canUpload = false; files.write(); info("Uploaded successfully."); enableApplyOrUpload(); dispose(); } catch (final UpdateCanceledException e) { // TODO: teach uploader to remove the lock file error("Canceled"); if (progress != null) progress.done(); } catch (final Throwable e) { UpdaterUserInterface.get().handleException(e); error("Upload failed: " + e); if (progress != null) progress.done(); } } protected boolean initializeUpdateSite(final String url, final String sshHost, final String uploadDirectory) throws InstantiationException { final FilesUploader uploader = FilesUploader.initialUploader(uploaderService, url, sshHost, uploadDirectory, getProgress(null)); Progress progress = null; try { if (!uploader.login()) return false; progress = getProgress("Initializing Update Site..."); uploader.upload(progress); // JSch needs some time to finalize the SSH connection try { Thread.sleep(1000); } catch (final InterruptedException e) { /* ignore */} return true; } catch (final UpdateCanceledException e) { if (progress != null) progress.done(); } catch (final Throwable e) { UpdaterUserInterface.get().handleException(e); if (progress != null) progress.done(); } return false; } public void error(final String message) { SwingTools.showMessageBox(this, message, JOptionPane.ERROR_MESSAGE); } public void warn(final String message) { SwingTools.showMessageBox(this, message, JOptionPane.WARNING_MESSAGE); } public void info(final String message) { SwingTools.showMessageBox(this, message, JOptionPane.INFORMATION_MESSAGE); } }
package seedu.address.model.task; import seedu.address.model.tag.Tag; import seedu.address.model.tag.UniqueTagList; /** * A read-only immutable interface for a Task in the addressbook. * Implementations should guarantee: details are present and not null, field values are validated. */ public interface ReadOnlyTask { Name getName(); Date getDate(); Time getTime(); Tag getTag(); Description getDescription(); Venue getVenue(); Priority getPriority(); boolean isFavorite(); /** * 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.getName().equals(this.getName())); // state checks here onwards /*&& other.getDate() != null? other.getDate().equals(this.getDate()): this.getDate() == null && other.getTime() != null? other.getTime().equals(this.getTime()): this.getTime() == null && other.getTag() != null? other.getTag().equals(this.getTag()): this.getTag() == null && other.getDescription() != null? other.equals(this.getDescription()): this.getDescription() == null && other.getVenue() != null? other.getVenue().equals(this.getVenue()): this.getVenue() == null && other.getPriority() != null? other.getPriority().equals(this.getPriority()): this.getPriority() == null && other.isFavorite()==this.isFavorite());*/ } /** * Formats the person as text, showing all contact details. */ default String getAsText() { final StringBuilder builder = new StringBuilder(); builder.append(getName()); if (getDate()!=null){ builder.append(" Due Date:"); builder.append(getDate()); } return builder.toString(); } }
package net.minecraftforge.oredict; import java.util.ArrayList; 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.ListIterator; import java.util.Map; import java.util.RandomAccess; import java.util.Map.Entry; import java.util.Set; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.ShapedRecipes; import net.minecraft.item.crafting.ShapelessRecipes; import net.minecraftforge.common.MinecraftForge; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.eventhandler.Event; public class OreDictionary { private static boolean hasInit = false; private static List<String> idToName = new ArrayList<String>(); private static Map<String, Integer> nameToId = new HashMap<String, Integer>(128); private static List<ArrayList<ItemStack>> idToStack = Lists.newArrayList(); //ToDo: Unqualify to List when possible {1.8} private static List<ArrayList<ItemStack>> idToStackUn = Lists.newArrayList(); //ToDo: Unqualify to List when possible {1.8} private static Map<Integer, List<Integer>> stackToId = Maps.newHashMapWithExpectedSize(96); // Calculated from 128 * 0.75 public static final ArrayList<ItemStack> EMPTY_LIST = new UnmodifiableArrayList(Lists.newArrayList()); //ToDo: Unqualify to List when possible {1.8} /** * Minecraft changed from -1 to Short.MAX_VALUE in 1.5 release for the "block wildcard". Use this in case it * changes again. */ public static final int WILDCARD_VALUE = Short.MAX_VALUE; static { initVanillaEntries(); } @SuppressWarnings("unchecked") public static void initVanillaEntries() { if (!hasInit) { registerOre("logWood", new ItemStack(Blocks.log, 1, WILDCARD_VALUE)); registerOre("logWood", new ItemStack(Blocks.log2, 1, WILDCARD_VALUE)); registerOre("plankWood", new ItemStack(Blocks.planks, 1, WILDCARD_VALUE)); registerOre("slabWood", new ItemStack(Blocks.wooden_slab, 1, WILDCARD_VALUE)); registerOre("stairWood", Blocks.oak_stairs); registerOre("stairWood", Blocks.spruce_stairs); registerOre("stairWood", Blocks.birch_stairs); registerOre("stairWood", Blocks.jungle_stairs); registerOre("stairWood", Blocks.acacia_stairs); registerOre("stairWood", Blocks.dark_oak_stairs); registerOre("stickWood", Items.stick); registerOre("treeSapling", new ItemStack(Blocks.sapling, 1, WILDCARD_VALUE)); registerOre("treeLeaves", new ItemStack(Blocks.leaves, 1, WILDCARD_VALUE)); registerOre("treeLeaves", new ItemStack(Blocks.leaves2, 1, WILDCARD_VALUE)); registerOre("oreGold", Blocks.gold_ore); registerOre("oreIron", Blocks.iron_ore); registerOre("oreLapis", Blocks.lapis_ore); registerOre("oreDiamond", Blocks.diamond_ore); registerOre("oreRedstone", Blocks.redstone_ore); registerOre("oreEmerald", Blocks.emerald_ore); registerOre("oreQuartz", Blocks.quartz_ore); registerOre("oreCoal", Blocks.coal_ore); registerOre("blockGold", Blocks.gold_block); registerOre("blockIron", Blocks.iron_block); registerOre("blockLapis", Blocks.lapis_block); registerOre("blockDiamond", Blocks.diamond_block); registerOre("blockRedstone", Blocks.redstone_block); registerOre("blockEmerald", Blocks.emerald_block); registerOre("blockQuartz", Blocks.quartz_block); registerOre("blockCoal", Blocks.coal_block); registerOre("blockGlassColorless", Blocks.glass); registerOre("blockGlass", Blocks.glass); registerOre("blockGlass", new ItemStack(Blocks.stained_glass, 1, WILDCARD_VALUE)); //blockGlass{Color} is added below with dyes registerOre("paneGlassColorless", Blocks.glass_pane); registerOre("paneGlass", Blocks.glass_pane); registerOre("paneGlass", new ItemStack(Blocks.stained_glass_pane, 1, WILDCARD_VALUE)); //paneGlass{Color} is added below with dyes registerOre("ingotIron", Items.iron_ingot); registerOre("ingotGold", Items.gold_ingot); registerOre("ingotBrick", Items.brick); registerOre("ingotBrickNether", Items.netherbrick); registerOre("nuggetGold", Items.gold_nugget); registerOre("gemDiamond", Items.diamond); registerOre("gemEmerald", Items.emerald); registerOre("gemQuartz", Items.quartz); registerOre("dustRedstone", Items.redstone); registerOre("dustGlowstone", Items.glowstone_dust); registerOre("gemLapis", new ItemStack(Items.dye, 1, 4)); registerOre("slimeball", Items.slime_ball); registerOre("glowstone", Blocks.glowstone); registerOre("cropWheat", Items.wheat); registerOre("cropPotato", Items.potato); registerOre("cropCarrot", Items.carrot); registerOre("stone", Blocks.stone); registerOre("cobblestone", Blocks.cobblestone); registerOre("sandstone", new ItemStack(Blocks.sandstone, 1, WILDCARD_VALUE)); registerOre("sand", new ItemStack(Blocks.sand, 1, WILDCARD_VALUE)); registerOre("dye", new ItemStack(Items.dye, 1, WILDCARD_VALUE)); registerOre("record", Items.record_13); registerOre("record", Items.record_cat); registerOre("record", Items.record_blocks); registerOre("record", Items.record_chirp); registerOre("record", Items.record_far); registerOre("record", Items.record_mall); registerOre("record", Items.record_mellohi); registerOre("record", Items.record_stal); registerOre("record", Items.record_strad); registerOre("record", Items.record_ward); registerOre("record", Items.record_11); registerOre("record", Items.record_wait); } // Build our list of items to replace with ore tags Map<ItemStack, String> replacements = new HashMap<ItemStack, String>(); replacements.put(new ItemStack(Items.stick), "stickWood"); replacements.put(new ItemStack(Blocks.planks), "plankWood"); replacements.put(new ItemStack(Blocks.planks, 1, WILDCARD_VALUE), "plankWood"); replacements.put(new ItemStack(Blocks.stone), "stone"); replacements.put(new ItemStack(Blocks.stone, 1, WILDCARD_VALUE), "stone"); replacements.put(new ItemStack(Blocks.cobblestone), "cobblestone"); replacements.put(new ItemStack(Blocks.cobblestone, 1, WILDCARD_VALUE), "cobblestone"); replacements.put(new ItemStack(Items.gold_ingot), "ingotGold"); replacements.put(new ItemStack(Items.iron_ingot), "ingotIron"); replacements.put(new ItemStack(Items.diamond), "gemDiamond"); replacements.put(new ItemStack(Items.emerald), "gemEmerald"); replacements.put(new ItemStack(Items.redstone), "dustRedstone"); replacements.put(new ItemStack(Items.glowstone_dust), "dustGlowstone"); replacements.put(new ItemStack(Blocks.glowstone), "glowstone"); replacements.put(new ItemStack(Items.slime_ball), "slimeball"); replacements.put(new ItemStack(Blocks.glass), "blockGlassColorless"); // Register dyes String[] dyes = { "Black", "Red", "Green", "Brown", "Blue", "Purple", "Cyan", "LightGray", "Gray", "Pink", "Lime", "Yellow", "LightBlue", "Magenta", "Orange", "White" }; for(int i = 0; i < 16; i++) { ItemStack dye = new ItemStack(Items.dye, 1, i); ItemStack block = new ItemStack(Blocks.stained_glass, 1, 15 - i); ItemStack pane = new ItemStack(Blocks.stained_glass_pane, 1, 15 - i); if (!hasInit) { registerOre("dye" + dyes[i], dye); registerOre("blockGlass" + dyes[i], block); registerOre("paneGlass" + dyes[i], pane); } replacements.put(dye, "dye" + dyes[i]); replacements.put(block, "blockGlass" + dyes[i]); replacements.put(pane, "paneGlass" + dyes[i]); } hasInit = true; ItemStack[] replaceStacks = replacements.keySet().toArray(new ItemStack[replacements.keySet().size()]); // Ignore recipes for the following items ItemStack[] exclusions = new ItemStack[] { new ItemStack(Blocks.lapis_block), new ItemStack(Items.cookie), new ItemStack(Blocks.stonebrick), new ItemStack(Blocks.stone_slab, 1, WILDCARD_VALUE), new ItemStack(Blocks.stone_stairs), new ItemStack(Blocks.cobblestone_wall), new ItemStack(Blocks.oak_stairs), new ItemStack(Blocks.spruce_stairs), new ItemStack(Blocks.birch_stairs), new ItemStack(Blocks.jungle_stairs), new ItemStack(Blocks.acacia_stairs), new ItemStack(Blocks.dark_oak_stairs), new ItemStack(Blocks.glass_pane) }; List<IRecipe> recipes = CraftingManager.getInstance().getRecipeList(); List<IRecipe> recipesToRemove = new ArrayList<IRecipe>(); List<IRecipe> recipesToAdd = new ArrayList<IRecipe>(); // Search vanilla recipes for recipes to replace for(Object obj : recipes) { if(obj instanceof ShapedRecipes) { ShapedRecipes recipe = (ShapedRecipes)obj; ItemStack output = recipe.getRecipeOutput(); if (output != null && containsMatch(false, exclusions, output)) { continue; } if(containsMatch(true, recipe.recipeItems, replaceStacks)) { recipesToRemove.add(recipe); recipesToAdd.add(new ShapedOreRecipe(recipe, replacements)); } } else if(obj instanceof ShapelessRecipes) { ShapelessRecipes recipe = (ShapelessRecipes)obj; ItemStack output = recipe.getRecipeOutput(); if (output != null && containsMatch(false, exclusions, output)) { continue; } if(containsMatch(true, (ItemStack[])recipe.recipeItems.toArray(new ItemStack[recipe.recipeItems.size()]), replaceStacks)) { recipesToRemove.add((IRecipe)obj); IRecipe newRecipe = new ShapelessOreRecipe(recipe, replacements); recipesToAdd.add(newRecipe); } } } recipes.removeAll(recipesToRemove); recipes.addAll(recipesToAdd); if (recipesToRemove.size() > 0) { FMLLog.info("Replaced %d ore recipies", recipesToRemove.size()); } } /** * Gets the integer ID for the specified ore name. * If the name does not have a ID it assigns it a new one. * * @param name The unique name for this ore 'oreIron', 'ingotIron', etc.. * @return A number representing the ID for this ore type */ public static int getOreID(String name) { Integer val = nameToId.get(name); if (val == null) { idToName.add(name); val = idToName.size() - 1; //0 indexed nameToId.put(name, val); idToStack.add(new ArrayList<ItemStack>()); idToStackUn.add(new UnmodifiableArrayList(idToStack.get(val))); } return val; } /** * Reverse of getOreID, will not create new entries. * * @param id The ID to translate to a string * @return The String name, or "Unknown" if not found. */ public static String getOreName(int id) { return (id >= 0 && id < idToName.size()) ? idToName.get(id) : "Unknown"; } /** * Gets the integer ID for the specified item stack. * If the item stack is not linked to any ore, this will return -1 and no new entry will be created. * * @param stack The item stack of the ore. * @return A number representing the ID for this ore type, or -1 if couldn't find it. */ @Deprecated // Use getOreIds below for more accuracy public static int getOreID(ItemStack stack) { if (stack == null || stack.getItem() == null) return -1; int id = Item.getIdFromItem(stack.getItem()); List<Integer> ids = stackToId.get(id); //Try the wildcard first if (ids == null || ids.size() == 0) { ids = stackToId.get(id | ((stack.getItemDamage() + 1) << 16)); // Mow the Meta specific one, +1 so that meta 0 is significant } return (ids != null && ids.size() > 0) ? ids.get(0) : -1; } /** * Gets all the integer ID for the ores that the specified item stakc is registered to. * If the item stack is not linked to any ore, this will return an empty array and no new entry will be created. * * @param stack The item stack of the ore. * @return An array of ids that this ore is registerd as. */ public static int[] getOreIDs(ItemStack stack) { if (stack == null || stack.getItem() == null) return new int[0]; Set<Integer> set = new HashSet<Integer>(); int id = Item.getIdFromItem(stack.getItem()); List<Integer> ids = stackToId.get(id); if (ids != null) set.addAll(ids); ids = stackToId.get(id | ((stack.getItemDamage() + 1) << 16)); if (ids != null) set.addAll(ids); Integer[] tmp = set.toArray(new Integer[set.size()]); int[] ret = new int[tmp.length]; for (int x = 0; x < tmp.length; x++) ret[x] = tmp[x]; return ret; } /** * Retrieves the ArrayList of items that are registered to this ore type. * Creates the list as empty if it did not exist. * * The returned List is unmodifiable, but will be updated if a new ore * is registered using registerOre * * @param name The ore name, directly calls getOreID * @return An arrayList containing ItemStacks registered for this ore */ public static ArrayList<ItemStack> getOres(String name) //TODO: 1.8 ArrayList -> List { return getOres(getOreID(name)); } /** * Retrieves the List of items that are registered to this ore type at this instant. * If the flag is TRUE, then it will create the list as empty if it did not exist. * * This option should be used by modders who are doing blanket scans in postInit. * It greatly reduces clutter in the OreDictionary is the responsible and proper * way to use the dictionary in a large number of cases. * * The other function above is utilized in OreRecipe and is required for the * operation of that code. * * @param name The ore name, directly calls getOreID if the flag is TRUE * @param alwaysCreateEntry Flag - should a new entry be created if empty * @return An arraylist containing ItemStacks registered for this ore */ public static List<ItemStack> getOres(String name, boolean alwaysCreateEntry) { if (alwaysCreateEntry) { return getOres(getOreID(name)); } return nameToId.get(name) != null ? getOres(getOreID(name)) : EMPTY_LIST; } /** * Returns whether or not an oreName exists in the dictionary. * This function can be used to safely query the Ore Dictionary without * adding needless clutter to the underlying map structure. * * Please use this when possible and appropriate. * * @param name The ore name * @return Whether or not that name is in the Ore Dictionary. */ public static boolean doesOreNameExist(String name) { return nameToId.get(name) != null; } /** * Retrieves a list of all unique ore names that are already registered. * * @return All unique ore names that are currently registered. */ public static String[] getOreNames() { return idToName.toArray(new String[idToName.size()]); } /** * Retrieves the ArrayList of items that are registered to this ore type. * Creates the list as empty if it did not exist. * * Warning: In 1.8, the return value will become a immutible list, * and this function WILL NOT create the entry if the ID doesn't exist, * IDs are intended to be internal OreDictionary things and modders * should not ever code them in. * * @param id The ore ID, see getOreID * @return An List containing ItemStacks registered for this ore */ @Deprecated // Use the named version not int public static ArrayList<ItemStack> getOres(Integer id) //TODO: delete in 1.8 in favor of unboxed version below { return getOres((int)id.intValue()); } private static ArrayList<ItemStack> getOres(int id) //TODO: change to ImmutibleList<ItemStack> in 1.8, also make private { while (idToName.size() < id + 1) // TODO: Remove this in 1.8, this is only for backwards compatibility { String name = "Filler: " + idToName.size(); idToName.add(name); nameToId.put(name, idToName.size() - 1); //0 indexed idToStack.add(null); idToStackUn.add(EMPTY_LIST); } return idToStackUn.size() > id ? idToStackUn.get(id) : EMPTY_LIST; } private static boolean containsMatch(boolean strict, ItemStack[] inputs, ItemStack... targets) { for (ItemStack input : inputs) { for (ItemStack target : targets) { if (itemMatches(target, input, strict)) { return true; } } } return false; } private static boolean containsMatch(boolean strict, List<ItemStack> inputs, ItemStack... targets) { for (ItemStack input : inputs) { for (ItemStack target : targets) { if (itemMatches(target, input, strict)) { return true; } } } return false; } public static boolean itemMatches(ItemStack target, ItemStack input, boolean strict) { if (input == null && target != null || input != null && target == null) { return false; } return (target.getItem() == input.getItem() && ((target.getItemDamage() == WILDCARD_VALUE && !strict) || target.getItemDamage() == input.getItemDamage())); } //Convenience functions that make for cleaner code mod side. They all drill down to registerOre(String, int, ItemStack) public static void registerOre(String name, Item ore){ registerOre(name, new ItemStack(ore)); } public static void registerOre(String name, Block ore){ registerOre(name, new ItemStack(ore)); } public static void registerOre(String name, ItemStack ore){ registerOreImpl(name, ore); } @Deprecated //Use named, not ID in 1.8+ public static void registerOre(int id, Item ore){ registerOre(id, new ItemStack(ore)); } @Deprecated //Use named, not ID in 1.8+ public static void registerOre(int id, Block ore){ registerOre(id, new ItemStack(ore)); } @Deprecated //Use named, not ID in 1.8+ public static void registerOre(int id, ItemStack ore){ registerOreImpl(getOreName(id), ore); } /** * Registers a ore item into the dictionary. * Raises the registerOre function in all registered handlers. * * @param name The name of the ore * @param id The ID of the ore * @param ore The ore's ItemStack */ private static void registerOreImpl(String name, ItemStack ore) { if (name == null || name.isEmpty() || "Unknown".equals(name)) return; //prevent bad IDs. if (ore == null || ore.getItem() == null) { FMLLog.bigWarning("Invalid registration attempt for an Ore Dictionary item with name %s has occurred. The registration has been denied to prevent crashes. The mod responsible for the registration needs to correct this.", name); return; //prevent bad ItemStacks. } int oreID = getOreID(name); int hash = Item.getIdFromItem(ore.getItem()); if (ore.getItemDamage() != WILDCARD_VALUE) { hash |= ((ore.getItemDamage() + 1) << 16); // +1 so 0 is significant } //Add things to the baked version, and prevent duplicates List<Integer> ids = stackToId.get(hash); if (ids != null && ids.contains(oreID)) return; if (ids == null) { ids = Lists.newArrayList(); stackToId.put(hash, ids); } ids.add(oreID); //Add to the unbaked version ore = ore.copy(); idToStack.get(oreID).add(ore); MinecraftForge.EVENT_BUS.post(new OreRegisterEvent(name, ore)); } public static class OreRegisterEvent extends Event { public final String Name; public final ItemStack Ore; public OreRegisterEvent(String name, ItemStack ore) { this.Name = name; this.Ore = ore; } } public static void rebakeMap() { //System.out.println("Baking OreDictionary:"); stackToId.clear(); for (int id = 0; id < idToStack.size(); id++) { List<ItemStack> ores = idToStack.get(id); if (ores == null) continue; for (ItemStack ore : ores) { int hash = Item.getIdFromItem(ore.getItem()); if (ore.getItemDamage() != WILDCARD_VALUE) { hash |= ((ore.getItemDamage() + 1) << 16); // +1 so meta 0 is significant } List<Integer> ids = stackToId.get(hash); if (ids == null) { ids = Lists.newArrayList(); stackToId.put(hash, ids); } ids.add(id); //System.out.println(id + " " + getOreName(id) + " " + Integer.toHexString(hash) + " " + ore); } } } //Pulled from Collections.UnmodifiableList, as we need to explicitly subclass ArrayList for backward compatibility. //Delete this class in 1.8 when we loose the ArrayList specific return types. private static class UnmodifiableArrayList<E> extends ArrayList<E> { final ArrayList<? extends E> list; UnmodifiableArrayList(ArrayList<? extends E> list) { super(0); this.list = list; } public ListIterator<E> listIterator() {return listIterator(0); } public boolean equals(Object o) { return o == this || list.equals(o); } public int hashCode() { return list.hashCode(); } public E get(int index) { return list.get(index); } public int indexOf(Object o) { return list.indexOf(o); } public int lastIndexOf(Object o) { return list.lastIndexOf(o); } public int size() { return list.size(); } public boolean isEmpty() { return list.isEmpty(); } public boolean contains(Object o) { return list.contains(o); } public Object[] toArray() { return list.toArray(); } public <T> T[] toArray(T[] a) { return list.toArray(a); } public String toString() { return list.toString(); } public boolean containsAll(Collection<?> coll) { return list.containsAll(coll); } public E set(int index, E element) { throw new UnsupportedOperationException(); } public void add(int index, E element) { throw new UnsupportedOperationException(); } public E remove(int index) { throw new UnsupportedOperationException(); } public boolean add(E e) { throw new UnsupportedOperationException(); } public boolean remove(Object o) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public boolean removeAll(Collection<?> coll) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection<?> coll) { throw new UnsupportedOperationException(); } public boolean addAll(Collection<? extends E> coll) { throw new UnsupportedOperationException(); } public boolean addAll(int index, Collection<? extends E> c) { throw new UnsupportedOperationException(); } public ListIterator<E> listIterator(final int index) { return new ListIterator<E>() { private final ListIterator<? extends E> i = list.listIterator(index); public boolean hasNext() {return i.hasNext();} public E next() {return i.next();} public boolean hasPrevious() {return i.hasPrevious();} public E previous() {return i.previous();} public int nextIndex() {return i.nextIndex();} public int previousIndex() {return i.previousIndex();} public void remove() { throw new UnsupportedOperationException(); } public void set(E e) { throw new UnsupportedOperationException(); } public void add(E e) { throw new UnsupportedOperationException(); } }; } public List<E> subList(int fromIndex, int toIndex) { return Collections.unmodifiableList(list.subList(fromIndex, toIndex)); } public Iterator<E> iterator() { return new Iterator<E>() { private final Iterator<? extends E> i = list.iterator(); public boolean hasNext() { return i.hasNext(); } public E next() { return i.next(); } public void remove() { throw new UnsupportedOperationException(); } }; } } }
package seedu.jimi.logic.commands; import java.util.HashSet; import java.util.Set; import seedu.jimi.commons.core.Messages; import seedu.jimi.commons.core.UnmodifiableObservableList; import seedu.jimi.commons.exceptions.IllegalValueException; import seedu.jimi.model.tag.Tag; import seedu.jimi.model.tag.UniqueTagList; import seedu.jimi.model.task.FloatingTask; import seedu.jimi.model.task.Name; import seedu.jimi.model.task.ReadOnlyTask; import seedu.jimi.model.task.UniqueTaskList; import seedu.jimi.model.task.UniqueTaskList.DuplicateTaskException; import seedu.jimi.model.task.UniqueTaskList.TaskNotFoundException; /** * * @author zexuan * * Edits an existing task/event in Jimi. */ public class EditCommand extends Command{ public static final String COMMAND_WORD = "edit"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Edits an existing task/event in Jimi. \n" + "Example: " + COMMAND_WORD + " 2 by 10th July at 12 pm"; public static final String MESSAGE_EDIT_TASK_SUCCESS = "Updated task details: %1$s"; public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in Jimi"; private final int taskIndex; //index of task/event to be edited private UniqueTagList newTagList; private Name newName; public EditCommand(String name, Set<String> tags, int taskIndex) throws IllegalValueException { final Set<Tag> tagSet = new HashSet<>(); for (String tagName : tags) { tagSet.add(new Tag(tagName)); } this.taskIndex = taskIndex; //if new fields are to be edited, instantiate them if(name != null) { this.newName = new Name(name); } if(tagSet != null) { this.newTagList = new UniqueTagList(tagSet); } } @Override public CommandResult execute() { UnmodifiableObservableList<ReadOnlyTask> lastShownList = model.getFilteredTaskList(); if (lastShownList.size() < taskIndex) { indicateAttemptToExecuteIncorrectCommand(); return new CommandResult(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } ReadOnlyTask taskToEdit = lastShownList.get(taskIndex - 1); try { model.deleteTask(taskToEdit); //delete UniqueTagList oldTagList = taskToEdit.getTags(); Name oldName = taskToEdit.getName(); if(newName != null && !oldName.equals(newName)){ if(newTagList != null && !oldTagList.equals(newTagList)){ model.addFloatingTask(new FloatingTask(newName, newTagList)); //change both name and tags } model.addFloatingTask(new FloatingTask(newName, oldTagList)); //change only name } else { model.addFloatingTask(new FloatingTask(oldName, oldTagList)); //change nothing //TODO: reduce redundancy } } catch (TaskNotFoundException pnfe) { assert false : "The target task cannot be missing"; } catch (UniqueTaskList.DuplicateTaskException e) { return new CommandResult(MESSAGE_DUPLICATE_TASK); } return new CommandResult(String.format(MESSAGE_EDIT_TASK_SUCCESS, lastShownList.get(lastShownList.size()-1))); } }
package org.rspql.spin.utils; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.topbraid.spin.model.Argument; import org.topbraid.spin.model.Template; import org.topbraid.spin.system.SPINLabels; import org.topbraid.spin.util.JenaUtil; import com.hp.hpl.jena.datatypes.DatatypeFormatException; import com.hp.hpl.jena.query.QuerySolutionMap; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import com.hp.hpl.jena.vocabulary.XSD; public class ArgumentHandler { public static Pattern urlPattern = Pattern.compile("^http(s?): /** * Validate a set of bindings against a template. Type checking is done * against an empty model. * * @param template * @param bindings * @param validationErrors * @param model */ public static void check(Template template, QuerySolutionMap bindings, List<String> validationErrors) { check(template, bindings, validationErrors, ModelFactory.createDefaultModel()); } /** * Validate a set of bindings against a template. Type checking is done * against the provided model. * * @param template * @param bindings * @param validationErrors * @param model */ public static void check(Template template, QuerySolutionMap bindings, List<String> validationErrors, Model model) { for (Argument arg : template.getArguments(false)) { String varName = arg.getVarName(); Resource valueType = arg.getValueType(); if (bindings.contains(varName)) { RDFNode value = bindings.get(varName); if (value.isLiteral()) { if (value.asLiteral().getDatatypeURI().equals(valueType.getURI())) { // System.err.println("Literals matched."); continue; } else { StringBuffer sb = new StringBuffer("Validation error: Literal "); sb.append(value.asLiteral().getLexicalForm()); sb.append(" ("); sb.append(value.asLiteral().getDatatype().getURI().replaceAll(XSD.getURI(), "xsd:")); sb.append(") for argument '"); sb.append(varName); sb.append("' must have datatype "); sb.append(SPINLabels.get().getLabel(valueType)); validationErrors.add(sb.toString()); } } else { if (valueType.equals(RDFS.Resource) || valueType.equals(RDF.Property)) { // System.err.println("Resource matched."); continue; } else { Resource resource = model.getResource(value.toString()); Property property = model.getProperty(value.toString()); Property propertyType = model.getProperty(valueType.toString()); if (resource.equals(valueType) || JenaUtil.hasIndirectType(resource, valueType) || JenaUtil.hasSuperClass(resource, valueType) ||JenaUtil.hasSuperProperty(property, propertyType)){ StringBuffer sb = new StringBuffer("Type of "); sb.append(resource); sb.append(" for argument '"); sb.append(varName); sb.append("' is an instance/subclass/subproperty of "); sb.append(SPINLabels.get().getLabel(valueType)); //System.out.println(sb.toString()); continue; } else { StringBuffer sb = new StringBuffer("Validation error: Type of "); sb.append(resource); sb.append(" for argument '"); sb.append(varName); sb.append("' must be of an instance/subclass/subproperty of "); sb.append(SPINLabels.get().getLabel(valueType)); validationErrors.add(sb.toString()); continue; } } } } else if (!arg.isOptional()) { validationErrors.add("Validation error: Missing required argument '" + varName + "'"); continue; } } } /** * Generate a set of typed bindings for a template based on a map of * strings. Warnings and errors are appended to the errors list. This also * adds default values for unspecified parameters (if available in * template). * * @param template * @param parameters * @param errors * @return bindings */ public static QuerySolutionMap createBindings(Template template, Map<String, String> parameters, List<String> errors) { QuerySolutionMap bindings = new QuerySolutionMap(); Map<String, Argument> arguments = template.getArgumentsMap(); for (Map.Entry<String, String> entry : parameters.entrySet()) { String name = entry.getKey(); String value = entry.getValue(); // Skip variables in the template that are not defined if (!arguments.containsKey(entry.getKey())) { errors.add(String.format("Binding warning: Variable '%s' is not defined for the template", name)); continue; } // Get value type for parameter Resource valueType = arguments.get(name).getValueType(); // Check if value type is an XSD data type if (valueType.getNameSpace().equals(XSD.getURI())) { // Attempt to create typed literal Literal literal = null; try { String datatypeURI = valueType.getURI(); literal = template.getModel().createTypedLiteral(value, datatypeURI); } catch (DatatypeFormatException e) { errors.add(String.format("Binding error: %s", e.getMessage())); continue; } if (literal != null) { bindings.add(name, literal); } } else { // Attempt to create resource Matcher m = urlPattern.matcher(value); if (m.find()) { bindings.add(name, ResourceFactory.createResource(value)); } else { errors.add(String.format("Binding error: Value %s is not a proper URL", value)); } } } // Set default values for (Argument arg : template.getArguments(false)) { if (!bindings.contains(arg.getVarName()) && arg.getDefaultValue() != null) { bindings.add(arg.getVarName(), arg.getDefaultValue()); } } return bindings; } /** * Create an RDF node from a string value. * * @param value * @param valueType * @param errors * @return rdfNode */ public static RDFNode createRDFNode(String value, Resource valueType, List<String> errors) { // Return null if no value or type given if (value == null || valueType == null) { return null; } // Check if value type is an XSD data type if (valueType.getNameSpace().equals(XSD.getURI())) { // Attempt to create typed literal Literal literal = null; try { String datatypeURI = valueType.getURI(); literal = ModelFactory.createDefaultModel().createTypedLiteral(value, datatypeURI); } catch (DatatypeFormatException e) { errors.add(String.format("RDFNode error: %s", e.getMessage())); return null; } return literal; } else { // Attempt to create resource Matcher m = urlPattern.matcher(value); if (m.find()) { return ResourceFactory.createResource(value); } else { errors.add(String.format("RDFNode error: Value %s is not a proper URL", value)); return null; } } } }
package net.sf.mzmine.util.components; import org.controlsfx.glyphfont.Glyph; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.ToggleButton; public class ButtonCell<T> extends TableCell<T, Boolean> { ToggleButton button; public ButtonCell(TableColumn<T, Boolean> column) { button = new ToggleButton(); button.setGraphic(new Glyph("FontAwesome", "EYE")); button.setOnMouseClicked(event -> { final TableView<T> tableView = getTableView(); tableView.getSelectionModel().select(getTableRow().getIndex()); tableView.edit(tableView.getSelectionModel().getSelectedIndex(), column); if (button.isSelected()) { commitEdit(false); } else { commitEdit(true); } }); } @Override protected void updateItem(Boolean item, boolean empty) { super.updateItem(item, empty); if (empty) { setGraphic(null); } else { setGraphic(button); } } }
package siren; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * An embedded entity representation that contains all the characteristics of a typical entity. * One difference is that a sub-entity MUST contain a rel attribute to describe its relationship to the parent entity. * @author jonfreer * @since 8/13/17 */ public class EmbeddedRepresentationSubEntity extends Entity { /** * Constructs an instance of {@link EmbeddedRepresentationSubEntity.Builder}. */ public static class Builder implements siren.Builder<EmbeddedRepresentationSubEntity>{ private List<String> rel; private List<String> classes; private Map<String, Object> properties; private List<Action> actions; private List<Link> links; private List<EntityBase> subEntities; private String title; /** * Constructs an instance of {@link EmbeddedRepresentationSubEntity.Builder}. */ public Builder(){} /** * Adds the class provided to the current state of the builder. * @param klass Describes the nature of an entity's content based on the current representation. * Possible values are implementation-dependent and should be documented. * @return The builder this method is called on. */ public Builder klass(String klass){ if(this.classes == null) { this.classes = new ArrayList<String>(); } this.classes.add(klass); return this; } /** * Adds the class provided to the current state of the builder. * @param classNames Describes the nature of an entity's content based on the current representation. * Possible values are implementation-dependent and should be documented. * @return The builder this method is called on. */ public Builder klasses(List<String> classNames){ if(this.classes == null) { this.classes = new ArrayList<String>(); } this.classes.addAll(classNames); return this; } /** * Adds the property provided to the current state of the builder. * @param propertyKey The key portion of a key-value pair that describes the state of an entity. * @param propertyValue The value portion of a key-value pair that describes the state of an entity. * @param <T> The type of the value portion of a key-value pair that describes the state of an entity. * @return The builder this method is called on. */ public <T> Builder property(String propertyKey, T propertyValue){ if(this.properties == null){ this.properties = new HashMap<String, Object>(); } this.properties.put(propertyKey, propertyValue); return this; } /** * Adds the properties provided to the current state of the builder. * @param properties A set of key-value pairs that describe the state of an entity. * @return The builder this method is called on. */ public Builder properties(Map<String, Object> properties){ if(this.properties == null){ this.properties = new HashMap<String, Object>(); } this.properties.putAll(properties); return this; } /** * Adds the action provided to the current state of the builder. * @param action An action showing an available behavior an entity exposes. * @return The builder this method is called on. */ public Builder action(Action action){ if(this.actions == null){ this.actions = new ArrayList<Action>(); } this.actions.add(action); return this; } /** * Adds the actions provided to the current state of the builder. * @param actions Actions showing available behaviors an entity exposes. * @return The builder this method is called on. */ public Builder actions(List<Action> actions){ if(this.actions == null){ this.actions = new ArrayList<>(); } this.actions.addAll(actions); return this; } /** * Adds the link provided to the current state of the builder. * @param link A navigational link, distinct from an entity relationship. * Link items should contain a `rel` attribute to describe the relationship * and an `href` attribute to point to the target URI. * Entities should include a link `rel` to `self`. * @return The builder this method is called on. */ public Builder link(Link link){ if(this.links == null){ this.links = new ArrayList<Link>(); } this.links.add(link); return this; } /** * Adds the links provided to the current state of the builder. * @param links Navigational links, distinct from entity relationships. Link items should contain a `rel` * attribute to describe the relationship and an `href` attribute to point to the target URI. * @return The builder this method is called on. */ public Builder links(List<Link> links){ if(this.links == null){ this.links = new ArrayList<>(); } this.links.addAll(links); return this; } /** * Adds the sub-entity provided to the current state of the builder. * @param subEntity A sub-entity represented as an embedded link or an embedded entity representation. * @return The builder this method is called on. */ public Builder subEntity(EntityBase subEntity){ if(this.subEntities == null){ this.subEntities = new ArrayList<>(); } this.subEntities.add(subEntity); return this; } /** * Adds the title provided to the current state of the builder. * @param title Descriptive text about the entity. * @return The builder this method is called on. */ public Builder title(String title){ this.title = title; return this; } public Builder rel(String rel){ if(this.rel == null){ this.rel = new ArrayList<String>(); } this.rel.add(rel); return this; } /** * Clears the state of the builder. */ @Override public void clear() { this.classes = null; this.properties = null; this.actions = null; this.links = null; this.title = null; this.rel = null; this.subEntities = null; } /** * Constructs an instance with the * current state of the builder. * * @return Instance with the current state of the builder. */ @Override public EmbeddedRepresentationSubEntity build() { // TODO 2017-08-15 - FREER - Do some checking that required state has been set. return new EmbeddedRepresentationSubEntity( this.classes, this.properties, this.actions, this.links, this.title, this.rel, this.subEntities ); } } private List<String> rel; private EmbeddedRepresentationSubEntity( List<String> klass, Map<String, Object> properties, List<Action> actions, List<Link> links, String title, List<String> rel, List<EntityBase> subEntities ){ super(klass, properties, actions, links, title, subEntities); if(rel == null){ throw new IllegalArgumentException("'rel' cannot be null as it is required."); } this.rel = rel; } public List<String> getRel(){ if(this.rel == null) return this.rel; List<String> relCopy = new ArrayList<String>(); relCopy.addAll(this.rel); return relCopy; } }
package org.scijava.convert; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.scijava.Priority; import org.scijava.plugin.Plugin; import org.scijava.util.ArrayUtils; import org.scijava.util.ConversionUtils; import org.scijava.util.Types; /** * Default {@link Converter} implementation. Provides useful conversion * functionality for many common conversion cases. * <p> * Supported conversions include: * </p> * <ul> * <li>Object to Array</li> * <li>Object to Collection</li> * <li>Number to Number</li> * <li>Object to String</li> * <li>String to Character</li> * <li>String to Enum</li> * <li>Objects where the destination Class has a constructor which takes that * Object * </li> * </ul> * * @author Mark Hiner */ @Plugin(type = Converter.class, priority = Priority.EXTREMELY_LOW) public class DefaultConverter extends AbstractConverter<Object, Object> { // -- ConversionHandler methods -- @Override public Object convert(final Object src, final Type dest) { // Handle array types, including generic array types. final Type componentType = Types.component(dest); if (componentType != null) { // NB: Destination is an array type. return convertToArray(src, Types.raw(componentType)); } // Handle parameterized collection types. if (dest instanceof ParameterizedType && isCollection(dest)) { return convertToCollection(src, (ParameterizedType) dest); } // This wasn't a collection or array, so convert it as a single element. return convert(src, Types.raw(dest)); } @Override public <T> T convert(final Object src, final Class<T> dest) { // ensure type is well-behaved, rather than a primitive type final Class<T> saneDest = Types.box(dest); // Handle array types if (isArray(dest)) { @SuppressWarnings("unchecked") T array = (T) convertToArray(src, Types.raw(Types.component(dest))); return array; } // special case for conversion from number to number if (src instanceof Number) { final Number number = (Number) src; if (saneDest == Byte.class) { final Byte result = number.byteValue(); @SuppressWarnings("unchecked") final T typedResult = (T) result; return typedResult; } if (saneDest == Double.class) { final Double result = number.doubleValue(); @SuppressWarnings("unchecked") final T typedResult = (T) result; return typedResult; } if (saneDest == Float.class) { final Float result = number.floatValue(); @SuppressWarnings("unchecked") final T typedResult = (T) result; return typedResult; } if (saneDest == Integer.class) { final Integer result = number.intValue(); @SuppressWarnings("unchecked") final T typedResult = (T) result; return typedResult; } if (saneDest == Long.class) { final Long result = number.longValue(); @SuppressWarnings("unchecked") final T typedResult = (T) result; return typedResult; } if (saneDest == Short.class) { final Short result = number.shortValue(); @SuppressWarnings("unchecked") final T typedResult = (T) result; return typedResult; } } // special cases for strings if (src instanceof String) { // source type is String final String s = (String) src; if (s.isEmpty()) { // return null for empty strings return Types.nullValue(dest); } // use first character when converting to Character if (saneDest == Character.class) { final Character c = new Character(s.charAt(0)); @SuppressWarnings("unchecked") final T result = (T) c; return result; } // special case for conversion to enum if (dest.isEnum()) { final T result = ConversionUtils.convertToEnum(s, dest); if (result != null) return result; } } if (saneDest == String.class) { // destination type is String; use Object.toString() method if (src.getClass().isArray()) { final String elementString = ArrayUtils.toCollection(src).stream() .map(object -> convert(object, String.class)) .collect(Collectors.joining(",")); String sb = "[" + elementString + ']'; @SuppressWarnings("unchecked") final T result = (T) elementString; return result; } else { final String sValue = src.toString(); @SuppressWarnings("unchecked") final T result = (T) sValue; return result; } } // wrap the original object with one of the new type, using a constructor try { final Constructor<?> ctor = getConstructor(saneDest, src.getClass()); if (ctor == null) return null; @SuppressWarnings("unchecked") final T instance = (T) ctor.newInstance(src); return instance; } catch (final Exception exc) { // TODO: Best not to catch blanket Exceptions here. // no known way to convert return null; } } @Override public Class<Object> getOutputType() { return Object.class; } @Override public Class<Object> getInputType() { return Object.class; } // -- Helper methods -- private Constructor<?> getConstructor(final Class<?> type, final Class<?> argType) { for (final Constructor<?> ctor : type.getConstructors()) { final Class<?>[] params = ctor.getParameterTypes(); if (params.length == 1 && Types.isAssignable(Types.box(argType), Types.box(params[0]))) { return ctor; } } return null; } private boolean isArray(final Type type) { return Types.component(type) != null; } private boolean isCollection(final Type type) { return Types.isAssignable(Types.raw(type), Collection.class); } private Object convertToArray(final Object value, final Class<?> componentType) { // First we make sure the value is a collection. This provides the simplest // interface for iterating over all the elements. We use SciJava's // PrimitiveArray collection implementations internally, so that this // conversion is always wrapping by reference, for performance. final Collection<?> items = ArrayUtils.toCollection(value); final Object array = Array.newInstance(componentType, items.size()); // Populate the array by converting each item in the value collection // to the component type. int index = 0; for (final Object item : items) { Array.set(array, index++, convert(item, componentType)); } return array; } private Object convertToCollection(final Object value, final ParameterizedType pType) { final Collection<Object> collection = createCollection(Types.raw(pType)); if (collection == null) return null; // Populate the collection. final Collection<?> items = ArrayUtils.toCollection(value); // TODO: The following can fail; e.g. "Foo extends ArrayList<String>" final Type collectionType = pType.getActualTypeArguments()[0]; for (final Object item : items) { collection.add(convert(item, collectionType)); } return collection; } private Collection<Object> createCollection(final Class<?> type) { // If we were given an interface or abstract class, and not a concrete // class, we attempt to make default implementations. if (type.isInterface() || Modifier.isAbstract(type.getModifiers())) { // We don't have a concrete class. If it's a set or a list, we use // the typical default implementation. Otherwise we won't convert. if (Types.isAssignable(type, List.class)) return new ArrayList<>(); if (Types.isAssignable(type, Set.class)) return new HashSet<>(); return null; } // Got a concrete type. Instantiate it. try { @SuppressWarnings("unchecked") final Collection<Object> c = (Collection<Object>) type.newInstance(); return c; } catch (final InstantiationException exc) { return null; } catch (final IllegalAccessException exc) { return null; } } // -- Deprecated API -- @Override @Deprecated public boolean canConvert(final Class<?> src, final Type dest) { // Handle array types, including generic array types. if (isArray(dest)) return true; // Handle parameterized collection types. if (dest instanceof ParameterizedType && isCollection(dest) && createCollection(Types.raw(dest)) != null) { return true; } return super.canConvert(src, dest); } @Override @Deprecated public boolean canConvert(final Class<?> src, final Class<?> dest) { // ensure type is well-behaved, rather than a primitive type final Class<?> saneDest = Types.box(dest); // OK for numerical conversions if (Types.isAssignable(Types.box(src), Number.class) && (Types.isByte(dest) || Types.isDouble(dest) || Types.isFloat(dest) || Types.isInteger(dest) || Types.isLong(dest) || Types.isShort(dest))) { return true; } // OK if string if (saneDest == String.class) return true; if (Types.isAssignable(src, String.class)) { // OK if source type is string and destination type is character // (in this case, the first character of the string would be used) if (saneDest == Character.class) return true; // OK if source type is string and destination type is an enum if (dest.isEnum()) return true; } // OK if appropriate wrapper constructor exists try { return getConstructor(saneDest, src) != null; } catch (final Exception exc) { // TODO: Best not to catch blanket Exceptions here. // no known way to convert return false; } } }
package nl.github.martijn9612.fishy; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; /** * This class logs to a file to observe the behaviour of a program */ public class ActionLogger { private static FileWriter fileWriter; private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); ActionLogger() { try { fileWriter = new FileWriter("log.txt", false); } catch (Exception e) { System.out.println(e.toString()); } } /** * Logs one line to file to log in. * @param text Text to log * @param className Class the log is called in */ public void logLine(String text, String className) { try { fileWriter.write("[ " + getTimeStamp() + "] - " + text + " - " + className + "\n"); } catch (IOException e) { System.out.println("Unable to log to file!"); e.printStackTrace(); } } /** * Logs one line to file to log in. * @param text Text to log * @param className Class the log is called in * @param isError Adds additional error text if set to true */ public void logLine(String text, String className, boolean isError) { try { if (isError) { fileWriter.write("[ERROR!][ " + getTimeStamp() + "] - " + text + " - " + className + "\n"); } else { logLine(text, className); } } catch (IOException e) { System.out.println("Unable to log to file!"); e.printStackTrace(); } } /** * Closes the filewriter so that the lines are written, otherwise all the logs are lost. */ public void close() { try { fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Gets the current time to specify the moment the log was made. * @return String with the current time */ private String getTimeStamp() { return dateFormat.format(new Date()); } }
package skadistats.clarity.examples.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import skadistats.clarity.model.Entity; import skadistats.clarity.processor.entities.Entities; import skadistats.clarity.processor.entities.UsesEntities; import skadistats.clarity.processor.runner.AbstractRunner; import skadistats.clarity.processor.runner.Context; import skadistats.clarity.processor.runner.SimpleRunner; import skadistats.clarity.source.InputStreamSource; import skadistats.clarity.util.TextTable; import java.io.UnsupportedEncodingException; @UsesEntities public class Main { private final Logger log = LoggerFactory.getLogger(Main.class.getPackage().getClass()); public void run(String[] args) throws Exception { long tStart = System.currentTimeMillis(); AbstractRunner<SimpleRunner> r = new SimpleRunner(new InputStreamSource(System.in)).runWith(this); summary(r.getContext()); long tMatch = System.currentTimeMillis() - tStart; log.info("total time taken: {}s", (tMatch) / 1000.0); } private void summary(Context ctx) throws UnsupportedEncodingException { Entity ps = ctx.getProcessor(Entities.class).getByDtName("DT_DOTA_PlayerResource"); String[][] columns = new String[][]{ {"Name", "m_iszPlayerNames"}, {"Level", "m_iLevel"}, {"K", "m_iKills"}, {"D", "m_iDeaths"}, {"A", "m_iAssists"}, {"Gold", "EndScoreAndSpectatorStats.m_iTotalEarnedGold"}, {"LH", "m_iLastHitCount"}, {"DN", "m_iDenyCount"}, }; TextTable.Builder b = new TextTable.Builder(); for (int c = 0; c < columns.length; c++) { b.addColumn(columns[c][0], c == 0 ? TextTable.Alignment.LEFT : TextTable.Alignment.RIGHT); } TextTable t = b.build(); for (int c = 0; c < columns.length; c++) { int baseIndex = ps.getDtClass().getPropertyIndex(columns[c][1] + ".0000"); for (int r = 0; r < 10; r++) { Object val = ps.getState()[baseIndex + r]; String str = new String(val.toString().getBytes("ISO-8859-1")); t.setData(r, c, str); } } System.out.println(t); } public static void main(String[] args) throws Exception { new Main().run(args); } }
package org.scijava.ui.swing.script; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import org.scijava.Context; import org.scijava.script.ScriptLanguage; import org.scijava.script.ScriptREPL; import org.scijava.script.ScriptService; /** * A side pane with information about available languages and variables. * * @author Curtis Rueden */ public class VarsPane extends JPanel { private final ScriptREPL repl; private final JComboBox langBox; private final VarsTableModel varsTableModel; public VarsPane(final Context context, final ScriptREPL repl) { this.repl = repl; setLayout(new BorderLayout()); final ScriptService scriptService = context.service(ScriptService.class); final List<ScriptLanguage> langList = scriptService.getLanguages(); final ScriptLanguage[] langs = langList.toArray(new ScriptLanguage[0]); langBox = new JComboBox(langs); langBox.setMaximumRowCount(25); langBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final ScriptLanguage lang = (ScriptLanguage) langBox.getSelectedItem(); if (lang == repl.getInterpreter().getLanguage()) return; // no change try { repl.lang(lang.getLanguageName()); } catch (final RuntimeException exc) { // Something went wrong... // TODO: Issue the exception to the log via the LogService. } update(); } }); add(langBox, BorderLayout.NORTH); varsTableModel = new VarsTableModel(); final JTable varsTable = new JTable(varsTableModel); varsTable.getColumnModel().getColumn(0).setMinWidth(120); varsTable.getColumnModel().getColumn(0).setMaxWidth(120); varsTable.getColumnModel().getColumn(1).setPreferredWidth(120); add(new JScrollPane(varsTable), BorderLayout.CENTER); varsTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN); final JCheckBox showTypes = new JCheckBox("Show variable types"); showTypes.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { varsTableModel.setShowTypes(showTypes.isSelected()); } }); add(showTypes, BorderLayout.SOUTH); update(); } // -- VarsPane methods -- public void update() { langBox.setSelectedItem(repl.getInterpreter().getLanguage()); varsTableModel.update(); } // -- Helper classes -- /** Helper class for the table of variables. */ private class VarsTableModel extends AbstractTableModel { private final ArrayList<String> varNames = new ArrayList<String>(); private boolean showTypes; // -- InterpreterTableModel methods -- public void update() { varNames.clear(); try { varNames.addAll(repl.getInterpreter().getBindings().keySet()); Collections.sort(varNames); } catch (final RuntimeException exc) { // Something went wrong. Leave the variables list empty. // TODO: Issue the exception to the log via the LogService. } fireTableDataChanged(); } public void setShowTypes(final boolean showTypes) { this.showTypes = showTypes; VarsPane.this.update(); } // -- TableModel methods -- @Override public int getColumnCount() { return 2; } @Override public String getColumnName(final int columnIndex) { switch (columnIndex) { case 0: return "Name"; case 1: return "Value"; default: throw invalidColumnException(columnIndex); } } @Override public int getRowCount() { return repl.getInterpreter().getBindings().size(); } @Override public Object getValueAt(final int rowIndex, final int columnIndex) { if (rowIndex >= varNames.size()) return null; final String varName = varNames.get(rowIndex); switch (columnIndex) { case 0: return varName; case 1: return value(varName); default: throw invalidColumnException(columnIndex); } } // -- Helper methods -- private String value(final String varName) { final Object value = repl.getInterpreter().getBindings().get(varName); if (value == null) return "<null>"; final String vs = value.toString(); final String type = value.getClass().getName(); return vs.startsWith(type) || !showTypes ? vs : vs + " [" + type + "]"; } private ArrayIndexOutOfBoundsException invalidColumnException( final int columnIndex) { return new ArrayIndexOutOfBoundsException("Invalid column index: " + columnIndex); } } }
package nl.tudelft.lifetiles.graph.view; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.paint.Color; import nl.tudelft.lifetiles.graph.controller.GraphController; import nl.tudelft.lifetiles.graph.model.Edge; import nl.tudelft.lifetiles.graph.model.Graph; import nl.tudelft.lifetiles.annotation.model.ResistanceAnnotation; import nl.tudelft.lifetiles.sequence.model.SequenceSegment; /** * The TileView is responsible for displaying the graph given from * the TileController. * */ public class TileView { /** * Default color of a tile element. */ private static Color defaultColor = Color.web("a1d3ff"); /** * The edges contains all EdgeLines to be displayed. */ private final Group edges; /** * The nodes contains all Vertices to be displayed. */ private final Map<SequenceSegment, VertexView> nodemap; /** * The bookmarks group contains all bookmarks and annotations to be * displayed. */ private Group bookmarks; /** * The root contains all the to be displayed * elements. */ private Group root; /** * The lanes list which contains the occupation of the lanes inside the * tileview. */ private List<Long> lanes; /** * Controller for the View. */ private final GraphController controller; /** * Create the TileView by initializing the groups where the to be drawn * vertices and edges are stored. * * @param control * The controller for the TileView */ public TileView(final GraphController control) { controller = control; nodemap = new HashMap<SequenceSegment, VertexView>(); edges = new Group(); bookmarks = new Group(); } /** * Draw the given graph. * * @param segments * Graph to be drawn * @param graph * Graph to base the edges on * @param annotations * Map from segment to annotations. * @return the elements that must be displayed on the screen */ public final Group drawGraph(final Set<SequenceSegment> segments, final Graph<SequenceSegment> graph, final Map<SequenceSegment, List<ResistanceAnnotation>> annotations) { Group root = new Group(); lanes = new ArrayList<Long>(); for (SequenceSegment segment : segments) { List<ResistanceAnnotation> segmentAnnotations = null; if (annotations != null && annotations.containsKey(segment)) { annotations.get(segment); } drawVertexLane(segment, segmentAnnotations); } drawEdges(graph); Group nodes = new Group(); for (Entry<SequenceSegment, VertexView> entry : nodemap.entrySet()) { nodes.getChildren().add(entry.getValue()); } root.getChildren().addAll(nodes, edges, bookmarks); return root; } /** * @param graph * graph to draw the edges from */ private void drawEdges(final Graph<SequenceSegment> graph) { for (Edge<SequenceSegment> edge : graph.getAllEdges()) { if (nodemap.containsKey(graph.getSource(edge)) && nodemap.containsKey(graph.getDestination(edge))) { VertexView source = nodemap.get(graph.getSource(edge)); VertexView destination = nodemap .get(graph.getDestination(edge)); drawEdge(source, destination); } } } /** * Draws a given segment to an available position in the graph. * * @param segment * segment to be drawn * @param annotations * List of annotations in this segment */ private void drawVertexLane(final SequenceSegment segment, final List<ResistanceAnnotation> annotations) { for (int index = 0; index < lanes.size(); index++) { if (lanes.get(index) <= segment.getUnifiedStart() && segmentFree(index, segment)) { drawVertex(index, segment, annotations); segmentInsert(index, segment); return; } } drawVertex(lanes.size(), segment, annotations); segmentInsert(lanes.size(), segment); } /** * Returns the mutation color of a given mutation. Default if no mutation. * * @param mutation * mutation to return color from. * @return color of the mutation */ private Color sequenceColor(final Mutation mutation) { if (mutation == null) { return defaultColor; } else { return mutation.getColor(); } } /** * Create an Edge that can be displayed on the screen. * * @param source * Node to draw from * @param destination * Node to draw to */ private void drawEdge(final Node source, final Node destination) { EdgeLine edge = new EdgeLine(source, destination); edges.getChildren().add(edge); } /** * Create a Vertex that can be displayed on the screen. * * @param index * top left y coordinate * @param segment * the segment to be drawn in the vertex * @param annotations * the annotations of the vertex */ private void drawVertex(final double index, final SequenceSegment segment, final List<ResistanceAnnotation> annotations) { String text = segment.getContent().toString(); long start = segment.getUnifiedStart(); long width = segment.getContent().getLength(); long height = segment.getSources().size(); Color color = sequenceColor(segment.getMutation()); VertexView vertex = new VertexView(text, start, index, width, height, color); nodemap.put(segment, vertex); vertex.setOnMouseClicked(event -> controller.clicked(segment)); // Hovering vertex.setOnMouseEntered(event -> controller.hovered(segment, true)); vertex.setOnMouseExited(event -> controller.hovered(segment, false)); if (annotations != null) { for (ResistanceAnnotation annotation : annotations) { long segmentPosition = annotation.getGenomePosition() - segment.getStart(); Bookmark bookmark = new Bookmark(vertex, annotation, segmentPosition); bookmarks.getChildren().add(bookmark); } } } /** * Check if there is a free spot to draw the segment at this location. * * @param ind * location in the linked list of already drawn segments * @param segment * segment to be drawn * @return Boolean indicating if there is a free spot */ private boolean segmentFree(final int ind, final SequenceSegment segment) { for (int height = 0; height < segment.getSources().size(); height++) { int position = ind + height; if (position < lanes.size() && lanes.get(position) > segment.getUnifiedStart()) { return false; } } return true; } /** * Insert a segment in the linked list. * * @param index * location in the linked list of already drawn segments * @param segment * segment to be inserted */ private void segmentInsert(final int index, final SequenceSegment segment) { for (int height = 0; height < segment.getSources().size(); height++) { int position = index + height; if (position < lanes.size()) { lanes.set(position, segment.getUnifiedEnd()); } else { lanes.add(position, segment.getUnifiedEnd()); } } } }
package skadistats.clarity.examples.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import skadistats.clarity.decoder.BitStream; import skadistats.clarity.decoder.s2.FieldOpType; import skadistats.clarity.decoder.s2.HuffmanTree; import skadistats.clarity.decoder.unpacker.Unpacker; import skadistats.clarity.model.FieldPath; import skadistats.clarity.model.StringTable; import skadistats.clarity.model.s2.S2DTClass; import skadistats.clarity.model.s2.field.FieldProperties; import skadistats.clarity.model.s2.field.FieldType; import skadistats.clarity.processor.reader.OnTickStart; import skadistats.clarity.processor.runner.Context; import skadistats.clarity.processor.runner.SimpleRunner; import skadistats.clarity.processor.sendtables.DTClasses; import skadistats.clarity.processor.sendtables.UsesDTClasses; import skadistats.clarity.processor.stringtables.StringTables; import skadistats.clarity.processor.stringtables.UsesStringTable; import skadistats.clarity.source.MappedFileSource; import skadistats.clarity.util.TextTable; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; @UsesDTClasses @UsesStringTable("instancebaseline") public class Main { public static final HuffmanTree HUFFMAN_TREE = new HuffmanTree(); private final Logger log = LoggerFactory.getLogger(Main.class.getPackage().getClass()); @OnTickStart public void onTickStart(Context ctx, boolean synthetic) throws InterruptedException, FileNotFoundException, UnsupportedEncodingException { if (ctx.getTick() == 50000) { //System.out.println(new HuffmanGraph(FieldPathDecoder.HUFFMAN_TREE).generate()); StringTables stringTables = ctx.getProcessor(StringTables.class); DTClasses dtClasses = ctx.getProcessor(DTClasses.class); StringTable baseline = stringTables.forName("instancebaseline"); PrintStream[] ps = new PrintStream[] { System.out, null, }; List<String> onlyThese = new ArrayList<>(); //onlyThese = Arrays.asList("CBaseAnimating"); Exception exx; for (int idx = 0; idx < baseline.getEntryCount(); idx++) { int clsId = Integer.valueOf(baseline.getNameByIndex(idx)); if (baseline.getValueByIndex(idx) != null) { S2DTClass dtClass = (S2DTClass) dtClasses.forClassId(clsId); if (onlyThese.size() != 0 && !onlyThese.contains(dtClass.getDtName())) { continue; } ps[0] = new PrintStream(new FileOutputStream("baselines/" + dtClass.getDtName() + ".txt"), true, "UTF-8"); TextTable.Builder b = new TextTable.Builder(); b.setTitle(dtClass.getDtName()); b.setFrame(TextTable.FRAME_COMPAT); b.setPadding(0, 0); b.addColumn("FP"); b.addColumn("Name"); b.addColumn("L", TextTable.Alignment.RIGHT); b.addColumn("H", TextTable.Alignment.RIGHT); b.addColumn("BC", TextTable.Alignment.RIGHT); b.addColumn("Flags", TextTable.Alignment.RIGHT); b.addColumn("Decoder"); b.addColumn("Type"); b.addColumn("Value"); b.addColumn("#", TextTable.Alignment.RIGHT); b.addColumn("read"); TextTable t = b.build(); BitStream bs = new BitStream(baseline.getValueByIndex(idx)); exx = null; try { List<FieldPath> fieldPaths = new ArrayList<>(); FieldPath fp = new FieldPath(); while (true) { FieldOpType op = HUFFMAN_TREE.decodeOp(bs); op.execute(fp, bs); if (op == FieldOpType.FieldPathEncodeFinish) { break; } fieldPaths.add(fp); fp = new FieldPath(fp); } for (int r = 0; r < fieldPaths.size(); r++) { fp = fieldPaths.get(r); FieldProperties f = dtClass.getFieldForFieldPath(fp).getProperties(); FieldType ft = dtClass.getTypeForFieldPath(fp); t.setData(r, 0, fp); t.setData(r, 1, dtClass.getNameForFieldPath(fp)); t.setData(r, 2, f.getLowValue()); t.setData(r, 3, f.getHighValue()); t.setData(r, 4, f.getBitCount()); t.setData(r, 5, f.getEncodeFlags() != null ? Integer.toHexString(f.getEncodeFlags()) : "-"); t.setData(r, 7, String.format("%s%s", ft.toString(true), f.getEncoder() != null ? String.format(" {%s}", f.getEncoder()) : "")); int offsBefore = bs.pos(); Unpacker unpacker = dtClass.getUnpackerForFieldPath(fp); if (unpacker == null) { System.out.format("no unpacker for field %s with type %s!", f.getName(), f.getType()); System.exit(1); } Object data = unpacker.unpack(bs); t.setData(r, 6, unpacker.getClass().getSimpleName().toString()); t.setData(r, 8, data); t.setData(r, 9, bs.pos() - offsBefore); t.setData(r, 10, bs.toString(offsBefore, bs.pos())); } } catch (Exception e) { exx = e; } finally { for (PrintStream s : ps) { if (s == null) { continue; } t.print(s); s.format("%s/%s remaining: %s\n", bs.remaining(), bs.len(), bs.toString(bs.pos(), bs.len())); if (exx != null) { exx.printStackTrace(s); } s.format("\n\n\n"); } } } } } } public void run(String[] args) throws Exception { long tStart = System.currentTimeMillis(); new SimpleRunner(new MappedFileSource(args[0])).runWith(this); long tMatch = System.currentTimeMillis() - tStart; log.info("total time taken: {}s", (tMatch) / 1000.0); } public static void main(String[] args) throws Exception { new Main().run(args); } }
package org.se.lab.web; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; import org.apache.log4j.Logger; import org.se.lab.data.Community; import org.se.lab.data.User; import org.se.lab.service.CommunityService; import org.se.lab.service.UserService; @Named @RequestScoped public class CommunityOverviewBean { private final Logger LOG = Logger.getLogger(CommunityOverviewBean.class); // Activate when DAO works @Inject private CommunityService service; private List<Community> communities; private Community selectedCommunity; @PostConstruct public void init() { // DummyData communities = new ArrayList<>(); // When service works communities = service.findAll(); } public List<Community> getCommunities() { return communities; } public void setCommunities(List<Community> communities) { this.communities = communities; } public Community getSelectedCommunity() { return selectedCommunity; } public void setSelectedCommunity(Community selectedCommunity) { this.selectedCommunity = selectedCommunity; } public void gotoCom() { LOG.info("In Method gotoCom"); if (selectedCommunity != null) { LOG.info("Selected Community: " + selectedCommunity.getId() + " " + selectedCommunity.getDescription()); // To be done // go to community page if exist -> use data of selectedCommunity to distinct } } }
package org.usfirst.frc.team4828.vision; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.nio.charset.Charset; import org.usfirst.frc.team4828.Ultrasonic; public class Pixy implements Runnable { private static final String HOST = "pixyco.local"; private static final int PORT = 5800; private static final int PIXY_SIDE = 1; //-1 for right, 1 for left private boolean enabled; private boolean connected; private boolean blocksDetected; private volatile Frame currentFrame; private volatile Frame lastFrame; private BufferedReader in; private Socket soc; private Ultrasonic us; private String line; /** * loops while it's alive * Create object encapsulating the last frame and ultrasonic data. */ public Pixy(Ultrasonic ultra) { System.out.println("Constructing pixy thread"); String[] temp = {"0 1 2 3 4 5 6"}; currentFrame = new Frame(temp, .5); lastFrame = new Frame(temp, .5); enabled = false; blocksDetected = false; connected = false; us = ultra; } public boolean blocksDetected() { return blocksDetected; } public double horizontalOffset() { //if two blocks are detected return position of peg if (currentFrame.numBlocks() == 2) { return lastFrame.getRealDistance(((lastFrame.getFrameData().get(0).getX() + lastFrame.getFrameData().get(1).getX()) / 2) - Block.X_CENTER); } //if only one vision target is detected guess position of peg else if (currentFrame.numBlocks() == 1) { blocksDetected = false; double pegPos = ((currentFrame.getFrameData().get(0).getX() - Block.X_CENTER) > 0) ? 4.125 : -4.125; return currentFrame.getRealDistance(currentFrame.getFrameData().get(0).getX() - Block.X_CENTER) + pegPos; } //if no vision targets are detected blocksDetected = false; return 4828; } @Override public void run() { System.out.println("Searching for socket connection..."); enabled = true; while (enabled) { try { soc = new Socket(HOST, PORT); in = new BufferedReader(new InputStreamReader(soc.getInputStream(), Charset.forName("UTF-8"))); System.out.print("Socket connection established on ip: " + soc.getInetAddress()); break; } catch (IOException e) { System.out.println("Connect failed, waiting and trying again"); try { Thread.sleep(1000); } catch (InterruptedException ie) { ie.printStackTrace(); } } } connected = true; while (enabled) { try { line = in.readLine(); assert line != null; currentFrame = new Frame(line.split(","), us.getDist()); } catch (IOException e) { e.printStackTrace(); } if (currentFrame.numBlocks() >= 2 || (lastFrame == null && currentFrame.numBlocks() == 1)) { blocksDetected = true; lastFrame = currentFrame; } edu.wpi.first.wpilibj.Timer.delay(0.01); } } public void terminate() { System.out.println("DISABLING THREAD"); if (enabled && connected) { try { in.close(); soc.close(); } catch (IOException e) { e.printStackTrace(); } } blocksDetected = false; connected = false; enabled = false; } public int getWidth() { return lastFrame.getFrameData().get(0).getWidth(); } public Frame getLastFrame() { if (lastFrame != null) { return lastFrame; } return currentFrame; } @Override public String toString() { if (lastFrame != null) { return lastFrame.toString(); } else { return currentFrame.toString(); } } }
package org.wildfly.swarm.plugin; import java.io.*; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import javax.inject.Inject; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.DefaultArtifactHandler; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.model.Resource; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.project.MavenProject; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.impl.ArtifactResolver; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.resolution.ArtifactRequest; import org.eclipse.aether.resolution.ArtifactResolutionException; import org.eclipse.aether.resolution.ArtifactResult; /** * @author Bob McWhirter * @author Ken Finnigan */ @Mojo( name = "package", defaultPhase = LifecyclePhase.PACKAGE, requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME ) public class PackageMojo extends AbstractMojo { //extends AbstractSwarmMojo { private static final Pattern ARTIFACT_PATTERN = Pattern.compile("<artifact name=\"([^\"]+)\".*"); @Component protected MavenProject project; @Parameter(defaultValue = "${project.build.directory}") protected String projectBuildDir; @Parameter(defaultValue = "${repositorySystemSession}") protected DefaultRepositorySystemSession repositorySystemSession; @Parameter(defaultValue = "${project.remoteArtifactRepositories}") protected List<ArtifactRepository> remoteRepositories; @Parameter(alias = "modules") private String[] additionalModules; @Parameter(alias = "bundleDependencies", defaultValue = "true") private boolean bundleDependencies; @Parameter(alias = "mainClass") private String mainClass; @Parameter(alias = "httpPort", defaultValue = "8080") private int httpPort; @Parameter(alias = "portOffset", defaultValue = "0") private int portOffset; @Parameter(alias = "bindAddress", defaultValue = "0.0.0.0") private String bindAddress; @Parameter(alias = "contextPath", defaultValue = "/") private String contextPath; @Inject private ArtifactResolver resolver; private Path dir; private Set<String> dependencies = new HashSet<>(); @Override public void execute() throws MojoExecutionException, MojoFailureException { setupDirectory(); addWildflySwarmBootstrapJar(); addBootstrapJars(); createManifest(); createWildflySwarmProperties(); createDependenciesTxt(); collectDependencies(); createJar(); } private void setupDirectory() throws MojoFailureException { this.dir = Paths.get(this.projectBuildDir, "wildfly-swarm-archive"); try { if (Files.exists(dir)) { emptyDir(dir); } } catch (IOException e) { throw new MojoFailureException("Failed to setup wildfly-swarm-archive directory", e); } } private void addWildflySwarmBootstrapJar() throws MojoFailureException { Artifact artifact = findArtifact("org.wildfly.swarm", "wildfly-swarm-bootstrap", "jar"); if (artifact == null) { getLog().error(" getLog().error("Unable to locate wildfly-swarm-bootstrap.jar in project dependencies."); getLog().error("Please ensure that your project contains some wildfly-swarm-*.jar dependency with <scope>compile</scope>"); getLog().error(" throw new MojoFailureException("Unable to locate wildfly-swarm-bootstrap.jar in project dependencies."); } try { expandArtifact(artifact); } catch (IOException e) { throw new MojoFailureException("Unable to add bootstrap", e); } } private void addBootstrapJars() throws MojoFailureException { Set<String> bootstrapGavs = new HashSet<>(); Path projectArtifactPath = null; try { Set<Artifact> artifacts = this.project.getArtifacts(); for (Artifact each : artifacts) { if (includeAsBootstrapJar(each)) { gatherDependency(each); //bootstrapGavs.add(each.toString()); if ( each.getType().equals( "jar" ) ) { if (each.getClassifier() == null) { bootstrapGavs.add(each.getGroupId() + ":" + each.getArtifactId() + ":" + each.getVersion()); } else { bootstrapGavs.add(each.getGroupId() + ":" + each.getArtifactId() + ":" + each.getVersion() + ":" + each.getClassifier()); } } } } Path bootstrapJars = this.dir.resolve("_bootstrap"); projectArtifactPath = bootstrapJars.resolve(this.project.getArtifactId() + "-" + this.project.getVersion() + "." + this.project.getPackaging()); Files.createDirectories(bootstrapJars); Files.copy(this.project.getArtifact().getFile().toPath(), projectArtifactPath); } catch (IOException e) { throw new MojoFailureException("Unable to create _bootstrap directory", e); } final Path bootstrapTxt = dir.resolve("META-INF").resolve("wildfly-swarm-bootstrap.txt"); try { Files.createDirectories(bootstrapTxt.getParent()); try (final OutputStreamWriter out = new OutputStreamWriter(Files.newOutputStream(bootstrapTxt, StandardOpenOption.CREATE))) { for (String each : bootstrapGavs) { out.write("gav: " + each + "\n"); } out.write("path: _bootstrap/" + this.project.getArtifactId() + "-" + this.project.getVersion() + "." + this.project.getPackaging() + "\n"); } } catch (IOException e) { throw new MojoFailureException("Could not create wildfly-swarm-bootstrap.txt", e); } } private boolean includeAsBootstrapJar(Artifact artifact) { // TODO figure out a better more generic way if (artifact.getGroupId().equals("org.wildfly.swarm") && artifact.getArtifactId().equals("wildfly-swarm-bootstrap")) { return false; } if (artifact.getGroupId().equals("org.wildfly.swarm")) { return true; } if (artifact.getGroupId().equals("org.jboss.shrinkwrap")) { return true; } if (artifact.getGroupId().equals("org.jboss.msc") && artifact.getArtifactId().equals("jboss-msc")) { return false; } return !artifact.getScope().equals("provided"); } private void createManifest() throws MojoFailureException { Manifest manifest = new Manifest(); Attributes attrs = manifest.getMainAttributes(); attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0"); attrs.put(Attributes.Name.MAIN_CLASS, "org.wildfly.swarm.bootstrap.Main"); if (this.mainClass != null && !this.mainClass.equals("")) { attrs.put(new Attributes.Name("Wildfly-Swarm-Main-Class"), this.mainClass); } attrs.putValue("Application-Artifact", this.project.getArtifact().getFile().getName()); // Write the manifest to the dir final Path manifestPath = dir.resolve("META-INF").resolve("MANIFEST.MF"); // Ensure the directories have been created try { Files.createDirectories(manifestPath.getParent()); try (final OutputStream out = Files.newOutputStream(manifestPath, StandardOpenOption.CREATE)) { manifest.write(out); } } catch (IOException e) { throw new MojoFailureException("Could not create manifest file: " + manifestPath.toString(), e); } } private void createWildflySwarmProperties() throws MojoFailureException { Path propsPath = dir.resolve("META-INF").resolve("wildfly-swarm.properties"); Properties props = new Properties(); //props.setProperty("wildfly.swarm.app.artifact", this.project.getBuild().getFinalName() + "." + this.project.getPackaging()); props.setProperty("wildfly.swarm.app.artifact", this.project.getArtifactId() + "-" + this.project.getVersion() + "." + this.project.getPackaging()); props.setProperty("wildfly.swarm.context.path", this.contextPath); props.setProperty("jboss.http.port", "" + this.httpPort); props.setProperty("jboss.socket.binding.port-offset", "" + this.portOffset); props.setProperty("jboss.bind.address", this.bindAddress); try { try (FileOutputStream out = new FileOutputStream(propsPath.toFile())) { props.store(out, "Generated By Wildfly Swarm"); } } catch (IOException e) { throw new MojoFailureException("Unable to create META-INF/wildfly-swarm.properties", e); } } private void createDependenciesTxt() throws MojoFailureException { Set<String> provided = new HashSet<>(); Set<Artifact> artifacts = this.project.getArtifacts(); for (Artifact each : artifacts) { if (each.getType().equals("jar")) { try { try (JarFile jar = new JarFile(each.getFile())) { ZipEntry entry = jar.getEntry("provided-dependencies.txt"); if (entry != null) { // add ourselves provided.add(each.getGroupId() + ":" + each.getArtifactId()); try (InputStream in = jar.getInputStream(entry)) { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; // add everything mentioned in the file while ((line = reader.readLine()) != null) { line = line.trim(); if (line.length() > 0) { provided.add(line); } } } } } } catch (IOException e) { throw new MojoFailureException("Unable to inspect jar", e); } } } List<Resource> resources = this.project.getResources(); for (Resource each : resources) { Path providedDependencies = Paths.get(each.getDirectory(), "provided-dependencies.txt"); if (Files.exists(providedDependencies)) { try { try (InputStream in = new FileInputStream(providedDependencies.toFile())) { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; // add everything mentioned in the file while ((line = reader.readLine()) != null) { line = line.trim(); if (line.length() > 0) { provided.add(line); } } } } catch (IOException e) { throw new MojoFailureException("Error reading project's provided-dependencies.txt"); } } } Path depsPath = dir.resolve("META-INF").resolve("wildfly-swarm-dependencies.txt"); try (FileWriter out = new FileWriter(depsPath.toFile())) { for (Artifact each : artifacts) { if (provided.contains(each.getGroupId() + ":" + each.getArtifactId())) { continue; } if (each.getScope().equals("compile") && each.getType().equals("jar")) { this.dependencies.add(each.getGroupId() + ":" + each.getArtifactId() + ":" + each.getVersion()); out.write(each.getGroupId() + ":" + each.getArtifactId() + ":" + each.getVersion() + "\n"); } } } catch (Exception e) { throw new MojoFailureException("Unable to create META-INF/wildfly-swarm-dependencies.txt"); } } protected void collectDependencies() throws MojoFailureException { if (!this.bundleDependencies) { return; } try { analyzeModuleDependencies(); } catch (IOException e) { throw new MojoFailureException("Unable to collect dependencies", e); } gatherDependencies(); } protected void analyzeModuleDependencies() throws IOException { for (Artifact each : this.project.getArtifacts()) { if (includeAsBootstrapJar(each)) { analyzeModuleDependencies(each); } } } protected void analyzeModuleDependencies(Artifact artifact) throws IOException { if (!artifact.getType().equals("jar")) { return; } JarFile jar = new JarFile(artifact.getFile()); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry each = entries.nextElement(); String name = each.getName(); if (name.startsWith("modules/") && name.endsWith("module.xml")) { try (InputStream in = jar.getInputStream(each)) { analyzeModuleDependencies(in); } } } } protected void analyzeModuleDependencies(InputStream moduleXml) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(moduleXml)); String line = null; while ((line = reader.readLine()) != null) { Matcher matcher = ARTIFACT_PATTERN.matcher(line.trim()); if (matcher.matches()) { this.dependencies.add(matcher.group(1)); } } } protected void gatherDependencies() throws MojoFailureException { for (String each : this.dependencies) { try { gatherDependency(each); } catch (ArtifactResolutionException e) { throw new MojoFailureException("Unable to resolve artifact: " + each, e); } } } protected void gatherDependency(String gav) throws ArtifactResolutionException, MojoFailureException { String[] parts = gav.split(":"); if (parts.length < 3) { throw new MojoFailureException("GAV must be at least 3 parts: " + gav); } String groupId = parts[0]; String artifactId = parts[1]; String packaging = "jar"; String version = null; String classifier = null; if (parts.length > 3) { version = parts[2]; classifier = parts[3]; } else { version = parts[2]; } ArtifactRequest request = new ArtifactRequest(); org.eclipse.aether.artifact.DefaultArtifact aetherArtifact = new org.eclipse.aether.artifact.DefaultArtifact(groupId, artifactId, classifier, packaging, version); request.setArtifact(aetherArtifact); request.setRepositories(remoteRepositories()); ArtifactResult result = resolver.resolveArtifact(this.repositorySystemSession, request); if (result.isResolved()) { try { gatherDependency(result.getArtifact()); } catch (IOException e) { throw new MojoFailureException("Unable to gather dependency: " + gav, e); } } } protected void gatherDependency(Artifact artifact) throws IOException { org.eclipse.aether.artifact.Artifact a = new org.eclipse.aether.artifact.DefaultArtifact( artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier(), artifact.getType(), artifact.getVersion()); a = a.setFile(artifact.getFile()); gatherDependency(a); } protected void gatherDependency(org.eclipse.aether.artifact.Artifact artifact) throws IOException { Path artifactPath = this.dir.resolve("m2repo"); String[] groupIdParts = artifact.getGroupId().split("\\."); for (int i = 0; i < groupIdParts.length; ++i) { artifactPath = artifactPath.resolve(groupIdParts[i]); } artifactPath = artifactPath.resolve(artifact.getArtifactId()); artifactPath = artifactPath.resolve(artifact.getVersion()); artifactPath = artifactPath.resolve(artifact.getFile().getName()); if (Files.exists(artifactPath)) { return; } Files.createDirectories(artifactPath.getParent()); Files.copy(artifact.getFile().toPath(), artifactPath, StandardCopyOption.REPLACE_EXISTING); } private void createJar() throws MojoFailureException { Artifact primaryArtifact = this.project.getArtifact(); ArtifactHandler handler = new DefaultArtifactHandler("jar"); Artifact artifact = new DefaultArtifact( primaryArtifact.getGroupId(), primaryArtifact.getArtifactId(), primaryArtifact.getVersion(), primaryArtifact.getScope(), "jar", "swarm", handler ); String name = this.project.getBuild().getFinalName() + "-swarm.jar"; File file = new File(this.projectBuildDir, name); try ( FileOutputStream fileOut = new FileOutputStream(file); JarOutputStream out = new JarOutputStream(fileOut) ) { writeToJar(out, this.dir); } catch (IOException e) { throw new MojoFailureException("Unable to create jar", e); } artifact.setFile(file); this.project.addAttachedArtifact(artifact); } private void emptyDir(final Path dir) throws IOException { Files.walkFileTree(dir, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); } private void expandArtifact(Artifact artifact) throws IOException { Path destination = this.dir; File artifactFile = artifact.getFile(); if (artifact.getType().equals("jar")) { JarFile jarFile = new JarFile(artifactFile); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry each = entries.nextElement(); if (each.getName().startsWith("META-INF")) { continue; } Path fsEach = destination.resolve(each.getName()); if (each.isDirectory()) { Files.createDirectories(fsEach); } else { try (InputStream in = jarFile.getInputStream(each)) { Files.createDirectories(fsEach.getParent()); Files.copy(in, fsEach, StandardCopyOption.REPLACE_EXISTING); } } } } } private Artifact findArtifact(String groupId, String artifactId, String type) { Set<Artifact> artifacts = this.project.getArtifacts(); for (Artifact each : artifacts) { if (each.getGroupId().equals(groupId) && each.getArtifactId().equals(artifactId) && each.getType().equals(type)) { return each; } } return null; } private void writeToJar(final JarOutputStream out, final Path entry) throws IOException { String rootPath = this.dir.toAbsolutePath().toString(); String entryPath = entry.toAbsolutePath().toString(); if (!rootPath.equals(entryPath)) { String jarPath = entryPath.substring(rootPath.length() + 1); if (Files.isDirectory(entry)) { jarPath = jarPath + "/"; } out.putNextEntry(new ZipEntry(jarPath.replace(File.separatorChar, '/'))); } if (Files.isDirectory(entry)) { Files.walkFileTree(entry, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { writeToJar(out, file); return FileVisitResult.CONTINUE; } }); } else { Files.copy(entry, out); } } protected List<RemoteRepository> remoteRepositories() { List<RemoteRepository> repos = new ArrayList<>(); for (ArtifactRepository each : this.remoteRepositories) { RemoteRepository.Builder builder = new RemoteRepository.Builder(each.getId(), "default", each.getUrl()); repos.add(builder.build()); } repos.add(new RemoteRepository.Builder("jboss-public-repository-group", "default", "http://repository.jboss.org/nexus/content/groups/public/").build()); return repos; } }
package uk.ac.ebi.phenotype.stats; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.springframework.stereotype.Service; import uk.ac.ebi.phenotype.stats.GenotypePhenotypeService.GenotypePhenotypeField; @Service public class GeneService { private HttpSolrServer solr; private ArrayList<String> alleleTypes_mi; private ArrayList<String> alleleTypes_pa; private Logger log = Logger.getLogger(this.getClass().getCanonicalName()); public GeneService(String solrUrl){ solr = new HttpSolrServer(solrUrl); alleleTypes_mi = new ArrayList<>(); alleleTypes_pa = new ArrayList<>(); alleleTypes_mi.add("tm1"); alleleTypes_mi.add("tm1a"); alleleTypes_mi.add("tm1e"); alleleTypes_pa.add("tm1.1"); alleleTypes_pa.add("tm1b"); alleleTypes_pa.add("tm1e.1"); } private String derivePhenotypingStatus(SolrDocument doc){ // Vivek email to ckchen on 07/02/14 11:57 List<String> phenos = new ArrayList<String>() { { add("mi_phenotyping_status"); add("pa_phenotyping_status"); } }; try { for (String p : phenos) { // Phenotyping complete if (doc.containsKey(p)) { for (Object s : doc.getFieldValues(p)) { if (s.toString().equals("Phenotyping Started") || s.toString().equals("Phenotyping Complete") ) { return "available"; } } } } // for legacy data: indexed through experiment core (so not want Sanger Gene or Allele cores) if (doc.containsKey("hasQc")) { return "QCed data available"; } } catch (Exception e) { log.error("Error getting phenotyping status"); log.error(e.getLocalizedMessage()); } return ""; } // returns ready formatted icons public Map<String, String> getProductionStatus(String geneId) throws SolrServerException{ SolrQuery query = new SolrQuery(); query.setQuery("mgi_accession_id:\"" + geneId + "\""); QueryResponse response = solr.query(query); SolrDocument doc = response.getResults().get(0); String miceStatus = ""; String esCellStatus = ""; String phenStatus = ""; Boolean order = false; try { //phenotype status phenStatus = derivePhenotypingStatus(doc).equals("") ? "" : "<a class='status done'><span>phenotype data available</span></a>"; // mice production status // Mice: blue tm1.1/tm1b/tm1e.1 mice (depending on how many allele docs) if ( doc.containsKey("pa_allele_type") ){ // blue es cell status miceStatus += parseAlleleType(doc, "done", "B"); } // Mice: blue tm1/tm1a/tm1e mice (depending on how many allele docs) else if ( doc.containsKey("mi_allele_type") ){ // blue es cell status miceStatus += parseAlleleType(doc, "done", "A"); order = true; } else if ( doc.containsKey("es_allele_name") && doc.containsKey("gene_type_status") ){ if ( doc.getFieldValue("gene_type_status").toString().equals("Microinjection in progress") ){ // draw orange tm1/tm1a/tm1e mice with given alleles miceStatus += parseAlleleType(doc, "inprogress", "A"); } else if (doc.getFieldValue("gene_type_status").toString().equals("") ){ miceStatus += parseAlleleType(doc, "none", "A"); // mouse production planned } } else if ( doc.containsKey("es_allele_name") && !doc.containsKey("gene_type_status") ){ // grey mice status: miceStatus += parseAlleleType(doc, "none", "A"); // mouse production planned } // ES cell production status if ( doc.containsKey("es_allele_name") ){ // blue es cell status esCellStatus = "<a class='status done' href='' title='ES Cells produced' >" + " <span>ES cells</span>" + "</a>"; order = true; } else if ( !doc.containsKey("es_allele_name") && doc.containsKey("gene_type") ){ esCellStatus = "<span class='status inprogress' title='ES cells production in progress' >" + " <span>ES Cell</span>" + "</span>"; } } catch (Exception e) { log.error("Error getting ES cell/Mice status"); log.error(e.getLocalizedMessage()); } HashMap<String, String> res = new HashMap<>(); res.put("icons", esCellStatus + miceStatus + phenStatus); res.put("orderPossible", order.toString()); return res; } private String parseAlleleType(SolrDocument doc, String prodStatus, String type){ System.out.println("parseAlleleType with : \n \t\t" + prodStatus + " " + type); String miceStr = ""; String hoverTxt = null; if ( prodStatus.equals("done") ){ hoverTxt = "Mice produced"; } else if (prodStatus.equals("inprogress") ) { hoverTxt = "Mice production in progress"; } else if ( prodStatus.equals("none") ){ hoverTxt = "Mice production planned"; } //tm1/tm1a/tm1e mice if ( type.equals("A") ){ Map<String,Integer> seenMap = new HashMap<String,Integer>(); seenMap.put("tm1", 0); seenMap.put("tm1a", 0); seenMap.put("tm1e", 0); for (String alleleType : alleleTypes_mi){ String key = prodStatus.equals("inprogress") ? "es_allele_name" : "mi_allele_name"; ArrayList<String> alleleNames = (ArrayList<String>) doc.getFieldValue(key); for (String an : alleleNames) { if ( an.contains(alleleType+"(") ){ seenMap.put(alleleType, seenMap.get(alleleType)+1); //tm1seen++; if ( seenMap.get(alleleType) == 1 ){ miceStr += "<span class='status " + prodStatus + "' title='" + hoverTxt + "' >" + " <span>Mice<br>" + alleleType + "</span>" + "</span>"; break; } } } } } //tm1.1/tm1b/tm1e.1 mice else if ( type.equals("B") ){ Map<String,Integer> seenMap = new HashMap<String,Integer>(); seenMap.put("tm1.1", 0); seenMap.put("tm1b", 0); seenMap.put("tm1e.1", 0); for (String alleleType : alleleTypes_pa){ ArrayList<String> alleleNames = (ArrayList<String>) doc.getFieldValue("pa_allele_name"); for (String an : alleleNames) { if ( an.contains(alleleType+"(") ){ seenMap.put(alleleType, seenMap.get(alleleType)+1); if ( seenMap.get(alleleType) == 1 ){ miceStr += "<span class='status " + prodStatus + "' title='" + hoverTxt + "' >" + " <span>Mice<br>" + alleleType + "</span>" + "</span>"; break; } } } } } System.out.println("\t\t miceStr : " + miceStr); return miceStr; } }
package uk.co.epsilontechnologies.primer; import uk.co.epsilontechnologies.primer.domain.Request; import uk.co.epsilontechnologies.primer.domain.Response; /** * Container for programming the 'when' of the test case. * * @author Shane Gibson */ public class When { /** * The primer instance that is being programmed */ private final Primer primer; /** * The request that is being programmed */ private final Request request; /** * Constructs the 'when' instance for the given primer and request * @param primer the primer instance that is being programmed * @param request the request instance that is being programmed */ When(final Primer primer, final Request request) { this.primer = primer; this.request = request; } /** * Configures the primer to return the given responses (in sequence) for the primer and request * @param responses the responses to configure * @return The instance of the 'when' that is being programmed */ public When thenReturn(final Response... responses) { this.primer.prime(request, responses); return this; } }
package ru.r2cloud.jradio.meteor; import java.awt.image.BufferedImage; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.r2cloud.jradio.lrpt.Packet; import ru.r2cloud.jradio.lrpt.VCDU; public class MeteorImage { public static int METEOR_SPACECRAFT_ID = 0; private static final Logger LOG = LoggerFactory.getLogger(MeteorImage.class); private static final int ADMIN_PACKET_APID = 70; private static final int DEFAULT_RED_APID = 66; private static final int DEFAULT_GREEN_APID = 65; private static final int DEFAULT_BLUE_APID = 64; private final Map<Integer, ImageChannel> channelByApid = new HashMap<>(); public MeteorImage(Iterator<VCDU> input) { while (input.hasNext()) { VCDU next = input.next(); for (Packet cur : next.getPackets()) { if (cur.getApid() == ADMIN_PACKET_APID) { continue; } try { MeteorImagePacket meteorPacket = new MeteorImagePacket(cur); ImageChannel channel = getOrCreateChannel(cur.getApid()); // explicitly start from the beginning if (channel.getLastPacket() == -1) { channel.setCurrentY(0); channel.setFirstPacket(cur.getSequenceCount()); channel.setFirstMcu(meteorPacket.getMcuNumber()); } else { channel.appendRows(ImageChannelUtil.calculateMissingRows(channel.getLastMcu(), channel.getLastPacket(), meteorPacket.getMcuNumber(), cur.getSequenceCount())); } channel.setLastPacket(cur.getSequenceCount()); channel.setLastMcu(meteorPacket.getMcuNumber()); channel.setCurrentX(meteorPacket.getMcuNumber() * 8); while (meteorPacket.hasNext()) { channel.fill(meteorPacket.next()); channel.setCurrentX(channel.getCurrentX() + 8); } } catch (Exception e) { LOG.error("unable to decode packet", e); } } } //find first channel and align other channels based on it ImageChannel first = findFirst(channelByApid.values()); if (first != null) { for (ImageChannel cur : channelByApid.values()) { if (cur == first) { continue; } ImageChannelUtil.align(first, cur); } } } public BufferedImage toBufferedImage() { return toBufferedImage(DEFAULT_RED_APID, DEFAULT_GREEN_APID, DEFAULT_BLUE_APID); } public BufferedImage toBufferedImage(int redApid, int greenApid, int blueApid) { if (channelByApid.isEmpty()) { return null; } ImageChannel red = channelByApid.get(redApid); ImageChannel green = channelByApid.get(greenApid); ImageChannel blue = channelByApid.get(blueApid); int maxHeight = -1; if (red != null) { maxHeight = Math.max(red.getCurrentY() + 8, maxHeight); } if (green != null) { maxHeight = Math.max(green.getCurrentY() + 8, maxHeight); } if (blue != null) { maxHeight = Math.max(blue.getCurrentY() + 8, maxHeight); } BufferedImage result = new BufferedImage(ImageChannel.WIDTH, maxHeight, BufferedImage.TYPE_INT_RGB); for (int row = 0; row < result.getHeight(); row++) { for (int col = 0; col < result.getWidth(); col++) { int index = row * result.getWidth() + col; result.setRGB(col, row, getRGB(getColor(red, index), getColor(green, index), getColor(blue, index))); } } return result; } private static int getRGB(int r, int g, int b) { return ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | ((b & 0xFF) << 0); } private ImageChannel getOrCreateChannel(int apid) { ImageChannel result = channelByApid.get(apid); if (result == null) { result = new ImageChannel(apid); channelByApid.put(apid, result); } return result; } private static ImageChannel findFirst(Collection<ImageChannel> all) { ImageChannel result = null; for (ImageChannel cur : all) { if (result == null || cur.getFirstPacket() < result.getFirstPacket()) { result = cur; } } return result; } private static int getColor(ImageChannel channel, int index) { if (channel == null || index >= channel.getData().length) { return 0; } return channel.getData()[index]; } }
package com.gplucky.task.Scheduling; import com.gplucky.common.mybatis.model.ext.StockExt; import com.gplucky.common.mybatis.model.ext.TaskHistoryExt; import com.gplucky.task.service.StockRedisService; import com.gplucky.task.service.StockService; import com.gplucky.task.service.TaskHistoryService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; @Configuration @ComponentScan("com.gplucky.task.service") @EnableScheduling public class Config { private final Logger LOG = LoggerFactory.getLogger(Config.class); @Autowired private StockService stockService; @Autowired private TaskHistoryService taskHistoryService; @Autowired private StockRedisService stockRedisService; /** * 18:00 */ @Scheduled(cron = "0 30 18 ? * MON-FRI") public void fetchStockInfo() { int taskId = taskHistoryService.insertStartTask(TaskHistoryExt.TYPE_FETCHSTOCKINFO); LOG.info("()…………"); stockService.fetchStockInfo(); LOG.info("…………()"); taskHistoryService.updateFinishedTask((long) taskId); } /** * 19:00 */ @Scheduled(cron = "0 0 19 ? * MON-FRI") public void initTask() { int taskId = taskHistoryService.insertStartTask(TaskHistoryExt.TYPE_INITTASK); LOG.info("()…………"); LOG.info("redis…………"); stockRedisService.initStockSeqUpAndDown(StockExt.SEQ_UP_0, StockExt.SEQ_DOWN_0); LOG.info("…………redis"); LOG.info("…………"); stockRedisService.autoStockSeqUpAndDown(); LOG.info("…………"); LOG.info("…………()"); taskHistoryService.updateFinishedTask((long) taskId); } }
package se.kits.gakusei.util; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import se.kits.gakusei.content.model.Inflection; import se.kits.gakusei.content.model.Lesson; import se.kits.gakusei.content.model.Nugget; import se.kits.gakusei.content.repository.InflectionRepository; import se.sandboge.japanese.conjugation.Verb; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.stream.Collectors; @Component public class QuestionHandler { @Autowired InflectionRepository inflectionRepository; public List<HashMap<String, Object>> createQuestions(List<Nugget> nuggets, String questionType, String answerType) { List<HashMap<String, Object>> questions = nuggets.stream() .map(n -> createQuestion(n, nuggets, questionType, answerType)) .filter(Objects::nonNull) .collect(Collectors.toList()); return questions; } protected HashMap<String, Object> createQuestion(Nugget nugget, List<Nugget> nuggets, String questionType, String answerType) { LinkedList<Nugget> optimalNuggets = new LinkedList<>(); LinkedList<Nugget> allNuggets = new LinkedList<>(nuggets); Collections.shuffle(allNuggets); allNuggets.remove(nugget); List<List<String>> alternatives = new ArrayList<>(); alternatives.add(createAlternative(nugget, answerType)); HashMap<String, Object> questionMap = new HashMap<>(); for(int i = 0; optimalNuggets.size() < 3 && i < allNuggets.size(); i++) { if(allNuggets.get(i).getType().equals(nugget.getType())) optimalNuggets.push(allNuggets.get(i)); else if(allNuggets.size() - (i + 1) <= 4 - optimalNuggets.size()) optimalNuggets.push(allNuggets.get(i)); } //Avoid getting the same alternative from another nugget while (alternatives.size() < 4 && !optimalNuggets.isEmpty()) { List<String> tempAlternative = createAlternative(optimalNuggets.poll(), answerType); if (alternatives.stream().noneMatch(l -> l.get(0).equals(tempAlternative.get(0)))) { alternatives.add(tempAlternative); } } if (alternatives.size() == 4) { List<String> question = createAlternative(nugget, questionType); questionMap.put("question", question); questionMap.put("correctAlternative", alternatives.get(0)); questionMap.put("alternative1", alternatives.get(1)); questionMap.put("alternative2", alternatives.get(2)); questionMap.put("alternative3", alternatives.get(3)); questionMap.put("questionNuggetId", nugget.getId()); return questionMap; } else { return null; } } public List<HashMap<String, Object>> createGrammarQuestions(Lesson lesson, List<Nugget> nuggets, String questionType, String answerType){ return nuggets.stream(). map(n -> createGrammarQuestion(lesson, n, questionType, answerType)). filter(Objects::nonNull). collect(Collectors.toList()); } private HashMap<String, Object> createGrammarQuestion(Lesson lesson, Nugget nugget, String questionType, String answerType){ HashMap<String, Object> questionMap = new HashMap<>(); List<Inflection> inflections = inflectionRepository.findByLessonId(lesson.getId()); Collections.shuffle(inflections); // Get "random" inflection Inflection selectedInflection = inflections.get(0); List<String> question = createAlternative(nugget, questionType); List<String> inflectionInfo = InflectionUtil.getInflectionNameAndTextLink(selectedInflection.getInflectionMethod()); question.add(inflectionInfo.get(0)); question.addAll(createAlternative(nugget, answerType)); if(inflectionInfo.get(1) != null){ question.add(inflectionInfo.get(1)); } String inflectedVerb = inflectVerb(selectedInflection, question.get(1)); if(inflectedVerb == null){ return null; } questionMap.put("question", question); questionMap.put("correctAlternative", Collections.singletonList(inflectedVerb)); questionMap.put("alternative1", Collections.EMPTY_LIST); questionMap.put("alternative2", Collections.EMPTY_LIST); questionMap.put("alternative3", Collections.EMPTY_LIST); questionMap.put("questionNuggetId", nugget.getId()); return questionMap; } private String inflectVerb(Inflection inflection, String baseVerb){ try { Verb verb = new Verb(baseVerb); Method methodToInvoke = verb.getClass().getMethod(inflection.getInflectionMethod()); String inflectedVerb = (String) methodToInvoke.invoke(verb); return inflectedVerb; } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | IllegalArgumentException e) { e.printStackTrace(); return null; } } public List<Nugget> chooseNuggets(List<Nugget> nuggetsWithLowSuccessrate, List<Nugget> unansweredNuggets, List<Nugget> allLessonNuggets, int quantity) { if (allLessonNuggets.size() <= quantity) { return allLessonNuggets; } else { List<Nugget> nuggets = new ArrayList<>(); nuggets.addAll(unansweredNuggets); nuggets.addAll(nuggetsWithLowSuccessrate); nuggets.addAll(allLessonNuggets); List<Nugget> visibleNuggets = nuggets.stream().filter(nugget -> !nugget.isHidden()).distinct() .collect(Collectors.toList()); Collections.shuffle(visibleNuggets); return visibleNuggets.subList(0, quantity); } } private List<String> createAlternative(Nugget nugget, String type) { List<String> alternative = new ArrayList<>(); try { if (type.equals("reading")) { // reading -> japanese alternative.add(nugget.getJpRead()); alternative.add(nugget.getJpWrite()); } else { String methodName = "get" + Character.toString(Character.toUpperCase(type.charAt(0))) + type.substring(1); alternative.add((String)nugget.getClass().getMethod(methodName).invoke(nugget)); } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } return alternative; } }
package org.ftcTeam.opmodes.test; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import org.ftcTeam.configurations.Team8702Prod; import org.ftcTeam.configurations.Team8702Servo; import org.ftcbootstrap.ActiveOpMode; import org.ftcbootstrap.components.operations.motors.GamePadTankDrive; import org.ftcbootstrap.components.operations.servos.GamePadServo; @TeleOp public class TanyaTeleopTest extends ActiveOpMode { //private Team8702Prod robot; private Team8702Servo robot; private GamePadServo gamePadServo; // private GamePadFourWheelDrive gamePadFourWheelDrive; /** * Implement this method to define the code to run when the Init button is pressed on the Driver station. */ @Override protected void onInit() { robot = Team8702Servo.newConfig(hardwareMap, getTelemetryUtil()); //Note The Telemetry Utility is designed to let you organize all telemetry data before sending it to //the Driver station via the sendTelemetry command getTelemetryUtil().addData("Init", getClass().getSimpleName() + " initialized."); getTelemetryUtil().sendTelemetry(); } @Override protected void onStart() throws InterruptedException { super.onStart(); gamePadServo = new GamePadServo(this, gamepad1, robot.servo1, GamePadServo.Control.X_B, 1.0); } /** * Implement this method to define the code to run when the Start button is pressed on the Driver station. * This method will be called on each hardware cycle just as the loop() method is called for event based Opmodes * * @throws InterruptedException */ @Override protected void activeLoop() throws InterruptedException { //update the motors with the gamepad joystick values gamePadServo.update(); //send any telemetry that may have been added in the above operations getTelemetryUtil().sendTelemetry(); } }
package valandur.webapi.services; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; import ninja.leaping.configurate.ConfigurationNode; import ninja.leaping.configurate.loader.ConfigurationLoader; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.tileentity.TileEntity; import org.spongepowered.api.command.CommandMapping; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.command.SendCommandEvent; import org.spongepowered.api.event.message.MessageEvent; import org.spongepowered.api.plugin.PluginContainer; import org.spongepowered.api.util.Tuple; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import org.spongepowered.api.world.storage.WorldProperties; import valandur.webapi.WebAPI; import valandur.webapi.api.cache.CachedObject; import valandur.webapi.api.cache.chat.CachedChatMessage; import valandur.webapi.api.cache.command.CachedCommand; import valandur.webapi.api.cache.command.CachedCommandCall; import valandur.webapi.api.cache.entity.CachedEntity; import valandur.webapi.api.cache.player.CachedPlayer; import valandur.webapi.api.cache.plugin.CachedPluginContainer; import valandur.webapi.api.cache.tileentity.CachedTileEntity; import valandur.webapi.api.cache.world.CachedWorld; import valandur.webapi.api.permission.Permissions; import valandur.webapi.api.service.ICacheService; import valandur.webapi.command.CommandSource; import valandur.webapi.util.Util; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; public class CacheService implements ICacheService { private String configFileName = "cache.conf"; private JsonService json; private Map<String, Long> cacheDurations = new HashMap<>(); private int numChatMessages; private int numCommandCalls; private ConcurrentLinkedQueue<CachedChatMessage> chatMessages = new ConcurrentLinkedQueue<>(); private ConcurrentLinkedQueue<CachedCommandCall> commandCalls = new ConcurrentLinkedQueue<>(); private Collection<CachedPluginContainer> plugins = new LinkedHashSet<>(); private Collection<CachedCommand> commands = new LinkedHashSet<>(); private Map<UUID, CachedWorld> worlds = new ConcurrentHashMap<>(); private Map<UUID, CachedPlayer> players = new ConcurrentHashMap<>(); private Map<UUID, CachedEntity> entities = new ConcurrentHashMap<>(); private Map<Class, JsonNode> classes = new ConcurrentHashMap<>(); public ConcurrentLinkedQueue<CachedChatMessage> getChatMessages() { return chatMessages; } public ConcurrentLinkedQueue<CachedCommandCall> getCommandCalls() { return commandCalls; } public void init() { this.json = WebAPI.getJsonService(); Tuple<ConfigurationLoader, ConfigurationNode> tup = Util.loadWithDefaults(configFileName, "defaults/" + configFileName); ConfigurationNode config = tup.getSecond(); ConfigurationNode amountNode = config.getNode("amount"); numChatMessages = amountNode.getNode("chat").getInt(); numCommandCalls = amountNode.getNode("command").getInt(); cacheDurations.clear(); ConfigurationNode durationNode = config.getNode("duration"); for (ConfigurationNode node : durationNode.getChildrenMap().values()) { cacheDurations.put(node.getKey().toString(), node.getLong()); } } @Override public Long getCacheDurationFor(Class clazz) { Long dur = cacheDurations.get(clazz.getSimpleName()); return dur != null ? dur : Long.MAX_VALUE; } public Map<Class, JsonNode> getClasses() { return classes; } public JsonNode getClass(Class type) { if (classes.containsKey(type)) return classes.get(type); JsonNode e = json.classToJson(type); classes.put(type, e); return e; } public CachedChatMessage addChatMessage(Player sender, MessageEvent event) { CachedChatMessage cache = new CachedChatMessage(sender, event); chatMessages.add(cache); while (chatMessages.size() > numChatMessages) { chatMessages.poll(); } return cache; } public CachedCommandCall addCommandCall(SendCommandEvent event) { CachedCommandCall cache = new CachedCommandCall(event); commandCalls.add(cache); while (commandCalls.size() > numCommandCalls) { commandCalls.poll(); } return cache; } public Optional<Object> executeMethod(CachedObject cache, String methodName, Class[] paramTypes, Object[] paramValues) { return WebAPI.runOnMain(() -> { Optional<?> obj = cache.getLive(); if (!obj.isPresent()) return null; Object o = obj.get(); Method[] ms = Arrays.stream(Util.getAllMethods(o.getClass())).filter(m -> { if (!m.getName().equalsIgnoreCase(methodName)) return false; Class<?>[] reqTypes = m.getParameterTypes(); if (reqTypes.length != paramTypes.length) return false; for (int i = 0; i < reqTypes.length; i++) { if (!reqTypes[i].isAssignableFrom(paramTypes[i])) { return false; } } return true; }).toArray(Method[]::new); if (ms.length == 0) { return new Exception("Method not found"); } try { Method m = ms[0]; m.setAccessible(true); Object res = m.invoke(o, paramValues); if (m.getReturnType() == Void.class || m.getReturnType() == void.class) return true; return res; } catch (Exception e) { return e; } }); } public Tuple<Map<String, JsonNode>, Map<String, JsonNode>> getExtraData(CachedObject cache, String[] reqFields, String[] reqMethods) { return WebAPI.runOnMain(() -> { Map<String, JsonNode> fields = new HashMap<>(); Map<String, JsonNode> methods = new HashMap<>(); Optional<?> opt = cache.getLive(); if (!opt.isPresent()) return null; Object obj = opt.get(); Class c = obj.getClass(); List<Field> allFields = Arrays.asList(Util.getAllFields(c)); List<Method> allMethods = Arrays.asList(Util.getAllMethods(c)); for (String fieldName : reqFields) { Optional<Field> field = allFields.stream().filter(f -> f.getName().equalsIgnoreCase(fieldName)).findAny(); if (!field.isPresent()) { fields.put(fieldName, TextNode.valueOf("ERROR: Field not found")); continue; } field.get().setAccessible(true); try { Object res = field.get().get(obj); fields.put(fieldName, json.toJson(res, true, Permissions.permitAllNode())); } catch (IllegalAccessException e) { fields.put(fieldName, TextNode.valueOf("ERROR: " + e.toString())); } } for (String methodName : reqMethods) { Optional<Method> method = allMethods.stream().filter(f -> f.getName().equalsIgnoreCase(methodName)).findAny(); if (!method.isPresent()) { methods.put(methodName, TextNode.valueOf("ERROR: Method not found")); continue; } if (method.get().getParameterCount() > 0) { methods.put(methodName, TextNode.valueOf("ERROR: Method must not have parameters")); continue; } if (method.get().getReturnType().equals(Void.TYPE) || method.get().getReturnType().equals(Void.class)) { methods.put(methodName, TextNode.valueOf("ERROR: Method must not return void")); continue; } method.get().setAccessible(true); try { Object res = method.get().invoke(obj); methods.put(methodName, json.toJson(res, true, Permissions.permitAllNode())); } catch (IllegalAccessException | InvocationTargetException e) { methods.put(methodName, TextNode.valueOf("ERROR: " + e.toString())); } } return new Tuple<>(fields, methods); }).orElse(null); } public void updateWorlds() { WebAPI.runOnMain(() -> { worlds.clear(); // The worlds that are loaded on server start are overwritten by the world load event later Collection<WorldProperties> unloadedWorlds = Sponge.getServer().getAllWorldProperties(); for (WorldProperties world : unloadedWorlds) { updateWorld(world); } }); } public Collection<CachedWorld> getWorlds() { return worlds.values(); } public Optional<CachedWorld> getWorld(String nameOrUuid) { if (Util.isValidUUID(nameOrUuid)) { return getWorld(UUID.fromString(nameOrUuid)); } Optional<CachedWorld> world = worlds.values().stream().filter(w -> w.getName().equalsIgnoreCase(nameOrUuid)).findAny(); return world.flatMap(cachedWorld -> getWorld(cachedWorld.getUUID())); } public Optional<CachedWorld> getWorld(UUID uuid) { if (!worlds.containsKey(uuid)) { return Optional.empty(); } final CachedWorld res = worlds.get(uuid); if (res.isExpired()) { return WebAPI.runOnMain(() -> { Optional<World> world = Sponge.getServer().getWorld(uuid); if (world.isPresent()) return updateWorld(world.get()); Optional<WorldProperties> props = Sponge.getServer().getWorldProperties(uuid); return props.map(this::updateWorld).orElse(null); }); } else { return Optional.of(res); } } public CachedWorld getWorld(World world) { Optional<CachedWorld> w = getWorld(world.getUniqueId()); return w.orElseGet(() -> updateWorld(world)); } public CachedWorld updateWorld(World world) { CachedWorld w = new CachedWorld(world); worlds.put(world.getUniqueId(), w); return w; } public CachedWorld updateWorld(WorldProperties world) { CachedWorld w = new CachedWorld(world); worlds.put(world.getUniqueId(), w); return w; } public void removeWorld(UUID worldUuid) { worlds.remove(worldUuid); } public Collection<CachedPlayer> getPlayers() { return players.values(); } public Optional<CachedPlayer> getPlayer(UUID uuid) { if (!players.containsKey(uuid)) { return Optional.empty(); } final CachedPlayer res = players.get(uuid); if (res.isExpired()) { return WebAPI.runOnMain(() -> { Optional<Player> player = Sponge.getServer().getPlayer(uuid); return player.map(this::updatePlayer).orElse(null); }); } else { return Optional.of(res); } } public CachedPlayer getPlayer(Player player) { Optional<CachedPlayer> p = getPlayer(player.getUniqueId()); return p.orElseGet(() -> updatePlayer(player)); } public CachedPlayer updatePlayer(Player player) { CachedPlayer p = new CachedPlayer(player); players.put(player.getUniqueId(), p); return p; } public CachedPlayer removePlayer(UUID uuid) { return players.remove(uuid); } public Collection<CachedEntity> getEntities() { return entities.values(); } public Optional<CachedEntity> getEntity(UUID uuid) { if (!entities.containsKey(uuid)) { return Optional.empty(); } final CachedEntity res = entities.get(uuid); if (res.isExpired()) { return WebAPI.runOnMain(() -> { Optional<Entity> entity = Optional.empty(); for (World world : Sponge.getServer().getWorlds()) { Optional<Entity> ent = world.getEntity(uuid); if (ent.isPresent()) { entity = ent; break; } } return entity.map(this::updateEntity).orElse(null); }); } else { return Optional.of(res); } } public CachedEntity getEntity(Entity entity) { Optional<CachedEntity> e = getEntity(entity.getUniqueId()); return e.orElseGet(() -> updateEntity(entity)); } public CachedEntity updateEntity(Entity entity) { CachedEntity e = new CachedEntity(entity); entities.put(entity.getUniqueId(), e); return e; } public CachedEntity removeEntity(UUID uuid) { return entities.remove(uuid); } public void updatePlugins() { Collection<PluginContainer> plugins = Sponge.getPluginManager().getPlugins(); Collection<CachedPluginContainer> cachedPlugins = new LinkedHashSet<>(); for (PluginContainer plugin : plugins) { cachedPlugins.add(new CachedPluginContainer(plugin)); } this.plugins = cachedPlugins; } public Collection<CachedPluginContainer> getPlugins() { return plugins; } public Optional<CachedPluginContainer> getPlugin(String id) { for (CachedPluginContainer plugin : plugins) { if (plugin.getId().equalsIgnoreCase(id)) return Optional.of(plugin); } return Optional.empty(); } public CachedPluginContainer getPlugin(PluginContainer plugin) { Optional<CachedPluginContainer> e = getPlugin(plugin.getId()); return e.orElseGet(() -> new CachedPluginContainer(plugin)); } public void updateCommands() { Collection<CommandMapping> commands = Sponge.getCommandManager().getAll().values(); Collection<CachedCommand> cachedCommands = new LinkedHashSet<>(); for (CommandMapping cmd : commands) { if (cachedCommands.stream().anyMatch(c -> c.getName().equalsIgnoreCase(cmd.getPrimaryAlias()))) continue; cachedCommands.add(new CachedCommand(cmd, CommandSource.instance)); } this.commands = cachedCommands; } public Collection<CachedCommand> getCommands() { return commands; } public Optional<CachedCommand> getCommand(String name) { for (CachedCommand cmd : commands) { if (cmd.getName().equalsIgnoreCase(name)) return Optional.of(cmd); } return Optional.empty(); } public Optional<Collection<CachedTileEntity>> getTileEntities() { return WebAPI.runOnMain(() -> { Collection<CachedTileEntity> entities = new LinkedList<>(); for (World world : Sponge.getServer().getWorlds()) { Collection<TileEntity> ents = world.getTileEntities(); for (TileEntity te : ents) { entities.add(new CachedTileEntity(te)); } } return entities; }); } public Optional<Collection<CachedTileEntity>> getTileEntities(CachedWorld world) { return WebAPI.runOnMain(() -> { Optional<?> w = world.getLive(); if (!w.isPresent()) return null; Collection<CachedTileEntity> entities = new LinkedList<>(); Collection<TileEntity> ents = ((World)w.get()).getTileEntities(); for (TileEntity te : ents) { if (!te.isValid()) continue; entities.add(new CachedTileEntity(te)); } return entities; }); } public Optional<CachedTileEntity> getTileEntity(Location<World> location) { Optional<CachedWorld> w = this.getWorld(location.getExtent().getUniqueId()); if (!w.isPresent()) return Optional.empty(); return getTileEntity(w.get(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); } public Optional<CachedTileEntity> getTileEntity(CachedWorld world, int x, int y, int z) { return WebAPI.runOnMain(() -> { Optional<?> w = world.getLive(); if (!w.isPresent()) return null; Optional<TileEntity> ent = ((World)w.get()).getTileEntity(x, y, z); if (!ent.isPresent() || !ent.get().isValid()) { return null; } return new CachedTileEntity(ent.get()); }); } }
//@@author A0114395E package seedu.address.model; import seedu.address.logic.commands.*; /** * Class to store an action, and it's inverse */ public class StateCommandPair { private Command executeCommand; private Command undoCommand; public StateCommandPair(Command cmd) { this.executeCommand = cmd; this.undoCommand = this.evaluateInverse(cmd); } /** * Executes the command previously entered (for redo) */ public void execute() { System.out.println(executeCommand); } /** * Executes the inverse of the command previously entered (for undo) */ public void executeInvese() { System.out.println(undoCommand); } /** * * @param Command * @return an Inverse action of the Command */ private Command evaluateInverse(Command cmd) { return cmd;// stub } }
package com.tinapaproject.tinapa; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.FrameLayout; import android.widget.ImageView; import com.squareup.otto.Bus; import com.squareup.otto.Subscribe; import com.tinapaproject.tinapa.database.key.DexKeyValues; import com.tinapaproject.tinapa.database.key.OwnedKeyValues; import com.tinapaproject.tinapa.database.key.PlannedKeyValues; import com.tinapaproject.tinapa.database.key.TeamKeyValues; import com.tinapaproject.tinapa.database.provider.TinapaContentProvider; import com.tinapaproject.tinapa.events.CreatePlannedPokemonEvent; import com.tinapaproject.tinapa.events.DeleteOwnedPokemonEvent; import com.tinapaproject.tinapa.events.DeletePlannedPokemonEvent; import com.tinapaproject.tinapa.events.SaveTeamEvent; import com.tinapaproject.tinapa.events.StartNewTeamEvent; import com.tinapaproject.tinapa.events.TeamListSelectedEvent; import com.tinapaproject.tinapa.fragments.DexDetailFragment; import com.tinapaproject.tinapa.fragments.DexDetailFragment.DexDetailListener; import com.tinapaproject.tinapa.fragments.DexListFragment; import com.tinapaproject.tinapa.fragments.DexListFragment.DexListListener; import com.tinapaproject.tinapa.fragments.OwnedAddDialogFragment; import com.tinapaproject.tinapa.fragments.OwnedAddDialogFragment.OwnedAddFragmentListener; import com.tinapaproject.tinapa.fragments.OwnedListFragment; import com.tinapaproject.tinapa.fragments.OwnedListFragment.OwnedListListener; import com.tinapaproject.tinapa.fragments.PlannedAddDialogFragment; import com.tinapaproject.tinapa.fragments.PlannedListFragment; import com.tinapaproject.tinapa.fragments.PlannedListFragment.PlannedListListener; import com.tinapaproject.tinapa.fragments.TeamAddDialogFragment; import com.tinapaproject.tinapa.fragments.TeamListFragment; public class MainActivity extends Activity implements DexListListener, DexDetailListener, OwnedListListener, OwnedAddFragmentListener, PlannedListListener { private String temp_id; private ImageView temp_imageView; private boolean temp_isDefault; private boolean temp_isShiny; private boolean temp_isIcon; private Bus bus; public static int RESULT_LOAD_DEX_LIST_ICON = 100; public static final String SAVE_STATE_SELECTED_TAB_INDEX = "SAVE_STATE_SELECTED_TAB_INDEX"; public static final String DEX_DETAILS_FRAGMENT = "DEX_DETAILS_FRAGMENT"; public static final String OWNED_DETAILS_FRAGMENT = "OWNED_DETAILS_FRAGMENT"; public static final String PLANNED_DETAILS_FRAGMENT = "PLANNED_DETAILS_FRAGMENT"; public static final String TEAM_DETAILS_FRAGMENT = "TEAM_DETAILS_FRAGMENT"; public static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bus = TinapaApplication.bus; bus.register(this); ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayShowTitleEnabled(false); Tab dexTab = actionBar.newTab() .setText(R.string.tab_pokedex) .setTabListener(new TabListener<DexListFragment>("Pokedex" /*TODO: Needs to be a field. */, new DexListFragment())); actionBar.addTab(dexTab, true); Tab ownedTab = actionBar.newTab() .setText(R.string.tab_owned_pokemon) .setTabListener(new TabListener<OwnedListFragment>("Owned" /*TODO: Needs to be a field. */, new OwnedListFragment())); actionBar.addTab(ownedTab); Tab plannedTab = actionBar.newTab() .setText(R.string.tab_planned_pokemon) .setTabListener(new TabListener<PlannedListFragment>("Planned" /*TODO: Needs to be a field. */, new PlannedListFragment())); actionBar.addTab(plannedTab); Tab teamTab = actionBar.newTab() .setText(R.string.tab_teams) .setTabListener(new TabListener<TeamListFragment>("Team" /*TODO: Needs to be a field. */, new TeamListFragment())); actionBar.addTab(teamTab); Log.i(TAG, "All tabs have been added."); if (savedInstanceState != null) { actionBar.setSelectedNavigationItem(savedInstanceState.getInt(SAVE_STATE_SELECTED_TAB_INDEX, 0)); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); bus.register(this); } @Override protected void onPause() { super.onPause(); bus.unregister(this); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_DEX_LIST_ICON && resultCode == RESULT_OK && data != null) { Uri selectedImage = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); BitmapFactory.Options imageOptions = new BitmapFactory.Options(); imageOptions.outHeight = temp_imageView.getHeight(); imageOptions.outWidth = temp_imageView.getWidth(); temp_imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath, imageOptions)); // Now store the path Cursor imageQuery = null; if (!TextUtils.isEmpty(temp_id)) { imageQuery = getContentResolver().query(TinapaContentProvider.POKEDEX_POKEMON_IMAGE_URI, null, "pokemon_id = " + temp_id + " AND is_default = " + (temp_isDefault ? 1 : 0) + " AND is_shinny = " + (temp_isShiny ? 1 : 0) + " AND is_icon = " + (temp_isIcon ? 1 : 0), null, null); ContentValues values = new ContentValues(); values.put(DexKeyValues.imageUri, picturePath); values.put(DexKeyValues.isDefault, temp_isDefault ? 1 : 0); values.put(DexKeyValues.isShiny, temp_isShiny ? 1 : 0); values.put(DexKeyValues.isIcon, temp_isIcon ? 1 : 0); if (imageQuery.getCount() > 0) { getContentResolver().update(TinapaContentProvider.POKEDEX_POKEMON_IMAGE_URI, values, DexKeyValues.insertIntoImageColumnWhereCreation(temp_id), null); } else { values.put("pokemon_id", temp_id); getContentResolver().insert(TinapaContentProvider.POKEDEX_POKEMON_IMAGE_URI, values); } } temp_id = null; temp_imageView = null; temp_isDefault = false; temp_isShiny = false; temp_isIcon = false; } } // From DexCursorAdapter @Override public void onDexItemClicked(String id) { // TODO: Pull information using the ID based off of the topic. // Cursor pokemonCursor = getContentResolver().query(TinapaContentProvider.POKEDEX_URI, null, "pokemon.id = " + id, null, null); // Cursor movesCursor = getContentResolver().query(TinapaContentProvider.POKEDEX_POKEMON_MOVES_URI, null, "pokemon_moves.pokemon_id = " + id, null, null); FrameLayout fragmentView = (FrameLayout) findViewById(R.id.mainActivityFragment2); if (fragmentView == null) { fragmentView = (FrameLayout) findViewById(R.id.mainActivityFragment1); } FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(fragmentView.getId(), DexDetailFragment.newInstance(id), DEX_DETAILS_FRAGMENT); ft.addToBackStack("DexDetail"); ft.commit(); } // From DexCursorAdapter @Override public void onDexImageLongClicked(String id, ImageView imageView, boolean isDefault, boolean isShiny, boolean isIcon) { loadImage(id, imageView, isDefault, isShiny, isIcon); } // From DexDetailFragment @Override public void onDexDetailImageLongClicked(String id, ImageView imageView, boolean isDefault, boolean isShiny, boolean isIcon) { loadImage(id, imageView, isDefault, isShiny, isIcon); } // From OwnedListFragment @Override public void onOwnedItemClicked(String id) { FrameLayout fragmentView = (FrameLayout) findViewById(R.id.mainActivityFragment2); if (fragmentView == null) { fragmentView = (FrameLayout) findViewById(R.id.mainActivityFragment1); } FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(fragmentView.getId(), OwnedAddDialogFragment.newInstance(id), OWNED_DETAILS_FRAGMENT); ft.addToBackStack("OwnedDetail"); ft.commit(); } // From OwnedListFragment @Override public void onAddOwnedClicked() { OwnedAddDialogFragment dialogFragment = OwnedAddDialogFragment.newInstance(); dialogFragment.show(getFragmentManager(), OwnedAddDialogFragment.TAG); } // From OwnedAddDialog @Override public void onPositiveClicked(int level, String nickname, boolean shinny, String speciesId, String abilityId, String natureId, String genderId, String move1Id, String move2Id, String move3Id, String move4Id, int ivHP, int ivAtt, int ivDef, int ivSAtt, int ivSDef, int ivSpd, int evHP, int evAtt, int evDef, int evSAtt, int evSDef, int evSpd, String notes, String planId) { // TODO ContentValues contentValues = new ContentValues(); contentValues.put(OwnedKeyValues.LEVEL, level); contentValues.put(OwnedKeyValues.NICKNAME, nickname); contentValues.put(OwnedKeyValues.SHINNY, shinny); contentValues.put(OwnedKeyValues.POKEMON_ID, speciesId); contentValues.put(OwnedKeyValues.ABILITY_ID, abilityId); contentValues.put(OwnedKeyValues.NATURE_ID, natureId); contentValues.put(OwnedKeyValues.GENDER_ID, genderId); contentValues.put(OwnedKeyValues.MOVE1_ID, move1Id); contentValues.put(OwnedKeyValues.MOVE2_ID, move2Id); contentValues.put(OwnedKeyValues.MOVE3_ID, move3Id); contentValues.put(OwnedKeyValues.MOVE4_ID, move4Id); contentValues.put(OwnedKeyValues.IV_HP, ivHP); contentValues.put(OwnedKeyValues.IV_ATT, ivAtt); contentValues.put(OwnedKeyValues.IV_DEF, ivDef); contentValues.put(OwnedKeyValues.IV_SATT, ivSAtt); contentValues.put(OwnedKeyValues.IV_SDEF, ivSDef); contentValues.put(OwnedKeyValues.IV_SPD, ivSpd); contentValues.put(OwnedKeyValues.EV_HP, evHP); contentValues.put(OwnedKeyValues.EV_ATT, evAtt); contentValues.put(OwnedKeyValues.EV_DEF, evDef); contentValues.put(OwnedKeyValues.EV_SATT, evSAtt); contentValues.put(OwnedKeyValues.EV_SDEF, evSDef); contentValues.put(OwnedKeyValues.EV_SPD, evSpd); contentValues.put(OwnedKeyValues.NOTE, notes); contentValues.put(OwnedKeyValues.PLAN_ID, planId); Uri uri = getContentResolver().insert(TinapaContentProvider.OWNED_POKEMON_URI, contentValues); Log.d(TAG, "Added an owned Pokemon with ID of " + uri.getLastPathSegment()); } // From OwnedAddDialog @Override public void onUpdateClicked(String ownedId, int level, String nickname, boolean shinny, String speciesId, String abilityId, String natureId, String genderId, String move1Id, String move2Id, String move3Id, String move4Id, int ivHP, int ivAtt, int ivDef, int ivSAtt, int ivSDef, int ivSpd, int evHP, int evAtt, int evDef, int evSAtt, int evSDef, int evSpd, String notes, String planId) { // TODO ContentValues contentValues = new ContentValues(); contentValues.put(OwnedKeyValues.LEVEL, level); contentValues.put(OwnedKeyValues.NICKNAME, nickname); contentValues.put(OwnedKeyValues.SHINNY, shinny); contentValues.put(OwnedKeyValues.POKEMON_ID, speciesId); contentValues.put(OwnedKeyValues.ABILITY_ID, abilityId); contentValues.put(OwnedKeyValues.NATURE_ID, natureId); contentValues.put(OwnedKeyValues.GENDER_ID, genderId); contentValues.put(OwnedKeyValues.MOVE1_ID, move1Id); contentValues.put(OwnedKeyValues.MOVE2_ID, move2Id); contentValues.put(OwnedKeyValues.MOVE3_ID, move3Id); contentValues.put(OwnedKeyValues.MOVE4_ID, move4Id); contentValues.put(OwnedKeyValues.IV_HP, ivHP); contentValues.put(OwnedKeyValues.IV_ATT, ivAtt); contentValues.put(OwnedKeyValues.IV_DEF, ivDef); contentValues.put(OwnedKeyValues.IV_SATT, ivSAtt); contentValues.put(OwnedKeyValues.IV_SDEF, ivSDef); contentValues.put(OwnedKeyValues.IV_SPD, ivSpd); contentValues.put(OwnedKeyValues.EV_HP, evHP); contentValues.put(OwnedKeyValues.EV_ATT, evAtt); contentValues.put(OwnedKeyValues.EV_DEF, evDef); contentValues.put(OwnedKeyValues.EV_SATT, evSAtt); contentValues.put(OwnedKeyValues.EV_SDEF, evSDef); contentValues.put(OwnedKeyValues.EV_SPD, evSpd); contentValues.put(OwnedKeyValues.NOTE, notes); contentValues.put(OwnedKeyValues.PLAN_ID, planId); getContentResolver().update(TinapaContentProvider.OWNED_POKEMON_URI, contentValues, "owned_pokemons.id == " + ownedId, null); Log.d(TAG, "Update an owned Pokemon with ID of " + ownedId); onBackPressed(); } @Subscribe public void deleteOwnedPokemon(DeleteOwnedPokemonEvent event) { getContentResolver().delete(TinapaContentProvider.OWNED_POKEMON_URI, event.getOwnedId(), null); Log.d(TAG, "The column for " + event.getOwnedId() + " was deleted."); onBackPressed(); } private void loadImage(String id, ImageView imageView, boolean isDefault, boolean isShiny, boolean isIcon) { temp_id = id; temp_imageView = imageView; temp_isDefault = isDefault; temp_isShiny = isShiny; temp_isIcon = isIcon; Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// B a r s R e t r i e v e r // // <editor-fold defaultstate="collapsed" desc="hdr"> // This program is free software: you can redistribute it and/or modify it under the terms of the // </editor-fold> package org.audiveris.omr.sheet.grid; import org.audiveris.omr.constant.Constant; import org.audiveris.omr.constant.ConstantSet; import org.audiveris.omr.glyph.Glyph; import org.audiveris.omr.glyph.GlyphIndex; import org.audiveris.omr.glyph.Grades; import org.audiveris.omr.glyph.Shape; import org.audiveris.omr.glyph.dynamic.CompoundFactory; import org.audiveris.omr.glyph.dynamic.CompoundFactory.CompoundConstructor; import org.audiveris.omr.glyph.dynamic.CurvedFilament; import org.audiveris.omr.glyph.dynamic.Filament; import org.audiveris.omr.glyph.dynamic.FilamentIndex; import org.audiveris.omr.glyph.dynamic.SectionCompound; import org.audiveris.omr.glyph.dynamic.StraightFilament; import org.audiveris.omr.lag.Lag; import org.audiveris.omr.lag.Lags; import org.audiveris.omr.lag.Section; import org.audiveris.omr.math.GeoUtil; import org.audiveris.omr.math.PointUtil; import static org.audiveris.omr.run.Orientation.*; import org.audiveris.omr.sheet.Part; import org.audiveris.omr.sheet.Scale; import org.audiveris.omr.sheet.Sheet; import org.audiveris.omr.sheet.Staff; import org.audiveris.omr.sheet.StaffManager; import org.audiveris.omr.sheet.SystemInfo; import org.audiveris.omr.sheet.grid.BarColumn.Chain; import org.audiveris.omr.sheet.grid.PartGroup.Symbol; import static org.audiveris.omr.sheet.grid.StaffPeak.Attribute.*; import org.audiveris.omr.sig.SIGraph; import org.audiveris.omr.sig.inter.AbstractVerticalInter; import org.audiveris.omr.sig.inter.BarConnectorInter; import org.audiveris.omr.sig.inter.BarlineInter; import org.audiveris.omr.sig.inter.BraceInter; import org.audiveris.omr.sig.inter.BracketConnectorInter; import org.audiveris.omr.sig.inter.BracketInter; import org.audiveris.omr.sig.inter.BracketInter.BracketKind; import org.audiveris.omr.sig.inter.Inter; import org.audiveris.omr.sig.relation.BarConnectionRelation; import org.audiveris.omr.sig.relation.BarGroupRelation; import org.audiveris.omr.sig.relation.Relation; import org.audiveris.omr.step.StepException; import org.audiveris.omr.ui.Colors; import org.audiveris.omr.ui.ViewParameters; import org.audiveris.omr.ui.util.ItemRenderer; import org.audiveris.omr.ui.util.UIUtil; import org.audiveris.omr.util.Dumping; import org.audiveris.omr.util.Entities; import org.audiveris.omr.util.HorizontalSide; import static org.audiveris.omr.util.HorizontalSide.*; import org.audiveris.omr.util.Navigable; import org.audiveris.omr.util.StopWatch; import org.audiveris.omr.util.VerticalSide; import static org.audiveris.omr.util.VerticalSide.*; import org.jgrapht.alg.ConnectivityInspector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.Stroke; import java.awt.geom.Area; import java.awt.geom.Line2D; import java.awt.geom.Path2D; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.TreeSet; public class BarsRetriever implements ItemRenderer { private static final Constants constants = new Constants(); private static final Logger logger = LoggerFactory.getLogger(BarsRetriever.class); /** Related sheet. */ @Navigable(false) private final Sheet sheet; /** Global sheet scale. */ @Navigable(false) private final Scale scale; /** Scale-dependent constants. */ private final Parameters params; /** Related staff manager. */ private final StaffManager staffManager; /** Staff projectors. (sequence parallel to staves in sheet) */ private final List<StaffProjector> projectors = new ArrayList<>(); /** Graph of all peaks. */ private final PeakGraph peakGraph; /** Columns of barlines, organized by system. */ private final SortedMap<SystemInfo, List<BarColumn>> columnMap = new TreeMap<>(); /** Constructor for brace compound. */ private final CompoundConstructor braceConstructor; /** Constructor for (bracket) serif compound. */ private final CompoundConstructor serifConstructor; /** Specific builder for peak-based filaments. */ private final BarFilamentBuilder filamentBuilder; /** Index of filaments. */ private final FilamentIndex filamentIndex; /** All sections suitable for a brace. */ private List<Section> allBraceSections; /** * Retrieve the bar lines of all staves. * * @param sheet the sheet to process */ public BarsRetriever (Sheet sheet) { this.sheet = sheet; // Scale-dependent parameters scale = sheet.getScale(); params = new Parameters(scale); // Specific constructors braceConstructor = new CurvedFilament.Constructor( scale.getInterline(), params.braceSegmentLength); serifConstructor = new StraightFilament.Constructor(scale.getInterline()); // Companions staffManager = sheet.getStaffManager(); filamentBuilder = new BarFilamentBuilder(sheet); filamentIndex = sheet.getFilamentIndex(); peakGraph = new PeakGraph(sheet, projectors); } // process // /** * Retrieve all barlines, brackets and braces in the sheet and create systems, * groups and parts. * * @throws StepException raised if processing must stop */ public void process () throws StepException { final StopWatch watch = new StopWatch("BarRetriever"); watch.start("buildSystems"); peakGraph.buildSystems(); // Build graph of staff peaks, until systems are known watch.start("buildColumns"); buildColumns(); // Within each system, organize peaks into system-based columns watch.start("detectStartColumns"); detectStartColumns(); // Detect start columns watch.start("purgePartialColumns"); purgePartialColumns(); // Purge partial columns after start watch.start("purgeTooLeft"); purgeTooLeft(); // Purge any peak located too far on left of start peak watch.start("detectBracePortions"); detectBracePortions(); // Detect brace portions at start of staff watch.start("buildBraces"); buildBraces(); // Build brace interpretations across staves out of brace portions watch.start("purgeLeftOfBraces"); purgeLeftOfBraces(); // Purge any peak located on left side of brace watch.start("verifyLinesRoot"); verifyLinesRoot(); // Make sure lines don't start before first (bar/bracket) peak watch.start("detectBracketEnds"); detectBracketEnds(); // Detect top and bottom portions of brackets watch.start("detectBracketMiddles"); detectBracketMiddles(); // Detect middle portions of brackets watch.start("purgeLeftPeaks"); purgeLeftPeaks(); // Purge peaks on left of staff (if not brace or bracket) watch.start("purgeUnalignedBars"); purgeUnalignedBars(); // On multi-staff systems, purge unaligned bars watch.start("purgeExtendingPeaks"); purgeExtendingPeaks(); // Purge peaks extending beyond system staves watch.start("refineRightEnd"); refineRightEnds(); // Define precise right end of each staff watch.start("purgeCClefs"); purgeCClefs(); // Purge C-clef-based false barlines watch.start("partitionWidths"); partitionWidths(); // Partition peaks between thin and thick watch.start("createInters"); createInters(); // Create barline and bracket interpretations within each system watch.start("createConnectionInters"); createConnectionInters(); // Create barline and bracket connection across staves watch.start("groupBarlines"); groupBarlines(); // Detect grouped barlines watch.start("recordBars"); recordBars(); // Record barlines in staff watch.start("createGroups"); createGroups(); // Build groups of staves watch.start("createParts"); createParts(); // Build parts watch.start("contextualize"); contextualize(); // Compute contextual grades if (constants.printWatch.isSet()) { watch.print(); } } // renderItems // /** * Render the axis of each bar line / bracket / connection. * * @param g graphics context */ @Override public void renderItems (Graphics2D g) { // Display staff peaks? if (ViewParameters.getInstance().isStaffPeakPainting()) { for (StaffProjector projector : projectors) { final List<StaffPeak> peaks = projector.getPeaks(); for (StaffPeak peak : peaks) { peak.render(g); } StaffPeak bracePeak = projector.getBracePeak(); if ((bracePeak != null) && !peaks.contains(bracePeak)) { bracePeak.render(g); } } } if (!constants.showVerticalLines.isSet()) { return; } final Rectangle clip = g.getClipBounds(); final Stroke oldStroke = UIUtil.setAbsoluteStroke(g, 1f); final Color oldColor = g.getColor(); g.setColor(Colors.ENTITY_MINOR); // Draw bar lines (only within staff height) for (StaffProjector projector : projectors) { for (StaffPeak peak : projector.getPeaks()) { if (peak.isBrace()) { continue; } Rectangle peakBox = new Rectangle( peak.getStart(), peak.getTop(), peak.getWidth(), peak.getBottom() - peak.getTop()); if (clip.intersects(peakBox)) { double xMid = (peak.getStart() + peak.getStop()) / 2d; Line2D line = new Line2D.Double(xMid, peak.getTop(), xMid, peak.getBottom()); g.draw(line); } } } // Draw Connections (outside of staff height) for (BarAlignment align : peakGraph.edgeSet()) { if (align instanceof BarConnection) { BarConnection connection = (BarConnection) align; Line2D median = connection.getMedian(); if (median.intersects(clip)) { g.draw(median); } } } g.setStroke(oldStroke); g.setColor(oldColor); } // buildBraceFilament // /** * Build the brace filament that goes through all provided portions. * * @param portions the vertical sequence of brace portions * @return the brace filament */ private Filament buildBraceFilament (List<StaffPeak> portions) { final StaffPeak topPeak = portions.get(0); // Define (perhaps slanted) area, slightly increased to the left final Path2D path = new Path2D.Double(); path.moveTo(topPeak.getStart() - params.braceLeftMargin, topPeak.getTop()); // Start point // Left (top down) for (StaffPeak peak : portions) { path.lineTo(peak.getStop() + 1, peak.getTop()); path.lineTo(peak.getStop() + 1, peak.getBottom() + 1); } // Right (bottom up) for (ListIterator<StaffPeak> it = portions.listIterator(portions.size()); it .hasPrevious();) { StaffPeak peak = it.previous(); path.lineTo(peak.getStart() - params.braceLeftMargin, peak.getBottom() + 1); if (it.hasPrevious()) { path.lineTo(peak.getStart() - params.braceLeftMargin, peak.getTop()); } } path.closePath(); final Area area = new Area(path); // Select sections that could be added to filaments final List<Filament> filaments = new ArrayList<>(); final List<Section> sections = getAreaSections(area, allBraceSections); for (StaffPeak peak : portions) { Filament filament = peak.getFilament(); filaments.add(filament); sections.removeAll(filament.getMembers()); } // Now we have several filaments and a few sections around Filament compound = (Filament) CompoundFactory.buildCompoundFromParts( filaments, braceConstructor); // Expand compound as much as possible boolean expanding; do { expanding = false; for (Iterator<Section> it = sections.iterator(); it.hasNext();) { Section section = it.next(); if (compound.touches(section)) { compound.addSection(section); it.remove(); expanding = true; break; } } } while (expanding); return compound; } // buildBraces // /** * Retrieve concrete braces between staves with brace portions. */ private void buildBraces () { final GlyphIndex glyphIndex = sheet.getGlyphIndex(); for (SystemInfo system : sheet.getSystems()) { if (!system.isMultiStaff()) { continue; } final List<Staff> staves = system.getStaves(); StaffLoop: for (int iStaff = 0; iStaff < staves.size(); iStaff++) { Staff staff = staves.get(iStaff); final StaffPeak bracePeak = projectorOf(staff).getBracePeak(); if (bracePeak == null) { continue; } if (bracePeak.isSet(BRACE_TOP)) { List<StaffPeak> portions = new ArrayList<>(); portions.add(bracePeak); // Look down for compatible brace portion(s): // These portions are typically brace middle(s) if any followed by one brace bottom. // In very long braces, middle portions may be rather straight and seen as "bars". StaffPeak topPeak = bracePeak; for (Staff otherStaff : staves.subList(iStaff + 1, staves.size())) { StaffProjector otherProjector = projectorOf(otherStaff); StaffPeak otherPeak = otherProjector.getBracePeak(); if (otherPeak == null) { // Look for an aligned "bar" portion StaffPeak p = otherProjector.getPeaks().get(0); // No check on width (some brace portions can be wide) boolean aligned = peakGraph.checkBraceAlignment(topPeak, p); if (aligned) { otherPeak = p; otherPeak.set(BRACE_MIDDLE); otherProjector.setBracePeak(otherPeak); } } if (otherPeak == null) { logger.warn("Staff#{} isolated brace top", staff.getId()); break; } if (!otherPeak.isSet(BRACE_MIDDLE) && !otherPeak.isSet(BRACE_BOTTOM)) { logger.warn( "Staff#{} expected brace middle/bottom", otherStaff.getId()); break; } portions.add(otherPeak); if (otherPeak.isSet(BRACE_BOTTOM)) { break; } topPeak = otherPeak; } if (portions.size() > 1) { // Retrieve the full brace filament Filament braceFilament = buildBraceFilament(portions); Glyph glyph = glyphIndex.registerOriginal(braceFilament.toGlyph(null)); BraceInter braceInter = new BraceInter(glyph, Grades.intrinsicRatio * 1); SIGraph sig = staff.getSystem().getSig(); sig.addVertex(braceInter); } // Skip the staves processed iStaff = staves.indexOf(portions.get(portions.size() - 1).getStaff()); } } } } // buildColumns // /** * Within each system, organize peaks into system columns. * We use connections (or alignments when there is no connection) */ private void buildColumns () { ConnectivityInspector<StaffPeak, BarAlignment> inspector = new ConnectivityInspector<>( peakGraph); List<Set<StaffPeak>> sets = inspector.connectedSets(); logger.debug("sets: {}", sets.size()); // Process system per system (we have already purged cross-system links) final SortedMap<SystemInfo, List<Chain>> chainMap = new TreeMap<>(); for (Set<StaffPeak> set : sets) { Chain chain = new Chain(set); SystemInfo system = chain.first().getStaff().getSystem(); List<Chain> chainList = chainMap.get(system); if (chainList == null) { chainMap.put(system, chainList = new ArrayList<>()); } chainList.add(chain); } // Sort all chains by deskewed abscissa within each system for (List<Chain> chains : chainMap.values()) { Collections.sort(chains, Chain.byAbscissa); } // Try to aggregate chains into full-size columns for (SystemInfo system : sheet.getSystems()) { List<BarColumn> columns = columnMap.get(system); if (columns == null) { columnMap.put(system, columns = new ArrayList<>()); } final List<Chain> chains = chainMap.get(system); if (chains != null) { for (Chain chain : chains) { BarColumn column = null; // Can this chain join the last column? if (!columns.isEmpty()) { column = columns.get(columns.size() - 1); // Check slope and peak indices double dx = chain.first().getDeskewedAbscissa() - column.getXDsk(); //TODO: this is to be improved! if ((Math.abs(dx) > params.maxColumnDx) || !column.canInclude(chain)) { column = null; } } if (column == null) { columns.add(column = new BarColumn(system, peakGraph)); } column.addChain(chain); } } if (logger.isDebugEnabled()) { logger.info("{} columns:{}", system, columns.size()); for (int i = 0; i < columns.size(); i++) { BarColumn column = columns.get(i); String prefix = column.isFull() ? " logger.info("{} {} {}", i, prefix, column); } } } } // buildSerifFilament // /** * Build the filament that may represent a bracket end serif. * * @param staff containing staff * @param sections the population of candidate sections * @param side top or bottom of staff * @param roi the rectangular roi for the serif * @return the filament built */ private Filament buildSerifFilament (Staff staff, Set<Section> sections, VerticalSide side, Rectangle roi) { // Retrieve all glyphs out of connected sections List<SectionCompound> compounds = CompoundFactory.buildCompounds( sections, serifConstructor); for (SectionCompound compound : compounds) { filamentIndex.register((Filament) compound); } logger.debug("Staff#{} serif {}", staff.getId(), Entities.ids(compounds)); if (compounds.size() > 1) { // Sort filaments according to their distance from bar/roi vertex final Point vertex = new Point(roi.x, roi.y + ((side == TOP) ? (roi.height - 1) : 0)); Collections.sort(compounds, new Comparator<SectionCompound>() { @Override public int compare (SectionCompound g1, SectionCompound g2) { double d1 = PointUtil .length(GeoUtil.vectorOf(g1.getCentroid(), vertex)); double d2 = PointUtil .length(GeoUtil.vectorOf(g2.getCentroid(), vertex)); return Double.compare(d1, d2); } }); // Pickup the first ones and stop as soon as minimum weight is reached int totalWeight = 0; for (int i = 0; i < compounds.size(); i++) { SectionCompound compound = compounds.get(i); totalWeight += compound.getWeight(); if (totalWeight >= params.serifMinWeight) { compounds = compounds.subList(0, i + 1); break; } } return (Filament) CompoundFactory.buildCompoundFromParts(compounds, serifConstructor); } else { return (Filament) compounds.get(0); } } // contextualize // /** * Compute contextual grades for barlines. */ private void contextualize () { for (SystemInfo system : sheet.getSystems()) { system.getSig().contextualize(); } } // createConnectionInters // /** * Populate all systems SIGs with connection inters for barline and brackets. */ private void createConnectionInters () { for (BarAlignment align : peakGraph.edgeSet()) { if (align instanceof BarConnection) { BarConnection connection = (BarConnection) align; StaffPeak topPeak = connection.topPeak; SystemInfo system = topPeak.getStaff().getSystem(); SIGraph sig = system.getSig(); if (topPeak.isBrace()) { continue; } try { BarConnectorInter connector = null; if (topPeak.isBracket()) { sig.addVertex( new BracketConnectorInter(connection, connection.getImpacts())); } else { sig.addVertex( connector = new BarConnectorInter( connection, topPeak.isSet(THICK) ? Shape.THICK_CONNECTOR : Shape.THIN_CONNECTOR, connection.getImpacts())); } // Also, connected bars support each other final Inter topInter = topPeak.getInter(); final StaffPeak bottomPeak = connection.bottomPeak; final Inter bottomInter = bottomPeak.getInter(); if ((topInter != null) && (bottomInter != null)) { Relation bcRel = new BarConnectionRelation(connection.getImpacts()); sig.addEdge(topInter, bottomInter, bcRel); // Extend this information to sibling barlines in system height if ((connector != null) && connector.isGood()) { connector.freeze(); extendConnection(connection); } } else { logger.info("Cannot create connection for {}", align); } } catch (Exception ex) { logger.warn("Error creating connection for {} {}", align, ex.toString(), ex); } } } } // createGroups // /** * Within each system, retrieve all groups. * <ul> * <li>A bracket/square defines a (bracket/square) group. * <li>No staff connection implies different parts. * <li>Braced staves represent a single part when not connected to other staves and count of * braced staves is not more than 2, otherwise it is a group of separate parts. * </ul> * Code in this method is rather fragile, because it relies on presence of proper peaks * (especially brace top/bottom which are not always correct) and at proper level. */ private void createGroups () { for (SystemInfo system : sheet.getSystems()) { logger.debug("createGroups {}", system); final List<PartGroup> allGroups = system.getPartGroups(); // All groups in this system final Map<Integer, PartGroup> activeGroups = new TreeMap<>(); // Active groups for (Staff staff : system.getStaves()) { logger.debug(" Staff#{}", staff.getId()); final StaffProjector projector = projectorOf(staff); final List<StaffPeak> peaks = projector.getPeaks(); final int iStart = projector.getStartPeakIndex(); if (iStart == -1) { logger.debug("Staff#{} one-staff system", staff.getId()); continue; } // Going from startBar (excluded) to the left, look for bracket/square peaks // Braces are not handled in this loop final boolean botConn = isPartConnected(staff, BOTTOM); // Part connection below? int level = 0; for (int i = iStart - 1; i >= 0; i final StaffPeak peak = peaks.get(i); logger.debug(" {}", peak); if (peak.isBrace()) { break; } level++; if (peak.isBracket()) { final PartGroup pg; if (peak.isBracketEnd(TOP)) { // Start bracket group pg = new PartGroup(level, Symbol.bracket, botConn, staff.getId()); allGroups.add(pg); activeGroups.put(level, pg); logger.debug("Staff#{} start bracket {}", staff.getId(), pg); } else { // Continue bracket group pg = activeGroups.get(level); if (pg != null) { pg.setLastStaffId(staff.getId()); // Stop bracket group? if (peak.isBracketEnd(BOTTOM)) { logger.debug("Staff#{} stop bracket {}", staff.getId(), pg); activeGroups.remove(level); } else { logger.debug("Staff#{} continue bracket {}", staff.getId(), pg); } } else { logger.warn("Staff#{} no group level:{}", staff.getId(), level); } } } else if (!isConnected(peak, TOP) && isConnected(peak, BOTTOM)) { // Start square group PartGroup pg = new PartGroup(level, Symbol.square, botConn, staff.getId()); allGroups.add(pg); activeGroups.put(level, pg); logger.debug("Staff#{} start square {}", staff.getId(), pg); } else if (isConnected(peak, TOP)) { // Continue square group PartGroup pg = activeGroups.get(level); if (pg != null) { pg.setLastStaffId(staff.getId()); // Stop square group? if (!isConnected(peak, BOTTOM)) { logger.debug("Staff#{} stop square {}", staff.getId(), pg); activeGroups.remove(level); } else { logger.debug("Staff#{} continue square {}", staff.getId(), pg); } } else { logger.warn("Staff#{} no group level:{}", staff.getId(), level); } } else { logger.warn("Staff#{} weird square portion", staff.getId()); } } // Finally, here we handle braces if any final StaffPeak bracePeak = projector.getBracePeak(); // Leading brace peak? if (bracePeak == null) { logger.debug("Staff#{} no brace before starting barline", staff.getId()); } else { level++; if (bracePeak.isBraceEnd(TOP)) { // (We may have a brace group on hold at this level if bottom was missed) // Start brace group PartGroup pg = new PartGroup(level, Symbol.brace, botConn, staff.getId()); allGroups.add(pg); activeGroups.put(level, pg); logger.debug("Staff#{} start brace {}", staff.getId(), pg); } else { // Continue brace group PartGroup pg = activeGroups.get(level); if (pg != null) { pg.setLastStaffId(staff.getId()); // Stop brace group? if (bracePeak.isBraceEnd(BOTTOM)) { activeGroups.remove(level); logger.debug("Staff#{} stop brace {}", staff.getId(), pg); } } else { logger.info("No brace partner at level:{} for {}", level, bracePeak); } } } } } } // createInters // /** * Based on remaining peaks, populate each system sig with proper inters for bar * lines and for brackets. * <p> * We use a single underlying glyph for each "column" of barlines with connectors or * brackets with connectors. */ private void createInters () { for (SystemInfo system : sheet.getSystems()) { SIGraph sig = system.getSig(); for (Staff staff : system.getStaves()) { StaffProjector projector = projectorOf(staff); for (StaffPeak peak : projector.getPeaks()) { if (peak.isBrace()) { continue; } double x = (peak.getStart() + peak.getStop()) / 2d; Line2D median = new Line2D.Double(x, peak.getTop(), x, peak.getBottom()); final Glyph glyph = sheet.getGlyphIndex().registerOriginal( peak.getFilament().toGlyph(null)); final AbstractVerticalInter inter; if (peak.isBracket()) { BracketKind kind = getBracketKind(peak); inter = new BracketInter( glyph, peak.getImpacts(), median, peak.getWidth(), kind); } else { inter = new BarlineInter( glyph, peak.isSet(THICK) ? Shape.THICK_BARLINE : Shape.THIN_BARLINE, peak.getImpacts(), median, (double) peak.getWidth()); for (HorizontalSide side : HorizontalSide.values()) { if (peak.isStaffEnd(side)) { ((BarlineInter) inter).setStaffEnd(side); } } } sig.addVertex(inter); inter.setStaff(staff); peak.setInter(inter); } } } } // createPart // /** * Create a part. * * @param system containing system * @param first first staff in part * @param last last staff in part * @return the created part */ private Part createPart (SystemInfo system, Staff first, Staff last) { final List<Part> parts = system.getParts(); final List<Staff> systemStaves = system.getStaves(); int iFirst = systemStaves.indexOf(first); int iLast = systemStaves.indexOf(last); // Dirty hack to prevent multiple part creation for same staff if (!parts.isEmpty()) { final Part latestPart = parts.get(parts.size() - 1); final Staff latestStaff = latestPart.getLastStaff(); final int iLatest = systemStaves.indexOf(latestStaff); if (iLast <= iLatest) { return null; } iFirst = Math.max(iLatest + 1, iFirst); } Part part = new Part(system); for (Staff staff : systemStaves.subList(iFirst, iLast + 1)) { part.addStaff(staff); } part.setId(1 + parts.size()); system.addPart(part); // Check of a "merged" part (composed of 2 staves merged into some 11-line grand staff) // This is based on the vertical distance between the 2 staves if (system.getStaves().size() == 2 && part.getStaves().size() == 2) { int x = Math.max(first.getAbscissa(LEFT), last.getAbscissa(LEFT)); // Safer int y1 = first.getLastLine().yAt(x); int y2 = last.getFirstLine().yAt(x); int gutter = y2 - y1; if (gutter < params.minSeparateStaffGutter) { part.setMerged(true); logger.info( "System#{} {} detected as a merged 11-line grand staff", system.getId(), part); } } return part; } // createParts // /** * Within each system, create all parts. * <p> * By default, each staff corresponds to a separate part. The only exception is the case of a * "real" brace (multi-staff instrument) for which the embraced staves share a single part. * Such "true" braced group is then removed from system groups. * <p> * Since brace symbols are not always present, we provide the ability to force a 2-staff part * if all the 3 following conditions are met: * <ol> * <li>The application constant 'forceSinglePart' is set to true * <li>The system is made of exactly 2 staves * <li>The system left margin contains no brace symbol * </ol> * <p> * <p> * NOTA: We have to make sure that every staff is somehow assigned to a part, without exception, * otherwise it would be lost when data is finally stored into project file. */ private void createParts () { final List<Staff> sheetStaves = staffManager.getStaves(); for (SystemInfo system : sheet.getSystems()) { logger.debug("createParts {}", system); final List<PartGroup> allGroups = system.getPartGroups(); // All groups in this system // Look for "true" braced groups TreeSet<PartGroup> bracedGroups = new TreeSet<>(PartGroup.byFirstId); if (!constants.forceSeparateParts.isSet()) { for (PartGroup pg : allGroups) { if (isTrueBraceGroup(pg)) { bracedGroups.add(pg); } } } // Assign all staves int nextId = system.getFirstStaff().getId(); // ID of next staff to be assigned for (PartGroup braced : bracedGroups) { // Gap to fill? for (int id = nextId; id < braced.getFirstStaffId(); id++) { Staff staff = sheetStaves.get(id - 1); createPart(system, staff, staff); } // Brace itself createPart( system, sheetStaves.get(braced.getFirstStaffId() - 1), sheetStaves.get(braced.getLastStaffId() - 1)); nextId = braced.getLastStaffId() + 1; } // Final gap to fill? if (constants.forceSinglePart.isSet() && (system.getStaves().size() == 2) && bracedGroups.isEmpty()) { // Force this 2-staff system as a single part, despite the lack of brace symbol createPart(system, system.getFirstStaff(), system.getLastStaff()); } else { // Create a separate part for each staff found for (int id = nextId; id <= system.getLastStaff().getId(); id++) { Staff staff = sheetStaves.get(id - 1); createPart(system, staff, staff); } } // The "true" braced groups are removed from system groups allGroups.removeAll(bracedGroups); // Print out purged system groups if (!allGroups.isEmpty()) { dumpGroups(allGroups, system); } } } // deleteRelatedColumns // /** * Delete the columns that are based on the provided removed peaks. * * @param system the containing system * @param removed the provided removed peaks */ private void deleteRelatedColumns (SystemInfo system, Collection<? extends StaffPeak> removed) { final List<BarColumn> columns = columnMap.get(system); if (columns != null) { final Set<BarColumn> columnsToRemove = new LinkedHashSet<>(); for (StaffPeak peak : removed) { BarColumn column = peak.getColumn(); if (column != null) { columnsToRemove.add(column); } } for (BarColumn column : columnsToRemove) { logger.debug("Deleting {}", column); for (StaffPeak peak : column.getPeaks()) { if (peak != null) { Staff staff = peak.getStaff(); StaffProjector projector = projectorOf(staff); projector.removePeak(peak); } } } columns.removeAll(columnsToRemove); } } // detectBracePortions // /** * Look for brace top, middle or bottom portion before start column. * Each detected brace portion is stored in staff projector. */ private void detectBracePortions () { for (SystemInfo system : sheet.getSystems()) { if (!system.isMultiStaff()) { continue; } for (Staff staff : system.getStaves()) { StaffProjector projector = projectorOf(staff); final List<StaffPeak> peaks = projector.getPeaks(); final int iStart = projector.getStartPeakIndex(); if (iStart == -1) { continue; // Start peak must exist } // Look for brace portion on left of first peak final StaffPeak firstPeak = peaks.get(0); int maxRight = firstPeak.getStart() - 1 - params.braceBarNeutralGap; int minLeft = Math.max( 0, maxRight - (params.maxBracePeakWidth + params.maxBraceBarGap)); StaffPeak bracePeak = lookForBracePeak(staff, minLeft, maxRight); if ((bracePeak == null) && (iStart >= 1)) { // First peak could itself be a brace portion (mistaken for a bar) final StaffPeak secondPeak = peaks.get(1); maxRight = secondPeak.getStart() - 1 - params.braceBarNeutralGap; minLeft = Math.max( 0, maxRight - (params.maxBracePeakWidth + params.maxBraceBarGap)); bracePeak = lookForBracePeak(staff, minLeft, maxRight); if (bracePeak != null) { replacePeak(firstPeak, bracePeak); } } if (bracePeak != null) { projector.setBracePeak(bracePeak); } } } } // detectBracketEnds // /** * Detect the peaks that correspond to top or bottom end of brackets. * <p> * Such bracket end is characterized as follows: * <ul> * <li>It is located on left side of the start column.</li> * <li>It is a rather thick peak.</li> * <li>It sometimes (but not always) goes a bit beyond staff top or bottom line.</li> * <li>It has a serif shape at end.</li> * </ul> */ private void detectBracketEnds () { for (SystemInfo system : sheet.getSystems()) { if (!system.isMultiStaff()) { continue; } for (Staff staff : system.getStaves()) { StaffProjector projector = projectorOf(staff); final List<StaffPeak> peaks = projector.getPeaks(); final int iStart = projector.getStartPeakIndex(); if (iStart == -1) { continue; // Start peak must exist } for (int i = iStart - 1; i >= 0; i final StaffPeak peak = peaks.get(i); if (peak.isBrace()) { break; } // Sufficient width? if (peak.getWidth() < params.minBracketWidth) { continue; } final StaffPeak rightPeak = peaks.get(i + 1); // It cannot go too far beyond staff height for (VerticalSide side : VerticalSide.values()) { double ext = extensionOf(peak, side); // Check for serif shape Filament serif; if ((ext <= params.maxBracketExtension) && (null != (serif = getSerif( staff, peak, rightPeak, side)))) { logger.debug("Staff#{} {} bracket end", staff.getId(), side); peak.setBracketEnd(side, serif); } } } } } } // detectBracketMiddles // /** * Among peaks, flag the ones that correspond to brackets middle portions. */ private void detectBracketMiddles () { for (SystemInfo system : sheet.getSystems()) { if (!system.isMultiStaff()) { continue; } for (Staff staff : system.getStaves()) { StaffProjector projector = projectorOf(staff); PeakLoop: for (StaffPeak peak : projector.getPeaks()) { if (peak.isBracketEnd(TOP)) { // Flag all connected peaks below as MIDDLE until a BOTTOM is encountered while (true) { Set<BarAlignment> aligns = peakGraph.outgoingEdgesOf(peak); StaffPeak next = null; for (BarAlignment align : aligns) { if (align instanceof BarConnection) { next = align.bottomPeak; if (next.isBracketEnd(BOTTOM)) { continue PeakLoop; } next.set(BRACKET_MIDDLE); } } if (next == null) { break; } peak = next; } } } } } } // detectStartColumns // /** * For each system, detect the first group of full columns, and use the right-most * (fully connected) one as actual "start column" with defines the precise left * limit of staff lines. * <p> * A brace cannot be used as a start column. * Unfortunately, we have yet no efficient way to recognize a given peak as a brace peak. * Methods detectBracePortions() and buildBraces() provide a limited recognition capability. * The risk is high on 2-staff systems, as a brace can be perceived as a fully-connected column. * <p> * Strategy is as follows: browse the fully-connected columns from left to right within maxGap * abscissa from previous column. The last column should be the right one. * We use a wider gap (brace-bar) for the very first couple of columns. * (This should be double-checked with gap being free of staff lines, but at this point staff * lines are not yet fully defined, and projection may be biased by brace touching next bar). * <p> * When there is no first bar group, use only staff lines horizontal limits as the staff limit. */ private void detectStartColumns () { SystemLoop: for (SystemInfo system : sheet.getSystems()) { List<BarColumn> columns = columnMap.get(system); BarColumn startColumn = null; // Last full column (within same group as first full) for (int i = 0; i < columns.size(); i++) { final BarColumn column = columns.get(i); if (column.isFull()) { if (startColumn != null) { double gap = (column.getXDsk() - (column.getWidth() / 2)) - (startColumn .getXDsk() + (startColumn.getWidth() / 2)); int maxGap = (i == 1) ? params.maxBraceBarGap : params.maxDoubleBarGap; if (gap > maxGap) { break; // We are now too far on right } } if (column.isFullyConnected()) { startColumn = column; } } } if (startColumn != null) { logger.debug("{} candidate startColumn: {}", system, startColumn); StaffPeak[] startPeaks = startColumn.getPeaks(); for (StaffPeak peak : startPeaks) { Staff staff = peak.getStaff(); int xLeft = staff.getAbscissa(LEFT); // Based on long line chunks only // Check column is not too far right into staff if ((peak.getStart() - xLeft) > params.maxLinesLeftToStartBar) { if (peak.isVip() || logger.isDebugEnabled()) { logger.info("start {} too far inside staff#{}", peak, staff.getId()); } continue SystemLoop; } // Check column is not too far left of lines (using projection) StaffProjector projector = projectorOf(staff); if (projector.hasStandardBlank(peak.getStop(), xLeft)) { if (peak.isVip() || logger.isDebugEnabled()) { logger.info("start {} too far ahead of staff#{}", peak, staff.getId()); } continue SystemLoop; } } // Use start column as left limit for (StaffPeak peak : startColumn.getPeaks()) { Staff staff = peak.getStaff(); staff.setAbscissa(LEFT, peak.getStop()); peak.setStaffEnd(LEFT); } } else if (system.isMultiStaff()) { logger.warn("No startColumn found for multi-staff {}", system); } } } // dumpGroups // private void dumpGroups (List<PartGroup> groups, SystemInfo system) { logger.info("System#{}", system.getId()); for (PartGroup group : groups) { logger.info(" {}", group); } } // extendConnection // /** * Process the provided concrete connection by freezing its barlines as well as * the corresponding barlines in all the other staves of the system. * * @param connection the concrete connection (between barlines, not brackets) */ private void extendConnection (BarConnection connection) { final StaffPeak topPeak = connection.topPeak; if (topPeak.isBracket()) { return; } // Build the column of peaks, recursively final List<StaffPeak> list = new ArrayList<>(); list.add(topPeak); for (int i = 0; i < list.size(); i++) { StaffPeak peak = list.get(i); for (BarAlignment align : peakGraph.edgesOf(peak)) { for (VerticalSide side : VerticalSide.values()) { StaffPeak p = align.getPeak(side); if (!list.contains(p)) { list.add(p); } } } } // Freeze the corresponding inters for (StaffPeak peak : list) { peak.getInter().freeze(); } } // extensionOf // /** * Report how much a peak goes beyond a staff limit line. * * @param peak the peak to check * @param side TOP or BOTTOM * @return delta ordinate beyond staff */ private double extensionOf (StaffPeak peak, VerticalSide side) { final Filament fil = peak.getFilament(); final Rectangle box = fil.getBounds(); final double halfLine = scale.getMaxFore() / 2.0; if (side == TOP) { return (peak.getTop() - halfLine - box.y); } else { return ((box.y + box.height) - 1 - halfLine - peak.getBottom()); } } // getAreaSections // private List<Section> getAreaSections (Area area, List<Section> allSections) { final Rectangle areaBox = area.getBounds(); final int xBreak = areaBox.x + areaBox.width; final List<Section> sections = new ArrayList<>(); for (Section section : allSections) { final Rectangle sectionBox = section.getBounds(); if (area.contains(sectionBox)) { sections.add(section); } else if (sectionBox.x >= xBreak) { break; // Since allSections are sorted by abscissa } } return sections; } // getBracketKind // private BracketKind getBracketKind (StaffPeak peak) { if (peak.isSet(BRACKET_MIDDLE)) { return BracketKind.NONE; } if (peak.isBracketEnd(TOP)) { if (peak.isBracketEnd(BOTTOM)) { return BracketKind.BOTH; } else { return BracketKind.TOP; } } if (peak.isBracketEnd(BOTTOM)) { return BracketKind.BOTTOM; } else { return null; } } // getConnections // private List<BarConnection> getConnections (Staff staff, VerticalSide side) { final List<BarConnection> list = new ArrayList<>(); final VerticalSide opposite = side.opposite(); final StaffProjector projector = projectorOf(staff); final int iStart = projector.getStartPeakIndex(); if (iStart == -1) { return list; } final List<StaffPeak> peaks = projector.getPeaks(); final StaffPeak startBar = peaks.get(iStart); for (BarAlignment align : peakGraph.edgeSet()) { if (align instanceof BarConnection) { BarConnection connection = (BarConnection) align; StaffPeak peak = connection.getPeak(opposite); if (peak.getStaff() == staff) { // Is this a part-connection, rather than a system-connection? if (peak.getStart() > startBar.getStart()) { list.add(connection); } } else if (peak.getStaff().getId() > staff.getId()) { break; // Since connections are ordered by staff, then abscissa } } } return list; } // getGroups // /** * Report the peak groups as found in the provided sequence of peaks. * * @param peaks the horizontal sequence of peaks * @return the groups detected */ private List<List<StaffPeak>> getGroups (List<StaffPeak> peaks) { List<List<StaffPeak>> groups = new ArrayList<>(); List<StaffPeak> group = new ArrayList<>(); for (StaffPeak peak : peaks) { if (!group.isEmpty()) { int gap = peak.getStart() - group.get(group.size() - 1).getStop() - 1; if (gap > params.maxDoubleBarGap) { if (group.size() > 1) { groups.add(new ArrayList<>(group)); } group.clear(); } } group.add(peak); } // Last group? if (group.size() > 1) { groups.add(new ArrayList<>(group)); } return groups; } // getSectionsByWidth // /** * Select relevant sections for bar sticks. * <p> * Both vertical and horizontal sections are OK if they are not wider than the maximum allowed. * The global collection is sorted on abscissa. * * @param maxWidth maximum section horizontal width * @return the abscissa-sorted list of compliant sections */ private List<Section> getSectionsByWidth (int maxWidth) { List<Section> sections = new ArrayList<>(); Lag hLag = sheet.getLagManager().getLag(Lags.HLAG); Lag vLag = sheet.getLagManager().getLag(Lags.VLAG); for (Lag lag : Arrays.asList(vLag, hLag)) { for (Section section : lag.getEntities()) { if (section.getLength(HORIZONTAL) <= maxWidth) { sections.add(section); } } } Collections.sort(sections, Section.byAbscissa); return sections; } // getSerif // /** * Check whether the provided peak glyph exhibits a serif on desired side. * <p> * Define a region of interest just beyond glyph end and look for sections contained in roi. * Build a glyph from connected sections and check its shape. * * @param peak provided peak * @param rightPeak next peak on right, if any * @param side TOP or BOTTOM * @return serif filament if serif was detected */ private Filament getSerif (Staff staff, StaffPeak peak, StaffPeak rightPeak, VerticalSide side) { // Constants final int halfLine = (int) Math.ceil(scale.getMaxFore() / 2.0); // Define lookup region for serif final Filament barFilament = peak.getFilament(); final int yBox = (side == TOP) ? (peak.getTop() - halfLine - params.serifRoiHeight) : (peak.getBottom() + halfLine); final Rectangle roi = new Rectangle( peak.getStop() + 1, yBox, params.serifRoiWidth, params.serifRoiHeight); barFilament.addAttachment(((side == TOP) ? "t" : "b") + "Serif", roi); // Look for intersected sections // Remove sections from bar peak (and from next peak if any) Lag hLag = sheet.getLagManager().getLag(Lags.HLAG); Lag vLag = sheet.getLagManager().getLag(Lags.VLAG); Set<Section> sections = hLag.intersectedSections(roi); sections.addAll(vLag.intersectedSections(roi)); sections.removeAll(barFilament.getMembers()); if (rightPeak != null) { sections.removeAll(rightPeak.getFilament().getMembers()); } if (sections.isEmpty()) { return null; } // Retrieve serif glyph from sections Filament serif = buildSerifFilament(staff, sections, side, roi); filamentIndex.register(serif); serif.computeLine(); double slope = serif.getSlope(); logger.debug( "Staff#{} {} {} serif#{} weight:{} slope:{}", staff.getId(), peak, side, serif.getId(), serif.getWeight(), slope); if (serif.getWeight() < params.serifMinWeight) { logger.info( "Staff#{} serif normalized weight too small {} vs {}", staff.getId(), String.format("%.2f", serif.getNormalizedWeight(scale.getInterline())), constants.serifMinWeight.getValue()); return null; } return serif; } // getStartColumnIndex // private int getStartColumnIndex (List<BarColumn> columns) { for (int i = 0; i < columns.size(); i++) { if (columns.get(i).isStart()) { return i; } } return -1; } // groupBarPeaks // /** * Dispatch all bar peaks into either isolated or grouped ones. * * @param isolated (output) collection of isolated peaks * @param groups (output) collection of grouped peaks */ private void groupBarPeaks (List<StaffPeak> isolated, List<List<StaffPeak>> groups) { for (SystemInfo system : sheet.getSystems()) { for (Staff staff : system.getStaves()) { List<StaffPeak> group = null; StaffPeak prevPeak = null; for (StaffPeak peak : projectorOf(staff).getPeaks()) { if (peak.isBrace() || peak.isBracket()) { if ((group == null) && (prevPeak != null)) { isolated.add(prevPeak); } group = null; prevPeak = null; } else { if (prevPeak != null) { int gap = peak.getStart() - prevPeak.getStop() - 1; if (gap <= params.maxDoubleBarGap) { // We are in a group with previous peak if (group == null) { groups.add(group = new ArrayList<>()); group.add(prevPeak); } group.add(peak); } else if (group != null) { group = null; } else { isolated.add(prevPeak); } } prevPeak = peak; } } // End of staff if ((group == null) && (prevPeak != null)) { isolated.add(prevPeak); } } } } // groupBarlines // /** * Detect barlines organized in groups. */ private void groupBarlines () { for (SystemInfo system : sheet.getSystems()) { SIGraph sig = system.getSig(); for (Staff staff : system.getStaves()) { StaffPeak prevPeak = null; for (StaffPeak peak : projectorOf(staff).getPeaks()) { if (peak.isBrace() || peak.isBracket()) { continue; } if (prevPeak != null) { int gap = peak.getStart() - prevPeak.getStop() - 1; if (gap <= params.maxDoubleBarGap) { BarGroupRelation rel = new BarGroupRelation(scale.pixelsToFrac(gap)); sig.addEdge(prevPeak.getInter(), peak.getInter(), rel); } } prevPeak = peak; } } } } // isConnected // /** * Check whether the provided peak is connected on the provided vertical side. * * @param peak the peak to check * @param side which vertical side to look for from peak * @return true if a compliant connection was found, false otherwise */ private boolean isConnected (StaffPeak peak, VerticalSide side) { Set<BarAlignment> edges = (side == TOP) ? peakGraph.incomingEdgesOf(peak) : peakGraph.outgoingEdgesOf(peak); for (BarAlignment edge : edges) { if (edge instanceof BarConnection) { return true; } } return false; } // isPartConnected // /** * Check whether the provided staff has part-connection on provided vertical side. * <p> * A part-connection is a connection between two staves, not counting the system-connection on * the left side of the staves. * * @param staff the staff to check * @param side which vertical side to look for from staff * @return true if a compliant part connection was found, false otherwise */ private boolean isPartConnected (Staff staff, VerticalSide side) { return !getConnections(staff, side).isEmpty(); } // isTrueBraceGroup // /** * Check whether the provided group corresponds to a 1-instrument part * (such as a piano part). * Braced staves represent a single part when the count of braced staves is 2 (to be improved?) * and they are internally connected but not connected to external staves. * * @param pg the brace PartGroup to check * @return true if check is positive */ private boolean isTrueBraceGroup (PartGroup pg) { if (!pg.isBrace()) { return false; } final int firstId = pg.getFirstStaffId(); final int lastId = pg.getLastStaffId(); final int staffCount = lastId - firstId + 1; if (staffCount != 2) { return false; } final Staff firstStaff = staffManager.getStaff(firstId - 1); final Staff lastStaff = staffManager.getStaff(lastId - 1); return !isPartConnected(firstStaff, TOP) // Not connected above && isPartConnected(firstStaff, BOTTOM) // Internally connected && !isPartConnected(lastStaff, BOTTOM); // Not connected below } // lookForBracePeak // private StaffPeak lookForBracePeak (Staff staff, int minLeft, int maxRight) { final StaffProjector projector = projectorOf(staff); final StaffPeak bracePeak = projector.findBracePeak(minLeft, maxRight); if (bracePeak == null) { return null; } if (bracePeak.getWidth() > params.maxBracePeakWidth) { logger.info("too wide bracePeak {}", bracePeak); return null; } if (allBraceSections == null) { allBraceSections = getSectionsByWidth(params.maxBraceThickness); } Filament filament = filamentBuilder.buildFilament( bracePeak, params.braceLookupExtension, allBraceSections); bracePeak.setFilament(filament); // A few tests on glyph if (filament == null) { return null; } if (filament.getLength(VERTICAL) < params.minBracePortionHeight) { return null; } double curvature = filament.getMeanCurvature(); // curvature radius value logger.debug( "Staff#{} curvature:{} vs {}", staff.getId(), curvature, params.maxBraceCurvature); if (curvature >= params.maxBraceCurvature) { return null; } final SystemInfo system = staff.getSystem(); boolean beyondTop = false; boolean beyondBottom = false; for (VerticalSide side : VerticalSide.values()) { double ext = extensionOf(bracePeak, side); if (ext > params.braceLookupExtension) { if (side == TOP) { if (staff != system.getFirstStaff()) { beyondTop = true; } } else if (staff != system.getLastStaff()) { beyondBottom = true; } } } if (beyondTop && beyondBottom) { bracePeak.set(BRACE_MIDDLE); } else if (beyondBottom) { bracePeak.set(BRACE_TOP); } else if (beyondTop) { bracePeak.set(BRACE_BOTTOM); } if (bracePeak.isVip()) { logger.info("VIP {}", bracePeak); } else { logger.debug("{}", bracePeak); } return bracePeak; } // partitionWidths // /** * Assign each peak as being thin or thick. * <p> * We can discard the case of all page peaks being thick, so we simply have to detect whether we * do have some thick ones. * When this method is called, some peaks are still due to stems. We don't know the average * stem width, but typically stem peaks are thinner or equal to bar peaks. * <p> * Isolated bars are thin (TODO: unless we hit a thick bar but missed a thin candidate nearby, * however this could be fixed using the global sheet population of thin bars). * <p> * We look for grouped bars and compare widths within the same group. If significant difference * is found, then we discriminate thins & thicks, otherwise they are all considered as thin. */ private void partitionWidths () { // Dispatch peaks into isolated peaks and groups of peaks final List<StaffPeak> isolated = new ArrayList<>(); final List<List<StaffPeak>> groups = new ArrayList<>(); groupBarPeaks(isolated, groups); // Isolated peaks are considered thin for (StaffPeak peak : isolated) { peak.set(THIN); } // Process groups is any for (List<StaffPeak> group : groups) { // Read maximum width difference within this group int minWidth = Integer.MAX_VALUE; int maxWidth = Integer.MIN_VALUE; for (StaffPeak peak : group) { int width = peak.getWidth(); minWidth = Math.min(minWidth, width); maxWidth = Math.max(maxWidth, width); } double normedDelta = (maxWidth - minWidth) / (double) scale.getInterline(); logger.debug("min:{} max:{} nDelta:{} {}", minWidth, maxWidth, normedDelta, group); if (normedDelta >= params.minNormedDeltaWidth) { // Hetero (thins & thicks) for (StaffPeak peak : group) { int width = peak.getWidth(); if ((width - minWidth) <= (maxWidth - width)) { peak.set(THIN); } else { peak.set(THICK); } } } else { // Homo => all thins for (StaffPeak peak : group) { peak.set(THIN); } } } } // projectorOf // private StaffProjector projectorOf (Staff staff) { return projectors.get(staff.getId() - 1); } // purgeCClefs // /** * Purge C-Clef portions mistaken for bar lines. * <p> * A C-clef exhibits a pair of peaks (a rather thick one followed by a rather thin one). * It should be looked for in two location kinds: * <ul> * <li>At the very beginning of staff with no initial bar line, with only a short chunk of staff * lines, so that first peak is not a staff end.</li> * <li>After a barline, provided this barline is not part of a thin + thick + thin group. * For this case the horizontal gap between barline and start of C-clef must be larger than * maximum multi-bar gap.</li> * </ul> * Additional check is made for lack of connection above & below, including for tail peaks. */ private void purgeCClefs () { for (StaffProjector projector : projectors) { final Staff staff = projector.getStaff(); final List<StaffPeak> peaks = projector.getPeaks(); final int staffStart = staff.getAbscissa(LEFT); int measureStart = staffStart; final List<StaffPeak> tails = new ArrayList<>(); for (int i = 0; i < peaks.size(); i++) { final StaffPeak p1 = peaks.get(i); if (p1.getStart() <= measureStart) { continue; } // Look for a rather thick first peak if (!p1.isStaffEnd(LEFT) && !p1.isStaffEnd(RIGHT) && !(p1.isBrace()) && !p1.isBracket() && (p1.getWidth() >= params.minPeak1WidthForCClef)) { // Check gap is larger than multi-bar gap but smaller than measure int gap = p1.getStart() - measureStart; // Gap is not relevant for first measure, thanks to !peak.isStaffEnd() test int minGap = (measureStart == staffStart) ? 0 : params.maxDoubleBarGap; if ((gap > minGap) && (gap < params.minMeasureWidth) && !isConnected(p1, TOP) && !isConnected(p1, BOTTOM)) { if (logger.isDebugEnabled() || p1.isVip()) { logger.info("VIP perhaps a C-Clef peak1 at {}", p1); } else { logger.debug("perhaps a C-Clef peak1 at {}", p1); } // Look for a rather thin second peak right after the first if ((i + 1) < peaks.size()) { final StaffPeak p2 = peaks.get(i + 1); int gap2 = p2.getStart() - p1.getStop() - 1; if ((p2.getWidth() <= params.maxPeak2WidthForCClef) && (gap2 <= params.maxDoubleBarGap) && !isConnected(p2, TOP) && !isConnected(p2, BOTTOM)) { boolean cancelled = false; tails.clear(); if (logger.isDebugEnabled() || p1.isVip() || p2.isVip()) { logger.info("VIP perhaps a C-Clef peak2 at {}", p2); } else { logger.debug("perhaps C-Clef peak2 {}", p2); } // Avoid false peaks before the end of C-Clef has been passed if ((i + 1) < peaks.size()) { int mid2 = (p2.getStart() + p2.getStop()) / 2; int xBreak = mid2 + params.cClefTail; for (StaffPeak tp : peaks.subList(i + 1, peaks.size())) { int otherMid = (tp.getStart() + tp.getStop()) / 2; if (otherMid < xBreak) { if (isConnected(tp, TOP) || isConnected(tp, BOTTOM)) { cancelled = true; // Cancel everything break; } else { if (logger.isDebugEnabled() || tp.isVip()) { logger.info( "VIP perhaps tail of C-Clef {}", staff.getId(), tp); } tails.add(tp); } } else { break; } } } if (!cancelled) { p1.set(CCLEF_ONE); p2.set(CCLEF_TWO); for (StaffPeak t : tails) { t.set(CCLEF_TAIL); } final List<StaffPeak> toRemove = new ArrayList<>(); toRemove.add(p1); toRemove.add(p2); toRemove.addAll(tails); if (logger.isDebugEnabled() || p1.isVip() || p2.isVip()) { logger.info("VIP C-Clef peaks {}", toRemove); } else { logger.debug("C-Clef peaks {}", toRemove); } projector.removePeaks(toRemove); deleteRelatedColumns(staff.getSystem(), toRemove); i += (1 + tails.size()); // Don't rebrowse C-Clef peaks } } } } else { measureStart = p1.getStop() + 1; } } else { measureStart = p1.getStop() + 1; } } } } // purgeExtendingPeaks // /** * Purge bars extending above system top staff or below system bottom staff. * <p> * This purge apply only to peaks on right of start column, since brackets and braces, as * well as the start column itself, can extend past top/bottom staves. */ private void purgeExtendingPeaks () { for (SystemInfo system : sheet.getSystems()) { if (system.getStaves().size() >= params.largeSystemStaffCount) { continue; // We cannot not ruin a whole column of large system here! } for (VerticalSide side : VerticalSide.values()) { final Staff staff = (side == TOP) ? system.getFirstStaff() : system.getLastStaff(); final StaffProjector projector = projectorOf(staff); final List<StaffPeak> peaks = projector.getPeaks(); final int iStart = projector.getStartPeakIndex(); final Set<StaffPeak> toRemove = new LinkedHashSet<>(); for (int i = iStart + 1; i < peaks.size(); i++) { StaffPeak peak = peaks.get(i); double ext = extensionOf(peak, side); if (ext > params.maxBarExtension) { if (peak.isVip()) { logger.info("VIP removed {} long {}", side, peak); } toRemove.add(peak); } } if (!toRemove.isEmpty()) { logger.debug("Staff#{} removing extendings {}", staff.getId(), toRemove); projector.removePeaks(toRemove); deleteRelatedColumns(system, toRemove); } } } } // purgeLeftOfBraces // /** * In every staff with a brace, purge any peak located on left of the brace. */ private void purgeLeftOfBraces () { for (SystemInfo system : sheet.getSystems()) { if (!system.isMultiStaff()) { continue; } for (Staff staff : system.getStaves()) { final StaffProjector projector = projectorOf(staff); final StaffPeak bracePeak = projector.getBracePeak(); if (bracePeak == null) { continue; } final List<StaffPeak> peaks = projector.getPeaks(); final int iStart = projector.getStartPeakIndex(); final Set<StaffPeak> toRemove = new LinkedHashSet<>(); for (int i = iStart - 1; i >= 0; i final StaffPeak peak = peaks.get(i); if (peak.getStop() < bracePeak.getStart()) { if (peak.isVip()) { logger.info("VIP removing left {}", peak); } toRemove.add(peak); } } if (!toRemove.isEmpty()) { logger.debug("Staff#{} removing lefts {}", staff.getId(), toRemove); projector.removePeaks(toRemove); deleteRelatedColumns(system, toRemove); } } } } // purgeLeftPeaks // /** * Any peak located before staff start (be it start column or non-bar lines start), * and which is neither a bracket nor a brace, is purged. */ private void purgeLeftPeaks () { for (SystemInfo system : sheet.getSystems()) { for (Staff staff : system.getStaves()) { final StaffProjector projector = projectorOf(staff); final Set<StaffPeak> toRemove = new LinkedHashSet<>(); final int xLeft = staff.getAbscissa(LEFT); for (StaffPeak peak : projector.getPeaks()) { if (peak.getStart() > xLeft) { break; } if (!peak.isStaffEnd(LEFT) && !peak.isBrace() && !peak.isBracket()) { if (peak.isVip()) { logger.info("VIP removing left {}", peak); } toRemove.add(peak); } } if (!toRemove.isEmpty()) { logger.debug("Staff#{} removing lefts {}", staff.getId(), toRemove); projector.removePeaks(toRemove); deleteRelatedColumns(system, toRemove); } } } } // purgePartialColumns // /** * Remove all non-full columns located on right side of staff left limit. */ private void purgePartialColumns () { for (SystemInfo system : sheet.getSystems()) { final List<BarColumn> columns = columnMap.get(system); final int iStart = getStartColumnIndex(columns); // Start column (or -1) for (int i = iStart + 1; i < columns.size(); i++) { final BarColumn column = columns.get(i); if (!column.isFull()) { logger.debug("Deleting partial {}", column); // Delete this column, with its related peaks for (StaffPeak peak : column.getPeaks()) { if (peak != null) { if (peak.isVip()) { logger.info("VIP part of partial column {}", peak); } projectorOf(peak.getStaff()).removePeak(peak); } } columns.remove(i } } } } // purgeTooLeft // /** * In every staff with a start peak, discard the peaks located too far on left. */ private void purgeTooLeft () { for (SystemInfo system : sheet.getSystems()) { for (Staff staff : system.getStaves()) { final StaffProjector projector = projectorOf(staff); int iStart = projector.getStartPeakIndex(); if (iStart == -1) { continue; } final List<StaffPeak> peaks = projector.getPeaks(); final Set<StaffPeak> toRemove = new LinkedHashSet<>(); StaffPeak prevPeak = peaks.get(iStart); for (int i = iStart - 1; i >= 0; i final StaffPeak peak = peaks.get(i); final int gap = prevPeak.getStart() - peak.getStop() + 1; if (gap > params.maxBraceBarGap) { if (peak.isVip()) { logger.info("VIP removing too left {}", peak); } toRemove.add(peak); } else { prevPeak = peak; } } if (!toRemove.isEmpty()) { logger.debug("Staff#{} removing too lefts {}", staff.getId(), toRemove); projector.removePeaks(toRemove); deleteRelatedColumns(system, toRemove); } } } } // purgeUnalignedBars // /** * On multi-staff system, purge isolated bars (bars aligned with nothing). */ private void purgeUnalignedBars () { for (SystemInfo system : sheet.getSystems()) { if (!system.isMultiStaff()) { continue; } for (Staff staff : system.getStaves()) { final StaffProjector projector = projectorOf(staff); for (StaffPeak peak : new ArrayList<>(projector.getPeaks())) { if (peakGraph.containsVertex(peak) && peakGraph.edgesOf(peak).isEmpty()) { if (peak.isVip()) { logger.info("VIP unaligned {}", peak); } projector.removePeak(peak); } } } } } // recordBars // private void recordBars () { for (SystemInfo system : sheet.getSystems()) { for (Staff staff : system.getStaves()) { // All bars List<BarlineInter> bars = new ArrayList<>(); for (StaffPeak peak : projectorOf(staff).getPeaks()) { Inter inter = peak.getInter(); if (inter instanceof BarlineInter) { bars.add((BarlineInter) inter); } } staff.setBarlines(bars); } } } // refineRightEnds // private void refineRightEnds () { for (StaffProjector projector : projectors) { projector.refineRightEnd(); } } // replacePeak // /** * Replace a peak by another one. * * @param oldPeak the peak to be replaced * @param newPeak the new peak */ private void replacePeak (StaffPeak oldPeak, StaffPeak newPeak) { // PeakGraph for (BarAlignment edge : new ArrayList<>(peakGraph.incomingEdgesOf(oldPeak))) { StaffPeak source = peakGraph.getEdgeSource(edge); peakGraph.addEdge(source, newPeak, edge); } for (BarAlignment edge : new ArrayList<>(peakGraph.outgoingEdgesOf(oldPeak))) { StaffPeak target = peakGraph.getEdgeTarget(edge); peakGraph.addEdge(newPeak, target, edge); } // Column BarColumn column = oldPeak.getColumn(); if (column != null) { column.addPeak(newPeak); } // Projector final Staff staff = oldPeak.getStaff(); final StaffProjector projector = projectorOf(staff); projector.insertPeak(newPeak, oldPeak); projector.removePeak(oldPeak); } // verifyLinesRoot // /** * Make sure that there is no staff line portion just before first bar or bracket. * <p> * This may occur only on 1-staff systems. */ private void verifyLinesRoot () { for (SystemInfo system : sheet.getSystems()) { if (system.isMultiStaff()) { continue; } final Staff staff = system.getFirstStaff(); final StaffProjector projector = projectorOf(staff); projector.checkLinesRoot(); } } // Constants // private static class Constants extends ConstantSet { private final Constant.Boolean printWatch = new Constant.Boolean( false, "Should we print out the stop watch?"); private final Constant.Boolean showVerticalLines = new Constant.Boolean( false, "Should we show the vertical grid lines?"); private final Constant.Integer largeSystemStaffCount = new Constant.Integer( "staves", 4, "Minimum number of staves for a system to be large"); private final Scale.Fraction minThinThickDelta = new Scale.Fraction( 0.2, "Minimum difference between THIN/THICK width values"); private final Scale.Fraction maxBarExtension = new Scale.Fraction( 1.0, "Maximum extension for a barline above or below staff line"); private final Scale.Fraction maxLinesLeftToStartBar = new Scale.Fraction( 0.15, "Maximum dx between left end of staff lines and start bar"); private final Scale.Fraction maxDoubleBarGap = new Scale.Fraction( 0.75, "Max horizontal gap between two members of a double bar"); private final Scale.Fraction minMeasureWidth = new Scale.Fraction( 2.0, "Minimum width for a measure"); private final Scale.Fraction maxColumnDx = new Scale.Fraction( 0.75, "Maximum abscissa shift within a column"); private final Scale.Fraction minPeak1WidthForCClef = new Scale.Fraction( 0.3, "Minimum width for first peak of C-Clef"); private final Scale.Fraction maxPeak2WidthForCClef = new Scale.Fraction( 0.3, "Maximum width for second peak of C-Clef"); private final Scale.Fraction cClefTail = new Scale.Fraction( 2.0, "Typical width for tail of C-Clef, from second peak to right end"); private final Scale.Fraction braceLeftMargin = new Scale.Fraction( 0.5, "Margin on left side of brace peak to retrieve full glyph"); private final Scale.Fraction braceSegmentLength = new Scale.Fraction( 1.0, "Typical distance between brace points"); private final Scale.Fraction minBracePortionHeight = new Scale.Fraction( 3.0, "Minimum height for a brace portion"); private final Scale.Fraction maxBraceThickness = new Scale.Fraction( 1.0, "Maximum thickness of a brace (for sections)"); private final Scale.Fraction maxBracePeakWidth = new Scale.Fraction( 3.0, "Maximum width of a brace peak"); private final Scale.Fraction maxBraceBarGap = new Scale.Fraction( 2.0, "Max horizontal gap between a brace peak and next bar"); private final Scale.Fraction braceBarNeutralGap = new Scale.Fraction( 0.1, "Horizontal neutral area between a brace and next bar"); private final Scale.Fraction braceLookupExtension = new Scale.Fraction( 0.5, "Lookup height for brace end above or below staff line"); private final Scale.Fraction maxBraceCurvature = new Scale.Fraction( 20, "Maximum mean curvature radius for a brace"); private final Constant.Boolean forceSinglePart = new Constant.Boolean( false, "Should we force single part for 2-staff systems without brace?"); private final Constant.Boolean forceSeparateParts = new Constant.Boolean( false, "Should we force all staves to use separate parts?"); private final Scale.Fraction minSeparateStaffGutter = new Scale.Fraction( 2.5, "Minimum vertical gap between two part staves to be separated"); private final Scale.Fraction minBracketWidth = new Scale.Fraction( 0.25, "Minimum width for a bracket peak"); private final Scale.Fraction maxBracketExtension = new Scale.Fraction( 1.25, "Maximum extension for bracket trunk end above or below staff line"); private final Scale.Fraction serifSegmentLength = new Scale.Fraction( 1.0, "Typical distance between bracket serif points"); private final Scale.Fraction serifRoiWidth = new Scale.Fraction( 2.0, "Width of lookup ROI for bracket serif"); private final Scale.Fraction serifRoiHeight = new Scale.Fraction( 2.0, "Height of lookup ROI for bracket serif"); private final Scale.Fraction serifThickness = new Scale.Fraction( 0.3, "Typical thickness of bracket serif"); private final Scale.AreaFraction serifMinWeight = new Scale.AreaFraction( 0.2, "Minimum weight for bracket serif"); } // Parameters // private static class Parameters { final int largeSystemStaffCount; final double minNormedDeltaWidth; final double maxBarExtension; final int maxLinesLeftToStartBar; final int maxDoubleBarGap; final int minMeasureWidth; final int minPeak1WidthForCClef; final int maxPeak2WidthForCClef; final int cClefTail; final int braceLeftMargin; final int braceSegmentLength; final int minBracePortionHeight; final int maxBraceThickness; final int maxBracePeakWidth; final int maxBraceBarGap; final int braceBarNeutralGap; final int braceLookupExtension; final int maxBraceCurvature; final int minSeparateStaffGutter; final int serifSegmentLength; final int minBracketWidth; final int maxBracketExtension; final int serifRoiWidth; final int serifRoiHeight; final int serifThickness; final int serifMinWeight; final int maxColumnDx; /** * Creates a new Parameters object. * * @param scale the scaling factor */ Parameters (Scale scale) { largeSystemStaffCount = constants.largeSystemStaffCount.getValue(); minNormedDeltaWidth = constants.minThinThickDelta.getValue(); maxBarExtension = scale.toPixels(constants.maxBarExtension); maxLinesLeftToStartBar = scale.toPixels(constants.maxLinesLeftToStartBar); maxDoubleBarGap = scale.toPixels(constants.maxDoubleBarGap); minMeasureWidth = scale.toPixels(constants.minMeasureWidth); cClefTail = scale.toPixels(constants.cClefTail); minPeak1WidthForCClef = scale.toPixels(constants.minPeak1WidthForCClef); maxPeak2WidthForCClef = scale.toPixels(constants.maxPeak2WidthForCClef); braceLeftMargin = scale.toPixels(constants.braceLeftMargin); braceSegmentLength = scale.toPixels(constants.braceSegmentLength); minBracePortionHeight = scale.toPixels(constants.minBracePortionHeight); maxBraceThickness = scale.toPixels(constants.maxBraceThickness); maxBracePeakWidth = scale.toPixels(constants.maxBracePeakWidth); maxBraceBarGap = scale.toPixels(constants.maxBraceBarGap); braceBarNeutralGap = scale.toPixels(constants.braceBarNeutralGap); braceLookupExtension = scale.toPixels(constants.braceLookupExtension); maxBraceCurvature = scale.toPixels(constants.maxBraceCurvature); minSeparateStaffGutter = scale.toPixels(constants.minSeparateStaffGutter); serifSegmentLength = scale.toPixels(constants.serifSegmentLength); minBracketWidth = scale.toPixels(constants.minBracketWidth); maxBracketExtension = scale.toPixels(constants.maxBracketExtension); serifRoiWidth = scale.toPixels(constants.serifRoiWidth); serifRoiHeight = scale.toPixels(constants.serifRoiHeight); serifThickness = scale.toPixels(constants.serifThickness); serifMinWeight = scale.toPixels(constants.serifMinWeight); maxColumnDx = scale.toPixels(constants.maxColumnDx); // TODO: improve this if (logger.isDebugEnabled()) { new Dumping().dump(this); } } } }
package org.lantern; import java.net.InetSocketAddress; import java.security.NoSuchAlgorithmException; import java.util.Collection; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executors; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import org.apache.commons.lang.StringUtils; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.http.DefaultHttpChunk; import org.jboss.netty.handler.codec.http.HttpChunk; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpMethod; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpRequestEncoder; import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.codec.http.HttpResponseDecoder; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.jboss.netty.handler.ssl.SslHandler; import org.littleshoot.proxy.HttpConnectRelayingHandler; import org.littleshoot.proxy.ProxyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Handler that relays traffic to another proxy. */ public class DispatchingProxyRelayHandler extends SimpleChannelUpstreamHandler { private final Logger log = LoggerFactory.getLogger(getClass()); private final Collection<String> whitelist; private volatile long messagesReceived = 0L; private final InetSocketAddress proxyAddress; private Channel outboundChannel; private Channel browserToProxyChannel; private final ProxyStatusListener proxyStatusListener; private final ClientSocketChannelFactory clientSocketChannelFactory = new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); private final Queue<HttpRequest> httpRequests = new ConcurrentLinkedQueue<HttpRequest>(); /** * Creates a new handler that reads incoming HTTP requests and dispatches * them to proxies as appropriate. * * @param proxyStatusListener The class to notify of changes in the proxy * status. * @param whitelist The list of sites to proxy. */ public DispatchingProxyRelayHandler( final ProxyStatusListener proxyStatusListener, final Collection<String> whitelist) { this.proxyAddress = new InetSocketAddress("laeproxy.appspot.com", 443); //new InetSocketAddress("127.0.0.1", 8080); this.proxyStatusListener = proxyStatusListener; this.whitelist = whitelist; } @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent me) { messagesReceived++; log.info("Received {} total messages", messagesReceived); final Object msg = me.getMessage(); log.info("Msg is "+msg); // TODO: This could be a chunk!! We also need to reset this somehow // when the current request changes. Tricky. final HttpRequest request = (HttpRequest)msg; final String uri = request.getUri(); log.info("URI is: {}", uri); final String referer = request.getHeader("referer"); final String uriToCheck; log.info("Referer: "+referer); if (!StringUtils.isBlank(referer)) { uriToCheck = referer; } else { uriToCheck = uri; } final boolean shouldProxy = DomainWhitelister.isWhitelisted(uriToCheck, whitelist); if (shouldProxy) { log.info("Proxying!"); if (request.getMethod().equals(HttpMethod.CONNECT)) { // We need to forward the CONNECT request from this proxy to an // external proxy that can handle it. We effectively want to // relay all traffic in this case without doing anything on // our own other than direct the CONNECT request to the correct // proxy. if (this.outboundChannel == null) { log.info("Opening HTTP CONNECT tunnel"); openOutgoingRelayChannel(ctx, request); } else { log.error("Outbound channel already assigned?"); } } else { if (this.outboundChannel == null) { log.error("Outbound channel already assigned?"); final ChannelFuture future = openOutgoingChannel(); future.addListener(new ChannelFutureListener() { public void operationComplete(final ChannelFuture cf) throws Exception { if (cf.isSuccess()) { writeRequest(uri, request); } } }); } else { writeRequest(uri, request); } } } else { log.info("Not proxying!"); final HttpRequestHandler rh = new HttpRequestHandler(); rh.messageReceived(ctx, me); } } private void writeRequest(final String uri, final HttpRequest request) { // We need to decide which proxy to send the request to here. final String proxyHost = "laeproxy.appspot.com"; //final String proxyHost = "127.0.0.1"; final String proxyBaseUri = "https://" + proxyHost; if (!uri.startsWith(proxyBaseUri)) { request.setHeader("Host", proxyHost); final String scheme = uri.substring(0, uri.indexOf(':')); final String rest = uri.substring(scheme.length() + 3); final String proxyUri = proxyBaseUri + "/" + scheme + "/" + rest; log.debug("proxyUri: " + proxyUri); request.setUri(proxyUri); } else { log.info("NOT MODIFYING URI -- ALREADY HAS FREELANTERN"); } writeRequest(request); } @Override public void channelOpen(final ChannelHandlerContext ctx, final ChannelStateEvent e) { log.info("Got incoming channel"); //openOutgoingChannel(e.getChannel()); this.browserToProxyChannel = e.getChannel(); } private ChannelFuture openOutgoingChannel() { if (this.outboundChannel != null) { log.error("Outbound channel already assigned?"); } //this.browserToProxyChannel = incomingChannel; browserToProxyChannel.setReadable(false); // Start the connection attempt. final ClientBootstrap cb = new ClientBootstrap(this.clientSocketChannelFactory); final ChannelPipeline pipeline = cb.getPipeline(); try { log.info("Creating SSL engine"); final SSLEngine engine = SSLContext.getDefault().createSSLEngine(); engine.setUseClientMode(true); pipeline.addLast("ssl", new SslHandler(engine)); } catch (final NoSuchAlgorithmException nsae) { log.error("Could not create default SSL context"); } pipeline.addLast("decoder", new HttpResponseDecoder()); pipeline.addLast("encoder", new HttpRequestEncoder()); pipeline.addLast("handler", new OutboundHandler()); final ChannelFuture cf = cb.connect(this.proxyAddress); this.outboundChannel = cf.getChannel(); log.info("Got an outbound channel on: {}", hashCode()); // This is handy, as set readable to false while the channel is // connecting ensures we won't get any incoming messages until // we're fully connected. cf.addListener(new ChannelFutureListener() { public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection attempt succeeded: // Begin to accept incoming traffic. browserToProxyChannel.setReadable(true); } else { // Close the connection if the connection attempt has failed. browserToProxyChannel.close(); proxyStatusListener.onCouldNotConnect(proxyAddress); } } }); return cf; } private void openOutgoingRelayChannel(final ChannelHandlerContext ctx, final HttpRequest request) { if (this.outboundChannel != null) { log.error("Outbound channel already assigned?"); } //this.browserToProxyChannel = incomingChannel; browserToProxyChannel.setReadable(false); // Start the connection attempt. final ClientBootstrap cb = new ClientBootstrap(this.clientSocketChannelFactory); final ChannelPipeline pipeline = cb.getPipeline(); pipeline.addLast("encoder", new HttpRequestEncoder()); pipeline.addLast("handler", new HttpConnectRelayingHandler(browserToProxyChannel, null)); log.info("Connecting to relay proxy"); final ChannelFuture cf = cb.connect( new InetSocketAddress("75.101.155.190", 7777)); this.outboundChannel = cf.getChannel(); log.info("Got an outbound channel on: {}", hashCode()); final ChannelPipeline browserPipeline = ctx.getPipeline(); browserPipeline.remove("encoder"); browserPipeline.remove("decoder"); browserPipeline.remove("handler"); browserPipeline.addLast("handler", new HttpConnectRelayingHandler(this.outboundChannel, null)); // This is handy, as set readable to false while the channel is // connecting ensures we won't get any incoming messages until // we're fully connected. cf.addListener(new ChannelFutureListener() { public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { outboundChannel.write(request).addListener( new ChannelFutureListener() { public void operationComplete( final ChannelFuture future) throws Exception { pipeline.remove("encoder"); // Begin to accept incoming traffic. browserToProxyChannel.setReadable(true); } }); } else { // Close the connection if the connection attempt has failed. browserToProxyChannel.close(); proxyStatusListener.onCouldNotConnect(proxyAddress); } } }); } @Override public void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent e) { log.info("Got inbound channel closed. Closing outbound."); LanternUtils.closeOnFlush(this.outboundChannel); } @Override public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent e) throws Exception { log.error("Caught exception on INBOUND channel", e.getCause()); LanternUtils.closeOnFlush(this.browserToProxyChannel); } private class OutboundHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) { final Object msg = e.getMessage(); if (msg instanceof HttpChunk) { final HttpChunk chunk = (HttpChunk) msg; if (chunk.isLast()) { log.info("GOT LAST CHUNK"); } browserToProxyChannel.write(chunk); } else { log.info("Got message on outbound handler: {}", msg); // There should always be a one-to-one relaationship between // requests and responses, so we want to pop a request off the // queue for every response we get in. This is only really // needed so we have all the appropriate request values for // making additional requests to handle 206 partial responses. final HttpRequest request = httpRequests.remove(); //final ChannelBuffer msg = (ChannelBuffer) e.getMessage(); //if (msg instanceof HttpResponse) { final HttpResponse response = (HttpResponse) msg; final int code = response.getStatus().getCode(); if (code != 206) { log.info("No 206. Writing whole response"); browserToProxyChannel.write(response); } else { // We just grab this before queuing the request because // we're about to remove it. final String cr = response.getHeader(HttpHeaders.Names.CONTENT_RANGE); final long cl = parseFullContentLength(cr); if (isFirstChunk(cr)) { // If this is the *first* partial response to this // request, we need to build a new HTTP response as if // it were a normal, non-partial 200 OK. We need to // make sure not to do this for *every* 206 response, // however. response.setStatus(HttpResponseStatus.OK); log.info("Setting Content Length to: "+cl+" from "+cr); response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, cl); response.removeHeader(HttpHeaders.Names.CONTENT_RANGE); browserToProxyChannel.write(response); } else { // We need to grab the body of the partial response // and return it as an HTTP chunk. final HttpChunk chunk = new DefaultHttpChunk(response.getContent()); browserToProxyChannel.write(chunk); } // Spin up additional requests on a new thread. requestRange(request, response, cr, cl); } } } @Override public void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent e) throws Exception { LanternUtils.closeOnFlush(browserToProxyChannel); } @Override public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent e) throws Exception { log.error("Caught exception on OUTBOUND channel", e.getCause()); LanternUtils.closeOnFlush(e.getChannel()); } } /** * Helper method that ensures all written requests are properly recorded. * * @param request The request. */ private void writeRequest(final HttpRequest request) { this.httpRequests.add(request); log.info("Writing request: {}", request); this.outboundChannel.write(request); } private boolean isFirstChunk(final String contentRange) { return contentRange.trim().startsWith("bytes 0-"); } private long parseFullContentLength(final String contentRange) { final String fullLength = StringUtils.substringAfterLast(contentRange, "/"); return Long.parseLong(fullLength); } private static final long CHUNK_SIZE = 1024 * 1024 * 10 - (2 * 1024); private void requestRange(final HttpRequest request, final HttpResponse response, final String contentRange, final long fullContentLength) { log.info("Queuing request based on Content-Range: {}", contentRange); // Note we don't need to thread this since it's all asynchronous // anyway. final String body = StringUtils.substringAfter(contentRange, "bytes "); if (StringUtils.isBlank(body)) { log.error("Blank bytes body: "+contentRange); return; } final long contentLength = HttpHeaders.getContentLength(response); final String startPlus = StringUtils.substringAfter(body, "-"); final String startString = StringUtils.substringBefore(startPlus, "/"); final long start = Long.parseLong(startString) + 1; // This means the last response provided the final range, so we don't // want to request another one. if (start == fullContentLength) { log.info("Received full length...not requesting new range"); return; } final long end; if (contentLength - start > CHUNK_SIZE) { end = start + CHUNK_SIZE; } else { end = fullContentLength - 1; } request.setHeader(HttpHeaders.Names.RANGE, "bytes="+start+"-"+end); writeRequest(request); } private void handleHttpConnect(final ChannelHandlerContext ctx, final HttpRequest httpRequest, final Channel outgoingChannel) { final int port = ProxyUtils.parsePort(httpRequest); final Channel browserToProxyChannel = ctx.getChannel(); // TODO: We should really only allow access on 443, but this breaks // what a lot of browsers do in practice. //if (port != 443) { if (port < 0) { log.warn("Connecting on port other than 443!!"); final String statusLine = "HTTP/1.1 502 Proxy Error\r\n"; ProxyUtils.writeResponse(browserToProxyChannel, statusLine, ProxyUtils.PROXY_ERROR_HEADERS); } else { // We need to modify both the pipeline encoders and decoders for the // browser to proxy channel *and* the encoders and decoders for the // proxy to external site channel. ctx.getPipeline().remove("encoder"); ctx.getPipeline().remove("decoder"); ctx.getPipeline().remove("handler"); ctx.getPipeline().addLast("handler", new HttpConnectRelayingHandler(outgoingChannel, null)); //final String statusLine = "HTTP/1.1 200 Connection established\r\n"; //ProxyUtils.writeResponse(browserToProxyChannel, statusLine, // ProxyUtils.CONNECT_OK_HEADERS); //final HttpRequestEncoder encoder = new HttpRequestEncoder(); //final int cb = encoder. browserToProxyChannel.setReadable(true); } } }
package skadistats.clarity.decoder; public class BitStream { final int[] words; int pos; public BitStream(byte[] data) { // it seems valve started not sending trailing zero bits in a stream under certain circumstances? // example match id 714979634 // append a zero word at the end, which seems to fix it for now this.words = new int[(data.length + 7) / 4]; this.pos = 0; int akku = 0; for (int i = 0; i < data.length; i++) { int shift = 8 * (i & 3); int val = ((int) data[i]) & 0xFF; akku = akku | (val << shift); if ((i & 3) == 3) { words[i / 4] = akku; akku = 0; } } if ((data.length & 3) != 0) { words[data.length / 4] = akku; } words[words.length - 1] = 0; } public int peekNumericBits(int num) { int l = words[pos >> 5]; int r = words[(pos + num - 1) >> 5]; int shift = pos & 31; int rebuild = (r << (32 - shift)) | (l >>> shift); return (rebuild & ((int)((long)1 << num) - 1)); } public int readNumericBits(int num) { int result = peekNumericBits(num); pos += num; return result; } public boolean readBit() { boolean result = peekNumericBits(1) != 0; pos += 1; return result; } public byte[] readBits(int num) { byte[] result = new byte[(num + 7) / 8]; int i = 0; while (num > 7) { num -= 8; result[i] = (byte) readNumericBits(8); i++; } if (num != 0) { result[i] = (byte) readNumericBits(num); } return result; } public String readString(int num) { StringBuffer buf = new StringBuffer(); while (num > 0) { char c = (char) readNumericBits(8); if (c == 0) { break; } buf.append(c); num } return buf.toString(); } public int readVarInt() { int run = 0; int value = 0; while (true) { int bits = readNumericBits(8); value = value | ((bits & 0x7f) << run); run += 7; if ((bits >> 7) == 0 || run == 35) { break; } } return value; } public String toString() { StringBuffer buf = new StringBuffer(); int min = Math.max(0, (pos - 32) / 32); int max = Math.min(words.length - 1, (pos + 63) / 32); for (int i = min; i <= max; i++) { buf.append(new StringBuffer(String.format("%32s", Integer.toBinaryString(words[i])).replace(' ', '0')).reverse()); } buf.insert(pos - min * 32, '*'); return buf.toString(); } }
package org.mac.sim.simulation; import org.mac.sim.domain.SimulationConfigurations; import org.mac.sim.domain.SimulationParameters; import org.mac.sim.exception.TurnoverException; /** * SimulationBuilder implementations are meant to 1) encapsulate the logic which * extracts relevant information from the configuration, 2) provide simple * methods for modifying/editing this information, all while 3) hiding the * details of the Simulation implementation itself. * * @author Home * */ public abstract class SimulationBuilder { protected SimulationParameters simulationParams; protected SimulationBuilder(SimulationConfigurations simulationConfig) { } public abstract Simulation build() throws TurnoverException; }
package techreborn.blocks; import com.google.common.base.CaseFormat; import com.google.common.collect.Lists; import net.minecraft.block.material.Material; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import prospector.shootingstar.ShootingStar; import prospector.shootingstar.model.ModelCompound; import reborncore.api.ToolManager; import reborncore.common.blocks.BlockWrenchEventHandler; import reborncore.common.blocks.PropertyString; import reborncore.common.items.WrenchHelper; import reborncore.common.multiblock.BlockMultiblockBase; import reborncore.common.util.ArrayUtils; import techreborn.utils.TechRebornCreativeTab; import techreborn.init.ModBlocks; import techreborn.lib.ModInfo; import techreborn.tiles.TileMachineCasing; import java.security.InvalidParameterException; import java.util.List; import java.util.Random; public class BlockMachineCasing extends BlockMultiblockBase { public static final String[] types = new String[] { "standard", "reinforced", "advanced" }; public static final PropertyString TYPE = new PropertyString("type", types); private static final List<String> typesList = Lists.newArrayList(ArrayUtils.arrayToLowercase(types)); public BlockMachineCasing() { super(Material.IRON); setCreativeTab(TechRebornCreativeTab.instance); setHardness(2F); this.setDefaultState(this.getDefaultState().withProperty(TYPE, "standard")); for (int i = 0; i < types.length; i++) { ShootingStar.registerModel(new ModelCompound(ModInfo.MOD_ID, this, i, "machines/structure").setInvVariant("type=" + types[i])); } BlockWrenchEventHandler.wrenableBlocks.add(this); } public static ItemStack getStackByName(String name, int count) { name = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name); for (int i = 0; i < types.length; i++) { if (types[i].equalsIgnoreCase(name)) { return new ItemStack(ModBlocks.MACHINE_CASINGS, count, i); } } throw new InvalidParameterException("The machine casing " + name + " could not be found."); } public static ItemStack getStackByName(String name) { return getStackByName(name, 1); } /** * Provides heat info per casing for Industrial Blast Furnace * @param state Machine casing type * @return Integer Heat value for casing */ public int getHeatFromState(IBlockState state) { switch (getMetaFromState(state)) { case 0: return 1020 / 25; case 1: return 1700 / 25; case 2: return 2380 / 25; } return 0; } @Override public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { ItemStack stack = playerIn.getHeldItem(EnumHand.MAIN_HAND); TileEntity tileEntity = worldIn.getTileEntity(pos); // We extended BaseTileBlock. Thus we should always have tile entity. I hope. if (tileEntity == null) { return false; } if (!stack.isEmpty() && ToolManager.INSTANCE.canHandleTool(stack)) { if (WrenchHelper.handleWrench(stack, worldIn, pos, playerIn, side)) { return true; } } return super.onBlockActivated(worldIn, pos, state, playerIn, hand, side, hitX, hitY, hitZ); } @Override public IBlockState getStateFromMeta(int meta) { if (meta > types.length) { meta = 0; } return getBlockState().getBaseState().withProperty(TYPE, typesList.get(meta)); } @Override public int getMetaFromState(IBlockState state) { return typesList.indexOf(state.getValue(TYPE)); } @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, TYPE); } @Override public Item getItemDropped(IBlockState state, Random rand, int fortune) { return Item.getItemFromBlock(this); } @Override @SideOnly(Side.CLIENT) public void getSubBlocks(CreativeTabs creativeTabs, NonNullList<ItemStack> list) { for (int meta = 0; meta < types.length; meta++) { list.add(new ItemStack(this, 1, meta)); } } @Override public int damageDropped(IBlockState state) { return getMetaFromState(state); } @Override public TileEntity createNewTileEntity(final World world, final int meta) { return new TileMachineCasing(); } }
package techreborn.compat.recipes; import cpw.mods.fml.common.Mod; import ic2.api.item.IC2Items; import ic2.api.recipe.RecipeInputOreDict; import ic2.api.recipe.Recipes; import ic2.core.item.resources.ItemCell; import ic2.core.item.resources.ItemDust; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; import techreborn.api.recipe.RecipeHanderer; import techreborn.api.recipe.machines.AssemblingMachineRecipe; import techreborn.api.recipe.machines.CentrifugeRecipe; import techreborn.api.recipe.machines.GrinderRecipe; import techreborn.config.ConfigTechReborn; import techreborn.init.ModBlocks; import techreborn.init.ModFluids; import techreborn.init.ModItems; import techreborn.items.*; import techreborn.util.CraftingHelper; import techreborn.util.LogHelper; import techreborn.util.RecipeRemover; import techreborn.items.ItemParts; import techreborn.items.ItemIngots; import techreborn.items.ItemDusts; public class RecipesIC2 { public static ConfigTechReborn config; public static void init() { removeIc2Recipes(); addShappedIc2Recipes(); addShapedTrRecipes(); addTRMaceratorRecipes(); addTROreWashingRecipes(); addTRThermalCentrifugeRecipes(); addMetalFormerRecipes(); addAssemblingMachineRecipes(); addIndustrialCentrifugeRecipes(); addIndustrialGrinderRecipes(); } public static void removeIc2Recipes() { if (config.ExpensiveMacerator); RecipeRemover.removeAnyRecipe(IC2Items.getItem("macerator")); if (config.ExpensiveDrill); RecipeRemover.removeAnyRecipe(IC2Items.getItem("miningDrill")); if (config.ExpensiveDiamondDrill); RecipeRemover.removeAnyRecipe(IC2Items.getItem("diamondDrill")); if (config.ExpensiveSolar); RecipeRemover.removeAnyRecipe(IC2Items.getItem("solarPanel")); LogHelper.info("IC2 Recipes Removed"); } public static void addShappedIc2Recipes() { if (config.ExpensiveMacerator); CraftingHelper.addShapedOreRecipe(IC2Items.getItem("macerator"), new Object[] {"FDF", "DMD", "FCF", 'F', Items.flint, 'D', Items.diamond, 'M', IC2Items.getItem("machine"), 'C', IC2Items.getItem("electronicCircuit")}); if (config.ExpensiveDrill); CraftingHelper.addShapedOreRecipe(IC2Items.getItem("miningDrill"), new Object[] {" S ", "SCS", "SBS", 'S', "ingotSteel", 'B', IC2Items.getItem("reBattery"), 'C', IC2Items.getItem("electronicCircuit")}); if (config.ExpensiveDiamondDrill); CraftingHelper.addShapedOreRecipe(IC2Items.getItem("diamondDrill"), new Object[] {" D ", "DBD", "TCT", 'D', "gemDiamond", 'T', "ingotTitanium", 'B', IC2Items.getItem("miningDrill"), 'C', IC2Items.getItem("advancedCircuit")}); if (config.ExpensiveSolar); CraftingHelper.addShapedOreRecipe(IC2Items.getItem("solarPanel"), new Object[] {"PPP", "SZS", "CGC", 'P', "paneGlass", 'S', new ItemStack(ModItems.parts, 1, 1), 'Z', IC2Items.getItem("carbonPlate"), 'G', IC2Items.getItem("generator"), 'C', IC2Items.getItem("electronicCircuit")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.thermalGenerator), new Object[] {"III", "IHI", "CGC", 'I', "plateInvar", 'H', IC2Items.getItem("reinforcedGlass"), 'C', "circuitBasic", 'G', IC2Items.getItem("geothermalGenerator")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.thermalGenerator), new Object[] {"AAA", "AHA", "CGC", 'A', "plateAluminum", 'H', IC2Items.getItem("reinforcedGlass"), 'C', "circuitBasic", 'G', IC2Items.getItem("geothermalGenerator")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Gasturbine), new Object[] {"IAI", "WGW", "IAI", 'I', "plateInvar", 'A', IC2Items.getItem("advancedCircuit"), 'W', IC2Items.getItem("windMill"), 'G', IC2Items.getItem("reinforcedGlass")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Gasturbine), new Object[] {"IAI", "WGW", "IAI", 'I', "plateAluminum", 'A', IC2Items.getItem("advancedCircuit"), 'W', IC2Items.getItem("windMill"), 'G', IC2Items.getItem("reinforcedGlass")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Semifluidgenerator), new Object[] {"III", "IHI", "CGC", 'I', "plateIron", 'H', IC2Items.getItem("reinforcedGlass"), 'C', "circuitBasic", 'G', IC2Items.getItem("generator")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Semifluidgenerator), new Object[] {"AAA", "AHA", "CGC", 'A', "plateAluminum", 'H', IC2Items.getItem("reinforcedGlass"), 'C', "circuitBasic", 'G', IC2Items.getItem("generator")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.DieselGenerator), new Object[] {"III", "I I", "CGC", 'I', "plateIron", 'C', "circuitBasic", 'G', IC2Items.getItem("generator")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.DieselGenerator), new Object[] {"AAA", "A A", "CGC", 'A', "plateAluminum", 'C', "circuitBasic", 'G', IC2Items.getItem("generator")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.MagicalAbsorber), new Object[] {"CSC", "IBI", "CAC", 'C', "circuitMaster", 'S', "craftingSuperconductor", 'B', Blocks.beacon, 'A', ModBlocks.Magicenergeyconverter, 'I', IC2Items.getItem("iridiumPlate")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Magicenergeyconverter), new Object[] {"CTC", "PBP", "CLC", 'C', "circuitAdvanced", 'P', "platePlatinum", 'B', Blocks.beacon, 'L', IC2Items.getItem("lapotronCrystal"), 'T', IC2Items.getItem("teleporter")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Dragoneggenergysiphoner), new Object[] {"CTC", "ISI", "CBC", 'I', IC2Items.getItem("iridiumPlate"), 'C', "circuitMaster", 'B', "batteryUltimate", 'S', ModBlocks.Supercondensator, 'T', IC2Items.getItem("teleporter")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.centrifuge), new Object[] {"SCS", "BEB", "SCS", 'S', "plateSteel", 'C', "circuitAdvanced", 'B', IC2Items.getItem("advancedMachine"), 'E', IC2Items.getItem("extractor")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.IndustrialElectrolyzer), new Object[] {"SXS", "CEC", "SMS", 'S', "plateSteel", 'C', "circuitAdvanced", 'X', IC2Items.getItem("extractor"), 'E', IC2Items.getItem("electrolyzer"), 'M', IC2Items.getItem("magnetizer")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.BlastFurnace), new Object[] {"CHC", "HBH", "FHF", 'H', new ItemStack(ModItems.parts, 1, 17), 'C', "circuitAdvanced", 'B', IC2Items.getItem("advancedMachine"), 'F', IC2Items.getItem("inductionFurnace")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Grinder), new Object[] {"ECP", "GGG", "CBC", 'E', ModBlocks.IndustrialElectrolyzer, 'P', IC2Items.getItem("pump"), 'C', "circuitAdvanced", 'B', IC2Items.getItem("advancedMachine"), 'G', "craftingGrinder"}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.ImplosionCompressor), new Object[] {"ABA", "CPC", "ABA", 'A', IC2Items.getItem("advancedAlloy"), 'C', "circuitAdvanced", 'B', IC2Items.getItem("advancedMachine"), 'P', IC2Items.getItem("compressor")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.VacuumFreezer), new Object[] {"SPS", "CGC", "SPS", 'S', "plateSteel", 'C', "circuitAdvanced", 'G', IC2Items.getItem("reinforcedGlass"), 'P', IC2Items.getItem("pump")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Distillationtower), new Object[] {"CMC", "PBP", "EME", 'E', ModBlocks.IndustrialElectrolyzer, 'M', "circuitMaster", 'B', IC2Items.getItem("advancedMachine"), 'C', ModBlocks.centrifuge, 'P', IC2Items.getItem("pump")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.AlloyFurnace), new Object[] {"III", "F F", "III", 'I', "plateIron", 'F', IC2Items.getItem("ironFurnace")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.AlloySmelter), new Object[] {"IHI", "CFC", "IHI", 'I', "plateInvar", 'C', "circuitBasic", 'H', new ItemStack(ModItems.parts, 1, 17), 'F', ModBlocks.AlloyFurnace}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.AssemblyMachine), new Object[] {"CPC", "SBS", "CSC", 'S', "plateSteel", 'C', "circuitBasic", 'B', IC2Items.getItem("machine"), 'P', "craftingPiston"}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.ChemicalReactor), new Object[] {"IMI", "CPC", "IEI", 'I', "plateInvar", 'C', "circuitAdvanced", 'M', IC2Items.getItem("magnetizer"), 'P', IC2Items.getItem("compressor"), 'E', IC2Items.getItem("extractor")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.ChemicalReactor), new Object[] {"AMA", "CPC", "AEA", 'A', "plateAluminum", 'C', "circuitAdvanced", 'M', IC2Items.getItem("magnetizer"), 'P', IC2Items.getItem("compressor"), 'E', IC2Items.getItem("extractor")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.lathe), new Object[] {"SLS", "GBG", "SCS", 'S', "plateSteel", 'C', "circuitAdvanced", 'G', "gearSteel", 'B', IC2Items.getItem("advancedMachine"), 'L', IC2Items.getItem("LathingTool")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.platecuttingmachine), new Object[] {"SCS", "GDG", "SBS", 'S', "plateSteel", 'C', "circuitAdvanced", 'G', "gearSteel", 'B', IC2Items.getItem("advancedMachine"), 'D', new ItemStack(ModItems.parts, 1, 9)}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.RollingMachine), new Object[] {"PCP", "MBM", "PCP", 'P', "craftingPiston", 'C', "circuitAdvanced", 'M', IC2Items.getItem("compressor"), 'B', IC2Items.getItem("machine")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.ElectricCraftingTable), new Object[] {"ITI", "IBI", "ICI", 'I', "plateIron", 'C', "circuitAdvanced", 'T', "crafterWood", 'B', IC2Items.getItem("machine")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.ElectricCraftingTable), new Object[] {"ATA", "ABA", "ACA", 'A', "plateAluminum", 'C', "circuitAdvanced", 'T', "crafterWood", 'B', IC2Items.getItem("machine")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.ChunkLoader), new Object[] {"SCS", "CMC", "SCS", 'S', "plateSteel", 'C', "circuitMaster", 'M', new ItemStack(ModItems.parts, 1, 39)}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Lesu), new Object[] {" L ", "CBC", " M ", 'L', IC2Items.getItem("lvTransformer"), 'C', "circuitAdvanced", 'M', IC2Items.getItem("mvTransformer"), 'B', ModBlocks.LesuStorage}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.LesuStorage), new Object[] {"LLL", "LCL", "LLL", 'L', "blockLapis", 'C', "circuitBasic"}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Woodenshelf), new Object[] {"WWW", "A A", "WWW", 'W', "plankWood", 'A', "plateAluminum"}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Metalshelf), new Object[] {"III", "A A", "III", 'I', "plateIron", 'A', "plateAluminum"}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.HighAdvancedMachineBlock), new Object[] {"CTC", "TBT", "CTC", 'C', "plateChrome", 'T', "plateTitanium", 'B', IC2Items.getItem("advancedMachine")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.MachineCasing, 4, 0), new Object[] {"III", "CBC", "III", 'I', "plateIron", 'C', "circuitBasic", 'B', IC2Items.getItem("machine")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.MachineCasing, 4, 1), new Object[] {"SSS", "CBC", "SSS", 'S', "plateSteel", 'C', "circuitAdvanced", 'B', IC2Items.getItem("advancedMachine")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.MachineCasing, 4, 2), new Object[] {"HHH", "CBC", "HHH", 'H', "plateChrome", 'C', "circuitElite", 'B', ModBlocks.HighAdvancedMachineBlock}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.quantumChest), new Object[] {"DCD", "ATA", "DQD", 'D', ItemParts.getPartByName("dataOrb"), 'C', ItemParts.getPartByName("computerMonitor"), 'A', ModBlocks.HighAdvancedMachineBlock, 'Q', ModBlocks.digitalChest, 'T', IC2Items.getItem("teleporter")}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.ComputerCube), new Object[] {"DME", "MAM", "EMD", 'E', ItemParts.getPartByName("energyFlowCircuit"), 'D', ItemParts.getPartByName("dataOrb"), 'M', ItemParts.getPartByName("computerMonitor"), 'A', IC2Items.getItem("advancedMachine") }); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.lapotronicOrb), new Object[] {"LLL", "LPL", "LLL", 'L', IC2Items.getItem("lapotronCrystal"), 'P', IC2Items.getItem("iridiumPlate") }); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.lapotronicOrb), new Object[] {"LLL", "LPL", "LLL", 'L', IC2Items.getItem("lapotronCrystal"), 'P', IC2Items.getItem("iridiumPlate") }); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("tungstenGrindingHead", 2), new Object[] {"TST", "SBS", "TST", 'T', "plateTungsten", 'S', "plateSteel", 'B', "blockSteel" }); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.MatterFabricator), new Object[] {"ETE", "AOA", "ETE", 'E', ItemParts.getPartByName("energyFlowCircuit"), 'T', IC2Items.getItem("teleporter"), 'A', ModBlocks.HighAdvancedMachineBlock, 'O', ModItems.lapotronicOrb }); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("iridiumAlloyIngot"), new Object[] {"IAI", "ADA", "IAI", 'I', ItemIngots.getIngotByName("iridium"), 'D', ItemDusts.getDustByName("diamond"), 'A', IC2Items.getItem("advancedAlloy") }); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("energyFlowCircuit", 4), new Object[] {"ATA", "LIL", "ATA", 'T', "plateTungsten", 'I', IC2Items.getItem("iridiumPlate"), 'A', IC2Items.getItem("advancedCircuit"), 'L', IC2Items.getItem("lapotronCrystal") }); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Supercondensator), new Object[] {"EOE", "SAS", "EOE", 'E', ItemParts.getPartByName("energyFlowCircuit"), 'O', ModItems.lapotronicOrb, 'S', ItemParts.getPartByName("superconductor"), 'A', ModBlocks.HighAdvancedMachineBlock }); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("superconductor", 4), new Object[] {"CCC", "TIT", "EEE", 'E', ItemParts.getPartByName("energyFlowCircuit"), 'C', ItemParts.getPartByName("heliumCoolantSimple"), 'T', "ingotTungsten", 'I', IC2Items.getItem("iridiumPlate") }); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("diamondSawBlade"), new Object[] {"DSD", "S S", "DSD", 'S', "plateSteel", 'D', ItemDusts.getDustByName("diamond") }); LogHelper.info("Added Expensive IC2 Recipes"); } public static void addShapedTrRecipes() { CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.quantumTank), new Object[] {"EPE", "PCP", "EPE", 'P', "platePlatinum", 'E', "circuitMaster", 'C', ModBlocks.quantumChest}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.digitalChest), new Object[] {"PPP", "PDP", "PCP", 'P', "plateAluminum", 'D', ItemParts.getPartByName("dataOrb"), 'C', ItemParts.getPartByName("computerMonitor") }); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.digitalChest), new Object[] {"PPP", "PDP", "PCP", 'P', "plateSteel", 'D', ItemParts.getPartByName("dataOrb"), 'C', ItemParts.getPartByName("computerMonitor") }); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.parts, 1, 40), new Object[] { "PLP", "RGB", "PYP", 'P', "plateAluminum", 'L', "dyeLime", 'R', "dyeRed", 'G', "paneGlass", 'B', "dyeBlue", 'Y', Items.glowstone_dust}); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.parts, 4, 6), new Object[] { "EEE", "EAE", "EEE", 'E', "gemEmerald", 'A', IC2Items.getItem("electronicCircuit") }); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.parts, 1, 7), new Object[] { "AGA", "RPB", "ASA", 'A', "ingotAluminium", 'G', "dyeGreen", 'R', "dyeRed", 'P', "paneGlass", 'B', "dyeBlue", 'S',Items.glowstone_dust, }); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.parts, 4, 8), new Object[] { "DSD", "S S", "DSD", 'D', "dustDiamond", 'S', "ingotSteel" }); CraftingHelper.addShapedOreRecipe( new ItemStack(ModItems.parts, 16, 13), new Object[] { "CSC", "SCS", "CSC", 'S', "ingotSteel", 'C',IC2Items.getItem("electronicCircuit") }); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.parts, 2, 14), new Object[] { "TST", "SBS", "TST", 'S', "ingotSteel", 'T', "ingotTungsten", 'B', "blockSteel" }); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.parts, 1, 15), new Object[] { "AAA", "AMA", "AAA", 'A', "ingotAluminium", 'M', new ItemStack(ModItems.parts, 1, 13) }); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.parts, 1, 16), new Object[] { "AAA", "AMA", "AAA", 'A', "ingotBronze", 'M', new ItemStack(ModItems.parts, 1, 13) }); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.parts, 1, 17), new Object[] { "AAA", "AMA", "AAA", 'A', "ingotSteel", 'M', new ItemStack(ModItems.parts, 1, 13) }); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.parts, 1, 18), new Object[] { "AAA", "AMA", "AAA", 'A', "ingotTitanium", 'M', new ItemStack(ModItems.parts, 1, 13) }); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.parts, 1, 19), new Object[] {"AAA", "AMA", "AAA", 'A', "ingotBrass", 'M', new ItemStack(ModItems.parts, 1, 13)}); } public static void addTRMaceratorRecipes() { //Macerator if(OreDictionary.doesOreNameExist("oreAluminum")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreAluminum"), null, ItemCrushedOre.getCrushedOreByName("Aluminum", 2)); } if(OreDictionary.doesOreNameExist("oreArdite")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreArdite"), null, ItemCrushedOre.getCrushedOreByName("Ardite", 2)); } if(OreDictionary.doesOreNameExist("oreBauxite")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreBauxite"), null, ItemCrushedOre.getCrushedOreByName("Bauxite", 2)); } if(OreDictionary.doesOreNameExist("oreCadmium")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreCadmium"), null, ItemCrushedOre.getCrushedOreByName("Cadmium", 2)); } if(OreDictionary.doesOreNameExist("oreCinnabar")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreCinnabar"), null, ItemCrushedOre.getCrushedOreByName("Cinnabar", 2)); } if(OreDictionary.doesOreNameExist("oreCobalt")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreCobalt"), null, ItemCrushedOre.getCrushedOreByName("Cobalt", 2)); } if(OreDictionary.doesOreNameExist("oreDarkIron")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreDarkIron"), null, ItemCrushedOre.getCrushedOreByName("DarkIron", 2)); } if(OreDictionary.doesOreNameExist("oreIndium")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreIndium"), null, ItemCrushedOre.getCrushedOreByName("Indium", 2)); } if(OreDictionary.doesOreNameExist("oreIridium")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreIridium"), null, ItemCrushedOre.getCrushedOreByName("Iridium", 2)); } if(OreDictionary.doesOreNameExist("oreNickel")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreNickel"), null, ItemCrushedOre.getCrushedOreByName("Nickel", 2)); } if(OreDictionary.doesOreNameExist("orePlatinum")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("orePlatinum"), null, ItemCrushedOre.getCrushedOreByName("Platinum", 2)); } if(OreDictionary.doesOreNameExist("orePyrite")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("orePyrite"), null, ItemCrushedOre.getCrushedOreByName("Pyrite", 2)); } if(OreDictionary.doesOreNameExist("oreSphalerite")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreSphalerite"), null, ItemCrushedOre.getCrushedOreByName("Sphalerite", 2)); } if(OreDictionary.doesOreNameExist("oreTetrahedrite")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreTetrahedrite"), null, ItemCrushedOre.getCrushedOreByName("Tetrahedrite", 2)); } if(OreDictionary.doesOreNameExist("oreTungsten")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreTungsten"), null, ItemCrushedOre.getCrushedOreByName("Tungsten", 2)); } if(OreDictionary.doesOreNameExist("oreGalena")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreGalena"), null, ItemCrushedOre.getCrushedOreByName("Galena", 2)); } if(OreDictionary.doesOreNameExist("oreRedstone")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreRedstone"), null, new ItemStack(Items.redstone, 10)); } if(OreDictionary.doesOreNameExist("oreLapis")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreLapis"), null, ItemDusts.getDustByName("lapis", 12)); } if(OreDictionary.doesOreNameExist("oreDiamond")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreDiamond"), null, ItemDusts.getDustByName("diamond", 2)); } if(OreDictionary.doesOreNameExist("oreEmerald")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreEmerald"), null, ItemDusts.getDustByName("emerald", 2)); } if(OreDictionary.doesOreNameExist("oreRuby")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreRuby"), null, ItemDusts.getDustByName("ruby", 2)); } if(OreDictionary.doesOreNameExist("oreSapphire")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreSapphire"), null, ItemDusts.getDustByName("sapphire", 2)); } if(OreDictionary.doesOreNameExist("orePeridot")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("orePeridot"), null, ItemDusts.getDustByName("peridot", 2)); } if(OreDictionary.doesOreNameExist("oreSulfur")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreSulfur"), null, ItemDusts.getDustByName("sulfur", 2)); } if(OreDictionary.doesOreNameExist("oreSaltpeter")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreSaltpeter"), null, ItemDusts.getDustByName("saltpeter", 2)); } if(OreDictionary.doesOreNameExist("oreTeslatite")) { ItemStack teslatiteStack = OreDictionary.getOres("dustTeslatite").get(0); teslatiteStack.stackSize = 10; Recipes.macerator.addRecipe(new RecipeInputOreDict("oreTeslatite"), null, teslatiteStack); } if(OreDictionary.doesOreNameExist("oreMithril")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreMithril"), null, ItemDusts.getDustByName("mithril", 2)); } if(OreDictionary.doesOreNameExist("oreVinteum")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreVinteum"), null, ItemDusts.getDustByName("vinteum", 2)); } if(OreDictionary.doesOreNameExist("limestone")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("limestone"), null, ItemDusts.getDustByName("limestone", 2)); } if(OreDictionary.doesOreNameExist("stoneNetherrack")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("stoneNetherrack"), null, ItemDusts.getDustByName("netherrack", 2)); } if(OreDictionary.doesOreNameExist("stoneEndstone")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("stoneEndstone"), null, ItemDusts.getDustByName("endstone", 2)); } if(OreDictionary.doesOreNameExist("stoneRedrock")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("stoneRedrock"), null, ItemDusts.getDustByName("redrock", 2)); } if(OreDictionary.doesOreNameExist("oreMagnetite")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreMagnetite"), null, ItemDusts.getDustByName("magnetite", 2)); } if(OreDictionary.doesOreNameExist("oreLodestone")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreLodestone"), null, ItemDusts.getDustByName("lodestone", 2)); } if(OreDictionary.doesOreNameExist("oreTellurium")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreTellurium"), null, ItemDusts.getDustByName("tellurium", 2)); } if(OreDictionary.doesOreNameExist("oreSilicon")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreSilicon"), null, ItemDusts.getDustByName("silicon", 2)); } if(OreDictionary.doesOreNameExist("oreVoidstone")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreVoidstone"), null, ItemDusts.getDustByName("voidstone", 2)); } if(OreDictionary.doesOreNameExist("oreCalcite")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreCalcite"), null, ItemDusts.getDustByName("calcite", 2)); } if(OreDictionary.doesOreNameExist("oreSodalite")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreSodalite"), null, ItemDusts.getDustByName("sodalite", 2)); } if(OreDictionary.doesOreNameExist("oreGraphite")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("oreGraphite"), null, ItemDusts.getDustByName("graphite", 2)); } if(OreDictionary.doesOreNameExist("blockMarble")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("blockMarble"), null, ItemDusts.getDustByName("marble", 2)); } if(OreDictionary.doesOreNameExist("blockBasalt")) { Recipes.macerator.addRecipe(new RecipeInputOreDict("blockBasalt"), null, ItemDusts.getDustByName("basalt", 2)); } } public static void addTROreWashingRecipes() { //Ore Washing Plant NBTTagCompound liquidAmount = new NBTTagCompound(); liquidAmount.setInteger("amount", 1000); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedAluminum"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("Aluminum", 1), ItemDustTiny.getTinyDustByName("Aluminum", 2), IC2Items.getItem("stoneDust")); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedArdite"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("Ardite", 1), ItemDustTiny.getTinyDustByName("Ardite", 2), IC2Items.getItem("stoneDust")); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedBauxite"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("Bauxite", 1), ItemDustTiny.getTinyDustByName("Bauxite", 2), IC2Items.getItem("stoneDust")); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedCadmium"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("Cadmium", 1), ItemDustTiny.getTinyDustByName("Cadmium", 2), IC2Items.getItem("stoneDust")); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedCinnabar"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("Cinnabar", 1), ItemDustTiny.getTinyDustByName("Cinnabar", 2), IC2Items.getItem("stoneDust")); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedCobalt"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("Cobalt", 1), ItemDustTiny.getTinyDustByName("Cobalt", 2), IC2Items.getItem("stoneDust")); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedDarkIron"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("DarkIron", 1), ItemDustTiny.getTinyDustByName("DarkIron", 2), IC2Items.getItem("stoneDust")); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedIndium"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("Indium", 1), ItemDustTiny.getTinyDustByName("Indium", 2), IC2Items.getItem("stoneDust")); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedIridium"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("Iridium", 1), ItemDustTiny.getTinyDustByName("Iridium", 2), IC2Items.getItem("stoneDust")); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedNickel"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("Nickel", 1), ItemDustTiny.getTinyDustByName("Nickel", 2), IC2Items.getItem("stoneDust")); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedOsmium"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("Osmium", 1), ItemDustTiny.getTinyDustByName("Osmium", 2), IC2Items.getItem("stoneDust")); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedPlatinum"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("Platinum", 1), ItemDustTiny.getTinyDustByName("Platinum", 2), IC2Items.getItem("stoneDust")); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedPyrite"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("Pyrite", 1), ItemDustTiny.getTinyDustByName("Pyrite", 2), IC2Items.getItem("stoneDust")); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedSphalerite"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("Sphalerite", 1), ItemDustTiny.getTinyDustByName("Sphalerite", 2), IC2Items.getItem("stoneDust")); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedTetrahedrite"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("Tetrahedrite", 1), ItemDustTiny.getTinyDustByName("Tetrahedrite", 2), IC2Items.getItem("stoneDust")); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedTungsten"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("Tungsten", 1), ItemDustTiny.getTinyDustByName("Tungsten", 2), IC2Items.getItem("stoneDust")); Recipes.oreWashing.addRecipe(new RecipeInputOreDict("crushedGalena"), liquidAmount, ItemPurifiedCrushedOre.getPurifiedCrushedOreByName("Galena", 1), ItemDustTiny.getTinyDustByName("Galena", 2), IC2Items.getItem("stoneDust")); } public static void addTRThermalCentrifugeRecipes() { //Thermal Centrifuge //Heat Values NBTTagCompound aluminumHeat = new NBTTagCompound(); aluminumHeat.setInteger("minHeat", 2000); NBTTagCompound arditeHeat = new NBTTagCompound(); arditeHeat.setInteger("minHeat", 3000); NBTTagCompound bauxiteHeat = new NBTTagCompound(); bauxiteHeat.setInteger("minHeat", 2500); NBTTagCompound cadmiumHeat = new NBTTagCompound(); cadmiumHeat.setInteger("minHeat", 1500); NBTTagCompound cinnabarHeat = new NBTTagCompound(); cinnabarHeat.setInteger("minHeat", 1500); NBTTagCompound cobaltHeat = new NBTTagCompound(); cobaltHeat.setInteger("minHeat", 3000); NBTTagCompound darkIronHeat = new NBTTagCompound(); darkIronHeat.setInteger("minHeat", 2500); NBTTagCompound indiumHeat = new NBTTagCompound(); indiumHeat.setInteger("minHeat", 2000); NBTTagCompound iridiumHeat = new NBTTagCompound(); iridiumHeat.setInteger("minHeat", 4000); NBTTagCompound nickelHeat = new NBTTagCompound(); nickelHeat.setInteger("minHeat", 2000); NBTTagCompound osmiumHeat = new NBTTagCompound(); osmiumHeat.setInteger("minHeat", 2000); NBTTagCompound platinumHeat = new NBTTagCompound(); platinumHeat.setInteger("minHeat", 3000); NBTTagCompound pyriteHeat = new NBTTagCompound(); pyriteHeat.setInteger("minHeat", 1500); NBTTagCompound sphaleriteHeat = new NBTTagCompound(); sphaleriteHeat.setInteger("minHeat", 1500); NBTTagCompound tetrahedriteHeat = new NBTTagCompound(); tetrahedriteHeat.setInteger("minHeat", 500); NBTTagCompound tungstenHeat = new NBTTagCompound(); tungstenHeat.setInteger("minHeat", 2000); NBTTagCompound galenaHeat = new NBTTagCompound(); galenaHeat.setInteger("minHeat", 2500); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedAluminum"), aluminumHeat, ItemDustTiny.getTinyDustByName("Bauxite", 1), ItemDusts.getDustByName("aluminum", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedArdite"), arditeHeat, ItemDustTiny.getTinyDustByName("Ardite", 1), ItemDusts.getDustByName("ardite", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedBauxite"), bauxiteHeat, ItemDustTiny.getTinyDustByName("Aluminum", 1), ItemDusts.getDustByName("bauxite", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedCadmium"), cadmiumHeat, ItemDustTiny.getTinyDustByName("Cadmium", 1), ItemDusts.getDustByName("cadmium", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedCinnabar"), cinnabarHeat, ItemDustTiny.getTinyDustByName("Redstone", 1), ItemDusts.getDustByName("cinnabar", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedCobalt"), cobaltHeat, ItemDustTiny.getTinyDustByName("Cobalt", 1), ItemDusts.getDustByName("cobalt", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedDarkIron"), darkIronHeat, ItemDustTiny.getTinyDustByName("Iron", 1), ItemDusts.getDustByName("darkIron", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedIndium"), indiumHeat, ItemDustTiny.getTinyDustByName("Indium", 1), ItemDusts.getDustByName("indium", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedIridium"), iridiumHeat, ItemDustTiny.getTinyDustByName("Platinum", 1), ItemDusts.getDustByName("iridium", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedNickel"), nickelHeat, ItemDustTiny.getTinyDustByName("Iron", 1), ItemDusts.getDustByName("nickel", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedOsmium"), osmiumHeat, ItemDustTiny.getTinyDustByName("Osmium", 1), ItemDusts.getDustByName("osmium", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPlatinum"), platinumHeat, ItemDustTiny.getTinyDustByName("Iridium", 1), ItemDusts.getDustByName("platinum", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPyrite"), pyriteHeat, ItemDustTiny.getTinyDustByName("Sulfur", 1), ItemDusts.getDustByName("pyrite", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedSphalerite"), sphaleriteHeat, ItemDustTiny.getTinyDustByName("Zinc", 1), ItemDusts.getDustByName("sphalerite", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedTetrahedrite"), tetrahedriteHeat, ItemDustTiny.getTinyDustByName("Antimony", 1), ItemDusts.getDustByName("tetrahedrite", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedTungsten"), tungstenHeat, ItemDustTiny.getTinyDustByName("Manganese", 1), ItemDusts.getDustByName("tungsten", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedGalena"), galenaHeat, ItemDustTiny.getTinyDustByName("Sulfur", 1), ItemDusts.getDustByName("galena", 1), IC2Items.getItem("stoneDust")); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedAluminum"), aluminumHeat, ItemDustTiny.getTinyDustByName("Bauxite", 1), ItemDusts.getDustByName("aluminum", 1)); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedArdite"), arditeHeat, ItemDustTiny.getTinyDustByName("Ardite", 1), ItemDusts.getDustByName("ardite", 1)); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedBauxite"), bauxiteHeat, ItemDustTiny.getTinyDustByName("Aluminum", 1), ItemDusts.getDustByName("bauxite", 1)); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedCadmium"), cadmiumHeat, ItemDustTiny.getTinyDustByName("Cadmium", 1), ItemDusts.getDustByName("cadmium", 1)); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedCinnabar"), cinnabarHeat, ItemDustTiny.getTinyDustByName("Redstone", 1), ItemDusts.getDustByName("cinnabar", 1)); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedCobalt"), cobaltHeat, ItemDustTiny.getTinyDustByName("Cobalt", 1), ItemDusts.getDustByName("cobalt", 1)); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedDarkIron"), darkIronHeat, ItemDustTiny.getTinyDustByName("Iron", 1), ItemDusts.getDustByName("darkIron", 1)); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedIndium"), indiumHeat, ItemDustTiny.getTinyDustByName("Indium", 1), ItemDusts.getDustByName("indium", 1)); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedIridium"), iridiumHeat, ItemDustTiny.getTinyDustByName("Platinum", 1), ItemDusts.getDustByName("iridium", 1)); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedNickel"), nickelHeat, ItemDustTiny.getTinyDustByName("Iron", 1), ItemDusts.getDustByName("nickel", 1)); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedOsmium"), osmiumHeat, ItemDustTiny.getTinyDustByName("Osmium", 1), ItemDusts.getDustByName("osmium", 1)); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedPlatinum"), platinumHeat, ItemDustTiny.getTinyDustByName("Iridium", 1), ItemDusts.getDustByName("platinum", 1)); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedPyrite"), pyriteHeat, ItemDustTiny.getTinyDustByName("Sulfur", 1), ItemDusts.getDustByName("pyrite", 1)); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedSphalerite"), sphaleriteHeat, ItemDustTiny.getTinyDustByName("Zinc", 1), ItemDusts.getDustByName("sphalerite", 1)); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedTetrahedrite"), tetrahedriteHeat, ItemDustTiny.getTinyDustByName("Antimony", 1), ItemDusts.getDustByName("tetrahedrite", 1)); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedTungsten"), tungstenHeat, ItemDustTiny.getTinyDustByName("Manganese", 1), ItemDusts.getDustByName("tungsten", 1)); Recipes.centrifuge.addRecipe(new RecipeInputOreDict("crushedPurifiedGalena"), galenaHeat, ItemDustTiny.getTinyDustByName("Sulfur", 1), ItemDusts.getDustByName("galena", 1)); } public static void addMetalFormerRecipes() { //Metal Former NBTTagCompound mode = new NBTTagCompound(); mode.setInteger("mode", 1); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotAluminum"), mode, ItemPlates.getPlateByName("aluminum")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotBatteryAlloy"), mode, ItemPlates.getPlateByName("batteryAlloy")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotBrass"), mode, ItemPlates.getPlateByName("brass")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotChrome"), mode, ItemPlates.getPlateByName("chrome")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotElectrum"), mode, ItemPlates.getPlateByName("electrum")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotInvar"), mode, ItemPlates.getPlateByName("invar")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotIridium"), mode, ItemPlates.getPlateByName("iridium")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotMagnalium"), mode, ItemPlates.getPlateByName("magnalium")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotNickel"), mode, ItemPlates.getPlateByName("nickel")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotOsmium"), mode, ItemPlates.getPlateByName("osmium")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotPlatinum"), mode, ItemPlates.getPlateByName("platinum")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotSilver"), mode, ItemPlates.getPlateByName("silver")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotTitanium"), mode, ItemPlates.getPlateByName("titanium")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotTungsten"), mode, ItemPlates.getPlateByName("tungsten")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotTungstensteel"), mode, ItemPlates.getPlateByName("tungstensteel")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotZinc"), mode, ItemPlates.getPlateByName("zinc")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotRedAlloy"), mode, ItemPlates.getPlateByName("redstone")); Recipes.metalformerRolling.addRecipe(new RecipeInputOreDict("ingotBlueAlloy"), mode, ItemPlates.getPlateByName("teslatite")); } public static void addAssemblingMachineRecipes() { //Ender Eye RecipeHanderer.addRecipe(new AssemblingMachineRecipe(new ItemStack(Items.ender_pearl, 1), new ItemStack(Items.blaze_powder), new ItemStack(Items.ender_eye), 120, 5)); RecipeHanderer.addRecipe(new AssemblingMachineRecipe(new ItemStack(Items.ender_pearl, 6), new ItemStack(Items.blaze_rod), new ItemStack(Items.ender_eye, 6), 120, 5)); //Redstone Lamp RecipeHanderer.addRecipe(new AssemblingMachineRecipe(new ItemStack(Items.redstone, 4), new ItemStack(Items.glowstone_dust, 4), new ItemStack(Blocks.redstone_lamp), 120, 5)); //Note Block RecipeHanderer.addRecipe(new AssemblingMachineRecipe(new ItemStack(Blocks.planks, 8), new ItemStack(Items.redstone, 1), new ItemStack(Blocks.noteblock), 120, 5)); //Jukebox RecipeHanderer.addRecipe(new AssemblingMachineRecipe(new ItemStack(Items.diamond, 1), new ItemStack(Blocks.planks, 8), new ItemStack(Blocks.jukebox), 120, 5)); //Clock RecipeHanderer.addRecipe(new AssemblingMachineRecipe(new ItemStack(Items.redstone, 1), new ItemStack(Items.gold_ingot, 4), new ItemStack(Items.clock), 120, 5)); //Compass RecipeHanderer.addRecipe(new AssemblingMachineRecipe(new ItemStack(Items.redstone, 1), new ItemStack(Items.iron_ingot, 4), new ItemStack(Items.clock), 120, 5)); //Lead RecipeHanderer.addRecipe(new AssemblingMachineRecipe(new ItemStack(Items.string, 1), new ItemStack(Items.slime_ball, 1), new ItemStack(Items.lead, 2), 120, 5)); //Circuit Parts RecipeHanderer.addRecipe(new AssemblingMachineRecipe(new ItemStack(Items.glowstone_dust), ItemDusts.getDustByName("lazurite", 1), ItemParts.getPartByName("advancedCircuitParts", 2), 120, 5)); RecipeHanderer.addRecipe(new AssemblingMachineRecipe(new ItemStack(Items.glowstone_dust), ItemDusts.getDustByName("lapis", 1), ItemParts.getPartByName("advancedCircuitParts", 2), 120, 5)); //Electronic Circuit RecipeHanderer.addRecipe(new AssemblingMachineRecipe(ItemParts.getPartByName("basicCircuitBoard", 1), new ItemStack(IC2Items.getItem("insulatedCopperCableItem").getItem(), 3), IC2Items.getItem("electronicCircuit"), 120, 5)); //Advanced Circuit RecipeHanderer.addRecipe(new AssemblingMachineRecipe(ItemParts.getPartByName("advancedCircuitBoard", 1), ItemParts.getPartByName("advancedCircuitParts", 2), IC2Items.getItem("advancedCircuit"), 120, 5)); //Energy Flow Circuit RecipeHanderer.addRecipe(new AssemblingMachineRecipe(ItemParts.getPartByName("processorCircuitBoard", 1), new ItemStack(IC2Items.getItem("lapotronCrystal").getItem(), 1, OreDictionary.WILDCARD_VALUE), new ItemStack(ModItems.parts, 1, 4), 120, 5)); //Data Control Circuit RecipeHanderer.addRecipe(new AssemblingMachineRecipe(ItemParts.getPartByName("processorCircuitBoard", 1), ItemParts.getPartByName("dataStorageCircuit", 1), ItemParts.getPartByName("dataControlCircuit", 1), 120, 5)); //Data Storage Circuit RecipeHanderer.addRecipe(new AssemblingMachineRecipe(ItemPlates.getPlateByName("emerald", 8), IC2Items.getItem("advancedCircuit"), ItemParts.getPartByName("dataStorageCircuit", 1), 120, 5)); RecipeHanderer.addRecipe(new AssemblingMachineRecipe(ItemPlates.getPlateByName("peridot", 8), IC2Items.getItem("advancedCircuit"), ItemParts.getPartByName("dataStorageCircuit", 1), 120, 5)); //Data Orb RecipeHanderer.addRecipe(new AssemblingMachineRecipe(ItemParts.getPartByName("dataControlCircuit", 1), ItemParts.getPartByName("dataStorageCircuit", 8), ItemParts.getPartByName("dataOrb"), 120, 5)); //Basic Circuit Board RecipeHanderer.addRecipe(new AssemblingMachineRecipe(ItemPlates.getPlateByName("aluminum", 1), ItemPlates.getPlateByName("electrum", 2), ItemParts.getPartByName("basicCircuitBoard", 2), 120, 5)); RecipeHanderer.addRecipe(new AssemblingMachineRecipe(ItemPlates.getPlateByName("iron", 1), ItemPlates.getPlateByName("electrum", 2), ItemParts.getPartByName("basicCircuitBoard", 2), 120, 5)); //Advanced Circuit Board RecipeHanderer.addRecipe(new AssemblingMachineRecipe(ItemPlates.getPlateByName("electrum", 2), IC2Items.getItem("electronicCircuit"), ItemParts.getPartByName("advancedCircuitBoard", 1), 120, 5)); RecipeHanderer.addRecipe(new AssemblingMachineRecipe(ItemPlates.getPlateByName("electrum", 4), ItemPlates.getPlateByName("silicon", 1), ItemParts.getPartByName("advancedCircuitBoard", 2), 120, 5)); //Processor Circuit Board RecipeHanderer.addRecipe(new AssemblingMachineRecipe(ItemPlates.getPlateByName("platinum", 1), IC2Items.getItem("advancedCircuit"), ItemParts.getPartByName("processorCircuitBoard", 1), 120, 5)); //Frequency Transmitter RecipeHanderer.addRecipe(new AssemblingMachineRecipe(IC2Items.getItem("electronicCircuit"), IC2Items.getItem("insulatedCopperCableItem"), IC2Items.getItem("frequencyTransmitter"), 120, 5)); //Wind Mill RecipeHanderer.addRecipe(new AssemblingMachineRecipe(ItemPlates.getPlateByName("magnalium", 2), IC2Items.getItem("generator"), IC2Items.getItem("windMill"), 120, 5)); RecipeHanderer.addRecipe(new AssemblingMachineRecipe(new ItemStack(IC2Items.getItem("carbonPlate").getItem(), 4), IC2Items.getItem("generator"), IC2Items.getItem("windMill"), 120, 5)); //Water Mill RecipeHanderer.addRecipe(new AssemblingMachineRecipe(ItemPlates.getPlateByName("aluminum", 4), IC2Items.getItem("generator"), IC2Items.getItem("waterMill"), 120, 5)); //Industrial TNT RecipeHanderer.addRecipe(new AssemblingMachineRecipe(ItemDusts.getDustByName("flint", 5), new ItemStack(Blocks.tnt), new ItemStack(IC2Items.getItem("industrialTnt").getItem(), 5), 120, 5)); } public static void addIndustrialCentrifugeRecipes() { //Plantball/Bio Chaff RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Blocks.grass, 16), null, new ItemStack(IC2Items.getItem("biochaff").getItem(), 8), new ItemStack(IC2Items.getItem("plantBall").getItem(), 8), new ItemStack(Items.clay_ball), new ItemStack(Blocks.sand, 8), 2500, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Blocks.dirt, 16), null, new ItemStack(IC2Items.getItem("biochaff").getItem(), 4), new ItemStack(IC2Items.getItem("plantBall").getItem(), 4), new ItemStack(Items.clay_ball), new ItemStack(Blocks.sand, 8), 2500, 5)); //Methane RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.mushroom_stew, 16), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.apple, 32), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.porkchop, 12), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.cooked_porkchop, 16), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.bread, 64), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.fish, 12), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.cooked_fished, 16), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.beef, 12), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.cooked_beef, 16), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Blocks.pumpkin, 16), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.speckled_melon, 1), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), new ItemStack(Items.gold_nugget, 6), null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.spider_eye, 32), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.chicken, 12), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.cooked_chicken, 16), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.rotten_flesh, 16), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.melon, 64), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.cookie, 64), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.cake, 8), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.golden_carrot, 1), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), new ItemStack(Items.gold_nugget, 6), null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.carrot, 16), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.baked_potato, 24), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.potato, 16), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.poisonous_potato, 12), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.nether_wart, 1), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(IC2Items.getItem("terraWart").getItem(), 16), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Blocks.brown_mushroom, 1), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Blocks.red_mushroom, 1), IC2Items.getItem("cell"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); //Rubber Wood Yields RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(IC2Items.getItem("rubberWood").getItem(), 15), new ItemStack(IC2Items.getItem("cell").getItem(), 5), new ItemStack(IC2Items.getItem("resin").getItem(), 8), new ItemStack(IC2Items.getItem("plantBall").getItem(), 6), ItemCells.getCellByName("methane", 1), ItemCells.getCellByName("carbon", 4), 5000, 5)); //Soul Sand Byproducts RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Blocks.soul_sand, 16), IC2Items.getItem("cell"), ItemCells.getCellByName("oil", 1), ItemDusts.getDustByName("saltpeter", 4), ItemDusts.getDustByName("coal", 1), new ItemStack(Blocks.sand, 10), 2500, 5)); //Mycelium Byproducts RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Blocks.mycelium, 8), null, new ItemStack(Blocks.brown_mushroom, 2), new ItemStack(Blocks.red_mushroom, 2), new ItemStack(Items.clay_ball, 1), new ItemStack(Blocks.sand, 4), 1640, 5)); //Ice RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemCells.getCellByName("ice", 1), null, new ItemStack(Blocks.ice, 1), IC2Items.getItem("cell"), null, null, 40, 5)); //Blaze Powder Byproducts RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.blaze_powder), null, ItemDusts.getDustByName("darkAshes", 1), ItemDusts.getDustByName("sulfur", 1), null, null, 1240, 5)); //Magma Cream Products RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.magma_cream, 1), null, new ItemStack(Items.blaze_powder, 1), new ItemStack(Items.slime_ball, 1), null, null, 2500, 5)); //Dust Byproducts RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("platinum", 1), null, ItemDustTiny.getTinyDustByName("Iridium", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), null, null, 3000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("electrum", 2), null, ItemDusts.getDustByName("silver", 1), ItemDusts.getDustByName("gold", 1), null, null, 2400, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("invar", 3), null, ItemDusts.getDustByName("iron", 2), ItemDusts.getDustByName("nickel", 1), null, null, 1340, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("marble", 8), null, ItemDusts.getDustByName("magnesium", 1), ItemDusts.getDustByName("calcite", 7), null, null, 1280, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("redrock", 4), null, ItemDusts.getDustByName("calcite", 2), ItemDusts.getDustByName("flint", 1), ItemDusts.getDustByName("clay", 1), null, 640, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("basalt", 16), null, ItemDusts.getDustByName("peridot", 1), ItemDusts.getDustByName("calcite", 3), ItemDusts.getDustByName("magnesium", 8), ItemDusts.getDustByName("darkAshes", 4), 2680, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.glowstone_dust, 16), IC2Items.getItem("cell"), new ItemStack(Items.redstone, 8), ItemDusts.getDustByName("gold", 8), ItemCells.getCellByName("helium", 1), null, 25000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("yellowGarnet", 16), null, ItemDusts.getDustByName("andradite", 5), ItemDusts.getDustByName("grossular", 8), ItemDusts.getDustByName("uvarovite", 3), null, 2940, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("redGarnet", 16), null, ItemDusts.getDustByName("pyrope", 3), ItemDusts.getDustByName("almandine", 5), ItemDusts.getDustByName("spessartine", 8), null, 2940, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("phosphorous", 5), new ItemStack(IC2Items.getItem("cell").getItem(), 3), ItemCells.getCellByName("calcium", 3), null, null, null, 1280, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("darkAshes", 2), null, ItemDusts.getDustByName("ashes", 2), null, null, null, 240, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("ashes", 1), IC2Items.getItem("cell"), ItemCells.getCellByName("carbon"), null, null, null, 80, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(new ItemStack(Items.redstone, 10), new ItemStack(IC2Items.getItem("cell").getItem(), 4), ItemCells.getCellByName("silicon", 1), ItemDusts.getDustByName("pyrite", 3), ItemDusts.getDustByName("ruby", 1), ItemCells.getCellByName("mercury", 3), 6800, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("manyullyn", 2), null, ItemDusts.getDustByName("cobalt", 1), ItemDusts.getDustByName("ardite", 1), null, null, 1240, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("nichrome", 5), null, ItemDusts.getDustByName("nickel", 4), ItemDusts.getDustByName("chrome", 1), null, null, 2240, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("cupronickel", 2), null, ItemDusts.getDustByName("copper", 1), ItemDusts.getDustByName("nickel", 1), null, null, 960, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("kanthal", 3), null, ItemDusts.getDustByName("iron", 1), ItemDusts.getDustByName("aluminum", 1), ItemDusts.getDustByName("chrome", 1), null, 1040, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("endstone", 16), new ItemStack(IC2Items.getItem("cell").getItem(), 2), ItemCells.getCellByName("helium3", 1), ItemCells.getCellByName("helium"), ItemDustTiny.getTinyDustByName("Tungsten", 1), new ItemStack(Blocks.sand, 12), 4800, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("cinnabar", 2), IC2Items.getItem("cell"), ItemCells.getCellByName("mercury", 1), ItemDusts.getDustByName("sulfur", 1), null, null, 80, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("brass", 4), null, ItemDusts.getDustByName("zinc", 1), ItemDusts.getDustByName("copper", 3), null, null, 2000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("aluminumBrass", 4), null, ItemDusts.getDustByName("aluminum", 1), ItemDusts.getDustByName("copper", 3), null, null, 2000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("bronze", 4), null, ItemDusts.getDustByName("tin", 1), ItemDusts.getDustByName("copper", 3), null, null, 2420, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("flint", 1), null, IC2Items.getItem("silicondioxideDust"), null, null, null, 160, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("netherrack", 16), null, new ItemStack(Items.redstone, 1), ItemDusts.getDustByName("sulfur", 4), ItemDusts.getDustByName("basalt", 1), new ItemStack(Items.gold_nugget, 1), 2400, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("enderEye", 1), null, ItemDusts.getDustByName("enderPearl", 1), new ItemStack(Items.blaze_powder, 1), null, null, 1280, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("tetrahedrite", 8), null, ItemDusts.getDustByName("copper", 3), ItemDusts.getDustByName("antimony", 1), ItemDusts.getDustByName("sulfur", 3), ItemDusts.getDustByName("iron", 1), 3640, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("lapis", 16), null, ItemDusts.getDustByName("lazurite", 12), ItemDusts.getDustByName("sodalite", 2), ItemDusts.getDustByName("pyrite", 7), ItemDusts.getDustByName("calcite", 1), 3580, 5)); //Deuterium/Tritium RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemCells.getCellByName("helium", 16), null, ItemCells.getCellByName("deuterium", 1), new ItemStack(IC2Items.getItem("cell").getItem(), 15), null, null, 10000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemCells.getCellByName("deuterium", 4), null, ItemCells.getCellByName("tritium", 1), new ItemStack(IC2Items.getItem("cell").getItem(), 3), null, null, 3000, 5)); RecipeHanderer.addRecipe(new CentrifugeRecipe(ItemCells.getCellByName("hydrogen", 4), null, ItemCells.getCellByName("deuterium", 1), new ItemStack(IC2Items.getItem("cell").getItem(), 3), null, null, 3000, 5)); //Lava Cell Byproducts ItemStack lavaCells = IC2Items.getItem("lavaCell"); lavaCells.stackSize = 8; RecipeHanderer.addRecipe(new CentrifugeRecipe(lavaCells, null, ItemNuggets.getNuggetByName("electrum", 4), ItemIngots.getIngotByName("copper", 2), ItemDustTiny.getTinyDustByName("Tungsten", 1), ItemIngots.getIngotByName("tin", 17), 6000, 5)); } public static void addIndustrialGrinderRecipes() { //Coal Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.coal_ore, 1), null, new FluidStack(FluidRegistry.WATER, 1000), new ItemStack(Items.coal, 1), ItemDustsSmall.getSmallDustByName("Coal", 6), ItemDustsSmall.getSmallDustByName("Coal", 2), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.coal_ore, 1), IC2Items.getItem("waterCell"), null, new ItemStack(Items.coal, 1), ItemDustsSmall.getSmallDustByName("Coal", 6), ItemDustsSmall.getSmallDustByName("Coal", 2), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.coal_ore, 1), new ItemStack(Items.water_bucket), null, new ItemStack(Items.coal, 1), ItemDustsSmall.getSmallDustByName("Coal", 6), ItemDustsSmall.getSmallDustByName("Coal", 2), new ItemStack(Items.bucket), 100, 120)); //Iron Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.iron_ore, 1), null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("iron", 2), ItemDustsSmall.getSmallDustByName("Nickel", 1), ItemDustsSmall.getSmallDustByName("Tin", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.iron_ore, 1), IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("iron", 2), ItemDustsSmall.getSmallDustByName("Nickel", 1), ItemDustsSmall.getSmallDustByName("Tin", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.iron_ore, 1), new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("iron", 2), ItemDustsSmall.getSmallDustByName("Nickel", 1), ItemDustsSmall.getSmallDustByName("Tin", 1), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.iron_ore, 1), null, new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("iron", 2), ItemDusts.getDustByName("nickel", 1), ItemDustsSmall.getSmallDustByName("Tin", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.iron_ore, 1), ItemCells.getCellByName("sodiumPersulfate", 1), null, ItemDusts.getDustByName("iron", 2), ItemDusts.getDustByName("nickel", 1), ItemDustsSmall.getSmallDustByName("Tin", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.iron_ore, 1), new ItemStack(ModItems.bucketSodiumpersulfate), null, ItemDusts.getDustByName("iron", 2), ItemDusts.getDustByName("nickel", 1), ItemDustsSmall.getSmallDustByName("Tin", 1), new ItemStack(Items.bucket), 100, 120)); //Gold Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.gold_ore, 1), null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("gold", 2), ItemDustsSmall.getSmallDustByName("Copper", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.gold_ore, 1), IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("gold", 2), ItemDustsSmall.getSmallDustByName("Copper", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.gold_ore, 1), new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("gold", 2), ItemDustsSmall.getSmallDustByName("Copper", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.gold_ore, 1), null, new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("gold", 2), ItemDusts.getDustByName("copper", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.gold_ore, 1), ItemCells.getCellByName("sodiumPersulfate", 1), null, ItemDusts.getDustByName("gold", 2), ItemDusts.getDustByName("copper", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.gold_ore, 1), new ItemStack(ModItems.bucketSodiumpersulfate), null, ItemDusts.getDustByName("gold", 2), ItemDusts.getDustByName("copper", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.gold_ore, 1), null, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("gold", 3), ItemDustsSmall.getSmallDustByName("Copper", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.gold_ore, 1), ItemCells.getCellByName("mercury", 1), null, ItemDusts.getDustByName("gold", 3), ItemDustsSmall.getSmallDustByName("Copper", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.gold_ore, 1), new ItemStack(ModItems.bucketMercury), null, ItemDusts.getDustByName("gold", 3), ItemDustsSmall.getSmallDustByName("Copper", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), new ItemStack(Items.bucket), 100, 120)); //Diamond Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.diamond_ore, 1), null, new FluidStack(FluidRegistry.WATER, 1000), new ItemStack(Items.diamond, 1), ItemDustsSmall.getSmallDustByName("Diamond", 6), ItemDustsSmall.getSmallDustByName("Coal", 2), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.diamond_ore, 1), IC2Items.getItem("waterCell"), null, new ItemStack(Items.diamond, 1), ItemDustsSmall.getSmallDustByName("Diamond", 6), ItemDustsSmall.getSmallDustByName("Coal", 2), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.diamond_ore, 1), new ItemStack(Items.water_bucket), null, new ItemStack(Items.diamond, 1), ItemDustsSmall.getSmallDustByName("Diamond", 6), ItemDustsSmall.getSmallDustByName("Coal", 2), new ItemStack(Items.bucket), 100, 120)); //Emerald Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.emerald_ore, 1), null, new FluidStack(FluidRegistry.WATER, 1000), new ItemStack(Items.emerald, 1), ItemDustsSmall.getSmallDustByName("Emerald", 6), ItemDustsSmall.getSmallDustByName("Aluminum", 2), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.emerald_ore, 1), IC2Items.getItem("waterCell"), null, new ItemStack(Items.emerald, 1), ItemDustsSmall.getSmallDustByName("Emerald", 6), ItemDustsSmall.getSmallDustByName("Aluminum", 2), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.emerald_ore, 1), new ItemStack(Items.water_bucket), null, new ItemStack(Items.emerald, 1), ItemDustsSmall.getSmallDustByName("Emerald", 6), ItemDustsSmall.getSmallDustByName("Aluminum", 2), new ItemStack(Items.bucket), 100, 120)); //Redstone RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.redstone_ore, 1), null, new FluidStack(FluidRegistry.WATER, 1000), new ItemStack(Items.redstone, 10), ItemDustsSmall.getSmallDustByName("Cinnabar", 1), ItemDustsSmall.getSmallDustByName("Glowstone", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.redstone_ore, 1), IC2Items.getItem("waterCell"), null, new ItemStack(Items.redstone, 10), ItemDustsSmall.getSmallDustByName("Cinnabar", 1), ItemDustsSmall.getSmallDustByName("Glowstone", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.redstone_ore, 1), new ItemStack(Items.water_bucket), null, new ItemStack(Items.redstone, 10), ItemDustsSmall.getSmallDustByName("Cinnabar", 1), ItemDustsSmall.getSmallDustByName("Glowstone", 1), new ItemStack(Items.bucket), 100, 120)); //Lapis Lazuli Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.lapis_ore, 1), null, new FluidStack(FluidRegistry.WATER, 1000), new ItemStack(Items.dye, 6, 4), ItemDustsSmall.getSmallDustByName("Lapis", 36), ItemDustsSmall.getSmallDustByName("Lazurite", 8), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.lapis_ore, 1), IC2Items.getItem("waterCell"), null, new ItemStack(Items.dye, 6, 4), ItemDustsSmall.getSmallDustByName("Lapis", 36), ItemDustsSmall.getSmallDustByName("Lazurite", 8), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.lapis_ore, 1), new ItemStack(Items.water_bucket), null, new ItemStack(Items.dye, 6 , 4), ItemDustsSmall.getSmallDustByName("Lapis", 36), ItemDustsSmall.getSmallDustByName("Lazurite", 8), new ItemStack(Items.bucket), 100, 120)); //Copper Ore if(OreDictionary.doesOreNameExist("oreCopper")) { try { ItemStack oreStack = OreDictionary.getOres("oreCopper").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("copper", 2), ItemDustsSmall.getSmallDustByName("Gold", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("copper", 2), ItemDustsSmall.getSmallDustByName("Gold", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("copper", 2), ItemDustsSmall.getSmallDustByName("Gold", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("copper", 2), ItemDusts.getDustByName("gold", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, ItemCells.getCellByName("sodiumPersulfate", 1), null, ItemDusts.getDustByName("copper", 2), ItemDusts.getDustByName("gold", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(ModItems.bucketSodiumpersulfate), null, ItemDusts.getDustByName("copper", 2), ItemDusts.getDustByName("gold", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("copper", 2), ItemDustsSmall.getSmallDustByName("Gold", 1), ItemDusts.getDustByName("nickel", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, ItemCells.getCellByName("mercury", 1), null, ItemDusts.getDustByName("copper", 2), ItemDustsSmall.getSmallDustByName("Gold", 1), ItemDusts.getDustByName("nickel", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, ItemCells.getCellByName("mercury", 1), null, ItemDusts.getDustByName("copper", 2), ItemDustsSmall.getSmallDustByName("Gold", 1), ItemDusts.getDustByName("nickel", 1), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Copper Ore"); } } //Tin Ore if(OreDictionary.doesOreNameExist("oreTin")) { try { ItemStack oreStack = OreDictionary.getOres("oreTin").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("tin", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Zinc", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("tin", 2), ItemDustsSmall.getSmallDustByName("Iron", 1),ItemDustsSmall.getSmallDustByName("Zinc", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("tin", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Zinc", 1), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("tin", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDusts.getDustByName("zinc", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, ItemCells.getCellByName("sodiumPersulfate", 1), null, ItemDusts.getDustByName("tin", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDusts.getDustByName("zinc", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(ModItems.bucketSodiumpersulfate), null, ItemDusts.getDustByName("tin", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDusts.getDustByName("zinc", 1), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Tin Ore"); } } //Nickel Ore if(OreDictionary.doesOreNameExist("oreNickel")) { try { ItemStack oreStack = OreDictionary.getOres("oreNickel").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("nickel", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Platinum", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("nickel", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Platinum", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("nickel", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Platinum", 1), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("nickel", 3), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Platinum", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, ItemCells.getCellByName("sodiumPersulfate", 1), null, ItemDusts.getDustByName("nickel", 3), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Platinum", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(ModItems.bucketSodiumpersulfate), null, ItemDusts.getDustByName("nickel", 3), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Platinum", 1), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("nickel", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDusts.getDustByName("platinum", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, ItemCells.getCellByName("mercury", 1), null, ItemDusts.getDustByName("nickel", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDusts.getDustByName("platinum", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(ModItems.bucketMercury), null, ItemDusts.getDustByName("nickel", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDusts.getDustByName("platinum", 1), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Nickel Ore"); } } //Zinc Ore if(OreDictionary.doesOreNameExist("oreZinc")) { try { ItemStack oreStack = OreDictionary.getOres("oreZinc").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("zinc", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Tin", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("zinc", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Tin", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("zinc", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Tin", 1), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("zinc", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDusts.getDustByName("iron", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, ItemCells.getCellByName("sodiumPersulfate", 1), null, ItemDusts.getDustByName("zinc", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDusts.getDustByName("iron", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(ModItems.bucketSodiumpersulfate), null, ItemDusts.getDustByName("zinc", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDusts.getDustByName("iron", 1), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Zinc Ore"); } } //Silver Ore if(OreDictionary.doesOreNameExist("oreSilver")) { try { ItemStack oreStack = OreDictionary.getOres("oreSilver").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("silver", 2), ItemDustsSmall.getSmallDustByName("Lead", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("silver", 2), ItemDustsSmall.getSmallDustByName("Lead", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("silver", 2), ItemDustsSmall.getSmallDustByName("Lead", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("silver", 3), ItemDustsSmall.getSmallDustByName("Lead", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, ItemCells.getCellByName("mercury", 1), null, ItemDusts.getDustByName("silver", 3), ItemDustsSmall.getSmallDustByName("Lead", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(ModItems.bucketMercury), null, ItemDusts.getDustByName("silver", 3), ItemDustsSmall.getSmallDustByName("Lead", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Silver Ore"); } } //Lead Ore if(OreDictionary.doesOreNameExist("oreLead")) { try { ItemStack oreStack = OreDictionary.getOres("oreLead").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("lead", 2), ItemDustsSmall.getSmallDustByName("Silver", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("lead", 2), ItemDustsSmall.getSmallDustByName("Silver", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("lead", 2), ItemDustsSmall.getSmallDustByName("Silver", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("lead", 2), ItemDusts.getDustByName("silver", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, ItemCells.getCellByName("mercury", 1), null, ItemDusts.getDustByName("lead", 2), ItemDusts.getDustByName("silver", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(ModItems.bucketMercury), null, ItemDusts.getDustByName("lead", 2), ItemDusts.getDustByName("silver", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Lead Ore"); } } //Uranium Ore if(OreDictionary.doesOreNameExist("oreUranium")) { try { ItemStack oreStack = OreDictionary.getOres("oreUranium").get(0); ItemStack uranium238Stack = IC2Items.getItem("Uran238"); uranium238Stack.stackSize = 8; ItemStack uranium235Stack = IC2Items.getItem("smallUran235"); uranium235Stack.stackSize = 2; RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), uranium238Stack, uranium235Stack, null, null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, uranium238Stack, uranium235Stack, null, IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, uranium238Stack, uranium235Stack, null, new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Uranium Ore"); } } //Pitchblende Ore if(OreDictionary.doesOreNameExist("orePitchblende")) { try { ItemStack oreStack = OreDictionary.getOres("orePitchblende").get(0); ItemStack uranium238Stack = IC2Items.getItem("Uran238"); uranium238Stack.stackSize = 8; ItemStack uranium235Stack = IC2Items.getItem("smallUran235"); uranium235Stack.stackSize = 2; RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), uranium238Stack, uranium235Stack, null, null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, uranium238Stack, uranium235Stack, null, IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, uranium238Stack, uranium235Stack, null, new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Uranium Ore"); } } //Aluminum Ore if(OreDictionary.doesOreNameExist("oreAluminum")) { try { ItemStack oreStack = OreDictionary.getOres("oreAluminum").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("aluminum", 2), ItemDustsSmall.getSmallDustByName("Bauxite", 1), ItemDustsSmall.getSmallDustByName("Bauxite", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("aluminum", 2), ItemDustsSmall.getSmallDustByName("Bauxite", 1), ItemDustsSmall.getSmallDustByName("Bauxite", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("aluminum", 2), ItemDustsSmall.getSmallDustByName("Bauxite", 1), ItemDustsSmall.getSmallDustByName("Bauxite", 1), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Lead Ore"); } } //Ardite Ore if(OreDictionary.doesOreNameExist("oreArdite")) { try { ItemStack oreStack = OreDictionary.getOres("oreArdite").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("ardite", 2), ItemDustsSmall.getSmallDustByName("Ardite", 1), ItemDustsSmall.getSmallDustByName("Ardite", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("ardite", 2), ItemDustsSmall.getSmallDustByName("Ardite", 1), ItemDustsSmall.getSmallDustByName("Ardite", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("ardite", 2), ItemDustsSmall.getSmallDustByName("Ardite", 1), ItemDustsSmall.getSmallDustByName("Ardite", 1), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Ardite Ore"); } } //Cobalt Ore if(OreDictionary.doesOreNameExist("oreCobalt")) { try { ItemStack oreStack = OreDictionary.getOres("oreCobalt").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("cobalt", 2), ItemDustsSmall.getSmallDustByName("Cobalt", 1), ItemDustsSmall.getSmallDustByName("Cobalt", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("cobalt", 2), ItemDustsSmall.getSmallDustByName("Cobalt", 1), ItemDustsSmall.getSmallDustByName("Cobalt", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("cobalt", 2), ItemDustsSmall.getSmallDustByName("Cobalt", 1), ItemDustsSmall.getSmallDustByName("Cobalt", 1), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Cobalt Ore"); } } //Dark Iron Ore if(OreDictionary.doesOreNameExist("oreDarkIron")) { try { ItemStack oreStack = OreDictionary.getOres("oreDarkIron").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("darkIron", 2), ItemDustsSmall.getSmallDustByName("DarkIron", 1), ItemDustsSmall.getSmallDustByName("Iron", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("darkIron", 2), ItemDustsSmall.getSmallDustByName("DarkIron", 1), ItemDustsSmall.getSmallDustByName("Iron", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("darkIron", 2), ItemDustsSmall.getSmallDustByName("DarkIron", 1), ItemDustsSmall.getSmallDustByName("Iron", 1), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Dark Iron Ore"); } } //Cadmium Ore if(OreDictionary.doesOreNameExist("oreCadmium")) { try { ItemStack oreStack = OreDictionary.getOres("oreCadmium").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("cadmium", 2), ItemDustsSmall.getSmallDustByName("Cadmium", 1), ItemDustsSmall.getSmallDustByName("Cadmium", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("cadmium", 2), ItemDustsSmall.getSmallDustByName("Cadmium", 1), ItemDustsSmall.getSmallDustByName("Cadmium", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("cadmium", 2), ItemDustsSmall.getSmallDustByName("Cadmium", 1), ItemDustsSmall.getSmallDustByName("Cadmium", 1), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Cadmium Ore"); } } //Indium Ore if(OreDictionary.doesOreNameExist("oreIndium")) { try { ItemStack oreStack = OreDictionary.getOres("oreIndium").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("indium", 2), ItemDustsSmall.getSmallDustByName("Indium", 1), ItemDustsSmall.getSmallDustByName("Indium", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("indium", 2), ItemDustsSmall.getSmallDustByName("Indium", 1), ItemDustsSmall.getSmallDustByName("Indium", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("indium", 2), ItemDustsSmall.getSmallDustByName("Indium", 1), ItemDustsSmall.getSmallDustByName("Indium", 1), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Indium Ore"); } } //Calcite Ore if(OreDictionary.doesOreNameExist("oreCalcite") && OreDictionary.doesOreNameExist("gemCalcite")) { try { ItemStack oreStack = OreDictionary.getOres("oreCalcite").get(0); ItemStack gemStack = OreDictionary.getOres("gemCalcite").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), gemStack, ItemDustsSmall.getSmallDustByName("Calcite", 6), null, null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, gemStack, ItemDustsSmall.getSmallDustByName("Calcite", 6), null, IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, gemStack, ItemDustsSmall.getSmallDustByName("Calcite", 6), null, new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Calcite Ore"); } } //Magnetite Ore if(OreDictionary.doesOreNameExist("oreMagnetite") && OreDictionary.doesOreNameExist("chunkMagnetite")) { try { ItemStack oreStack = OreDictionary.getOres("oreMagnetite").get(0); ItemStack chunkStack = OreDictionary.getOres("chunkMagnetite").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), chunkStack, ItemDustsSmall.getSmallDustByName("Magnetite", 6), null, null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, chunkStack, ItemDustsSmall.getSmallDustByName("Magnetite", 6), null, IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, chunkStack, ItemDustsSmall.getSmallDustByName("Magnetite", 6), null, new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Magnetite Ore"); } } //Graphite Ore if(OreDictionary.doesOreNameExist("oreGraphite") && OreDictionary.doesOreNameExist("chunkGraphite")) { try { ItemStack oreStack = OreDictionary.getOres("oreGraphite").get(0); ItemStack chunkStack = OreDictionary.getOres("chunkGraphite").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), chunkStack, ItemDustsSmall.getSmallDustByName("Graphite", 6), null, null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, chunkStack, ItemDustsSmall.getSmallDustByName("Graphite", 6), null, IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, chunkStack, ItemDustsSmall.getSmallDustByName("Graphite", 6), null, new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Graphite Ore"); } } //Osmium Ore if(OreDictionary.doesOreNameExist("oreOsmium")) { try { ItemStack oreStack = OreDictionary.getOres("oreOsmium").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("osmium", 2), ItemDustsSmall.getSmallDustByName("Osmium", 1), ItemDustsSmall.getSmallDustByName("Osmium", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("osmium", 2), ItemDustsSmall.getSmallDustByName("Osmium", 1), ItemDustsSmall.getSmallDustByName("Osmium", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("osmium", 2), ItemDustsSmall.getSmallDustByName("Osmium", 1), ItemDustsSmall.getSmallDustByName("Osmium", 1), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Osmium Ore"); } } //Teslatite Ore if(OreDictionary.doesOreNameExist("oreTeslatite") && OreDictionary.doesOreNameExist("dustTeslatite")) { try { ItemStack oreStack = OreDictionary.getOres("oreTeslatite").get(0); ItemStack dustStack = OreDictionary.getOres("dustTeslatite").get(0); dustStack.stackSize = 10; RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), dustStack, ItemDustsSmall.getSmallDustByName("Sodalite", 1), ItemDustsSmall.getSmallDustByName("Glowstone", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, dustStack, ItemDustsSmall.getSmallDustByName("Sodalite", 1), ItemDustsSmall.getSmallDustByName("Glowstone", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, dustStack, ItemDustsSmall.getSmallDustByName("Sodalite", 1), ItemDustsSmall.getSmallDustByName("Glowstone", 1), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Teslatite Ore"); } } //Sulfur Ore if(OreDictionary.doesOreNameExist("oreSulfur")) { try { ItemStack oreStack = OreDictionary.getOres("oreSulfur").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("sulfur", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("sulfur", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("sulfur", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Sulfur Ore"); } } //Saltpeter Ore if(OreDictionary.doesOreNameExist("oreSaltpeter")) { try { ItemStack oreStack = OreDictionary.getOres("oreSaltpeter").get(0); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("saltpeter", 2), ItemDustsSmall.getSmallDustByName("Saltpeter", 1), ItemDustsSmall.getSmallDustByName("Saltpeter", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("saltpeter", 2), ItemDustsSmall.getSmallDustByName("Saltpeter", 1), ItemDustsSmall.getSmallDustByName("Saltpeter", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("saltpeter", 2), ItemDustsSmall.getSmallDustByName("Saltpeter", 1), ItemDustsSmall.getSmallDustByName("Saltpeter", 1), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Saltpeter Ore"); } } //Apatite Ore if(OreDictionary.doesOreNameExist("oreApatite") & OreDictionary.doesOreNameExist("gemApatite")) { try { ItemStack oreStack = OreDictionary.getOres("oreApatite").get(0); ItemStack gemStack = OreDictionary.getOres("gemApatite").get(0); gemStack.stackSize = 6; RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), gemStack, gemStack, ItemDustsSmall.getSmallDustByName("Phosphorous", 4), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, gemStack, gemStack, ItemDustsSmall.getSmallDustByName("Phosphorous", 4), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, gemStack, gemStack, ItemDustsSmall.getSmallDustByName("Phosphorous", 4), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Apatite Ore"); } } //Nether Quartz Ore if(OreDictionary.doesOreNameExist("dustNetherQuartz")) { try { ItemStack dustStack = OreDictionary.getOres("dustNetherQuartz").get(0); dustStack.stackSize = 4; RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.quartz_ore, 1), null, new FluidStack(FluidRegistry.WATER, 1000), new ItemStack(Items.quartz, 2), dustStack, ItemDustsSmall.getSmallDustByName("Netherrack", 2), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.quartz_ore, 1), IC2Items.getItem("waterCell"), null, new ItemStack(Items.quartz, 2), dustStack, ItemDustsSmall.getSmallDustByName("Netherrack", 2), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(Blocks.quartz_ore, 1), new ItemStack(Items.water_bucket), null, new ItemStack(Items.quartz, 2), dustStack, ItemDustsSmall.getSmallDustByName("Netherrack", 2), new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Nether Quartz Ore"); } } //Certus Quartz Ore if(OreDictionary.doesOreNameExist("oreCertusQuartz")) { try { ItemStack oreStack = OreDictionary.getOres("oreCertusQuartz").get(0); ItemStack gemStack = OreDictionary.getOres("crystalCertusQuartz").get(0); ItemStack dustStack = OreDictionary.getOres("dustCertusQuartz").get(0); dustStack.stackSize = 2; RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, gemStack, dustStack, null, IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, gemStack, dustStack, null, new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Certus Quartz Ore"); } } //Charged Certus Quartz Ore if(OreDictionary.doesOreNameExist("oreChargedCertusQuartz")) { try { ItemStack oreStack = OreDictionary.getOres("oreChargedCertusQuartz").get(0); ItemStack gemStack = OreDictionary.getOres("crystalChargedCertusQuartz").get(0); ItemStack dustStack = OreDictionary.getOres("dustCertusQuartz").get(0); dustStack.stackSize = 2; RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, gemStack, dustStack, null, IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, gemStack, dustStack, null, new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Charged Certus Quartz Ore"); } } //Amethyst Ore if(OreDictionary.doesOreNameExist("oreAmethyst") && OreDictionary.doesOreNameExist("gemAmethyst")) { try { ItemStack oreStack = OreDictionary.getOres("oreAmethyst").get(0); ItemStack gemStack = OreDictionary.getOres("gemAmethyst").get(0); gemStack.stackSize = 2; ItemStack dustStack = OreDictionary.getOres("gemAmethyst").get(0); dustStack.stackSize = 1; RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, gemStack, dustStack, null, IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, gemStack, dustStack, null, new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Certus Quartz Ore"); } } //Topaz Ore if(OreDictionary.doesOreNameExist("oreTopaz") && OreDictionary.doesOreNameExist("gemTopaz")) { try { ItemStack oreStack = OreDictionary.getOres("oreTopaz").get(0); ItemStack gemStack = OreDictionary.getOres("gemTopaz").get(0); gemStack.stackSize = 2; ItemStack dustStack = OreDictionary.getOres("gemTopaz").get(0); dustStack.stackSize = 1; RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, gemStack, dustStack, null, IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, gemStack, dustStack, null, new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Topaz Ore"); } } //Tanzanite Ore if(OreDictionary.doesOreNameExist("oreTanzanite") && OreDictionary.doesOreNameExist("gemTanzanite")) { try { ItemStack oreStack = OreDictionary.getOres("oreTanzanite").get(0); ItemStack gemStack = OreDictionary.getOres("gemTanzanite").get(0); gemStack.stackSize = 2; ItemStack dustStack = OreDictionary.getOres("gemTanzanite").get(0); dustStack.stackSize = 1; RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, gemStack, dustStack, null, IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, gemStack, dustStack, null, new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Tanzanite Ore"); } } //Malachite Ore if(OreDictionary.doesOreNameExist("oreMalachite") && OreDictionary.doesOreNameExist("gemMalachite")) { try { ItemStack oreStack = OreDictionary.getOres("oreMalachite").get(0); ItemStack gemStack = OreDictionary.getOres("gemMalachite").get(0); gemStack.stackSize = 2; ItemStack dustStack = OreDictionary.getOres("gemMalachite").get(0); dustStack.stackSize = 1; RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, null, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, IC2Items.getItem("waterCell"), null, gemStack, dustStack, null, IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(oreStack, new ItemStack(Items.water_bucket), null, gemStack, dustStack, null, new ItemStack(Items.bucket), 100, 120)); } catch (Exception e) { LogHelper.info("Failed to Load Grinder Recipe for Malachite Ore"); } } //Galena Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 0), null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("galena", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDustsSmall.getSmallDustByName("Silver", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 0), IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("galena", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDustsSmall.getSmallDustByName("Silver", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 0), new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("galena", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDustsSmall.getSmallDustByName("Silver", 1), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 0), null, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("galena", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDusts.getDustByName("silver", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 0), ItemCells.getCellByName("mercury", 1), null, ItemDusts.getDustByName("galena", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDusts.getDustByName("silver", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 0), new ItemStack(ModItems.bucketMercury), null, ItemDusts.getDustByName("galena", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDusts.getDustByName("silver", 1), new ItemStack(Items.bucket), 100, 120)); //Iridium Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 1), null, new FluidStack(FluidRegistry.WATER, 1000), IC2Items.getItem("iridiumOre"), ItemDustsSmall.getSmallDustByName("Iridium", 6), ItemDustsSmall.getSmallDustByName("Platinum", 2), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 1), IC2Items.getItem("waterCell"), null, IC2Items.getItem("iridiumOre"), ItemDustsSmall.getSmallDustByName("Iridium", 6), ItemDustsSmall.getSmallDustByName("Platinum", 2), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 1), new ItemStack(Items.water_bucket), null, IC2Items.getItem("iridiumOre"), ItemDustsSmall.getSmallDustByName("Iridium", 6), ItemDustsSmall.getSmallDustByName("Platinum", 2), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 1), null, new FluidStack(ModFluids.fluidMercury, 1000), IC2Items.getItem("iridiumOre"), ItemDustsSmall.getSmallDustByName("Iridium", 6), ItemDusts.getDustByName("platinum", 2), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 1), ItemCells.getCellByName("mercury", 1), null, IC2Items.getItem("iridiumOre"), ItemDustsSmall.getSmallDustByName("Iridium", 6), ItemDusts.getDustByName("platinum", 2), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 1), new ItemStack(ModItems.bucketMercury), null, IC2Items.getItem("iridiumOre"), ItemDustsSmall.getSmallDustByName("Iridium", 6), ItemDusts.getDustByName("platinum", 2), new ItemStack(Items.bucket), 100, 120)); //Ruby Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 2), null, new FluidStack(FluidRegistry.WATER, 1000), ItemGems.getGemByName("ruby", 1), ItemDustsSmall.getSmallDustByName("Ruby", 6), ItemDustsSmall.getSmallDustByName("Chrome", 2), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 2), IC2Items.getItem("waterCell"), null, ItemGems.getGemByName("ruby", 1), ItemDustsSmall.getSmallDustByName("Ruby", 6), ItemDustsSmall.getSmallDustByName("Chrome", 2), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 2), new ItemStack(Items.water_bucket), null, ItemGems.getGemByName("ruby", 1), ItemDustsSmall.getSmallDustByName("Ruby", 6), ItemDustsSmall.getSmallDustByName("Chrome", 2), new ItemStack(Items.bucket), 100, 120)); //Sapphire Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 3), null, new FluidStack(FluidRegistry.WATER, 1000), ItemGems.getGemByName("sapphire", 1), ItemDustsSmall.getSmallDustByName("Sapphire", 6), ItemDustsSmall.getSmallDustByName("Aluminum", 2), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 3), IC2Items.getItem("waterCell"), null, ItemGems.getGemByName("sapphire", 1), ItemDustsSmall.getSmallDustByName("Sapphire", 6), ItemDustsSmall.getSmallDustByName("Aluminum", 2), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 3), new ItemStack(Items.water_bucket), null, ItemGems.getGemByName("sapphire", 1), ItemDustsSmall.getSmallDustByName("Sapphire", 6), ItemDustsSmall.getSmallDustByName("Aluminum", 2), new ItemStack(Items.bucket), 100, 120)); //Bauxite Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 4), null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("bauxite", 2), ItemDustsSmall.getSmallDustByName("Grossular", 4), ItemDustsSmall.getSmallDustByName("Titanium", 4), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 4), IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("bauxite", 2), ItemDustsSmall.getSmallDustByName("Grossular", 4), ItemDustsSmall.getSmallDustByName("Titanium", 4), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 4), new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("bauxite", 2), ItemDustsSmall.getSmallDustByName("Grossular", 4), ItemDustsSmall.getSmallDustByName("Titanium", 4), new ItemStack(Items.bucket), 100, 120)); //Pyrite Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 5), null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("pyrite", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDustsSmall.getSmallDustByName("Phosphorous", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 5), IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("pyrite", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDustsSmall.getSmallDustByName("Phosphorous", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 5), new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("pyrite", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDustsSmall.getSmallDustByName("Phosphorous", 1), new ItemStack(Items.bucket), 100, 120)); //Cinnabar Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 6), null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("cinnabar", 2), ItemDustsSmall.getSmallDustByName("Redstone", 1), ItemDustsSmall.getSmallDustByName("Glowstone", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 6), IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("cinnabar", 2), ItemDustsSmall.getSmallDustByName("Redstone", 1), ItemDustsSmall.getSmallDustByName("Glowstone", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 6), new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("cinnabar", 2), ItemDustsSmall.getSmallDustByName("Redstone", 1), ItemDustsSmall.getSmallDustByName("Glowstone", 1), new ItemStack(Items.bucket), 100, 120)); //Sphalerite Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 7), null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("sphalerite", 2), ItemDustsSmall.getSmallDustByName("Zinc", 1), ItemDustsSmall.getSmallDustByName("YellowGarnet", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 7), IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("sphalerite", 2), ItemDustsSmall.getSmallDustByName("Zinc", 1), ItemDustsSmall.getSmallDustByName("YellowGarnet", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 7), new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("sphalerite", 2), ItemDustsSmall.getSmallDustByName("Zinc", 1), ItemDustsSmall.getSmallDustByName("YellowGarnet", 1), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 7), null, new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("sphalerite", 2), ItemDusts.getDustByName("zinc", 1), ItemDustsSmall.getSmallDustByName("YellowGarnet", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 7), ItemCells.getCellByName("sodiumPersulfate", 1), null, ItemDusts.getDustByName("sphalerite", 2), ItemDusts.getDustByName("zinc", 1), ItemDustsSmall.getSmallDustByName("YellowGarnet", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 7), new ItemStack(ModItems.bucketSodiumpersulfate), null, ItemDusts.getDustByName("sphalerite", 2), ItemDusts.getDustByName("zinc", 1), ItemDustsSmall.getSmallDustByName("YellowGarnet", 1), new ItemStack(Items.bucket), 100, 120)); //Tungsten Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 8), null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("tungsten", 2), ItemDustsSmall.getSmallDustByName("Manganese", 1), ItemDustsSmall.getSmallDustByName("Silver", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 8), IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("tungsten", 2), ItemDustsSmall.getSmallDustByName("Manganese", 1), ItemDustsSmall.getSmallDustByName("Silver", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 8), new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("tungsten", 2), ItemDustsSmall.getSmallDustByName("Manganese", 1), ItemDustsSmall.getSmallDustByName("Silver", 1), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 8), null, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("tungsten", 2), ItemDustsSmall.getSmallDustByName("Manganese", 1), ItemDusts.getDustByName("silver", 2), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 8), ItemCells.getCellByName("mercury", 1), null, ItemDusts.getDustByName("tungsten", 2), ItemDustsSmall.getSmallDustByName("Manganese", 1), ItemDusts.getDustByName("silver", 2), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 8), new ItemStack(ModItems.bucketMercury), null, ItemDusts.getDustByName("tungsten", 2), ItemDustsSmall.getSmallDustByName("Manganese", 1), ItemDusts.getDustByName("silver", 2), new ItemStack(Items.bucket), 100, 120)); //Sheldonite Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 9), null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("platinum", 2), ItemDustsSmall.getSmallDustByName("Iridium", 1), ItemDustsSmall.getSmallDustByName("Iridium", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 9), IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("platinum", 2), ItemDustsSmall.getSmallDustByName("Iridium", 1), ItemDustsSmall.getSmallDustByName("Iridium", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 9), new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("platinum", 2), ItemDustsSmall.getSmallDustByName("Iridium", 1), ItemDustsSmall.getSmallDustByName("Iridium", 1), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 9), null, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("platinum", 3), ItemDustsSmall.getSmallDustByName("Iridium", 1), ItemDustsSmall.getSmallDustByName("Iridium", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 9), ItemCells.getCellByName("mercury", 1), null, ItemDusts.getDustByName("platinum", 3), ItemDustsSmall.getSmallDustByName("Iridium", 1), ItemDustsSmall.getSmallDustByName("Iridium", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 9), new ItemStack(ModItems.bucketMercury), null, ItemDusts.getDustByName("platinum", 3), ItemDustsSmall.getSmallDustByName("Iridium", 1), ItemDustsSmall.getSmallDustByName("Iridium", 1), new ItemStack(Items.bucket), 100, 120)); //Peridot Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 10), null, new FluidStack(FluidRegistry.WATER, 1000), ItemGems.getGemByName("peridot", 1), ItemDustsSmall.getSmallDustByName("Peridot", 6), ItemDustsSmall.getSmallDustByName("Pyrope", 2), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 10), IC2Items.getItem("waterCell"), null, ItemGems.getGemByName("peridot", 1), ItemDustsSmall.getSmallDustByName("Peridot", 6), ItemDustsSmall.getSmallDustByName("Pyrope", 2), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 10), new ItemStack(Items.water_bucket), null, ItemGems.getGemByName("peridot", 1), ItemDustsSmall.getSmallDustByName("Peridot", 6), ItemDustsSmall.getSmallDustByName("Pyrope", 2), new ItemStack(Items.bucket), 100, 120)); //Sodalite Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 11), null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("sodalite", 12), ItemDustsSmall.getSmallDustByName("Lazurite", 4), ItemDustsSmall.getSmallDustByName("Lapis", 4), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 11), IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("sodalite", 12), ItemDustsSmall.getSmallDustByName("Lazurite", 4), ItemDustsSmall.getSmallDustByName("Lapis", 4), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 11), new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("sodalite", 12), ItemDustsSmall.getSmallDustByName("Lazurite", 4), ItemDustsSmall.getSmallDustByName("Lapis", 4), new ItemStack(Items.bucket), 100, 120)); //Tetrahedrite Ore RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 12), null, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("tetrahedrite", 2), ItemDustsSmall.getSmallDustByName("Antimony", 1), ItemDustsSmall.getSmallDustByName("Zinc", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 12), IC2Items.getItem("waterCell"), null, ItemDusts.getDustByName("tetrahedrite", 2), ItemDustsSmall.getSmallDustByName("Antimony", 1), ItemDustsSmall.getSmallDustByName("Zinc", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 12), new ItemStack(Items.water_bucket), null, ItemDusts.getDustByName("tetrahedrite", 2), ItemDustsSmall.getSmallDustByName("Antimony", 1), ItemDustsSmall.getSmallDustByName("Zinc", 1), new ItemStack(Items.bucket), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 12), null, new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("tetrahedrite", 3), ItemDustsSmall.getSmallDustByName("Antimony", 1), ItemDustsSmall.getSmallDustByName("Zinc", 1), null, 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 12), ItemCells.getCellByName("sodiumPersulfate", 1), null, ItemDusts.getDustByName("tetrahedrite", 3), ItemDustsSmall.getSmallDustByName("Antimony", 1), ItemDustsSmall.getSmallDustByName("Zinc", 1), IC2Items.getItem("cell"), 100, 120)); RecipeHanderer.addRecipe(new GrinderRecipe(new ItemStack(ModBlocks.ore, 1, 12), new ItemStack(ModItems.bucketSodiumpersulfate), null, ItemDusts.getDustByName("tetrahedrite", 3), ItemDustsSmall.getSmallDustByName("Antimony", 1), ItemDustsSmall.getSmallDustByName("Zinc", 1), new ItemStack(Items.bucket), 100, 120)); } }
package org.myrobotlab.framework.repo; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.ivy.Main; import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.core.report.ArtifactDownloadReport; import org.apache.ivy.core.report.ResolveReport; import org.apache.ivy.util.AbstractMessageLogger; import org.apache.ivy.util.Message; import org.apache.ivy.util.filter.Filter; import org.apache.ivy.util.filter.NoFilter; import org.myrobotlab.framework.Platform; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.framework.Status; import org.myrobotlab.framework.StatusLevel; import org.myrobotlab.io.FileIO; import org.myrobotlab.io.Zip; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggingFactory; // FIXME - 2 layer abstraction - because to generate build files and // other critical methods - they do not require actual "ivy" components // so these methods should be un-hindered by actual maven, gradle or ivy imports ! public class IvyWrapper extends Repo { static IvyWrapper localInstance = null; public static final Filter NO_FILTER = NoFilter.INSTANCE; static String ivyXmlTemplate = null; static String ivysettingsXmlTemplate = null; class IvyWrapperLogger extends AbstractMessageLogger { private int level = Message.MSG_INFO; /** * @param level */ public IvyWrapperLogger(int level) { this.level = level; } @Override public void log(String msg, int level) { if (level <= this.level) { publishStatus(msg, level); } } @Override public void rawlog(String msg, int level) { log(msg, level); } @Override public void doProgress() { // log.info("."); } @Override public void doEndProgress(String msg) { log.info(msg); } public int getLevel() { return level; } } static public Repo getTypeInstance() { if (localInstance == null) { init(); } return localInstance; } static private synchronized void init() { if (localInstance == null) { localInstance = new IvyWrapper(); ivyXmlTemplate = FileIO.resourceToString("framework/ivy.xml.template"); ivysettingsXmlTemplate = FileIO.resourceToString("framework/ivysettings.xml.template"); } } @Override public void install(String location, String[] serviceTypes) { try { publishStatus(Status.newInstance(Repo.class.getSimpleName(), StatusLevel.INFO, Repo.INSTALL_START, String.format("starting install of %s", (Object[]) serviceTypes))); Set<ServiceDependency> targetLibraries = getUnfulfilledDependencies(serviceTypes); if (targetLibraries.size() == 0) { log.info("{} already installed", (Object[]) serviceTypes); return; } log.info("installing {} services into {}", serviceTypes.length, location); // create build files - generates appropriate ivy.xml and settings files // this service file should be marked as dependencies all others // should be marked as provided // ??? do "provided" get incorporate in the resolve ? createBuildFiles(location, serviceTypes); Platform platform = Platform.getLocalInstance(); String[] cmd = new String[] { "-settings", location + "/ivysettings.xml", "-ivy", location + "/ivy.xml", "-retrieve", location + "/[originalname].[ext]" }; StringBuilder sb = new StringBuilder("java -jar ..\\..\\ivy-2.4.0-3.jar"); for (String s : cmd) { sb.append(" "); sb.append(s); } log.info("cmd {}", sb); Main.setLogger(new IvyWrapperLogger(Message.MSG_INFO)); ResolveReport report = Main.run(cmd); // if no errors - // mark "service" as installed // mark all libraries as installed List<?> err = report.getAllProblemMessages(); if (err.size() > 0) { for (int i = 0; i < err.size(); ++i) { String errStr = err.get(i).toString(); error(errStr); } return; } // TODO - promote to Repo.setInstalled for (ServiceDependency library : targetLibraries) { // set as installed & save state library.setInstalled(true); installedLibraries.put(library.toString(), library); info("installed %s platform %s", library, platform.getPlatformId()); } save(); ArtifactDownloadReport[] artifacts = report.getAllArtifactsReports(); for (int i = 0; i < artifacts.length; ++i) { ArtifactDownloadReport ar = artifacts[i]; Artifact artifact = ar.getArtifact(); // String filename = IvyPatternHelper.substitute("[originalname].[ext]", // artifact); File file = ar.getLocalFile(); String filename = file.getAbsoluteFile().getAbsolutePath(); log.info("{}", filename); if ("zip".equalsIgnoreCase(artifact.getExt())) { info("unzipping %s", filename); try { Zip.unzip(filename, "./"); info("unzipped %s", filename); } catch (Exception e) { log.error(e.getMessage(), e); } } } publishStatus(Status.newInstance(Repo.class.getSimpleName(), StatusLevel.INFO, Repo.INSTALL_FINISHED, String.format("finished install of %s", (Object[]) serviceTypes))); } catch (Exception e) { error(e.getMessage()); log.error(e.getMessage(), e); } } public void createIvySettings(String location) throws IOException { Map<String, String> snr = new HashMap<String, String>(); StringBuilder sb = new StringBuilder(); for (RemoteRepo repo : remotes) { if (repo.comment != null) { sb.append(" <!-- " + repo.comment + " -->\n"); } sb.append(" <ibiblio name=\""); sb.append(repo.id); sb.append("\" m2compatible=\"true\" "); if (repo.url != null) { sb.append("root=\"" + repo.url + "\" "); } sb.append("/>\n\n"); } snr.put("{{repos}}", sb.toString()); createFilteredFile(snr, location, "ivysettings", "xml"); } public void createIvy(String location, String[] serviceTypes) throws IOException { Map<String, String> snr = new HashMap<String, String>(); StringBuilder sb = null; StringBuilder ret = new StringBuilder(); ServiceData sd = ServiceData.getLocalInstance(); ret.append(" <dependencies>\n\n"); for (String serviceType : serviceTypes) { ServiceType service = sd.getServiceType(serviceType); List<ServiceDependency> dependencies = service.getDependencies(); if (dependencies.size() == 0) { continue; } sb = new StringBuilder(); sb.append(String.format(" \n", service.getSimpleName())); for (ServiceDependency dependency : dependencies) { sb.append(" <dependency"); // conf="provided->master" sb.append(String.format(" org=\"%s\" name=\"%s\" rev=\"%s\"", dependency.getOrgId(), dependency.getArtifactId(), dependency.getVersion())); // FIXME - if (!service.includeServiceInOneJar()) { // sb.append(" conf=\"provided->master\" "); } // <dependency /> or <dependency></dependency> - ie do we have more // stuff ? List<ServiceExclude> excludes = dependency.getExcludes(); boolean twoTags = dependency.getExt() != null || excludes != null & excludes.size() > 0; if (twoTags) { // more stuffs ! - we have 2 tags - end this one without /> sb.append(">\n"); } if (dependency.getExt() != null) { // " <artifact name=\"foo-src\" type=\"%s\" ext=\"%s\" // conf=\"provided->master\" sb.append(String.format(" <artifact name=\"%s\" type=\"%s\" ext=\"%s\" />\n", dependency.getArtifactId(), dependency.getExt(), dependency.getExt())); } if (excludes != null & excludes.size() > 0) { StringBuilder ex = new StringBuilder(); for (ServiceExclude exclude : excludes) { ex.append(" <exclude "); ex.append(String.format(" org=\"%s\" ", exclude.getOrgId())); ex.append(String.format(" name=\"%s\" ", exclude.getArtifactId())); ex.append("/>\n"); } sb.append(ex); } if (twoTags) { sb.append(" </dependency>\n"); } else { // single tag sb.append("/>\n"); } } // for each dependency // sb.append(String.format("<!-- %s end -->\n\n", // service.getSimpleName())); sb.append("\n"); if (dependencies.size() > 0) { ret.append(sb); } } // for each service ret.append(" </dependencies>\n"); snr.put("{{dependencies}}", ret.toString()); createFilteredFile(snr, location, "ivy", "xml"); } /** * <pre> * generates all ivy related build files based on Service.getMetaData * * ivy.xml * ivysettings.xml * build.xml * * </pre> * * @return */ public void createBuildFiles(String location, String[] serviceTypes) { try { location = createWorkDirectory(location); createIvySettings(location); createIvy(location, serviceTypes); } catch (Exception e) { log.error("could not generate build files", e); } } private void publishStatus(String msg, int level) { // if (level <= this.level) { Status status = Status.newInstance(Repo.class.getSimpleName(), StatusLevel.INFO, Repo.INSTALL_PROGRESS, msg); // FIXME - set it to the instance of IvyWrapper - really this method should just call IvyWrapper.publishStatus(String msg, int level) status.source = this; if (level == Message.MSG_ERR) { status.level = StatusLevel.ERROR; } else if (level == Message.MSG_WARN) { status.level = StatusLevel.WARN; } publishStatus(status); } public static void main(String[] args) { try { LoggingFactory.init(Level.INFO); Repo repo = Repo.getInstance("IvyWrapper"); String serviceType = "all"; long ts = System.currentTimeMillis(); String dir = String.format("install.ivy.%s.%d", serviceType, ts); // repo.createBuildFiles(dir, serviceType); repo.installTo("install.ivy"); // repo.install(dir, serviceType); // repo.install("install.dl4j.maven", "Deeplearning4j"); // repo.install("install.opencv.maven","OpenCV"); // repo.createBuildFiles(dir, "Arm"); // repo.createBuildFilesTo(dir); // repo.installTo(dir); // repo.install(); // repo.installEach(); <-- TODO - test log.info("done"); } catch (Exception e) { log.error(e.getMessage(), e); } } }
package util.validator; import http.helpers.Helper; import net.itarray.automotion.Element; import net.itarray.automotion.internal.Errors; import net.itarray.automotion.internal.SimpleTransform; import net.itarray.automotion.internal.TransformedGraphics; import net.itarray.automotion.internal.Zoom; import net.itarray.automotion.internal.DriverFacade; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.json.simple.JSONObject; import org.json.simple.parser.ParseException; import org.openqa.selenium.*; import org.openqa.selenium.Dimension; import util.general.HtmlReportBuilder; import util.validator.properties.Padding; import javax.imageio.ImageIO; import java.awt.*; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicLong; import static environment.EnvironmentFactory.*; import static util.general.SystemHelper.isRetinaDisplay; import static util.validator.Constants.*; import static util.validator.ResponsiveUIValidator.Units.PX; public class ResponsiveUIValidator { static final int MIN_OFFSET = -10000; private final static Logger LOG = Logger.getLogger(ResponsiveUIValidator.class); private final DriverFacade driver; private static Element rootElement; static long startTime; private static boolean isMobileTopBar = false; private static boolean withReport = false; private static String scenarioName = "Default"; private static Color rootColor = new Color(255, 0, 0, 255); private static Color highlightedElementsColor = new Color(255, 0, 255, 255); private static Color linesColor = Color.ORANGE; private static String currentZoom = "100%"; private static List<String> jsonFiles = new ArrayList<>(); protected static Errors errors; private boolean drawLeftOffsetLine = false; private boolean drawRightOffsetLine = false; private boolean drawTopOffsetLine = false; private boolean drawBottomOffsetLine = false; String rootElementReadableName = "Root Element"; ResponsiveUIValidator.Units units = PX; private Dimension pageSize; public ResponsiveUIValidator(WebDriver driver) { this(new DriverFacade(driver)); } protected ResponsiveUIValidator(DriverFacade driver) { this.driver = driver; ResponsiveUIValidator.errors = new Errors(); currentZoom = driver.getZoom(); pageSize = driver.retrievePageSize(); } protected static Element getRootElement() { return rootElement; } protected static void setRootElement(Element element) { ResponsiveUIValidator.rootElement = element; } /** * Set color for main element. This color will be used for highlighting element in results * * @param color */ public void setColorForRootElement(Color color) { rootColor = color; } /** * Set color for compared elements. This color will be used for highlighting elements in results * * @param color */ public void setColorForHighlightedElements(Color color) { highlightedElementsColor = color; } /** * Set color for grid lines. This color will be used for the lines of alignment grid in results * * @param color */ public void setLinesColor(Color color) { linesColor = color; } /** * Set top bar mobile offset. Applicable only for native mobile testing * * @param state */ public void setTopBarMobileOffset(boolean state) { isMobileTopBar = state; } /** * Method that defines start of new validation. Needs to be called each time before calling findElement(), findElements() * * @return ResponsiveUIValidator */ public ResponsiveUIValidator init() { return new ResponsiveUIValidator(driver); } /** * Method that defines start of new validation with specified name of scenario. Needs to be called each time before calling findElement(), findElements() * * @param scenarioName * @return ResponsiveUIValidator */ public ResponsiveUIValidator init(String scenarioName) { ResponsiveUIValidator.scenarioName = scenarioName; return new ResponsiveUIValidator(driver); } /** * Main method to specify which element we want to validate (can be called only findElement() OR findElements() for single validation) * * @param element * @param readableNameOfElement * @return UIValidator */ public UIValidator findElement(WebElement element, String readableNameOfElement) { return new UIValidator(driver, element, readableNameOfElement); } /** * Main method to specify the list of elements that we want to validate (can be called only findElement() OR findElements() for single validation) * * @param elements * @return ResponsiveUIChunkValidator */ public ResponsiveUIChunkValidator findElements(java.util.List<WebElement> elements) { return new ResponsiveUIChunkValidator(driver, elements); } /** * Change units to Pixels or % (Units.PX, Units.PERCENT) * * @param units * @return UIValidator */ public ResponsiveUIValidator changeMetricsUnitsTo(Units units) { this.units = units; return this; } /** * Methods needs to be called to collect all the results in JSON file and screenshots * * @return ResponsiveUIValidator */ public ResponsiveUIValidator drawMap() { withReport = true; return this; } /** * Call method to summarize and validate the results (can be called with drawMap(). In this case result will be only True or False) * * @return boolean */ public boolean validate() { if (errors.hasMessages()) { compileValidationReport(); } return !errors.hasMessages(); } private void compileValidationReport() { if (!withReport) { return; } File screenshot = drawScreenshot(); writeResults(screenshot); } private void writeResults(File screenshot) { JSONObject jsonResults = new JSONObject(); jsonResults.put(ERROR_KEY, errors.hasMessages()); jsonResults.put(DETAILS, errors.getMessages()); JSONObject rootDetails = new JSONObject(); if (rootElement != null) { rootDetails.put(X, rootElement.getX()); rootDetails.put(Y, rootElement.getY()); rootDetails.put(WIDTH, rootElement.getWidth()); rootDetails.put(HEIGHT, rootElement.getHeight()); } jsonResults.put(SCENARIO, scenarioName); jsonResults.put(ROOT_ELEMENT, rootDetails); jsonResults.put(TIME_EXECUTION, String.valueOf(System.currentTimeMillis() - startTime) + " milliseconds"); jsonResults.put(ELEMENT_NAME, rootElementReadableName); jsonResults.put(SCREENSHOT, rootElementReadableName.replace(" ", "") + "-" + screenshot.getName()); long ms = System.currentTimeMillis(); String uuid = Helper.getGeneratedStringWithLength(7); String jsonFileName = rootElementReadableName.replace(" ", "") + "-automotion" + ms + uuid + ".json"; File jsonFile = new File(TARGET_AUTOMOTION_JSON + jsonFileName); jsonFile.getParentFile().mkdirs(); try ( OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(jsonFile), StandardCharsets.UTF_8); Writer writer = new BufferedWriter(outputStreamWriter)) { writer.write(jsonResults.toJSONString()); } catch (IOException ex) { LOG.error("Cannot create json report: " + ex.getMessage()); } jsonFiles.add(jsonFileName); } private File drawScreenshot() { File screenshot = null; BufferedImage img = null; try { screenshot = driver.takeScreenshot(); img = ImageIO.read(screenshot); } catch (Exception e) { LOG.error("Failed to create screenshot file: " + e.getMessage()); } drawScreenshot(screenshot, img); return screenshot; } /** * Call method to generate HTML report */ public void generateReport() { if (withReport && !jsonFiles.isEmpty()) { try { new HtmlReportBuilder().buildReport(jsonFiles); } catch (IOException | ParseException | InterruptedException e) { e.printStackTrace(); } } } /** * Call method to generate HTML report with specified file report name * * @param name */ public void generateReport(String name) { if (withReport && !jsonFiles.isEmpty()) { try { new HtmlReportBuilder().buildReport(name, jsonFiles); } catch (IOException | ParseException | InterruptedException e) { e.printStackTrace(); } } } private void drawScreenshot(File output, BufferedImage img) { if (img != null) { Graphics2D g = img.createGraphics(); TransformedGraphics graphics = graphics(g, getTransform()); drawRootElement(graphics); drawOffsetLines(graphics, img); for (Object obj : errors.getMessages()) { JSONObject det = (JSONObject) obj; JSONObject details = (JSONObject) det.get(REASON); JSONObject numE = (JSONObject) details.get(ELEMENT); if (numE != null) { int x = (int) (float) numE.get(X); int y = (int) (float) numE.get(Y); int width = (int) (float) numE.get(WIDTH); int height = (int) (float) numE.get(HEIGHT); graphics.setColor(highlightedElementsColor); graphics.setStroke(new BasicStroke(2)); graphics.drawRectByExtend(x, y, width, height); } } try { ImageIO.write(img, "png", output); File file = new File(TARGET_AUTOMOTION_IMG + rootElementReadableName.replace(" ", "") + "-" + output.getName()); FileUtils.copyFile(output, file); } catch (IOException e) { e.printStackTrace(); } } else { LOG.error("Taking of screenshot was failed for some reason."); } } void validateElementsAreNotOverlapped(List<Element> elements) { for (int firstIndex = 0; firstIndex < elements.size(); firstIndex++) { Element first = elements.get(firstIndex); for (int secondIndex = firstIndex+1; secondIndex < elements.size(); secondIndex++) { Element second = elements.get(secondIndex); if (first.overlaps(second)) { errors.add("Elements are overlapped", first); break; } } } } void validateGridAlignment(List<Element> elements, int columns, int rows) { ConcurrentSkipListMap<Integer, AtomicLong> map = new ConcurrentSkipListMap<>(); for (Element element : elements) { Integer y = element.getY(); map.putIfAbsent(y, new AtomicLong(0)); map.get(y).incrementAndGet(); } int mapSize = map.size(); if (rows > 0) { if (mapSize != rows) { errors.add(String.format("Elements in a grid are not aligned properly. Looks like grid has wrong amount of rows. Expected is %d. Actual is %d", rows, mapSize)); } } if (columns > 0) { int errorLastLine = 0; int rowCount = 1; for (Map.Entry<Integer, AtomicLong> entry : map.entrySet()) { if (rowCount <= mapSize) { int actualInARow = entry.getValue().intValue(); if (actualInARow != columns) { errorLastLine++; if (errorLastLine > 1) { errors.add(String.format("Elements in a grid are not aligned properly in row #%d. Expected %d elements in a row. Actually it's %d", rowCount, columns, actualInARow)); } } rowCount++; } } } } void validateRightOffsetForChunk(List<Element> elements) { for (int i = 0; i < elements.size() - 1; i++) { Element element = elements.get(i); Element elementToCompare = elements.get(i + 1); if (!element.hasEqualRightOffsetAs(elementToCompare)) { errors.add(String.format("Element #%d has not the same right offset as element #%d", i + 1, i + 2), elementToCompare); } } } void validateLeftOffsetForChunk(List<Element> elements) { for (int i = 0; i < elements.size() - 1; i++) { Element element = elements.get(i); Element elementToCompare = elements.get(i + 1); if (!element.hasEqualLeftOffsetAs(elementToCompare)) { errors.add(String.format("Element #%d has not the same left offset as element #%d", i + 1, i + 2), elementToCompare); } } } void validateTopOffsetForChunk(List<Element> elements) { for (int i = 0; i < elements.size() - 1; i++) { Element element = elements.get(i); Element elementToCompare = elements.get(i + 1); if (!element.hasEqualTopOffsetAs(elementToCompare)) { errors.add(String.format("Element #%d has not the same top offset as element #%d", i + 1, i + 2), elementToCompare); } } } void validateBottomOffsetForChunk(List<Element> elements) { for (int i = 0; i < elements.size() - 1; i++) { Element element = elements.get(i); Element elementToCompare = elements.get(i + 1); if (!element.hasEqualBottomOffsetAs(elementToCompare)) { errors.add(String.format("Element #%d has not the same bottom offset as element #%d", i + 1, i + 2), elementToCompare); } } } void validateRightOffsetForElements(Element element, String readableName) { if (!rootElement.hasEqualRightOffsetAs(element)) { errors.add(String.format("Element '%s' has not the same right offset as element '%s'", rootElementReadableName, readableName), element); } } void validateLeftOffsetForElements(Element element, String readableName) { if (!rootElement.hasEqualLeftOffsetAs(element)) { errors.add(String.format("Element '%s' has not the same left offset as element '%s'", rootElementReadableName, readableName), element); } } void validateTopOffsetForElements(Element element, String readableName) { if (!rootElement.hasEqualTopOffsetAs(element)) { errors.add(String.format("Element '%s' has not the same top offset as element '%s'", rootElementReadableName, readableName), element); } } void validateBottomOffsetForElements(Element element, String readableName) { if (!rootElement.hasEqualBottomOffsetAs(element)) { errors.add(String.format("Element '%s' has not the same bottom offset as element '%s'", rootElementReadableName, readableName), element); } } void validateNotOverlappingWithElements(Element element, String readableName) { if (rootElement.overlaps(element)) { errors.add(String.format("Element '%s' is overlapped with element '%s' but should not", rootElementReadableName, readableName), element); } } void validateOverlappingWithElements(Element element, String readableName) { if (!rootElement.overlaps(element)) { errors.add(String.format("Element '%s' is not overlapped with element '%s' but should be", rootElementReadableName, readableName), element); } } void validateMaxOffset(int top, int right, int bottom, int left) { int rootElementRightOffset = getRootElement().getRightOffset(pageSize); int rootElementBottomOffset = rootElement.getBottomOffset(pageSize); if (rootElement.getX() > left) { errors.add(String.format("Expected max left offset of element '%s' is: %spx. Actual left offset is: %spx", rootElementReadableName, left, rootElement.getX())); } if (rootElement.getY() > top) { errors.add(String.format("Expected max top offset of element '%s' is: %spx. Actual top offset is: %spx", rootElementReadableName, top, rootElement.getY())); } if (rootElementRightOffset > right) { errors.add(String.format("Expected max right offset of element '%s' is: %spx. Actual right offset is: %spx", rootElementReadableName, right, rootElementRightOffset)); } if (rootElementBottomOffset > bottom) { errors.add(String.format("Expected max bottom offset of element '%s' is: %spx. Actual bottom offset is: %spx", rootElementReadableName, bottom, rootElementBottomOffset)); } } void validateMinOffset(int top, int right, int bottom, int left) { int rootElementRightOffset = getRootElement().getRightOffset(pageSize); int rootElementBottomOffset = rootElement.getBottomOffset(pageSize); if (rootElement.getX() < left) { errors.add(String.format("Expected min left offset of element '%s' is: %spx. Actual left offset is: %spx", rootElementReadableName, left, rootElement.getX())); } if (rootElement.getY() < top) { errors.add(String.format("Expected min top offset of element '%s' is: %spx. Actual top offset is: %spx", rootElementReadableName, top, rootElement.getY())); } if (rootElementRightOffset < right) { errors.add(String.format("Expected min top offset of element '%s' is: %spx. Actual right offset is: %spx", rootElementReadableName, right, rootElementRightOffset)); } if (rootElementBottomOffset < bottom) { errors.add(String.format("Expected min bottom offset of element '%s' is: %spx. Actual bottom offset is: %spx", rootElementReadableName, bottom, rootElementBottomOffset)); } } void validateMaxHeight(int height) { if (!rootElement.hasMaxHeight(height)) { errors.add(String.format("Expected max height of element '%s' is: %spx. Actual height is: %spx", rootElementReadableName, height, rootElement.getHeight())); } } void validateMinHeight(int height) { if (!rootElement.hasMinHeight(height)) { errors.add(String.format("Expected min height of element '%s' is: %spx. Actual height is: %spx", rootElementReadableName, height, rootElement.getHeight())); } } void validateMaxWidth(int width) { if (!rootElement.hasMaxWidth(width)) { errors.add(String.format("Expected max width of element '%s' is: %spx. Actual width is: %spx", rootElementReadableName, width, rootElement.getWidth())); } } void validateMinWidth(int width) { if (!rootElement.hasMinWidth(width)) { errors.add(String.format("Expected min width of element '%s' is: %spx. Actual width is: %spx", rootElementReadableName, width, rootElement.getWidth())); } } void validateSameWidth(Element element, String readableName) { if (!rootElement.hasSameWidthAs(element)) { errors.add(String.format("Element '%s' has not the same width as %s. Width of '%s' is %spx. Width of element is %spx", rootElementReadableName, readableName, rootElementReadableName, rootElement.getWidth(), element.getWidth()), element); } } void validateSameHeight(Element element, String readableName) { if (!rootElement.hasSameHeightAs(element)) { errors.add(String.format("Element '%s' has not the same height as %s. Height of '%s' is %spx. Height of element is %spx", rootElementReadableName, readableName, rootElementReadableName, rootElement.getHeight(), element.getHeight()), element); } } void validateSameSize(Element element, String readableName) { if (!rootElement.hasSameSizeAs(element)) { errors.add(String.format("Element '%s' has not the same size as %s. Size of '%s' is %spx x %spx. Size of element is %spx x %spx", rootElementReadableName, readableName, rootElementReadableName, rootElement.getWidth(), rootElement.getHeight(), element.getWidth(), element.getHeight()), element); } } void validateSameWidth(List<Element> elements) { for (int i = 0; i < elements.size() - 1; i++) { Element element = elements.get(i); Element elementToCompare = elements.get(i + 1); if (!element.hasSameWidthAs(elementToCompare)) { errors.add(String.format("Element #%d has different width. Element width is: [%d, %d]", (i + 1), element.getWidth(), element.getHeight()), element); errors.add(String.format("Element #%d has different width. Element width is: [%d, %d]", (i + 2), elementToCompare.getWidth(), elementToCompare.getHeight()), elementToCompare); } } } void validateSameHeight(List<Element> elements) { for (int i = 0; i < elements.size() - 1; i++) { Element element = elements.get(i); Element elementToCompare = elements.get(i + 1); if (!element.hasSameHeightAs(elementToCompare)) { errors.add(String.format("Element #%d has different height. Element height is: [%d, %d]", (i + 1), element.getWidth(), element.getHeight()), element); errors.add(String.format("Element #%d has different height. Element height is: [%d, %d]", (i + 2), elementToCompare.getWidth(), elementToCompare.getHeight()), elementToCompare); } } } void validateSameSize(List<Element> elements) { for (int i = 0; i < elements.size() - 1; i++) { Element element = elements.get(i); Element elementToCompare = elements.get(i + 1); if (!element.hasSameSizeAs(elementToCompare)) { errors.add(String.format("Element #%d has different size. Element size is: [%d, %d]", (i + 1), element.getWidth(), element.getHeight()), element); errors.add(String.format("Element #%d has different size. Element size is: [%d, %d]", (i + 2), elementToCompare.getWidth(), elementToCompare.getHeight()), elementToCompare); } } } void validateNotSameSize(Element element, String readableName) { if (!element.hasEqualWebElement(getRootElement())) { int h = element.getHeight(); int w = element.getWidth(); if (h == rootElement.getHeight() && w == rootElement.getWidth()) { errors.add(String.format("Element '%s' has the same size as %s. Size of '%s' is %spx x %spx. Size of element is %spx x %spx", rootElementReadableName, readableName, rootElementReadableName, rootElement.getWidth(), rootElement.getHeight(), w, h), element); } } } void validateNotSameSize(List<Element> elements) { for (int i = 0; i < elements.size() - 1; i++) { Element element = elements.get(i); Element elementToCompare = elements.get(i + 1); if (element.hasSameSizeAs(elementToCompare)) { errors.add(String.format("Element #%d has same size. Element size is: [%d, %d]", (i + 1), element.getWidth(), element.getHeight()), element); errors.add(String.format("Element #%d has same size. Element size is: [%d, %d]", (i + 2), elementToCompare.getWidth(), elementToCompare.getHeight()), elementToCompare); } } } void validateNotSameWidth(List<Element> elements) { for (int i = 0; i < elements.size() - 1; i++) { Element element = elements.get(i); Element elementToCompare = elements.get(i + 1); if (element.hasSameWidthAs(elementToCompare)) { errors.add(String.format("Element #%d has same width. Element width is: [%d, %d]", (i + 1), element.getWidth(), element.getHeight()), element); errors.add(String.format("Element #%d has same width. Element width is: [%d, %d]", (i + 2), elementToCompare.getWidth(), elementToCompare.getHeight()), elementToCompare); } } } void validateNotSameHeight(List<Element> elements) { for (int i = 0; i < elements.size() - 1; i++) { Element element = elements.get(i); Element elementToCompare = elements.get(i + 1); if (element.hasSameHeightAs(elementToCompare)) { errors.add(String.format("Element #%d has same height. Element height is: [%d, %d]", (i + 1), element.getWidth(), element.getHeight()), element); errors.add(String.format("Element #%d has same height. Element height is: [%d, %d]", (i + 2), elementToCompare.getWidth(), elementToCompare.getHeight()), elementToCompare); } } } void validateBelowElement(Element element, int minMargin, int maxMargin) { int marginBetweenRoot = element.getY() - rootElement.getCornerY(); if (marginBetweenRoot < minMargin || marginBetweenRoot > maxMargin) { errors.add(String.format("Below element aligned not properly. Expected margin should be between %spx and %spx. Actual margin is %spx", minMargin, maxMargin, marginBetweenRoot), element); } } void validateBelowElement(Element belowElement) { if (!getRootElement().hasBelowElement(belowElement)) { errors.add("Below element aligned not properly", belowElement); } } void validateAboveElement(Element element, int minMargin, int maxMargin) { int marginBetweenRoot = rootElement.getY() - element.getCornerY(); if (marginBetweenRoot < minMargin || marginBetweenRoot > maxMargin) { errors.add(String.format("Above element aligned not properly. Expected margin should be between %spx and %spx. Actual margin is %spx", minMargin, maxMargin, marginBetweenRoot), element); } } void validateAboveElement(Element aboveElement) { if (!getRootElement().hasAboveElement(aboveElement)) { errors.add("Above element aligned not properly", aboveElement); } } void validateRightElement(Element element, int minMargin, int maxMargin) { int marginBetweenRoot = element.getX() - rootElement.getCornerX(); if (marginBetweenRoot < minMargin || marginBetweenRoot > maxMargin) { errors.add(String.format("Right element aligned not properly. Expected margin should be between %spx and %spx. Actual margin is %spx", minMargin, maxMargin, marginBetweenRoot), element); } } void validateRightElement(Element rightElement) { if (!getRootElement().hasRightElement(rightElement)) { errors.add("Right element aligned not properly", rightElement); } } void validateLeftElement(Element leftElement, int minMargin, int maxMargin) { int marginBetweenRoot = rootElement.getX() - leftElement.getCornerX(); if (marginBetweenRoot < minMargin || marginBetweenRoot > maxMargin) { errors.add(String.format("Left element aligned not properly. Expected margin should be between %spx and %spx. Actual margin is %spx", minMargin, maxMargin, marginBetweenRoot), leftElement); } } void validateLeftElement(Element leftElement) { if (!getRootElement().hasLeftElement(leftElement)) { errors.add("Left element aligned not properly", leftElement); } } void validateEqualLeftRightOffset(Element element, String rootElementReadableName) { if (!element.hasEqualLeftRightOffset(pageSize)) { errors.add(String.format("Element '%s' has not equal left and right offset. Left offset is %dpx, right is %dpx", rootElementReadableName, element.getX(), element.getRightOffset(pageSize)), element); } } void validateEqualTopBottomOffset(Element element, String rootElementReadableName) { if (!element.hasEqualTopBottomOffset(pageSize)) { errors.add(String.format("Element '%s' has not equal top and bottom offset. Top offset is %dpx, bottom is %dpx", rootElementReadableName, element.getY(), element.getBottomOffset(pageSize)), element); } } void validateEqualLeftRightOffset(List<Element> elements) { for (Element element : elements) { if (!element.hasEqualLeftRightOffset(pageSize)) { errors.add(String.format("Element '%s' has not equal left and right offset. Left offset is %dpx, right is %dpx", element.getFormattedMessage(), element.getX(), element.getRightOffset(pageSize)), element); } } } void validateEqualTopBottomOffset(List<Element> elements) { for (Element element : elements) { if (!element.hasEqualTopBottomOffset(pageSize)) { errors.add(String.format("Element '%s' has not equal top and bottom offset. Top offset is %dpx, bottom is %dpx", element.getFormattedMessage(), element.getY(), element.getBottomOffset(pageSize)), element); } } } private void drawRootElement(TransformedGraphics graphics) { graphics.setColor(rootColor); graphics.setStroke(new BasicStroke(2)); int x = rootElement.getX(); int y = rootElement.getY(); graphics.drawRectByExtend(x, y, rootElement.getWidth(), rootElement.getHeight()); } private void drawOffsetLines(TransformedGraphics graphics, BufferedImage img) { Stroke dashed = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{9}, 0); graphics.setStroke(dashed); graphics.setColor(linesColor); if (drawLeftOffsetLine) { graphics.drawVerticalLine(rootElement.getX(), img.getHeight()); } if (drawRightOffsetLine) { graphics.drawVerticalLine(rootElement.getCornerX(), img.getHeight()); } if (drawTopOffsetLine) { graphics.drawHorizontalLine(rootElement.getY(), img.getWidth()); } if (drawBottomOffsetLine) { graphics.drawHorizontalLine(rootElement.getCornerY(), img.getWidth()); } } private TransformedGraphics graphics(Graphics2D g, SimpleTransform transform) { return new TransformedGraphics(g, transform); } private int getYOffset() { if (isMobile() && driver.isAppiumWebContext() && isMobileTopBar) { if (isIOS() || isAndroid()) { return 20; } } return 0; } private SimpleTransform getTransform() { return new SimpleTransform(getYOffset(), getScaleFactor()); } private double getScaleFactor() { double factor = 1; if (isMobile()) { if (isIOS() && isIOSDevice()) { factor = 2; } } else { int zoom = Integer.parseInt(currentZoom.replace("%", "")); factor = Zoom.getFactor(zoom); if (isRetinaDisplay() && isChrome()) { factor = factor * 2; } } return factor; } int getConvertedInt(int i, boolean horizontal) { if (units.equals(PX)) { return i; } else { if (horizontal) { return (i * pageSize.getWidth()) / 100; } else { return (i * pageSize.getHeight()) / 100; } } } void validateInsideOfContainer(Element containerElement, String readableContainerName) { Rectangle2D.Double elementRectangle = containerElement.rectangle(); if (!elementRectangle.contains(rootElement.rectangle())) { errors.add(String.format("Element '%s' is not inside of '%s'", rootElementReadableName, readableContainerName), containerElement); } } void validateInsideOfContainer(Element containerElement, String readableContainerName, List<Element> elements) { Rectangle2D.Double elementRectangle = containerElement.rectangle(); for (Element element : elements) { if (!elementRectangle.contains(element.rectangle())) { errors.add(String.format("Element is not inside of '%s'", readableContainerName), containerElement); } } } void validateInsideOfContainer(Element element, String readableContainerName, Padding padding) { int top = getConvertedInt(padding.getTop(), false); int right = getConvertedInt(padding.getRight(), true); int bottom = getConvertedInt(padding.getBottom(), false); int left = getConvertedInt(padding.getLeft(), true); Rectangle2D.Double paddedRootRectangle = new Rectangle2D.Double( rootElement.getX() - left, rootElement.getY() - top, rootElement.getWidth() + left + right, rootElement.getHeight() + top + bottom); int paddingTop = rootElement.getY() - element.getY(); int paddingLeft = rootElement.getX() - element.getX(); int paddingBottom = element.getCornerY() - rootElement.getCornerY(); int paddingRight = element.getCornerX() - rootElement.getCornerX(); if (!element.rectangle().contains(paddedRootRectangle)) { errors.add(String.format("Padding of element '%s' is incorrect. Expected padding: top[%d], right[%d], bottom[%d], left[%d]. Actual padding: top[%d], right[%d], bottom[%d], left[%d]", rootElementReadableName, top, right, bottom, left, paddingTop, paddingRight, paddingBottom, paddingLeft), element); } } protected void drawLeftOffsetLine() { drawLeftOffsetLine = true; } protected void drawRightOffsetLine() { drawRightOffsetLine = true; } protected void drawTopOffsetLine() { drawTopOffsetLine = true; } protected void drawBottomOffsetLine() { drawBottomOffsetLine = true; } public enum Units { PX, PERCENT } }
package yahoofinance.quotes.stock; import java.math.BigDecimal; import java.util.Calendar; import java.util.TimeZone; import yahoofinance.Utils; /** * All getters can return null in case the data is not available from Yahoo Finance. * * @author Stijn Strickx */ public class StockQuote { private final String symbol; private TimeZone timeZone; private BigDecimal ask; private Long askSize; private BigDecimal bid; private Long bidSize; private BigDecimal price; private Long lastTradeSize; private String lastTradeDateStr; private String lastTradeTimeStr; private Calendar lastTradeTime; private BigDecimal open; private BigDecimal previousClose; private BigDecimal dayLow; private BigDecimal dayHigh; private BigDecimal yearLow; private BigDecimal yearHigh; private BigDecimal priceAvg50; private BigDecimal priceAvg200; private Long volume; private Long avgVolume; public StockQuote(String symbol) { this.symbol = symbol; } /** * * @return difference between current price and previous close */ public BigDecimal getChange() { if(this.price == null || this.previousClose == null) { return null; } return this.price.subtract(this.previousClose); } /** * * @return change relative to previous close */ public BigDecimal getChangeInPercent() { return Utils.getPercent(this.getChange(), this.previousClose); } /** * * @return difference between current price and year low */ public BigDecimal getChangeFromYearLow() { if(this.price == null || this.yearLow == null) { return null; } return this.price.subtract(this.yearLow); } /** * * @return change from year low relative to year low */ public BigDecimal getChangeFromYearLowInPercent() { return Utils.getPercent(this.getChangeFromYearLow(), this.yearLow); } /** * * @return difference between current price and year high */ public BigDecimal getChangeFromYearHigh() { if(this.price == null || this.yearHigh == null) { return null; } return this.price.subtract(this.yearHigh); } /** * * @return change from year high relative to year high */ public BigDecimal getChangeFromYearHighInPercent() { return Utils.getPercent(this.getChangeFromYearHigh(), this.yearHigh); } /** * * @return difference between current price and 50 day moving average */ public BigDecimal getChangeFromAvg50() { if(this.price == null || this.priceAvg50 == null) { return null; } return this.price.subtract(this.priceAvg50); } /** * * @return change from 50 day moving average relative to 50 day moving average */ public BigDecimal getChangeFromAvg50InPercent() { return Utils.getPercent(this.getChangeFromAvg50(), this.priceAvg50); } /** * * @return difference between current price and 200 day moving average */ public BigDecimal getChangeFromAvg200() { if(this.price == null || this.priceAvg200 == null) { return null; } return this.price.subtract(this.priceAvg200); } /** * * @return change from 200 day moving average relative to 200 day moving average */ public BigDecimal getChangeFromAvg200InPercent() { return Utils.getPercent(this.getChangeFromAvg200(), this.priceAvg200); } public String getSymbol() { return symbol; } public BigDecimal getAsk() { return ask; } public void setAsk(BigDecimal ask) { this.ask = ask; } public Long getAskSize() { return askSize; } public void setAskSize(Long askSize) { this.askSize = askSize; } public BigDecimal getBid() { return bid; } public void setBid(BigDecimal bid) { this.bid = bid; } public Long getBidSize() { return bidSize; } public void setBidSize(Long bidSize) { this.bidSize = bidSize; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public Long getLastTradeSize() { return lastTradeSize; } public void setLastTradeSize(Long lastTradeSize) { this.lastTradeSize = lastTradeSize; } public String getLastTradeDateStr() { return lastTradeDateStr; } public void setLastTradeDateStr(String lastTradeDateStr) { this.lastTradeDateStr = lastTradeDateStr; } public String getLastTradeTimeStr() { return lastTradeTimeStr; } public void setLastTradeTimeStr(String lastTradeTimeStr) { this.lastTradeTimeStr = lastTradeTimeStr; } /** * Will derive the time zone from the exchange to parse the date time into a Calendar object. * This will not react to changes in the lastTradeDateStr and lastTradeTimeStr * * @return last trade date time */ public Calendar getLastTradeTime() { return lastTradeTime; } public void setLastTradeTime(Calendar lastTradeTime) { this.lastTradeTime = lastTradeTime; } /** * Will use the provided time zone to parse the date time into a Calendar object * Reacts to changes in the lastTradeDateStr and lastTradeTimeStr * * @param timeZone time zone where the stock is traded * @return last trade date time */ public Calendar getLastTradeTime(TimeZone timeZone) { return Utils.parseDateTime(this.lastTradeDateStr, this.lastTradeTimeStr, timeZone); } public TimeZone getTimeZone() { return timeZone; } public void setTimeZone(TimeZone timeZone) { this.timeZone = timeZone; } public BigDecimal getOpen() { return open; } public void setOpen(BigDecimal open) { this.open = open; } public BigDecimal getPreviousClose() { return previousClose; } public void setPreviousClose(BigDecimal previousClose) { this.previousClose = previousClose; } public BigDecimal getDayLow() { return dayLow; } public void setDayLow(BigDecimal dayLow) { this.dayLow = dayLow; } public BigDecimal getDayHigh() { return dayHigh; } public void setDayHigh(BigDecimal dayHigh) { this.dayHigh = dayHigh; } public BigDecimal getYearLow() { return yearLow; } public void setYearLow(BigDecimal yearLow) { this.yearLow = yearLow; } public BigDecimal getYearHigh() { return yearHigh; } public void setYearHigh(BigDecimal yearHigh) { this.yearHigh = yearHigh; } /** * * @return 50 day moving average */ public BigDecimal getPriceAvg50() { return priceAvg50; } public void setPriceAvg50(BigDecimal priceAvg50) { this.priceAvg50 = priceAvg50; } /** * * @return 200 day moving average */ public BigDecimal getPriceAvg200() { return priceAvg200; } public void setPriceAvg200(BigDecimal priceAvg200) { this.priceAvg200 = priceAvg200; } public Long getVolume() { return volume; } public void setVolume(Long volume) { this.volume = volume; } public Long getAvgVolume() { return avgVolume; } public void setAvgVolume(Long avgVolume) { this.avgVolume = avgVolume; } @Override public String toString() { return "Ask: " + this.ask + ", Bid: " + this.bid + ", Price: " + this.price + ", Prev close: " + this.previousClose; } }
package org.randomcoder.config; import java.util.Properties; import javax.inject.Inject; import org.randomcoder.article.*; import org.randomcoder.article.comment.*; import org.randomcoder.bo.*; import org.randomcoder.content.ContentFilter; import org.randomcoder.db.*; import org.randomcoder.springmvc.IdCommand; import org.randomcoder.tag.*; import org.randomcoder.user.*; import org.springframework.context.annotation.*; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.annotation.Order; import org.springframework.core.env.Environment; import org.springframework.core.io.ClassPathResource; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import org.springframework.web.servlet.view.*; @Configuration @SuppressWarnings("javadoc") @EnableTransactionManagement(proxyTargetClass = true) @ComponentScan("org.randomcoder.controller") @EnableWebMvc public class DispatcherContext extends WebMvcConfigurerAdapter { @Inject Environment env; @Inject ArticleDao articleDao; @Inject TagDao tagDao; @Inject UserDao userDao; @Inject RoleDao roleDao; @Inject ContentFilter contentFilter; @Inject ArticleBusiness articleBusiness; @Inject TagBusiness tagBusiness; @Inject UserBusiness userBusiness; @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer(); pspc.setIgnoreUnresolvablePlaceholders(false); return pspc; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // define some static content that will bypass the dispatcher registry .addResourceHandler("*.html", "*.css", "*.js", "*.ico", "*.jpg", "*.png", "*.gif") .addResourceLocations("classpath:/webapp/"); } @Bean @Order(0) public RequestMappingHandlerMapping annotationMapping() { RequestMappingHandlerMapping mapping = new RequestMappingHandlerMapping(); mapping.setAlwaysUseFullPath(true); mapping.setOrder(0); return mapping; } @Bean @Order(1) public SimpleUrlHandlerMapping legayMapping() { Properties p = new Properties(); p.setProperty("/account/create", "accountCreateController"); p.setProperty("/article/add", "articleAddController"); p.setProperty("/article/edit", "articleEditController"); p.setProperty("/article/delete", "articleDeleteController");
package org.skysql.jdbc.internal.mysql; import org.skysql.jdbc.internal.common.DataType; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Blob; import java.sql.Date; import java.sql.Time; public class MySQLType implements DataType { private final Type type; public MySQLType(final Type type) { this.type = type; } public Class getJavaType() { return type.getDataType(); } public int getSqlType() { return type.getSqlType(); } public String getTypeName() { return type.name(); } public Type getType() { return type; } public enum Type { DECIMAL(java.sql.Types.DECIMAL, Double.class), TINY(java.sql.Types.SMALLINT, Short.class), SHORT(java.sql.Types.SMALLINT, Short.class), LONG(java.sql.Types.INTEGER, Integer.class), FLOAT(java.sql.Types.FLOAT, Float.class), DOUBLE(java.sql.Types.DOUBLE, Double.class), NULL(java.sql.Types.NULL, null), TIMESTAMP(java.sql.Types.TIMESTAMP, Long.class), LONGLONG(java.sql.Types.BIGINT, BigInteger.class), INT24(java.sql.Types.INTEGER, Integer.class), DATETIME(java.sql.Types.DATE, Date.class), DATE(java.sql.Types.DATE, Date.class), TIME(java.sql.Types.TIME, Time.class), YEAR(java.sql.Types.SMALLINT, Short.class), BIT(java.sql.Types.BIT, Boolean.class), VARCHAR(java.sql.Types.VARCHAR, String.class), NEWDECIMAL(java.sql.Types.DECIMAL, BigDecimal.class), ENUM(java.sql.Types.VARCHAR, String.class), SET(java.sql.Types.VARCHAR, String.class), BLOB(java.sql.Types.BLOB, Blob.class), MAX(java.sql.Types.BLOB, Blob.class), CLOB(java.sql.Types.CLOB, String.class); private final int sqlType; private final Class<?> javaClass; Type(final int sqlType, final Class<?> javaClass) { this.sqlType = sqlType; this.javaClass = javaClass; } public Class getDataType() { return javaClass; } public int getSqlType() { return sqlType; } } public static MySQLType fromServer(final byte typeValue) { switch (typeValue) { case 0: return new MySQLType(Type.DECIMAL); case 1: return new MySQLType(Type.TINY); case 2: return new MySQLType(Type.SHORT); case 3: return new MySQLType(Type.LONG); case 4: return new MySQLType(Type.FLOAT); case 5: return new MySQLType(Type.DOUBLE); case 6: return new MySQLType(Type.NULL); case 7: return new MySQLType(Type.TIMESTAMP); case 8: return new MySQLType(Type.LONGLONG); case 9: return new MySQLType(Type.INT24); case 10: return new MySQLType(Type.DATE); case 11: return new MySQLType(Type.TIME); case 12: return new MySQLType(Type.DATETIME); case 13: return new MySQLType(Type.YEAR); case 14: return new MySQLType(Type.DATE); case 15: return new MySQLType(Type.VARCHAR); case 16: return new MySQLType(Type.BIT); case (byte) 0xf6: return new MySQLType(Type.NEWDECIMAL); case (byte) 0xf7: return new MySQLType(Type.ENUM); case (byte) 0xf8: return new MySQLType(Type.SET); case (byte) 0xf9: case (byte) 0xfa: case (byte) 0xfb: case (byte) 0xfc: return new MySQLType(Type.BLOB); default: return new MySQLType(Type.VARCHAR); } } }
package org.spacehq.packetlib.tcp; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageCodec; import org.spacehq.packetlib.Session; import org.spacehq.packetlib.event.session.PacketReceivedEvent; import org.spacehq.packetlib.io.NetInput; import org.spacehq.packetlib.io.NetOutput; import org.spacehq.packetlib.packet.Packet; import org.spacehq.packetlib.tcp.io.ByteBufNetInput; import org.spacehq.packetlib.tcp.io.ByteBufNetOutput; import java.util.List; public class TcpPacketCodec extends ByteToMessageCodec<Packet> { private Session session; public TcpPacketCodec(Session session) { this.session = session; } @Override public void encode(ChannelHandlerContext ctx, Packet packet, ByteBuf buf) throws Exception { NetOutput out = new ByteBufNetOutput(buf); this.session.getPacketProtocol().getPacketHeader().writePacketId(out, this.session.getPacketProtocol().getOutgoingId(packet.getClass())); packet.write(out); } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception { int initial = buf.readerIndex(); NetInput in = new ByteBufNetInput(buf); int id = this.session.getPacketProtocol().getPacketHeader().readPacketId(in); if(id == -1) { buf.readerIndex(initial); return; } Packet packet = this.session.getPacketProtocol().createIncomingPacket(id); packet.read(in); if(buf.readableBytes() > 0) { throw new IllegalStateException("Packet \"" + packet.getClass().getSimpleName() + "\" not fully read."); } if(packet.isPriority()) { this.session.callEvent(new PacketReceivedEvent(this.session, packet)); } out.add(packet); } }
package seedu.malitio.logic.commands; import java.util.Set; /** * Finds and lists all tasks in Malitio whose name contains any of the argument keywords. * Keyword matching is case sensitive. */ public class FindCommand extends Command { public static final String COMMAND_WORD = "find"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Finds all tasks whose names contain any of " + "the specified keywords (case-sensitive) and displays them as a list with index numbers.\n" + "Parameters: KEYWORD [MORE_KEYWORDS]...\n" + "Example: " + COMMAND_WORD + " alice bob charlie"; private final Set<String> keywords; public FindCommand(Set<String> keywords) { this.keywords = keywords; } @Override public CommandResult execute() { model.updateFilteredTaskList(keywords); model.updateFilteredDeadlineList(keywords); model.updateFilteredEventList(keywords); return new CommandResult(getMessageForTaskListShownSummary(model.getFilteredFloatingTaskList().size())); } }
package soot.shimple.internal; 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 java.util.Stack; import soot.Local; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.jimple.DefinitionStmt; import soot.jimple.internal.JimpleLocal; import soot.jimple.toolkits.base.Aggregator; import soot.jimple.toolkits.scalar.DeadAssignmentEliminator; import soot.jimple.toolkits.scalar.LocalNameStandardizer; import soot.jimple.toolkits.scalar.NopEliminator; import soot.jimple.toolkits.scalar.UnconditionalBranchFolder; import soot.jimple.toolkits.scalar.UnreachableCodeEliminator; import soot.options.ShimpleOptions; import soot.shimple.DefaultShimpleFactory; import soot.shimple.PhiExpr; import soot.shimple.Shimple; import soot.shimple.ShimpleBody; import soot.shimple.ShimpleFactory; import soot.toolkits.graph.Block; import soot.toolkits.graph.BlockGraph; import soot.toolkits.graph.DominatorNode; import soot.toolkits.graph.DominatorTree; import soot.toolkits.scalar.UnusedLocalEliminator; public class ShimpleBodyBuilder { protected ShimpleBody body; protected ShimpleFactory sf; protected DominatorTree<Block> dt; protected BlockGraph cfg; /** * A fixed list of all original Locals. **/ protected List<Local> origLocals; public PhiNodeManager phi; public PiNodeManager pi; final String ssaSeparator = "_$$A_"; ShimpleOptions options; /** * Transforms the provided body to pure SSA form. **/ public ShimpleBodyBuilder(ShimpleBody body) { // Must remove nops prior to building the CFG because NopStmt appearing // before the IdentityStmt in a trap handler that is itself protected // by a trap cause Phi nodes to be inserted before the NopStmt and // therefore before the IdentityStmt. This introduces a validation // problem if the Phi nodes leave residual assignment statements after // their removal. NopEliminator.v().transform(body); this.body = body; sf = new DefaultShimpleFactory(body); sf.clearCache(); phi = new PhiNodeManager(body, sf); pi = new PiNodeManager(body, false, sf); options = body.getOptions(); makeUniqueLocalNames(); } public void update() { cfg = sf.getBlockGraph(); dt = sf.getDominatorTree(); origLocals = new ArrayList<Local>(body.getLocals()); } public void transform() { phi.insertTrivialPhiNodes(); boolean change = false; if (options.extended()) { change = pi.insertTrivialPiNodes(); while (change) { if (phi.insertTrivialPhiNodes()) { change = pi.insertTrivialPiNodes(); } else { break; } } } renameLocals(); phi.trimExceptionalPhiNodes(); makeUniqueLocalNames(); } public void preElimOpt() { // boolean optElim = options.node_elim_opt(); // if(optElim) // DeadAssignmentEliminator.v().transform(body); } public void postElimOpt() { boolean optElim = options.node_elim_opt(); if (optElim) { DeadAssignmentEliminator.v().transform(body); UnreachableCodeEliminator.v().transform(body); UnconditionalBranchFolder.v().transform(body); Aggregator.v().transform(body); UnusedLocalEliminator.v().transform(body); } } /** * Remove Phi nodes from current body, high probablity this destroys SSA form. * * <p> * Dead code elimination + register aggregation are performed as recommended by Cytron. The Aggregator looks like it could * use some improvements. * * @see soot.options.ShimpleOptions **/ public void eliminatePhiNodes() { if (phi.doEliminatePhiNodes()) { makeUniqueLocalNames(); } } public void eliminatePiNodes() { boolean optElim = options.node_elim_opt(); pi.eliminatePiNodes(optElim); } /** * Maps new name Strings to Locals. **/ protected Map<String, Local> newLocals; /** * Maps renamed Locals to original Locals. **/ protected Map<Local, Local> newLocalsToOldLocal; protected int[] assignmentCounters; protected Stack<Integer>[] namingStacks; /** * Variable Renaming Algorithm from Cytron et al 91, P26-8, implemented in various bits and pieces by the next functions. * Must be called after trivial nodes have been added. **/ public void renameLocals() { update(); newLocals = new HashMap<String, Local>(); newLocalsToOldLocal = new HashMap<Local, Local>(); assignmentCounters = new int[origLocals.size()]; namingStacks = new Stack[origLocals.size()]; for (int i = 0; i < namingStacks.length; i++) { namingStacks[i] = new Stack<Integer>(); } List<Block> heads = cfg.getHeads(); if (heads.isEmpty()) { return; } if (heads.size() != 1) { throw new RuntimeException("Assertion failed: Only one head expected."); } Block entry = heads.get(0); renameLocalsSearch(entry); } /** * Driven by renameLocals(). **/ public void renameLocalsSearch(Block block) { // accumulated in Step 1 to be re-processed in Step 4 List<Local> lhsLocals = new ArrayList<Local>(); // Step 1 of 4 -- Rename block's uses (ordinary) and defs { // accumulated and re-processed in a later loop for (Unit unit : block) { // Step 1/2 of 1 { List<ValueBox> useBoxes = new ArrayList<ValueBox>(); if (!Shimple.isPhiNode(unit)) { useBoxes.addAll(unit.getUseBoxes()); } for (ValueBox useBox : useBoxes) { Value use = useBox.getValue(); int localIndex = indexOfLocal(use); // not one of our locals if (localIndex == -1) { continue; } Local localUse = (Local) use; if (namingStacks[localIndex].empty()) { continue; } Integer subscript = namingStacks[localIndex].peek(); Local renamedLocal = fetchNewLocal(localUse, subscript); useBox.setValue(renamedLocal); } } // Step 1 of 1 { if (!(unit instanceof DefinitionStmt)) { continue; } DefinitionStmt defStmt = (DefinitionStmt) unit; Value lhsValue = defStmt.getLeftOp(); // not something we're interested in if (!origLocals.contains(lhsValue)) { continue; } ValueBox lhsLocalBox = defStmt.getLeftOpBox(); Local lhsLocal = (Local) lhsValue; // re-processed in Step 4 lhsLocals.add(lhsLocal); int localIndex = indexOfLocal(lhsLocal); if (localIndex == -1) { throw new RuntimeException("Assertion failed."); } Integer subscript = assignmentCounters[localIndex]; Local newLhsLocal = fetchNewLocal(lhsLocal, subscript); lhsLocalBox.setValue(newLhsLocal); namingStacks[localIndex].push(subscript); assignmentCounters[localIndex]++; } } } // Step 2 of 4 -- Rename Phi node uses in Successors { for (Block succ : cfg.getSuccsOf(block)) { // Ignore dummy blocks if (block.getHead() == null && block.getTail() == null) { continue; } for (Unit unit : succ) { PhiExpr phiExpr = Shimple.getPhiExpr(unit); if (phiExpr == null) { continue; } // simulate whichPred int argIndex = phiExpr.getArgIndex(block); if (argIndex == -1) { throw new RuntimeException("Assertion failed."); } ValueBox phiArgBox = phiExpr.getArgBox(argIndex); Local phiArg = (Local) phiArgBox.getValue(); int localIndex = indexOfLocal(phiArg); if (localIndex == -1) { throw new RuntimeException("Assertion failed."); } if (namingStacks[localIndex].empty()) { continue; } Integer subscript = namingStacks[localIndex].peek(); Local newPhiArg = fetchNewLocal(phiArg, subscript); phiArgBox.setValue(newPhiArg); } } } // Step 3 of 4 -- Recurse over children. { DominatorNode<Block> node = dt.getDode(block); // now we recurse over children Iterator<DominatorNode<Block>> childrenIt = dt.getChildrenOf(node).iterator(); while (childrenIt.hasNext()) { DominatorNode<Block> childNode = childrenIt.next(); renameLocalsSearch(childNode.getGode()); } } // Step 4 of 4 -- Tricky name stack updates. { Iterator<Local> lhsLocalsIt = lhsLocals.iterator(); while (lhsLocalsIt.hasNext()) { Local lhsLocal = lhsLocalsIt.next(); int lhsLocalIndex = indexOfLocal(lhsLocal); if (lhsLocalIndex == -1) { throw new RuntimeException("Assertion failed."); } namingStacks[lhsLocalIndex].pop(); } } /* And we're done. The renaming process is complete. */ } /** * Clever convenience function to fetch or create new Local's given a Local and the desired subscript. **/ protected Local fetchNewLocal(Local local, Integer subscript) { Local oldLocal = local; if (!origLocals.contains(local)) { oldLocal = newLocalsToOldLocal.get(local); } if (subscript.intValue() == 0) { return oldLocal; } // If the name already exists, makeUniqueLocalNames() will // take care of it. String name = oldLocal.getName() + ssaSeparator + subscript; Local newLocal = newLocals.get(name); if (newLocal == null) { newLocal = new JimpleLocal(name, oldLocal.getType()); newLocals.put(name, newLocal); newLocalsToOldLocal.put(newLocal, oldLocal); // add proper Local declation body.getLocals().add(newLocal); } return newLocal; } /** * Convenient function that maps new Locals to the originating Local, and finds the appropriate array index into the naming * structures. **/ protected int indexOfLocal(Value local) { int localIndex = origLocals.indexOf(local); if (localIndex == -1) { // might be null Local oldLocal = newLocalsToOldLocal.get(local); localIndex = origLocals.indexOf(oldLocal); } return localIndex; } /** * Make sure the locals in the given body all have unique String names. Renaming is done if necessary. **/ public void makeUniqueLocalNames() { if (options.standard_local_names()) { LocalNameStandardizer.v().transform(body); return; } Set<String> localNames = new HashSet<String>(); Iterator<Local> localsIt = body.getLocals().iterator(); while (localsIt.hasNext()) { Local local = localsIt.next(); String localName = local.getName(); if (localNames.contains(localName)) { String uniqueName = makeUniqueLocalName(localName, localNames); local.setName(uniqueName); localNames.add(uniqueName); } else { localNames.add(localName); } } } /** * Given a set of Strings, return a new name for dupName that is not currently in the set. **/ public String makeUniqueLocalName(String dupName, Set<String> localNames) { int counter = 1; String newName = dupName; while (localNames.contains(newName)) { newName = dupName + ssaSeparator + counter++; } return newName; } }
package net.sourceforge.jtds.jdbc; import java.sql.*; /** * Implements a cursor-based <code>ResultSet</code>. Implementation is based on * the undocumented <code>sp_cursor</code> procedures. * * @created March 16, 2001 * @version 2.0 */ public class CursorResultSet extends AbstractResultSet implements OutputParamHandler { public static final int FETCH_FIRST = 1; public static final int FETCH_NEXT = 2; public static final int FETCH_PREVIOUS = 4; public static final int FETCH_LAST = 8; public static final int FETCH_ABSOLUTE = 16; public static final int FETCH_RELATIVE = 32; public static final int FETCH_REPEAT = 128; public static final int FETCH_INFO = 256; public static final int CURSOR_TYPE_KEYSET = 1; public static final int CURSOR_TYPE_DYNAMIC = 2; public static final int CURSOR_TYPE_FORWARD = 4; public static final int CURSOR_TYPE_STATIC = 8; public static final int CURSOR_CONCUR_READ_ONLY = 1; public static final int CURSOR_CONCUR_SCROLL_LOCKS = 2; public static final int CURSOR_CONCUR_OPTIMISTIC = 4; public static final int CURSOR_OP_INSERT = 4; public static final int CURSOR_OP_UPDATE = 33; public static final int CURSOR_OP_DELETE = 34; /** * The row is unchanged. */ public static final int SQL_ROW_SUCCESS = 1; /** * The row has been deleted. */ public static final int SQL_ROW_DELETED = 2; // @todo Check the values for the constants below (above are ok). /** * The row has been updated. */ public static final int SQL_ROW_UPDATED = 3; /** * There is no row that corresponds this position. */ public static final int SQL_ROW_NOROW = 4; /** * The row has been added. */ public static final int SQL_ROW_ADDED = 5; /** * The row is unretrievable due to an error. */ public static final int SQL_ROW_ERROR = 6; private static final int POS_BEFORE_FIRST = -100000; private static final int POS_AFTER_LAST = -200000; private int pos = POS_BEFORE_FIRST; private Integer cursorHandle; private int rowsInResult; private String sql; private TdsStatement stmt; private TdsConnection conn; private int direction = FETCH_FORWARD; private boolean open = false; private Context context; private PacketRowResult current; /** * Parameter list used for calling stored procedures. */ private ParameterListItem[] parameterList; /** * Stores return values from stored procedure calls. */ private Integer retVal; /** * Index of the last output parameter. */ private int lastOutParam = -1; private int type; private int concurrency; /** * Set when <code>moveToInsertRow()</code> was called. */ private boolean onInsertRow = false; /** * The "insert row". */ private PacketRowResult insertRow; public Context getContext() { return context; } public CursorResultSet(TdsStatement stmt, String sql, int fetchDir) throws SQLException { this.stmt = stmt; this.conn = (TdsConnection) stmt.getConnection(); this.sql = sql; this.direction = fetchDir == FETCH_UNKNOWN ? FETCH_FORWARD : fetchDir; this.type = stmt.getResultSetType(); this.concurrency = stmt.getResultSetConcurrency(); // SAfe Until we're actually created use the Statement's warning chain. warningChain = stmt.warningChain; cursorCreate(); // SAfe Now we can create our own warning chain. warningChain = new SQLWarningChain(); } protected void finalize() { try { close(); } catch (SQLException ex) { } } public void setFetchDirection(int direction) throws SQLException { switch (direction) { case FETCH_UNKNOWN: case FETCH_REVERSE: if (type != ResultSet.TYPE_FORWARD_ONLY) { throw new SQLException("ResultSet is forward-only."); } // Fall through case FETCH_FORWARD: this.direction = direction; break; default: throw new SQLException("Invalid fetch direction: "+direction); } } public void setFetchSize(int rows) throws SQLException { } public String getCursorName() throws SQLException { throw new SQLException("Positioned update not supported."); } public boolean isBeforeFirst() throws SQLException { return (pos == POS_BEFORE_FIRST) && (rowsInResult != 0); } public boolean isAfterLast() throws SQLException { return (pos == POS_AFTER_LAST) && (rowsInResult != 0); } public boolean isFirst() throws SQLException { return pos == 1; } public boolean isLast() throws SQLException { return pos == rowsInResult; } public int getRow() throws SQLException { return pos>0 ? pos : 0; } public int getFetchDirection() throws SQLException { return direction; } public int getFetchSize() throws SQLException { return 1; } public int getType() throws SQLException { return type; } public int getConcurrency() throws SQLException { return concurrency; } public Statement getStatement() throws SQLException { return stmt; } public void close() throws SQLException { if (open) { try { warningChain.clearWarnings(); cursorClose(); } finally { open = false; stmt = null; conn = null; } } warningChain.checkForExceptions(); } public SQLWarning getWarnings() throws SQLException { return warningChain.getWarnings(); } public boolean next() throws SQLException { if (cursorFetch(FETCH_NEXT, 0)) { pos += (pos < 0) ? (1-pos) : 1; return true; } else { pos = POS_AFTER_LAST; return false; } } public void clearWarnings() throws SQLException { warningChain.clearWarnings(); } public void beforeFirst() throws SQLException { if (pos != POS_BEFORE_FIRST) { cursorFetch(FETCH_ABSOLUTE, 0); pos = POS_BEFORE_FIRST; } } public void afterLast() throws SQLException { if (pos != POS_AFTER_LAST) { cursorFetch(FETCH_ABSOLUTE, rowsInResult + 1); pos = POS_AFTER_LAST; } } public boolean first() throws SQLException { boolean res = cursorFetch(FETCH_FIRST, 0); pos = 1; return res; } public boolean last() throws SQLException { boolean res = cursorFetch(FETCH_LAST, 0); pos = rowsInResult; return res; } public boolean absolute(int row) throws SQLException { // If nothing was fetched, we got passed the beginning or end if (!cursorFetch(FETCH_ABSOLUTE, row)) { if (row > 0) { pos = POS_AFTER_LAST; } else { pos = POS_BEFORE_FIRST; } return false; } pos = row; return true; } public boolean relative(int rows) throws SQLException { if (!cursorFetch(FETCH_RELATIVE, rows)) { if (rows > 0) { pos = POS_AFTER_LAST; } else { pos = POS_BEFORE_FIRST; } return false; } // If less than 0, it can only be POS_BEFORE_FIRST or POS_AFTER_LAST if( pos < 0 ) { if( pos == POS_BEFORE_FIRST ) { pos = 0; } else { pos = rowsInResult; } } pos += rows; return true; } public boolean previous() throws SQLException { if (cursorFetch(FETCH_PREVIOUS, 0)) { pos -= (pos < 0) ? (pos-rowsInResult) : 1; return true; } else { pos = POS_BEFORE_FIRST; return false; } } public boolean rowUpdated() throws SQLException { return getRowStat() == SQL_ROW_UPDATED; } private int getRowStat() throws SQLException { return (int) current.getLong( context.getColumnInfo().realColumnCount()); } public boolean rowInserted() throws SQLException { return getRowStat() == this.SQL_ROW_ADDED; } public boolean rowDeleted() throws SQLException { return getRowStat() == SQL_ROW_DELETED; } public void cancelRowUpdates() throws SQLException { if (onInsertRow) { throw new SQLException("The cursor is on the insert row."); } refreshRow(); } public void moveToInsertRow() throws SQLException { onInsertRow = true; } public void moveToCurrentRow() throws SQLException { onInsertRow = false; } public PacketRowResult currentRow() throws SQLException { if (onInsertRow) { if (insertRow == null) { insertRow = new PacketRowResult(context); } return insertRow; } if (current == null) { throw new SQLException("No current row in the ResultSet"); } return current; } public void insertRow() throws SQLException { if (!onInsertRow) { throw new SQLException("The cursor is not on the insert row."); } // This might just happen if the ResultSet has no writeable column. // Very unlikely and very stupid, but who knows? if (insertRow == null) { insertRow = new PacketRowResult(context); } cursor(CURSOR_OP_INSERT, insertRow); insertRow = new PacketRowResult(context); } public void updateRow() throws SQLException { if (current == null) { throw new SQLException("No current row in the ResultSet"); } if (onInsertRow) { throw new SQLException("The cursor is on the insert row."); } cursor(CURSOR_OP_UPDATE, current); refreshRow(); } public void deleteRow() throws SQLException { if (current == null) { throw new SQLException("No current row in the ResultSet"); } if (onInsertRow) { throw new SQLException("The cursor is on the insert row."); } cursor(CURSOR_OP_DELETE, null); cursorFetch(FETCH_REPEAT, 1); } public void refreshRow() throws SQLException { if (onInsertRow) { throw new SQLException("The cursor is on the insert row."); } cursorFetch(FETCH_REPEAT, 1); } private void cursorCreate() throws SQLException { warningChain.clearWarnings(); parameterList = new ParameterListItem[5]; int scrollOpt, ccOpt; switch (type) { case TYPE_SCROLL_INSENSITIVE: scrollOpt = CURSOR_TYPE_STATIC; break; case TYPE_SCROLL_SENSITIVE: scrollOpt = CURSOR_TYPE_KEYSET; break; case TYPE_FORWARD_ONLY: default: scrollOpt = CURSOR_TYPE_FORWARD; break; } switch (concurrency) { case CONCUR_READ_ONLY: default: ccOpt = CURSOR_CONCUR_READ_ONLY; break; case CONCUR_UPDATABLE: ccOpt = CURSOR_CONCUR_SCROLL_LOCKS; break; } ParameterListItem param[] = parameterList; // Setup cursor handle param param[0] = new ParameterListItem(); param[0].isSet = true; param[0].type = Types.INTEGER; param[0].isOutput = true; // Setup statement param param[1] = new ParameterListItem(); param[1].isSet = true; param[1].type = Types.LONGVARCHAR; param[1].maxLength = Integer.MAX_VALUE; param[1].formalType = "ntext"; param[1].value = sql; // Setup scroll options param[2] = new ParameterListItem(); param[2].isSet = true; param[2].type = Types.INTEGER; param[2].value = new Integer(scrollOpt); param[2].isOutput = true; // Setup concurrency options param[3] = new ParameterListItem(); param[3].isSet = true; param[3].type = Types.INTEGER; param[3].value = new Integer(ccOpt); param[3].isOutput = true; // Setup numRows parameter param[4] = new ParameterListItem(); param[4].isSet = true; param[4].type = Types.INTEGER; param[4].isOutput = true; lastOutParam = -1; retVal = null; // SAfe We have to synchronize this, in order to avoid mixing up our // actions with another CursorResultSet's and eating up its // results. synchronized (conn.mainTdsMonitor) { stmt.outParamHandler = this; Tds tds = conn.allocateTds(true); try { tds.executeProcedure("sp_cursoropen", param, param, stmt, warningChain, stmt.getQueryTimeout(), false); // @todo Should maybe use a different statement here if (stmt.getMoreResults(tds, warningChain, true)) { context = stmt.results.context; // Hide rowstat column. context.getColumnInfo().setFakeColumnCount( context.getColumnInfo().realColumnCount() - 1); stmt.results.close(); } else { warningChain.addException(new SQLException( "Expected a ResultSet.")); } if (stmt.getMoreResults(tds, warningChain, true) || (stmt.getUpdateCount() != -1)) { warningChain.addException(new SQLException( "No more results expected.")); } } finally { try { conn.freeTds(tds); } catch (TdsException ex) { warningChain.addException( new SQLException(ex.getMessage())); } lastOutParam = -1; retVal = null; stmt.outParamHandler = null; } } cursorHandle = (Integer) param[0].value; rowsInResult = ((Number) param[4].value).intValue(); int actualScroll = ((Number) param[2].value).intValue(); int actualCc = ((Number) param[3].value).intValue(); if ((actualScroll != scrollOpt) || (actualCc != ccOpt)) { if (actualScroll != scrollOpt) { switch (actualScroll) { case CURSOR_TYPE_FORWARD: type = TYPE_FORWARD_ONLY; break; case CURSOR_TYPE_STATIC: type = TYPE_SCROLL_INSENSITIVE; break; case CURSOR_TYPE_DYNAMIC: case CURSOR_TYPE_KEYSET: type = TYPE_SCROLL_SENSITIVE; break; default: warningChain.addException(new SQLException( "Don't know how to handle cursor type " + actualScroll)); } } if (actualCc != ccOpt) { switch (actualCc) { case CURSOR_CONCUR_READ_ONLY: concurrency = CONCUR_READ_ONLY; break; case CURSOR_CONCUR_SCROLL_LOCKS: case CURSOR_CONCUR_OPTIMISTIC: concurrency = CONCUR_UPDATABLE; break; default: warningChain.addException(new SQLException( "Don't know how to handle concurrency type " + actualScroll)); } } // @todo This warning should somehow go to the Statement warningChain.addWarning(new SQLWarning( "ResultSet type/concurrency downgraded.")); } if ((retVal == null) || (retVal.intValue() != 0)) { warningChain.addException( new SQLException("Cursor open failed.")); } warningChain.checkForExceptions(); open = true; } private boolean cursorFetch(int fetchType, int rowNum) throws SQLException { warningChain.clearWarnings(); ParameterListItem param[] = new ParameterListItem[4]; System.arraycopy(parameterList, 0, param, 0, 4); boolean isInfo = (fetchType == FETCH_INFO); if (fetchType != FETCH_ABSOLUTE && fetchType != FETCH_RELATIVE) rowNum = 1; // Setup cursor handle param param[0].clear(); param[0].isSet = true; param[0].type = Types.INTEGER; param[0].value = cursorHandle; // Setup fetchtype param param[1].clear(); param[1].isSet = true; param[1].type = Types.INTEGER; param[1].value = new Integer(fetchType); // Setup rownum param[2].clear(); param[2].isSet = true; param[2].type = Types.INTEGER; param[2].value = isInfo ? null : new Integer(rowNum); param[2].isOutput = isInfo; // Setup numRows parameter param[3].clear(); param[3].isSet = true; param[3].type = Types.INTEGER; param[3].value = isInfo ? null : new Integer(1); param[3].isOutput = isInfo; lastOutParam = -1; retVal = null; // SAfe We have to synchronize this, in order to avoid mixing up our // actions with another CursorResultSet's and eating up its // results. synchronized (conn.mainTdsMonitor) { stmt.outParamHandler = this; Tds tds = conn.allocateTds(true); try { tds.executeProcedure("sp_cursorfetch", param, param, stmt, warningChain, stmt.getQueryTimeout(), true); current = tds.fetchRow(stmt, warningChain, context); // @todo Should maybe use a different statement here if (stmt.getMoreResults(tds, warningChain, true) || (stmt.getUpdateCount() != -1)) { warningChain.addException(new SQLException( "No results expected.")); } if ((retVal == null) || (retVal.intValue() != 0)) { warningChain.addException( new SQLException("Cursor fetch failed.")); } } finally { try { conn.freeTds(tds); } catch (TdsException ex) { warningChain.addException( new SQLException(ex.getMessage())); } lastOutParam = -1; retVal = null; stmt.outParamHandler = null; } } warningChain.checkForExceptions(); return current != null; } private void cursorClose() throws SQLException { warningChain.clearWarnings(); ParameterListItem param[] = new ParameterListItem[1]; param[0] = parameterList[0]; // Setup cursor handle param param[0].clear(); param[0].isSet = true; param[0].type = Types.INTEGER; param[0].value = cursorHandle; lastOutParam = -1; retVal = null; // SAfe We have to synchronize this, in order to avoid mixing up our // actions with another CursorResultSet's and eating up its // results. synchronized (conn.mainTdsMonitor) { stmt.outParamHandler = this; Tds tds = conn.allocateTds(true); try { tds.executeProcedure("sp_cursorclose", param, param, stmt, warningChain, stmt.getQueryTimeout(), false); // @todo Should maybe use a different statement here if (stmt.getMoreResults(tds, warningChain, true) || (stmt.getUpdateCount() != -1)) { warningChain.addException(new SQLException( "No results expected.")); } if ((retVal == null) || (retVal.intValue() != 0)) { warningChain.addException( new SQLException("Cursor close failed.")); } } finally { try { conn.freeTds(tds); } catch (TdsException ex) { warningChain.addException( new SQLException(ex.getMessage())); } lastOutParam = -1; retVal = null; stmt.outParamHandler = null; } } warningChain.checkForExceptions(); } private void cursor(int opType, PacketRowResult row) throws SQLException { warningChain.clearWarnings(); ParameterListItem param[]; if (opType == CURSOR_OP_DELETE) { if (row != null) { throw new SQLException( "Non-null row provided to delete operation."); } // 3 parameters for delete param = new ParameterListItem[3]; System.arraycopy(parameterList, 0, param, 0, 3); } else { if (row == null) { throw new SQLException( "Null row provided to insert/update operation."); } // 4 parameters plus one for each column for insert/update param = new ParameterListItem[4 + row.context.getColumnInfo().fakeColumnCount()]; System.arraycopy(parameterList, 0, param, 0, 4); } // Setup cursor handle param param[0].clear(); param[0].isSet = true; param[0].type = Types.INTEGER; param[0].value = cursorHandle; // Setup optype param param[1].clear(); param[1].isSet = true; param[1].type = Types.INTEGER; param[1].value = new Integer(opType); // Setup rownum param[2].clear(); param[2].isSet = true; param[2].type = Types.INTEGER; param[2].value = new Integer(1); // If row is not null, we're dealing with an insert/update if (row != null) { // Setup table param[3].clear(); param[3].isSet = true; param[3].type = Types.VARCHAR; param[3].value = ""; param[3].formalType = "nvarchar(4000)"; param[3].maxLength = 4000; Columns cols = row.context.getColumnInfo(); int colCnt = cols.fakeColumnCount(); // Current column; we should only update/insert columns // that are not read-only (such as identity columns) int crtCol = 4; for (int i=1; i <= colCnt; i++) { // Only send non-read-only columns if (!cols.isReadOnly(i).booleanValue()) { param[crtCol] = new ParameterListItem(); param[crtCol].isSet = true; param[crtCol].type = cols.getJdbcType(i); param[crtCol].value = row.getObject(i); param[crtCol].formalName = '@' + cols.getName(i); param[crtCol].maxLength = cols.getBufferSize(i); param[crtCol].scale = cols.getScale(i); // This is only for Tds.executeProcedureInternal to // know that it's a Unicode column switch (cols.getNativeType(i)) { case TdsDefinitions.SYBBIGNVARCHAR: case TdsDefinitions.SYBNVARCHAR: case TdsDefinitions.SYBNCHAR: param[crtCol].formalType = "nvarchar(4000)"; break; case TdsDefinitions.SYBNTEXT: param[crtCol].formalType = "ntext"; break; } crtCol++; } else { if (row.getObject(i) != null) throw new SQLException( "Column " + i + "/" + cols.getName(i) + " is read-only."); } } // If the count is different (i.e. there were read-only // columns) reallocate the parameters into a shorter array if (crtCol != colCnt+4) { ParameterListItem[] newParam = new ParameterListItem[crtCol]; System.arraycopy(param, 0, newParam, 0, crtCol); param = newParam; } } lastOutParam = -1; retVal = null; // SAfe We have to synchronize this, in order to avoid mixing up our // actions with another CursorResultSet's and eating up its // results. synchronized (conn.mainTdsMonitor) { stmt.outParamHandler = this; Tds tds = conn.allocateTds(true); try { tds.executeProcedure("sp_cursor", param, param, stmt, warningChain, stmt.getQueryTimeout(), false); // @todo Should maybe use a different statement here if (stmt.getMoreResults(tds, warningChain, true) || (stmt.getUpdateCount() != -1)) { warningChain.addException(new SQLException( "No results expected.")); } if ((retVal == null) || (retVal.intValue() != 0)) { warningChain.addException( new SQLException("Cursor operation failed.")); } } finally { try { conn.freeTds(tds); } catch (TdsException ex) { warningChain.addException( new SQLException(ex.getMessage())); } lastOutParam = -1; retVal = null; stmt.outParamHandler = null; } } warningChain.checkForExceptions(); } /** * Handle a return status. * * @param packet a RetStat packet */ public boolean handleRetStat(PacketRetStatResult packet) { retVal = new Integer(packet.getRetStat()); return true; } /** * Handle an output parameter. * * @param packet an OutputParam packet * @throws SQLException if there is a handling exception */ public boolean handleParamResult(PacketOutputParamResult packet) throws SQLException { for (lastOutParam++; lastOutParam < parameterList.length; lastOutParam++) if (parameterList[lastOutParam].isOutput) { parameterList[lastOutParam].value = packet.value; return true; } throw new SQLException("More output params than expected."); } }
package viewer.render; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import net.imglib2.Cursor; import net.imglib2.FinalInterval; import net.imglib2.IterableInterval; import net.imglib2.RandomAccess; import net.imglib2.RandomAccessible; import net.imglib2.RandomAccessibleInterval; import net.imglib2.Volatile; import net.imglib2.converter.Converter; import net.imglib2.img.Img; import net.imglib2.img.array.ArrayImgs; import net.imglib2.type.numeric.NumericType; import net.imglib2.type.numeric.integer.ByteType; import net.imglib2.ui.AbstractInterruptibleProjector; import net.imglib2.ui.util.StopWatch; import net.imglib2.view.Views; import viewer.hdf5.img.CacheIoTiming; import viewer.hdf5.img.CacheIoTiming.IoStatistics; /** * {@link Projector} for a hierarchy of {@link Volatile} inputs. After each * {@link #map()} call, the projector has a {@link #isValid() state} that * signalizes whether all projected pixels were perfect. * * @author Stephan Saalfeld <saalfeld@mpi-cbg.de> * @author Tobias Pietzsch <tobias.pietzsch@gmail.com> */ public class VolatileHierarchyProjector< A extends Volatile< ? >, B extends NumericType< B > > extends AbstractInterruptibleProjector< A, B > implements VolatileProjector { final protected ArrayList< RandomAccessible< A > > sources = new ArrayList< RandomAccessible< A > >(); final private byte[] maskArray; final protected Img< ByteType > mask; protected volatile boolean valid = false; protected int numInvalidLevels; /** * Extends of the source to be used for mapping. */ final protected FinalInterval sourceInterval; /** * Target width */ final protected int width; /** * Target height */ final protected int height; /** * Steps for carriage return. Typically -{@link #width} */ final protected int cr; /** * A reference to the target image as an iterable. Used for source-less * operations such as clearing its content. */ final protected IterableInterval< B > iterableTarget; /** * Number of threads to use for rendering */ final protected int numThreads; /** * Time needed for rendering the last frame, in nano-seconds. */ protected long lastFrameRenderNanoTime; /** * TODO */ // TODO move to derived implementation for local sources only protected long lastFrameIoNanoTime; final protected AtomicBoolean interrupted = new AtomicBoolean(); public VolatileHierarchyProjector( final List< ? extends RandomAccessible< A > > sources, final Converter< ? super A, B > converter, final RandomAccessibleInterval< B > target, final int numThreads ) { this( sources, converter, target, new byte[ ( int ) ( target.dimension( 0 ) * target.dimension( 1 ) ) ], numThreads ); } public VolatileHierarchyProjector( final List< ? extends RandomAccessible< A > > sources, final Converter< ? super A, B > converter, final RandomAccessibleInterval< B > target, final byte[] maskArray, final int numThreads ) { super( Math.max( 2, sources.get( 0 ).numDimensions() ), converter, target ); this.sources.addAll( sources ); numInvalidLevels = sources.size(); this.maskArray = maskArray; mask = ArrayImgs.bytes( maskArray, target.dimension( 0 ), target.dimension( 1 ) ); iterableTarget = Views.iterable( target ); for ( int d = 2; d < min.length; ++d ) min[ d ] = max[ d ] = 0; max[ 0 ] = target.max( 0 ); max[ 1 ] = target.max( 1 ); sourceInterval = new FinalInterval( min, max ); width = ( int )target.dimension( 0 ); height = ( int )target.dimension( 1 ); cr = -width; this.numThreads = numThreads; lastFrameRenderNanoTime = -1; clearMask(); } @Override public void cancel() { interrupted.set( true ); } @Override public long getLastFrameRenderNanoTime() { return lastFrameRenderNanoTime; } public long getLastFrameIoNanoTime() { return lastFrameIoNanoTime; } @Override public boolean isValid() { return valid; } /** * Set all pixels in target to 100% transparent zero, and mask to all * Integer.MAX_VALUE. */ public void clearMask() { Arrays.fill( maskArray, 0, ( int ) mask.size(), Byte.MAX_VALUE ); numInvalidLevels = sources.size(); } /** * Clear target pixels that were never written. */ protected void clearUntouchedTargetPixels() { final Cursor< ByteType > maskCursor = mask.cursor(); for ( final B t : iterableTarget ) if ( maskCursor.next().get() == Byte.MAX_VALUE ) t.setZero(); } @Override public boolean map() { return map( true ); } @Override public boolean map( final boolean clearUntouchedTargetPixels ) { interrupted.set( false ); final StopWatch stopWatch = new StopWatch(); stopWatch.start(); final IoStatistics iostat = CacheIoTiming.getThreadGroupIoStatistics(); final long startTimeIo = iostat.getIoNanoTime(); final long startTimeIoCumulative = iostat.getCumulativeIoNanoTime(); final long startIoBytes = iostat.getIoBytes(); final int numTasks; if ( numThreads > 1 ) { numTasks = Math.max( numThreads * 10, height ); } else numTasks = 1; final double taskHeight = ( double )height / numTasks; int i; valid = false; final ExecutorService ex = Executors.newFixedThreadPool( numThreads ); for ( i = 0; i < numInvalidLevels && !valid; ++i ) { final byte iFinal = ( byte ) i; valid = true; final ArrayList< Callable< Void > > tasks = new ArrayList< Callable< Void > >( numTasks ); for ( int taskNum = 0; taskNum < numTasks; ++taskNum ) { final int myOffset = width * ( int ) ( taskNum * taskHeight ); final long myMinY = min[ 1 ] + ( int ) ( taskNum * taskHeight ); final int myHeight = ( int ) ( ( (taskNum == numTasks - 1 ) ? height : ( int ) ( ( taskNum + 1 ) * taskHeight ) ) - myMinY - min[ 1 ] ); final Callable< Void > r = new Callable< Void >() { @Override public Void call() { if ( interrupted.get() ) return null; final RandomAccess< B > targetRandomAccess = target.randomAccess( target ); final Cursor< ByteType > maskCursor = mask.cursor(); final RandomAccess< A > sourceRandomAccess = sources.get( iFinal ).randomAccess( sourceInterval ); boolean myValid = true; sourceRandomAccess.setPosition( min ); sourceRandomAccess.setPosition( myMinY, 1 ); targetRandomAccess.setPosition( min[ 0 ], 0 ); targetRandomAccess.setPosition( myMinY, 1 ); maskCursor.jumpFwd( myOffset ); for ( int y = 0; y < myHeight; ++y ) { if ( interrupted.get() ) return null; for ( int x = 0; x < width; ++x ) { final ByteType m = maskCursor.next(); if ( m.get() > iFinal ) { final A a = sourceRandomAccess.get(); final boolean v = a.isValid(); if ( v ) { converter.convert( a, targetRandomAccess.get() ); m.set( iFinal ); } else myValid = false; } sourceRandomAccess.fwd( 0 ); targetRandomAccess.fwd( 0 ); } sourceRandomAccess.move( cr, 0 ); targetRandomAccess.move( cr, 0 ); sourceRandomAccess.fwd( 1 ); targetRandomAccess.fwd( 1 ); } if ( !myValid ) valid = false; return null; } }; tasks.add( r ); } try { ex.invokeAll( tasks ); } catch ( final InterruptedException e ) { e.printStackTrace(); } if ( interrupted.get() ) { // System.out.println( "interrupted" ); ex.shutdown(); return false; } } ex.shutdown(); if ( clearUntouchedTargetPixels && !interrupted.get() ) clearUntouchedTargetPixels(); final long lastFrameTime = stopWatch.nanoTime(); // final long numIoBytes = iostat.getIoBytes() - startIoBytes; lastFrameIoNanoTime = iostat.getIoNanoTime() - startTimeIo; lastFrameRenderNanoTime = lastFrameTime - ( iostat.getCumulativeIoNanoTime() - startTimeIoCumulative ) / numThreads; System.out.println( "lastFrameTime = " + lastFrameTime / 1000000 ); System.out.println( "lastFrameRenderNanoTime = " + lastFrameRenderNanoTime / 1000000 ); if ( valid ) numInvalidLevels = i - 1; valid = numInvalidLevels == 0; // System.out.println( "Mapping complete after " + ( s + 1 ) + " levels." ); return !interrupted.get(); } }
package yokohama.unit.translator; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.util.Optional; import lombok.SneakyThrows; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; import yokohama.unit.ast.Group; import yokohama.unit.ast_junit.CompilationUnit; import yokohama.unit.grammar.YokohamaUnitLexer; import yokohama.unit.grammar.YokohamaUnitParser; import yokohama.unit.grammar.YokohamaUnitParser.GroupContext; public class TranslatorUtils { public static class TranslationException extends RuntimeException { } private static class ErrorListener extends BaseErrorListener { public int numErrors = 0; @Override public void syntaxError( Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { numErrors++; } } public static Group parseDocy(final String input) { return parseDocy(input, YokohamaUnitLexer.DEFAULT_MODE); } @SneakyThrows(IOException.class) public static Group parseDocy(final String input, final int mode) { ErrorListener errorListener = new ErrorListener(); InputStream bais = new ByteArrayInputStream(input.getBytes()); CharStream stream = new ANTLRInputStream(bais); Lexer lex = new YokohamaUnitLexer(stream); lex.mode(mode); lex.addErrorListener(errorListener); CommonTokenStream tokens = new CommonTokenStream(lex); YokohamaUnitParser parser = new YokohamaUnitParser(tokens); parser.addErrorListener(errorListener); GroupContext ctx = parser.group(); if (errorListener.numErrors > 0) { throw new TranslationException(); } return new ParseTreeToAstVisitor().visitGroup(ctx); } public static String docyToJava( final Optional<Path> docyPath, final String docy, final String className, final String packageName) { // Source to AST Group ast = parseDocy(docy); // AST to JUnit AST CompilationUnit junit = new AstToJUnitAst( docyPath, className, packageName, new OgnlExpressionStrategy(), new MockitoMockStrategy() ).translate(className, ast, packageName); // JUnit AST to string return junit.getText(); } }
package voldemort.server.storage; import java.io.ByteArrayInputStream; import java.io.File; import java.util.List; import java.util.Properties; import junit.framework.TestCase; import voldemort.MockTime; import voldemort.ServerTestUtils; import voldemort.TestUtils; import voldemort.cluster.Cluster; import voldemort.common.service.SchedulerService; import voldemort.server.StoreRepository; import voldemort.server.VoldemortConfig; import voldemort.store.Store; import voldemort.store.StoreDefinition; import voldemort.store.metadata.MetadataStore; import voldemort.store.system.SystemStoreConstants; import voldemort.utils.ByteArray; import voldemort.versioning.Versioned; /** * Test that the storage service is able to load all stores. * * */ public class StorageServiceTest extends TestCase { private Cluster cluster; private StoreRepository storeRepository; private StorageService storage; private SchedulerService scheduler; private List<StoreDefinition> storeDefs; @Override public void setUp() { File temp = TestUtils.createTempDir(); VoldemortConfig config = new VoldemortConfig(0, temp.getAbsolutePath()); config.setEnableServerRouting(true); // this is turned off by default new File(config.getMetadataDirectory()).mkdir(); config.setBdbCacheSize(100000); this.scheduler = new SchedulerService(1, new MockTime()); this.cluster = ServerTestUtils.getLocalCluster(1); this.storeDefs = ServerTestUtils.getStoreDefs(2); this.storeRepository = new StoreRepository(); MetadataStore mdStore = ServerTestUtils.createMetadataStore(cluster, storeDefs); storage = new StorageService(storeRepository, mdStore, scheduler, config); storage.start(); } public void testStores() { StoreRepository repo = storage.getStoreRepository(); for(StoreDefinition def: storeDefs) { // test local stores assertTrue("Missing local store '" + def.getName() + "'.", repo.hasLocalStore(def.getName())); assertEquals(def.getName(), repo.getLocalStore(def.getName()).getName()); assertTrue("Missing storage engine '" + def.getName() + "'.", repo.hasStorageEngine(def.getName())); assertEquals(def.getName(), repo.getStorageEngine(def.getName()).getName()); for(int node = 0; node < cluster.getNumberOfNodes(); node++) { assertTrue("Missing node store '" + def.getName() + "'.", repo.hasNodeStore(def.getName(), node)); assertEquals(def.getName(), repo.getNodeStore(def.getName(), node).getName()); } } } public void testMetadataVersionsInit() { Store<ByteArray, byte[], byte[]> versionStore = storeRepository.getLocalStore(SystemStoreConstants.SystemStoreName.voldsys$_metadata_version_persistence.name()); Properties props = new Properties(); try { ByteArray metadataVersionsKey = new ByteArray(StorageService.VERSIONS_METADATA_STORE.getBytes()); List<Versioned<byte[]>> versionList = versionStore.get(metadataVersionsKey, null); if(versionList != null && versionList.size() > 0) { byte[] versionsByteArray = versionList.get(0).getValue(); if(versionsByteArray != null) { props.load(new ByteArrayInputStream(versionsByteArray)); } else { fail("Illegal value returned for metadata key: " + StorageService.VERSIONS_METADATA_STORE); } } else { fail("Illegal value returned for metadata key: " + StorageService.VERSIONS_METADATA_STORE); } // Check if version exists for cluster.xml if(!props.containsKey(StorageService.CLUSTER_VERSION_KEY)) { fail(StorageService.CLUSTER_VERSION_KEY + " not present in " + StorageService.VERSIONS_METADATA_STORE); } // Check if version exists for stores.xml if(!props.containsKey(StorageService.STORES_VERSION_KEY)) { fail(StorageService.STORES_VERSION_KEY + " not present in " + StorageService.VERSIONS_METADATA_STORE); } // Check if version exists for each store for(StoreDefinition def: storeDefs) { if(!props.containsKey(def.getName())) { fail(def.getName() + " store not present in " + StorageService.VERSIONS_METADATA_STORE); } } } catch(Exception e) { fail("Error in retrieving : " + StorageService.VERSIONS_METADATA_STORE + " key from " + SystemStoreConstants.SystemStoreName.voldsys$_metadata_version_persistence.name() + " store. "); } } }
// 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.io.Serializable; import java.io.PrintWriter; import java.sql.SQLException; import javax.sql.DataSource; import javax.naming.NamingException; import javax.naming.Reference; import javax.naming.Referenceable; import javax.naming.StringRefAddr; import net.sourceforge.jtds.jdbc.Driver; import net.sourceforge.jtds.jdbc.Support; import net.sourceforge.jtds.jdbc.TdsCore; import net.sourceforge.jtds.util.Logger; /** * An abstract <code>DataSource</code> implementation. * * @author Alin Sinplean * @since jTDS 0.3 * @version $Id: AbstractDataSource.java,v 1.10 2004-08-03 17:48:39 ddkilzer Exp $ */ abstract class AbstractDataSource implements DataSource, Referenceable, Serializable { protected int loginTimeout = 0; protected String databaseName = ""; protected int portNumber = TdsCore.DEFAULT_SQLSERVER_PORT; protected String serverName; protected String user; protected String password = ""; protected String description; protected String tds = "7.0"; protected int serverType = Driver.SQLSERVER; protected String charset = ""; protected String language = ""; protected String domain = ""; protected String instance = ""; protected boolean lastUpdateCount = false; protected boolean sendStringParametersAsUnicode = true; protected boolean namedPipe = false; protected String macAddress = ""; protected int packetSize = 0; protected boolean prepareSql = true; protected long lobBuffer = TdsCore.DEFAULT_LOB_BUFFER_SIZE; public Reference getReference() throws NamingException { Reference ref = new Reference(getClass().getName(), JtdsObjectFactory.class.getName(), null); ref.add(new StringRefAddr(Support.getMessage("prop.servername"), serverName)); ref.add(new StringRefAddr(Support.getMessage("prop.portnumber"), String.valueOf(portNumber))); ref.add(new StringRefAddr(Support.getMessage("prop.databasename"), databaseName)); ref.add(new StringRefAddr(Support.getMessage("prop.user"), user)); ref.add(new StringRefAddr(Support.getMessage("prop.password"), password)); ref.add(new StringRefAddr(Support.getMessage("prop.charset"), charset)); ref.add(new StringRefAddr(Support.getMessage("prop.language"), language)); ref.add(new StringRefAddr(Support.getMessage("prop.tds"), tds)); ref.add(new StringRefAddr(Support.getMessage("prop.servertype"), String.valueOf(serverType))); ref.add(new StringRefAddr(Support.getMessage("prop.domain"), domain)); ref.add(new StringRefAddr(Support.getMessage("prop.instance"), instance)); ref.add(new StringRefAddr(Support.getMessage("prop.lastupdatecount"), String.valueOf(isLastUpdateCount()))); ref.add(new StringRefAddr(Support.getMessage("prop.logintimeout"), String.valueOf(loginTimeout))); ref.add(new StringRefAddr(Support.getMessage("prop.useunicode"), String.valueOf(sendStringParametersAsUnicode))); ref.add(new StringRefAddr(Support.getMessage("prop.namedpipe"), String.valueOf(namedPipe))); ref.add(new StringRefAddr(Support.getMessage("prop.macaddress"), macAddress)); ref.add(new StringRefAddr(Support.getMessage("prop.packetsize"), String.valueOf(packetSize))); ref.add(new StringRefAddr(Support.getMessage("prop.preparesql"), String.valueOf(prepareSql))); ref.add(new StringRefAddr(Support.getMessage("prop.lobbuffer"), String.valueOf(lobBuffer))); return ref; } public PrintWriter getLogWriter() throws SQLException { return Logger.getLogWriter(); } public void setLogWriter(PrintWriter out) throws SQLException { Logger.setLogWriter(out); } public void setLoginTimeout(int loginTimeout) throws SQLException { this.loginTimeout = loginTimeout; } public int getLoginTimeout() throws SQLException { return loginTimeout; } public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } public String getDatabaseName() { return databaseName; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } public void setPortNumber(int portNumber) { this.portNumber = portNumber; } public int getPortNumber() { return portNumber; } public void setServerName(String serverName) { this.serverName = serverName; } public String getServerName() { return serverName; } public void setUser(String user) { this.user = user; } public String getUser() { return user; } public void setTds(String tds) { this.tds = tds; } public String getTds() { return tds; } public void setServerType(int serverType) { this.serverType = serverType; } public int getServerType() { return serverType; } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public String getInstance() { return instance; } public void setInstance(String instance) { this.instance = instance; } public boolean getSendStringParametersAsUnicode() { return sendStringParametersAsUnicode; } public void setSendStringParametersAsUnicode(boolean sendStringParametersAsUnicode) { this.sendStringParametersAsUnicode = sendStringParametersAsUnicode; } public boolean getNamedPipe() { return namedPipe; } public void setNamedPipe(boolean namedPipe) { this.namedPipe = namedPipe; } public boolean isLastUpdateCount() { return lastUpdateCount; } public void setLastUpdateCount(boolean lastUpdateCount) { this.lastUpdateCount = lastUpdateCount; } public String getCharset() { return charset; } public void setCharset(String charset) { this.charset = charset; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getMacAddress() { return macAddress; } public void setMacAddress(String macAddress) { this.macAddress = macAddress; } public void setPacketSize(int packetSize) { this.packetSize = packetSize; } public int getPacketSize() { return packetSize; } public void setPrepareSql(boolean value) { this.prepareSql = value; } public boolean getPrepareSql() { return prepareSql; } public void setLobBuffer(long lobBuffer) { this.lobBuffer = lobBuffer; } public long getLobBuffer() { return lobBuffer; } }
package org.voltdb.export; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.voltdb.BackendTarget; import org.voltdb.VoltTable; import org.voltdb.client.Client; import org.voltdb.compiler.VoltProjectBuilder; import org.voltdb.compiler.deploymentfile.ServerExportEnum; import org.voltdb.export.TestExportBaseSocketExport.ServerListener; import org.voltdb.regressionsuites.LocalCluster; import org.voltdb.utils.MiscUtils; import org.voltdb.utils.VoltFile; public class TestPersistentExport extends ExportLocalClusterBase { private LocalCluster m_cluster; private static int KFACTOR = 1; private static final String SCHEMA = "CREATE TABLE T1 EXPORT TO TARGET FOO1 ON INSERT, DELETE (a integer not null, b integer not nulL);" + " PARTITION table T1 ON COLUMN a;" + "CREATE TABLE T3 EXPORT TO TARGET FOO3 ON UPDATE (a integer not null, b integer not nulL);"; @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { if (m_cluster != null) { System.out.println("Shutting down client and server"); for (Entry<String, ServerListener> entry : m_serverSockets.entrySet()) { ServerListener serverSocket = entry.getValue(); if (serverSocket != null) { serverSocket.closeClient(); serverSocket.close(); } } m_cluster.shutDown(); m_cluster = null; } } @Test public void testInsertDeleteUpdate() throws Exception { if (!MiscUtils.isPro()) { return; } resetDir(); VoltFile.resetSubrootForThisProcess(); VoltProjectBuilder builder = null; builder = new VoltProjectBuilder(); builder.addLiteralSchema(SCHEMA); builder.setUseDDLSchema(true); builder.setPartitionDetectionEnabled(true); builder.setDeadHostTimeout(30); builder.addExport(true /* enabled */, ServerExportEnum.CUSTOM, "org.voltdb.exportclient.SocketExporter", createSocketExportProperties("T1", false /* is replicated stream? */), "FOO1"); builder.addExport(true /* enabled */, ServerExportEnum.CUSTOM, "org.voltdb.exportclient.SocketExporter", createSocketExportProperties("T3", false /* is replicated stream? */), "FOO3"); // Start socket exporter client startListener(); m_cluster = new LocalCluster("TestPersistentExport.jar", 4, 3, KFACTOR, BackendTarget.NATIVE_EE_JNI); m_cluster.setNewCli(true); m_cluster.setHasLocalServer(false); m_cluster.overrideAnyRequestForValgrind(); boolean success = m_cluster.compile(builder); assertTrue(success); m_cluster.startUp(true); m_verifier = new ExportTestExpectedData(m_serverSockets, false /*is replicated stream? */, true, KFACTOR + 1); m_verifier.m_verifySequenceNumber = false; m_verifier.m_verbose = false; Client client = getClient(m_cluster); //add data to stream table Object[] data = new Object[3]; Arrays.fill(data, 1); insertToStream("T1", 0, 100, client, data); client.callProcedure("@AdHoc", "delete from T1 where a < 10000;"); client.drain(); TestExportBaseSocketExport.waitForStreamedTargetAllocatedMemoryZero(client); checkTupleCount(client, "T1", 200, false); m_verifier.verifyRows(); // test update on replicated table insertToStream("T3", 0, 100, client, data); client.callProcedure("@AdHoc", "update T3 set b = 100 where a < 10000;"); client.drain(); TestExportBaseSocketExport.waitForStreamedTargetAllocatedMemoryZero(client); checkTupleCount(client, "T3", 200, true); // Change trigger to update_new client.callProcedure("@AdHoc", "ALTER TABLE T3 ALTER EXPORT TO TARGET FOO3 ON UPDATE_NEW,DELETE;"); client.callProcedure("@AdHoc", "update T3 set b = 200 where a < 10000;"); client.drain(); TestExportBaseSocketExport.waitForStreamedTargetAllocatedMemoryZero(client); checkTupleCount(client, "T3", 300, true); client.callProcedure("@AdHoc", "delete from T3 where a < 10000;"); client.drain(); TestExportBaseSocketExport.waitForStreamedTargetAllocatedMemoryZero(client); checkTupleCount(client, "T3", 400, true); } private static void checkTupleCount(Client client, String tableName, long expectedCount, boolean replicated){ //allow time to get the stats final long maxSleep = TimeUnit.MINUTES.toMillis(2); boolean success = false; long start = System.currentTimeMillis(); while (!success) { try { VoltTable vt = client.callProcedure("@Statistics", "EXPORT").getResults()[0]; long count = 0; while (vt.advanceRow()) { if (tableName.equalsIgnoreCase(vt.getString("SOURCE")) && "TRUE".equalsIgnoreCase(vt.getString("ACTIVE"))) { if (replicated) { if (0 == vt.getLong("PARTITION_ID")) { count = vt.getLong("TUPLE_COUNT"); break; } } else { count +=vt.getLong("TUPLE_COUNT"); } } } if (count == expectedCount) { return; } if (maxSleep < (System.currentTimeMillis() - start)) { break; } try { Thread.sleep(5000); } catch (Exception ignored) { } } catch (Exception e) { } } assert(false); } }
package com.cardshift.core; import static org.junit.Assert.*; import org.junit.Test; public class AppTest { @Test public void testApp() { assertTrue(true); } }
package thredds.catalog2.simpleImpl; import thredds.catalog2.Catalog; import thredds.catalog2.Service; import thredds.catalog2.Dataset; import thredds.catalog2.Property; import java.net.URI; import java.util.Date; import java.util.List; import java.util.Collections; import java.util.ArrayList; /** * _more_ * * @author edavis * @since 4.0 */ public class CatalogImpl implements Catalog { private String name; private URI documentBaseUri; private String version; private Date expires; private Date lastModified; private List<Service> services; private List<Dataset> datasets; private List<Property> properties; public CatalogImpl( String name, URI documentBaseUri, String version, Date expires, Date lastModified ) { if ( documentBaseUri == null ) throw new IllegalArgumentException( "Catalog base URI must not be null."); this.name = name; this.documentBaseUri = documentBaseUri; this.version = version; this.expires = expires; this.lastModified = lastModified; this.services = new ArrayList<Service>(); this.datasets = new ArrayList<Dataset>(); this.properties = new ArrayList<Property>(); } public void setServices( List<Service> services ) { if ( services == null ) this.services = new ArrayList<Service>(); else this.services = services; } public void addService ( Service service ) { if ( service == null ) throw new IllegalArgumentException( "Can't add a null Service."); this.services.add( service ); } public void setDatasets( List<Dataset> datasets ) { if ( datasets == null ) this.datasets = new ArrayList<Dataset>(); else this.datasets = datasets; } public void setProperties( List<Property> properties ) { if ( properties == null ) this.properties = new ArrayList<Property>(); else this.properties = properties; } @Override public String getName() { return this.name; } @Override public URI getDocumentBaseUri() { return this.documentBaseUri; } @Override public String getVersion() { return this.version; } @Override public Date getExpires() { return this.expires; } @Override public Date getLastModified() { return this.lastModified; } @Override public List<Service> getServices() { return this.services; } @Override public List<Dataset> getDatasets() { return this.datasets; } @Override public List<Property> getProperties() { return this.properties; } }
package org.jgroups.protocols; import static java.util.concurrent.TimeUnit.SECONDS; import org.jgroups.*; import org.jgroups.tests.ChannelTestBase; import org.jgroups.util.Util; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; /** * It's an attemp to setup Junit test case template for Protocol regression. <p> * Two "processes" are started, and the coord. keeps sending msg of a counter. The 2nd * process joins the grp and get the state from the coordinator. The subsequent msgs * after the setState will be validated to ensure the total ordering of msg delivery. <p> * This should cover the fix introduced by rev. 1.12 * @author Wenbo Zhu * @version $Id: STATE_TRANSFER_Test.java,v 1.16 2008/06/26 20:06:00 vlada Exp $ */ @Test(groups="temp") public class STATE_TRANSFER_Test extends ChannelTestBase { public static final String GROUP_NAME="STATE_TRANSFER_Test"; private Coordinator coord; @BeforeMethod protected void setUp() throws Exception { coord=new Coordinator(); coord.recvLoop(); coord.sendLoop(); } @AfterMethod protected void tearDown() throws Exception { coord.stop(); coord=null; } class Coordinator implements ChannelListener { private JChannel channel=null; private int cnt=0; // the state private volatile boolean closed=false; String getProps() { return channel.getProperties(); } public JChannel getChannel() { return channel; } protected Coordinator() throws Exception { channel=createChannel(true); channel.setOpt(Channel.LOCAL, Boolean.FALSE); channel.setOpt(Channel.AUTO_RECONNECT, Boolean.TRUE); channel.addChannelListener(this); channel.connect(GROUP_NAME); } public void channelConnected(Channel channel) { } public void channelDisconnected(Channel channel) { } public void channelClosed(Channel channel) { } public void channelShunned() { } public void channelReconnected(Address addr) { // n/a. now } public void recvLoop() throws Exception { Thread task=new Thread(new Runnable() { public void run() { Object tmp; while(!closed) { try { tmp=channel.receive(0); if(tmp instanceof ExitEvent) { // System.err.println("-- received EXIT, waiting for ChannelReconnected callback"); break; } if(tmp instanceof GetStateEvent) { synchronized(Coordinator.this) { // System.err.println("-- GetStateEvent, cnt=" + cnt); channel.returnState(Util.objectToByteBuffer(new Integer(cnt))); } } } catch(ChannelNotConnectedException not) { break; } catch(ChannelClosedException closed) { break; } catch(Exception e) { System.err.println(e); } } } }); task.start(); } public void sendLoop() throws Exception { Thread task=new Thread(new Runnable() { public void run() { while(!closed) { try { synchronized(Coordinator.this) { channel.send(null, null, new Integer(++cnt)); // System.err.println("send cnt=" + cnt); } Thread.sleep(1000); } catch(ChannelNotConnectedException not) { break; } catch(ChannelClosedException closed) { break; } catch(Exception e) { System.err.println(e); } } } }); task.start(); } public void stop() { closed=true; channel.close(); } } public void testBasicStateSync() throws Exception { Channel channel= null; int timeout=120; //seconds int counter=0; try { channel = createChannel(coord.getChannel()); channel.setOpt(Channel.LOCAL, Boolean.FALSE); channel.connect(GROUP_NAME); Thread.sleep(1000); boolean join=false; join=channel.getState(null, 100000l); assertTrue(join); Object tmp; int cnt=-1; for(;counter < timeout;SECONDS.sleep(1),counter++) { try { tmp=channel.receive(0); if(tmp instanceof ExitEvent) { break; } if(tmp instanceof SetStateEvent) { cnt=((Integer)Util.objectFromByteBuffer(((SetStateEvent)tmp).getArg())).intValue(); // System.err.println("-- SetStateEvent, cnt=" + cnt); continue; } if(tmp instanceof Message) { if(cnt != -1) { int msg=((Integer)((Message)tmp).getObject()).intValue(); assertEquals(cnt, msg - 1); break; // done } } } catch(ChannelNotConnectedException not) { break; } catch(ChannelClosedException closed) { break; } catch(Exception e) { System.err.println(e); } } } finally { channel.close(); assertTrue("Timeout reached", counter < 120); } } }
// $Id: STATE_TRANSFER_Test.java,v 1.2 2005/05/04 04:25:28 wenbo Exp $ package org.jgroups.protocols; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jgroups.Address; import org.jgroups.Channel; import org.jgroups.ChannelClosedException; import org.jgroups.ChannelException; import org.jgroups.ChannelListener; import org.jgroups.ChannelNotConnectedException; import org.jgroups.ExitEvent; import org.jgroups.GetStateEvent; import org.jgroups.JChannel; import org.jgroups.SetStateEvent; import org.jgroups.Message; import org.jgroups.util.Util; /** * It's an attemp to setup Junit test cast template for Protocol regression. <p> * <p/> * Two processes are started, and the coord. keeps sending msg of a counter. The 2nd * process joins the grp and get the state from the coordinator. The subsequent msgs * after the setState will be validated to ensure the total ordering of msg delivery. <p> * <p/> * This should cover the fix introduced by rev. 11/12. * * @author Wenbo Zhu * @version 1.0 */ public class STATE_TRANSFER_Test extends TestCase { public final static String CHANNEL_PROPS = "UDP(mcast_addr=228.8.8.8;mcast_port=45566;ip_ttl=32;" + "mcast_send_buf_size=64000;mcast_recv_buf_size=64000):" + "PING(timeout=2000;num_initial_members=3):" + "MERGE2(min_interval=5000;max_interval=10000):" + "FD_SOCK:" + "VERIFY_SUSPECT(timeout=1500):" + "UNICAST(timeout=600,1200,2400,4800):" + "STABLE():" + "NAKACK(retransmit_timeout=600,1200,2400,4800):" + "FRAG(frag_size=8096;down_thread=false;up_thread=false):" + "FLUSH():" + "GMS(join_timeout=5000;join_retry_timeout=2000;" + "print_local_addr=true):" + "VIEW_ENFORCER:" + "TOTAL:" + "STATE_TRANSFER:" + "QUEUE"; public static final String GROUP_NAME = "jgroups.TEST_GROUP"; private Coordinator coord; public STATE_TRANSFER_Test(String testName) { super(testName); } protected void setUp() throws Exception { super.setUp(); System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "error"); coord = new Coordinator(); coord.recvLoop(); coord.sendLoop(); } protected void tearDown() throws Exception { super.tearDown(); coord.stop(); coord = null; } class Coordinator implements ChannelListener { private JChannel channel = null; private int cnt = 0; // the state private volatile boolean closed = false; protected Coordinator() throws ChannelException { channel = new JChannel(CHANNEL_PROPS); channel.setOpt(Channel.LOCAL, Boolean.FALSE); channel.setOpt(Channel.AUTO_RECONNECT, Boolean.TRUE); channel.setOpt(Channel.GET_STATE_EVENTS, Boolean.TRUE); channel.setChannelListener(this); channel.connect(GROUP_NAME); } public void channelConnected(Channel channel) { } public void channelDisconnected(Channel channel) { } public void channelClosed(Channel channel) { } public void channelShunned() { } public void channelReconnected(Address addr) { // n/a. now } public void recvLoop() throws Exception { Thread task = new Thread(new Runnable() { public void run() { Object tmp; while (! closed) { try { tmp = channel.receive(0); if (tmp instanceof ExitEvent) { System.err.println("-- received EXIT, waiting for ChannelReconnected callback"); break; } if (tmp instanceof GetStateEvent) { synchronized (Coordinator.this) { System.err.println("-- GetStateEvent, cnt=" + cnt); channel.returnState(Util.objectToByteBuffer(new Integer(cnt))); } continue; } } catch (ChannelNotConnectedException not) { break; } catch (ChannelClosedException closed) { break; } catch (Exception e) { System.err.println(e); continue; } } } }); task.start(); } public void sendLoop() throws Exception { Thread task = new Thread(new Runnable() { public void run() { while (! closed) { try { synchronized (Coordinator.this) { channel.send(null, null, new Integer(++cnt)); System.err.println("send cnt=" + cnt); } Thread.sleep(1000); } catch (ChannelNotConnectedException not) { break; } catch (ChannelClosedException closed) { break; } catch (Exception e) { System.err.println(e); continue; } } } }); task.start(); } public void stop() { closed = true; channel.close(); } } public void testBasicStateSync() throws Exception { Channel channel = new JChannel(CHANNEL_PROPS); channel.setOpt(Channel.LOCAL, Boolean.FALSE); channel.connect(GROUP_NAME); Thread.sleep(1000); boolean join = false; join = channel.getState(null, 100000l); assertTrue(join); Object tmp; int cnt = -1; while (true) { try { tmp = channel.receive(0); if (tmp instanceof ExitEvent) { break; } if (tmp instanceof SetStateEvent) { cnt = ((Integer) Util.objectFromByteBuffer(((SetStateEvent) tmp).getArg())).intValue(); System.err.println("-- SetStateEvent, cnt=" + cnt); continue; } if ( tmp instanceof Message ) { if (cnt != -1) { int msg = ((Integer) ((Message) tmp).getObject()).intValue(); assertEquals(cnt, msg - 1); break; // done } } } catch (ChannelNotConnectedException not) { break; } catch (ChannelClosedException closed) { break; } catch (Exception e) { System.err.println(e); continue; } } channel.close(); } public static Test suite() { return new TestSuite(STATE_TRANSFER_Test.class); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } }
/* * This samples uses multiple threads to post synchronous requests to the * VoltDB server, simulating multiple client application posting * synchronous requests to the database, using the native VoltDB client * library. * * While synchronous processing can cause performance bottlenecks (each * caller waits for a transaction answer before calling another * transaction), the VoltDB cluster at large is still able to perform at * blazing speeds when many clients are connected to it. */ package kvbench; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.voltdb.CLIConfig; import org.voltdb.VoltTable; import org.voltdb.client.Client; import org.voltdb.client.ClientConfig; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientResponse; import org.voltdb.client.ClientStats; import org.voltdb.client.ClientStatsContext; import org.voltdb.client.ClientStatusListenerExt; import org.voltdb.client.NullCallback; import com.google_voltpatches.common.base.Preconditions; import com.google_voltpatches.common.base.Throwables; public class SyncBenchmark { // handy, rather than typing this out several times static final String HORIZONTAL_RULE = " " // validated command line configuration final KVConfig config; // Reference to the database connection we will use final Client client; // Timer for periodic stats printing Timer timer; // Benchmark start time long benchmarkStartTS; // Get a payload generator to create random Key-Value pairs to store in the database // and process (uncompress) pairs retrieved from the database. final PayloadProcessor processor; // random number generator with constant seed final Random rand = new Random(0); // Flags to tell the worker threads to stop or go AtomicBoolean warmupComplete = new AtomicBoolean(false); AtomicBoolean benchmarkComplete = new AtomicBoolean(false); // Statistics manager objects from the client final ClientStatsContext periodicStatsContext; final ClientStatsContext fullStatsContext; // Graphite logger GraphiteLogger graphite = null; // CSV logger CsvLogger csvlogger = null; // kv benchmark state final AtomicLong successfulGets = new AtomicLong(0); final AtomicLong missedGets = new AtomicLong(0); final AtomicLong failedGets = new AtomicLong(0); final AtomicLong rawGetData = new AtomicLong(0); final AtomicLong networkGetData = new AtomicLong(0); final AtomicLong successfulPuts = new AtomicLong(0); final AtomicLong failedPuts = new AtomicLong(0); final AtomicLong rawPutData = new AtomicLong(0); final AtomicLong networkPutData = new AtomicLong(0); static final SimpleDateFormat LOG_DF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); private static final ExecutorService es = Executors.newCachedThreadPool(new ThreadFactory() { @Override public Thread newThread(Runnable arg0) { Thread thread = new Thread(arg0, "Retry Connection"); thread.setDaemon(true); return thread; } }); /** * Uses included {@link CLIConfig} class to * declaratively state command line options with defaults * and validation. */ static class KVConfig extends CLIConfig { @Option(desc = "Interval for performance feedback, in seconds.") long displayinterval = 5; @Option(desc = "Benchmark duration, in seconds.") int duration = 10; @Option(desc = "Warmup duration in seconds.") int warmup = 5; @Option(desc = "Comma separated list of the form server[:port] to connect to.") String servers = "localhost"; @Option(desc = "Number of keys to preload.") int poolsize = 100000; @Option(desc = "Whether to preload a specified number of keys and values.") boolean preload = true; @Option(desc = "Fraction of ops that are gets (vs puts).") double getputratio = 0.90; @Option(desc = "Size of keys in bytes.") int keysize = 32; @Option(desc = "Minimum value size in bytes.") int minvaluesize = 1024; @Option(desc = "Maximum value size in bytes.") int maxvaluesize = 1024; @Option(desc = "Number of values considered for each value byte.") int entropy = 127; @Option(desc = "Compress values on the client side.") boolean usecompression= false; @Option(desc = "Number of concurrent threads synchronously calling procedures.") int threads = 40; @Option(desc = "Filename to write raw summary statistics to.") String statsfile = ""; @Option(desc = "Graphite server hostname") String graphitehost = ""; @Option(desc = "Filename to write periodic stat infomation in CSV format") String csvfile = ""; @Override public void validate() { if (duration <= 0) exitWithMessageAndUsage("duration must be > 0"); if (warmup < 0) exitWithMessageAndUsage("warmup must be >= 0"); if (displayinterval <= 0) exitWithMessageAndUsage("displayinterval must be > 0"); if (poolsize <= 0) exitWithMessageAndUsage("poolsize must be > 0"); if (getputratio < 0) exitWithMessageAndUsage("getputratio must be >= 0"); if (getputratio > 1) exitWithMessageAndUsage("getputratio must be <= 1"); if (keysize <= 0) exitWithMessageAndUsage("keysize must be > 0"); if (keysize > 250) exitWithMessageAndUsage("keysize must be <= 250"); if (minvaluesize <= 0) exitWithMessageAndUsage("minvaluesize must be > 0"); if (maxvaluesize <= 0) exitWithMessageAndUsage("maxvaluesize must be > 0"); if (entropy <= 0) exitWithMessageAndUsage("entropy must be > 0"); if (entropy > 127) exitWithMessageAndUsage("entropy must be <= 127"); if (threads <= 0) exitWithMessageAndUsage("threads must be > 0"); } } static class GraphiteLogger implements AutoCloseable { final static String METRIC_PREFIX = "volt.kv."; final Socket m_socket; final PrintWriter m_writer; public GraphiteLogger(final String host) { Preconditions.checkArgument(host != null && !host.trim().isEmpty(), "host is null or emtpy"); InetSocketAddress addr = new InetSocketAddress(host, 2003); m_socket = new Socket(); PrintWriter pw = null; try { m_socket.connect(addr,2000); pw = new PrintWriter(m_socket.getOutputStream(),true); } catch (IOException ioex) { Throwables.propagate(ioex); } m_writer = pw; } @Override public void close() throws IOException { m_writer.close(); m_socket.close(); } public void log(final ClientStats stats) { if (stats == null) return; double now = stats.getEndTimestamp() / 1000.0; m_writer.printf("volt.kv.aborts %d %.3f\n", stats.getInvocationAborts(), now); m_writer.printf("volt.kv.errors %d %.3f\n", stats.getInvocationErrors(), now); m_writer.printf("volt.kv.latency.average %f %.3f\n", stats.getAverageLatency(), now); m_writer.printf("volt.kv.latency.five9s %.2f %.3f\n", stats.kPercentileLatencyAsDouble(0.99999), now); m_writer.printf("volt.kv.completed %d %.3f\n", stats.getInvocationsCompleted(), now); m_writer.printf("volt.kv.throughput %d %.3f\n", stats.getTxnThroughput(), now); } } static class CsvLogger implements AutoCloseable { final PrintWriter m_writer; final SimpleDateFormat m_df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); public CsvLogger(String csvFN) { Preconditions.checkArgument(csvFN != null && !csvFN.trim().isEmpty(),"file name is null or empty"); File fh = new File(csvFN); PrintWriter pw = null; try { // 'true' to flush the buffer every println/printf pw = new PrintWriter(new FileWriter(fh), true); } catch (IOException ioex) { Throwables.propagate(ioex); } m_writer = pw; pw.println("TIMESTAMP,TSMILLIS,COMPLETED,ABORTS,ERRORS,TIMEOUTS,THROUGHPUT,AVERAGE_LATENCY,TWO9S_LATENCY,THREE9S_LATENCY,FOUR9S_LATENCY,FIVE9S_LATENCY"); } @Override public void close() throws IOException { m_writer.close(); } public void log(final ClientStats stats) { String ts = m_df.format(new Date(stats.getEndTimestamp())); m_writer.printf("%s,%d,%d,%d,%d,%d,%d,%.4f,%.4f,%.4f,%.4f,%.4f\n", ts, // col 00 string timestamp stats.getEndTimestamp(), // col 01 long timestamp millis stats.getInvocationsCompleted(), // col 02 long invocations completed stats.getInvocationAborts(), // col 03 long invocation aborts stats.getInvocationErrors(), // col 04 long invocation errors stats.getInvocationTimeouts(), // col 05 long invocation timeouts stats.getTxnThroughput(), // col 06 long transaction throughput stats.getAverageLatency(), // col 07 double average latency stats.kPercentileLatencyAsDouble(0.99), // col 08 double two nines latency stats.kPercentileLatencyAsDouble(0.999), // col 09 double three nines latency stats.kPercentileLatencyAsDouble(0.9999), // col 10 double four nines latency stats.kPercentileLatencyAsDouble(0.99999) // col 11 double five nines latency ); } } void logMetric(final ClientStats stats) { if (graphite != null) { graphite.log(stats); } if (csvlogger != null) { csvlogger.log(stats); } } /** * Provides a callback to be notified on node failure. * This example only logs the event. */ class StatusListener extends ClientStatusListenerExt { @Override public void connectionLost(String hostname, int port, int connectionsLeft, DisconnectCause cause) { if (benchmarkComplete.get()) return; // if the benchmark is still active if ((System.currentTimeMillis() - benchmarkStartTS) < (config.duration * 1000)) { System.err.printf("Connection to %s:%d was lost.\n", hostname, port); } // setup for retry StringBuilder hnsb = new StringBuilder(hostname); if (port > 0) { hnsb.append(':').append(port); } final String server = hnsb.toString(); es.execute(new Runnable() { @Override public void run() { connectToOneServerWithRetry(server); } }); } } /** * Constructor for benchmark instance. * Configures VoltDB client and prints configuration. * * @param config Parsed & validated CLI options. */ public SyncBenchmark(KVConfig config) { this.config = config; ClientConfig clientConfig = new ClientConfig("", "", new StatusListener()); clientConfig.setClientAffinity(true); client = ClientFactory.createClient(clientConfig); periodicStatsContext = client.createStatsContext(); fullStatsContext = client.createStatsContext(); if (config.graphitehost != null && !config.graphitehost.trim().isEmpty()) { graphite = new GraphiteLogger(config.graphitehost); } if (config.csvfile != null && !config.csvfile.trim().isEmpty()) { csvlogger = new CsvLogger(config.csvfile); } processor = new PayloadProcessor(config.keysize, config.minvaluesize, config.maxvaluesize, config.entropy, config.poolsize, config.usecompression); System.out.print(HORIZONTAL_RULE); System.out.println(" Command Line Configuration"); System.out.println(HORIZONTAL_RULE); System.out.println(config.getConfigDumpString()); } /** * Connect to a single server with retry. Limited exponential backoff. * No timeout. This will run until the process is killed if it's not * able to connect. * * @param server hostname:port or just hostname (hostname can be ip). */ void connectToOneServerWithRetry(String server) { int sleep = 1000; while (true) { try { client.createConnection(server); break; } catch (Exception e) { System.err.printf("Connection failed - retrying in %d second(s).\n", sleep / 1000); try { Thread.sleep(sleep); } catch (Exception interruted) {} if (sleep < 8000) sleep += sleep; } } System.out.printf("Connected to VoltDB node at: %s.\n", server); } /** * Connect to a set of servers in parallel. Each will retry until * connection. This call will block until all have connected. * * @param servers A comma separated list of servers using the hostname:port * syntax (where :port is optional). * @throws InterruptedException if anything bad happens with the threads. */ void connect(String servers) throws InterruptedException { System.out.println("Connecting to VoltDB..."); String[] serverArray = servers.split(","); final CountDownLatch connections = new CountDownLatch(serverArray.length); // use a new thread to connect to each server for (final String server : serverArray) { new Thread(new Runnable() { @Override public void run() { connectToOneServerWithRetry(server); connections.countDown(); } }).start(); } // block until all have connected connections.await(); } /** * Create a Timer task to display performance data on the Vote procedure * It calls printStatistics() every displayInterval seconds */ public void schedulePeriodicStats() { timer = new Timer(); TimerTask statsPrinting = new TimerTask() { @Override public void run() { printStatistics(); } }; timer.scheduleAtFixedRate(statsPrinting, config.displayinterval * 1000, config.displayinterval * 1000); } /** * Prints a one line update on performance that can be printed * periodically during a benchmark. */ public synchronized void printStatistics() { ClientStats stats = periodicStatsContext.fetchAndResetBaseline().getStats(); // Print an ISO8601 timestamp (of the same kind Python logging uses) to help // log merger correlate correctly System.out.print(LOG_DF.format(new Date(stats.getEndTimestamp()))); System.out.printf(" Throughput %d/s, ", stats.getTxnThroughput()); System.out.printf("Aborts/Failures %d/%d, ", stats.getInvocationAborts(), stats.getInvocationErrors()); System.out.printf("Avg/99.999%% Latency %.2f/%.2fms\n", stats.getAverageLatency(), stats.kPercentileLatencyAsDouble(0.99999)); logMetric(stats); } /** * Prints the results of the voting simulation and statistics * about performance. * * @throws Exception if anything unexpected happens. */ public synchronized void printResults() throws Exception { ClientStats stats = fullStatsContext.fetch().getStats(); // 1. Get/Put performance results String display = "\n" + HORIZONTAL_RULE + " KV Store Results\n" + HORIZONTAL_RULE + "\nA total of %,d operations were posted...\n" + " - GETs: %,9d Operations (%,d Misses and %,d Failures)\n" + " %,9d MB in compressed store data\n" + " %,9d MB in uncompressed application data\n" + " Network Throughput: %6.3f Gbps*\n" + " - PUTs: %,9d Operations (%,d Failures)\n" + " %,9d MB in compressed store data\n" + " %,9d MB in uncompressed application data\n" + " Network Throughput: %6.3f Gbps*\n" + " - Total Network Throughput: %6.3f Gbps*\n\n" + "* Figure includes key & value traffic but not database protocol overhead.\n\n"; double oneGigabit = (1024 * 1024 * 1024) / 8; long oneMB = (1024 * 1024); double getThroughput = networkGetData.get() + (successfulGets.get() * config.keysize); getThroughput /= (oneGigabit * config.duration); long totalPuts = successfulPuts.get() + failedPuts.get(); double putThroughput = networkGetData.get() + (totalPuts * config.keysize); putThroughput /= (oneGigabit * config.duration); System.out.printf(display, stats.getInvocationsCompleted(), successfulGets.get(), missedGets.get(), failedGets.get(), networkGetData.get() / oneMB, rawGetData.get() / oneMB, getThroughput, successfulPuts.get(), failedPuts.get(), networkPutData.get() / oneMB, rawPutData.get() / oneMB, putThroughput, getThroughput + putThroughput); // 2. Performance statistics System.out.print(HORIZONTAL_RULE); System.out.println(" Client Workload Statistics"); System.out.println(HORIZONTAL_RULE); System.out.printf("Average throughput: %,9d txns/sec\n", stats.getTxnThroughput()); System.out.printf("Average latency: %,9.2f ms\n", stats.getAverageLatency()); System.out.printf("10th percentile latency: %,9.2f ms\n", stats.kPercentileLatencyAsDouble(.1)); System.out.printf("25th percentile latency: %,9.2f ms\n", stats.kPercentileLatencyAsDouble(.25)); System.out.printf("50th percentile latency: %,9.2f ms\n", stats.kPercentileLatencyAsDouble(.5)); System.out.printf("75th percentile latency: %,9.2f ms\n", stats.kPercentileLatencyAsDouble(.75)); System.out.printf("90th percentile latency: %,9.2f ms\n", stats.kPercentileLatencyAsDouble(.9)); System.out.printf("95th percentile latency: %,9.2f ms\n", stats.kPercentileLatencyAsDouble(.95)); System.out.printf("99th percentile latency: %,9.2f ms\n", stats.kPercentileLatencyAsDouble(.99)); System.out.printf("99.5th percentile latency: %,9.2f ms\n", stats.kPercentileLatencyAsDouble(.995)); System.out.printf("99.9th percentile latency: %,9.2f ms\n", stats.kPercentileLatencyAsDouble(.999)); System.out.printf("99.999th percentile latency: %,9.2f ms\n", stats.kPercentileLatencyAsDouble(.99999)); System.out.print("\n" + HORIZONTAL_RULE); System.out.println(" System Server Statistics"); System.out.println(HORIZONTAL_RULE); System.out.printf("Reported Internal Avg Latency: %,9.2f ms\n", stats.getAverageInternalLatency()); System.out.print("\n" + HORIZONTAL_RULE); System.out.println(" Latency Histogram"); System.out.println(HORIZONTAL_RULE); System.out.println(stats.latencyHistoReport()); // 3. Write stats to file if requested client.writeSummaryCSV(stats, config.statsfile); } /** * While <code>benchmarkComplete</code> is set to false, run as many * synchronous procedure calls as possible and record the results. * */ class KVThread implements Runnable { @Override public void run() { while (warmupComplete.get() == false) { // Decide whether to perform a GET or PUT operation if (rand.nextDouble() < config.getputratio) { // Get a key/value pair, synchronously try { client.callProcedure("Get", processor.generateRandomKeyForRetrieval()); } catch (Exception e) {} } else { // Put a key/value pair, synchronously final PayloadProcessor.Pair pair = processor.generateForStore(); try { client.callProcedure("Put", pair.Key, pair.getStoreValue()); } catch (Exception e) {} } } while (benchmarkComplete.get() == false) { // Decide whether to perform a GET or PUT operation if (rand.nextDouble() < config.getputratio) { // Get a key/value pair, synchronously try { ClientResponse response = client.callProcedure("Get", processor.generateRandomKeyForRetrieval()); final VoltTable pairData = response.getResults()[0]; // Cache miss (Key does not exist) if (pairData.getRowCount() == 0) missedGets.incrementAndGet(); else { final PayloadProcessor.Pair pair = processor.retrieveFromStore(pairData.fetchRow(0).getString(0), pairData.fetchRow(0).getVarbinary(1)); successfulGets.incrementAndGet(); networkGetData.addAndGet(pair.getStoreValueLength()); rawGetData.addAndGet(pair.getRawValueLength()); } } catch (Exception e) { failedGets.incrementAndGet(); } } else { // Put a key/value pair, synchronously final PayloadProcessor.Pair pair = processor.generateForStore(); try { client.callProcedure("Put", pair.Key, pair.getStoreValue()); successfulPuts.incrementAndGet(); } catch (Exception e) { failedPuts.incrementAndGet(); } networkPutData.addAndGet(pair.getStoreValueLength()); rawPutData.addAndGet(pair.getRawValueLength()); } } } } /** * Core benchmark code. * Connect. Initialize. Run the loop. Cleanup. Print Results. * * @throws Exception if anything unexpected happens. */ public void runBenchmark() throws Exception { System.out.print(HORIZONTAL_RULE); System.out.println(" Setup & Initialization"); System.out.println(HORIZONTAL_RULE); // connect to one or more servers, loop until success connect(config.servers); // preload keys if requested System.out.println(); if (config.preload) { System.out.println("Preloading data store..."); for(int i=0; i < config.poolsize; i++) { client.callProcedure(new NullCallback(), "Put", String.format(processor.KeyFormat, i), processor.generateForStore().getStoreValue()); } client.drain(); System.out.println("Preloading complete.\n"); } System.out.print(HORIZONTAL_RULE); System.out.println(" Starting Benchmark"); System.out.println(HORIZONTAL_RULE); // create/start the requested number of threads Thread[] kvThreads = new Thread[config.threads]; for (int i = 0; i < config.threads; ++i) { kvThreads[i] = new Thread(new KVThread()); kvThreads[i].start(); } // Run the benchmark loop for the requested warmup time System.out.println("Warming up..."); Thread.sleep(1000l * config.warmup); // signal to threads to end the warmup phase warmupComplete.set(true); // reset the stats after warmup fullStatsContext.fetchAndResetBaseline(); periodicStatsContext.fetchAndResetBaseline(); // print periodic statistics to the console benchmarkStartTS = System.currentTimeMillis(); schedulePeriodicStats(); // Run the benchmark loop for the requested warmup time System.out.println("\nRunning benchmark..."); Thread.sleep(1000l * config.duration); // stop the threads benchmarkComplete.set(true); // cancel periodic stats printing timer.cancel(); // block until all outstanding txns return client.drain(); // join on the threads for (Thread t : kvThreads) { t.join(); } // print the summary results printResults(); // close down the client connections client.close(); // if enabled close the graphite logger if (graphite != null) { graphite.close(); } // if enabled close the csv logger if (csvlogger != null) { csvlogger.close(); } } /** * Main routine creates a benchmark instance and kicks off the run method. * * @param args Command line arguments. * @throws Exception if anything goes wrong. * @see {@link KVConfig} */ public static void main(String[] args) throws Exception { // create a configuration from the arguments KVConfig config = new KVConfig(); config.parse(SyncBenchmark.class.getName(), args); SyncBenchmark benchmark = new SyncBenchmark(config); benchmark.runBenchmark(); } }
package org.broad.igv.data.expression; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.exceptions.ParserException; import org.broad.igv.exceptions.ProbeMappingException; import org.broad.igv.feature.Locus; import org.broad.igv.feature.genome.Genome; import org.broad.igv.tools.StatusMonitor; import org.broad.igv.track.TrackType; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.MagetabSignalDialog; import org.broad.igv.util.ParsingUtils; import org.broad.igv.util.ResourceLocator; import htsjdk.tribble.readers.AsciiLineReader; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; /** * TODO -- handle case with probe file * * @author jrobinso */ public class ExpressionFileParser { private static Logger log = Logger.getLogger(ExpressionFileParser.class); private static final int MAX_ERROR_COUNT = 200; public enum FileType { RES, GCT, MAPPED, TAB, MET, DCHIP, MAGE_TAB } ResourceLocator dataFileLocator; FileType type; Genome genome; /** * Map chr -> longest feature */ Map<String, Integer> longestProbeMap; Map<String, List<Row>> rowMap = new HashMap(); StatusMonitor statusMonitor; GeneToLocusHelper locusHelper; // For effecient lookup, data column name -> index Map<String, Integer> dataColumnIndexMap; int errorCount = 0; /** * Test to determine if the path referes to a GCT file. The GCT specification requires that the first line * be equal to #1.2 * * @param path * @return * @throws IOException */ public static boolean isGCT(String path) throws IOException { BufferedReader reader = null; try { reader = ParsingUtils.openBufferedReader(path); String firstLine = reader.readLine(); return firstLine != null && firstLine.trim().equals(" } finally { if (reader != null) reader.close(); } } public ExpressionFileParser(ResourceLocator resFile, String probeFile, Genome genome) throws IOException { this.dataFileLocator = resFile; this.type = determineType(resFile); this.genome = genome; longestProbeMap = new HashMap(); locusHelper = new GeneToLocusHelper(probeFile); } public ExpressionFileParser(File resFile, String probeFile, Genome genome) throws IOException { this(new ResourceLocator(resFile.getAbsolutePath()), probeFile, genome); } public static boolean parsableMAGE_TAB(ResourceLocator file) throws IOException { AsciiLineReader reader = null; try { reader = ParsingUtils.openAsciiReader(file); String nextLine = null; //skip first row reader.readLine(); //check second row for MAGE_TAB identifiers if ((nextLine = reader.readLine()) != null && (nextLine.contains("Reporter REF") || nextLine.contains("Composite Element REF") || nextLine.contains("Term Source REF") || nextLine.contains("CompositeElement REF") || nextLine.contains("TermSource REF") || nextLine.contains("Coordinates REF"))) { return true; } } finally { if (reader != null) { reader.close(); } } return false; } public ExpressionDataset createDataset() { ExpressionDataset dataset = new ExpressionDataset(genome); parse(dataset); return dataset; } public static FileType determineType(ResourceLocator dataFileLocator) { String fn = dataFileLocator.getPath().toLowerCase(); if (fn.endsWith(".gz")) { int l = fn.length() - 3; fn = fn.substring(0, l); } if (fn.endsWith(".txt")) { int l = fn.length() - 4; fn = fn.substring(0, l); } //TODO genomespace hack if (dataFileLocator.getPath().contains("?") && dataFileLocator.getPath().contains("dataformat/gct")) { fn = ".gct"; } FileType type; if (fn.endsWith("res")) { type = FileType.RES; } else if (fn.endsWith("gct")) { type = FileType.GCT; } else if (fn.endsWith("mapped")) { type = FileType.MAPPED; } else if (fn.endsWith("met")) { type = FileType.MET; } else if (fn.endsWith("dchip")) { type = FileType.DCHIP; } else if ("mage-tab".equals(dataFileLocator.getType()) || "MAGE_TAB".equals(dataFileLocator.getDescription())) { type = FileType.MAGE_TAB; } else { type = FileType.TAB; } return type; } /** * Parse the file and return a Dataset * * @return */ public void parse(ExpressionDataset dataset) { // Create a buffer for the string split utility. We use a custom utility as opposed // to String.split() for performance. dataset.setType(TrackType.GENE_EXPRESSION); BufferedReader reader = null; String nextLine = null; int lineCount = 0; //String[] columnHeadings = null; try { reader = ParsingUtils.openBufferedReader(dataFileLocator); // Parse the header(s) to determine the precise format. FormatDescriptor formatDescriptor = parseHeader(reader, type, dataset); final int probeColumn = formatDescriptor.probeColumn; final int descriptionColumn = formatDescriptor.descriptionColumn; int nDataColumns = formatDescriptor.dataColumns.length; dataset.setColumnHeadings(formatDescriptor.dataHeaders); dataColumnIndexMap = new HashMap<String, Integer>(); for (int i = 0; i < formatDescriptor.dataHeaders.length; i++) { dataColumnIndexMap.put(formatDescriptor.dataHeaders[i], i); } // Loop through the data rows while ((nextLine = reader.readLine()) != null) { String[] tokens = Globals.tabPattern.split(nextLine, -1); int nTokens = tokens.length; String probeId = new String(tokens[probeColumn]); float[] values = new float[nDataColumns]; String description = (descriptionColumn >= 0) ? tokens[descriptionColumn] : null; if (type == FileType.MAGE_TAB && probeId.startsWith("cg")) { // TODO -- this is a very ugly and fragile method to determine data type! Change this! dataset.setType(TrackType.DNA_METHYLATION); } for (int i = 0; i < nDataColumns; i++) { try { int dataIndex = formatDescriptor.dataColumns[i]; // If we are out of value tokens, or the cell is blank, assign NAN to the cell. if ((dataIndex >= nTokens) || (tokens[dataIndex].length() == 0)) { values[i] = Float.NaN; } else { values[i] = Float.parseFloat(tokens[dataIndex]); } } catch (NumberFormatException numberFormatException) { // This s an expected condition. IGV uses NaN to // indicate non numbers (missing data values) values[i] = Float.NaN; } } addRow(probeId, description, values); lineCount++; // This method is designed to be interruptable (canceled by // user. Check every 1000 lines for an interrupt. if (lineCount == 1000) { checkForInterrupt(); lineCount = 0; if (statusMonitor != null) { statusMonitor.incrementPercentComplete(1); } } } // End loop through lines // Sort row for each chromosome by start location sortRows(); // Update dataset for (String chr : rowMap.keySet()) { dataset.setStartLocations(chr, getStartLocations(chr)); dataset.setEndLocations(chr, getEndLocations(chr)); dataset.setFeatureNames(chr, getProbes(chr)); for (String heading : formatDescriptor.dataHeaders) { dataset.setData(heading, chr, getData(heading, chr)); } } dataset.setLongestFeatureMap(longestProbeMap); } catch (FileNotFoundException ex) { throw new RuntimeException(ex); } catch (InterruptedException e) { throw new RuntimeException("Operation cancelled"); } catch (Exception e) { e.printStackTrace(); if (nextLine != null && lineCount != 0) { throw new ParserException(e.getMessage(), e, lineCount, nextLine); } else { throw new RuntimeException(e); } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } } public void addRow(String probeId, String description, float[] values) { List<Locus> loci = locusHelper.getLoci(probeId, description, genome.getId()); if (loci != null) { for (Locus locus : loci) { if ((locus != null) && locus.isValid()) { String chr = genome == null ? locus.getChr() : genome.getChromosomeAlias(locus.getChr()); List<Row> rows = rowMap.get(chr); if (rows == null) { rows = new ArrayList(); rowMap.put(chr, rows); } int length = locus.getEnd() - locus.getStart(); if (longestProbeMap.containsKey(chr)) { longestProbeMap.put(chr, Math.max(longestProbeMap.get(chr), length)); } else { longestProbeMap.put(chr, length); } rows.add(new Row(probeId, chr, locus.getStart(), locus.getEnd(), values)); } } } else { if (errorCount < MAX_ERROR_COUNT) { log.info("Probe: '" + probeId + "' could not be mapped to a genomic position."); } else if (errorCount == MAX_ERROR_COUNT) { log.info("Maximum probe mapping warning count exceeded. Further mapping errors will not be logged"); } errorCount++; } } /** * Sort all row collections by ascending start location */ private void sortRows() { Comparator<Row> c = new Comparator<Row>() { public int compare(ExpressionFileParser.Row arg0, ExpressionFileParser.Row arg1) { return arg0.start - arg1.start; } }; for (List<Row> rows : rowMap.values()) { Collections.sort(rows, c); } } public String[] getProbes(String chr) { List<Row> rows = rowMap.get(chr); String[] labels = new String[rows.size()]; for (int i = 0; i < rows.size(); i++) { labels[i] = rows.get(i).feature; } return labels; } public int[] getStartLocations(String chr) { List<Row> rows = rowMap.get(chr); int[] startLocations = new int[rows.size()]; for (int i = 0; i < rows.size(); i++) { startLocations[i] = rows.get(i).start; } return startLocations; } public int[] getEndLocations(String chr) { List<Row> rows = rowMap.get(chr); int[] endLocations = new int[rows.size()]; for (int i = 0; i < rows.size(); i++) { endLocations[i] = rows.get(i).end; } return endLocations; } public float[] getData(String heading, String chr) { int columnIndex = dataColumnIndexMap.get(heading); List<Row> rows = rowMap.get(chr); float[] data = new float[rows.size()]; for (int i = 0; i < rows.size(); i++) { data[i] = rows.get(i).values[columnIndex]; } return data; } /** * Note: This is an exact copy of the method in IGVDatasetParser. Refactor to merge these * two parsers, or share a common base class. * * @param comment * @param dataset */ private static void parseComment(String comment, ExpressionDataset dataset) { // If no dataset is supplied there is nothing to do if (dataset == null) return; String tmp = comment.substring(1, comment.length()); if (tmp.startsWith("track")) { dataset.setTrackLine(tmp); } else { String[] tokens = tmp.split("="); if (tokens.length != 2) { return; } String key = tokens[0].trim().toLowerCase(); if (key.equals("name")) { dataset.setName(tokens[1].trim()); } else if (key.equals("type")) { try { dataset.setType(TrackType.valueOf(tokens[1].trim().toUpperCase())); } catch (Exception exception) { // Ignore } } } } private void checkForInterrupt() throws InterruptedException { Thread.sleep(1); // <- check for interrupted thread } public static FormatDescriptor parseHeader(BufferedReader reader, FileType type, ExpressionDataset dataset) throws IOException { int descriptionColumn = -1; // Default - no description column int dataStartColumn = -1; int probeColumn = 0; switch (type) { case RES: dataStartColumn = 2; probeColumn = 1; descriptionColumn = 0; break; case GCT: dataStartColumn = 2; probeColumn = 0; descriptionColumn = 1; break; case MAPPED: dataStartColumn = 4; probeColumn = 0; break; case MET: dataStartColumn = 4; probeColumn = 0; break; case DCHIP: dataStartColumn = 1; probeColumn = 0; descriptionColumn = -1; break; case MAGE_TAB: descriptionColumn = -1; probeColumn = 0; break; case TAB: dataStartColumn = 1; probeColumn = 0; default: // throw exception? } String headerLine = findHeaderLine(reader, type, dataset); String[] firstHeaderRowTokens = headerLine.split("\t"); List<String> dataHeadingList = new ArrayList(firstHeaderRowTokens.length); List<Integer> dataColumnList = new ArrayList<Integer>(firstHeaderRowTokens.length); if (type != FileType.MAGE_TAB) { int skip = type == FileType.RES ? 2 : 1; for (int i = dataStartColumn; i < firstHeaderRowTokens.length; i += skip) { String heading = firstHeaderRowTokens[i].replace('\"', ' ').trim(); dataHeadingList.add(heading); dataColumnList.add(i); } } else { //Mage-Tab String nextLine = reader.readLine(); String[] secondHeaderRowTokens = nextLine.split("\t"); // Remove the label columns. for (int i = 1; i < firstHeaderRowTokens.length; i++) { if (firstHeaderRowTokens[i].trim().length() > 0) { dataStartColumn = i; break; } } String[] dataHeaderColumns = new String[secondHeaderRowTokens.length - dataStartColumn]; System.arraycopy(secondHeaderRowTokens, dataStartColumn, dataHeaderColumns, 0, dataHeaderColumns.length); String qCol = findSignalColumnHeading(dataHeaderColumns); for (int i = 0; i < secondHeaderRowTokens.length; i++) { String heading = secondHeaderRowTokens[i].replace('\"', ' ').trim(); if (heading.toLowerCase().contains(qCol.toLowerCase())) { dataHeadingList.add(firstHeaderRowTokens[i]); dataColumnList.add(i); } } } String[] dataHeaders = dataHeadingList.toArray(new String[dataHeadingList.size()]); int[] dataColumns = new int[dataColumnList.size()]; for (int i = 0; i < dataColumnList.size(); i++) dataColumns[i] = dataColumnList.get(i); //nColumns = dataHeadings.length; // If format is RES skip the two lines following the header if (type == FileType.RES) { reader.readLine(); reader.readLine(); } return new FormatDescriptor(probeColumn, descriptionColumn, dataColumns, dataHeaders, firstHeaderRowTokens.length); } private static String findHeaderLine(BufferedReader reader, FileType type, ExpressionDataset dataset) throws IOException { String nextLine; String headerLine; if (type == FileType.GCT) { nextLine = reader.readLine(); if (nextLine.startsWith(" parseComment(nextLine, dataset); } nextLine = reader.readLine(); if (nextLine.startsWith(" parseComment(nextLine, dataset); } headerLine = reader.readLine(); } else if (type != FileType.MAGE_TAB) { // Skip meta data, if any while ((nextLine = reader.readLine()).startsWith("#") && (nextLine != null)) { parseComment(nextLine, dataset); } headerLine = nextLine; } else { headerLine = reader.readLine(); } return headerLine; } private static String findSignalColumnHeading(String[] tokens) { //Use a map so comparisons are case insensitive, //but returned column heading retains original case Map<String, String> columnHeaderSet = new HashMap<String, String>(); for (String tok : tokens) { columnHeaderSet.put(tok.toLowerCase(), tok); } String[] signals = new String[]{"beta_value", "beta value", "log2 signal", "signal"}; for (String sig : signals) { if (columnHeaderSet.containsKey(sig.toLowerCase())) { return columnHeaderSet.get(sig.toLowerCase()); } } String qCol = null; HashSet<String> uniqueColumns = new HashSet<String>(Arrays.asList(tokens)); List<String> qColumns = new ArrayList<String>(uniqueColumns); if (qColumns.size() == 1) { qCol = qColumns.get(0); } else if (!Globals.isHeadless()) { // Let user choose the signal column Collections.sort(qColumns); MagetabSignalDialog msDialog = new MagetabSignalDialog(IGV.getMainFrame(), qColumns.toArray(new String[0])); msDialog.setVisible(true); if (!msDialog.isCanceled()) { qCol = msDialog.getQuantitationColumn(); } else { throw new RuntimeException("Could not find any signal columns in the MAGE-TAB file"); } } return qCol; } class Row { String feature; String chr; int start; int end; float[] values; Row(String feature, String chr, int start, int end, float[] values) { this.feature = feature; this.chr = chr; this.start = start; this.end = end; this.values = values; } } public static class FormatDescriptor { private int probeColumn; private int descriptionColumn; private int[] dataColumns; private String[] dataHeaders; private int totalColumnCount; FormatDescriptor(int probeColumn, int descriptionColumn, int[] dataColumns, String[] dataHeaders, int totalColumnCount) { this.probeColumn = probeColumn; this.descriptionColumn = descriptionColumn; this.dataColumns = dataColumns; this.dataHeaders = dataHeaders; this.totalColumnCount = totalColumnCount; } public int getProbeColumn() { return probeColumn; } public int getDescriptionColumn() { return descriptionColumn; } public int[] getDataColumns() { return dataColumns; } public String[] getDataHeaders() { return dataHeaders; } public int getTotalColumnCount() { return totalColumnCount; } } }
package org.ensembl.healthcheck.testcase.generic; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.PreparedStatement; import java.util.Arrays; import java.util.List; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.DatabaseType; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.Team; import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase; import org.ensembl.healthcheck.util.DBUtils; import org.ensembl.healthcheck.util.SqlTemplate; import org.apache.commons.collections.ListUtils; /** * Check if any chromosomes that have different lengths in karyotype & seq_region tables. */ public class Karyotype extends SingleDatabaseTestCase { /** * Create a new Karyotype test case. */ public Karyotype() { addToGroup("post_genebuild"); addToGroup("release"); addToGroup("post-compara-handover"); addToGroup("pre-compara-handover"); setDescription("Check that karyotype and seq_region tables agree"); setTeamResponsible(Team.CORE); } /** * This only applies to core and Vega databases. */ public void types() { removeAppliesToType(DatabaseType.ESTGENE); removeAppliesToType(DatabaseType.VEGA); } /** * Run the test. * * @param dbre * The database to use. * @return true if the test passed. * */ public boolean run(DatabaseRegistryEntry dbre) { boolean result = true; Connection con = dbre.getConnection(); result &= karyotypeExists(dbre); // don't check for empty karyotype table - this is done in EmptyTables // meta_coord check also done in MetaCoord // The seq_region.length and karyotype.length should always be the // same. // The SQL returns failures String[] seqRegionNames = DBUtils.getColumnValues(con, "SELECT s.name FROM seq_region s, coord_system cs WHERE s.coord_system_id=cs.coord_system_id AND cs.name='chromosome' AND cs.attrib='default_version' AND s.name NOT LIKE 'LRG%' AND s.name != 'MT'"); String[] patches = DBUtils.getColumnValues(con, "SELECT sr.name FROM seq_region sr, assembly_exception ae WHERE sr.seq_region_id=ae.seq_region_id AND ae.exc_type IN ('PATCH_NOVEL', 'PATCH_FIX')"); List<String> nonPatchSeqRegions = ListUtils.removeAll(Arrays.asList(seqRegionNames), Arrays.asList(patches)); int count = 0; try { PreparedStatement stmt = con.prepareStatement("SELECT sr.name, MAX(kar.seq_region_end), sr.length FROM seq_region sr, karyotype kar WHERE sr.seq_region_id=kar.seq_region_id AND sr.seq_region_id=? GROUP BY kar.seq_region_id HAVING sr.length <> MAX(kar.seq_region_end)"); for (String seqRegion : nonPatchSeqRegions) { stmt.setString(1, seqRegion); ResultSet rs = stmt.executeQuery(); if (rs != null) { while (rs.next() && count < 50) { count++; String chrName = rs.getString(1); int karLen = rs.getInt(2); int chrLen = rs.getInt(3); String prob = ""; int bp = 0; if (karLen > chrLen) { bp = karLen - chrLen; prob = "longer"; } else { bp = chrLen - karLen; prob = "shorter"; } result = false; ReportManager.problem(this, con, "Chromosome " + chrName + " is " + bp + "bp " + prob + " in the karyotype table than " + "in the seq_region table"); } } } } catch (SQLException e) { e.printStackTrace(); } if (count == 0) { ReportManager.correct(this, con, "Chromosome lengths are the same" + " in karyotype and seq_region tables"); } return result; } // run protected boolean karyotypeExists(DatabaseRegistryEntry dbre) { Connection con = dbre.getConnection(); SqlTemplate t = DBUtils.getSqlTemplate(dbre); boolean result = true; String sqlCS = "SELECT count(*) FROM coord_system WHERE name = 'chromosome'"; String sqlAttrib = "SELECT count(*) FROM seq_region_attrib sa, attrib_type at WHERE at.attrib_type_id = sa.attrib_type_id AND code = 'karyotype_rank'"; String sqlMT = "SELECT count(*) FROM seq_region_attrib sa, attrib_type at, seq_region s WHERE at.attrib_type_id = sa.attrib_type_id AND code = 'karyotype_rank' AND s.name = 'MT'"; int karyotype = t.queryForDefaultObject(sqlCS, Integer.class); if (karyotype > 0) { int attrib = t.queryForDefaultObject(sqlAttrib, Integer.class); if (attrib == 0) { result = false; ReportManager.problem(this, con, "Chromosome entry exists but no karyotype attrib is present"); } int mt = t.queryForDefaultObject(sqlMT, Integer.class); if (mt == 0) { result = false; ReportManager.problem(this, con, "Species has chromosomes but no MT"); } } return result; } } // Karyotype
package graph; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Paint; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedList; import java.util.Properties; import java.util.Scanner; import java.util.concurrent.locks.ReentrantLock; import java.util.prefs.Preferences; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JColorChooser; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.SwingConstants; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.plaf.metal.MetalButtonUI; import javax.swing.plaf.metal.MetalIconFactory; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreePath; import lpn.parser.LhpnFile; import main.Gui; import main.Log; import main.util.Utility; import main.util.dataparser.DTSDParser; import main.util.dataparser.DataParser; import main.util.dataparser.TSDParser; import org.apache.batik.dom.GenericDOMImplementation; import org.apache.batik.svggen.SVGGraphics2D; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.LogarithmicAxis; import org.jfree.chart.axis.NumberTickUnit; import org.jfree.chart.axis.StandardTickUnitSource; import org.jfree.chart.event.ChartProgressEvent; import org.jfree.chart.event.ChartProgressListener; import org.jfree.chart.plot.DefaultDrawingSupplier; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.renderer.category.GradientBarPainter; import org.jfree.chart.renderer.category.StandardBarPainter; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.chart.title.LegendTitle; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYDataItem; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jibble.epsgraphics.EpsGraphics2D; import org.sbml.libsbml.ListOf; import org.sbml.libsbml.Model; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.Species; import org.w3c.dom.DOMImplementation; import analysis.AnalysisView; import biomodel.parser.BioModel; import com.lowagie.text.Document; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.DefaultFontMapper; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfTemplate; import com.lowagie.text.pdf.PdfWriter; /** * This is the Graph class. It takes in data and draws a graph of that data. The * Graph class implements the ActionListener class, the ChartProgressListener * class, and the MouseListener class. This allows the Graph class to perform * actions when buttons are pressed, when the chart is drawn, or when the chart * is clicked. * * @author Curtis Madsen */ public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener { private static final long serialVersionUID = 4350596002373546900L; private JFreeChart chart; // Graph of the output data private XYSeriesCollection curData; // Data in the current graph private String outDir; // output directory private String printer_id; // printer id /* * Text fields used to change the graph window */ private JTextField XMin, XMax, XScale, YMin, YMax, YScale; private ArrayList<String> graphSpecies; // names of species in the graph private Gui biomodelsim; // tstubd gui private JButton save, run, saveAs; private JButton export, refresh; // buttons // private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg, // exportCsv; // buttons private HashMap<String, Paint> colors; private HashMap<String, Shape> shapes; private String selected, lastSelected; private LinkedList<GraphSpecies> graphed; private LinkedList<GraphProbs> probGraphed; private JCheckBox resize; private JComboBox XVariable; private JCheckBox LogX, LogY; private JCheckBox visibleLegend; private LegendTitle legend; private Log log; private ArrayList<JCheckBox> boxes; private ArrayList<JTextField> series; private ArrayList<JComboBox> colorsCombo; private ArrayList<JButton> colorsButtons; private ArrayList<JComboBox> shapesCombo; private ArrayList<JCheckBox> connected; private ArrayList<JCheckBox> visible; private ArrayList<JCheckBox> filled; private JCheckBox use; private JCheckBox connectedLabel; private JCheckBox visibleLabel; private JCheckBox filledLabel; private String graphName; private String separator; private boolean change; private boolean timeSeries; private boolean topLevel; private ArrayList<String> graphProbs; private JTree tree; private IconNode node, simDir; private AnalysisView reb2sac; // reb2sac options private ArrayList<String> learnSpecs; private boolean warn; private ArrayList<String> averageOrder; private JPopupMenu popup; // popup menu private ArrayList<String> directories; private JPanel specPanel; private JScrollPane scrollpane; private JPanel all; private JPanel titlePanel; private JScrollPane scroll; private boolean updateXNumber; private final ReentrantLock lock, lock2; /** * Creates a Graph Object from the data given and calls the private graph * helper method. */ public Graph(AnalysisView reb2sac, String printer_track_quantity, String label, String printer_id, String outDir, String time, Gui biomodelsim, String open, Log log, String graphName, boolean timeSeries, boolean learnGraph) { lock = new ReentrantLock(true); lock2 = new ReentrantLock(true); this.reb2sac = reb2sac; averageOrder = null; popup = new JPopupMenu(); warn = false; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } // initializes member variables this.log = log; this.timeSeries = timeSeries; if (graphName != null) { this.graphName = graphName; topLevel = true; } else { if (timeSeries) { this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".grf"; } else { this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".prb"; } topLevel = false; } this.outDir = outDir; this.printer_id = printer_id; this.biomodelsim = biomodelsim; XYSeriesCollection data = new XYSeriesCollection(); if (learnGraph) { updateSpecies(); } else { learnSpecs = null; } // graph the output data if (timeSeries) { setUpShapesAndColors(); graphed = new LinkedList<GraphSpecies>(); selected = ""; lastSelected = ""; graph(printer_track_quantity, label, data, time); if (open != null) { open(open); } } else { setUpShapesAndColors(); probGraphed = new LinkedList<GraphProbs>(); selected = ""; lastSelected = ""; probGraph(label); if (open != null) { open(open); } } } /** * This private helper method calls the private readData method, sets up a * graph frame, and graphs the data. * * @param dataset * @param time */ private void graph(String printer_track_quantity, String label, XYSeriesCollection dataset, String time) { chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset, PlotOrientation.VERTICAL, true, true, false); chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY); chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); chart.addProgressListener(this); legend = chart.getLegend(); ChartPanel graph = new ChartPanel(chart); graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); graph.addMouseListener(this); change = false; // creates text fields for changing the graph's dimensions resize = new JCheckBox("Auto Resize"); resize.setSelected(true); XVariable = new JComboBox(); Dimension dim = new Dimension(1,1); XVariable.setPreferredSize(dim); updateXNumber = false; XVariable.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (updateXNumber && node != null) { String curDir = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { curDir = ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName(); } else if (directories.contains(((IconNode) node.getParent()).getName())) { curDir = ((IconNode) node.getParent()).getName(); } else { curDir = ""; } for (int i = 0; i < graphed.size(); i++) { if (graphed.get(i).getDirectory().equals(curDir)) { graphed.get(i).setXNumber(XVariable.getSelectedIndex()); } } } } }); LogX = new JCheckBox("LogX"); LogX.setSelected(false); LogY = new JCheckBox("LogY"); LogY.setSelected(false); visibleLegend = new JCheckBox("Visible Legend"); visibleLegend.setSelected(true); XMin = new JTextField(); XMax = new JTextField(); XScale = new JTextField(); YMin = new JTextField(); YMax = new JTextField(); YScale = new JTextField(); // creates the buttons for the graph frame JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); saveAs.addActionListener(this); export = new JButton("Export"); refresh = new JButton("Refresh"); // exportJPeg = new JButton("Export As JPEG"); // exportPng = new JButton("Export As PNG"); // exportPdf = new JButton("Export As PDF"); // exportEps = new JButton("Export As EPS"); // exportSvg = new JButton("Export As SVG"); // exportCsv = new JButton("Export As CSV"); run.addActionListener(this); save.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); // exportJPeg.addActionListener(this); // exportPng.addActionListener(this); // exportPdf.addActionListener(this); // exportEps.addActionListener(this); // exportSvg.addActionListener(this); // exportCsv.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // ButtonHolder.add(exportJPeg); // ButtonHolder.add(exportPng); // ButtonHolder.add(exportPdf); // ButtonHolder.add(exportEps); // ButtonHolder.add(exportSvg); // ButtonHolder.add(exportCsv); // puts all the components of the graph gui into a display panel // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); // determines maximum and minimum values and resizes resize(dataset); this.revalidate(); } private void readGraphSpecies(String file) { Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if (file.contains(".dtsd")) graphSpecies = (new DTSDParser(file)).getSpecies(); else graphSpecies = new TSDParser(file, true).getSpecies(); Gui.frame.setCursor(null); if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); i } } } } /** * This public helper method parses the output file of ODE, monte carlo, and * markov abstractions. */ public ArrayList<ArrayList<Double>> readData(String file, String label, String directory, boolean warning) { warn = warning; String[] s = file.split(separator); String getLast = s[s.length - 1]; String stem = ""; int t = 0; try { while (!Character.isDigit(getLast.charAt(t))) { stem += getLast.charAt(t); t++; } } catch (Exception e) { } if ((label.contains("average") && file.contains("mean")) || (label.contains("variance") && file.contains("variance")) || (label.contains("deviation") && file.contains("standard_deviation"))) { Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); TSDParser p = new TSDParser(file, warn); Gui.frame.setCursor(null); warn = p.getWarning(); graphSpecies = p.getSpecies(); ArrayList<ArrayList<Double>> data = p.getData(); if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } else if (averageOrder != null) { for (String spec : averageOrder) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!averageOrder.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } return data; } if (label.contains("average") || label.contains("variance") || label.contains("deviation")) { ArrayList<String> runs = new ArrayList<String>(); if (directory == null) { String[] files = new File(outDir).list(); for (String f : files) { if (f.contains(stem) && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { runs.add(f); } } } else { String[] files = new File(outDir + separator + directory).list(); for (String f : files) { if (f.contains(stem) && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { runs.add(f); } } } if (label.contains("average")) { return calculateAverageVarianceDeviation(runs, 0, directory, warn, false); } else if (label.contains("variance")) { return calculateAverageVarianceDeviation(runs, 1, directory, warn, false); } else { return calculateAverageVarianceDeviation(runs, 2, directory, warn, false); } } //if it's not a stats file else { Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); DTSDParser dtsdParser; TSDParser p; ArrayList<ArrayList<Double>> data; if (file.contains(".dtsd")) { dtsdParser = new DTSDParser(file); Gui.frame.setCursor(null); warn = false; graphSpecies = dtsdParser.getSpecies(); data = dtsdParser.getData(); } else { p = new TSDParser(file, warn); Gui.frame.setCursor(null); warn = p.getWarning(); graphSpecies = p.getSpecies(); data = p.getData(); } if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } else if (averageOrder != null) { for (String spec : averageOrder) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!averageOrder.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } return data; } } /** * This method adds and removes plots from the graph depending on what check * boxes are selected. */ public void actionPerformed(ActionEvent e) { // if the save button is clicked if (e.getSource() == run) { reb2sac.getRunButton().doClick(); } if (e.getSource() == save) { save(); } // if the save as button is clicked if (e.getSource() == saveAs) { saveAs(); } // if the export button is clicked else if (e.getSource() == export) { export(); } else if (e.getSource() == refresh) { refresh(); } else if (e.getActionCommand().equals("rename")) { String rename = JOptionPane.showInputDialog(Gui.frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE); if (rename != null) { rename = rename.trim(); } else { return; } if (!rename.equals("")) { boolean write = true; if (rename.equals(node.getName())) { write = false; } else if (new File(outDir + separator + rename).exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(outDir + separator + rename); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getChildCount() > 0 && ((IconNode) simDir.getChildAt(i)).getName().equals(rename)) { simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } for (int i = 0; i < graphed.size(); i++) { if (graphed.get(i).getDirectory().equals(rename)) { graphed.remove(i); i } } } else { write = false; } } if (write) { String getFile = node.getName(); IconNode s = node; while (s.getParent().getParent() != null) { getFile = s.getName() + separator + getFile; s = (IconNode) s.getParent(); } getFile = outDir + separator + getFile; new File(getFile).renameTo(new File(outDir + separator + rename)); for (GraphSpecies spec : graphed) { if (spec.getDirectory().equals(node.getName())) { spec.setDirectory(rename); } } directories.remove(node.getName()); directories.add(rename); node.setUserObject(rename); node.setName(rename); simDir.remove(node); int i; for (i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { if (((IconNode) simDir.getChildAt(i)).getName().compareToIgnoreCase(rename) > 0) { simDir.insert(node, i); break; } } else { break; } } simDir.insert(node, i); ArrayList<String> rows = new ArrayList<String>(); for (i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); int select = 0; for (i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } if (rename.equals(node.getName())) { select = i; } } tree.removeTreeSelectionListener(t); addTreeListener(); tree.setSelectionRow(select); } } } else if (e.getActionCommand().equals("recalculate")) { TreePath select = tree.getSelectionPath(); String[] files; if (((IconNode) select.getLastPathComponent()).getParent() != null) { files = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName()).list(); } else { files = new File(outDir).list(); } ArrayList<String> runs = new ArrayList<String>(); for (String file : files) { if (file.contains("run-") && file.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { runs.add(file); } } if (((IconNode) select.getLastPathComponent()).getParent() != null) { calculateAverageVarianceDeviation(runs, 0, ((IconNode) select.getLastPathComponent()).getName(), warn, true); } else { calculateAverageVarianceDeviation(runs, 0, null, warn, true); } } else if (e.getActionCommand().equals("delete")) { TreePath[] selected = tree.getSelectionPaths(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; for (TreeSelectionListener listen : tree.getTreeSelectionListeners()) { tree.removeTreeSelectionListener(listen); } tree.addTreeSelectionListener(t); for (TreePath select : selected) { tree.setSelectionPath(select); if (((IconNode) select.getLastPathComponent()).getParent() != null) { for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)) == ((IconNode) select.getLastPathComponent())) { if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { simDir.remove(i); File dir = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName()); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } directories.remove(((IconNode) select.getLastPathComponent()).getName()); for (int j = 0; j < graphed.size(); j++) { if (graphed.get(j).getDirectory().equals(((IconNode) select.getLastPathComponent()).getName())) { graphed.remove(j); j } } } else { String name = ((IconNode) select.getLastPathComponent()).getName(); if (name.equals("Average")) { name = "mean"; } else if (name.equals("Variance")) { name = "variance"; } else if (name.equals("Standard Deviation")) { name = "standard_deviation"; } else if (name.equals("Percent Termination")) { name = "percent-term-time"; simDir.remove(i); } else if (name.equals("Termination Time")) { name = "term-time"; simDir.remove(i); } else { simDir.remove(i); } name += "." + printer_id.substring(0, printer_id.length() - 8); File dir = new File(outDir + separator + name); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } int count = 0; boolean m = false; if (new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { m = true; } boolean v = false; if (new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { v = true; } boolean d = false; if (new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { d = true; } for (int j = 0; j < simDir.getChildCount(); j++) { if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) { if (((IconNode) simDir.getChildAt(j)).getName().contains("run-")) { count++; } } } if (count == 0) { for (int j = 0; j < simDir.getChildCount(); j++) { if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) { if (((IconNode) simDir.getChildAt(j)).getName().contains("Average") && !m) { simDir.remove(j); j } else if (((IconNode) simDir.getChildAt(j)).getName().contains("Variance") && !v) { simDir.remove(j); j } else if (((IconNode) simDir.getChildAt(j)).getName().contains("Deviation") && !d) { simDir.remove(j); j } } } } } } else if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { for (int j = 0; j < simDir.getChildAt(i).getChildCount(); j++) { if (((IconNode) ((IconNode) simDir.getChildAt(i)).getChildAt(j)) == ((IconNode) select.getLastPathComponent())) { String name = ((IconNode) select.getLastPathComponent()).getName(); if (name.equals("Average")) { name = "mean"; } else if (name.equals("Variance")) { name = "variance"; } else if (name.equals("Standard Deviation")) { name = "standard_deviation"; } else if (name.equals("Percent Termination")) { name = "percent-term-time"; ((IconNode) simDir.getChildAt(i)).remove(j); } else if (name.equals("Termination Time")) { name = "term-time"; ((IconNode) simDir.getChildAt(i)).remove(j); } else { ((IconNode) simDir.getChildAt(i)).remove(j); } name += "." + printer_id.substring(0, printer_id.length() - 8); File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + name); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } boolean checked = false; for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { ((IconNode) simDir.getChildAt(i)).setIcon(MetalIconFactory.getTreeFolderIcon()); ((IconNode) simDir.getChildAt(i)).setIconName(""); } int count = 0; boolean m = false; if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { m = true; } boolean v = false; if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { v = true; } boolean d = false; if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { d = true; } for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getChildCount() == 0) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("run-")) { count++; } } } if (count == 0) { for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getChildCount() == 0) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Average") && !m) { ((IconNode) simDir.getChildAt(i)).remove(k); k } else if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Variance") && !v) { ((IconNode) simDir.getChildAt(i)).remove(k); k } else if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Deviation") && !d) { ((IconNode) simDir.getChildAt(i)).remove(k); k } } } } } } } } } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } else if (e.getActionCommand().equals("delete runs")) { for (int i = simDir.getChildCount() - 1; i >= 0; i if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) { String name = ((IconNode) simDir.getChildAt(i)).getName(); if (name.equals("Average")) { name = "mean"; } else if (name.equals("Variance")) { name = "variance"; } else if (name.equals("Standard Deviation")) { name = "standard_deviation"; } else if (name.equals("Percent Termination")) { name = "percent-term-time"; } else if (name.equals("Termination Time")) { name = "term-time"; } name += "." + printer_id.substring(0, printer_id.length() - 8); File dir = new File(outDir + separator + name); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } else if (e.getActionCommand().equals("delete all")) { for (int i = simDir.getChildCount() - 1; i >= 0; i if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) { String name = ((IconNode) simDir.getChildAt(i)).getName(); if (name.equals("Average")) { name = "mean"; } else if (name.equals("Variance")) { name = "variance"; } else if (name.equals("Standard Deviation")) { name = "standard_deviation"; } else if (name.equals("Percent Termination")) { name = "percent-term-time"; } else if (name.equals("Termination Time")) { name = "term-time"; } name += "." + printer_id.substring(0, printer_id.length() - 8); File dir = new File(outDir + separator + name); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } simDir.remove(i); } else { File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName()); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } // // if the export as jpeg button is clicked // else if (e.getSource() == exportJPeg) { // export(0); // // if the export as png button is clicked // else if (e.getSource() == exportPng) { // export(1); // // if the export as pdf button is clicked // else if (e.getSource() == exportPdf) { // export(2); // // if the export as eps button is clicked // else if (e.getSource() == exportEps) { // export(3); // // if the export as svg button is clicked // else if (e.getSource() == exportSvg) { // export(4); // } else if (e.getSource() == exportCsv) { // export(5); } /** * Private method used to auto resize the graph. */ private void resize(XYSeriesCollection dataset) { NumberFormat num = NumberFormat.getInstance(); num.setMaximumFractionDigits(4); num.setGroupingUsed(false); XYPlot plot = chart.getXYPlot(); XYItemRenderer rend = plot.getRenderer(); double minY = Double.MAX_VALUE; double maxY = Double.MIN_VALUE; double minX = Double.MAX_VALUE; double maxX = Double.MIN_VALUE; for (int j = 0; j < dataset.getSeriesCount(); j++) { XYSeries series = dataset.getSeries(j); double[][] seriesArray = series.toArray(); Boolean visible = rend.getSeriesVisible(j); if (visible == null || visible.equals(true)) { for (int k = 0; k < series.getItemCount(); k++) { maxY = Math.max(seriesArray[1][k], maxY); minY = Math.min(seriesArray[1][k], minY); maxX = Math.max(seriesArray[0][k], maxX); minX = Math.min(seriesArray[0][k], minX); } } } NumberAxis axis = (NumberAxis) plot.getRangeAxis(); if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) { axis.setRange(-1, 1); } // else if ((maxY - minY) < .001) { // axis.setRange(minY - 1, maxY + 1); else { /* * axis.setRange(Double.parseDouble(num.format(minY - * (Math.abs(minY) .1))), Double .parseDouble(num.format(maxY + * (Math.abs(maxY) .1)))); */ if ((maxY - minY) < .001) { axis.setStandardTickUnits(new StandardTickUnitSource()); } else { axis.setStandardTickUnits(NumberAxis.createStandardTickUnits()); } axis.setRange(minY - (Math.abs(minY) * .1), maxY + (Math.abs(maxY) * .1)); } axis.setAutoTickUnitSelection(true); if (LogY.isSelected()) { try { LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis().getLabel()); rangeAxis.setStrictValuesFlag(false); plot.setRangeAxis(rangeAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel()); plot.setRangeAxis(rangeAxis); LogY.setSelected(false); } } if (visibleLegend.isSelected()) { if (chart.getLegend() == null) { chart.addLegend(legend); } } else { if (chart.getLegend() != null) { legend = chart.getLegend(); } chart.removeLegend(); } axis = (NumberAxis) plot.getDomainAxis(); if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) { axis.setRange(-1, 1); } // else if ((maxX - minX) < .001) { // axis.setRange(minX - 1, maxX + 1); else { if ((maxX - minX) < .001) { axis.setStandardTickUnits(new StandardTickUnitSource()); } else { axis.setStandardTickUnits(NumberAxis.createStandardTickUnits()); } axis.setRange(minX, maxX); } axis.setAutoTickUnitSelection(true); if (LogX.isSelected()) { try { LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis().getLabel()); domainAxis.setStrictValuesFlag(false); plot.setDomainAxis(domainAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel()); plot.setRangeAxis(domainAxis); LogX.setSelected(false); } } } /** * After the chart is redrawn, this method calculates the x and y scale and * updates those text fields. */ public void chartProgress(ChartProgressEvent e) { // if the chart drawing is started if (e.getType() == ChartProgressEvent.DRAWING_STARTED) { this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } // if the chart drawing is finished else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) { this.setCursor(null); JFreeChart chart = e.getChart(); XYPlot plot = (XYPlot) chart.getXYPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); YMin.setText("" + axis.getLowerBound()); YMax.setText("" + axis.getUpperBound()); YScale.setText("" + axis.getTickUnit().getSize()); axis = (NumberAxis) plot.getDomainAxis(); XMin.setText("" + axis.getLowerBound()); XMax.setText("" + axis.getUpperBound()); XScale.setText("" + axis.getTickUnit().getSize()); } } /** * Invoked when the mouse is clicked on the chart. Allows the user to edit * the title and labels of the chart. */ public void mouseClicked(MouseEvent e) { if (e.getSource() != tree) { if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { if (timeSeries) { editGraph(); } else { editProbGraph(); } } } } public void mousePressed(MouseEvent e) { if (e.getSource() == tree) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); if (selRow < 0) return; TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); boolean set = true; for (TreePath p : tree.getSelectionPaths()) { if (p.equals(selPath)) { tree.addSelectionPath(selPath); set = false; } } if (set) { tree.setSelectionPath(selPath); } if (e.isPopupTrigger()) { popup.removeAll(); if (node.getChildCount() != 0) { JMenuItem recalculate = new JMenuItem("Recalculate Statistics"); recalculate.addActionListener(this); recalculate.setActionCommand("recalculate"); popup.add(recalculate); } if (node.getChildCount() != 0 && node.getParent() != null) { JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(rename); } if (node.getParent() != null) { JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); popup.add(delete); } else { JMenuItem delete = new JMenuItem("Delete All Runs"); delete.addActionListener(this); delete.setActionCommand("delete runs"); popup.add(delete); JMenuItem deleteAll = new JMenuItem("Delete Recursive"); deleteAll.addActionListener(this); deleteAll.setActionCommand("delete all"); popup.add(deleteAll); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } } public void mouseReleased(MouseEvent e) { if (e.getSource() == tree) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); if (selRow < 0) return; TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); boolean set = true; for (TreePath p : tree.getSelectionPaths()) { if (p.equals(selPath)) { tree.addSelectionPath(selPath); set = false; } } if (set) { tree.setSelectionPath(selPath); } if (e.isPopupTrigger()) { popup.removeAll(); if (node.getChildCount() != 0) { JMenuItem recalculate = new JMenuItem("Recalculate Statistics"); recalculate.addActionListener(this); recalculate.setActionCommand("recalculate"); popup.add(recalculate); } if (node.getChildCount() != 0 && node.getParent() != null) { JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(rename); } if (node.getParent() != null) { JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); popup.add(delete); } else { JMenuItem delete = new JMenuItem("Delete All Runs"); delete.addActionListener(this); delete.setActionCommand("delete runs"); popup.add(delete); JMenuItem deleteAll = new JMenuItem("Delete Recursive"); deleteAll.addActionListener(this); deleteAll.setActionCommand("delete all"); popup.add(deleteAll); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } } /** * This method currently does nothing. */ public void mouseEntered(MouseEvent e) { } /** * This method currently does nothing. */ public void mouseExited(MouseEvent e) { } private void setUpShapesAndColors() { DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); colors = new HashMap<String, Paint>(); shapes = new HashMap<String, Shape>(); colors.put("Red", draw.getNextPaint()); colors.put("Blue", draw.getNextPaint()); colors.put("Green", draw.getNextPaint()); colors.put("Yellow", draw.getNextPaint()); colors.put("Magenta", draw.getNextPaint()); colors.put("Cyan", draw.getNextPaint()); colors.put("Tan", draw.getNextPaint()); colors.put("Gray (Dark)", draw.getNextPaint()); colors.put("Red (Dark)", draw.getNextPaint()); colors.put("Blue (Dark)", draw.getNextPaint()); colors.put("Green (Dark)", draw.getNextPaint()); colors.put("Yellow (Dark)", draw.getNextPaint()); colors.put("Magenta (Dark)", draw.getNextPaint()); colors.put("Cyan (Dark)", draw.getNextPaint()); colors.put("Black", draw.getNextPaint()); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); // colors.put("Red ", draw.getNextPaint()); // colors.put("Blue ", draw.getNextPaint()); // colors.put("Green ", draw.getNextPaint()); // colors.put("Yellow ", draw.getNextPaint()); // colors.put("Magenta ", draw.getNextPaint()); // colors.put("Cyan ", draw.getNextPaint()); colors.put("Gray", draw.getNextPaint()); colors.put("Red (Extra Dark)", draw.getNextPaint()); colors.put("Blue (Extra Dark)", draw.getNextPaint()); colors.put("Green (Extra Dark)", draw.getNextPaint()); colors.put("Yellow (Extra Dark)", draw.getNextPaint()); colors.put("Magenta (Extra Dark)", draw.getNextPaint()); colors.put("Cyan (Extra Dark)", draw.getNextPaint()); colors.put("Red (Light)", draw.getNextPaint()); colors.put("Blue (Light)", draw.getNextPaint()); colors.put("Green (Light)", draw.getNextPaint()); colors.put("Yellow (Light)", draw.getNextPaint()); colors.put("Magenta (Light)", draw.getNextPaint()); colors.put("Cyan (Light)", draw.getNextPaint()); colors.put("Gray (Light)", new java.awt.Color(238, 238, 238)); shapes.put("Square", draw.getNextShape()); shapes.put("Circle", draw.getNextShape()); shapes.put("Triangle", draw.getNextShape()); shapes.put("Diamond", draw.getNextShape()); shapes.put("Rectangle (Horizontal)", draw.getNextShape()); shapes.put("Triangle (Upside Down)", draw.getNextShape()); shapes.put("Circle (Half)", draw.getNextShape()); shapes.put("Arrow", draw.getNextShape()); shapes.put("Rectangle (Vertical)", draw.getNextShape()); shapes.put("Arrow (Backwards)", draw.getNextShape()); } public void editGraph() { final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { old.add(g); } titlePanel = new JPanel(new BorderLayout()); JLabel titleLabel = new JLabel("Title:"); JLabel xLabel = new JLabel("X-Axis Label:"); JLabel yLabel = new JLabel("Y-Axis Label:"); final JTextField title = new JTextField(chart.getTitle().getText(), 5); final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5); final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5); final JLabel xMin = new JLabel("X-Min:"); final JLabel xMax = new JLabel("X-Max:"); final JLabel xScale = new JLabel("X-Step:"); final JLabel yMin = new JLabel("Y-Min:"); final JLabel yMax = new JLabel("Y-Max:"); final JLabel yScale = new JLabel("Y-Step:"); LogX.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { XYPlot plot = (XYPlot) chart.getXYPlot(); try { LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis().getLabel()); domainAxis.setStrictValuesFlag(false); plot.setRangeAxis(domainAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel()); plot.setRangeAxis(domainAxis); LogX.setSelected(false); } } } }); LogY.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { XYPlot plot = (XYPlot) chart.getXYPlot(); try { LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis().getLabel()); rangeAxis.setStrictValuesFlag(false); plot.setRangeAxis(rangeAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Semilog plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel()); plot.setRangeAxis(rangeAxis); LogY.setSelected(false); } } } }); visibleLegend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { if (chart.getLegend() == null) { chart.addLegend(legend); } } else { if (chart.getLegend() != null) { legend = chart.getLegend(); } chart.removeLegend(); } } }); resize.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { xMin.setEnabled(false); XMin.setEnabled(false); xMax.setEnabled(false); XMax.setEnabled(false); xScale.setEnabled(false); XScale.setEnabled(false); yMin.setEnabled(false); YMin.setEnabled(false); yMax.setEnabled(false); YMax.setEnabled(false); yScale.setEnabled(false); YScale.setEnabled(false); } else { xMin.setEnabled(true); XMin.setEnabled(true); xMax.setEnabled(true); XMax.setEnabled(true); xScale.setEnabled(true); XScale.setEnabled(true); yMin.setEnabled(true); YMin.setEnabled(true); yMax.setEnabled(true); YMax.setEnabled(true); yScale.setEnabled(true); YScale.setEnabled(true); } } }); if (resize.isSelected()) { xMin.setEnabled(false); XMin.setEnabled(false); xMax.setEnabled(false); XMax.setEnabled(false); xScale.setEnabled(false); XScale.setEnabled(false); yMin.setEnabled(false); YMin.setEnabled(false); yMax.setEnabled(false); YMax.setEnabled(false); yScale.setEnabled(false); YScale.setEnabled(false); } else { xMin.setEnabled(true); XMin.setEnabled(true); xMax.setEnabled(true); XMax.setEnabled(true); xScale.setEnabled(true); XScale.setEnabled(true); yMin.setEnabled(true); YMin.setEnabled(true); yMax.setEnabled(true); YMax.setEnabled(true); yScale.setEnabled(true); YScale.setEnabled(true); } Properties p = null; if (learnSpecs != null) { try { String[] split = outDir.split(separator); p = new Properties(); FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn")); p.load(load); load.close(); } catch (Exception e) { } } String simDirString = outDir.split(separator)[outDir.split(separator).length - 1]; simDir = new IconNode(simDirString, simDirString); simDir.setIconName(""); String[] files = new File(outDir).list(); // for (int i = 1; i < files.length; i++) { // String index = files[i]; // int j = i; // while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) { // files[j] = files[j - 1]; // j = j - 1; // files[j] = index; boolean addMean = false; boolean addVar = false; boolean addDev = false; boolean addTerm = false; boolean addPercent = false; boolean addConst = false; directories = new ArrayList<String>(); for (String file : files) { if ((file.length() > 3 && (file.substring(file.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8)))) || (file.length() > 4 && file.substring(file.length() - 5).equals(".dtsd"))) { if (file.contains("run-") || file.contains("mean")) { addMean = true; } else if (file.contains("run-") || file.contains("variance")) { addVar = true; } else if (file.contains("run-") || file.contains("standard_deviation")) { addDev = true; } else if (file.startsWith("term-time")) { addTerm = true; } else if (file.contains("percent-term-time")) { addPercent = true; } else if (file.contains("sim-rep")) { addConst = true; } else { IconNode n = new IconNode(file.substring(0, file.length() - 4), file.substring(0, file.length() - 4)); boolean added = false; for (int j = 0; j < simDir.getChildCount(); j++) { if (simDir.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) { simDir.insert(n, j); added = true; break; } } if (!added) { simDir.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(file.substring(0, file.length() - 4)) && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } else if (new File(outDir + separator + file).isDirectory()) { boolean addIt = false; String[] files3 = new File(outDir + separator + file).list(); // for (int i = 1; i < files3.length; i++) { // String index = files3[i]; // int j = i; // while ((j > 0) && files3[j - 1].compareToIgnoreCase(index) > // files3[j] = files3[j - 1]; // j = j - 1; // files3[j] = index; for (String getFile : files3) { if ((getFile.length() > 3 && (getFile.substring(getFile.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8)))) || (getFile.length() > 4 && getFile.substring(getFile.length() - 5).equals(".dtsd"))) { addIt = true; } else if (new File(outDir + separator + file + separator + getFile).isDirectory()) { for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) { if ((getFile2.length() > 3 && (getFile2.substring(getFile2.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8)))) || (getFile2.length() > 4 && getFile.substring(getFile.length() - 5).equals(".dtsd"))) { addIt = true; } } } } if (addIt) { directories.add(file); IconNode d = new IconNode(file, file); d.setIconName(""); boolean addMean2 = false; boolean addVar2 = false; boolean addDev2 = false; boolean addTerm2 = false; boolean addPercent2 = false; boolean addConst2 = false; for (String f : files3) { if (f.contains(printer_id.substring(0, printer_id.length() - 8)) || f.contains(".dtsd")) { if (f.contains("run-") || f.contains("mean")) { addMean2 = true; } else if (f.contains("run-") || f.contains("variance")) { addVar2 = true; } else if (f.contains("run-") || f.contains("standard_deviation")) { addDev2 = true; } else if (f.startsWith("term-time")) { addTerm2 = true; } else if (f.contains("percent-term-time")) { addPercent2 = true; } else if (f.contains("sim-rep")) { addConst2 = true; } else { IconNode n = new IconNode(f.substring(0, f.length() - 4), f.substring(0, f.length() - 4)); boolean added = false; for (int j = 0; j < d.getChildCount(); j++) { if (d.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) { d.insert(n, j); added = true; break; } } if (!added) { d.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(f.substring(0, f.length() - 4)) && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } else if (new File(outDir + separator + file + separator + f).isDirectory()) { boolean addIt2 = false; String[] files2 = new File(outDir + separator + file + separator + f).list(); // for (int i = 1; i < files2.length; i++) { // String index = files2[i]; // int j = i; // while ((j > 0) && files2[j - // 1].compareToIgnoreCase(index) > 0) { // files2[j] = files2[j - 1]; // j = j - 1; // files2[j] = index; for (String getFile2 : files2) { if ((getFile2.length() > 3 && (getFile2.substring(getFile2.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8)))) || (getFile2.length() > 4 && getFile2.substring(getFile2.length() - 5).equals(".dtsd"))) { addIt2 = true; } } if (addIt2) { directories.add(file + separator + f); IconNode d2 = new IconNode(f, f); d2.setIconName(""); boolean addMean3 = false; boolean addVar3 = false; boolean addDev3 = false; boolean addTerm3 = false; boolean addPercent3 = false; boolean addConst3 = false; for (String f2 : files2) { if (f2.contains(printer_id.substring(0, printer_id.length() - 8)) || f2.contains(".dtsd")) { if (f2.contains("run-") || f2.contains("mean")) { addMean3 = true; } else if (f2.contains("run-") || f2.contains("variance")) { addVar3 = true; } else if (f2.contains("run-") || f2.contains("standard_deviation")) { addDev3 = true; } else if (f2.startsWith("term-time")) { addTerm3 = true; } else if (f2.contains("percent-term-time")) { addPercent3 = true; } else if (f2.contains("sim-rep")) { addConst3 = true; } else { IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4)); boolean added = false; for (int j = 0; j < d2.getChildCount(); j++) { if (d2.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) { d2.insert(n, j); added = true; break; } } if (!added) { d2.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(f2.substring(0, f2.length() - 4)) && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } if (addMean3) { IconNode n = new IconNode("Average", "Average"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addDev3) { IconNode n = new IconNode("Standard Deviation", "Standard Deviation"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addVar3) { IconNode n = new IconNode("Variance", "Variance"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addTerm3) { IconNode n = new IconNode("Termination Time", "Termination Time"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addPercent3) { IconNode n = new IconNode("Percent Termination", "Percent Termination"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addConst3) { IconNode n = new IconNode("Constraint Termination", "Constraint Termination"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String r2 = null; for (String s : files2) { if (s.contains("run-")) { r2 = s; } } if (r2 != null) { for (String s : files2) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals("dtsd")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + file + separator + f + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists() || new File(outDir + separator + file + separator + f + separator + "run-" + (i + 1) + ".dtsd").exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1)); if (d2.getChildCount() > 3) { boolean added = false; for (int j = 3; j < d2.getChildCount(); j++) { if (d2.getChildAt(j) .toString() .compareToIgnoreCase( (String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) { d2.insert(n, j); added = true; break; } } if (!added) { d2.add(n); } } else { d2.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); d2.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } boolean added = false; for (int j = 0; j < d.getChildCount(); j++) { if ((d.getChildAt(j).toString().compareToIgnoreCase(d2.toString()) > 0) || new File(outDir + separator + d.toString() + separator + (d.getChildAt(j).toString() + "." + printer_id.substring(0, printer_id.length() - 8))).isFile()) { d.insert(d2, j); added = true; break; } } if (!added) { d.add(d2); } } } } if (addMean2) { IconNode n = new IconNode("Average", "Average"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addDev2) { IconNode n = new IconNode("Standard Deviation", "Standard Deviation"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addVar2) { IconNode n = new IconNode("Variance", "Variance"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addTerm2) { IconNode n = new IconNode("Termination Time", "Termination Time"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addPercent2) { IconNode n = new IconNode("Percent Termination", "Percent Termination"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addConst2) { IconNode n = new IconNode("Constraint Termination", "Constraint Termination"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String r = null; for (String s : files3) { if (s.contains("run-")) { r = s; } } if (r != null) { for (String s : files3) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals("dtsd")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + file + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1)); if (d.getChildCount() > 3) { boolean added = false; for (int j = 3; j < d.getChildCount(); j++) { if (d.getChildAt(j) .toString() .compareToIgnoreCase( (String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) { d.insert(n, j); added = true; break; } } if (!added) { d.add(n); } } else { d.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); d.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } boolean added = false; for (int j = 0; j < simDir.getChildCount(); j++) { if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0) || new File(outDir + separator + (simDir.getChildAt(j).toString() + "." + printer_id.substring(0, printer_id.length() - 8))).isFile()) { simDir.insert(d, j); added = true; break; } } if (!added) { simDir.add(d); } } } } if (addMean) { IconNode n = new IconNode("Average", "Average"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addDev) { IconNode n = new IconNode("Standard Deviation", "Standard Deviation"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addVar) { IconNode n = new IconNode("Variance", "Variance"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addTerm) { IconNode n = new IconNode("Termination Time", "Termination Time"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addPercent) { IconNode n = new IconNode("Percent Termination", "Percent Termination"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addConst) { IconNode n = new IconNode("Constraint Termination", "Constraint Termination"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String runs = null; for (String s : new File(outDir).list()) { if (s.contains("run-")) { runs = s; } } if (runs != null) { for (String s : new File(outDir).list()) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals("dtsd")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists() || new File(outDir + separator + "run-" + (i + 1) + ".dtsd").exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1)); if (simDir.getChildCount() > 3) { boolean added = false; for (int j = 3; j < simDir.getChildCount(); j++) { if (simDir .getChildAt(j) .toString() .compareToIgnoreCase( (String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) { simDir.insert(n, j); added = true; break; } } if (!added) { simDir.add(n); } } else { simDir.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); simDir.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } if (simDir.getChildCount() == 0) { JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data", JOptionPane.PLAIN_MESSAGE); } else { all = new JPanel(new BorderLayout()); specPanel = new JPanel(); scrollpane = new JScrollPane(); refreshTree(); addTreeListener(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); scroll = new JScrollPane(); scroll.setPreferredSize(new Dimension(1050, 500)); JPanel editPanel = new JPanel(new BorderLayout()); editPanel.add(specPanel, "Center"); scroll.setViewportView(editPanel); // JButton ok = new JButton("Ok"); /* * ok.addActionListener(new ActionListener() { public void * actionPerformed(ActionEvent e) { double minY; double maxY; double * scaleY; double minX; double maxX; double scaleX; change = true; * try { minY = Double.parseDouble(YMin.getText().trim()); maxY = * Double.parseDouble(YMax.getText().trim()); scaleY = * Double.parseDouble(YScale.getText().trim()); minX = * Double.parseDouble(XMin.getText().trim()); maxX = * Double.parseDouble(XMax.getText().trim()); scaleX = * Double.parseDouble(XScale.getText().trim()); NumberFormat num = * NumberFormat.getInstance(); num.setMaximumFractionDigits(4); * num.setGroupingUsed(false); minY = * Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); } catch (Exception e1) { * JOptionPane.showMessageDialog(BioSim.frame, "Must enter doubles * into the inputs " + "to change the graph's dimensions!", "Error", * JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected; * selected = ""; ArrayList<XYSeries> graphData = new * ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = * (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int * thisOne = -1; for (int i = 1; i < graphed.size(); i++) { * GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && * (graphed.get(j - * 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { * graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, * index); } ArrayList<GraphSpecies> unableToGraph = new * ArrayList<GraphSpecies>(); HashMap<String, * ArrayList<ArrayList<Double>>> allData = new HashMap<String, * ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { * if (g.getDirectory().equals("")) { thisOne++; * rend.setSeriesVisible(thisOne, true); * rend.setSeriesLinesVisible(thisOne, g.getConnected()); * rend.setSeriesShapesFilled(thisOne, g.getFilled()); * rend.setSeriesShapesVisible(thisOne, g.getVisible()); * rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); * rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if * (!g.getRunNumber().equals("Average") && * !g.getRunNumber().equals("Variance") && * !g.getRunNumber().equals("Standard Deviation")) { if (new * File(outDir + separator + g.getRunNumber() + "." + * printer_id.substring(0, printer_id.length() - 8)).exists()) { * readGraphSpecies(outDir + separator + g.getRunNumber() + "." + * printer_id.substring(0, printer_id.length() - 8), BioSim.frame); * ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getRunNumber() + * "." + printer_id.substring(0, printer_id.length() - 8), * BioSim.frame, y.getText().trim(), g.getRunNumber(), null); for * (int i = 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = * false; try { for (String s : new File(outDir).list()) { if * (s.length() > 3 && s.substring(0, 4).equals("run-")) { * ableToGraph = true; } } } catch (Exception e1) { ableToGraph = * false; } if (ableToGraph) { int next = 1; while (!new File(outDir * + separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { next++; } * readGraphSpecies(outDir + separator + "run-" + next + "." + * printer_id.substring(0, printer_id.length() - 8), BioSim.frame); * ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + "run-1." + * printer_id.substring(0, printer_id.length() - 8), BioSim.frame, * y.getText().trim(), g.getRunNumber().toLowerCase(), null); for * (int i = 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } } else { thisOne++; * rend.setSeriesVisible(thisOne, true); * rend.setSeriesLinesVisible(thisOne, g.getConnected()); * rend.setSeriesShapesFilled(thisOne, g.getFilled()); * rend.setSeriesShapesVisible(thisOne, g.getVisible()); * rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); * rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if * (!g.getRunNumber().equals("Average") && * !g.getRunNumber().equals("Variance") && * !g.getRunNumber().equals("Standard Deviation")) { if (new * File(outDir + separator + g.getDirectory() + separator + * g.getRunNumber() + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { readGraphSpecies( outDir + * separator + g.getDirectory() + separator + g.getRunNumber() + "." * + printer_id.substring(0, printer_id.length() - 8), * BioSim.frame); ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getDirectory() + * separator + g.getRunNumber() + "." + printer_id.substring(0, * printer_id.length() - 8), BioSim.frame, y.getText().trim(), * g.getRunNumber(), g.getDirectory()); for (int i = 2; i < * graphSpecies.size(); i++) { String index = graphSpecies.get(i); * ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) * && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { * graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, * data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); * data.set(j, index2); } allData.put(g.getRunNumber() + " " + * g.getDirectory(), data); } graphData.add(new * XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = * 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = * false; try { for (String s : new File(outDir + separator + * g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, * 4).equals("run-")) { ableToGraph = true; } } } catch (Exception * e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; * while (!new File(outDir + separator + g.getDirectory() + * separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { next++; } * readGraphSpecies(outDir + separator + g.getDirectory() + * separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8), BioSim.frame); * ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getDirectory() + * separator + "run-1." + printer_id.substring(0, * printer_id.length() - 8), BioSim.frame, y.getText().trim(), * g.getRunNumber().toLowerCase(), g.getDirectory()); for (int i = * 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g : * unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset * = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); * i++) { dataset.addSeries(graphData.get(i)); } * fixGraph(title.getText().trim(), x.getText().trim(), * y.getText().trim(), dataset); * chart.getXYPlot().setRenderer(rend); XYPlot plot = * chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } * else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); * axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); * axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) * plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); * axis.setRange(minX, maxX); axis.setTickUnit(new * NumberTickUnit(scaleX)); } //f.dispose(); } }); */ // final JButton cancel = new JButton("Cancel"); // cancel.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // selected = ""; // int size = graphed.size(); // for (int i = 0; i < size; i++) { // graphed.remove(); // for (GraphSpecies g : old) { // graphed.add(g); // f.dispose(); final JButton deselect = new JButton("Deselect All"); deselect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // selected = ""; int size = graphed.size(); for (int i = 0; i < size; i++) { graphed.remove(); } IconNode n = simDir; while (n != null) { if (n.isLeaf()) { n.setIcon(MetalIconFactory.getTreeLeafIcon()); n.setIconName(""); IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); if (check == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); if (check2 == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { n = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); } } else { n = check2; } } } else { n = check; } } else { n.setIcon(MetalIconFactory.getTreeFolderIcon()); n.setIconName(""); n = (IconNode) n.getChildAt(0); } } tree.revalidate(); tree.repaint(); if (tree.getSelectionCount() > 0) { int selectedRow = tree.getSelectionRows()[0]; tree.setSelectionRow(0); tree.setSelectionRow(selectedRow); } } }); JPanel titlePanel1 = new JPanel(new GridLayout(3, 6)); JPanel titlePanel2 = new JPanel(new GridLayout(1, 6)); titlePanel1.add(titleLabel); titlePanel1.add(title); titlePanel1.add(xMin); titlePanel1.add(XMin); titlePanel1.add(yMin); titlePanel1.add(YMin); titlePanel1.add(xLabel); titlePanel1.add(x); titlePanel1.add(xMax); titlePanel1.add(XMax); titlePanel1.add(yMax); titlePanel1.add(YMax); titlePanel1.add(yLabel); titlePanel1.add(y); titlePanel1.add(xScale); titlePanel1.add(XScale); titlePanel1.add(yScale); titlePanel1.add(YScale); JPanel deselectPanel = new JPanel(); deselectPanel.add(deselect); titlePanel2.add(deselectPanel); titlePanel2.add(resize); titlePanel2.add(XVariable); titlePanel2.add(LogX); titlePanel2.add(LogY); titlePanel2.add(visibleLegend); titlePanel.add(titlePanel1, "Center"); titlePanel.add(titlePanel2, "South"); // JPanel buttonPanel = new JPanel(); // buttonPanel.add(ok); // buttonPanel.add(deselect); // buttonPanel.add(cancel); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); // all.add(buttonPanel, "South"); Object[] options = { "Ok", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, all, "Edit Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { double minY; double maxY; double scaleY; double minX; double maxX; double scaleX; change = true; try { minY = Double.parseDouble(YMin.getText().trim()); maxY = Double.parseDouble(YMax.getText().trim()); scaleY = Double.parseDouble(YScale.getText().trim()); minX = Double.parseDouble(XMin.getText().trim()); maxX = Double.parseDouble(XMax.getText().trim()); scaleX = Double.parseDouble(XScale.getText().trim()); /* * NumberFormat num = NumberFormat.getInstance(); * num.setMaximumFractionDigits(4); * num.setGroupingUsed(false); minY = * Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); */ } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Must enter doubles into the inputs " + "to change the graph's dimensions!", "Error", JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected; selected = ""; ArrayList<XYSeries> graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); } ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>(); HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) { if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists() || new File(outDir + separator + g.getRunNumber() + ".dtsd").exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { String extension = printer_id.substring(0, printer_id.length() - 8); if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists() == false && new File(outDir + separator + g.getRunNumber() + ".dtsd").exists()) { extension = "dtsd"; } data = readData(outDir + separator + g.getRunNumber() + "." + extension, g.getRunNumber(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber() .toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { boolean ableToGraph = false; try { for (String s : new File(outDir).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new File(outDir + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { next++; } ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } } } else { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) { if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists() || new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + ".dtsd").exists()) { ArrayList<ArrayList<Double>> data; //if the data has already been put into the data structure if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { String extension = printer_id.substring(0, printer_id.length() - 8); if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists() == false && new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + ".dtsd").exists()) { extension = "dtsd"; } data = readData( outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + extension, g.getRunNumber(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } //if it's one of the stats/termination files else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } //end average else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } //end variance else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } //end standard deviation else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } //end termination time else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } //end percent termination else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } //end constraint termination else { boolean ableToGraph = false; try { for (String s : new File(outDir + separator + g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { next++; } ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } } } } for (GraphSpecies g : unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) { dataset.addSeries(graphData.get(i)); } fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset); chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX); axis.setTickUnit(new NumberTickUnit(scaleX)); } } //end of "Ok" option being true else { selected = ""; int size = graphed.size(); for (int i = 0; i < size; i++) { graphed.remove(); } for (GraphSpecies g : old) { graphed.add(g); } } // WindowListener w = new WindowListener() { // public void windowClosing(WindowEvent arg0) { // cancel.doClick(); // public void windowOpened(WindowEvent arg0) { // public void windowClosed(WindowEvent arg0) { // public void windowIconified(WindowEvent arg0) { // public void windowDeiconified(WindowEvent arg0) { // public void windowActivated(WindowEvent arg0) { // public void windowDeactivated(WindowEvent arg0) { // f.addWindowListener(w); // f.setContentPane(all); // f.pack(); // Dimension screenSize; // try { // Toolkit tk = Toolkit.getDefaultToolkit(); // screenSize = tk.getScreenSize(); // catch (AWTError awe) { // screenSize = new Dimension(640, 480); // Dimension frameSize = f.getSize(); // if (frameSize.height > screenSize.height) { // frameSize.height = screenSize.height; // if (frameSize.width > screenSize.width) { // frameSize.width = screenSize.width; // int xx = screenSize.width / 2 - frameSize.width / 2; // int yy = screenSize.height / 2 - frameSize.height / 2; // f.setLocation(xx, yy); // f.setVisible(true); } } private void refreshTree() { tree = new JTree(simDir); if (!topLevel && learnSpecs == null) { tree.addMouseListener(this); } tree.putClientProperty("JTree.icons", makeIcons()); tree.setCellRenderer(new IconNodeRenderer()); DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer(); renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon()); renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon()); renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon()); } private void addTreeListener() { boolean stop = false; int selectionRow = 1; for (int i = 1; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (selected.equals(lastSelected)) { stop = true; selectionRow = i; break; } } tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); if (!directories.contains(node.getName()) && node.getParent() != null && !directories.contains(((IconNode) node.getParent()).getName() + separator + node.getName())) { selected = node.getName(); int select; if (selected.equals("Average")) { select = 0; } else if (selected.equals("Variance")) { select = 1; } else if (selected.equals("Standard Deviation")) { select = 2; } else if (selected.contains("-run")) { select = 0; } else if (selected.equals("Termination Time")) { select = 0; } else if (selected.equals("Percent Termination")) { select = 0; } else if (selected.equals("Constraint Termination")) { select = 0; } else { try { if (selected.contains("run-")) { select = Integer.parseInt(selected.substring(4)) + 2; } else { select = -1; } } catch (Exception e1) { select = -1; } } if (select != -1) { specPanel.removeAll(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { specPanel.add(fixGraphChoices(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())); } else if (directories.contains(((IconNode) node.getParent()).getName())) { specPanel.add(fixGraphChoices(((IconNode) node.getParent()).getName())); } else { specPanel.add(fixGraphChoices("")); } specPanel.revalidate(); specPanel.repaint(); for (int i = 0; i < series.size(); i++) { series.get(i).setText(graphSpecies.get(i + 1)); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); } for (int i = 0; i < boxes.size(); i++) { boxes.get(i).setSelected(false); } if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals( ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]); shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } else if (directories.contains(((IconNode) node.getParent()).getName())) { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals(((IconNode) node.getParent()).getName())) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]); shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } else { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals("")) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]); shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } boolean allChecked = true; boolean allCheckedVisible = true; boolean allCheckedFilled = true; boolean allCheckedConnected = true; for (int i = 0; i < boxes.size(); i++) { if (!boxes.get(i).isSelected()) { allChecked = false; String s = ""; s = ((IconNode) e.getPath().getLastPathComponent()).toString(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else if (directories.contains(((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else { if (s.equals("Average")) { s = "(" + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + s + ")"; } } String text = graphSpecies.get(i + 1); String end = ""; if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } boxes.get(i).setName(text); series.get(i).setText(text); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); colorsCombo.get(i).setSelectedIndex(0); colorsButtons.get(i).setBackground((Color) colors.get("Black")); colorsButtons.get(i).setForeground((Color) colors.get("Black")); shapesCombo.get(i).setSelectedIndex(0); } else { String s = ""; s = ((IconNode) e.getPath().getLastPathComponent()).toString(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else if (directories.contains(((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else { if (s.equals("Average")) { s = "(" + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + s + ")"; } } String text = series.get(i).getText(); String end = ""; if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } boxes.get(i).setName(text); } if (!visible.get(i).isSelected()) { allCheckedVisible = false; } if (!connected.get(i).isSelected()) { allCheckedConnected = false; } if (!filled.get(i).isSelected()) { allCheckedFilled = false; } } if (allChecked) { use.setSelected(true); } else { use.setSelected(false); } if (allCheckedVisible) { visibleLabel.setSelected(true); } else { visibleLabel.setSelected(false); } if (allCheckedFilled) { filledLabel.setSelected(true); } else { filledLabel.setSelected(false); } if (allCheckedConnected) { connectedLabel.setSelected(true); } else { connectedLabel.setSelected(false); } } } else { specPanel.removeAll(); specPanel.revalidate(); specPanel.repaint(); } } }); if (!stop) { tree.setSelectionRow(0); tree.setSelectionRow(1); } else { tree.setSelectionRow(0); tree.setSelectionRow(selectionRow); } } private JPanel fixGraphChoices(final String directory) { if (directory.equals("")) { if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation") || selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination")) { if (selected.equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { int nextOne = 1; while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } } else { String extension = printer_id.substring(0, printer_id.length() - 8); if (new File(outDir + separator + selected + "." + extension).exists() == false) extension = "dtsd"; readGraphSpecies(outDir + separator + selected + "." + extension); } } else { if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation") || selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination")) { if (selected.equals("Average") && new File(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Variance") && new File(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Standard Deviation") && new File(outDir + separator + directory + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Termination Time") && new File(outDir + separator + directory + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + directory + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Percent Termination") && new File(outDir + separator + directory + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Constraint Termination") && new File(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { int nextOne = 1; while (!new File(outDir + separator + directory + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + separator + directory + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } } else { readGraphSpecies(outDir + separator + directory + separator + selected + "." + printer_id.substring(0, printer_id.length() - 8)); } } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1)); JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3)); JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3)); use = new JCheckBox("Use"); JLabel specs; specs = new JLabel("Variables"); JLabel color = new JLabel("Color"); JLabel shape = new JLabel("Shape"); connectedLabel = new JCheckBox("Connect"); visibleLabel = new JCheckBox("Visible"); filledLabel = new JCheckBox("Fill"); connectedLabel.setSelected(true); visibleLabel.setSelected(true); filledLabel.setSelected(true); boxes = new ArrayList<JCheckBox>(); series = new ArrayList<JTextField>(); colorsCombo = new ArrayList<JComboBox>(); colorsButtons = new ArrayList<JButton>(); shapesCombo = new ArrayList<JComboBox>(); connected = new ArrayList<JCheckBox>(); visible = new ArrayList<JCheckBox>(); filled = new ArrayList<JCheckBox>(); use.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (use.isSelected()) { for (JCheckBox box : boxes) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : boxes) { if (box.isSelected()) { box.doClick(); } } } } }); connectedLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (connectedLabel.isSelected()) { for (JCheckBox box : connected) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : connected) { if (box.isSelected()) { box.doClick(); } } } } }); visibleLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (visibleLabel.isSelected()) { for (JCheckBox box : visible) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : visible) { if (box.isSelected()) { box.doClick(); } } } } }); filledLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (filledLabel.isSelected()) { for (JCheckBox box : filled) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : filled) { if (box.isSelected()) { box.doClick(); } } } } }); speciesPanel1.add(use); speciesPanel2.add(specs); speciesPanel2.add(color); speciesPanel2.add(shape); speciesPanel3.add(connectedLabel); speciesPanel3.add(visibleLabel); speciesPanel3.add(filledLabel); final HashMap<String, Shape> shapey = this.shapes; final HashMap<String, Paint> colory = this.colors; for (int i = 0; i < graphSpecies.size() - 1; i++) { JCheckBox temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { node.setIcon(TextIcons.getIcon("g")); node.setIconName("" + (char) 10003); IconNode n = ((IconNode) node.getParent()); while (n != null) { n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); n.setIconName("" + (char) 10003); if (n.getParent() == null) { n = null; } else { n = ((IconNode) n.getParent()); } } tree.revalidate(); tree.repaint(); String s = series.get(i).getText(); ((JCheckBox) e.getSource()).setSelected(false); int[] cols = new int[35]; int[] shaps = new int[10]; for (int k = 0; k < boxes.size(); k++) { if (boxes.get(k).isSelected()) { if (colorsCombo.get(k).getSelectedItem().equals("Red")) { cols[0]++; colorsButtons.get(k).setBackground((Color) colory.get("Red")); colorsButtons.get(k).setForeground((Color) colory.get("Red")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) { cols[1]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue")); colorsButtons.get(k).setForeground((Color) colory.get("Blue")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green")) { cols[2]++; colorsButtons.get(k).setBackground((Color) colory.get("Green")); colorsButtons.get(k).setForeground((Color) colory.get("Green")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) { cols[3]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) { cols[4]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) { cols[5]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan")); } else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) { cols[6]++; colorsButtons.get(k).setBackground((Color) colory.get("Tan")); colorsButtons.get(k).setForeground((Color) colory.get("Tan")); } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) { cols[7]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Gray (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) { cols[8]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) { cols[9]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) { cols[10]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) { cols[11]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) { cols[12]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) { cols[13]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Black")) { cols[14]++; colorsButtons.get(k).setBackground((Color) colory.get("Black")); colorsButtons.get(k).setForeground((Color) colory.get("Black")); } /* * else if * (colorsCombo.get(k).getSelectedItem(). * equals("Red ")) { cols[15]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Blue ")) { * cols[16]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Green ")) { cols[17]++; } else if * (colorsCombo.get(k).getSelectedItem().equals( * "Yellow ")) { cols[18]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Magenta ")) * { cols[19]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Cyan ")) { cols[20]++; } */ else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) { cols[21]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray")); colorsButtons.get(k).setForeground((Color) colory.get("Gray")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) { cols[22]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) { cols[23]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) { cols[24]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) { cols[25]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) { cols[26]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) { cols[27]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) { cols[28]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) { cols[29]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) { cols[30]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) { cols[31]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) { cols[32]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) { cols[33]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) { cols[34]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Gray (Light)")); } if (shapesCombo.get(k).getSelectedItem().equals("Square")) { shaps[0]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) { shaps[1]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) { shaps[2]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) { shaps[3]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Horizontal)")) { shaps[4]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Triangle (Upside Down)")) { shaps[5]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Circle (Half)")) { shaps[6]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) { shaps[7]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Vertical)")) { shaps[8]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Arrow (Backwards)")) { shaps[9]++; } } } for (GraphSpecies graph : graphed) { if (graph.getShapeAndPaint().getPaintName().equals("Red")) { cols[0]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) { cols[1]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green")) { cols[2]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) { cols[3]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) { cols[4]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) { cols[5]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) { cols[6]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Dark)")) { cols[7]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) { cols[8]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Dark)")) { cols[9]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green (Dark)")) { cols[10]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Dark)")) { cols[11]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Dark)")) { cols[12]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Dark)")) { cols[13]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Black")) { cols[14]++; } /* * else if * (graph.getShapeAndPaint().getPaintName().equals * ("Red ")) { cols[15]++; } else if * (graph.getShapeAndPaint * ().getPaintName().equals("Blue ")) { cols[16]++; * } else if * (graph.getShapeAndPaint().getPaintName() * .equals("Green ")) { cols[17]++; } else if * (graph. * getShapeAndPaint().getPaintName().equals("Yellow " * )) { cols[18]++; } else if * (graph.getShapeAndPaint * ().getPaintName().equals("Magenta ")) { * cols[19]++; } else if * (graph.getShapeAndPaint().getPaintName * ().equals("Cyan ")) { cols[20]++; } */ else if (graph.getShapeAndPaint().getPaintName().equals("Gray")) { cols[21]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Extra Dark)")) { cols[22]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Extra Dark)")) { cols[23]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green (Extra Dark)")) { cols[24]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Extra Dark)")) { cols[25]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Extra Dark)")) { cols[26]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Extra Dark)")) { cols[27]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Light)")) { cols[28]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Light)")) { cols[29]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green (Light)")) { cols[30]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Light)")) { cols[31]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Light)")) { cols[32]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Light)")) { cols[33]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Light)")) { cols[34]++; } if (graph.getShapeAndPaint().getShapeName().equals("Square")) { shaps[0]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) { shaps[1]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) { shaps[2]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) { shaps[3]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Horizontal)")) { shaps[4]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Triangle (Upside Down)")) { shaps[5]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Circle (Half)")) { shaps[6]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) { shaps[7]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Vertical)")) { shaps[8]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Arrow (Backwards)")) { shaps[9]++; } } ((JCheckBox) e.getSource()).setSelected(true); series.get(i).setText(s); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); int colorSet = 0; for (int j = 1; j < cols.length; j++) { if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) { colorSet = j; } } int shapeSet = 0; for (int j = 1; j < shaps.length; j++) { if (shaps[j] < shaps[shapeSet]) { shapeSet = j; } } DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); Paint paint; if (colorSet == 34) { paint = colors.get("Gray (Light)"); } else { for (int j = 0; j < colorSet; j++) { draw.getNextPaint(); } paint = draw.getNextPaint(); } Object[] set = colory.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (paint == colory.get(set[j])) { colorsCombo.get(i).setSelectedItem(set[j]); colorsButtons.get(i).setBackground((Color) paint); colorsButtons.get(i).setForeground((Color) paint); } } for (int j = 0; j < shapeSet; j++) { draw.getNextShape(); } Shape shape = draw.getNextShape(); set = shapey.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (shape == shapey.get(set[j])) { shapesCombo.get(i).setSelectedItem(set[j]); } } boolean allChecked = true; for (JCheckBox temp : boxes) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { use.setSelected(true); } String color = (String) colorsCombo.get(i).getSelectedItem(); if (color.equals("Custom")) { color += "_" + colorsButtons.get(i).getBackground().getRGB(); } graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i).getSelectedItem()), color, filled.get(i).isSelected(), visible .get(i).isSelected(), connected.get(i).isSelected(), selected, boxes.get(i).getName(), series.get(i).getText().trim(), XVariable.getSelectedIndex(), i, directory)); } else { boolean check = false; for (JCheckBox b : boxes) { if (b.isSelected()) { check = true; } } if (!check) { node.setIcon(MetalIconFactory.getTreeLeafIcon()); node.setIconName(""); boolean check2 = false; IconNode parent = ((IconNode) node.getParent()); while (parent != null) { for (int j = 0; j < parent.getChildCount(); j++) { if (((IconNode) parent.getChildAt(j)).getIconName().equals("" + (char) 10003)) { check2 = true; } } if (!check2) { parent.setIcon(MetalIconFactory.getTreeFolderIcon()); parent.setIconName(""); } check2 = false; if (parent.getParent() == null) { parent = null; } else { parent = ((IconNode) parent.getParent()); } } tree.revalidate(); tree.repaint(); } ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { remove.add(g); } } for (GraphSpecies g : remove) { graphed.remove(g); } use.setSelected(false); colorsCombo.get(i).setSelectedIndex(0); colorsButtons.get(i).setBackground((Color) colory.get("Black")); colorsButtons.get(i).setForeground((Color) colory.get("Black")); shapesCombo.get(i).setSelectedIndex(0); } } }); boxes.add(temp); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : visible) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { visibleLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setVisible(true); } } } else { visibleLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setVisible(false); } } } } }); visible.add(temp); visible.get(i).setSelected(true); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : filled) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { filledLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setFilled(true); } } } else { filledLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setFilled(false); } } } } }); filled.add(temp); filled.get(i).setSelected(true); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : connected) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { connectedLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setConnected(true); } } } else { connectedLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setConnected(false); } } } } }); connected.add(temp); connected.get(i).setSelected(true); JTextField seriesName = new JTextField(graphSpecies.get(i + 1), 20); seriesName.setName("" + i); seriesName.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyReleased(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyTyped(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } }); series.add(seriesName); ArrayList<String> allColors = new ArrayList<String>(); for (String c : this.colors.keySet()) { allColors.add(c); } allColors.add("Custom"); Object[] col = allColors.toArray(); Arrays.sort(col); Object[] shap = this.shapes.keySet().toArray(); Arrays.sort(shap); JComboBox colBox = new JComboBox(col); colBox.setActionCommand("" + i); colBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) { colorsButtons.get(i).setBackground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem())); colorsButtons.get(i).setForeground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem())); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem()); } } } else { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaint("Custom_" + colorsButtons.get(i).getBackground().getRGB()); } } } } }); JComboBox shapBox = new JComboBox(shap); shapBox.setActionCommand("" + i); shapBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem()); } } } }); colorsCombo.add(colBox); JButton colorButton = new JButton(); colorButton.setPreferredSize(new Dimension(30, 20)); colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray)); colorButton.setBackground((Color) colory.get("Black")); colorButton.setForeground((Color) colory.get("Black")); colorButton.setUI(new MetalButtonUI()); colorButton.setActionCommand("" + i); colorButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground()); if (newColor != null) { ((JButton) e.getSource()).setBackground(newColor); ((JButton) e.getSource()).setForeground(newColor); colorsCombo.get(i).setSelectedItem("Custom"); } } }); colorsButtons.add(colorButton); JPanel colorPanel = new JPanel(new BorderLayout()); colorPanel.add(colorsCombo.get(i), "Center"); colorPanel.add(colorsButtons.get(i), "East"); shapesCombo.add(shapBox); speciesPanel1.add(boxes.get(i)); speciesPanel2.add(series.get(i)); speciesPanel2.add(colorPanel); speciesPanel2.add(shapesCombo.get(i)); speciesPanel3.add(connected.get(i)); speciesPanel3.add(visible.get(i)); speciesPanel3.add(filled.get(i)); } JPanel speciesPanel = new JPanel(new BorderLayout()); speciesPanel.add(speciesPanel1, "West"); speciesPanel.add(speciesPanel2, "Center"); speciesPanel.add(speciesPanel3, "East"); return speciesPanel; } private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) { curData = dataset; // chart = ChartFactory.createXYLineChart(title, x, y, dataset, // PlotOrientation.VERTICAL, // true, true, false); chart.getXYPlot().setDataset(dataset); chart.setTitle(title); chart.getXYPlot().getDomainAxis().setLabel(x); chart.getXYPlot().getRangeAxis().setLabel(y); // chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); // chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); // chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY); // chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); // chart.addProgressListener(this); ChartPanel graph = new ChartPanel(chart); if (graphed.isEmpty()) { graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); } graph.addMouseListener(this); JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); saveAs.addActionListener(this); export = new JButton("Export"); refresh = new JButton("Refresh"); // exportJPeg = new JButton("Export As JPEG"); // exportPng = new JButton("Export As PNG"); // exportPdf = new JButton("Export As PDF"); // exportEps = new JButton("Export As EPS"); // exportSvg = new JButton("Export As SVG"); // exportCsv = new JButton("Export As CSV"); run.addActionListener(this); save.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); // exportJPeg.addActionListener(this); // exportPng.addActionListener(this); // exportPdf.addActionListener(this); // exportEps.addActionListener(this); // exportSvg.addActionListener(this); // exportCsv.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // ButtonHolder.add(exportJPeg); // ButtonHolder.add(exportPng); // ButtonHolder.add(exportPdf); // ButtonHolder.add(exportEps); // ButtonHolder.add(exportSvg); // ButtonHolder.add(exportCsv); // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); this.revalidate(); } /** * This method saves the graph as a jpeg or as a png file. */ public void export() { try { int output = 2; /* Default is currently pdf */ int width = -1; int height = -1; JPanel sizePanel = new JPanel(new GridLayout(2, 2)); JLabel heightLabel = new JLabel("Desired pixel height:"); JLabel widthLabel = new JLabel("Desired pixel width:"); JTextField heightField = new JTextField("400"); JTextField widthField = new JTextField("650"); sizePanel.add(widthLabel); sizePanel.add(widthField); sizePanel.add(heightLabel); sizePanel.add(heightField); Object[] options2 = { "Export", "Cancel" }; int value; String export = "Export"; if (timeSeries) { export += " TSD"; } else { export += " Probability"; } File file; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.export_dir", "").equals("")) { file = null; } else { file = new File(biosimrc.get("biosim.general.export_dir", "")); } String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output); if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".jpg"))) { output = 0; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".png"))) { output = 1; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".pdf"))) { output = 2; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".eps"))) { output = 3; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".svg"))) { output = 4; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".csv"))) { output = 5; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".dat"))) { output = 6; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".tsd"))) { output = 7; } if (!filename.equals("")) { file = new File(filename); biosimrc.put("biosim.general.export_dir", filename); boolean exportIt = true; if (file.exists()) { Object[] options = { "Overwrite", "Cancel" }; value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); exportIt = false; if (value == JOptionPane.YES_OPTION) { exportIt = true; } } if (exportIt) { if ((output != 5) && (output != 6) && (output != 7)) { value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); if (value == JOptionPane.YES_OPTION) { while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1)) try { width = Integer.parseInt(widthField.getText().trim()); height = Integer.parseInt(heightField.getText().trim()); if (width < 1 || height < 1) { JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } catch (Exception e2) { JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } if (value == JOptionPane.NO_OPTION) { return; } } if (output == 0) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (output == 1) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else if (output == 2) { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); FileOutputStream out = new FileOutputStream(file); PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); chart.draw(g2, new java.awt.Rectangle(width, height)); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); out.close(); } else if (output == 3) { Graphics2D g = new EpsGraphics2D(); chart.draw(g, new java.awt.Rectangle(width, height)); Writer out = new FileWriter(file); out.write(g.toString()); out.close(); } else if (output == 4) { DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); chart.draw(svgGenerator, new java.awt.Rectangle(width, height)); boolean useCSS = true; FileOutputStream outStream = new FileOutputStream(file); Writer out = new OutputStreamWriter(outStream, "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); outStream.close(); } else if ((output == 5) || (output == 6) || (output == 7)) { exportDataFile(file, output); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } public void export(int output) { // jpg = 0 // png = 1 // pdf = 2 // eps = 3 // svg = 4 // csv = 5 (data) // dat = 6 (data) // tsd = 7 (data) try { int width = -1; int height = -1; JPanel sizePanel = new JPanel(new GridLayout(2, 2)); JLabel heightLabel = new JLabel("Desired pixel height:"); JLabel widthLabel = new JLabel("Desired pixel width:"); JTextField heightField = new JTextField("400"); JTextField widthField = new JTextField("650"); sizePanel.add(widthLabel); sizePanel.add(widthField); sizePanel.add(heightLabel); sizePanel.add(heightField); Object[] options2 = { "Export", "Cancel" }; int value; String export = "Export"; if (timeSeries) { export += " TSD"; } else { export += " Probability"; } File file; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.export_dir", "").equals("")) { file = null; } else { file = new File(biosimrc.get("biosim.general.export_dir", "")); } String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output); if (!filename.equals("")) { file = new File(filename); biosimrc.put("biosim.general.export_dir", filename); boolean exportIt = true; if (file.exists()) { Object[] options = { "Overwrite", "Cancel" }; value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); exportIt = false; if (value == JOptionPane.YES_OPTION) { exportIt = true; } } if (exportIt) { if ((output != 5) && (output != 6) && (output != 7)) { value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); if (value == JOptionPane.YES_OPTION) { while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1)) try { width = Integer.parseInt(widthField.getText().trim()); height = Integer.parseInt(heightField.getText().trim()); if (width < 1 || height < 1) { JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } catch (Exception e2) { JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } if (value == JOptionPane.NO_OPTION) { return; } } if (output == 0) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (output == 1) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else if (output == 2) { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); FileOutputStream out = new FileOutputStream(file); PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); chart.draw(g2, new java.awt.Rectangle(width, height)); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); out.close(); } else if (output == 3) { Graphics2D g = new EpsGraphics2D(); chart.draw(g, new java.awt.Rectangle(width, height)); Writer out = new FileWriter(file); out.write(g.toString()); out.close(); } else if (output == 4) { DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); chart.draw(svgGenerator, new java.awt.Rectangle(width, height)); boolean useCSS = true; FileOutputStream outStream = new FileOutputStream(file); Writer out = new OutputStreamWriter(outStream, "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); outStream.close(); } else if ((output == 5) || (output == 6) || (output == 7)) { exportDataFile(file, output); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } public void exportDataFile(File file, int output) { try { int count = curData.getSeries(0).getItemCount(); for (int i = 1; i < curData.getSeriesCount(); i++) { if (curData.getSeries(i).getItemCount() != count) { JOptionPane.showMessageDialog(Gui.frame, "Data series do not have the same number of points!", "Unable to Export Data File", JOptionPane.ERROR_MESSAGE); return; } } for (int j = 0; j < count; j++) { Number Xval = curData.getSeries(0).getDataItem(j).getX(); for (int i = 1; i < curData.getSeriesCount(); i++) { if (!curData.getSeries(i).getDataItem(j).getX().equals(Xval)) { JOptionPane.showMessageDialog(Gui.frame, "Data series time points are not the same!", "Unable to Export Data File", JOptionPane.ERROR_MESSAGE); return; } } } FileOutputStream csvFile = new FileOutputStream(file); PrintWriter csvWriter = new PrintWriter(csvFile); if (output == 7) { csvWriter.print("(("); } else if (output == 6) { csvWriter.print(" } csvWriter.print("\"Time\""); count = curData.getSeries(0).getItemCount(); int pos = 0; for (int i = 0; i < curData.getSeriesCount(); i++) { if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } csvWriter.print("\"" + curData.getSeriesKey(i) + "\""); if (curData.getSeries(i).getItemCount() > count) { count = curData.getSeries(i).getItemCount(); pos = i; } } if (output == 7) { csvWriter.print(")"); } else { csvWriter.println(""); } for (int j = 0; j < count; j++) { if (output == 7) { csvWriter.print(","); } for (int i = 0; i < curData.getSeriesCount(); i++) { if (i == 0) { if (output == 7) { csvWriter.print("("); } csvWriter.print(curData.getSeries(pos).getDataItem(j).getX()); } XYSeries data = curData.getSeries(i); if (j < data.getItemCount()) { XYDataItem item = data.getDataItem(j); if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } csvWriter.print(item.getY()); } else { if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } } } if (output == 7) { csvWriter.print(")"); } else { csvWriter.println(""); } } if (output == 7) { csvWriter.println(")"); } csvWriter.close(); csvFile.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } public ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(ArrayList<String> files, int choice, String directory, boolean warning, boolean output) { if (files.size() > 0) { ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>(); lock.lock(); try { warn = warning; // TSDParser p = new TSDParser(startFile, biomodelsim, false); ArrayList<ArrayList<Double>> data; if (directory == null) { data = readData(outDir + separator + files.get(0), "", directory, warn); } else { data = readData(outDir + separator + directory + separator + files.get(0), "", directory, warn); } averageOrder = graphSpecies; boolean first = true; for (int i = 0; i < graphSpecies.size(); i++) { average.add(new ArrayList<Double>()); variance.add(new ArrayList<Double>()); } HashMap<Double, Integer> dataCounts = new HashMap<Double, Integer>(); // int count = 0; for (String run : files) { if (directory == null) { if (new File(outDir + separator + run).exists()) { ArrayList<ArrayList<Double>> newData = readData(outDir + separator + run, "", directory, warn); data = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < averageOrder.size(); i++) { for (int k = 0; k < graphSpecies.size(); k++) { if (averageOrder.get(i).equals(graphSpecies.get(k))) { data.add(newData.get(k)); break; } } } } } else { if (new File(outDir + separator + directory + separator + run).exists()) { ArrayList<ArrayList<Double>> newData = readData(outDir + separator + directory + separator + run, "", directory, warn); data = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < averageOrder.size(); i++) { for (int k = 0; k < graphSpecies.size(); k++) { if (averageOrder.get(i).equals(graphSpecies.get(k))) { data.add(newData.get(k)); break; } } } } } // ArrayList<ArrayList<Double>> data = p.getData(); for (int k = 0; k < data.get(0).size(); k++) { if (first) { double put; if (k == data.get(0).size() - 1 && k >= 2) { if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) { put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2)); dataCounts.put(put, 1); } else { put = (data.get(0)).get(k); dataCounts.put(put, 1); } } else { put = (data.get(0)).get(k); dataCounts.put(put, 1); } for (int i = 0; i < data.size(); i++) { if (i == 0) { variance.get(i).add((data.get(i)).get(k)); average.get(i).add(put); } else { variance.get(i).add(0.0); average.get(i).add((data.get(i)).get(k)); } } } else { int index = -1; double put; if (k == data.get(0).size() - 1 && k >= 2) { if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) { put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2)); } else { put = (data.get(0)).get(k); } } else if (k == data.get(0).size() - 1 && k == 1) { if (average.get(0).size() > 1) { put = (average.get(0)).get(k); } else { put = (data.get(0)).get(k); } } else { put = (data.get(0)).get(k); } if (average.get(0).contains(put)) { index = average.get(0).indexOf(put); int count = dataCounts.get(put); dataCounts.put(put, count + 1); for (int i = 1; i < data.size(); i++) { double old = (average.get(i)).get(index); (average.get(i)).set(index, old + (((data.get(i)).get(k) - old) / (count + 1))); double newMean = (average.get(i)).get(index); double vary = (((count - 1) * (variance.get(i)).get(index)) + ((data.get(i)).get(k) - newMean) * ((data.get(i)).get(k) - old)) / count; (variance.get(i)).set(index, vary); } } else { dataCounts.put(put, 1); for (int a = 0; a < average.get(0).size(); a++) { if (average.get(0).get(a) > put) { index = a; break; } } if (index == -1) { index = average.get(0).size() - 1; } average.get(0).add(put); variance.get(0).add(put); for (int a = 1; a < average.size(); a++) { average.get(a).add(data.get(a).get(k)); variance.get(a).add(0.0); } if (index != average.get(0).size() - 1) { for (int a = average.get(0).size() - 2; a >= 0; a if (average.get(0).get(a) > average.get(0).get(a + 1)) { for (int b = 0; b < average.size(); b++) { double temp = average.get(b).get(a); average.get(b).set(a, average.get(b).get(a + 1)); average.get(b).set(a + 1, temp); temp = variance.get(b).get(a); variance.get(b).set(a, variance.get(b).get(a + 1)); variance.get(b).set(a + 1, temp); } } else { break; } } } } } } first = false; } deviation = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < variance.size(); i++) { deviation.add(new ArrayList<Double>()); for (int j = 0; j < variance.get(i).size(); j++) { deviation.get(i).add(variance.get(i).get(j)); } } for (int i = 1; i < deviation.size(); i++) { for (int j = 0; j < deviation.get(i).size(); j++) { deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j))); } } averageOrder = null; } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Unable to output average, variance, and standard deviation!", "Error", JOptionPane.ERROR_MESSAGE); } lock.unlock(); if (output) { DataParser m = new DataParser(graphSpecies, average); DataParser d = new DataParser(graphSpecies, deviation); DataParser v = new DataParser(graphSpecies, variance); if (directory == null) { m.outputTSD(outDir + separator + "mean.tsd"); v.outputTSD(outDir + separator + "variance.tsd"); d.outputTSD(outDir + separator + "standard_deviation.tsd"); } else { m.outputTSD(outDir + separator + directory + separator + "mean.tsd"); v.outputTSD(outDir + separator + directory + separator + "variance.tsd"); d.outputTSD(outDir + separator + directory + separator + "standard_deviation.tsd"); } } if (choice == 0) { return average; } else if (choice == 1) { return variance; } else { return deviation; } } return null; } public void run() { reb2sac.getRunButton().doClick(); } public void save() { if (timeSeries) { Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB()); graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB()); graph.setProperty("plot.domain.grid.line.paint", "" + ((Color) chart.getXYPlot().getDomainGridlinePaint()).getRGB()); graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getXYPlot().getRangeGridlinePaint()).getRGB()); graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel()); graph.setProperty("x.min", XMin.getText()); graph.setProperty("x.max", XMax.getText()); graph.setProperty("x.scale", XScale.getText()); graph.setProperty("y.min", YMin.getText()); graph.setProperty("y.max", YMax.getText()); graph.setProperty("y.scale", YScale.getText()); graph.setProperty("auto.resize", "" + resize.isSelected()); graph.setProperty("LogX", "" + LogX.isSelected()); graph.setProperty("LogY", "" + LogY.isSelected()); graph.setProperty("visibleLegend", "" + visibleLegend.isSelected()); for (int i = 0; i < graphed.size(); i++) { graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected()); graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled()); graph.setProperty("species.xnumber." + i, "" + graphed.get(i).getXNumber()); graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber()); graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber()); graph.setProperty("species.name." + i, graphed.get(i).getSpecies()); graph.setProperty("species.id." + i, graphed.get(i).getID()); graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible()); graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName()); graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName()); graph.setProperty("species.directory." + i, graphed.get(i).getDirectory()); } try { FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName)); graph.store(store, "Graph Data"); store.close(); log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n"); change = false; } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } else { Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB()); graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB()); graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getCategoryPlot().getRangeGridlinePaint()).getRGB()); graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel()); graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof GradientBarPainter)); graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible()); graph.setProperty("visibleLegend", "" + visibleLegend.isSelected()); for (int i = 0; i < probGraphed.size(); i++) { graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber()); graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies()); graph.setProperty("species.id." + i, probGraphed.get(i).getID()); graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName()); graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory()); } try { FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName)); graph.store(store, "Probability Data"); store.close(); log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n"); change = false; } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } public void saveAs() { if (timeSeries) { String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Graph Name:", "Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".grf")) { graphName += ".grf"; } } else { graphName += ".grf"; } File f; if (topLevel) { f = new File(outDir + separator + graphName); } else { f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File del; if (topLevel) { del = new File(outDir + separator + graphName); } else { del = new File( outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (del.isDirectory()) { biomodelsim.deleteDir(del); } else { del.delete(); } for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) { if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) { biomodelsim.getTab().remove(i); } } } else { return; } } Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel()); graph.setProperty("x.min", XMin.getText()); graph.setProperty("x.max", XMax.getText()); graph.setProperty("x.scale", XScale.getText()); graph.setProperty("y.min", YMin.getText()); graph.setProperty("y.max", YMax.getText()); graph.setProperty("y.scale", YScale.getText()); graph.setProperty("auto.resize", "" + resize.isSelected()); graph.setProperty("LogX", "" + LogX.isSelected()); graph.setProperty("LogY", "" + LogY.isSelected()); graph.setProperty("visibleLegend", "" + visibleLegend.isSelected()); for (int i = 0; i < graphed.size(); i++) { graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected()); graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled()); graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber()); graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber()); graph.setProperty("species.name." + i, graphed.get(i).getSpecies()); graph.setProperty("species.id." + i, graphed.get(i).getID()); graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible()); graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName()); graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName()); if (topLevel) { graph.setProperty("species.directory." + i, graphed.get(i).getDirectory()); } else { if (graphed.get(i).getDirectory().equals("")) { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]); } else { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/" + graphed.get(i).getDirectory()); } } } try { FileOutputStream store = new FileOutputStream(f); graph.store(store, "Graph Data"); store.close(); log.addText("Creating graph file:\n" + f.getAbsolutePath() + "\n"); change = false; biomodelsim.addToTree(f.getName()); } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } else { String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Probability Graph Name:", "Probability Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".prb")) { graphName += ".prb"; } } else { graphName += ".prb"; } File f; if (topLevel) { f = new File(outDir + separator + graphName); } else { f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File del; if (topLevel) { del = new File(outDir + separator + graphName); } else { del = new File( outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (del.isDirectory()) { biomodelsim.deleteDir(del); } else { del.delete(); } for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) { if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) { biomodelsim.getTab().remove(i); } } } else { return; } } Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel()); graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof GradientBarPainter)); graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible()); graph.setProperty("visibleLegend", "" + visibleLegend.isSelected()); for (int i = 0; i < probGraphed.size(); i++) { graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber()); graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies()); graph.setProperty("species.id." + i, probGraphed.get(i).getID()); graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName()); if (topLevel) { graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory()); } else { if (probGraphed.get(i).getDirectory().equals("")) { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]); } else { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/" + probGraphed.get(i).getDirectory()); } } } try { FileOutputStream store = new FileOutputStream(f); graph.store(store, "Probability Graph Data"); store.close(); log.addText("Creating probability graph file:\n" + f.getAbsolutePath() + "\n"); change = false; biomodelsim.addToTree(f.getName()); } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Probability Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } } private void open(String filename) { if (timeSeries) { Properties graph = new Properties(); try { FileInputStream load = new FileInputStream(new File(filename)); graph.load(load); load.close(); XMin.setText(graph.getProperty("x.min")); XMax.setText(graph.getProperty("x.max")); XScale.setText(graph.getProperty("x.scale")); YMin.setText(graph.getProperty("y.min")); YMax.setText(graph.getProperty("y.max")); YScale.setText(graph.getProperty("y.scale")); chart.setTitle(graph.getProperty("title")); if (graph.containsKey("chart.background.paint")) { chart.setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("chart.background.paint")))); } if (graph.containsKey("plot.background.paint")) { chart.getPlot().setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("plot.background.paint")))); } if (graph.containsKey("plot.domain.grid.line.paint")) { chart.getXYPlot().setDomainGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.domain.grid.line.paint")))); } if (graph.containsKey("plot.range.grid.line.paint")) { chart.getXYPlot().setRangeGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.range.grid.line.paint")))); } chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis")); chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis")); if (graph.getProperty("auto.resize").equals("true")) { resize.setSelected(true); } else { resize.setSelected(false); } if (graph.containsKey("LogX") && graph.getProperty("LogX").equals("true")) { LogX.setSelected(true); } else { LogX.setSelected(false); } if (graph.containsKey("LogY") && graph.getProperty("LogY").equals("true")) { LogY.setSelected(true); } else { LogY.setSelected(false); } if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) { visibleLegend.setSelected(false); } else { visibleLegend.setSelected(true); } int next = 0; while (graph.containsKey("species.name." + next)) { boolean connected, filled, visible; if (graph.getProperty("species.connected." + next).equals("true")) { connected = true; } else { connected = false; } if (graph.getProperty("species.filled." + next).equals("true")) { filled = true; } else { filled = false; } if (graph.getProperty("species.visible." + next).equals("true")) { visible = true; } else { visible = false; } int xnumber = 0; if (graph.containsKey("species.xnumber." + next)) { xnumber = Integer.parseInt(graph.getProperty("species.xnumber." + next)); } graphed.add(new GraphSpecies(shapes.get(graph.getProperty("species.shape." + next)), graph.getProperty("species.paint." + next) .trim(), filled, visible, connected, graph.getProperty("species.run.number." + next), graph.getProperty("species.id." + next), graph.getProperty("species.name." + next), xnumber, Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next))); next++; } updateXNumber = false; XVariable.addItem("time"); refresh(); } catch (IOException except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } else { Properties graph = new Properties(); try { FileInputStream load = new FileInputStream(new File(filename)); graph.load(load); load.close(); chart.setTitle(graph.getProperty("title")); if (graph.containsKey("chart.background.paint")) { chart.setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("chart.background.paint")))); } if (graph.containsKey("plot.background.paint")) { chart.getPlot().setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("plot.background.paint")))); } if (graph.containsKey("plot.range.grid.line.paint")) { chart.getCategoryPlot().setRangeGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.range.grid.line.paint")))); } chart.getCategoryPlot().getDomainAxis().setLabel(graph.getProperty("x.axis")); chart.getCategoryPlot().getRangeAxis().setLabel(graph.getProperty("y.axis")); if (graph.containsKey("gradient") && graph.getProperty("gradient").equals("true")) { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new GradientBarPainter()); } else { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new StandardBarPainter()); } if (graph.containsKey("shadow") && graph.getProperty("shadow").equals("false")) { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(false); } else { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(true); } if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) { visibleLegend.setSelected(false); } else { visibleLegend.setSelected(true); } int next = 0; while (graph.containsKey("species.name." + next)) { String color = graph.getProperty("species.paint." + next).trim(); Paint paint; if (color.startsWith("Custom_")) { paint = new Color(Integer.parseInt(color.replace("Custom_", ""))); } else { paint = colors.get(color); } probGraphed.add(new GraphProbs(paint, color, graph.getProperty("species.id." + next), graph.getProperty("species.name." + next), Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next))); next++; } refreshProb(); } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } public boolean isTSDGraph() { return timeSeries; } public void refresh() { lock2.lock(); if (timeSeries) { if (learnSpecs != null) { updateSpecies(); } double minY = 0; double maxY = 0; double scaleY = 0; double minX = 0; double maxX = 0; double scaleX = 0; try { minY = Double.parseDouble(YMin.getText().trim()); maxY = Double.parseDouble(YMax.getText().trim()); scaleY = Double.parseDouble(YScale.getText().trim()); minX = Double.parseDouble(XMin.getText().trim()); maxX = Double.parseDouble(XMax.getText().trim()); scaleX = Double.parseDouble(XScale.getText().trim()); /* * NumberFormat num = NumberFormat.getInstance(); * num.setMaximumFractionDigits(4); num.setGroupingUsed(false); * minY = Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); */ } catch (Exception e1) { } ArrayList<XYSeries> graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); } ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>(); HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) { if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); readGraphSpecies(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { data = readData(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } else { boolean ableToGraph = false; try { for (String s : new File(outDir).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e) { ableToGraph = false; } if (!ableToGraph) { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } } if (ableToGraph) { int nextOne = 1; // while (!new File(outDir + separator + "run-" + // nextOne + "." // + printer_id.substring(0, printer_id.length() - // 8)).exists()) { // nextOne++; ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber() .toLowerCase(), null, false); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else { while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } data = readData(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } } else { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) { if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); readGraphSpecies(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { data = readData( outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } else { boolean ableToGraph = false; try { for (String s : new File(outDir + separator + g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e) { ableToGraph = false; } if (!ableToGraph) { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } } if (ableToGraph) { int nextOne = 1; // while (!new File(outDir + separator + // g.getDirectory() + separator // + "run-" + nextOne + "." // + printer_id.substring(0, printer_id.length() - // 8)).exists()) { // nextOne++; ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else { while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } data = readData( outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), g.getDirectory(), false); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } } } for (GraphSpecies g : unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) { dataset.addSeries(graphData.get(i)); } fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(), chart.getXYPlot().getRangeAxis().getLabel(), dataset); chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX); axis.setTickUnit(new NumberTickUnit(scaleX)); } } else { BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { if (graphProbs.contains(g.getID())) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } else { unableToGraph.add(g); thisOne } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { String compare = g.getID().replace(" (", "~"); if (graphProbs.contains(compare.split("~")[0].trim())) { for (int i = 0; i < graphProbs.size(); i++) { if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } else { unableToGraph.add(g); thisOne } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot().getRangeAxis() .getLabel(), histDataset, rend); } lock2.unlock(); } private class ShapeAndPaint { private Shape shape; private Paint paint; private ShapeAndPaint(Shape s, String p) { shape = s; if (p.startsWith("Custom_")) { paint = new Color(Integer.parseInt(p.replace("Custom_", ""))); } else { paint = colors.get(p); } } private Shape getShape() { return shape; } private Paint getPaint() { return paint; } private String getShapeName() { Object[] set = shapes.keySet().toArray(); for (int i = 0; i < set.length; i++) { if (shape == shapes.get(set[i])) { return (String) set[i]; } } return "Unknown Shape"; } private String getPaintName() { Object[] set = colors.keySet().toArray(); for (int i = 0; i < set.length; i++) { if (paint == colors.get(set[i])) { return (String) set[i]; } } return "Custom_" + ((Color) paint).getRGB(); } public void setPaint(String paint) { if (paint.startsWith("Custom_")) { this.paint = new Color(Integer.parseInt(paint.replace("Custom_", ""))); } else { this.paint = colors.get(paint); } } public void setShape(String shape) { this.shape = shapes.get(shape); } } private class GraphSpecies { private ShapeAndPaint sP; private boolean filled, visible, connected; private String runNumber, species, directory, id; private int xnumber, number; private GraphSpecies(Shape s, String p, boolean filled, boolean visible, boolean connected, String runNumber, String id, String species, int xnumber, int number, String directory) { sP = new ShapeAndPaint(s, p); this.filled = filled; this.visible = visible; this.connected = connected; this.runNumber = runNumber; this.species = species; this.xnumber = xnumber; this.number = number; this.directory = directory; this.id = id; } private void setDirectory(String directory) { this.directory = directory; } private void setXNumber(int xnumber) { this.xnumber = xnumber; } private void setNumber(int number) { this.number = number; } private void setSpecies(String species) { this.species = species; } private void setPaint(String paint) { sP.setPaint(paint); } private void setShape(String shape) { sP.setShape(shape); } private void setVisible(boolean b) { visible = b; } private void setFilled(boolean b) { filled = b; } private void setConnected(boolean b) { connected = b; } private int getXNumber() { return xnumber; } private int getNumber() { return number; } private String getSpecies() { return species; } private ShapeAndPaint getShapeAndPaint() { return sP; } private boolean getFilled() { return filled; } private boolean getVisible() { return visible; } private boolean getConnected() { return connected; } private String getRunNumber() { return runNumber; } private String getDirectory() { return directory; } private String getID() { return id; } } public void setDirectory(String newDirectory) { outDir = newDirectory; } public void setGraphName(String graphName) { this.graphName = graphName; } public boolean hasChanged() { return change; } private void probGraph(String label) { chart = ChartFactory.createBarChart(label, "", "Percent", new DefaultCategoryDataset(), PlotOrientation.VERTICAL, true, true, false); ((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new StandardBarPainter()); chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); chart.getCategoryPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); legend = chart.getLegend(); visibleLegend = new JCheckBox("Visible Legend"); visibleLegend.setSelected(true); ChartPanel graph = new ChartPanel(chart); graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); graph.addMouseListener(this); change = false; // creates the buttons for the graph frame JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); export = new JButton("Export"); refresh = new JButton("Refresh"); run.addActionListener(this); save.addActionListener(this); saveAs.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // puts all the components of the graph gui into a display panel // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); } private void editProbGraph() { final ArrayList<GraphProbs> old = new ArrayList<GraphProbs>(); for (GraphProbs g : probGraphed) { old.add(g); } final JPanel titlePanel = new JPanel(new BorderLayout()); JLabel titleLabel = new JLabel("Title:"); JLabel xLabel = new JLabel("X-Axis Label:"); JLabel yLabel = new JLabel("Y-Axis Label:"); final JCheckBox gradient = new JCheckBox("Paint In Gradient Style"); gradient.setSelected(!(((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof StandardBarPainter)); final JCheckBox shadow = new JCheckBox("Paint Bar Shadows"); shadow.setSelected(((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible()); visibleLegend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { if (chart.getLegend() == null) { chart.addLegend(legend); } } else { if (chart.getLegend() != null) { legend = chart.getLegend(); } chart.removeLegend(); } } }); final JTextField title = new JTextField(chart.getTitle().getText(), 5); final JTextField x = new JTextField(chart.getCategoryPlot().getDomainAxis().getLabel(), 5); final JTextField y = new JTextField(chart.getCategoryPlot().getRangeAxis().getLabel(), 5); String simDirString = outDir.split(separator)[outDir.split(separator).length - 1]; simDir = new IconNode(simDirString, simDirString); simDir.setIconName(""); String[] files = new File(outDir).list(); // for (int i = 1; i < files.length; i++) { // String index = files[i]; // int j = i; // while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) { // files[j] = files[j - 1]; // j = j - 1; // files[j] = index; boolean add = false; final ArrayList<String> directories = new ArrayList<String>(); for (String file : files) { if (file.length() > 3 && file.substring(file.length() - 4).equals(".txt")) { if (file.contains("sim-rep")) { add = true; } } else if (new File(outDir + separator + file).isDirectory()) { boolean addIt = false; for (String getFile : new File(outDir + separator + file).list()) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) { addIt = true; } else if (new File(outDir + separator + file + separator + getFile).isDirectory()) { for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) { if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals(".txt") && getFile2.contains("sim-rep")) { addIt = true; } } } } if (addIt) { directories.add(file); IconNode d = new IconNode(file, file); d.setIconName(""); String[] files2 = new File(outDir + separator + file).list(); // for (int i = 1; i < files2.length; i++) { // String index = files2[i]; // int j = i; // while ((j > 0) && files2[j - // 1].compareToIgnoreCase(index) > 0) { // files2[j] = files2[j - 1]; // j = j - 1; // files2[j] = index; boolean add2 = false; for (String f : files2) { if (f.equals("sim-rep.txt")) { add2 = true; } else if (new File(outDir + separator + file + separator + f).isDirectory()) { boolean addIt2 = false; for (String getFile : new File(outDir + separator + file + separator + f).list()) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) { addIt2 = true; } } if (addIt2) { directories.add(file + separator + f); IconNode d2 = new IconNode(f, f); d2.setIconName(""); for (String f2 : new File(outDir + separator + file + separator + f).list()) { if (f2.equals("sim-rep.txt")) { IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4)); d2.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } boolean added = false; for (int j = 0; j < d.getChildCount(); j++) { if ((d.getChildAt(j).toString().compareToIgnoreCase(d2.toString()) > 0) || new File(outDir + separator + d.toString() + separator + (d.getChildAt(j).toString() + ".txt")) .isFile()) { d.insert(d2, j); added = true; break; } } if (!added) { d.add(d2); } } } } if (add2) { IconNode n = new IconNode("sim-rep", "sim-rep"); d.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } boolean added = false; for (int j = 0; j < simDir.getChildCount(); j++) { if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0) || new File(outDir + separator + (simDir.getChildAt(j).toString() + ".txt")).isFile()) { simDir.insert(d, j); added = true; break; } } if (!added) { simDir.add(d); } } } } if (add) { IconNode n = new IconNode("sim-rep", "sim-rep"); simDir.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (simDir.getChildCount() == 0) { JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data", JOptionPane.PLAIN_MESSAGE); } else { tree = new JTree(simDir); tree.putClientProperty("JTree.icons", makeIcons()); tree.setCellRenderer(new IconNodeRenderer()); DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer(); renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon()); renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon()); renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon()); final JPanel all = new JPanel(new BorderLayout()); final JScrollPane scroll = new JScrollPane(); tree.addTreeExpansionListener(new TreeExpansionListener() { public void treeCollapsed(TreeExpansionEvent e) { JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); } public void treeExpanded(TreeExpansionEvent e) { JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); } }); // for (int i = 0; i < tree.getRowCount(); i++) { // tree.expandRow(i); JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); final JPanel specPanel = new JPanel(); boolean stop = false; int selectionRow = 1; for (int i = 1; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (selected.equals(lastSelected)) { stop = true; selectionRow = i; break; } } tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); if (!directories.contains(node.getName())) { selected = node.getName(); int select; if (selected.equals("sim-rep")) { select = 0; } else { select = -1; } if (select != -1) { specPanel.removeAll(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { specPanel.add(fixProbChoices(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())); } else if (directories.contains(((IconNode) node.getParent()).getName())) { specPanel.add(fixProbChoices(((IconNode) node.getParent()).getName())); } else { specPanel.add(fixProbChoices("")); } specPanel.revalidate(); specPanel.repaint(); for (int i = 0; i < series.size(); i++) { series.get(i).setText(graphProbs.get(i)); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); } for (int i = 0; i < boxes.size(); i++) { boxes.get(i).setSelected(false); } if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { for (GraphProbs g : probGraphed) { if (g.getDirectory() .equals(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]); } } } else if (directories.contains(((IconNode) node.getParent()).getName())) { for (GraphProbs g : probGraphed) { if (g.getDirectory().equals(((IconNode) node.getParent()).getName())) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]); } } } else { for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]); } } } boolean allChecked = true; for (int i = 0; i < boxes.size(); i++) { if (!boxes.get(i).isSelected()) { allChecked = false; String s = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ")"; } else if (directories.contains(((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent()).getName() + ")"; } String text = series.get(i).getText(); String end = ""; if (!s.equals("")) { if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } } boxes.get(i).setName(text); series.get(i).setText(text); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); colorsCombo.get(i).setSelectedIndex(0); colorsButtons.get(i).setBackground((Color) colors.get("Black")); colorsButtons.get(i).setForeground((Color) colors.get("Black")); } else { String s = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ")"; } else if (directories.contains(((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent()).getName() + ")"; } String text = graphProbs.get(i); String end = ""; if (!s.equals("")) { if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } } boxes.get(i).setName(text); } } if (allChecked) { use.setSelected(true); } else { use.setSelected(false); } } } else { specPanel.removeAll(); specPanel.revalidate(); specPanel.repaint(); } } }); if (!stop) { tree.setSelectionRow(0); tree.setSelectionRow(1); } else { tree.setSelectionRow(0); tree.setSelectionRow(selectionRow); } scroll.setPreferredSize(new Dimension(1050, 500)); JPanel editPanel = new JPanel(new BorderLayout()); editPanel.add(specPanel, "Center"); scroll.setViewportView(editPanel); final JButton deselect = new JButton("Deselect All"); deselect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int size = probGraphed.size(); for (int i = 0; i < size; i++) { probGraphed.remove(); } IconNode n = simDir; while (n != null) { if (n.isLeaf()) { n.setIcon(MetalIconFactory.getTreeLeafIcon()); n.setIconName(""); IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); if (check == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); if (check2 == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { n = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); } } else { n = check2; } } } else { n = check; } } else { n.setIcon(MetalIconFactory.getTreeFolderIcon()); n.setIconName(""); n = (IconNode) n.getChildAt(0); } } tree.revalidate(); tree.repaint(); if (tree.getSelectionCount() > 0) { int selectedRow = tree.getSelectionRows()[0]; tree.setSelectionRow(0); tree.setSelectionRow(selectedRow); } } }); JPanel titlePanel1 = new JPanel(new GridLayout(1, 6)); JPanel titlePanel2 = new JPanel(new GridLayout(1, 6)); titlePanel1.add(titleLabel); titlePanel1.add(title); titlePanel1.add(xLabel); titlePanel1.add(x); titlePanel1.add(yLabel); titlePanel1.add(y); JPanel deselectPanel = new JPanel(); deselectPanel.add(deselect); titlePanel2.add(deselectPanel); titlePanel2.add(gradient); titlePanel2.add(shadow); titlePanel2.add(visibleLegend); titlePanel2.add(new JPanel()); titlePanel2.add(new JPanel()); titlePanel.add(titlePanel1, "Center"); titlePanel.add(titlePanel2, "South"); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); Object[] options = { "Ok", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, all, "Edit Probability Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { change = true; lastSelected = selected; selected = ""; BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); if (gradient.isSelected()) { rend.setBarPainter(new GradientBarPainter()); } else { rend.setBarPainter(new StandardBarPainter()); } if (shadow.isSelected()) { rend.setShadowVisible(true); } else { rend.setShadowVisible(false); } int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { String compare = g.getID().replace(" (", "~"); if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), histDataset, rend); } else { selected = ""; int size = probGraphed.size(); for (int i = 0; i < size; i++) { probGraphed.remove(); } for (GraphProbs g : old) { probGraphed.add(g); } } } } private JPanel fixProbChoices(final String directory) { if (directory.equals("")) { readProbSpecies(outDir + separator + "sim-rep.txt"); } else { readProbSpecies(outDir + separator + directory + separator + "sim-rep.txt"); } for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); j = j - 1; } graphProbs.set(j, index); } JPanel speciesPanel1 = new JPanel(new GridLayout(graphProbs.size() + 1, 1)); JPanel speciesPanel2 = new JPanel(new GridLayout(graphProbs.size() + 1, 2)); use = new JCheckBox("Use"); JLabel specs = new JLabel("Constraint"); JLabel color = new JLabel("Color"); boxes = new ArrayList<JCheckBox>(); series = new ArrayList<JTextField>(); colorsCombo = new ArrayList<JComboBox>(); colorsButtons = new ArrayList<JButton>(); use.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (use.isSelected()) { for (JCheckBox box : boxes) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : boxes) { if (box.isSelected()) { box.doClick(); } } } } }); speciesPanel1.add(use); speciesPanel2.add(specs); speciesPanel2.add(color); final HashMap<String, Paint> colory = this.colors; for (int i = 0; i < graphProbs.size(); i++) { JCheckBox temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { node.setIcon(TextIcons.getIcon("g")); node.setIconName("" + (char) 10003); IconNode n = ((IconNode) node.getParent()); while (n != null) { n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); n.setIconName("" + (char) 10003); if (n.getParent() == null) { n = null; } else { n = ((IconNode) n.getParent()); } } tree.revalidate(); tree.repaint(); String s = series.get(i).getText(); ((JCheckBox) e.getSource()).setSelected(false); int[] cols = new int[35]; for (int k = 0; k < boxes.size(); k++) { if (boxes.get(k).isSelected()) { if (colorsCombo.get(k).getSelectedItem().equals("Red")) { cols[0]++; colorsButtons.get(k).setBackground((Color) colory.get("Red")); colorsButtons.get(k).setForeground((Color) colory.get("Red")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) { cols[1]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue")); colorsButtons.get(k).setForeground((Color) colory.get("Blue")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green")) { cols[2]++; colorsButtons.get(k).setBackground((Color) colory.get("Green")); colorsButtons.get(k).setForeground((Color) colory.get("Green")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) { cols[3]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) { cols[4]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) { cols[5]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan")); } else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) { cols[6]++; colorsButtons.get(k).setBackground((Color) colory.get("Tan")); colorsButtons.get(k).setForeground((Color) colory.get("Tan")); } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) { cols[7]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Gray (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) { cols[8]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) { cols[9]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) { cols[10]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) { cols[11]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) { cols[12]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) { cols[13]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Black")) { cols[14]++; colorsButtons.get(k).setBackground((Color) colory.get("Black")); colorsButtons.get(k).setForeground((Color) colory.get("Black")); } /* * else if * (colorsCombo.get(k).getSelectedItem(). * equals("Red ")) { cols[15]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Blue ")) { * cols[16]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Green ")) { cols[17]++; } else if * (colorsCombo.get(k).getSelectedItem().equals( * "Yellow ")) { cols[18]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Magenta ")) * { cols[19]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Cyan ")) { cols[20]++; } */ else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) { cols[21]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray")); colorsButtons.get(k).setForeground((Color) colory.get("Gray")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) { cols[22]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) { cols[23]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) { cols[24]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) { cols[25]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) { cols[26]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) { cols[27]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) { cols[28]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) { cols[29]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) { cols[30]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) { cols[31]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) { cols[32]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) { cols[33]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) { cols[34]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Gray (Light)")); } } } for (GraphProbs graph : probGraphed) { if (graph.getPaintName().equals("Red")) { cols[0]++; } else if (graph.getPaintName().equals("Blue")) { cols[1]++; } else if (graph.getPaintName().equals("Green")) { cols[2]++; } else if (graph.getPaintName().equals("Yellow")) { cols[3]++; } else if (graph.getPaintName().equals("Magenta")) { cols[4]++; } else if (graph.getPaintName().equals("Cyan")) { cols[5]++; } else if (graph.getPaintName().equals("Tan")) { cols[6]++; } else if (graph.getPaintName().equals("Gray (Dark)")) { cols[7]++; } else if (graph.getPaintName().equals("Red (Dark)")) { cols[8]++; } else if (graph.getPaintName().equals("Blue (Dark)")) { cols[9]++; } else if (graph.getPaintName().equals("Green (Dark)")) { cols[10]++; } else if (graph.getPaintName().equals("Yellow (Dark)")) { cols[11]++; } else if (graph.getPaintName().equals("Magenta (Dark)")) { cols[12]++; } else if (graph.getPaintName().equals("Cyan (Dark)")) { cols[13]++; } else if (graph.getPaintName().equals("Black")) { cols[14]++; } /* * else if (graph.getPaintName().equals("Red ")) { * cols[15]++; } else if * (graph.getPaintName().equals("Blue ")) { * cols[16]++; } else if * (graph.getPaintName().equals("Green ")) { * cols[17]++; } else if * (graph.getPaintName().equals("Yellow ")) { * cols[18]++; } else if * (graph.getPaintName().equals("Magenta ")) { * cols[19]++; } else if * (graph.getPaintName().equals("Cyan ")) { * cols[20]++; } */ else if (graph.getPaintName().equals("Gray")) { cols[21]++; } else if (graph.getPaintName().equals("Red (Extra Dark)")) { cols[22]++; } else if (graph.getPaintName().equals("Blue (Extra Dark)")) { cols[23]++; } else if (graph.getPaintName().equals("Green (Extra Dark)")) { cols[24]++; } else if (graph.getPaintName().equals("Yellow (Extra Dark)")) { cols[25]++; } else if (graph.getPaintName().equals("Magenta (Extra Dark)")) { cols[26]++; } else if (graph.getPaintName().equals("Cyan (Extra Dark)")) { cols[27]++; } else if (graph.getPaintName().equals("Red (Light)")) { cols[28]++; } else if (graph.getPaintName().equals("Blue (Light)")) { cols[29]++; } else if (graph.getPaintName().equals("Green (Light)")) { cols[30]++; } else if (graph.getPaintName().equals("Yellow (Light)")) { cols[31]++; } else if (graph.getPaintName().equals("Magenta (Light)")) { cols[32]++; } else if (graph.getPaintName().equals("Cyan (Light)")) { cols[33]++; } else if (graph.getPaintName().equals("Gray (Light)")) { cols[34]++; } } ((JCheckBox) e.getSource()).setSelected(true); series.get(i).setText(s); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); int colorSet = 0; for (int j = 1; j < cols.length; j++) { if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) { colorSet = j; } } DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); Paint paint; if (colorSet == 34) { paint = colors.get("Gray (Light)"); } else { for (int j = 0; j < colorSet; j++) { draw.getNextPaint(); } paint = draw.getNextPaint(); } Object[] set = colory.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (paint == colory.get(set[j])) { colorsCombo.get(i).setSelectedItem(set[j]); colorsButtons.get(i).setBackground((Color) paint); colorsButtons.get(i).setForeground((Color) paint); } } boolean allChecked = true; for (JCheckBox temp : boxes) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { use.setSelected(true); } String color = (String) colorsCombo.get(i).getSelectedItem(); if (color.equals("Custom")) { color += "_" + colorsButtons.get(i).getBackground().getRGB(); } probGraphed.add(new GraphProbs(colorsButtons.get(i).getBackground(), color, boxes.get(i).getName(), series.get(i).getText() .trim(), i, directory)); } else { boolean check = false; for (JCheckBox b : boxes) { if (b.isSelected()) { check = true; } } if (!check) { node.setIcon(MetalIconFactory.getTreeLeafIcon()); node.setIconName(""); boolean check2 = false; IconNode parent = ((IconNode) node.getParent()); while (parent != null) { for (int j = 0; j < parent.getChildCount(); j++) { if (((IconNode) parent.getChildAt(j)).getIconName().equals("" + (char) 10003)) { check2 = true; } } if (!check2) { parent.setIcon(MetalIconFactory.getTreeFolderIcon()); parent.setIconName(""); } check2 = false; if (parent.getParent() == null) { parent = null; } else { parent = ((IconNode) parent.getParent()); } } tree.revalidate(); tree.repaint(); } ArrayList<GraphProbs> remove = new ArrayList<GraphProbs>(); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { remove.add(g); } } for (GraphProbs g : remove) { probGraphed.remove(g); } use.setSelected(false); colorsCombo.get(i).setSelectedIndex(0); colorsButtons.get(i).setBackground((Color) colory.get("Black")); colorsButtons.get(i).setForeground((Color) colory.get("Black")); } } }); boxes.add(temp); JTextField seriesName = new JTextField(graphProbs.get(i)); seriesName.setName("" + i); seriesName.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyReleased(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyTyped(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } }); series.add(seriesName); ArrayList<String> allColors = new ArrayList<String>(); for (String c : this.colors.keySet()) { allColors.add(c); } allColors.add("Custom"); Object[] col = allColors.toArray(); Arrays.sort(col); JComboBox colBox = new JComboBox(col); colBox.setActionCommand("" + i); colBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) { colorsButtons.get(i).setBackground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem())); colorsButtons.get(i).setForeground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem())); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaintName((String) ((JComboBox) e.getSource()).getSelectedItem()); g.setPaint(colory.get(((JComboBox) e.getSource()).getSelectedItem())); } } } else { for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaintName("Custom_" + colorsButtons.get(i).getBackground().getRGB()); g.setPaint(colorsButtons.get(i).getBackground()); } } } } }); colorsCombo.add(colBox); JButton colorButton = new JButton(); colorButton.setPreferredSize(new Dimension(30, 20)); colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray)); colorButton.setBackground((Color) colory.get("Black")); colorButton.setForeground((Color) colory.get("Black")); colorButton.setUI(new MetalButtonUI()); colorButton.setActionCommand("" + i); colorButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground()); if (newColor != null) { ((JButton) e.getSource()).setBackground(newColor); ((JButton) e.getSource()).setForeground(newColor); colorsCombo.get(i).setSelectedItem("Custom"); } } }); colorsButtons.add(colorButton); JPanel colorPanel = new JPanel(new BorderLayout()); colorPanel.add(colorsCombo.get(i), "Center"); colorPanel.add(colorsButtons.get(i), "East"); speciesPanel1.add(boxes.get(i)); speciesPanel2.add(series.get(i)); speciesPanel2.add(colorPanel); } JPanel speciesPanel = new JPanel(new BorderLayout()); speciesPanel.add(speciesPanel1, "West"); speciesPanel.add(speciesPanel2, "Center"); return speciesPanel; } private void readProbSpecies(String file) { graphProbs = new ArrayList<String>(); ArrayList<String> data = new ArrayList<String>(); try { Scanner s = new Scanner(new File(file)); while (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { return; } if (data.size() == 0) { for (String add : ss) { data.add(add); } } else { for (int i = 0; i < ss.length; i++) { data.set(i, data.get(i) + " " + ss[i]); } } } } catch (Exception e) { } for (String s : data) { if (!s.split(" ")[0].equals("#total")) { graphProbs.add(s.split(" ")[0]); } } } private double[] readProbs(String file) { ArrayList<String> data = new ArrayList<String>(); try { Scanner s = new Scanner(new File(file)); while (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { return new double[0]; } if (data.size() == 0) { for (String add : ss) { data.add(add); } } else { for (int i = 0; i < ss.length; i++) { data.set(i, data.get(i) + " " + ss[i]); } } } } catch (Exception e) { } double[] dataSet = new double[data.size()]; double total = 0; int i = 0; if (data.get(0).split(" ")[0].equals("#total")) { total = Double.parseDouble(data.get(0).split(" ")[1]); i = 1; } for (; i < data.size(); i++) { if (total == 0) { dataSet[i] = Double.parseDouble(data.get(i).split(" ")[1]); } else { dataSet[i - 1] = 100 * ((Double.parseDouble(data.get(i).split(" ")[1])) / total); } } return dataSet; } private void fixProbGraph(String label, String xLabel, String yLabel, DefaultCategoryDataset dataset, BarRenderer rend) { Paint chartBackground = chart.getBackgroundPaint(); Paint plotBackground = chart.getPlot().getBackgroundPaint(); Paint plotRangeGridLine = chart.getCategoryPlot().getRangeGridlinePaint(); chart = ChartFactory.createBarChart(label, xLabel, yLabel, dataset, PlotOrientation.VERTICAL, true, true, false); chart.getCategoryPlot().setRenderer(rend); chart.setBackgroundPaint(chartBackground); chart.getPlot().setBackgroundPaint(plotBackground); chart.getCategoryPlot().setRangeGridlinePaint(plotRangeGridLine); ChartPanel graph = new ChartPanel(chart); legend = chart.getLegend(); if (visibleLegend.isSelected()) { if (chart.getLegend() == null) { chart.addLegend(legend); } } else { if (chart.getLegend() != null) { legend = chart.getLegend(); } chart.removeLegend(); } if (probGraphed.isEmpty()) { graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); } graph.addMouseListener(this); JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); export = new JButton("Export"); refresh = new JButton("Refresh"); run.addActionListener(this); save.addActionListener(this); saveAs.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); this.revalidate(); } public void refreshProb() { BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { String compare = g.getID().replace(" (", "~"); if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot().getRangeAxis() .getLabel(), histDataset, rend); } private void updateSpecies() { String background; try { Properties p = new Properties(); String[] split = outDir.split(separator); FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); background = outDir.substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1]; } else if (p.containsKey("learn.file")) { String[] getProp = p.getProperty("learn.file").split(separator); background = outDir.substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1]; } else { background = null; } } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); background = null; } learnSpecs = new ArrayList<String>(); if (background != null) { if (background.contains(".gcm")) { BioModel gcm = new BioModel(biomodelsim.getRoot()); gcm.load(background); learnSpecs = gcm.getSpecies(); } else if (background.contains(".lpn")) { LhpnFile lhpn = new LhpnFile(biomodelsim.log); lhpn.load(background); /* HashMap<String, Properties> speciesMap = lhpn.getContinuous(); * for (String s : speciesMap.keySet()) { learnSpecs.add(s); } */ // ADDED BY SB. TSDParser extractVars; ArrayList<String> datFileVars = new ArrayList<String>(); // ArrayList<String> allVars = new ArrayList<String>(); Boolean varPresent = false; // Finding the intersection of all the variables present in all // data files. for (int i = 1; (new File(outDir + separator + "run-" + i + ".tsd")).exists(); i++) { extractVars = new TSDParser(outDir + separator + "run-" + i + ".tsd", false); datFileVars = extractVars.getSpecies(); if (i == 1) { learnSpecs.addAll(datFileVars); } for (String s : learnSpecs) { varPresent = false; for (String t : datFileVars) { if (s.equalsIgnoreCase(t)) { varPresent = true; break; } } if (!varPresent) { learnSpecs.remove(s); } } } // END ADDED BY SB. } else { SBMLDocument document = Gui.readSBML(background); Model model = document.getModel(); ListOf ids = model.getListOfSpecies(); for (int i = 0; i < model.getNumSpecies(); i++) { learnSpecs.add(((Species) ids.get(i)).getId()); } } } for (int i = 0; i < learnSpecs.size(); i++) { String index = learnSpecs.get(i); int j = i; while ((j > 0) && learnSpecs.get(j - 1).compareToIgnoreCase(index) > 0) { learnSpecs.set(j, learnSpecs.get(j - 1)); j = j - 1; } learnSpecs.set(j, index); } } public boolean getWarning() { return warn; } private class GraphProbs { private Paint paint; private String species, directory, id, paintName; private int number; private GraphProbs(Paint paint, String paintName, String id, String species, int number, String directory) { this.paint = paint; this.paintName = paintName; this.species = species; this.number = number; this.directory = directory; this.id = id; } private Paint getPaint() { return paint; } private void setPaint(Paint p) { paint = p; } private String getPaintName() { return paintName; } private void setPaintName(String p) { paintName = p; } private String getSpecies() { return species; } private void setSpecies(String s) { species = s; } private String getDirectory() { return directory; } private String getID() { return id; } private int getNumber() { return number; } private void setNumber(int n) { number = n; } } private Hashtable makeIcons() { Hashtable<String, Icon> icons = new Hashtable<String, Icon>(); icons.put("floppyDrive", MetalIconFactory.getTreeFloppyDriveIcon()); icons.put("hardDrive", MetalIconFactory.getTreeHardDriveIcon()); icons.put("computer", MetalIconFactory.getTreeComputerIcon()); icons.put("c", TextIcons.getIcon("c")); icons.put("java", TextIcons.getIcon("java")); icons.put("html", TextIcons.getIcon("html")); return icons; } } class IconNodeRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = -940588131120912851L; public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); Icon icon = ((IconNode) value).getIcon(); if (icon == null) { Hashtable icons = (Hashtable) tree.getClientProperty("JTree.icons"); String name = ((IconNode) value).getIconName(); if ((icons != null) && (name != null)) { icon = (Icon) icons.get(name); if (icon != null) { setIcon(icon); } } } else { setIcon(icon); } return this; } } class IconNode extends DefaultMutableTreeNode { private static final long serialVersionUID = 2887169888272379817L; protected Icon icon; protected String iconName; private String hiddenName; public IconNode() { this(null, ""); } public IconNode(Object userObject, String name) { this(userObject, true, null, name); } public IconNode(Object userObject, boolean allowsChildren, Icon icon, String name) { super(userObject, allowsChildren); this.icon = icon; hiddenName = name; } public String getName() { return hiddenName; } public void setName(String name) { hiddenName = name; } public void setIcon(Icon icon) { this.icon = icon; } public Icon getIcon() { return icon; } public String getIconName() { if (iconName != null) { return iconName; } else { String str = userObject.toString(); int index = str.lastIndexOf("."); if (index != -1) { return str.substring(++index); } else { return null; } } } public void setIconName(String name) { iconName = name; } } class TextIcons extends MetalIconFactory.TreeLeafIcon { private static final long serialVersionUID = 1623303213056273064L; protected String label; private static Hashtable<String, String> labels; protected TextIcons() { } public void paintIcon(Component c, Graphics g, int x, int y) { super.paintIcon(c, g, x, y); if (label != null) { FontMetrics fm = g.getFontMetrics(); int offsetX = (getIconWidth() - fm.stringWidth(label)) / 2; int offsetY = (getIconHeight() - fm.getHeight()) / 2 - 2; g.drawString(label, x + offsetX, y + offsetY + fm.getHeight()); } } public static Icon getIcon(String str) { if (labels == null) { labels = new Hashtable<String, String>(); setDefaultSet(); } TextIcons icon = new TextIcons(); icon.label = (String) labels.get(str); return icon; } public static void setLabelSet(String ext, String label) { if (labels == null) { labels = new Hashtable<String, String>(); setDefaultSet(); } labels.put(ext, label); } private static void setDefaultSet() { labels.put("c", "C"); labels.put("java", "J"); labels.put("html", "H"); labels.put("htm", "H"); labels.put("g", "" + (char) 10003); // and so on /* * labels.put("txt" ,"TXT"); labels.put("TXT" ,"TXT"); labels.put("cc" * ,"C++"); labels.put("C" ,"C++"); labels.put("cpp" ,"C++"); * labels.put("exe" ,"BIN"); labels.put("class" ,"BIN"); * labels.put("gif" ,"GIF"); labels.put("GIF" ,"GIF"); * * labels.put("", ""); */ } }
/** * Chapter 8 Programming Challenges 3. * @author Shung-Hsi Yu <syu07@nyit.edu> ID#0906172 * @version Apr 9, 2014 */ package programming2.ch8.carpetcalculator; public class RoomCarpetTester { public static void main(String[] args) { // Create a RoomCarpet instance costing $8/sqft in a 12x10 ft room RoomDimension room1 = new RoomDimension(12, 10); RoomCarpet room1Carpet = new RoomCarpet(room1, 8); System.out.println("room1: " + room1Carpet.toString()); // Create a RoomCarpet instance costing $10.5/sqft in a 12.5x10.5 ft room RoomDimension room2 = new RoomDimension(12.5, 10.5); RoomCarpet room2Carpet = new RoomCarpet(room2, 10.5); System.out.println("room2: " + room2Carpet.toString()); } }
package verification.platu.logicAnalysis; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import lpn.parser.LhpnFile; import lpn.parser.Transition; import verification.platu.lpn.DualHashMap; import verification.platu.stategraph.State; public class Constraint{ private LhpnFile lpn; // lpn that generates the constraint final private int[] interfaceValues; final private Transition lpnTransition; final private int[] vector; //List<VarNode> variableList = new ArrayList<VarNode>(1); List<Integer> variableList = new ArrayList<Integer>(1); // variableList stores the index of interface variables in the other lpn. List<Integer> valueList = new ArrayList<Integer>(1); private int hashVal = -1; public Constraint(State start, State end, Transition firedTran, LhpnFile lpn2) { this.lpnTransition = firedTran; this.lpn = firedTran.getLpn(); this.vector = start.getVector(); int[] endVector = end.getVector(); // int index = dstLpn.getInterfaceIndex(this.lpn.getLabel()); //int[] thisIndex = lpn2.getOtherIndexArray(this.lpn.ID-1); int[] thisIndex = lpn2.getOtherIndexArray(this.lpn.getLpnIndex()); DualHashMap<String, Integer> varIndexMap = this.lpn.getVarIndexMap(); this.interfaceValues = new int[thisIndex.length]; for(int i = 0; i < thisIndex.length; i++){ int varIndex = thisIndex[i]; this.interfaceValues[i] = this.vector[varIndex]; if(this.vector[varIndex] != endVector[varIndex]){ String variable = varIndexMap.getKey(varIndex); this.valueList.add(endVector[varIndex]); this.variableList.add(lpn2.getVarIndexMap().get(variable)); //this.variableList.add(lpn2.getVarNodeMap().get(variable)); } } if(this.variableList.size() == 0){ System.out.println(this.lpnTransition.getFullLabel()); System.err.println("error: invalid constraint"); System.exit(1); } } /** * @return List of modified variables. */ public List<Integer> getVariableList(){ return this.variableList; } /** * @return List of new variable values. */ public List<Integer> getValueList(){ return this.valueList; } /** * @return State vector. */ public int[] getVector(){ return this.vector; } /** * @return LPN where the constraint was generated. */ public LhpnFile getLpn(){ return this.lpn; } /** * @return Values of the interface variables. */ public int[] getInterfaceValue(){ return this.interfaceValues; } /** * @return LPNTran applied. */ public Transition getLpnTransition(){ return this.lpnTransition; } @Override public int hashCode() { if(this.hashVal == -1){ final int prime = 31; this.hashVal = 1; this.hashVal = prime * this.hashVal + Arrays.hashCode(interfaceValues); this.hashVal = prime * this.hashVal + ((this.lpn == null) ? 0 : this.lpn.getLabel().hashCode()); this.hashVal = prime * this.hashVal + ((this.lpnTransition == null) ? 0 : this.lpnTransition.hashCode()); } return this.hashVal; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Constraint other = (Constraint) obj; if (!Arrays.equals(this.interfaceValues, other.interfaceValues)) return false; if (this.lpn == null) { if (other.lpn != null) return false; } else if (!this.lpn.equals(other.lpn)) return false; if (this.lpnTransition == null) { if (other.lpnTransition != null) return false; } else if (!this.lpnTransition.equals(other.lpnTransition)) return false; return true; } @Override public String toString() { return "Constraint [lpn=" + lpn.getLabel() + ",\n interfaceValues=" + Arrays.toString(interfaceValues) + ",\n lpnTransition=" + lpnTransition + ",\n vector=" + Arrays.toString(vector) + ",\n variableList=" + variableList + ",\n valueList=" + valueList + "]"; } }
package com.continuuity.api.data; import com.google.common.base.Objects; import java.util.Arrays; /** * Atomic compare-and-swap operation. * * Performs an atomic compare-and-swap of the value of a key or column. An * expected value and a new value are specified, and if the current value is * equal to the expected value, it is atomically replaced with the new value, * and the operation is successful. If the current value was not equal to the * expected value, no change is made and the operation fails. * * Supports key-value and columnar operations. */ public class CompareAndSwap implements ConditionalWriteOperation { /** The key/row */ private final byte [] key; /** The column, if a columnar operation */ private final byte [] column; /** The expected value */ private final byte [] expectedValue; /** The new value */ private final byte [] newValue; /** * Compares-and-swaps the value of the specified key by atomically comparing * if the current value is the specified expected value and if so, replacing * it with the specified new value. * * @param key * @param expectedValue * @param newValue */ public CompareAndSwap(final byte [] key, final byte [] expectedValue, final byte [] newValue) { this(key, KV_COL, expectedValue, newValue); } /** * Compares-and-swaps the value of the specified column in the specified row * by atomically comparing if the current value is the specified expected * value and if so, replacing it with the specified new value. * * @param row * @param column * @param expectedValue * @param newValue */ public CompareAndSwap(final byte [] row, final byte [] column, final byte [] expectedValue, final byte [] newValue) { this.key = row; this.column = column; this.expectedValue = expectedValue; this.newValue = newValue; } @Override public byte [] getKey() { return this.key; } public byte [] getColumn() { return this.column; } public byte [] getExpectedValue() { return this.expectedValue; } public byte [] getNewValue() { return this.newValue; } @Override public int getPriority() { return 1; } @Override public String toString() { return Objects.toStringHelper(this) .add("key", new String(this.key)) .add("column", new String(this.column)) .add("expected", Arrays.toString(this.expectedValue)) .add("newValue", Arrays.toString(this.newValue)) .toString(); } }
package com.asha.vrlib.objects; import android.content.Context; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; public class MDSphere3D extends MDAbsObject3D { @Override protected void executeLoad(Context context) { generateSphere(this); } private static void generateSphere(MDAbsObject3D object3D) { generateSphere(18,75,150,object3D); } private static void generateSphere(float radius, int rings, int sectors, MDAbsObject3D object3D) { final float PI = (float) Math.PI; final float PI_2 = (float) (Math.PI / 2); float R = 1f/(float)(rings-1); float S = 1f/(float)(sectors-1); short r, s; float x, y, z; float[] points = new float[rings * sectors * 3]; float[] texcoords = new float[rings * sectors * 2]; int t = 0, v = 0, n = 0; for(r = 0; r < rings; r++) { for(s = 0; s < sectors; s++) { x = (float) (Math.cos(2*PI * s * S) * Math.sin( PI * r * R )); y = - (float) Math.sin( -PI_2 + PI * r * R ); z = (float) (Math.sin(2*PI * s * S) * Math.sin( PI * r * R )); texcoords[t++] = s*S; texcoords[t++] = r*R; points[v++] = x * radius; points[v++] = y * radius; points[v++] = z * radius; } } int counter = 0; short[] indices = new short[rings * sectors * 6]; for(r = 0; r < rings - 1; r++){ for(s = 0; s < sectors-1; s++) { indices[counter++] = (short) (r * sectors + s); indices[counter++] = (short) ((r+1) * sectors + (s)); indices[counter++] = (short) ((r) * sectors + (s+1)); indices[counter++] = (short) ((r) * sectors + (s+1)); indices[counter++] = (short) ((r+1) * sectors + (s)); indices[counter++] = (short) ((r+1) * sectors + (s+1)); } } // initialize vertex byte buffer for shape coordinates ByteBuffer bb = ByteBuffer.allocateDirect( // (# of coordinate values * 4 bytes per float) points.length * 4); bb.order(ByteOrder.nativeOrder()); FloatBuffer vertexBuffer = bb.asFloatBuffer(); vertexBuffer.put(points); vertexBuffer.position(0); // initialize vertex byte buffer for shape coordinates ByteBuffer cc = ByteBuffer.allocateDirect( texcoords.length * 4); cc.order(ByteOrder.nativeOrder()); FloatBuffer texBuffer = cc.asFloatBuffer(); texBuffer.put(texcoords); texBuffer.position(0); // initialize byte buffer for the draw list ByteBuffer dlb = ByteBuffer.allocateDirect( // (# of coordinate values * 2 bytes per short) indices.length * 2); dlb.order(ByteOrder.nativeOrder()); ShortBuffer indexBuffer = dlb.asShortBuffer(); indexBuffer.put(indices); indexBuffer.position(0); object3D.setIndicesBuffer(indexBuffer); object3D.setTexCoordinateBuffer(texBuffer); object3D.setVerticesBuffer(vertexBuffer); object3D.setNumIndices(indices.length); } }
package com.akiban.server.mttests.mtddl; import com.akiban.ais.model.TableName; import com.akiban.server.InvalidOperationException; import com.akiban.server.api.dml.EasyUseColumnSelector; import com.akiban.server.api.dml.scan.CursorId; import com.akiban.server.api.dml.scan.NewRow; import com.akiban.server.api.dml.scan.NiceRow; import com.akiban.server.api.dml.scan.RowOutput; import com.akiban.server.api.dml.scan.RowOutputException; import com.akiban.server.api.dml.scan.ScanAllRequest; import com.akiban.server.api.dml.scan.ScanFlag; import com.akiban.server.itests.ApiTestBase; import com.akiban.server.mttests.Util; import com.akiban.server.mttests.Util.TimedCallable; import com.akiban.server.mttests.Util.TimedResult; import com.akiban.server.mttests.Util.TimePoints; import com.akiban.server.service.session.Session; import com.akiban.server.service.session.SessionImpl; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public final class DdlDmlMT extends ApiTestBase { private static final String SCHEMA = "cold"; private static final String TABLE = "frosty"; @Test public void dropIndexWhileScanning() throws Exception { final int tableId = tableWithTwoRows(); final int SCAN_WAIT = 10000; int indexId = ddl().getUserTable(session, new TableName(SCHEMA, TABLE)).getIndex("name").getIndexId(); TimedCallable<List<NewRow>> scanCallable = getScanCallable(tableId, indexId, SCAN_WAIT); TimedCallable<Void> dropIndexCallable = new TimedCallable<Void>() { @Override protected Void doCall(TimePoints timePoints) throws Exception { TableName table = new TableName(SCHEMA, TABLE); Util.sleep(2000); timePoints.mark("INDEX: DROP>"); ddl().dropIndexes(new SessionImpl(), table, Collections.singleton("name")); timePoints.mark("INDEX: <DROP"); return null; } }; ExecutorService executor = Executors.newFixedThreadPool(2); Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable); Future<TimedResult<Void>> dropIndexFuture = executor.submit(dropIndexCallable); TimedResult<List<NewRow>> scanResult = scanFuture.get(); TimedResult<Void> dropIndexResult = dropIndexFuture.get(); new Util.TimePointsComparison(scanResult, dropIndexResult).verify( "SCAN: START", "SCAN: PAUSE", "INDEX: DROP>", "INDEX: <DROP", "SCAN: FINISH" ); List<NewRow> rowsScanned = scanResult.getItem(); List<NewRow> rowsExpected = Arrays.asList( createNewRow(tableId, 2L, "mr melty"), createNewRow(tableId, 1L, "the snowman") ); assertEquals("rows scanned (in order)", rowsExpected, rowsScanned); assertTrue("time took " + scanResult.getTime(), scanResult.getTime() >= SCAN_WAIT); assertTrue("time took " + dropIndexResult.getTime(), dropIndexResult.getTime() >= SCAN_WAIT); } @Test public void updateRowWhileScanning() throws Exception { final int tableId = tableWithTwoRows(); final int SCAN_WAIT = 10000; int indexId = ddl().getUserTable(session, new TableName(SCHEMA, TABLE)).getIndex("PRIMARY").getIndexId(); TimedCallable<List<NewRow>> scanCallable = getScanCallable(tableId, indexId, SCAN_WAIT); TimedCallable<Void> updateCallable = new TimedCallable<Void>() { @Override protected Void doCall(TimePoints timePoints) throws Exception { NewRow old = new NiceRow(tableId); old.put(0, 2L); NewRow updated = new NiceRow(tableId); updated.put(0, 2L); updated.put(1, "icebox"); Util.sleep(2000); timePoints.mark("UPDATE: IN"); dml().updateRow(new SessionImpl(), old, updated, new EasyUseColumnSelector(1)); timePoints.mark("UPDATE: OUT"); return null; } }; ExecutorService executor = Executors.newFixedThreadPool(2); Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable); Future<TimedResult<Void>> updateFuture = executor.submit(updateCallable); TimedResult<List<NewRow>> scanResult = scanFuture.get(); TimedResult<Void> updateResult = updateFuture.get(); new Util.TimePointsComparison(scanResult, updateResult).verify( "SCAN: START", "SCAN: PAUSE", "UPDATE: IN", "UPDATE: OUT", "SCAN: FINISH" ); List<NewRow> rowsScanned = scanResult.getItem(); List<NewRow> rowsExpected = Arrays.asList( createNewRow(tableId, 1L, "the snowman"), createNewRow(tableId, 2L, "mr melty") ); assertEquals("rows scanned (in order)", rowsExpected, rowsScanned); expectFullRows(tableId, createNewRow(tableId, 1L, "the snowman"), createNewRow(tableId, 2L, "icebox") ); assertTrue("time took " + scanResult.getTime(), scanResult.getTime() >= SCAN_WAIT); assertTrue("time took " + updateResult.getTime(), updateResult.getTime() >= SCAN_WAIT); } private TimedCallable<List<NewRow>> getScanCallable(final int tableId, final int indexId, final int sleepBetween) { return new TimedCallable<List<NewRow>>() { @Override protected List<NewRow> doCall(TimePoints timePoints) throws Exception { Session session = new SessionImpl(); ScanAllRequest request = new ScanAllRequest( tableId, new HashSet<Integer>(Arrays.asList(0, 1)), indexId, EnumSet.of(ScanFlag.START_AT_BEGINNING, ScanFlag.END_AT_END) ); CursorId cursorId = dml().openCursor(session, request); CountingRowOutput output = new CountingRowOutput(); timePoints.mark("SCAN: START"); dml().scanSome(session, cursorId, output, 1); timePoints.mark("SCAN: PAUSE"); Util.sleep(sleepBetween); dml().scanSome(session, cursorId, output, -1); timePoints.mark("SCAN: FINISH"); return output.rows; } }; } int tableWithTwoRows() throws InvalidOperationException { int id = createTable(SCHEMA, TABLE, "id int key", "name varchar(32)", "key(name)"); writeRows( createNewRow(id, 1L, "the snowman"), createNewRow(id, 2L, "mr melty") ); return id; } private static class CountingRowOutput implements RowOutput { private final List<NewRow> rows = new ArrayList<NewRow>(); @Override public void output(NewRow row) throws RowOutputException { rows.add(row); } } }
package com.finitejs.modules.read; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Test; public class ColumnTypeTest { @Test public void testGetInvalidType(){ ColumnType<?> type = ColumnType.getType("unknown"); assertNull(type); type = ColumnType.getType(""); assertNull(type); type = ColumnType.getType(null); assertNull(type); } @Test public void testGetNumberType(){ ColumnType<?> type = ColumnType.getType("number"); assertEquals("number", type.toString()); } @Test public void testGetBooleanType(){ ColumnType<?> type = ColumnType.getType("boolean "); assertEquals("boolean(TRUE_FALSE)", type.toString()); type = ColumnType.getType(" Boolean (true_false) "); assertEquals("boolean(TRUE_FALSE)", type.toString()); type = ColumnType.getType("boolean( yes_no )"); assertEquals("boolean(YES_NO)", type.toString()); type = ColumnType.getType("boolean( Yes_No)"); assertEquals("boolean(YES_NO)", type.toString()); } @Test public void testGetDateTypeWithoutFormat(){ ColumnType<?> type = ColumnType.getType("date"); assertNull(type); } @Test public void testGetDateType(){ ColumnType<?> type = ColumnType.getType("date (M/d/y)"); assertEquals("date(M/d/y)", type.toString()); type = ColumnType.getType("time( H:m )"); assertEquals("time(H:m)", type.toString()); type = ColumnType.getType("datetime(d/M/y H:m)"); assertEquals("datetime(d/M/y H:m)", type.toString()); type = ColumnType.getType("zoneddatetime(d/M/y H:m zzz)"); assertEquals("zoneddatetime(d/M/y H:m zzz)", type.toString()); } @Test public void testGetStringType(){ ColumnType<?> type = ColumnType.getType("string"); assertEquals("string", type.toString()); } @Test public void testFindEmptyType(){ ColumnType<?> type = ColumnType.findType(""); assertNull(type); type = ColumnType.findType(null); assertNull(type); } @Test public void testFindNumberType(){ ColumnType<?> type = ColumnType.findType("10"); assertEquals("number", type.toString()); type = ColumnType.findType("10.555"); assertEquals("number", type.toString()); } @Test public void testFindBooleanType(){ ColumnType<?> type = ColumnType.findType("yes"); assertEquals("boolean(YES_NO)", type.toString()); type = ColumnType.findType("false"); assertEquals("boolean(TRUE_FALSE)", type.toString()); } @Test public void testFindStringType(){ ColumnType<?> type = ColumnType.findType("falseeee"); assertEquals("string", type.toString()); } @Test public void testFindZonedDateTimeType(){ ColumnType<?> type = ColumnType.findType("2014-04-20T12:13:14+05:30"); assertEquals("zoneddatetime(y-M-d'T'HH:mm:ssXXX)", type.toString()); } @Test public void testFindDateTimeType(){ ColumnType<?> type = ColumnType.findType("2014-04-20 12:13:14"); assertEquals("datetime(y-M-d HH:mm:ss)", type.toString()); } @Test public void testFindDateType(){ ColumnType<?> type = ColumnType.findType("2014-04-20"); assertEquals("date(y-M-d)", type.toString()); } @Test public void testFindTimeType(){ ColumnType<?> type = ColumnType.findType("12:13:14"); assertEquals("time(HH:mm:ss)", type.toString()); } }
package com.github.nwillc.simplecache; import com.github.nwillc.simplecache.spi.SCachingProvider; import org.assertj.core.data.MapEntry; import org.junit.Before; import org.junit.Test; import javax.cache.Cache; import javax.cache.CacheManager; import javax.cache.Caching; import javax.cache.configuration.*; import javax.cache.event.CacheEntryEvent; import javax.cache.event.CacheEntryExpiredListener; import javax.cache.event.CacheEntryListener; import javax.cache.event.CacheEntryListenerException; import javax.cache.expiry.CreatedExpiryPolicy; import javax.cache.expiry.Duration; import javax.cache.processor.EntryProcessor; import javax.cache.processor.EntryProcessorResult; import javax.cache.spi.CachingProvider; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import static java.util.stream.StreamSupport.stream; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static org.assertj.core.data.MapEntry.entry; @SuppressWarnings("unchecked") public class SCacheTest { private static final String NAME = "hoard"; private Cache<Long, String> cache; private CacheManager cacheManager; @Before public void setUp() throws Exception { CachingProvider cachingProvider = Caching.getCachingProvider(SCachingProvider.class.getCanonicalName()); cacheManager = cachingProvider.getCacheManager(); cache = cacheManager.createCache(NAME, new MutableConfiguration<>()); } @Test public void testGet() throws Exception { cache.put(0L, "foo"); assertThat(cache.get(0L)).isEqualTo("foo"); } @Test public void testGetAll() throws Exception { cache.put(0L, "zero"); cache.put(1L, "one"); cache.put(2L, "two"); Set<Long> keys = new HashSet<>(); keys.add(0L); keys.add(1L); assertThat(cache.getAll(keys)).containsExactly(entry(0L, "zero"), entry(1L, "one")); assertThat(cache).hasSize(3); } @Test public void testKnowOrigins() throws Exception { assertThat(cache.getCacheManager()).isEqualTo(cacheManager); assertThat(cache.getName()).isEqualTo(NAME); } @Test public void testUnwrap() throws Exception { assertThat(cache.unwrap(SCache.class)).isEqualTo(cache); } @Test public void testUnwrapFail() throws Exception { assertThatThrownBy(() -> cache.unwrap(String.class)).isInstanceOf(IllegalArgumentException.class); } @Test public void testDeregisterListener() throws Exception { Factory<CacheEntryListener<Long,String>> listenerFactory = () -> (CacheEntryExpiredListener<Long, String>) cacheEntryEvents -> {}; CacheEntryListenerConfiguration<Long, String> cacheEntryListenerConfiguration = new MutableCacheEntryListenerConfiguration<>(listenerFactory, null, false, false); assertThatThrownBy(() -> cache.deregisterCacheEntryListener(cacheEntryListenerConfiguration)).isInstanceOf(UnsupportedOperationException.class); } @Test public void testRegisterListener() throws Exception { Factory<CacheEntryListener<Long,String>> listenerFactory = () -> (CacheEntryExpiredListener<Long, String>) cacheEntryEvents -> {}; CacheEntryListenerConfiguration<Long, String> cacheEntryListenerConfiguration = new MutableCacheEntryListenerConfiguration<>(listenerFactory, null, false, false); cache.registerCacheEntryListener(cacheEntryListenerConfiguration); cache.registerCacheEntryListener(cacheEntryListenerConfiguration); } @Test public void testDeregisterCacheEntryListener() throws Exception { assertThatThrownBy(() -> cache.deregisterCacheEntryListener(null)).isInstanceOf(UnsupportedOperationException.class); } @Test public void shouldClear() throws Exception { cache.put(0L, "foo"); assertThat(cache).hasSize(1); cache.clear(); assertThat(cache).hasSize(0); } @Test public void testInvokeAll() throws Exception { EntryProcessor<Long, String, String> processor = (entry, arguments) -> String.valueOf(entry.getKey()) + arguments[0] + entry.getValue(); cache.put(0L, "foo"); cache.put(1L, "bar"); Set<Long> keys = new HashSet<>(); keys.add(0L); keys.add(2L); Map<Long, EntryProcessorResult<String>> resultMap = cache.invokeAll(keys, processor, ":"); assertThat(resultMap).hasSize(1); assertThat(resultMap.get(0L).get()).isEqualTo("0:foo"); } @Test public void testInvoke() throws Exception { EntryProcessor<Long, String, String> processor = (entry, arguments) -> ((entry.getKey() == null) ? "na" : entry.getValue()) + arguments[0]; cache.put(0L, "foo"); assertThat(cache.invoke(0L, processor, "bar")).isEqualTo("foobar"); assertThat(cache.invoke(1L, processor, "ughty")).isEqualTo("naughty"); } @Test public void shouldContainsKey() throws Exception { assertThat(cache.containsKey(0L)).isFalse(); cache.put(0L, "foo"); assertThat(cache.containsKey(0L)).isTrue(); } @Test public void shouldStream() throws Exception { assertThat(cache).hasSize(0); cache.put(0L, "foo"); assertThat(cache).hasSize(1); assertThat(cache.containsKey(0L)).isTrue(); } @Test public void testRemoveAll() throws Exception { cache.put(0L, "zero"); cache.put(1L, "one"); assertThat(cache).hasSize(2); cache.removeAll(); assertThat(cache).isEmpty(); } @Test public void testRemoveAllSet() throws Exception { cache.put(0L, "zero"); cache.put(1L, "one"); assertThat(cache).hasSize(2); Set<Long> keys = new HashSet<>(); keys.add(0L); cache.removeAll(keys); assertThat(cache).containsExactly(new SEntry<>(1L, "one")); } @Test public void shouldPutIfAbsent() throws Exception { cache.put(0L, "foo"); assertThat(cache.get(0L)).isEqualTo("foo"); assertThat(cache.putIfAbsent(0L, "bar")).isFalse(); assertThat(cache.putIfAbsent(1L, "bar")).isTrue(); assertThat(cache.get(0L)).isEqualTo("foo"); assertThat(cache.get(1L)).isEqualTo("bar"); } @Test public void shouldRemove() throws Exception { cache.put(0L, "foo"); assertThat(cache.containsKey(0L)).isTrue(); assertThat(cache.remove(0L)).isTrue(); assertThat(cache.containsKey(0L)).isFalse(); assertThat(cache.remove(1L)).isFalse(); } @Test public void testGetAndReplace() throws Exception { cache.put(0L, "foo"); assertThat(cache.getAndReplace(0L, "zero")).isEqualTo("foo"); assertThat(cache.get(0L)).isEqualTo("zero"); } @Test public void testGetAndReplaceNotPresent() throws Exception { assertThat(cache.getAndReplace(0L, "zero")).isNull(); assertThat(cache.get(0L)).isNull(); } @Test public void testConfigurationFail() throws Exception { assertThatThrownBy(() -> cache.getConfiguration(OtherConfig.class)).isInstanceOf(IllegalArgumentException.class); } @Test public void testGetAndPut() throws Exception { cache.put(0L, "foo"); assertThat(cache.getAndPut(0L, "0")).isEqualTo("foo"); assertThat(cache.get(0L)).isEqualTo("0"); } @Test public void testPutAll() throws Exception { Map<Long, String> map = new HashMap<>(); map.put(0L, "0"); map.put(1L, "1"); assertThat(cache).isEmpty(); cache.putAll(map); assertThat(cache).containsExactly(new SEntry<>(0L, "0"), new SEntry<>(1L, "1")); } @Test public void testGetAndRemove() throws Exception { cache.put(0L, "foo"); String value = cache.getAndRemove(0L); assertThat(value).isEqualTo("foo"); assertThat(cache.get(0L)).isNull(); } @Test public void testRemove() throws Exception { cache.put(0L, "foo"); assertThat(cache.remove(0L, "bar")).isFalse(); assertThat(cache.get(0L)).isEqualTo("foo"); assertThat(cache.remove(0L, "foo")).isTrue(); assertThat(cache.get(0L)).isNull(); } @Test public void testReplace() throws Exception { cache.put(0L, "foo"); assertThat(cache.replace(0L, "bar")).isTrue(); assertThat(cache.get(0L)).isEqualTo("bar"); } @Test public void testReplaceFail() throws Exception { assertThat(cache.replace(0L, "foo")).isFalse(); assertThat(cache.get(0L)).isNull(); } @Test public void testReplaceWithValue() throws Exception { cache.put(0L, "foo"); assertThat(cache.replace(0L, "bar", "baz")).isFalse(); assertThat(cache.get(0L)).isEqualTo("foo"); assertThat(cache.replace(0L, "foo", "bar")).isTrue(); assertThat(cache.get(0L)).isEqualTo("bar"); } @Test public void shouldExpire() throws Exception { MutableConfiguration<Long, String> conf = new MutableConfiguration<>(); conf.setExpiryPolicyFactory(() -> new CreatedExpiryPolicy(new Duration(TimeUnit.SECONDS, 5))); cache = cacheManager.createCache(NAME + "-expiry", conf); SCache<Long, String> sCache = cache.unwrap(SCache.class); assertThat(sCache).isNotNull(); final AtomicLong time = new AtomicLong(0L); sCache.setClock(time::get); sCache.put(0L, "foo"); assertThat(sCache.get(0L)).isEqualTo("foo"); time.set(TimeUnit.SECONDS.toNanos(10)); assertThat(sCache.get(0L)).isNull(); } @Test public void testClose() throws Exception { assertThat(cache.isClosed()).isFalse(); cache.close(); assertThat(cache.isClosed()).isTrue(); assertThatThrownBy(() -> cache.get(0L)).isInstanceOf(IllegalStateException.class); cache.close(); } @Test public void testIterator() throws Exception { cache.put(0L, "foo"); cache.put(1L, "bar"); List<MapEntry> all = stream(cache.spliterator(), false).map(e -> entry(e.getKey(), e.getValue())).collect(Collectors.toList()); assertThat(all).containsExactly(entry(0L, "foo"), entry(1L, "bar")); } static class OtherConfig implements Configuration<Long, String> { @Override public Class<Long> getKeyType() { return null; } @Override public Class<String> getValueType() { return null; } @Override public boolean isStoreByValue() { return false; } } }
package biz.orgin.minecraft.hothgenerator; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.material.Mushroom; import java.util.UUID; /** * Listens to player interaction events, specifically using a * water or lava bucket so that any placed water or lava can * be frozen into ice or stone. * Bonemealing exposed blocks are prevented. * @author orgin * */ public class ToolUseManager implements Listener { private Map<UUID, PlayerSelection> playerSelections = new HashMap<UUID, PlayerSelection>(); HothGeneratorPlugin plugin; public ToolUseManager(HothGeneratorPlugin plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerInteract(PlayerInteractEvent event) { Action action = event.getAction(); // Hothexport primary position if(action.equals(Action.LEFT_CLICK_BLOCK)) { Player player = event.getPlayer(); ItemStack item = player.getInventory().getItemInMainHand(); if(player.hasPermission("hothgenerator.hothexport") && !ConfigManager.isWorldEditSelection(this.plugin) && item.getType().equals(ConfigManager.getSelectionToolMaterial(plugin))) { UUID uuid = player.getUniqueId(); Block block = event.getClickedBlock(); PlayerSelection ps = this.playerSelections.get(uuid); if(ps==null) { ps = new PlayerSelection(block.getLocation(), null); this.playerSelections.put(uuid, ps); } else { ps.setPos1(block.getLocation()); } this.plugin.sendMessage(player, "&b" + ps.getPrimaryPosition()); event.setCancelled(true); } } // Hothexport secondary position if(action.equals(Action.RIGHT_CLICK_BLOCK)) { Player player = event.getPlayer(); ItemStack item = player.getInventory().getItemInMainHand(); if(player.hasPermission("hothgenerator.hothexport") && !ConfigManager.isWorldEditSelection(this.plugin) && item.getType().equals(ConfigManager.getSelectionToolMaterial(plugin))) { UUID uuid = player.getUniqueId(); Block block = event.getClickedBlock(); PlayerSelection ps = this.playerSelections.get(uuid); if(ps==null) { ps = new PlayerSelection(null, block.getLocation()); this.playerSelections.put(uuid, ps); } else { ps.setPos2(block.getLocation()); } this.plugin.sendMessage(player, "&b" + ps.getSecondaryPosition()); } } if(!event.isCancelled()) { World world = event.getPlayer().getWorld(); if(action.equals(Action.RIGHT_CLICK_BLOCK)) { Player player = event.getPlayer(); ItemStack item = player.getInventory().getItemInMainHand(); WorldType worldtype = this.plugin.getWorldType(world); if(ConfigManager.isItemInfoTool(this.plugin) && item.getType().equals(Material.CLAY_BALL)) { Block block = event.getClickedBlock(); player.sendMessage("Item: name = " + block.getType().name() + " type = " + MaterialManager.toID(block.getType()) + ", data = " + DataManager.getData(block)); BlockState state = block.getState(); if(block.getType().equals(Material.HUGE_MUSHROOM_1) || block.getType().equals(Material.HUGE_MUSHROOM_2)) { Mushroom mushroom = (Mushroom)state.getData(); Set<BlockFace> faceSet = mushroom.getPaintedFaces(); BlockFace[] faces = faceSet.toArray(new BlockFace[0]); for(int i=0;i<faces.length;i++) { player.sendMessage(block.getType().name() + " face: " + faces[i].name()); } } } if(this.plugin.isHothWorld(world) && worldtype == WorldType.HOTH) { if(item.getType().equals(Material.WATER_BUCKET)) { Block block = event.getClickedBlock(); block = block.getRelative(event.getBlockFace()); if(ConfigManager.isRulesFreezewater(this.plugin, block.getLocation()) && !this.plugin.canPlaceLiquid(world, block)) { BlockPlacerThread th = new BlockPlacerThread(world, block.getX(), block.getY(), block.getZ(), Material.WATER, Material.ICE); try { Bukkit.getScheduler().scheduleSyncDelayedTask(this.plugin, th); } catch(Exception e) { this.plugin.logMessage("Exception while trying to register BlockPlacerThread. You probably need to restart yoru server.", true); } } } else if(item.getType().equals(Material.LAVA_BUCKET)) { Block block = event.getClickedBlock(); block = block.getRelative(event.getBlockFace()); if(ConfigManager.isRulesFreezelava(this.plugin, block.getLocation()) && !this.plugin.canPlaceLiquid(world, block)) { BlockPlacerThread th = new BlockPlacerThread(world, block.getX(), block.getY(), block.getZ(), Material.LAVA, Material.STONE); Bukkit.getScheduler().scheduleSyncDelayedTask(this.plugin, th); } } } if(this.plugin.isHothWorld(world) && worldtype == WorldType.MUSTAFAR) { if(item.getType().equals(Material.WATER_BUCKET)) { Block block = event.getClickedBlock(); block = block.getRelative(event.getBlockFace()); if(ConfigManager.isRulesPlaceWater(this.plugin, block.getLocation())) { WaterPlacerThread th = new WaterPlacerThread(player, block.getLocation()); try { Bukkit.getScheduler().scheduleSyncDelayedTask(this.plugin, th); } catch(Exception e) { this.plugin.logMessage("Exception while trying to register WaterPlacerThread. You probably need to restart your server.", true); } } } } if(this.plugin.isHothWorld(world) && (worldtype == WorldType.HOTH || worldtype == WorldType.TATOOINE)) { if(item.getType().equals(Material.INK_SACK) && item.getDurability() == 15) { Block block = event.getClickedBlock(); if(!ConfigManager.isRulesPlantsgrow(this.plugin, block.getLocation())) { // User is bonemealing something Material type = block.getType(); int maxy = world.getHighestBlockYAt(block.getLocation()); if(Math.abs(maxy-block.getY())<2) { if( type.equals(Material.CARROT) || type.equals(Material.POTATO) || type.equals(Material.PUMPKIN_STEM) || type.equals(Material.MELON_STEM) || type.equals(Material.SAPLING) || type.equals(Material.CROPS) ) { if(worldtype == WorldType.HOTH || (worldtype == WorldType.TATOOINE && !HothUtils.isWatered(block.getRelative(BlockFace.DOWN)))) { event.setCancelled(true); block.breakNaturally(); } } if(type.equals(Material.GRASS)) { if(worldtype == WorldType.HOTH || (worldtype == WorldType.TATOOINE && !HothUtils.isWatered(block))) { event.setCancelled(true); } } } } } } } } } public Location getPrimaryPosition(Player player) { PlayerSelection ps = this.playerSelections.get(player.getUniqueId()); if(ps==null) { return null; } return ps.getPos1(); } public Location getSecondaryPosition(Player player) { PlayerSelection ps = this.playerSelections.get(player.getUniqueId()); if(ps==null) { return null; } return ps.getPos2(); } private class PlayerSelection { private Location pos1; private Location pos2; public PlayerSelection(Location pos1, Location pos2) { this.pos1 = pos1; this.pos2 = pos2; } public Location getPos1() { return pos1; } public void setPos1(Location pos1) { this.pos1 = pos1; if(this.pos2!=null && !this.pos1.getWorld().equals(this.pos2.getWorld())) { this.pos2 = null; } } public Location getPos2() { return pos2; } public void setPos2(Location pos2) { this.pos2 = pos2; if(this.pos2!=null && !this.pos1.getWorld().equals(this.pos2.getWorld())) { this.pos1 = null; } } public String getPrimaryPosition() { int cnt = this.getBlockCnt(); if(cnt>0) { return "First position set to " + this.locToString(this.pos1) + ". (" + this.getBlockCnt() + ")"; } else { return "First position set to " + this.locToString(this.pos1) + "."; } } public String getSecondaryPosition() { int cnt = this.getBlockCnt(); if(cnt>0) { return "Second position set to " + this.locToString(this.pos2) + ". (" + this.getBlockCnt() + ")"; } else { return "Second position set to " + this.locToString(this.pos2) + "."; } } private String locToString(Location location) { int x = location.getBlockX(); int y = location.getBlockY(); int z = location.getBlockZ(); return x + ", " + y + ", " + z; } private int getBlockCnt() { if(pos1==null || pos2==null) { return -1; } int dx = Math.abs(pos1.getBlockX() - pos2.getBlockX()) + 1; int dy = Math.abs(pos1.getBlockY() - pos2.getBlockY()) + 1; int dz = Math.abs(pos1.getBlockZ() - pos2.getBlockZ()) + 1; return dx*dy*dz; } } private class WaterPlacerThread implements Runnable { @SuppressWarnings("unused") private Player player; private Location location; private WaterPlacerThread(Player player, Location location) { this.player = player; this.location = location; } @Override public void run() { if(!HothUtils.isTooHot(this.location, 2)) { Block block = this.location.getBlock(); block.setType(Material.WATER); } } } }
package mho.wheels.iterables; import mho.wheels.ordering.Ordering; import mho.wheels.random.IsaacPRNG; import mho.wheels.structures.Pair; import mho.wheels.structures.Triple; import java.math.BigInteger; import java.util.List; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.testing.Testing.*; @SuppressWarnings({"UnusedDeclaration", "ConstantConditions"}) public class RandomProviderDemos { private static final boolean USE_RANDOM = false; private static final int SMALL_LIMIT = 1000; private static int LIMIT; private static IterableProvider P; private static void initialize() { if (USE_RANDOM) { P = RandomProvider.example(); LIMIT = 1000; } else { P = ExhaustiveProvider.INSTANCE; LIMIT = 10000; } } private static void demoConstructor() { initialize(); for (Void v : take(LIMIT, repeat((Void) null))) { System.out.println("RandomProvider() = " + new RandomProvider()); } } private static void demoConstructor_List_Integer() { initialize(); for (List<Integer> is : take(LIMIT, P.lists(IsaacPRNG.SIZE, P.integers()))) { System.out.println("RandomProvider(" + is + ") = " + new RandomProvider(is)); } } private static void demoGetScale() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { System.out.println("getScale(" + rp + ") = " + rp.getScale()); } } private static void demoGetSecondaryScale() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { System.out.println("getSecondaryScale(" + rp + ") = " + rp.getSecondaryScale()); } } private static void demoGetSeed() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { System.out.println("getSeed(" + rp + ") = " + rp.getSeed()); } } private static void demoWithScale() { initialize(); for (Pair<RandomProvider, Integer> p : take(LIMIT, P.pairs(P.randomProviders(), P.naturalIntegers()))) { System.out.println("withScale(" + p.a + ", " + p.b + ") = " + p.a.withScale(p.b)); } } private static void demoWithSecondaryScale() { initialize(); for (Pair<RandomProvider, Integer> p : take(LIMIT, P.pairs(P.randomProviders(), P.naturalIntegers()))) { System.out.println("withSecondaryScale(" + p.a + ", " + p.b + ") = " + p.a.withSecondaryScale(p.b)); } } private static void demoCopy() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { System.out.println("copy(" + rp + ") = " + rp.copy()); } } private static void demoDeepCopy() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { System.out.println("deepCopy(" + rp + ") = " + rp.deepCopy()); } } private static void demoReset() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { rp.nextInt(); RandomProvider beforeReset = rp.deepCopy(); rp.reset(); System.out.println("reset(" + beforeReset + ") = " + rp); } } private static void demoGetId() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { System.out.println("getId(" + rp + ") = " + rp.getId()); } } private static void demoNextInt() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextInt(" + rp + ") = " + rp.nextInt()); } } private static void demoIntegers() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("integers(" + rp + ") = " + its(rp.integers())); } } private static void demoNextLong() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextLong(" + rp + ") = " + rp.nextLong()); } } private static void demoLongs() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("longs(" + rp + ") = " + its(rp.longs())); } } private static void demoNextBoolean() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextBoolean(" + rp + ") = " + rp.nextBoolean()); } } private static void demoBooleans() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("booleans(" + rp + ") = " + its(rp.booleans())); } } private static void demoNextUniformSample_Iterable() { initialize(); Iterable<Pair<RandomProvider, List<Integer>>> ps = P.pairs( P.randomProvidersDefault(), P.listsAtLeast(1, P.withNull(P.integers())) ); for (Pair<RandomProvider, List<Integer>> p : take(SMALL_LIMIT, ps)) { System.out.println("nextUniformSample(" + p.a + ", " + p.b.toString() + ") = " + p.a.nextUniformSample(p.b)); } } private static void demoUniformSample_Iterable() { initialize(); Iterable<Pair<RandomProvider, List<Integer>>> ps = P.pairs( P.randomProvidersDefault(), P.lists(P.withNull(P.integers())) ); for (Pair<RandomProvider, List<Integer>> p : take(SMALL_LIMIT, ps)) { System.out.println("uniformSample(" + p.a + ", " + p.b.toString() + ") = " + its(p.a.uniformSample(p.b))); } } private static void demoNextUniformSample_String() { initialize(); Iterable<Pair<RandomProvider, String>> ps = P.pairs(P.randomProvidersDefault(), P.stringsAtLeast(1)); for (Pair<RandomProvider, String> p : take(SMALL_LIMIT, ps)) { System.out.println("nextUniformSample(" + p.a + ", " + nicePrint(p.b) + ") = " + nicePrint(p.a.nextUniformSample(p.b))); } } private static void demoUniformSample_String() { initialize(); Iterable<Pair<RandomProvider, String>> ps = P.pairs(P.randomProvidersDefault(), P.strings()); for (Pair<RandomProvider, String> p : take(SMALL_LIMIT, ps)) { System.out.println("uniformSample(" + p.a + ", " + nicePrint(p.b) + ") = " + cits(p.a.uniformSample(p.b))); } } private static void demoNextOrdering() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextOrdering(" + rp + ") = " + rp.nextOrdering()); } } private static void demoOrderings() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("orderings(" + rp + ") = " + its(rp.orderings())); } } private static void demoNextRoundingMode() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextRoundingMode(" + rp + ") = " + rp.nextRoundingMode()); } } private static void demoRoundingModes() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("roundingModes(" + rp + ") = " + its(rp.roundingModes())); } } private static void demoNextPositiveByte() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextPositiveByte(" + rp + ") = " + rp.nextPositiveByte()); } } private static void demoPositiveBytes() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("positiveBytes(" + rp + ") = " + its(rp.positiveBytes())); } } private static void demoNextPositiveShort() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextPositiveShort(" + rp + ") = " + rp.nextPositiveShort()); } } private static void demoPositiveShorts() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("positiveShorts(" + rp + ") = " + its(rp.positiveShorts())); } } private static void demoNextPositiveInt() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextPositiveInt(" + rp + ") = " + rp.nextPositiveInt()); } } private static void demoPositiveIntegers() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("positiveIntegers(" + rp + ") = " + its(rp.positiveIntegers())); } } private static void demoNextPositiveLong() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextPositiveLong(" + rp + ") = " + rp.nextPositiveLong()); } } private static void demoPositiveLongs() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("positiveLongs(" + rp + ") = " + its(rp.positiveLongs())); } } private static void demoNextNegativeByte() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextNegativeByte(" + rp + ") = " + rp.nextNegativeByte()); } } private static void demoNegativeBytes() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("negativeBytes(" + rp + ") = " + its(rp.negativeBytes())); } } private static void demoNextNegativeShort() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextNegativeShort(" + rp + ") = " + rp.nextNegativeShort()); } } private static void demoNegativeShorts() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("negativeShorts(" + rp + ") = " + its(rp.negativeShorts())); } } private static void demoNextNegativeInt() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextNegativeInt(" + rp + ") = " + rp.nextNegativeInt()); } } private static void demoNegativeIntegers() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("negativeIntegers(" + rp + ") = " + its(rp.negativeIntegers())); } } private static void demoNextNegativeLong() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextNegativeLong(" + rp + ") = " + rp.nextNegativeLong()); } } private static void demoNegativeLongs() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("negativeLongs(" + rp + ") = " + its(rp.negativeLongs())); } } private static void demoNextNaturalByte() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextNaturalByte(" + rp + ") = " + rp.nextNaturalByte()); } } private static void demoNaturalBytes() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("naturalBytes(" + rp + ") = " + its(rp.naturalBytes())); } } private static void demoNextNaturalShort() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextNaturalShort(" + rp + ") = " + rp.nextNaturalShort()); } } private static void demoNaturalShorts() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("naturalShorts(" + rp + ") = " + its(rp.naturalShorts())); } } private static void demoNextNaturalInt() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextNaturalInt(" + rp + ") = " + rp.nextNaturalInt()); } } private static void demoNaturalIntegers() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("naturalIntegers(" + rp + ") = " + its(rp.naturalIntegers())); } } private static void demoNextNaturalLong() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextNaturalLong(" + rp + ") = " + rp.nextNaturalLong()); } } private static void demoNaturalLongs() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("naturalLongs(" + rp + ") = " + its(rp.naturalLongs())); } } private static void demoNextNonzeroByte() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextNonzeroByte(" + rp + ") = " + rp.nextNonzeroByte()); } } private static void demoNonzeroBytes() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("nonzeroBytes(" + rp + ") = " + its(rp.nonzeroBytes())); } } private static void demoNextNonzeroShort() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextNonzeroShort(" + rp + ") = " + rp.nextNonzeroShort()); } } private static void demoNonzeroShorts() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("nonzeroShorts(" + rp + ") = " + its(rp.nonzeroShorts())); } } private static void demoNextNonzeroInt() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextNonzeroInt(" + rp + ") = " + rp.nextNonzeroInt()); } } private static void demoNonzeroIntegers() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("nonzeroIntegers(" + rp + ") = " + its(rp.nonzeroIntegers())); } } private static void demoNextNonzeroLong() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextNonzeroLong(" + rp + ") = " + rp.nextNonzeroLong()); } } private static void demoNonzeroLongs() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("nonzeroLongs(" + rp + ") = " + its(rp.nonzeroLongs())); } } private static void demoNextByte() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextByte(" + rp + ") = " + rp.nextByte()); } } private static void demoBytes() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("bytes(" + rp + ") = " + its(rp.bytes())); } } private static void demoNextShort() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextShort(" + rp + ") = " + rp.nextShort()); } } private static void demoShorts() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("shorts(" + rp + ") = " + its(rp.shorts())); } } private static void demoNextAsciiChar() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextAsciiChar(" + rp + ") = " + nicePrint(rp.nextAsciiChar())); } } private static void demoAsciiCharacters() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("asciiCharacters(" + rp + ") = " + cits(rp.asciiCharacters())); } } private static void demoNextChar() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) { System.out.println("nextChar(" + rp + ") = " + nicePrint(rp.nextChar())); } } private static void demoCharacters() { initialize(); for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) { System.out.println("characters(" + rp + ") = " + cits(rp.characters())); } } private static void demoNextFromRangeUp_byte() { initialize(); for (Pair<RandomProvider, Byte> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.bytes()))) { System.out.println("nextFromRangeUp(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeUp(p.b)); } } private static void demoRangeUp_byte() { initialize(); for (Pair<RandomProvider, Byte> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.bytes()))) { System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b))); } } private static void demoNextFromRangeUp_short() { initialize(); for (Pair<RandomProvider, Short> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.shorts()))) { System.out.println("nextFromRangeUp(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeUp(p.b)); } } private static void demoRangeUp_short() { initialize(); Iterable<Pair<RandomProvider, Short>> ps = P.pairs(P.randomProvidersDefault(), P.shorts()); for (Pair<RandomProvider, Short> p : take(SMALL_LIMIT, ps)) { System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b))); } } private static void demoNextFromRangeUp_int() { initialize(); for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.integers()))) { System.out.println("nextFromRangeUp(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeUp(p.b)); } } private static void demoRangeUp_int() { initialize(); Iterable<Pair<RandomProvider, Integer>> ps = P.pairs(P.randomProvidersDefault(), P.integers()); for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, ps)) { System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b))); } } private static void demoNextFromRangeUp_long() { initialize(); for (Pair<RandomProvider, Long> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.longs()))) { System.out.println("nextFromRangeUp(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeUp(p.b)); } } private static void demoRangeUp_long() { initialize(); for (Pair<RandomProvider, Long> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.longs()))) { System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b))); } } private static void demoNextFromRangeUp_char() { initialize(); Iterable<Pair<RandomProvider, Character>> ps = P.pairs(P.randomProvidersDefault(), P.characters()); for (Pair<RandomProvider, Character> p : take(SMALL_LIMIT, ps)) { System.out.println("nextFromRangeUp(" + p.a + ", " + nicePrint(p.b) + ") = " + nicePrint(p.a.nextFromRangeUp(p.b))); } } private static void demoRangeUp_char() { initialize(); Iterable<Pair<RandomProvider, Character>> ps = P.pairs(P.randomProvidersDefault(), P.characters()); for (Pair<RandomProvider, Character> p : take(SMALL_LIMIT, ps)) { System.out.println("rangeUp(" + p.a + ", " + nicePrint(p.b) + ") = " + cits(p.a.rangeUp(p.b))); } } private static void demoNextFromRangeDown_byte() { initialize(); for (Pair<RandomProvider, Byte> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.bytes()))) { System.out.println("nextFromRangeDown(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeDown(p.b)); } } private static void demoRangeDown_byte() { initialize(); for (Pair<RandomProvider, Byte> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.bytes()))) { System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b))); } } private static void demoNextFromRangeDown_short() { initialize(); for (Pair<RandomProvider, Short> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.shorts()))) { System.out.println("nextFromRangeDown(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeDown(p.b)); } } private static void demoRangeDown_short() { initialize(); Iterable<Pair<RandomProvider, Short>> ps = P.pairs(P.randomProvidersDefault(), P.shorts()); for (Pair<RandomProvider, Short> p : take(SMALL_LIMIT, ps)) { System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b))); } } private static void demoNextFromRangeDown_int() { initialize(); for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.integers()))) { System.out.println("nextFromRangeDown(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeDown(p.b)); } } private static void demoRangeDown_int() { initialize(); Iterable<Pair<RandomProvider, Integer>> ps = P.pairs(P.randomProvidersDefault(), P.integers()); for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, ps)) { System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b))); } } private static void demoNextFromRangeDown_long() { initialize(); for (Pair<RandomProvider, Long> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.longs()))) { System.out.println("nextFromRangeDown(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeDown(p.b)); } } private static void demoRangeDown_long() { initialize(); for (Pair<RandomProvider, Long> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.longs()))) { System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b))); } } private static void demoNextFromRangeDown_char() { initialize(); Iterable<Pair<RandomProvider, Character>> ps = P.pairs(P.randomProvidersDefault(), P.characters()); for (Pair<RandomProvider, Character> p : take(SMALL_LIMIT, ps)) { System.out.println("nextFromRangeDown(" + p.a + ", " + nicePrint(p.b) + ") = " + nicePrint(p.a.nextFromRangeDown(p.b))); } } private static void demoRangeDown_char() { initialize(); Iterable<Pair<RandomProvider, Character>> ps = P.pairs(P.randomProvidersDefault(), P.characters()); for (Pair<RandomProvider, Character> p : take(SMALL_LIMIT, ps)) { System.out.println("rangeDown(" + p.a + ", " + nicePrint(p.b) + ") = " + cits(p.a.rangeDown(p.b))); } } private static void demoNextFromRange_byte_byte() { initialize(); Iterable<Triple<RandomProvider, Byte, Byte>> ts = filter( t -> t.b <= t.c, P.triples(P.randomProvidersDefault(), P.bytes(), P.bytes()) ); for (Triple<RandomProvider, Byte, Byte> p : take(SMALL_LIMIT, ts)) { System.out.println("nextFromRange(" + p.a + ", " + p.b + ", " + p.c + ") = " + p.a.nextFromRange(p.b, p.c)); } } private static void demoRange_byte_byte() { initialize(); Iterable<Triple<RandomProvider, Byte, Byte>> ts = P.triples(P.randomProvidersDefault(), P.bytes(), P.bytes()); for (Triple<RandomProvider, Byte, Byte> p : take(LIMIT, ts)) { System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + its(p.a.range(p.b, p.c))); } } private static void demoNextFromRange_short_short() { initialize(); Iterable<Triple<RandomProvider, Short, Short>> ts = filter( t -> t.b <= t.c, P.triples(P.randomProvidersDefault(), P.shorts(), P.shorts()) ); for (Triple<RandomProvider, Short, Short> p : take(SMALL_LIMIT, ts)) { System.out.println("nextFromRange(" + p.a + ", " + p.b + ", " + p.c + ") = " + p.a.nextFromRange(p.b, p.c)); } } private static void demoRange_short_short() { initialize(); Iterable<Triple<RandomProvider, Short, Short>> ts = P.triples( P.randomProvidersDefault(), P.shorts(), P.shorts() ); for (Triple<RandomProvider, Short, Short> p : take(LIMIT, ts)) { System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + its(p.a.range(p.b, p.c))); } } private static void demoNextFromRange_int_int() { initialize(); Iterable<Triple<RandomProvider, Integer, Integer>> ts = filter( t -> t.b <= t.c, P.triples(P.randomProvidersDefault(), P.integers(), P.integers()) ); for (Triple<RandomProvider, Integer, Integer> p : take(SMALL_LIMIT, ts)) { System.out.println("nextFromRange(" + p.a + ", " + p.b + ", " + p.c + ") = " + p.a.nextFromRange(p.b, p.c)); } } private static void demoRange_int_int() { initialize(); Iterable<Triple<RandomProvider, Integer, Integer>> ts = P.triples( P.randomProvidersDefault(), P.integers(), P.integers() ); for (Triple<RandomProvider, Integer, Integer> p : take(LIMIT, ts)) { System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + its(p.a.range(p.b, p.c))); } } private static void demoNextFromRange_long_long() { initialize(); Iterable<Triple<RandomProvider, Long, Long>> ts = filter( t -> t.b <= t.c, P.triples(P.randomProvidersDefault(), P.longs(), P.longs()) ); for (Triple<RandomProvider, Long, Long> p : take(SMALL_LIMIT, ts)) { System.out.println("nextFromRange(" + p.a + ", " + p.b + ", " + p.c + ") = " + p.a.nextFromRange(p.b, p.c)); } } private static void demoRange_long_long() { initialize(); Iterable<Triple<RandomProvider, Long, Long>> ts = P.triples(P.randomProvidersDefault(), P.longs(), P.longs()); for (Triple<RandomProvider, Long, Long> p : take(LIMIT, ts)) { System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + its(p.a.range(p.b, p.c))); } } private static void demoNextFromRange_BigInteger_BigInteger() { initialize(); Iterable<Triple<RandomProvider, BigInteger, BigInteger>> ts = filter( t -> Ordering.le(t.b, t.c), P.triples(P.randomProvidersDefault(), P.bigIntegers(), P.bigIntegers()) ); for (Triple<RandomProvider, BigInteger, BigInteger> p : take(SMALL_LIMIT, ts)) { System.out.println("nextFromRange(" + p.a + ", " + p.b + ", " + p.c + ") = " + p.a.nextFromRange(p.b, p.c)); } } private static void demoRange_BigInteger_BigInteger() { initialize(); Iterable<Triple<RandomProvider, BigInteger, BigInteger>> ts = P.triples( P.randomProvidersDefault(), P.bigIntegers(), P.bigIntegers() ); for (Triple<RandomProvider, BigInteger, BigInteger> p : take(LIMIT, ts)) { System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + its(p.a.range(p.b, p.c))); } } private static void demoNextFromRange_char_char() { initialize(); Iterable<Triple<RandomProvider, Character, Character>> ts = filter( t -> t.b <= t.c, P.triples(P.randomProvidersDefault(), P.characters(), P.characters()) ); for (Triple<RandomProvider, Character, Character> p : take(SMALL_LIMIT, ts)) { System.out.println("nextFromRange(" + p.a + ", " + nicePrint(p.b) + ", " + nicePrint(p.c) + ") = " + nicePrint(p.a.nextFromRange(p.b, p.c))); } } private static void demoRange_char_char() { initialize(); Iterable<Triple<RandomProvider, Character, Character>> ts = P.triples( P.randomProvidersDefault(), P.characters(), P.characters() ); for (Triple<RandomProvider, Character, Character> p : take(SMALL_LIMIT, ts)) { System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + cits(p.a.range(p.b, p.c))); } } private static void demoNextPositiveIntGeometric() { initialize(); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("nextPositiveIntGeometric(" + rp + ") = " + rp.nextPositiveIntGeometric()); } } private static void demoPositiveIntegersGeometric() { initialize(); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("positiveIntegersGeometric(" + rp + ") = " + its(rp.positiveIntegersGeometric())); } } private static void demoNextNegativeIntGeometric() { initialize(); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("nextNegativeIntGeometric(" + rp + ") = " + rp.nextNegativeIntGeometric()); } } private static void demoNegativeIntegersGeometric() { initialize(); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("negativeIntegersGeometric(" + rp + ") = " + its(rp.negativeIntegersGeometric())); } } private static void demoNextNaturalIntGeometric() { initialize(); Iterable<RandomProvider> rps = filter( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("nextNaturalIntGeometric(" + rp + ") = " + rp.nextNaturalIntGeometric()); } } private static void demoNaturalIntegersGeometric() { initialize(); Iterable<RandomProvider> rps = filter( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("naturalIntegersGeometric(" + rp + ") = " + its(rp.naturalIntegersGeometric())); } } private static void demoNextNonzeroIntGeometric() { initialize(); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("nextNonzeroIntGeometric(" + rp + ") = " + rp.nextNonzeroIntGeometric()); } } private static void demoNonzeroIntegersGeometric() { initialize(); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("nonzeroIntegersGeometric(" + rp + ") = " + its(rp.nonzeroIntegersGeometric())); } } private static void demoNextIntGeometric() { initialize(); Iterable<RandomProvider> rps = filter( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("nextIntGeometric(" + rp + ") = " + rp.nextIntGeometric()); } } private static void demoIntegersGeometric() { initialize(); Iterable<RandomProvider> rps = filter( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("integersGeometric(" + rp + ") = " + its(rp.integersGeometric())); } } private static void demoNextIntGeometricFromRangeUp() { initialize(); Iterable<Pair<RandomProvider, Integer>> ps = filter( p -> p.a.getScale() > p.b && (p.b > 1 || p.a.getScale() >= Integer.MAX_VALUE + p.b), P.pairs(P.randomProvidersDefaultSecondaryScale(), P.integersGeometric()) ); for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, ps)) { System.out.println("nextIntGeometricFromRangeUp(" + p.a + ", " + p.b + ") = " + p.a.nextIntGeometricFromRangeUp(p.b)); } } private static void demoRangeUpGeometric() { initialize(); Iterable<Pair<RandomProvider, Integer>> ps = filter( p -> p.a.getScale() > p.b && (p.b > 1 || p.a.getScale() >= Integer.MAX_VALUE + p.b), P.pairs(P.randomProvidersDefaultSecondaryScale(), P.integersGeometric()) ); for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, ps)) { System.out.println("rangeUpGeometric(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUpGeometric(p.b))); } } private static void demoNextIntGeometricFromRangeDown() { initialize(); Iterable<Pair<RandomProvider, Integer>> ps = filter( p -> p.a.getScale() < p.b && (p.b <= -1 || p.a.getScale() > p.b - Integer.MAX_VALUE), P.pairs(P.randomProvidersDefaultSecondaryScale(), P.integersGeometric()) ); for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, ps)) { System.out.println("nextIntGeometricFromRangeDown(" + p.a + ", " + p.b + ") = " + p.a.nextIntGeometricFromRangeDown(p.b)); } } private static void demoRangeDownGeometric() { initialize(); Iterable<Pair<RandomProvider, Integer>> ps = filter( p -> p.a.getScale() < p.b && (p.b <= -1 || p.a.getScale() > p.b - Integer.MAX_VALUE), P.pairs(P.randomProvidersDefaultSecondaryScale(), P.integersGeometric()) ); for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, ps)) { System.out.println("rangeDownGeometric(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDownGeometric(p.b))); } } private static void demoNextPositiveBigInteger() { initialize(); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("nextPositiveBigInteger(" + rp + ") = " + rp.nextPositiveBigInteger()); } } private static void demoPositiveBigIntegers() { initialize(); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("positiveBigIntegers(" + rp + ") = " + its(rp.positiveBigIntegers())); } } private static void demoNextNegativeBigInteger() { initialize(); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("nextNegativeBigInteger(" + rp + ") = " + rp.nextNegativeBigInteger()); } } private static void demoNegativeBigIntegers() { initialize(); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("negativeBigIntegers(" + rp + ") = " + its(rp.negativeBigIntegers())); } } private static void demoNextNaturalBigInteger() { initialize(); Iterable<RandomProvider> rps = filter( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("nextNaturalBigInteger(" + rp + ") = " + rp.nextNaturalBigInteger()); } } private static void demoNaturalBigIntegers() { initialize(); Iterable<RandomProvider> rps = filter( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("naturalBigIntegers(" + rp + ") = " + its(rp.naturalBigIntegers())); } } private static void demoNextNonzeroBigInteger() { initialize(); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("nextNonzeroBigInteger(" + rp + ") = " + rp.nextNonzeroBigInteger()); } } private static void demoNonzeroBigIntegers() { initialize(); Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale()); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("nonzeroBigIntegers(" + rp + ") = " + its(rp.nonzeroBigIntegers())); } } private static void demoNextBigInteger() { initialize(); Iterable<RandomProvider> rps = filter( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("nextBigInteger(" + rp + ") = " + rp.nextBigInteger()); } } private static void demoBigIntegers() { initialize(); Iterable<RandomProvider> rps = filter( x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE, P.randomProvidersDefaultSecondaryScale() ); for (RandomProvider rp : take(SMALL_LIMIT, rps)) { System.out.println("bigIntegers(" + rp + ") = " + its(rp.bigIntegers())); } } private static void demoNextFromRangeUp_BigInteger() { initialize(); Iterable<Pair<RandomProvider, BigInteger>> ps = filter( p -> { int minBitLength = p.b.signum() == -1 ? 0 : p.b.bitLength(); return p.a.getScale() > minBitLength && (minBitLength == 0 || p.a.getScale() != Integer.MAX_VALUE); }, P.pairs(P.randomProvidersDefaultSecondaryScale(), P.bigIntegers()) ); for (Pair<RandomProvider, BigInteger> p : take(SMALL_LIMIT, ps)) { System.out.println("nextFromRangeUp(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeUp(p.b)); } } private static void demoRangeUp_BigInteger() { initialize(); Iterable<Pair<RandomProvider, BigInteger>> ps = filter( p -> { int minBitLength = p.b.signum() == -1 ? 0 : p.b.bitLength(); return p.a.getScale() > minBitLength && (minBitLength == 0 || p.a.getScale() != Integer.MAX_VALUE); }, P.pairs(P.randomProvidersDefaultSecondaryScale(), P.bigIntegers()) ); for (Pair<RandomProvider, BigInteger> p : take(SMALL_LIMIT, ps)) { System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b))); } } private static void demoNextFromRangeDown_BigInteger() { initialize(); Iterable<Pair<RandomProvider, BigInteger>> ps = filter( p -> { int minBitLength = p.b.signum() == 1 ? 0 : p.b.negate().bitLength(); return p.a.getScale() > minBitLength && (minBitLength == 0 || p.a.getScale() != Integer.MAX_VALUE); }, P.pairs(P.randomProvidersDefaultSecondaryScale(), P.bigIntegers()) ); for (Pair<RandomProvider, BigInteger> p : take(SMALL_LIMIT, ps)) { System.out.println("nextFromRangeDown(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeDown(p.b)); } } private static void demoRangeDown_BigInteger() { initialize(); Iterable<Pair<RandomProvider, BigInteger>> ps = filter( p -> { int minBitLength = p.b.signum() == 1 ? 0 : p.b.negate().bitLength(); return p.a.getScale() > minBitLength && (minBitLength == 0 || p.a.getScale() != Integer.MAX_VALUE); }, P.pairs(P.randomProvidersDefaultSecondaryScale(), P.bigIntegers()) ); for (Pair<RandomProvider, BigInteger> p : take(SMALL_LIMIT, ps)) { System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b))); } } private static void demoEquals_RandomProvider() { initialize(); for (Pair<RandomProvider, RandomProvider> p : take(LIMIT, P.pairs(P.randomProviders()))) { System.out.println(p.a + (p.a.equals(p.b) ? " = " : " ≠ ") + p.b); } } private static void demoEquals_null() { initialize(); for (RandomProvider r : take(LIMIT, P.randomProviders())) { //noinspection ObjectEqualsNull System.out.println(r + (r.equals(null) ? " = " : " ≠ ") + null); } } private static void demoHashCode() { initialize(); for (RandomProvider r : take(LIMIT, P.randomProviders())) { System.out.println("hashCode(" + r + ") = " + r.hashCode()); } } private static void demoToString() { initialize(); for (RandomProvider rp : take(LIMIT, P.randomProviders())) { System.out.println(rp); } } }
package net.imagej.updater.calvin; import java.util.List; import net.imagej.updater.AbstractUploader; import net.imagej.updater.Uploadable; import net.imagej.updater.Uploader; import org.scijava.plugin.Plugin; /** * Dummy uploader. * * The only purpose this uploader has is to verify that ImageJ's updater * supports auto-installing uploaders given their protocol. * * @author Johannes Schindelin */ @Plugin(type = Uploader.class, name = "Hobbes") public class HobbesUploader extends AbstractUploader { @Override public String getProtocol() { return "hobbes"; } @Override public void upload(List<Uploadable> files, List<String> locks) { throw new UnsupportedOperationException(); } }
package com.akjava.gwt.modelweight.client; import java.io.IOException; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import com.akjava.gwt.html5.client.download.HTML5Download; import com.akjava.gwt.html5.client.file.File; import com.akjava.gwt.html5.client.file.FileUploadForm; import com.akjava.gwt.html5.client.file.FileUtils; import com.akjava.gwt.html5.client.file.FileUtils.DataURLListener; import com.akjava.gwt.html5.client.file.ui.DropVerticalPanelBase; import com.akjava.gwt.lib.client.GWTHTMLUtils; import com.akjava.gwt.lib.client.JavaScriptUtils; import com.akjava.gwt.lib.client.LogUtils; import com.akjava.gwt.lib.client.StorageControler; import com.akjava.gwt.lib.client.experimental.ExecuteButton; import com.akjava.gwt.modelweight.client.animation.QuickBoneAnimationWidget; import com.akjava.gwt.modelweight.client.bonemerge.BoneMergeToolPanel; import com.akjava.gwt.modelweight.client.morphmerge.MorphMergeToolPanel; import com.akjava.gwt.three.client.examples.js.THREEExp; import com.akjava.gwt.three.client.examples.js.controls.OrbitControls; import com.akjava.gwt.three.client.gwt.GWTParamUtils; import com.akjava.gwt.three.client.gwt.JSParameter; import com.akjava.gwt.three.client.gwt.boneanimation.AnimationBone; import com.akjava.gwt.three.client.gwt.ui.LabeledInputRangeWidget2; import com.akjava.gwt.three.client.java.SkinningVertexCalculator; import com.akjava.gwt.three.client.java.ThreeLog; import com.akjava.gwt.three.client.java.bone.BoneNameUtils; import com.akjava.gwt.three.client.java.bone.CloseVertexAutoWeight; import com.akjava.gwt.three.client.java.bone.SimpleAutoWeight; import com.akjava.gwt.three.client.java.bone.WeightResult; import com.akjava.gwt.three.client.java.ui.SimpleTabDemoEntryPoint; import com.akjava.gwt.three.client.java.ui.experiments.Vector3Editor; import com.akjava.gwt.three.client.js.THREE; import com.akjava.gwt.three.client.js.animation.AnimationClip; import com.akjava.gwt.three.client.js.animation.AnimationMixer; import com.akjava.gwt.three.client.js.animation.AnimationMixerAction; import com.akjava.gwt.three.client.js.core.Face3; import com.akjava.gwt.three.client.js.core.Geometry; import com.akjava.gwt.three.client.js.core.Object3D; import com.akjava.gwt.three.client.js.extras.geometries.SphereGeometry; import com.akjava.gwt.three.client.js.extras.helpers.VertexNormalsHelper; import com.akjava.gwt.three.client.js.extras.helpers.WireframeHelper; import com.akjava.gwt.three.client.js.lights.Light; import com.akjava.gwt.three.client.js.loaders.XHRLoader.XHRLoadHandler; import com.akjava.gwt.three.client.js.materials.Material; import com.akjava.gwt.three.client.js.materials.MeshPhongMaterial; import com.akjava.gwt.three.client.js.math.Vector2; import com.akjava.gwt.three.client.js.math.Vector3; import com.akjava.gwt.three.client.js.math.Vector4; import com.akjava.gwt.three.client.js.objects.Bone; import com.akjava.gwt.three.client.js.objects.Group; import com.akjava.gwt.three.client.js.objects.Mesh; import com.akjava.gwt.three.client.js.objects.SkinnedMesh; import com.akjava.gwt.three.client.js.renderers.WebGLRenderer; import com.akjava.gwt.three.client.js.textures.Texture; import com.akjava.lib.common.utils.FileNames; import com.google.common.base.Stopwatch; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.dom.client.ImageElement; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.DoubleClickEvent; import com.google.gwt.event.dom.client.MouseMoveEvent; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONParser; import com.google.gwt.json.client.JSONValue; import com.google.gwt.text.shared.Renderer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.DoubleBox; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.TabPanel; import com.google.gwt.user.client.ui.ValueListBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class GWTModelWeight extends SimpleTabDemoEntryPoint{ public static final String version="6.01(for r74)";//for three.js r74 private StorageControler storageControler; private Mesh mouseClickCatcher; private OrbitControls trackballControls; //private TrackballControls trackballControls; private boolean gpuSkinning; public boolean isGpuSkinning() { return gpuSkinning; } @Override public String getHtml(){ String html=""; return html; } //re-creating character private boolean disableMixer; public void setGpuSkinning(boolean gpuSkinning) { disableMixer=true; //i have no idea somehow problem //trackballControls.reset(); //trackballControls.setTarget(THREE.Vector3(0,cameraY,0)); double time=currentAnimationAction!=null?currentAnimationAction.getTime():0; double timeScale=mixer!=null?mixer.getTimeScale():1; this.gpuSkinning = gpuSkinning; createBaseCharacterModelSkin();//re-create mixer here if(hasEditingGeometry()){ createEditingClothSkin(); } playAnimation(lastAnimationClip);//pauseButton label update here //sync old value to recreated-mixer and action if(currentAnimationAction!=null){ currentAnimationAction.setTime(time); } mixer.setTimeScale(timeScale); updatePauseButtonLabel(); disableMixer=false; } private void updateTimeLabel(){ if(currentAnimationAction==null){ return; } double t=currentAnimationAction.getTime(); if(t==0){ timeLabel.setText("time:0"); return; } int m=(int) (t/60); String head="time:"; if(m>0){ head=m+"m "; } double r=JavaScriptUtils.fixNumber(4,t/60); timeLabel.setText(head+r); } @Override protected void beforeUpdate(WebGLRenderer renderer) { if(mixer!=null && !disableMixer){ mixer.update(1.0/60); updateTimeLabel(); } if(trackballControls!=null){ trackballControls.update(); //LogUtils.log(camera.getUuid()); } if(baseCharacterModelSkinnedMesh!=null){ baseCharacterModelSkinnedMesh.getPosition().set(baseCharacterModelPositionEditor.getX(), baseCharacterModelPositionEditor.getY(), baseCharacterModelPositionEditor.getZ()); if(!gpuSkinning){ skinningbyHand(baseCharacterModelSkinnedMesh,baseCharacterModelGeometry); baseCharacterModelSkinnedMesh.getGeometry().computeBoundingSphere(); } } if(baseCharacterModelWireframeMesh!=null){ baseCharacterModelWireframeMesh.getPosition().set(baseCharacterWireframePositionEditor.getX(), baseCharacterWireframePositionEditor.getY(), baseCharacterWireframePositionEditor.getZ()); } if(editingClothWireframeNormalsHelper!=null){ //editingClothWireframeNormalsHelper.update(); } if(editingClothModelSkinnedMesh!=null){ if(!gpuSkinning){ skinningbyHand(editingClothModelSkinnedMesh,editingGeometry); editingClothModelSkinnedMesh.getGeometry().computeBoundingSphere(); if(editingClothSkinVertexSelector.getSelectecVertex()!=-1){ editingClothSkinVertexSelector.update(); } } } if(editingClothSkinNormalsHelper!=null){ editingClothSkinNormalsHelper.update(); if(!gpuSkinning){ editingClothSkinNormalsHelper.getGeometry().computeBoundingSphere();//still gone easily } } } private int selectedTabIndex; final int WEIGHT_TAB_INDEX=3; final int BONE_TAB_INDEX=1; public void updateSelectedTabIndex(){ if(selectedTabIndex!=BONE_TAB_INDEX){ if(editingClothWireframeVertexSelector!=null){ editingClothWireframeVertexSelector.setVisible(true); } if(editingClothWireframeNormalsHelper!=null){ editingClothWireframeNormalsHelper.setVisible(true); } if(editingClothSkinNormalsHelper!=null){ if(!gpuSkinning){ editingClothSkinNormalsHelper.setVisible(true); } } }else{ if(editingClothWireframeVertexSelector!=null){ editingClothWireframeVertexSelector.setVisible(false); } if(editingClothWireframeNormalsHelper!=null){ editingClothWireframeNormalsHelper.setVisible(false); } if(editingClothSkinNormalsHelper!=null){ editingClothSkinNormalsHelper.setVisible(false); } } } @Override protected void initializeOthers(WebGLRenderer renderer) { LogUtils.log("Model Weight:"+version); //Window.open("text/plain:test.txt:"+url, "test", null); storageControler = new StorageControler(); canvas.setClearColor(0xaaaaaa);//canvas has margin? scene.add(THREE.AmbientLight(0x444444)); Light pointLight = THREE.DirectionalLight(0xaaaaaa,1); pointLight.setPosition(0, 10, 300); scene.add(pointLight); Light pointLight2 = THREE.DirectionalLight(0xaaaaaa,1);//for fix back side dark problem pointLight2.setPosition(0, 10, -300); scene.add(pointLight2); mouseClickCatcher=THREE.Mesh(THREE.PlaneGeometry(100, 100, 10, 10), THREE.MeshBasicMaterial(GWTParamUtils.MeshBasicMaterial().color(0xffff00).wireframe(true) .visible(false)));//hide and catch mouse mouseClickCatcher.setVisible(true); //now Ray only check visible object and to hide use material's visible scene.add(mouseClickCatcher); nearCamera=0.001; updateCamera(scene,screenWidth , screenHeight); cameraZ=4; autoUpdateCameraPosition=false; //showControl(); mouseSelector = new Object3DMouseSelecter(renderer, camera); //warning not loaded basicCharacterModelDisplacementTexture=GWTHTMLUtils.parameterImage("displacement"); basicCharacterModelMapTexture=GWTHTMLUtils.parameterImage("texture"); } ImageElement basicCharacterModelDisplacementTexture; ImageElement basicCharacterModelMapTexture; private JSONObject baseCharacterModelJson; private Geometry baseCharacterModelGeometry; private SkinnedMesh baseCharacterModelSkinnedMesh; private Vector3Editor baseCharacterModelPositionEditor; private Mesh baseCharacterModelWireframeMesh; private BoneVertexColorTools baseCharacterVertexColorTools; private BoneVertexColorTools editingClothVertexColorTools; private ValueListBox<AnimationBone> boneListBox; private List<AnimationBone> baseCharacterModelBones; private Object3DMouseSelecter mouseSelector; private Group boneMeshGroup; private BoneMeshMouseSelector boneMouseSelector; private Vector3Editor baseCharacterWireframePositionEditor; private Mesh editingClothSkinWireframeHelperMesh; private AbstractImageFileUploadPanel baseCharacterModelDisplacementUpload; private void initialLoadBaseCharacterModel(final String modelUrl) { THREE.XHRLoader().load(modelUrl, new XHRLoadHandler() { @Override public void onLoad(String text) { baseCharacterModelUpload.uploadText(FileNames.getFileNameAsSlashFileSeparator(modelUrl), text); } }); } private void createOrbitControler(){ baseCharacterModelGeometry.computeBoundingBox(); cameraY=baseCharacterModelGeometry.getBoundingBox().getMax().getY()/2; //this position used camera.getPosition().set(cameraX, cameraY, cameraZ); if(trackballControls!=null){ trackballControls.dispose(); } //trackball initialize here //i feeel orbit is much stable on y-axis trackballControls=THREEExp.OrbitControls(camera,canvas.getElement()); //trackballControls.setNoZoom(true); trackballControls.getMouseButtons().set("ORBIT", THREE.MOUSE.MIDDLE); trackballControls.getMouseButtons().set("ZOOM", 3);//3 is not exist,for ignore left button // trackballControls=THREEExp.TrackballControls(camera,canvas.getElement()); //trackballControls.setRotateSpeed(10); trackballControls.setTarget(THREE.Vector3(0,cameraY,0)); } protected void createBaseCharacterBones() { if(boneMeshGroup!=null){ scene.remove(boneMeshGroup); } BoneMeshTools bmt=new BoneMeshTools(); boneMeshGroup = bmt.createBoneMeshs(baseCharacterModelGeometry.getBones()); scene.add(boneMeshGroup); boneMouseSelector = new BoneMeshMouseSelector(boneMeshGroup, baseCharacterModelGeometry.getBones(), renderer, camera); } protected void updateBoneListBox() { baseCharacterModelBones = JavaScriptUtils.toList(baseCharacterModelGeometry.getBones()); boneListBox.setValue(baseCharacterModelBones.get(0)); boneListBox.setAcceptableValues(baseCharacterModelBones); updateBoneInfluenceSpheres(baseCharacterModelBones.get(0));//update position } protected void createBaseCharacterWireframe(){ if(baseCharacterModelWireframeMesh!=null){ scene.remove(baseCharacterModelWireframeMesh); } Geometry bodyGeometry=baseCharacterModelGeometry.clone(); bodyGeometry.setSkinIndices(baseCharacterModelGeometry.getSkinIndices()); bodyGeometry.setSkinWeights(baseCharacterModelGeometry.getSkinWeights()); bodyGeometry.setBones(baseCharacterModelGeometry.getBones()); baseCharacterModelWireframeMesh = THREE.Mesh(bodyGeometry, THREE.MeshPhongMaterial(GWTParamUtils.MeshBasicMaterial() .wireframe(true) .color(0xffffff) .vertexColors(THREE.VertexColors) ) ); //watch out once set color can't replace color.use setHex() scene.add(baseCharacterModelWireframeMesh); baseCharacterVertexColorTools = new BoneVertexColorTools(bodyGeometry); //make a class handle vertex color } protected void createEditingClothWireframe(){ if(editingGeometryWireMesh!=null){ scene.remove(editingGeometryWireMesh); } editingGeometryWireMesh = THREE.Mesh(editingGeometry, THREE.MeshPhongMaterial(GWTParamUtils.MeshBasicMaterial() //.wireframe(true) .shading(THREE.FlatShading) .color(0xffffff) .vertexColors(THREE.VertexColors) .transparent(true) .opacity(0.7) ) ); scene.add(editingGeometryWireMesh); editingClothVertexColorTools = new BoneVertexColorTools(editingGeometry); if(editingGeometryWireMeshHelper!=null){ scene.remove(editingGeometryWireMeshHelper); } editingGeometryWireMeshHelper = THREE.WireframeHelper(editingGeometryWireMesh,0x888888); scene.add(editingGeometryWireMeshHelper); } protected void createBaseCharacterModelSkin() { Texture texture=baseCharacterModelTextureUpload.createTextureFromUpload(basicCharacterModelMapTexture); Texture displacement=baseCharacterModelDisplacementUpload.createTextureFromUpload(basicCharacterModelDisplacementTexture); MeshPhongMaterial material=THREE.MeshPhongMaterial(GWTParamUtils.MeshPhongMaterial() .skinning(gpuSkinning) .map(texture) .transparent(true) .alphaTest(0.1) .side(textureSide) .displacementMap(displacement) .displacementScale(GWTHTMLUtils.parameterDouble("displacementScale", 0.1)) ); if(baseCharacterModelSkinnedMesh!=null){ scene.remove(baseCharacterModelSkinnedMesh); } Geometry geometry=baseCharacterModelGeometry.clone(); baseCharacterModelGeometry.gwtSoftCopyToWeightsAndIndicesAndBone(geometry); baseCharacterModelSkinnedMesh = THREE.SkinnedMesh(geometry, material); scene.add(baseCharacterModelSkinnedMesh); mixer=THREE.AnimationMixer(baseCharacterModelSkinnedMesh); } public boolean hasEditingGeometry(){ return editingGeometry!=null; } protected MeshPhongMaterial createEditingClothSkinMaterial(){ MeshPhongMaterial material=THREE.MeshPhongMaterial(GWTParamUtils.MeshPhongMaterial() .skinning(gpuSkinning) .color(editingClothModelSkinnedMeshColor) .shading(THREE.FlatShading) .transparent(true) .alphaTest(0.1) .side(textureSide) .displacementScale(GWTHTMLUtils.parameterDouble("displacementScale", 0.1)) ); if(editingClothModelTextureUpload.isUploaded()){ Texture texture=THREE.Texture(editingClothModelTextureUpload.getLastUploadImage()); texture.setNeedsUpdate(true); material.setMap(texture); material.getColor().setHex(0xffffff); } material.setDisplacementMap(editingClothModelDisplacementUpload.createTextureFromUpload(null)); return material; } protected void createEditingClothSkin() { Material material=createEditingClothSkinMaterial(); if(editingClothModelSkinnedMesh!=null){ //not scene , baseCharacterModelSkinnedMesh.remove(editingClothModelSkinnedMesh); } //can't use editingGeometry,maybe Indices & weights registered somewhere with geometry.need new geometry to update indicis&weight Geometry geometry=editingGeometry.clone(); //lightCopy geometry.setSkinIndices(editingGeometry.getSkinIndices()); geometry.setSkinWeights(editingGeometry.getSkinWeights()); //warning possible no bones,maybe no need here? geometry.setBones(editingGeometry.getBones()); editingClothModelSkinnedMesh = THREE.SkinnedMesh(geometry, material); editingClothModelSkinnedMesh.setSkeleton(baseCharacterModelSkinnedMesh.getSkeleton());//share bone to work same mixer baseCharacterModelSkinnedMesh.add(editingClothModelSkinnedMesh);//share same position,rotation //create normal helper if(editingClothSkinNormalsHelper!=null){ scene.remove(editingClothSkinNormalsHelper); } double lineWidth=0.1; double size=0.01; editingClothSkinNormalsHelper = THREE.VertexNormalsHelper(editingClothModelSkinnedMesh, size, 0xffff00, lineWidth); scene.add(editingClothSkinNormalsHelper); //create wireframe helper wireframehelper not good at geometry update with shareing geometry if(editingClothSkinWireframeHelperMesh!=null){ baseCharacterModelSkinnedMesh.remove(editingClothSkinWireframeHelperMesh); } editingClothSkinWireframeHelperMesh = THREE.Mesh(geometry,THREE.MeshBasicMaterial(GWTParamUtils.MeshBasicMaterial().color(0x888888).shading(THREE.FlatShading).wireframe(true))); baseCharacterModelSkinnedMesh.add(editingClothSkinWireframeHelperMesh); //for animation-mesh if(editingClothSkinVertexSelector!=null){ editingClothSkinVertexSelector.dispose(); } editingClothSkinVertexSelector = new MeshVertexSelector(editingClothModelSkinnedMesh, renderer, camera, scene); if(editingClothWireframeVertexSelector!=null){ //on initialize no need to sync,but when skinning-data update,need to sync selection editingClothSkinVertexSelector.setSelectionVertex(editingClothWireframeVertexSelector.getSelectecVertex());//sync again } //gpu based if(gpuSkinning){ editingClothModelSkinnedMesh.getMaterial().gwtCastMeshPhongMaterial().setShading(THREE.SmoothShading); }else{ editingClothModelSkinnedMesh.getMaterial().gwtCastMeshPhongMaterial().setShading(THREE.FlatShading); } editingClothSkinNormalsHelper.setVisible(!gpuSkinning); editingClothSkinVertexSelector.setVisible(!gpuSkinning); editingClothSkinWireframeHelperMesh.setVisible(!gpuSkinning); } public void skinningbyHand(SkinnedMesh mesh,Geometry origonalGeometry){ mesh.getGeometry().setDynamic(true); for(int i=0;i<mesh.getGeometry().getVertices().length();i++){ Vector3 transformed=SkinningVertexCalculator.transformSkinningVertex(mesh,i,origonalGeometry.getVertices().get(i)); mesh.getGeometry().getVertices().get(i).copy(transformed); } //for lighting mesh.getGeometry().computeFaceNormals (); mesh.getGeometry().computeVertexNormals (); mesh.getGeometry().setVerticesNeedUpdate(true); mesh.getGeometry().setNormalsNeedUpdate(true); } @Override public void onDoubleClick(DoubleClickEvent event) { // TODO Auto-generated method stub } @Override public void onMouseClick(ClickEvent event) { if(event.getNativeButton()!=NativeEvent.BUTTON_LEFT){ return; } //LogUtils.log("mouse-click"); if(selectedTabIndex!=BONE_TAB_INDEX){ if(editingClothWireframeVertexSelector!=null){ int vertex=editingClothWireframeVertexSelector.pickVertex(event); if(vertex==-1){ vertex=editingClothSkinVertexSelector.pickVertex(event); editingClothWireframeVertexSelector.setSelectionVertex(vertex); }else{ editingClothSkinVertexSelector.setSelectionVertex(vertex);//just syn now } //LogUtils.log("picked "+vertex); if(vertex!=-1){ vertexBoneDataEditor.setValue(VertexBoneData.createFromdMesh(editingGeometry, vertex)); }else{ vertexBoneDataEditor.setValue(null); } } return; } //when other tab selected if(boneMouseSelector!=null){ int index=boneMouseSelector.pickBone(event); //boneListBox would update wireframe weights color if(index==-1){ //no need unselect, //boneListBox.setValue(null,true); }else{ boneListBox.setValue(baseCharacterModelBones.get(index),true); } } } @Override public void onMouseMove(MouseMoveEvent event) { } public void onEditingClothJsonLoaded(String text){ JSONObject jsonObject=parseJSONGeometry(text); editingGeometryJsonObject=jsonObject; editingGeometryOrigin=THREE.JSONLoader().parse(jsonObject.getJavaScriptObject()).getGeometry(); //TODO bone check //TODO make gwtCloneWithBones() editingGeometry=THREE.JSONLoader().parse(jsonObject.getJavaScriptObject()).getGeometry(); setInfluencePerVertexFromJSON(editingGeometry,jsonObject); boolean needAutoSkinning=editingGeometry.getSkinIndices()==null || editingGeometry.getSkinIndices().length()==0; //todo more check if(editingGeometry.getBones()==null || editingGeometry.getBones().length()==0){ needAutoSkinning=true; }else{ if(editingGeometry.getBones().length()!=baseCharacterModelGeometry.getBones().length()){ LogUtils.log("editingGeometry has bone,but size different:base-bone-size="+baseCharacterModelGeometry.getBones().length()+",editing-size="+editingGeometry.getBones().length()); needAutoSkinning=true; } } if(needAutoSkinning){ //Window.alert("has no skin indices"); LogUtils.log("No skin indices.it would auto skinning."); Stopwatch watch=LogUtils.stopwatch(); editingGeometry.computeBoundingBox(); //double maxDistance=editingGeometry.getBoundingBox().getMax().distanceTo(editingGeometry.getBoundingBox().getMin()); int influence=3; WeightResult result= new SimpleAutoWeight(influence).autoWeight(editingGeometry, baseCharacterModelGeometry.getBones()); result.insertToGeometry(editingGeometry); //new CloseVertexAutoWeight().autoWeight(editingGeometry, baseCharacterModelGeometry,maxDistance).insertToGeometry(editingGeometry); //LogUtils.millisecond("auto-weight vertex="+editingGeometry.getVertices().length(), watch); //editingGeometry.gwtSetInfluencesPerVertex(baseCharacterModelGeometry.gwtGetInfluencesPerVertex()); editingGeometry.gwtSetInfluencesPerVertex(influence); editingGeometryOrigin.gwtSetInfluencesPerVertex(baseCharacterModelGeometry.gwtGetInfluencesPerVertex()); editingGeometry.gwtHardCopyToWeightsAndIndices(editingGeometryOrigin); } createEditingClothSkin(); createEditingClothWireframe(); createVertexSelections(); } public void onBaseCharacterModelJsonLoaded(String text){ JSONObject object=parseJSONGeometry(text); if(object==null){ Window.alert("invalid model"); return; } Geometry geometry=THREE.JSONLoader().parse(object.getJavaScriptObject()).getGeometry(); if(!geometry.gwtHasBone() || !geometry.gwtHasSkinIndicesAndWeights()){ Window.alert("Model has no bone,base model need bone.\nexport with Bones and Skinning checked"); return; } //TODO check weights //now safe baseCharacterModelJson=object; baseCharacterModelGeometry=geometry; setInfluencePerVertexFromJSON(baseCharacterModelGeometry,object); createBaseCharacterModelSkin(); createBaseCharacterWireframe(); createBaseCharacterBones(); updateBoneListBox(); vertexBoneDataEditor.setBone(baseCharacterModelGeometry.getBones()); createOrbitControler();//based skinned mesh height //editing has a possible based on baseSkinnedMesh,safe to reload if(editingMeshUpload.isUploaded()){ editingMeshUpload.reload(); } quickBoneAnimationWidget.setSkelton(baseCharacterModelSkinnedMesh.getSkeleton()); } private Panel createBasicControl(){ VerticalPanel basicPanel=new VerticalPanel(); basicPanel.setSpacing(2); basicPanel.add(new HTML("<h4>Base Skinnd Character Model</h4>")); baseCharacterModelUpload = new AbstractTextFileUploadPanel("Base Json",false) { @Override protected void onTextFileUpload(String text) { onBaseCharacterModelJsonLoaded(text); } }; baseCharacterModelUpload.getUploadForm().setAccept(FileUploadForm.ACCEPT_JSON); basicPanel.add(baseCharacterModelUpload); baseCharacterModelTextureUpload=new AbstractImageFileUploadPanel("Base Texture",true){ @Override protected void onImageFileUpload(ImageElement imageElement) { onBaseCharacterModelTextureLoaded(imageElement); } }; baseCharacterModelDisplacementUpload=new AbstractImageFileUploadPanel("Base Displacement",true){ @Override protected void onImageFileUpload(ImageElement imageElement) { onBaseCharacterModelDisplacementLoaded(imageElement); } }; baseCharacterModelTextureUpload.getUploadForm().setAccept(FileUploadForm.ACCEPT_IMAGE); basicPanel.add(baseCharacterModelTextureUpload); baseCharacterModelPositionEditor = new Vector3Editor("Skin Position",-2, 2, 0.001, 0); basicPanel.add(baseCharacterModelPositionEditor); baseCharacterModelPositionEditor.setX(-1.5,true); baseCharacterWireframePositionEditor = new Vector3Editor("Wire Position",-2, 2, 0.001, 0); basicPanel.add(baseCharacterWireframePositionEditor); basicPanel.add(new HTML("<h4>Camera</h4>")); Button resetCamera=new Button("Reset",new ClickHandler() { @Override public void onClick(ClickEvent event) { trackballControls.reset(); trackballControls.setTarget(THREE.Vector3(0,cameraY,0)); } }); basicPanel.add(resetCamera); basicPanel.add(new HTML("<h4>Texture</h4>")); CheckBox doubleSideCheck=new CheckBox("Double Side"); basicPanel.add(doubleSideCheck); doubleSideCheck.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { textureSide=event.getValue()?THREE.DoubleSide:THREE.FrontSide; editingClothModelSkinnedMesh.getMaterial().gwtCastMeshPhongMaterial().setSide(textureSide); baseCharacterModelSkinnedMesh.getMaterial().gwtCastMeshPhongMaterial().setSide(textureSide); } }); return basicPanel; } private int textureSide=THREE.FrontSide; private Panel createBonePanel(){ VerticalPanel bonePanel=new VerticalPanel(); boneListBox = new ValueListBox<AnimationBone>(new Renderer<AnimationBone>() { @Override public String render(AnimationBone object) { if(object==null){ return ""; } return object.getName(); } @Override public void render(AnimationBone object, Appendable appendable) throws IOException { // TODO Auto-generated method stub } }); bonePanel.add(boneListBox); boneListBox.addValueChangeHandler(new ValueChangeHandler<AnimationBone>() { @Override public void onValueChange(ValueChangeEvent<AnimationBone> event) { onBoneSelectionChanged(event.getValue()); } }); Button unselectBone=new Button("unselect",new ClickHandler() { @Override public void onClick(ClickEvent event) { boneListBox.setValue(null,true); } }); bonePanel.add(unselectBone); CheckBox gpuSkinning=new CheckBox("GPU Skin Animation"); gpuSkinning.setTitle("Using GPU is first.but can't pick vertex"); bonePanel.add(gpuSkinning); gpuSkinning.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { setGpuSkinning(event.getValue()); } }); Button removeInfluenceButton=new Button("Remove selected bone influence",new ClickHandler() { @Override public void onClick(ClickEvent event) { boolean neddUpdate=false; AnimationBone bone=boneListBox.getValue(); if(bone!=null){ int boneIndex=boneMouseSelector.getBoneIndex(bone); JsArray<Vector4> indices=editingGeometry.getSkinIndices(); JsArray<Vector4> weights=editingGeometry.getSkinWeights(); for(int i=0;i<indices.length();i++){ boolean modified=false; for(int j=0;j<4;j++){ int index=indices.get(i).gwtGet(j); if(index==boneIndex){ weights.get(i).gwtSet(j, 0); modified=true; neddUpdate=true; } } if(modified){ autobalanceWeight(weights.get(i)); } } } if(neddUpdate){ createEditingClothSkin();//weight updated } onBoneSelectionChanged(bone); } }); bonePanel.add(removeInfluenceButton); Button weightAllButton=new Button("Set all selected bone influence ",new ClickHandler() { @Override public void onClick(ClickEvent event) { AnimationBone bone=boneListBox.getValue(); if(bone!=null){ int boneIndex=boneMouseSelector.getBoneIndex(bone); JsArray<Vector4> indices=editingGeometry.getSkinIndices(); JsArray<Vector4> weights=editingGeometry.getSkinWeights(); for(int i=0;i<indices.length();i++){ for(int j=0;j<4;j++){ if(j==0){ indices.get(i).gwtSet(j, boneIndex); weights.get(i).gwtSet(j, 1); }else{ indices.get(i).gwtSet(j, 0); weights.get(i).gwtSet(j, 0); } } } } createEditingClothSkin();//weight updated onBoneSelectionChanged(bone); } }); bonePanel.add(weightAllButton); Button autoWeightButton=new Button("Exec auto close vertex skinning",new ClickHandler() { @Override public void onClick(ClickEvent event) { int influence=baseCharacterModelGeometry.gwtGetInfluencesPerVertex(); WeightResult result= new CloseVertexAutoWeight().autoWeight(editingGeometry, baseCharacterModelGeometry); JsArray<Vector4> indices=editingGeometry.getSkinIndices(); JsArray<Vector4> weights=editingGeometry.getSkinWeights(); for(int i=0;i<indices.length();i++){ indices.get(i).copy(result.getSkinIndices().get(i)); weights.get(i).copy(result.getSkinWeights().get(i)); } editingGeometry.gwtSetInfluencesPerVertex(influence); createEditingClothSkin();//weight updated //redraw wireframe AnimationBone bone=boneListBox.getValue(); onBoneSelectionChanged(bone); } }); bonePanel.add(autoWeightButton); HorizontalPanel boneSkinningPanel=new HorizontalPanel(); boneSkinningPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); bonePanel.add(boneSkinningPanel); boneSkinningPanel.add(new Label("Influence")); final ListBox influenceBox=new ListBox(); influenceBox.addItem("1"); influenceBox.addItem("2"); influenceBox.addItem("3"); influenceBox.addItem("4"); influenceBox.setSelectedIndex(2);//for auto grouping boneSkinningPanel.add(influenceBox); Button autoBoneWeightButton=new Button("Exec auto close bone skinning",new ClickHandler() { @Override public void onClick(ClickEvent event) { int influence=influenceBox.getSelectedIndex()+1; WeightResult result= new SimpleAutoWeight(influence).autoWeight(editingGeometry, baseCharacterModelGeometry.getBones()); JsArray<Vector4> indices=editingGeometry.getSkinIndices(); JsArray<Vector4> weights=editingGeometry.getSkinWeights(); for(int i=0;i<indices.length();i++){ indices.get(i).copy(result.getSkinIndices().get(i)); weights.get(i).copy(result.getSkinWeights().get(i)); } editingGeometry.gwtSetInfluencesPerVertex(influence); createEditingClothSkin();//weight updated //redraw wireframe AnimationBone bone=boneListBox.getValue(); onBoneSelectionChanged(bone); } }); boneSkinningPanel.add(autoBoneWeightButton); Button resetWeightButton=new Button("Reset to default indices & weights",new ClickHandler() { @Override public void onClick(ClickEvent event) { JsArray<Vector4> indices=editingGeometry.getSkinIndices(); JsArray<Vector4> weights=editingGeometry.getSkinWeights(); for(int i=0;i<indices.length();i++){ indices.get(i).copy(editingGeometryOrigin.getSkinIndices().get(i)); weights.get(i).copy(editingGeometryOrigin.getSkinWeights().get(i)); } createEditingClothSkin();//weight updated //redraw wireframe AnimationBone bone=boneListBox.getValue(); onBoneSelectionChanged(bone); } }); bonePanel.add(resetWeightButton); //add influence bonePanel.add(createBoneInfluencePanel()); return bonePanel; } private double coreRadius=0.01; private double totalRadius=0.05; private Mesh boneInfluenceSphere; private DoubleBox totalRadiusBox; private void updateBoneInfluenceSpheres(){ boolean checked=enableBoneInfluenceCheck.getValue(); boolean selectedBone=boneListBox.getValue()!=null; boneInfluenceCoreSphere.setVisible(checked&&selectedBone); boneInfluenceSphere.setVisible(checked&&selectedBone); } private Widget createBoneInfluencePanel() { Panel panel=new VerticalPanel(); final VerticalPanel boneInfluencePanel=new VerticalPanel(); enableBoneInfluenceCheck = new CheckBox("enable add editor"); panel.add(enableBoneInfluenceCheck); enableBoneInfluenceCheck.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { boneInfluencePanel.setVisible(event.getValue()); updateBoneInfluenceSpheres(); } }); enableBoneInfluenceCheck.setValue(true); panel.add(boneInfluencePanel); HorizontalPanel h1=new HorizontalPanel(); boneInfluencePanel.add(h1); h1.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); h1.add(new Label("Core radius")); coreRadiusBox = new DoubleBox(); h1.add(coreRadiusBox); coreRadiusBox.setWidth("50px"); coreRadiusBox.addValueChangeHandler(new ValueChangeHandler<Double>() { @Override public void onValueChange(ValueChangeEvent<Double> event) { updateScale(boneInfluenceCoreSphere,coreRadiusBox.getValue()); } }); HorizontalPanel h2=new HorizontalPanel(); boneInfluencePanel.add(h2); h2.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); h2.add(new Label("Total radius")); totalRadiusBox = new DoubleBox(); h2.add(totalRadiusBox); totalRadiusBox.setWidth("50px"); totalRadiusBox.addValueChangeHandler(new ValueChangeHandler<Double>() { @Override public void onValueChange(ValueChangeEvent<Double> event) { updateScale(boneInfluenceSphere,totalRadiusBox.getValue()); } }); boneInfluenceSetFromOriginCheck = new CheckBox("set from origin"); boneInfluencePanel.add(boneInfluenceSetFromOriginCheck); Button execute=new Button("Add influence",new ClickHandler() { @Override public void onClick(ClickEvent event) { doBoneInfluence(); createEditingClothSkin(); if(boneListBox.getValue()!=null){//update bone selection; onBoneSelectionChanged(boneListBox.getValue()); } } }); boneInfluencePanel.add(execute); SphereGeometry coreSphereGeometry=THREE.SphereGeometry(1, 10); boneInfluenceCoreSphere = THREE.Mesh(coreSphereGeometry,THREE.MeshPhongMaterial(GWTParamUtils.MeshPhongMaterial().color(0xffffff).wireframe(true))); scene.add(boneInfluenceCoreSphere); SphereGeometry sphereGeometry=THREE.SphereGeometry(1, 10); boneInfluenceSphere = THREE.Mesh(sphereGeometry,THREE.MeshPhongMaterial(GWTParamUtils.MeshPhongMaterial().color(0x008800).wireframe(true))); scene.add(boneInfluenceSphere); coreRadiusBox.setValue(coreRadius,true); totalRadiusBox.setValue(totalRadius,true); return panel; } protected void doBoneInfluence() { if(boneListBox.getValue()==null){ LogUtils.log("need select bone"); return; } int boneIndex=baseCharacterModelBones.indexOf(boneListBox.getValue()); if(boneIndex==-1){ LogUtils.log("somehow selection bone can'f find"); return; } if(editingGeometry==null){ LogUtils.log("no editing geometry"); return; } Vector3 centerPosition=boneInfluenceCoreSphere.getPosition(); double effectArea=totalRadiusBox.getValue(); double coreArea=coreRadiusBox.getValue(); for(int i=0;i<editingGeometry.getVertices().length();i++){ double distance=centerPosition.distanceTo(editingGeometry.getVertices().get(i)); if(distance>effectArea){ continue;//skip } boolean useOrigin=boneInfluenceSetFromOriginCheck.getValue(); Vector4 indicis; if(useOrigin){ indicis=editingGeometryOrigin.getSkinIndices().get(i).clone(); }else{ indicis=editingGeometry.getSkinIndices().get(i); } Vector4 weights; if(useOrigin){ weights=editingGeometryOrigin.getSkinWeights().get(i).clone(); }else{ weights=editingGeometry.getSkinWeights().get(i); } if(distance<coreArea){//simplly set all indicis.setX(boneIndex); indicis.setY(0); indicis.setZ(0); indicis.setW(0); weights.setX(1); weights.setY(0); weights.setZ(0); weights.setW(0); LogUtils.log("inside core-area:index="+i); }else{ //calcurate new value double maxDistance=effectArea-coreArea; double newdistance=distance-coreArea; double ratio=1.0-(newdistance/maxDistance);//0-1.0 int minIndex=0; int minValue=weights.gwtGet(0); for(int j=1;j<4;j++){ if(weights.gwtGet(j)<minValue){ minIndex=j; minValue=weights.gwtGet(j); } } if(ratio>minValue){ indicis.gwtSet(minIndex, boneIndex); autoBalanceWeights(weights,minIndex,ratio); } } if(useOrigin){ editingGeometry.getSkinIndices().get(i).copy(indicis); editingGeometry.getSkinWeights().get(i).copy(weights); } } //for(int i=0;i<result.size();i++){ //Vector4 indices=editingGeometry.getSkinIndices().get(result.get(i)); //get selection and position /* * show add editor core - size double radius -size double min - value double from origin - checkbox force insert - checkbox TODO addButton radius core lerp origin min */ } protected void autoBalanceWeights(Vector4 weights,int target,double newvalue) { if(newvalue<0 || newvalue>1){ LogUtils.log("invalid newvalue(0-1.0):"+newvalue); } if(target<0 || target>3){ LogUtils.log("invalid target(0-3):"+target); } //ThreeLog.log("before:",weights); //ThreeLog.log("target="+target+",value="+newvalue); double remain=1.0-newvalue; double total=0; for(int i=0;i<4;i++){ if(i!=target){ total+=weights.gwtGet(i); } } List<Double> ratios=Lists.newArrayList(); for(int i=0;i<4;i++){ if(i==target){ ratios.add(0.0); }else{ if(total==0){ ratios.add(1.0/3); }else{ if(weights.gwtGet(i)==0){ ratios.add(0.0); }else{ ratios.add(weights.gwtGet(i)/total); } } } } for(int i=0;i<4;i++){ if(i!=target){ weights.gwtSet(i, remain*ratios.get(i)); }else{ weights.gwtSet(i, newvalue); } } //ThreeLog.log("after:",weights); } private void updateScale(Mesh boneCoreInfluenceSphere, double value) { boneCoreInfluenceSphere.getScale().setScalar(value); } @Override public void createControl(DropVerticalPanelBase parent) { tabPanel.addSelectionHandler(new SelectionHandler<Integer>() { @Override public void onSelection(SelectionEvent<Integer> event) { int selection=event.getSelectedItem(); if(selection==0){ stats.setVisible(true); showControl(); //bottomPanel.setVisible(true); popupPanel.setVisible(true); resized(screenWidth,screenHeight);//for some blackout; }else{ stats.setVisible(false); //bottomPanel.setVisible(false); hideControl(); if(popupPanel!=null){//debug mode call this popupPanel.setVisible(false); } } } }); tabPanel.add(new CopyToolPanel(),"Copy Indices/Weights"); tabPanel.add(new MorphMergeToolPanel(),"Fix morphtargets"); tabPanel.add(new BoneMergeToolPanel(),"Merge bones"); TabPanel tab=new TabPanel(); parent.add(tab); tab.add(createBasicControl(),"Basic"); tab.add(createBonePanel(),"Bone"); tab.add(createLoadExportPanel(),"Load/Export"); tab.add(createSkinningPanel(),"Skinning"); tab.add(createAnimationPanel(),"Animation"); tab.selectTab(2); tab.addSelectionHandler(new SelectionHandler<Integer>() { @Override public void onSelection(SelectionEvent<Integer> event) { selectedTabIndex=event.getSelectedItem(); updateSelectedTabIndex(); } }); showControl(); initialLoadBaseCharacterModel(GWTHTMLUtils.parameterFile("baseModel")); } protected void onBaseCharacterModelDisplacementLoaded(@Nullable ImageElement imageElement) { baseCharacterModelSkinnedMesh.getMaterial().gwtCastMeshPhongMaterial().setDisplacementMap(baseCharacterModelDisplacementUpload.createTextureFromUpload(basicCharacterModelDisplacementTexture)); baseCharacterModelSkinnedMesh.getMaterial().setNeedsUpdate(true); } protected void onBaseCharacterModelTextureLoaded(@Nullable ImageElement imageElement) { ImageElement newImage=imageElement; if(imageElement==null){//reset newImage=basicCharacterModelMapTexture; } baseCharacterModelSkinnedMesh.getMaterial().gwtCastMeshPhongMaterial().getMap().setImage(newImage); baseCharacterModelSkinnedMesh.getMaterial().gwtCastMeshPhongMaterial().getMap().setNeedsUpdate(true); } private Button makeAnimationButton(String name,final String url){ return new Button(name,new ClickHandler() { @Override public void onClick(ClickEvent event) { THREE.XHRLoader().load(url, new XHRLoadHandler() { @Override public void onLoad(String text) { loadAnimation(text); } }); } }); } private Panel createAnimationPanel(){ VerticalPanel animationPanel=new VerticalPanel(); HorizontalPanel controls=new HorizontalPanel(); controls.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); animationPanel.add(controls); controls.add(new Button("Stop",new ClickHandler() { @Override public void onClick(ClickEvent event) { stopAnimation(); //Quaternion q=THREE.Quaternion(); for(int i=0;i<baseCharacterModelSkinnedMesh.getSkeleton().getBones().length();i++){ Bone bone=baseCharacterModelSkinnedMesh.getSkeleton().getBones().get(i); bone.getQuaternion().copy(baseCharacterModelBones.get(i).gwtGetRotationQuaternion()); bone.getPosition().copy(baseCharacterModelBones.get(i).gwtGetPosition()); bone.updateMatrixWorld(true); } //something strange on position //baseSkinnedModelMesh.pose(); } })); pauseButton = new Button("Pause",new ClickHandler() { @Override public void onClick(ClickEvent event) { if(mixer.getTimeScale()==1){ mixer.setTimeScale(0); }else{ pauseButton.setText("Pause"); mixer.setTimeScale(1); } updatePauseButtonLabel(); } }); pauseButton.setEnabled(false); pauseButton.setWidth("100px"); controls.add(pauseButton); controls.add(new Button("Step",new ClickHandler() { @Override public void onClick(ClickEvent event) { mixer.setTimeScale(1); mixer.update(1.0/60); mixer.setTimeScale(0); updatePauseButtonLabel(); } })); timeLabel = new Label("time:0"); controls.add(timeLabel); HorizontalPanel animations=new HorizontalPanel(); animationPanel.add(animations); animations.add(makeAnimationButton("animation1", GWTHTMLUtils.parameterFile("animation1"))); animations.add(makeAnimationButton("animation2", GWTHTMLUtils.parameterFile("animation2"))); animations.add(makeAnimationButton("animation3", GWTHTMLUtils.parameterFile("animation3"))); animations.add(makeAnimationButton("animation4", GWTHTMLUtils.parameterFile("animation4"))); HorizontalPanel filePanel=new HorizontalPanel(); filePanel.setWidth("100%"); filePanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); animationPanel.add(filePanel); filePanel.add(new Button("Play",new ClickHandler() { @Override public void onClick(ClickEvent event) { if(uploadAnimationText==null){ return; } loadAnimation(uploadAnimationText); } })); final Label fileNameLabel=new Label(); fileNameLabel.setWidth("100%"); filePanel.add(fileNameLabel); FileUploadForm upload=FileUtils.createSingleTextFileUploadForm(new DataURLListener() { @Override public void uploaded(File file, String text) { fileNameLabel.setText(file.getFileName()); uploadAnimationText=text; loadAnimation(text); } }, true); animationPanel.add(upload); quickBoneAnimationWidget = new QuickBoneAnimationWidget("bone-animation"); quickBoneAnimationWidget.addValueChangeHandler(new ValueChangeHandler<AnimationClip>() { @Override public void onValueChange(ValueChangeEvent<AnimationClip> event) { stopAnimation(); baseCharacterModelSkinnedMesh.getPosition().set(0, 0, 0); baseCharacterModelSkinnedMesh.updateMatrixWorld(true); baseCharacterModelSkinnedMesh.getSkeleton().pose();//before reset,better to fix position if(event.getValue()!=null){ playAnimation(event.getValue()); } } }); animationPanel.add(quickBoneAnimationWidget); return animationPanel; } protected void updatePauseButtonLabel() { if(mixer.getTimeScale()==0){ pauseButton.setText("UnPause"); }else{ pauseButton.setText("Pause"); } } private String uploadAnimationText; public void stopAnimation() { if(mixer==null){ return; } mixer.stopAllAction(); lastAnimationClip=null; //characterMesh.getGeometry().getBones().get(60).setRotq(q) pauseButton.setEnabled(false); } private AnimationMixer mixer; private void loadAnimation(String text) { JSONValue object=JSONParser.parseStrict(text); JavaScriptObject js=object.isObject().getJavaScriptObject(); AnimationClip animationClip = AnimationClip.parse(js); playAnimation(animationClip); } private AnimationClip lastAnimationClip; private AbstractImageFileUploadPanel editingClothModelTextureUpload; private AbstractImageFileUploadPanel editingClothModelDisplacementUpload; private AnimationMixerAction currentAnimationAction; public void playAnimation(@Nullable AnimationClip clip) { if(clip==null){ return; } mixer.setTimeScale(1);//if paused mixer.stopAllAction(); mixer.uncacheClip(clip);//reset can cache currentAnimationAction=mixer.clipAction(clip).play(); lastAnimationClip=clip; pauseButton.setEnabled(true); updatePauseButtonLabel(); } private Panel createLoadExportPanel(){ VerticalPanel loadExportPanel=new VerticalPanel(); loadExportPanel.add(new HTML("<h4>EditingCloth</h4>")); loadExportPanel.add(new Label("auto bone-skinning(influence=3) if no-bone")); editingMeshUpload=new AbstractTextFileUploadPanel("Cloth Model",false) { @Override protected void onTextFileUpload(String text) { onEditingClothJsonLoaded(text); } }; editingMeshUpload.getUploadForm().setAccept(FileUploadForm.ACCEPT_JSON); loadExportPanel.add(editingMeshUpload); editingClothModelTextureUpload=new AbstractImageFileUploadPanel("Cloth Texture",true){ @Override protected void onImageFileUpload(ImageElement imageElement) { onEditingClothModelTextureLoaded(imageElement); } }; editingClothModelTextureUpload.getUploadForm().setAccept(FileUploadForm.ACCEPT_IMAGE); loadExportPanel.add(editingClothModelTextureUpload); editingClothModelDisplacementUpload=new AbstractImageFileUploadPanel("Cloth Displacement",true){ @Override protected void onImageFileUpload(ImageElement imageElement) { onEditingClothModelDisplacementLoaded(imageElement); } }; editingClothModelDisplacementUpload.getUploadForm().setAccept(FileUploadForm.ACCEPT_IMAGE); loadExportPanel.add(editingClothModelDisplacementUpload); final HorizontalPanel downloadPanel=new HorizontalPanel(); loadExportPanel.add(new HTML("Export geometry as Version4 json Format")); loadExportPanel.add(new Label("contain bones,indices and weights")); ExecuteButton exportButton=new ExecuteButton("Exec Export"){ @Override public void executeOnClick() { JSONObject object=editingGeometry.gwtJSONWithBone(); JSONValue morphTargets=editingGeometryJsonObject.get("morphTargets"); if(morphTargets!=null){ object.get("data").isObject().put("morphTargets", morphTargets); } downloadPanel.clear(); Anchor a=HTML5Download.get().generateTextDownloadLink(object.toString(), "geometry-weight-modified.json", "geometry to download",true); downloadPanel.add(a); } }; loadExportPanel.add(exportButton); loadExportPanel.add(downloadPanel); return loadExportPanel; } private int editingClothModelSkinnedMeshColor=0x880000; protected void onEditingClothModelTextureLoaded(ImageElement imageElement) { if(editingClothModelSkinnedMesh==null){ return; } Texture texture=editingClothModelTextureUpload.createTextureFromUpload(null); editingClothModelSkinnedMesh.getMaterial().gwtCastMeshPhongMaterial().setMap(texture); editingClothModelSkinnedMesh.getMaterial().setNeedsUpdate(true); if(editingClothModelTextureUpload.isUploaded()){ editingClothModelSkinnedMesh.getMaterial().gwtCastMeshPhongMaterial().getColor().setHex(0xffffff); }else{ editingClothModelSkinnedMesh.getMaterial().gwtCastMeshPhongMaterial().getColor().setHex(editingClothModelSkinnedMeshColor); } } protected void onEditingClothModelDisplacementLoaded(ImageElement imageElement) { if(editingClothModelSkinnedMesh==null){ return; } Texture texture=editingClothModelDisplacementUpload.createTextureFromUpload(null); editingClothModelSkinnedMesh.getMaterial().gwtCastMeshPhongMaterial().setDisplacementMap(texture); editingClothModelSkinnedMesh.getMaterial().setNeedsUpdate(true); } private Panel createSkinningPanel(){ VerticalPanel weightPanel=new VerticalPanel(); //this is test. Button testClearAll=new Button("Test clear all",new ClickHandler() { @Override public void onClick(ClickEvent event) { for(int i=0;i<editingGeometry.getSkinIndices().length();i++){ for(int j=0;j<4;j++){ editingGeometry.getSkinIndices().get(i).gwtSet(j, 0); editingGeometry.getSkinWeights().get(i).gwtSet(j, 0); } } createEditingClothSkin();//weight updated LogUtils.log(editingClothModelSkinnedMesh); //editingGeometryMesh.setVisible(false); AnimationBone bone=boneListBox.getValue(); if(bone!=null){ onBoneSelectionChanged(bone); } } }); //weightPanel.add(testClearAll); weightPanel.add(new HTML("<h4>Skinning Indices & Weight</h4>")); vertexBoneDataEditor = new VertexBoneDataEditor(); vertexBoneDataEditor.setValue(null); weightPanel.add(vertexBoneDataEditor); //for test //need set bone HorizontalPanel buttons=new HorizontalPanel(); weightPanel.add(buttons); Button applyBt=new Button("Apply",new ClickHandler() { @Override public void onClick(ClickEvent event) { if(vertexBoneDataEditor.getValue()==null){ return; } //int index=vertexBoneDataEditor.getValue().getVertexIndex(); vertexBoneDataEditor.flush(); createEditingClothSkin(); } }); buttons.add(applyBt); applyBt.setWidth("120px"); Button cancelBt=new Button("Cancel Edit",new ClickHandler() { @Override public void onClick(ClickEvent event) { if(vertexBoneDataEditor.getValue()==null){ return; } int index=vertexBoneDataEditor.getValue().getVertexIndex(); vertexBoneDataEditor.setValue(VertexBoneData.createFromdMesh(editingGeometry, index)); //no effect when flushd //vertexBoneDataEditor.flush(); //createEditingGeometrySkinnedMesh(); } }); buttons.add(cancelBt); Button resetBt=new Button("Rest Origin",new ClickHandler() { @Override public void onClick(ClickEvent event) { if(vertexBoneDataEditor.getValue()==null){ return; } int index=vertexBoneDataEditor.getValue().getVertexIndex(); vertexBoneDataEditor.copyValue(VertexBoneData.createFromdMesh(editingGeometryOrigin, index)); vertexBoneDataEditor.flush(); createEditingClothSkin(); } }); buttons.add(resetBt); Button testVertexGroup=new Button("Vertical vertex group selection",new ClickHandler() { @Override public void onClick(ClickEvent event) { if(vertexBoneDataEditor.getValue()==null){ return; } //warning possible editingGeometry has no bone. int index=vertexBoneDataEditor.getValue().getVertexIndex(); execVerticalVertexGroup(index,false);//TODO balancing createEditingClothSkin(); } }); weightPanel.add(testVertexGroup); ExecuteButton testVertexGroupAll=new ExecuteButton("Vertical vertex group all"){ @Override public void executeOnClick() { boolean balancing=true; Stopwatch watch=LogUtils.stopwatch(); JSParameter param=JSParameter.createParameter(); for(int i=0;i<editingGeometry.getVertices().length();i++){ if(param.exists(String.valueOf(i))){ continue; } List<Integer> result=execVerticalVertexGroup(i,balancing); if(result==null){ return;//cancel } for(int v:result){ param.set(String.valueOf(v), true); } } if(balancing){ editingGeometry.gwtSetInfluencesPerVertex(editingGeometry.gwtGetInfluencesPerVertex()+1); } LogUtils.millisecond("convert-all", watch); createEditingClothSkin(); } }; weightPanel.add(testVertexGroupAll); return weightPanel; } private List<Integer> execVerticalVertexGroup(int index,boolean balancing){ int influence=editingGeometry.gwtGetInfluencesPerVertex(); if(balancing && influence==4){ LogUtils.log("not supported influence4 and balancing"); return null; } List<Integer> result=Lists.newArrayList(); findVertexGroup(editingGeometry,index,result); //LogUtils.log("size:"+result.size()); //LogUtils.millisecond("find", watch); List<List<String>> beforeBoneNames=Lists.newArrayList(); for(int i=0;i<result.size();i++){ Vector4 indices=editingGeometry.getSkinIndices().get(result.get(i)); List<String> boneNames=Lists.newArrayList(); for(int j=0;j<4;j++){ int boneIndex=indices.gwtGet(j); if(boneIndex!=0){//ignore root; boneNames.add(baseCharacterModelGeometry.getBones().get(boneIndex).getName()); } } beforeBoneNames.add(boneNames); } Map<Integer,Integer> countMap=Maps.newHashMap(); for(List<String> vs:beforeBoneNames){ for(String v:vs){ if(!v.contains(",")){ continue;// no plain style } Vector2 pos=BoneNameUtils.parsePlainBoneName(v); Integer count=countMap.get((int)pos.getX()); if(count==null){ countMap.put((int)pos.getX(), 1); }else{ countMap.put((int)pos.getX(), count+1); //LogUtils.log("?"+((int)pos.getX())+( count+1)); } } } if(countMap.size()==0){ LogUtils.log("maybe no plain-bone style"); return null; } int maxX=0; int maxValue=0; int total=0; for(int key:countMap.keySet()){ int count=countMap.get(key); total+=count; if(count>maxValue){ maxX=key; maxValue=count; } } //apply changes for(int i=0;i<result.size();i++){ Vector4 indices=editingGeometry.getSkinIndices().get(result.get(i)); for(int j=0;j<4;j++){ int boneIndex=indices.gwtGet(j); if(boneIndex!=0){//ignore root; String boneName=baseCharacterModelGeometry.getBones().get(boneIndex).getName(); Vector2 boneVec=BoneNameUtils.parsePlainBoneName(boneName); if(boneVec.getX()!=maxX){ String newName=BoneNameUtils.makePlainBoneName(maxX,(int)boneVec.getY()); int newIndex=BoneNameUtils.findBoneByName(baseCharacterModelGeometry.getBones(),newName); if(newIndex!=-1){ indices.gwtSet(j, newIndex); //LogUtils.log("update indices at "+j+" of "+result.get(i)+" name="+newName); }else{ LogUtils.log("can't find newBoneName:"+newName); } } } } } double mainPercent=(double)maxValue/total;//TODO change this strategy not so good //LogUtils.log("main-percent:"+mainPercent); double rootValue=1.0-mainPercent; for(int i=0;i<result.size();i++){ Vector4 indices=editingGeometry.getSkinIndices().get(result.get(i)); Vector4 weights=editingGeometry.getSkinWeights().get(result.get(i)); for(int j=0;j<influence;j++){ double changed=weights.gwtGet(j)*mainPercent; weights.gwtSet(j, changed); } indices.gwtSet(influence+1, 0);//must be root weights.gwtSet(influence+1, rootValue); } //DO increment influence finished all return result; } private void findVertexGroup(Geometry geometry,int vertexIndex,List<Integer> vertexs){ vertexs.add(vertexIndex); List<Integer> result= findContainFace(geometry,vertexIndex); for(int faceIndex:result){ Face3 face=geometry.getFaces().get(faceIndex); for(int i=0;i<3;i++){ int v=face.gwtGet(i); if(!vertexs.contains(v)){ findVertexGroup(geometry,v,vertexs); } } } } private List<Integer> findContainFace(Geometry geometry,int vertexIndex){ List<Integer> faces=Lists.newArrayList(); for(int i=0;i<geometry.getFaces().length();i++){ Face3 face=geometry.getFaces().get(i); for(int j=0;j<3;j++){ if(face.gwtGet(j)==vertexIndex){ faces.add(i); } } } return faces; } /** @deprecated * i don know how to update,without recreate skinnedmesh maybe attribute? * @param index */ public void copyIndicesAndWeightToSkinningMesh(int index){ editingClothModelSkinnedMesh.getGeometry().getSkinIndices().get(index).copy(editingGeometry.getSkinIndices().get(index)); editingClothModelSkinnedMesh.getGeometry().getSkinWeights().get(index).copy(editingGeometry.getSkinWeights().get(index)); } protected void autobalanceWeight(Vector4 vector4) { double total=0; for(int i=0;i<4;i++){ total+=vector4.gwtGet(i); } for(int i=0;i<4;i++){ if(total!=0){ vector4.gwtSet(i, vector4.gwtGet(i)/total); }else{ vector4.gwtSet(i,0);//need? } } } protected void onBoneSelectionChanged(@Nullable AnimationBone value) { if(value==null){ baseCharacterVertexColorTools.clearVertexsColor(); boneMouseSelector.setBoneSelection(null); }else{ baseCharacterVertexColorTools.updateVertexsColorByBone(baseCharacterModelBones.indexOf(value)); boneMouseSelector.setBoneSelection(value.getName()); } if(editingClothVertexColorTools!=null){ if(value==null){ editingClothVertexColorTools.clearVertexsColor(); }else{ editingClothVertexColorTools.updateVertexsColorByBone(baseCharacterModelBones.indexOf(value)); } } //for sphere updateBoneInfluenceSpheres(value); } private void updateBoneInfluenceSpheres(@Nullable AnimationBone value){ if(value==null){ updateBoneInfluenceSpheres(); }else{ updateBoneInfluenceSpheres(); Object3D mesh=boneMeshGroup.getObjectByName("core:"+value.getName()); boneInfluenceCoreSphere.getPosition().copy(mesh.getPosition()); boneInfluenceSphere.getPosition().copy(mesh.getPosition()); } } private JSONObject editingGeometryJsonObject; private Geometry editingGeometryOrigin; private Geometry editingGeometry; private SkinnedMesh editingClothModelSkinnedMesh; private Mesh editingGeometryWireMesh; private VertexNormalsHelper editingClothWireframeNormalsHelper; private MeshVertexSelector editingClothWireframeVertexSelector; private VertexBoneDataEditor vertexBoneDataEditor; private WireframeHelper editingGeometryWireMeshHelper; private VertexNormalsHelper editingClothSkinNormalsHelper; private MeshVertexSelector editingClothSkinVertexSelector; private AbstractTextFileUploadPanel baseCharacterModelUpload; private AbstractTextFileUploadPanel editingMeshUpload; private AbstractImageFileUploadPanel baseCharacterModelTextureUpload; private Button pauseButton; private Label timeLabel; private QuickBoneAnimationWidget quickBoneAnimationWidget; private Mesh boneInfluenceCoreSphere; private DoubleBox coreRadiusBox; private CheckBox enableBoneInfluenceCheck; private CheckBox boneInfluenceSetFromOriginCheck; private JSONObject parseJSONGeometry(String text){ JSONValue json=JSONParser.parseStrict(text); JSONObject jsonObject=json.isObject(); boolean hasData=jsonObject.get("data")!=null;//4.* format has this if(hasData){ jsonObject=jsonObject.get("data").isObject(); } return jsonObject; } private void setInfluencePerVertexFromJSON(Geometry geometry,JSONObject jsonObject){ double influencesPerVertex=jsonObject.get("influencesPerVertex")!=null?jsonObject.get("influencesPerVertex").isNumber().doubleValue():2; geometry.gwtSetInfluencesPerVertex((int)influencesPerVertex);//used when export } private void createVertexSelections() { if(editingClothWireframeNormalsHelper!=null){ scene.remove(editingClothWireframeNormalsHelper); } double lineWidth=0.1; double size=0.01; editingClothWireframeNormalsHelper = THREE.VertexNormalsHelper(editingGeometryWireMesh, size, 0xffff00, lineWidth); scene.add(editingClothWireframeNormalsHelper); //for editing-mesh if(editingClothWireframeVertexSelector!=null){ editingClothWireframeVertexSelector.dispose(); } editingClothWireframeVertexSelector = new MeshVertexSelector(editingGeometryWireMesh, renderer, camera, scene); updateSelectedTabIndex(); } @Override public String getTabTitle() { return "Skinning Tool"; } /** * for json meta * @return */ public static String getGeneratedBy(){ return "GWTModel-Weight ver"+GWTModelWeight.version; } }
package de.tum.in.reitinge.test; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCanvas; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLDrawable; import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLEventListener; import javax.media.opengl.glu.GLU; import javax.swing.JFrame; import javax.swing.JPanel; import com.sun.opengl.util.GLUT; import de.jreality.jogl.shader.GlslShaderProgram; import de.jreality.soft.NewDoublePolygonRasterizer; public class JOGLTest extends JPanel implements GLEventListener, MouseListener, MouseMotionListener, MouseWheelListener { private static final long serialVersionUID = 1L; GlslShaderProgram program = null; private GLAutoDrawable drawable = null; private GLU glu = new GLU(); private GLUT glut = new GLUT(); private boolean mouseDown = false; private float mouse[] = {0,0}; private float rotate[] = {0,0}; private float zoom = 0; private boolean first = true; public JOGLTest() { GLCanvas canvas = new GLCanvas(new GLCapabilities()); setLayout(new BorderLayout()); add(canvas, BorderLayout.CENTER); canvas.addGLEventListener(this); canvas.addMouseListener(this); canvas.addMouseMotionListener(this); canvas.addMouseWheelListener(this); } /** * @param args */ public static void main(String[] args) { final int WINDOW_WIDTH = 800; final int WINDOW_HEIGHT = 600; final String WINDOW_TITLE = "JOGL Program Template"; JFrame frame = new JFrame(); frame.setBackground(Color.blue); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final JOGLTest joglMain = new JOGLTest(); frame.setContentPane(joglMain); frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); frame.setVisible(true); frame.setTitle(WINDOW_TITLE); } @Override public void display(GLAutoDrawable drawable) { GL gl = drawable.getGL(); gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); gl.glColor3f(0, 1, 0); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glPushMatrix(); gl.glTranslatef(0, 0, -zoom); gl.glRotatef(rotate[0], 0.0f, 1.0f, 0.0f); gl.glRotatef(rotate[1], 1.0f, 0.0f, 0.0f); gl.glEnable(GL.GL_BLEND); gl.glDepthMask(false); drawTransparent(gl); gl.glDepthMask(true); gl.glDisable(GL.GL_BLEND); drawOpaque(gl); gl.glEnable(GL.GL_BLEND); gl.glDepthMask(false); drawTransparent(gl); gl.glDepthMask(true); gl.glColorMask(false, false, false, false); drawOpaque(gl); drawTransparent(gl); gl.glColorMask(true, true, true, true); gl.glEnable(GL.GL_BLEND); gl.glDepthMask(false); drawTransparent(gl); gl.glDepthMask(true); drawOpaque(gl); // gl.glDepthMask(false); // gl.glEnable(GL.GL_BLEND); // drawTransparent(gl); // gl.glDepthMask(true); // gl.glDisable(GL.GL_BLEND); //// gl.glColorMask(false, false, false, false); // drawOpaque(gl); //// gl.glColorMask(true, true, true, true); // gl.glDepthMask(false); // gl.glEnable(GL.GL_BLEND); // drawTransparent(gl); // gl.glDepthMask(true); // gl.glDisable(GL.GL_BLEND); //drawOpaque(gl); // program.bind(gl); // gl.glUniform1f(program.getUniformLocation(gl, "sphereRadius"), 0.5f); // gl.glUniform3f(program.getUniformLocation(gl, "sphereCenter"), 0.0f, 0.0f, 0.0f); // gl.glUniform3f(program.getUniformLocation(gl, "sphereColor"), 1.0f, 0.0f, 0.0f); // program.unbind(gl); gl.glPopMatrix(); gl.glFlush(); } private void drawOpaque(GL gl) { // gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // gl.glBegin(GL.GL_QUADS); // gl.glVertex3f(-1.0f, -1.0f,1.0f); // gl.glVertex3f(1.0f, -1.0f,1.0f); // gl.glVertex3f(1.0f, 1.0f,1.0f); // gl.glVertex3f(-1.0f, 1.0f,1.0f); // gl.glEnd(); // gl.glTranslated(0, 0, 7.5); // gl.glColor4f(1, 0, 0, 1); // glut.glutSolidTorus(1, 2, 32, 32); // gl.glTranslated(0, 0, -7.5); } private void drawTransparent(GL gl) { int steps = 128; double step = 2.0*Math.PI / steps; int j; double shift[][] = {{0,0,0},{1,-0.5,-1.3},{3,0.5,1.6},{2,0,3}}; for (int k=0; k<1; ++k) { for (int i=0; i<steps; ++i) { j = i%8; gl.glColor4f(j/4, (j%4)/2, j%2, 0.02f); double dir[] = {Math.cos(i*step), Math.sin(i*step)}; gl.glBegin(GL.GL_QUADS); gl.glVertex3d(dir[0]*0.5+shift[k][0], -1.0f+shift[k][1], dir[1]*0.5+shift[k][2]); gl.glVertex3d(dir[0]*2+shift[k][0], -1.0f+shift[k][1], dir[1]*2+shift[k][2]); gl.glVertex3d(dir[0]*2+shift[k][0], 1.0f+shift[k][1], dir[1]*2+shift[k][2]); gl.glVertex3d(dir[0]*0.5+shift[k][0], 1.0f+shift[k][1], dir[1]*0.5+shift[k][2]); gl.glEnd(); } } // gl.glBegin(GL.GL_QUADS); // gl.glVertex3d(-1, -1,) // gl.glEnd(); // gl.glColor4d(1, 0, 0, 0.1); // glut.glutSolidSphere(1, 32, 32); // for (int i=0; i<8; ++i) { // if (i == 4) { // gl.glTranslated(0, 0, 1.5); // continue; // gl.glColor4f(i/4, (i%4)/2, i%2, 0.1f); // gl.glTranslated(0, 0, 1.5); // glut.glutSolidTorus(1, 2, 32, 32); // gl.glTranslated(0, 0, -8*1.5); } @Override public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean arg2) { System.out.println("displayChanged() called"); } @Override public void init(GLAutoDrawable drawable) { System.out.println("init() called"); this.drawable = drawable; GL gl = drawable.getGL(); gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); //gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_DST_ALPHA); gl.glEnable(GL.GL_DEPTH_TEST); gl.glDepthFunc(GL.GL_LEQUAL); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glLoadIdentity(); glu.gluLookAt(0, 0, 5, 0, 0, 0, 0, 1, 0); try { program = new GlslShaderProgram(gl, getClass().getResourceAsStream("/de/tum/in/jrealityplugin/resources/shader/sphere.vert"), getClass().getResourceAsStream("/de/tum/in/jrealityplugin/resources/shader/sphere.frag") ); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { System.out.println("reshape() called"); if (height <=0) height = 1; GL gl = drawable.getGL(); gl.glViewport(0, 0, width, height); gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); glu.gluPerspective(45.0f, (float)width/(float)height, 0.1f, 500.0f); } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { mouseDown = true; mouse[0] = e.getX(); mouse[1] = e.getY(); } } @Override public void mouseReleased(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) mouseDown = false; } @Override public void mouseDragged(MouseEvent e) { if (mouseDown) { rotate[0] += e.getX() - mouse[0]; rotate[1] += e.getY() - mouse[1]; mouse[0] = e.getX(); mouse[1] = e.getY(); drawable.display(); } } @Override public void mouseMoved(MouseEvent e) { } @Override public void mouseWheelMoved(MouseWheelEvent e) { zoom += e.getWheelRotation(); drawable.display(); } }
package com.akjava.gwt.modelweight.client; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.akjava.bvh.client.BVH; import com.akjava.bvh.client.BVHParser; import com.akjava.bvh.client.BVHParser.ParserListener; import com.akjava.bvh.client.threejs.AnimationBoneConverter; import com.akjava.bvh.client.threejs.AnimationDataConverter; import com.akjava.gwt.html5.client.HTML5InputRange; import com.akjava.gwt.html5.client.extra.HTML5Builder; import com.akjava.gwt.html5.client.file.File; import com.akjava.gwt.html5.client.file.FileHandler; import com.akjava.gwt.html5.client.file.FileReader; import com.akjava.gwt.html5.client.file.FileUtils; import com.akjava.gwt.modelweight.client.weight.GWTWeightData; import com.akjava.gwt.modelweight.client.weight.WeighDataParser; import com.akjava.gwt.three.client.THREE; import com.akjava.gwt.three.client.core.Geometry; import com.akjava.gwt.three.client.core.Intersect; import com.akjava.gwt.three.client.core.Object3D; import com.akjava.gwt.three.client.core.Projector; import com.akjava.gwt.three.client.core.Vector3; import com.akjava.gwt.three.client.core.Vector4; import com.akjava.gwt.three.client.extras.GeometryUtils; import com.akjava.gwt.three.client.extras.ImageUtils; import com.akjava.gwt.three.client.extras.animation.Animation; import com.akjava.gwt.three.client.extras.animation.AnimationHandler; import com.akjava.gwt.three.client.extras.loaders.JSONLoader; import com.akjava.gwt.three.client.extras.loaders.JSONLoader.LoadHandler; import com.akjava.gwt.three.client.gwt.Clock; import com.akjava.gwt.three.client.gwt.GWTGeometryUtils; import com.akjava.gwt.three.client.gwt.SimpleDemoEntryPoint; import com.akjava.gwt.three.client.gwt.animation.AnimationBone; import com.akjava.gwt.three.client.gwt.animation.AnimationData; import com.akjava.gwt.three.client.gwt.animation.AnimationHierarchyItem; import com.akjava.gwt.three.client.gwt.animation.WeightBuilder; import com.akjava.gwt.three.client.gwt.collada.ColladaData; import com.akjava.gwt.three.client.lights.Light; import com.akjava.gwt.three.client.materials.Material; import com.akjava.gwt.three.client.objects.Mesh; import com.akjava.gwt.three.client.objects.SkinnedMesh; import com.akjava.gwt.three.client.renderers.WebGLRenderer; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayString; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.MouseMoveEvent; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.http.client.URL; import com.google.gwt.json.client.JSONArray; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONParser; import com.google.gwt.json.client.JSONValue; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.FileUpload; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Panel; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class GWTModelWeight extends SimpleDemoEntryPoint{ @Override protected void beforeUpdate(WebGLRenderer renderer) { if(root!=null){ boneAndVertex.getRotation().set(Math.toRadians(rotX),Math.toRadians(rotY),0); boneAndVertex.getPosition().set(posX,posY,0); root.setPosition(positionXRange.getValue(), positionYRange.getValue(), positionZRange.getValue()); root.getRotation().set(Math.toRadians(rotationRange.getValue()),Math.toRadians(rotationYRange.getValue()),Math.toRadians(rotationZRange.getValue())); } long delta=clock.delta(); //log(""+animation.getCurrentTime()); double v=(double)delta/1000; if(!paused && animation!=null){ AnimationHandler.update(v); currentTime=animation.getCurrentTime(); } } double currentTime; private Clock clock=new Clock(); @Override protected void initializeOthers(WebGLRenderer renderer) { scene.add(THREE.AmbientLight(0xffffff)); Light pointLight = THREE.DirectionalLight(0xffffff,1); pointLight.setPosition(0, 10, 300); scene.add(pointLight); Light pointLight2 = THREE.DirectionalLight(0xffffff,1);//for fix back side dark problem pointLight2.setPosition(0, 10, -300); scene.add(pointLight2); projector=THREE.Projector(); /* //write test Geometry g=THREE.CubeGeometry(1, 1, 1); log(g); Geometry g2=THREE.CubeGeometry(1, 1, 1); Matrix4 mx=THREE.Matrix4(); mx.setPosition(THREE.Vector3(0,10,0)); //g2.applyMatrix(mx); Mesh tmpM=THREE.Mesh(g2, THREE.MeshBasicMaterial().build()); tmpM.setPosition(0, 10, 0); GeometryUtils.merge(g, tmpM); JSONModelFile model=JSONModelFile.create(); model.setVertices(g.vertices()); model.setFaces(g.faces()); //JSONArray vertices=new JSONArray(nums); JSONObject js=new JSONObject(model); log(js.toString()); scene.add(THREE.AmbientLight(0x888888)); Light pointLight = THREE.PointLight(0xffffff); pointLight.setPosition(0, 10, 300); scene.add(pointLight); */ //loadBVH("14_08.bvh"); JSONLoader loader=THREE.JSONLoader(); loader.load("buffalo.js", new LoadHandler() { @Override public void loaded(Geometry geometry) { AnimationHandler.add(geometry.getAnimation()); log(geometry.getBones()); log(geometry.getAnimation()); //JSONObject test=new JSONObject(geometry.getAnimation()); //log(test.toString()); Geometry cube=THREE.CubeGeometry(1, 1, 1); JsArray<Vector4> indices=(JsArray<Vector4>) JsArray.createArray(); JsArray<Vector4> weight=(JsArray<Vector4>) JsArray.createArray(); for(int i=0;i<cube.vertices().length();i++){ Vector4 v4=THREE.Vector4(); v4.set(0, 0, 0, 0); indices.push(v4); Vector4 v4w=THREE.Vector4(); v4w.set(1, 0, 0, 0); weight.push(v4w); } cube.setSkinIndices(indices); cube.setSkinWeight(weight); cube.setBones(geometry.getBones()); //root=boneToCube(geometry.getBones()); //scene.add(root); //SkinnedMesh mesh=THREE.SkinnedMesh(cube, THREE.MeshLambertMaterial().skinning(true).color(0xff0000).build()); //scene.add(mesh); //Animation animation = THREE.Animation( mesh, "take_001" ); //log(animation); //animation.play(); //buffalo } }); loadBVH("14_01.bvh"); //loadBVH("14_08.bvh"); } Object3D root; List<Mesh> tmp=new ArrayList<Mesh>(); private Object3D boneToSkelton(JsArray<AnimationBone> bones){ tmp.clear(); Object3D group=THREE.Object3D(); for(int i=0;i<bones.length();i++){ AnimationBone bone=bones.get(i); Geometry cube=THREE.CubeGeometry(.3, .3, .3); int color=0xff0000; if(i==0){ //color=0x00ff00; } Mesh mesh=THREE.Mesh(cube, THREE.MeshLambertMaterial().color(color).build()); group.add(mesh); Vector3 pos=AnimationBone.jsArrayToVector3(bone.getPos()); if(bone.getParent()!=-1){ Vector3 half=pos.clone().multiplyScalar(.5); Vector3 ppos=tmp.get(bone.getParent()).getPosition(); pos.addSelf(ppos); half.addSelf(ppos); double length=ppos.clone().subSelf(pos).length(); //half Mesh halfMesh=THREE.Mesh(THREE.CubeGeometry(.2, .2, length), THREE.MeshLambertMaterial().color(0xaaaaaa).build()); group.add(halfMesh); halfMesh.setPosition(half); halfMesh.lookAt(pos); halfMesh.setName(bones.get(bone.getParent()).getName()); } mesh.setPosition(pos); mesh.setName(bone.getName()); if(bone.getParent()!=-1){ //AnimationBone parent=bones.get(bone.getParent()); Vector3 ppos=tmp.get(bone.getParent()).getPosition(); Mesh line=THREE.Line(GWTGeometryUtils.createLineGeometry(pos, ppos), THREE.LineBasicMaterial().color(0x888888).build()); group.add(line); } tmp.add(mesh); } return group; } private List<NameAndPosition> boneToNameAndWeight(JsArray<AnimationBone> bones){ List<NameAndPosition> lists=new ArrayList<NameAndPosition>(); List<Vector3> absolutePos=new ArrayList<Vector3>(); for(int i=0;i<bones.length();i++){ AnimationBone bone=bones.get(i); Vector3 pos=AnimationBone.jsArrayToVector3(bone.getPos()); String parentName=null; //add start //add center Vector3 parentPos=null; Vector3 endPos=null; int parentIndex=0; if(bone.getParent()!=-1){ parentIndex=bone.getParent(); parentName=bones.get(parentIndex).getName(); parentPos=absolutePos.get(parentIndex); if(pos.getX()!=0 || pos.getY()!=0 || pos.getZ()!=0){ endPos=pos.clone().multiplyScalar(.9).addSelf(parentPos); Vector3 half=pos.clone().multiplyScalar(.5).addSelf(parentPos); lists.add(new NameAndPosition(parentName,endPos,parentIndex));//start pos lists.add(new NameAndPosition(parentName,half,parentIndex));//half pos Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.2, .2, .2), THREE.MeshLambertMaterial().color(0x00ff00).build()); mesh.setName(parentName); mesh.setPosition(endPos); //boneAndVertex.add(mesh); Mesh mesh2=THREE.Mesh(THREE.CubeGeometry(.3, .3, .2), THREE.MeshLambertMaterial().color(0x00ff00).build()); mesh2.setName(parentName); mesh2.setPosition(half); //boneAndVertex.add(mesh2); }else{ } } //add end if(parentPos!=null){ pos.addSelf(parentPos); } absolutePos.add(pos); Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.5, .5, .5), THREE.MeshLambertMaterial().color(0x00ff00).build()); mesh.setName(bone.getName()); mesh.setPosition(pos); //boneAndVertex.add(mesh); if(parentPos!=null){ Mesh line=GWTGeometryUtils.createLineMesh(parentPos, pos, 0xff0000); //boneAndVertex.add(line); } lists.add(new NameAndPosition(bone.getName(),pos,i));//end pos } return lists; } private Projector projector; Label debugLabel; @Override public void onMouseClick(ClickEvent event) { int x=event.getX(); int y=event.getY(); /* if(inEdge(x,y)){ screenMove(x,y); return; }*/ JsArray<Intersect> intersects=projector.gwtPickIntersects(event.getX(), event.getY(), screenWidth, screenHeight, camera,scene); for(int i=0;i<intersects.length();i++){ Intersect sect=intersects.get(i); Object3D target=sect.getObject(); if(!target.getName().isEmpty()){ if(target.getName().startsWith("point:")){ if(!target.getVisible()){ continue; } String[] pv=target.getName().split(":"); int at=Integer.parseInt(pv[1]); Vector4 in=bodyIndices.get(at); Vector4 we=bodyWeight.get(at); indexWeightEditor.setValue(at, in, we); //createSkinnedMesh(); //log("raw-weight:"); //log(rawCollada.getWeights().get(at)); //debugLabel.setText(in.getX()+":"+in.getY()+","+we.getX()+":"+we.getY()); }else{ select(target); break; } } } } private Mesh selection; private int selectionBoneIndex; private Object3D selectVertex; private void select(Object3D target) { if(selection==null){ selection=THREE.Mesh(THREE.CubeGeometry(1, 1, 1), THREE.MeshLambertMaterial().color(0x00ff00).build()); boneAndVertex.add(selection); } selection.setPosition(target.getPosition()); selectionBoneIndex=findBoneIndex(target.getName()); selectVertex(selectionBoneIndex); } private void selectVertex(int selected) { for(int i=0;i<bodyGeometry.vertices().length();i++){ Vector4 index=bodyIndices.get(i); Mesh mesh=vertexs.get(i); if(index.getX()==selected || index.getY()==selected){ mesh.setVisible(true); Vector4 weight=bodyWeight.get(i); //log(weight.getX()+","+weight.getY()); }else{ mesh.setVisible(false); } } } private int findBoneIndex(String name){ int ret=0; for(int i=0;i<bones.length();i++){ if(bones.get(i).getName().equals(name)){ ret=i; break; } } return ret; } int rotX; int rotY; int posX; int posY; @Override public void onMouseMove(MouseMoveEvent event) { if(mouseDown){ int diffX=event.getX()-mouseDownX; int diffY=event.getY()-mouseDownY; mouseDownX=event.getX(); mouseDownY=event.getY(); if(event.isShiftKeyDown()){ posX+=diffX/2; posY-=diffY/2; }else{ rotX=(rotX+diffY); rotY=(rotY+diffX); } } } private HTML5InputRange positionXRange; private HTML5InputRange positionYRange; private HTML5InputRange positionZRange; private HTML5InputRange rotationRange; private HTML5InputRange rotationYRange; private HTML5InputRange rotationZRange; @Override public void createControl(Panel parent) { debugLabel=new Label(); parent.add(debugLabel); HorizontalPanel h1=new HorizontalPanel(); rotationRange = new HTML5InputRange(-180,180,0); parent.add(HTML5Builder.createRangeLabel("X-Rotate:", rotationRange)); parent.add(h1); h1.add(rotationRange); Button reset=new Button("Reset"); reset.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationRange.setValue(0); } }); h1.add(reset); HorizontalPanel h2=new HorizontalPanel(); rotationYRange = new HTML5InputRange(-180,180,0); parent.add(HTML5Builder.createRangeLabel("Y-Rotate:", rotationYRange)); parent.add(h2); h2.add(rotationYRange); Button reset2=new Button("Reset"); reset2.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationYRange.setValue(0); } }); h2.add(reset2); HorizontalPanel h3=new HorizontalPanel(); rotationZRange = new HTML5InputRange(-180,180,0); parent.add(HTML5Builder.createRangeLabel("Z-Rotate:", rotationZRange)); parent.add(h3); h3.add(rotationZRange); Button reset3=new Button("Reset"); reset3.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationZRange.setValue(0); } }); h3.add(reset3); HorizontalPanel h4=new HorizontalPanel(); positionXRange = new HTML5InputRange(-50,50,0); parent.add(HTML5Builder.createRangeLabel("X-Position:", positionXRange)); parent.add(h4); h4.add(positionXRange); Button reset4=new Button("Reset"); reset4.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { positionXRange.setValue(0); } }); h4.add(reset4); HorizontalPanel h5=new HorizontalPanel(); positionYRange = new HTML5InputRange(-50,50,0); parent.add(HTML5Builder.createRangeLabel("Y-Position:", positionYRange)); parent.add(h5); h5.add(positionYRange); Button reset5=new Button("Reset"); reset5.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { positionYRange.setValue(0); } }); h5.add(reset5); HorizontalPanel h6=new HorizontalPanel(); positionZRange = new HTML5InputRange(-50,50,0); parent.add(HTML5Builder.createRangeLabel("Z-Position:", positionZRange)); parent.add(h6); h6.add(positionZRange); Button reset6=new Button("Reset"); reset6.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { positionZRange.setValue(0); } }); h6.add(reset6); positionYRange.setValue(-13); positionXRange.setValue(20); Button bt=new Button("Pause/Play"); parent.add(bt); bt.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { paused=!paused; } }); //editor indexWeightEditor = new IndexAndWeightEditor(); parent.add(indexWeightEditor); Button update=new Button("Update"); update.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { int index=indexWeightEditor.getArrayIndex(); if(index==-1){ return; } Vector4 in=bodyIndices.get(index); Vector4 we=bodyWeight.get(index); in.setX(indexWeightEditor.getIndex1()); in.setY(indexWeightEditor.getIndex2()); we.setX(indexWeightEditor.getWeight1()); we.setY(indexWeightEditor.getWeight2()); //log("new-ind-weight:"+in.getX()+","+in.getY()+","+we.getX()+","+we.getY()); createSkinnedMesh(); selectVertex(selectionBoneIndex); } }); parent.add(update); useBasicMaterial = new CheckBox(); useBasicMaterial.setText("Use Basic Material"); parent.add(useBasicMaterial); parent.add(new Label("BVH Bone")); FileUpload bvhUpload=new FileUpload(); parent.add(bvhUpload); bvhUpload.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { JsArray<File> files = FileUtils.toFile(event.getNativeEvent()); final FileReader reader=FileReader.createFileReader(); reader.setOnLoad(new FileHandler() { @Override public void onLoad() { //log("load:"+Benchmark.end("load")); //GWT.log(reader.getResultAsString()); parseBVH(reader.getResultAsString()); } }); reader.readAsText(files.get(0),"utf-8"); } }); showControl(); } private boolean paused; private void loadBVH(String path){ RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(path)); try { builder.sendRequest(null, new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { String bvhText=response.getText(); //log("loaded:"+Benchmark.end("load")); //useless spend allmost time with request and spliting. parseBVH(bvhText); } @Override public void onError(Request request, Throwable exception) { Window.alert("load faild:"); } }); } catch (RequestException e) { log(e.getMessage()); e.printStackTrace(); } } private JsArray<Vector4> bodyIndices; private JsArray<Vector4> bodyWeight; private BVH bvh; private Animation animation; private Geometry bodyGeometry; private Object3D boneAndVertex; private JsArray<AnimationBone> bones; private SkinnedMesh skinnedMesh; private ColladaData rawCollada; private void parseBVH(String bvhText){ final BVHParser parser=new BVHParser(); parser.parseAsync(bvhText, new ParserListener() { private AnimationData animationData; @Override public void onSuccess(BVH bv) { bvh=bv; //bvh.setSkips(10); //bvh.setSkips(skipFrames); AnimationBoneConverter converter=new AnimationBoneConverter(); bones = converter.convertJsonBone(bvh); indexWeightEditor.setBones(bones); for(int i=0;i<bones.length();i++){ // log(i+":"+bones.get(i).getName()); } GWT.log("parsed"); /* for(int i=0;i<bones.length();i++){ Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.5, .5, .5), THREE.MeshLambertMaterial().color(0x0000ff).build()); scene.add(mesh); JsArrayNumber pos=bones.get(i).getPos(); mesh.setPosition(pos.get(0),pos.get(1),pos.get(2)); } */ AnimationDataConverter dataConverter=new AnimationDataConverter(); animationData = dataConverter.convertJsonAnimation(bones,bvh); animationName=animationData.getName(); JsArray<AnimationHierarchyItem> hitem=animationData.getHierarchy(); /* for(int i=0;i<hitem.length();i++){ AnimationHierarchyItem item=hitem.get(i); AnimationHierarchyItem parent=null; if(item.getParent()!=-1){ parent=hitem.get(item.getParent()); } AnimationKey key=item.getKeys().get(keyIndex); Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.5, .5, .5), THREE.MeshLambertMaterial().color(0x00ff00).build()); scene.add(mesh); Vector3 meshPos=AnimationUtils.getPosition(key); mesh.setPosition(meshPos); if(parent!=null){ Vector3 parentPos=AnimationUtils.getPosition(parent.getKeys().get(keyIndex)); Geometry lineG = THREE.Geometry(); lineG.vertices().push(THREE.Vertex(meshPos)); lineG.vertices().push(THREE.Vertex(parentPos)); Mesh line=THREE.Line(lineG, THREE.LineBasicMaterial().color(0xffffff).build()); scene.add(line); } Quaternion q=key.getRot(); Matrix4 rot=THREE.Matrix4(); rot.setRotationFromQuaternion(q); Vector3 rotV=THREE.Vector3(); rotV.setRotationFromMatrix(rot); mesh.setRotation(rotV); } */ /* Geometry cube=THREE.CubeGeometry(1, 1, 1); JsArray<Vector4> indices=(JsArray<Vector4>) JsArray.createArray(); JsArray<Vector4> weight=(JsArray<Vector4>) JsArray.createArray(); for(int i=0;i<cube.vertices().length();i++){ Vector4 v4=THREE.Vector4(); v4.set(0, 0, 0, 0); indices.push(v4); Vector4 v4w=THREE.Vector4(); v4w.set(1, 0, 0, 0); weight.push(v4w); } List<Vector3> parentPos=new ArrayList<Vector3>(); parentPos.add(THREE.Vector3()); for(int j=1;j<bones.length();j++){ Geometry cbone=THREE.CubeGeometry(1, 1, 1); AnimationBone ab=bones.get(j); Vector3 pos=AnimationBone.jsArrayToVector3(ab.getPos()); pos.addSelf(parentPos.get(ab.getParent())); parentPos.add(pos); Matrix4 m4=THREE.Matrix4(); m4.setPosition(pos); cbone.applyMatrix(m4); GeometryUtils.merge(cube, cbone); for(int i=0;i<cbone.vertices().length();i++){ Vector4 v4=THREE.Vector4(); v4.set(j, j, 0, 0); // v4.set(0, 0, 0, 0); indices.push(v4); Vector4 v4w=THREE.Vector4(); v4w.set(1, 0, 0, 0); weight.push(v4w); } } log("cube"); log(cube); cube.setSkinIndices(indices); cube.setSkinWeight(weight); cube.setBones(bones); */ final List<Vector3> bonePositions=new ArrayList<Vector3>(); for(int j=0;j<bones.length();j++){ AnimationBone bone=bones.get(j); Vector3 pos=AnimationBone.jsArrayToVector3(bone.getPos()); if(bone.getParent()!=-1){ pos.addSelf(bonePositions.get(bone.getParent())); } bonePositions.add(pos); } //overwrite same name AnimationHandler.add(animationData); //log(data); //log(bones); JSONArray array=new JSONArray(bones); //log(array.toString()); JSONObject test=new JSONObject(animationData); //log(test.toString()); root=THREE.Object3D(); scene.add(root); boneAndVertex = THREE.Object3D(); boneAndVertex.setPosition(-15, 0, 0); scene.add(boneAndVertex); Object3D bo=boneToSkelton(bones); //bo.setPosition(-30, 0, 0); boneAndVertex.add(bo); loadModel("miku.js", new LoadHandler() { //loader.load("men3smart.js", new LoadHandler() { @Override public void loaded(Geometry geometry) { // SubdivisionModifier modifier=THREE.SubdivisionModifier(3); // modifier.modify(geometry); log(geometry); for(int i=0;i<bones.length();i++){ if(bones.get(i).getParent()!=-1) log(bones.get(i).getName()+",parent="+bones.get(bones.get(i).getParent()).getName()); } //findIndex(geometry); //auto weight loadedGeometry=geometry; autoWeight(); //log(bodyIndices); //log(bodyWeight); createSkinnedMesh(); createWireBody(); } }); //log("before create"); //Mesh mesh=THREE.Mesh(cube, THREE.MeshLambertMaterial().skinning(false).color(0xff0000).build()); //log("create-mesh"); //scene.add(mesh); /* ColladaLoader loader=THREE.ColladaLoader(); loader.load("men3smart_hair.dae#1", new ColladaLoadHandler() { public void colladaReady(ColladaData collada) { rawCollada=collada; log(collada); boneNameMaps=new HashMap<String,Integer>(); for(int i=0;i<bones.length();i++){ boneNameMaps.put(bones.get(i).getName(), i); log(i+":"+bones.get(i).getName()); } Geometry geometry=collada.getGeometry(); colladaJoints=collada.getJoints(); Vector3 xup=THREE.Vector3(Math.toRadians(-90),0,0); Matrix4 mx=THREE.Matrix4(); mx.setRotationFromEuler(xup, "XYZ"); geometry.applyMatrix(mx); */ } @Override public void onFaild(String message) { log(message); } }); } private String animationName; private Geometry loadedGeometry; private void createWireBody(){ bodyGeometry=GeometryUtils.clone(loadedGeometry); Mesh wireBody=THREE.Mesh(bodyGeometry, THREE.MeshBasicMaterial().wireFrame(true).color(0xffffff).build()); boneAndVertex.add(wireBody); selectVertex=THREE.Object3D(); vertexs.clear(); boneAndVertex.add(selectVertex); Geometry cube=THREE.CubeGeometry(.3, .3, .3); Material mt=THREE.MeshBasicMaterial().color(0xffff00).build(); for(int i=0;i<bodyGeometry.vertices().length();i++){ Vector3 vx=bodyGeometry.vertices().get(i).getPosition(); Mesh point=THREE.Mesh(cube, mt); point.setVisible(false); point.setName("point:"+i); point.setPosition(vx); selectVertex.add(point); vertexs.add(point); } } private void autoWeight(){ bodyIndices = (JsArray<Vector4>) JsArray.createArray(); bodyWeight = (JsArray<Vector4>) JsArray.createArray(); WeightBuilder.autoWeight(loadedGeometry, bones, WeightBuilder.MODE_NearParentAndChildren, bodyIndices, bodyWeight); } private void loadJsonModel(String jsonText,LoadHandler handler){ JSONLoader loader=THREE.JSONLoader(); JSONValue jsonValue=JSONParser.parseLenient(jsonText); JSONObject object=jsonValue.isObject(); if(object==null){ log("invalid-json object"); } log(object.getJavaScriptObject()); loader.createModel(object.getJavaScriptObject(), handler, ""); loader.onLoadComplete(); } private void loadModel(String path,final LoadHandler handler){ RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(path)); try { builder.sendRequest(null, new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { loadJsonModel(response.getText(),handler); } @Override public void onError(Request request, Throwable exception) { Window.alert("load faild:"); } }); } catch (RequestException e) { log(e.getMessage()); e.printStackTrace(); } } private void createSkinnedMesh(){ Geometry newgeo=GeometryUtils.clone(loadedGeometry); newgeo.setSkinIndices(bodyIndices); newgeo.setSkinWeight(bodyWeight); newgeo.setBones(bones); if(skinnedMesh!=null){ root.remove(skinnedMesh); } Material material=null; if(useBasicMaterial.getValue()){ material=THREE.MeshBasicMaterial().skinning(true).color(0xffffff).map(ImageUtils.loadTexture("men3smart_underware_texture.png")).build(); }else{ material=THREE.MeshLambertMaterial().skinning(true).color(0xffffff).map(ImageUtils.loadTexture("men3smart_underware_texture.png")).build(); } skinnedMesh = THREE.SkinnedMesh(newgeo, material); root.add(skinnedMesh); if(animation!=null){ AnimationHandler.removeFromUpdate(animation); } animation = THREE.Animation( skinnedMesh, animationName ); animation.play(true,currentTime); } private List<Mesh> vertexs=new ArrayList<Mesh>(); private IndexAndWeightEditor indexWeightEditor; //simple simple near positions only use end point,this is totall not good private int findNear(List<Vector3> bonePositions,Vector3 pos){ Vector3 pt=THREE.Vector3(); Vector3 near=pt.sub(bonePositions.get(0),pos); int index=0; double length=pt.length(); for(int i=1;i<bonePositions.size();i++){ Vector3 npt=THREE.Vector3(); near=npt.sub(bonePositions.get(i),pos); double l=near.length(); if(l<length){ index=i; length=l; } } return index; } private Map<Integer,Integer> createChildMap(JsArray<AnimationBone> bones){ Map<Integer,Integer> childMap=new HashMap<Integer,Integer>(); for(int i=0;i<bones.length();i++){ List<Integer> children=new ArrayList<Integer>(); for(int j=0;j<bones.length();j++){ AnimationBone child=bones.get(j); if(child.getParent()==i){ children.add(j); } } if(children.size()==1){ childMap.put(i, children.get(0)); } } return childMap; } List<List<GWTWeightData>> wdatas; /* * some point totally wrong?or only work on multiple weight points * */ JsArrayString colladaJoints; Map<String,Integer> boneNameMaps; private CheckBox useBasicMaterial; private Vector4 convertWeight(int index,ColladaData collada){ if(wdatas==null){ //wdatas=new WeighDataParser().parse(Bundles.INSTANCE.weight().getText()); wdatas=new WeighDataParser().convert(collada.getWeights()); for(List<GWTWeightData> wd:wdatas){ String log=""; for(GWTWeightData w:wd){ log+=w.getBoneIndex()+":"+w.getWeight()+","; } //log(log); } } List<GWTWeightData> wd=wdatas.get(index); if(wd.size()<2){ int id=wd.get(0).getBoneIndex(); String fname=colladaJoints.get(id); id=boneNameMaps.get(fname); return THREE.Vector4(id,id,1,0); }else{ int fid=wd.get(0).getBoneIndex(); int sid=wd.get(1).getBoneIndex(); String fname=colladaJoints.get(fid); fid=boneNameMaps.get(fname); String sname=colladaJoints.get(sid); sid=boneNameMaps.get(sname); double fw=wd.get(0).getWeight(); double sw=wd.get(1).getWeight(); //log(fid+":"+fw+","+sid+":"+sw); //fw=1; return THREE.Vector4(fid,sid,fw,sw); } } private Vector4 findNearSpecial(List<NameAndPosition> nameAndPositions,Vector3 pos,JsArray<AnimationBone> bones,int vindex){ Vector3 pt=nameAndPositions.get(0).getPosition().clone(); Vector3 near=pt.subSelf(pos); int index1=nameAndPositions.get(0).getIndex(); double near1=near.length(); int index2=index1; double near2=near1; int nameIndex1=0; int nameIndex2=0; for(int i=1;i<nameAndPositions.size();i++){ Vector3 npt=nameAndPositions.get(i).getPosition().clone(); Vector3 subPos=npt.subSelf(pos); double l=subPos.length(); //if(vindex==250)log(nameAndPositions.get(i).getName()+","+l); if(l<near1){ int tmp=index1; double tmpL=near1; int tmpName=nameIndex1; index1=nameAndPositions.get(i).getIndex(); near1=l; nameIndex1=i; if(tmpL<near2){ index2=tmp; near2=tmpL; nameIndex2=tmpName; } }else if(l<near2){ index2=nameAndPositions.get(i).getIndex(); near2=l; nameIndex2=i; } } Map<Integer,Double> totalLength=new HashMap<Integer,Double>(); Map<Integer,Integer> totalIndex=new HashMap<Integer,Integer>(); //zero is largest Vector3 rootNear=nameAndPositions.get(0).getPosition().clone(); rootNear.subSelf(pos); for(int i=0;i<nameAndPositions.size();i++){ int index=nameAndPositions.get(i).getIndex(); Vector3 nearPos=nameAndPositions.get(i).getPosition().clone(); nearPos.subSelf(pos); double l=nearPos.length(); Double target=totalLength.get(index); double cvalue=0; if(target!=null){ cvalue=target.doubleValue(); } cvalue+=l; totalLength.put(index,cvalue); Integer count=totalIndex.get(index); int countV=0; if(count!=null){ countV=count; } countV++; totalIndex.put(index, countV); } //do average for end like head Integer[] keys=totalLength.keySet().toArray(new Integer[0]); for(int i=0;i<keys.length;i++){ int index=keys[i]; int count=totalIndex.get(index); totalLength.put(index, totalLength.get(index)/count); } if(index1==index2){ log(""+vindex+","+nameIndex1+":"+nameIndex2); if(vindex==250){ // log(nameAndPositions.get(nameIndex1).getPosition()); // log(nameAndPositions.get(nameIndex2).getPosition()); } return THREE.Vector4(index1,index1,1,0); }else{ double near1Length=totalLength.get(index1); double near2Length=totalLength.get(index2); double total=near1Length+near2Length; return THREE.Vector4(index1,index2,(total-near1Length)/total,(total-near2Length)/total); } } private Vector4 findNearThreeBone(List<NameAndPosition> nameAndPositions,Vector3 pos,JsArray<AnimationBone> bones,int vindex){ Map<Integer,Double> totalLength=new HashMap<Integer,Double>(); Map<Integer,Integer> totalIndex=new HashMap<Integer,Integer>(); log("find-near:"+vindex); for(int i=0;i<nameAndPositions.size();i++){ int index=nameAndPositions.get(i).getIndex(); Vector3 near=nameAndPositions.get(i).getPosition().clone(); near.subSelf(pos); double l=near.length(); Double target=totalLength.get(index); double cvalue=0; if(target!=null){ cvalue=target.doubleValue(); } cvalue+=l; totalLength.put(index,cvalue); Integer count=totalIndex.get(index); int countV=0; if(count!=null){ countV=count; } countV++; totalIndex.put(index, countV); } Integer[] keys=totalLength.keySet().toArray(new Integer[0]); for(int i=0;i<keys.length;i++){ int index=keys[i]; int count=totalIndex.get(index); totalLength.put(index, totalLength.get(index)/count); } int index1=0; double near1=totalLength.get(keys[0]); int index2=0; double near2=totalLength.get(keys[0]); for(int i=1;i<keys.length;i++){ double l=totalLength.get(keys[i]); if(l<near1){ int tmp=index1; double tmpL=near1; index1=keys[i]; near1=l; if(tmpL<near2){ index2=tmp; near2=tmpL; } }else if(l<near2){ index2=keys[i]; near2=l; } } if(index1==index2){ return THREE.Vector4(index1,index1,1,0); }else{ double total=near1+near2; log("xx:"+index1+","+index2); return THREE.Vector4(index1,index2,(total-near1)/total,(total-near2)/total); } } //use start,center and end position,choose near 2point private Vector4 findNearBoneAggresive(List<NameAndPosition> nameAndPositions,Vector3 pos,JsArray<AnimationBone> bones){ Vector3 pt=nameAndPositions.get(0).getPosition().clone(); Vector3 near=pt.subSelf(pos); int index1=nameAndPositions.get(0).getIndex(); double near1=pt.length(); int index2=nameAndPositions.get(0).getIndex(); double near2=pt.length(); for(int i=1;i<nameAndPositions.size();i++){ Vector3 npt=nameAndPositions.get(i).getPosition().clone(); near=npt.subSelf(pos); double l=near.length(); if(l<near1){ int tmp=index1; double tmpL=near1; index1=nameAndPositions.get(i).getIndex(); near1=l; if(tmpL<near2){ index2=tmp; near2=tmpL; } }else if(l<near2){ index2=nameAndPositions.get(i).getIndex(); near2=l; } } near1*=near1*near1*near1; near2*=near2*near2*near2; if(index1==index2){ return THREE.Vector4(index1,index1,1,0); }else{ double total=near1+near2; return THREE.Vector4(index1,index2,(total-near1)/total,(total-near2)/total); } } /* * find near ,but from three point */ private Vector4 findNearSingleBone(List<NameAndPosition> nameAndPositions,Vector3 pos,JsArray<AnimationBone> bones){ Vector3 pt=nameAndPositions.get(0).getPosition().clone(); Vector3 near=pt.subSelf(pos); int index1=nameAndPositions.get(0).getIndex(); double near1=pt.length(); for(int i=1;i<nameAndPositions.size();i++){ Vector3 npt=nameAndPositions.get(i).getPosition().clone(); near=npt.subSelf(pos); double l=near.length(); if(l<near1){ index1=nameAndPositions.get(i).getIndex(); near1=l; } } return THREE.Vector4(index1,index1,1,0); } //find neard point,choose second from parent or children which near than private Vector4 findNearParentAndChildren(List<Vector3> bonePositions, Vector3 pos,JsArray<AnimationBone> bones){ Map<Integer,Integer> cm=createChildMap(bones); Vector3 pt=THREE.Vector3(); Vector3 near=pt.sub(bonePositions.get(0),pos); int index=0; double length=pt.length(); for(int i=1;i<bonePositions.size();i++){ Vector3 npt=THREE.Vector3(); near=npt.sub(bonePositions.get(i),pos); double l=near.length(); if(l<length){ index=i; length=l; } } if(index!=0){ Vector3 parentPt=THREE.Vector3(); int parentIndex=bones.get(index).getParent(); parentPt=parentPt.sub(bonePositions.get(parentIndex),pos); double plength=parentPt.length(); Integer child=cm.get(index); if(child!=null){ Vector3 childPt=THREE.Vector3(); childPt=childPt.sub(bonePositions.get(child),pos); double clength=childPt.length(); if(clength<plength){ double total=length+clength; return THREE.Vector4(index,child,(total-length)/total,(total-clength)/total); }else{ double total=length+plength; return THREE.Vector4(index,parentIndex,(total-length)/total,(total-plength)/total); } }else{ double total=length+plength; return THREE.Vector4(index,parentIndex,(total-length)/total,(total-plength)/total); } }else{ return THREE.Vector4(index,index,1,0);//root } } /* * find near and choose parent */ private Vector4 findNearParent(List<Vector3> bonePositions, Vector3 pos,JsArray<AnimationBone> bones){ Vector3 pt=THREE.Vector3(); Vector3 near=pt.sub(bonePositions.get(0),pos); int index=0; double length=pt.length(); for(int i=1;i<bonePositions.size();i++){ Vector3 npt=THREE.Vector3(); near=npt.sub(bonePositions.get(i),pos); double l=near.length(); if(l<length){ index=i; length=l; } } if(index!=0){ Vector3 parentPt=THREE.Vector3(); int parentIndex=bones.get(index).getParent(); parentPt=parentPt.sub(bonePositions.get(parentIndex),pos); double plength=parentPt.length(); double total=length+plength; return THREE.Vector4(index,parentIndex,(total-length)/total,(total-plength)/total); }else{ return THREE.Vector4(index,index,1,0);//root } } //choose two point but only near about first * value private Vector4 findNearDouble(List<Vector3> bonePositions, Vector3 pos,double value){ Vector3 pt=THREE.Vector3(); Vector3 near=pt.sub(bonePositions.get(0),pos); int index1=0; double near1=pt.length(); int index2=0; double near2=pt.length(); for(int i=1;i<bonePositions.size();i++){ Vector3 npt=THREE.Vector3(); near=npt.sub(bonePositions.get(i),pos); double l=near.length(); if(l<near1){ int tmp=index1; double tmpL=near1; index1=i; near1=l; if(tmpL<near2){ index2=tmp; near2=tmpL; } }else if(l<near2){ index2=i; near2=l; } } if(index1==index2){ return THREE.Vector4(index1,index1,1,0); }else if(near2>near1*value){ //too fa near2 return THREE.Vector4(index1,index1,1,0); }else{ double total=near1+near2; return THREE.Vector4(index1,index2,near1/total,near2/total); } } }
package org.demo.controller; import static org.junit.Assert.*; import static org.hamcrest.Matchers.equalTo; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.demo.Application; import org.demo.service.PersonService; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @RunWith(SpringJUnit4ClassRunner.class) //@SpringApplicationConfiguration(classes = MockServletContext.class) @SpringApplicationConfiguration(classes=Application.class) @WebAppConfiguration public class PersonControllerTest { private MockMvc mvc; @Autowired private PersonService personService; @BeforeClass public static void setUpBeforeClass() throws Exception { } @Before public void setUp() throws Exception { mvc = MockMvcBuilders.standaloneSetup(new PersonController(personService)).build(); } @After public void tearDown() throws Exception { } @Test public void testCreate() { fail("Not yet implemented"); } @Test public void testDelete() { fail("Not yet implemented"); } @Test public void testFindAll() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/api/person").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8")); } @Test public void testFindById() { fail("Not yet implemented"); } @Test public void testUpdate() { fail("Not yet implemented"); } }
package org.wings.plaf.css; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wings.*; import org.wings.border.SDefaultBorder; import org.wings.border.SEmptyBorder; import org.wings.dnd.DragSource; import org.wings.dnd.DropTarget; import org.wings.io.Device; import org.wings.io.StringBuilderDevice; import org.wings.plaf.*; import org.wings.plaf.css.dwr.CallableManager; import org.wings.plaf.css.script.OnPageRenderedScript; import org.wings.script.ScriptListener; import org.wings.session.BrowserType; import org.wings.session.ScriptManager; import org.wings.util.SessionLocal; import java.io.IOException; import java.io.Serializable; import java.util.List; import java.util.Map; /** * Partial CG implementation that is common to all ComponentCGs. * * @author <a href="mailto:engels@mercatis.de">Holger Engels</a> */ public abstract class AbstractComponentCG<COMPONENT_TYPE extends SComponent> implements ComponentCG<COMPONENT_TYPE>, SConstants, Serializable { private static final Log log = LogFactory.getLog(AbstractComponentCG.class); /** * An invisible icon / graphic (spacer graphic) */ private static final SIcon BLIND_ICON = new SResourceIcon("org/wings/icons/blind.gif"); /** * Be careful with this shared StringBuilder. Don't use it in situations where unknown code is called, that might * use the StringBuilder, too. */ public static final SessionLocal<StringBuilder> STRING_BUILDER = new SessionLocal<StringBuilder>() { protected StringBuilder initialValue() { return new StringBuilder(); } }; protected AbstractComponentCG() { } /** * Renders the default HTML TABLE prefix code for a component. This prefix will handle * <ul> * <li>All CSS Attrbiutes declared on the SComponent</li> * <li>Components CSS class</li> * <li>Components id</li> * <li>Borders and insets (only if TABLE is used)</li> * <li>Components ToolTip hooks</li> * <li>Components Popup menu hooks</li> * <li>components event id <code>eid</code> </li> * </ul> * * @param device The output device to use * @param component The component to render * @throws IOException on error on the output device */ protected final void writeTablePrefix(Device device, COMPONENT_TYPE component) throws IOException { writePrefix(device, component, true, null); } /** * Renders the default HTML TABLE prefix code for a component. This prefix will handle * <ul> * <li>All CSS Attrbiutes declared on the SComponent</li> * <li>Components CSS class</li> * <li>Components id</li> * <li>Borders and insets (only if TABLE is used)</li> * <li>Components ToolTip hooks</li> * <li>Components Popup menu hooks</li> * <li>components event id <code>eid</code> </li> * </ul> * * @param device The output device to use * @param component The component to render * @throws IOException on error on the output device */ protected final void writeTablePrefix(Device device, COMPONENT_TYPE component, Map optionalAttributes) throws IOException { writePrefix(device, component, true, optionalAttributes); } /** * Renders the closing suffix for a TABLE based component prefix. * @param device The output device to use * @param component The component to render * @throws IOException on error on the output device */ protected final void writeTableSuffix(Device device, COMPONENT_TYPE component) throws IOException { writeSuffix(device, component, true); } /** * Renders a DIV prefix code for a component. <b>Discouraged</b> * This prefix will handle * <ul> * <li>All CSS Attrbiutes declared on the SComponent</li> * <li>Components CSS class</li> * <li>Components id</li> * <li>Borders and insets (only if TABLE is used)</li> * <li>Components ToolTip hooks</li> * <li>Components Popup menu hooks</li> * <li>components event id <code>eid</code> </li> * </ul> * * @param device The output device to use * @param component The component to render * @param optionalAttributes A map of additional CSS attributes * @throws IOException on error on the output device */ protected final void writeDivPrefix(Device device, COMPONENT_TYPE component, Map optionalAttributes) throws IOException { writePrefix(device, component, false, optionalAttributes); } /** * Renders the closing suffix for a DIV prefix. * @param device The output device to use * @param component The component to render * @throws IOException on error on the output device */ protected final void writeDivSuffix(Device device, COMPONENT_TYPE component) throws IOException { writeSuffix(device, component, false); } /** * Renders the HTML prefix code for a component. This prefix will handle * <ul> * <li>All CSS Attrbiutes declared on the SComponent</li> * <li>Components CSS class</li> * <li>Components id</li> * <li>Borders and insets (only if TABLE is used)</li> * <li>Components ToolTip hooks</li> * <li>Components Popup menu hooks</li> * <li>components event id <code>eid</code> </li> * </ul> * * @param device The output device to use * @param component The component to render * @param useTable <code>true</code> if it should be wrapped into a <code>TABLE</code> element <b>(recommended!)</b> or a <code>DIV</code> * @param optionalAttributes A map of additional CSS attributes * @throws IOException on error on the output device */ protected final void writePrefix(final Device device, final COMPONENT_TYPE component, final boolean useTable, Map optionalAttributes) throws IOException { // This is the containing element of a component // it is responsible for styles, sizing... if (useTable) { device.print("<table"); // table } else { device.print("<div"); // div } // We cant render this here. // Utils.writeEvents(device, component, null); Utils.writeAllAttributes(device, component); // Render the optional attributes. Utils.optAttributes(device, optionalAttributes); if (useTable) { device.print("><tr><td"); // table if (component.getBorder() != null) { Utils.printInlineStylesForInsets(device, component.getBorder().getInsets()); } device.print('>'); // table } else { device.print('>'); // div } } protected final void writeSuffix(Device device, COMPONENT_TYPE component, boolean useTable) throws IOException { if (useTable) { device.print("</td></tr></table>"); } else { device.print("</div>"); } } /** * Write JS code for context menus. Common implementaton for MSIE and gecko. * @deprecated use {@link Utils#writeContextMenu(Device, SComponent)} */ protected static void writeContextMenu(Device device, SComponent component) throws IOException { Utils.writeContextMenu(device, component); } /** * Write Tooltip code. * @deprecated use {@link Utils#writeTooltipMouseOver(Device, SComponent)} */ protected static void writeTooltipMouseOver(Device device, SComponent component) throws IOException { Utils.writeTooltipMouseOver(device, component); } /** * Install the appropriate CG for <code>component</code>. * * @param component the component */ public void installCG(COMPONENT_TYPE component) { Class clazz = component.getClass(); while (clazz.getPackage() == null || !("org.wings".equals(clazz.getPackage().getName()) || "org.wingx".equals(clazz.getPackage().getName()))) clazz = clazz.getSuperclass(); String style = clazz.getName(); style = style.substring(style.lastIndexOf('.') + 1); component.setStyle(style); // set default style name to component class (ie. SLabel). component.setBorder(SDefaultBorder.INSTANCE); // the default style writes _no_ attributes, thus the stylesheet is in effect if (Utils.isMSIE(component)) { final CGManager manager = component.getSession().getCGManager(); Object value; int verticalOversize = 0; value = manager.getObject(style + ".verticalOversize", Integer.class); if (value != null) verticalOversize = ((Integer) value).intValue(); int horizontalOversize = 0; value = manager.getObject(style + ".horizontalOversize", Integer.class); if (value != null) horizontalOversize = ((Integer) value).intValue(); if (verticalOversize != 0 || horizontalOversize != 0) component.putClientProperty("oversize", new SEmptyBorder(verticalOversize, horizontalOversize, verticalOversize, horizontalOversize)); } } /** * Uninstall the CG from <code>component</code>. * * @param component the component */ public void uninstallCG(COMPONENT_TYPE component) { } /** * Retrieve a empty blind icon. * @return A empty blind icon. */ protected final SIcon getBlindIcon() { return BLIND_ICON; } public void componentChanged(COMPONENT_TYPE component) { /* InputMap inputMap = component.getInputMap(); if (inputMap != null && inputMap.size() > 0) { if (!(inputMap instanceof VersionedInputMap)) { inputMap = new VersionedInputMap(inputMap); component.setInputMap(inputMap); } final VersionedInputMap versionedInputMap = (VersionedInputMap) inputMap; final Integer inputMapVersion = (Integer) component.getClientProperty("inputMapVersion"); if (inputMapVersion == null || versionedInputMap.getVersion() != inputMapVersion.intValue()) { //InputMapScriptListener.install(component); component.putClientProperty("inputMapVersion", new Integer(versionedInputMap.getVersion())); } } */ // Add script listener support. List scriptListenerList = component.getScriptListenerList(); if (scriptListenerList != null && !scriptListenerList.isEmpty()) { { /* TODO: this code destroys the dwr functionality List removeCallables = new ArrayList(); // Remove all existing - and maybe unusable - DWR script listeners. for (Iterator iter = CallableManager.getInstance().callableNames().iterator(); iter.hasNext();) { Object o = iter.next(); if (o instanceof String) { removeCallables.add(o); } } for (Iterator iter = removeCallables.iterator(); iter.hasNext(); ) { Object o = iter.next(); if (o instanceof String) { CallableManager.getInstance().unregisterCallable((String) o); } } */ // Add DWR script listener support. ScriptListener[] scriptListeners = component.getScriptListeners(); for (ScriptListener scriptListener1 : scriptListeners) { if (scriptListener1 instanceof DWRScriptListener) { DWRScriptListener scriptListener = (DWRScriptListener) scriptListener1; CallableManager.getInstance().registerCallable(scriptListener.getCallableName(), scriptListener.getCallable()); } } //component.putClientProperty("scriptListenerListVersion", new Integer(versionedList.getVersion())); } } } /** * This method renders the component (and all of its subcomponents) to the given device. */ public final void write(final Device device, final COMPONENT_TYPE component) throws IOException { Utils.printDebug(device, "<! Utils.printDebug(device, component.getName()); Utils.printDebug(device, " component.fireRenderEvent(SComponent.START_RENDERING); try { BorderCG.writeComponentBorderPrefix(device, component); writeInternal(device, component); ScriptManager.getInstance().addScriptListeners(component.getScriptListeners()); BorderCG.writeComponentBorderSufix(device, component); } catch (RuntimeException e) { log.fatal("Runtime exception during rendering of " + component.getName(), e); device.print("<blink>" + e.getClass().getName() + " during code generation of " + component.getName() + "(" + component.getClass().getName() + ")</blink>\n"); } component.fireRenderEvent(SComponent.DONE_RENDERING); Utils.printDebug(device, "<! Utils.printDebug(device, component.getName()); Utils.printDebug(device, " updateDragAndDrop(component); } protected void updateDragAndDrop(final SComponent component) { if (component instanceof DragSource && ((DragSource)component).isDragEnabled()) { StringBuilder builder = STRING_BUILDER.get(); builder.setLength(0); String name = component.getName(); builder.append("var ds_"); builder.append(name); builder.append(" = new wingS.dnd.DD(\""); builder.append(name); builder.append("\");"); writeRegisterDragHandle(builder, component); builder.append("\n"); ScriptManager.getInstance().addScriptListener(new OnPageRenderedScript(builder.toString())); } if (component instanceof DropTarget) { StringBuilder builder = STRING_BUILDER.get(); builder.setLength(0); String name = component.getName(); builder.append("var dt_"); builder.append(name); builder.append(" = new YAHOO.util.DDTarget(\""); builder.append(name); builder.append("\");\n"); ScriptManager.getInstance().addScriptListener(new OnPageRenderedScript(builder.toString())); } } protected void writeRegisterDragHandle(StringBuilder builder, SComponent component) { String dragHandle = getDragHandle(component); if (dragHandle != null) { String name = component.getName(); builder.append("ds_"); builder.append(name); builder.append(".setHandleElId(\""); builder.append(dragHandle); builder.append("\");"); } } protected String getDragHandle(SComponent component) { return null; } public abstract void writeInternal(Device device, COMPONENT_TYPE component) throws IOException; /** * @return true if current browser is Microsoft Internet Explorer */ protected final boolean isMSIE(final SComponent component) { return component.getSession().getUserAgent().getBrowserType() == BrowserType.IE; } public Update getComponentUpdate(COMPONENT_TYPE component) { updateDragAndDrop(component); return new ComponentUpdate(this, component); } protected static class ComponentUpdate<COMPONENT_TYPE extends SComponent> extends AbstractUpdate<COMPONENT_TYPE> { private final AbstractComponentCG<COMPONENT_TYPE> cg; public ComponentUpdate(AbstractComponentCG<COMPONENT_TYPE> cg, COMPONENT_TYPE component) { super(component); this.cg = cg; } @Override public int getProperty() { return FULL_REPLACE_UPDATE; } @Override public int getPriority() { return 4; } @Override public Handler getHandler() { String htmlCode = ""; String exception = null; try { StringBuilderDevice htmlDevice = new StringBuilderDevice(1024); cg.write(htmlDevice, component); htmlCode = htmlDevice.toString(); } catch (Throwable t) { log.fatal("An error occured during rendering", t); exception = t.getClass().getName(); } UpdateHandler handler = new UpdateHandler("component"); handler.addParameter(component.getName()); handler.addParameter(htmlCode); if (exception != null) { handler.addParameter(exception); } return handler; } } }
package org.wisdom.api.router; import org.wisdom.api.Controller; import org.wisdom.api.http.HttpMethod; import java.util.Collection; import java.util.Map; /** * The router service interface. */ public interface Router { Route getRouteFor(HttpMethod method, String uri); Route getRouteFor(String method, String uri); String getReverseRouteFor(Class<? extends Controller> clazz, String method, Map<String, Object> params); String getReverseRouteFor(String className, String method, Map<String, Object> params); String getReverseRouteFor(String className, String method); String getReverseRouteFor(Controller controller, String method, Map<String, Object> params); String getReverseRouteFor(Class<? extends Controller> clazz, String method); String getReverseRouteFor(Controller controller, String method); Collection<Route> getRoutes(); // Method avoiding using maps in controllers. String getReverseRouteFor(Controller controller, String method, String var1, Object val1); String getReverseRouteFor(Controller controller, String method, String var1, Object val1, String var2, Object val2); String getReverseRouteFor(Controller controller, String method, String var1, Object val1, String var2, Object val2, String var3, Object val3); String getReverseRouteFor(Controller controller, String method, String var1, Object val1, String var2, Object val2, String var3, Object val3, String var4, Object val4); String getReverseRouteFor(Controller controller, String method, String var1, Object val1, String var2, Object val2, String var3, Object val3, String var4, Object val4, String var5, Object val5); String getReverseRouteFor(Class<? extends Controller> clazz, String method, String var1, Object val1); String getReverseRouteFor(Class<? extends Controller> clazz, String method, String var1, Object val1, String var2, Object val2); String getReverseRouteFor(Class<? extends Controller> clazz, String method, String var1, Object val1, String var2, Object val2, String var3, Object val3); String getReverseRouteFor(Class<? extends Controller> clazz, String method, String var1, Object val1, String var2, Object val2, String var3, Object val3, String var4, Object val4); String getReverseRouteFor(Class<? extends Controller> clazz, String method, String var1, Object val1, String var2, Object val2, String var3, Object val3, String var4, Object val4, String var5, Object val5); }
package com.gulshansingh.hackerlivewallpaper; import static com.gulshansingh.hackerlivewallpaper.SettingsFragment.KEY_BIT_COLOR; import static com.gulshansingh.hackerlivewallpaper.SettingsFragment.KEY_CHANGE_BIT_SPEED; import static com.gulshansingh.hackerlivewallpaper.SettingsFragment.KEY_FALLING_SPEED; import static com.gulshansingh.hackerlivewallpaper.SettingsFragment.KEY_NUM_BITS; import static com.gulshansingh.hackerlivewallpaper.SettingsFragment.KEY_TEXT_SIZE; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.holoeverywhere.preference.PreferenceManager; import org.holoeverywhere.preference.SharedPreferences; import android.content.Context; import android.content.res.Resources; import android.graphics.BlurMaskFilter; import android.graphics.BlurMaskFilter.Blur; import android.graphics.Canvas; import android.graphics.Paint; import com.gulshansingh.hackerlivewallpaper.thirdparty.ArrayDeque; /** * A class that stores a list of bits. The first bit is removed and a new bit is * appended at a fixed interval. Calling the draw method of displays the bit * sequence vertically on the screen. Every time a bit is changed, the position * of the sequence on the screen will be shifted downward. Moving past the * bottom of the screen will cause the sequence to be placed above the screen * * @author Gulshan Singh */ public class BitSequence { /** The Mask to use for blurred text */ private static final BlurMaskFilter blurFilter = new BlurMaskFilter(3, Blur.NORMAL); /** The Mask to use for slightly blurred text */ private static final BlurMaskFilter slightBlurFilter = new BlurMaskFilter( 2, Blur.NORMAL); /** The Mask to use for regular text */ private static final BlurMaskFilter regularFilter = null; /** The height of the screen */ private static int HEIGHT; /** The bits this sequence stores */ private ArrayDeque<String> bits = new ArrayDeque<String>(); /** A variable used for all operations needing random numbers */ private Random r = new Random(); /** The scheduled operation for changing a bit and shifting downwards */ private ScheduledFuture<?> future; /** The position to draw the sequence at on the screen */ float x, y; /** True when the BitSequence should be paused */ private boolean pause = false; private static final ScheduledExecutorService scheduler = Executors .newSingleThreadScheduledExecutor(); /** The characters to use in the sequence */ private static final String[] symbols = { "0", "1" }; /** Describes the style of the sequence */ private final Style style = new Style(); public static class Style { /** The default speed at which bits should be changed */ private static final int DEFAULT_CHANGE_BIT_SPEED = 100; /** The maximum alpha a bit can have */ private static final int MAX_ALPHA = 240; private static int changeBitSpeed; private static int numBits; private static int color; private static int defaultTextSize; private static int defaultFallingSpeed; private static int alphaIncrement; private static int initialY; private int textSize; private int fallingSpeed; private BlurMaskFilter maskFilter; private Paint paint = new Paint(); public static void initParameters(Context context) { PreferenceUtility preferences = new PreferenceUtility(context); numBits = preferences.getInt(KEY_NUM_BITS, R.integer.default_num_bits); color = preferences .getInt(KEY_BIT_COLOR, R.color.default_bit_color); defaultTextSize = preferences.getInt(KEY_TEXT_SIZE, R.integer.default_text_size); double changeBitSpeedMultiplier = 100 / preferences.getDouble( KEY_CHANGE_BIT_SPEED, R.integer.default_change_bit_speed); double fallingSpeedMultiplier = preferences.getDouble( KEY_FALLING_SPEED, R.integer.default_falling_speed) / 100; changeBitSpeed = (int) (DEFAULT_CHANGE_BIT_SPEED * changeBitSpeedMultiplier); defaultFallingSpeed = (int) (defaultTextSize * fallingSpeedMultiplier); alphaIncrement = MAX_ALPHA / numBits; initialY = -1 * defaultTextSize * numBits; } public Style() { paint.setColor(color); } public void createPaint() { paint.setTextSize(textSize); paint.setMaskFilter(maskFilter); } private static class PreferenceUtility { private SharedPreferences preferences; private Resources res; public PreferenceUtility(Context context) { preferences = PreferenceManager .getDefaultSharedPreferences(context); res = context.getResources(); } public int getInt(String key, int defaultId) { return preferences.getInt(key, res.getInteger(defaultId)); } public double getDouble(String key, int defaultId) { return (double) preferences.getInt(key, res.getInteger(defaultId)); } } } /** * Resets the sequence by repositioning it, reseting its visual * characteristics, and rescheduling the thread */ private void reset() { y = Style.initialY; setDepth(); style.createPaint(); scheduleThread(); } /** * A runnable that changes the bit, moves the sequence down, and reschedules * its execution */ private final Runnable changeBitRunnable = new Runnable() { public void run() { changeBit(); y += style.fallingSpeed; if (y > HEIGHT) { reset(); } } }; private void setDepth() { double factor = r.nextDouble() * (1 - .8) + .8; style.textSize = (int) (Style.defaultTextSize * factor); style.fallingSpeed = (int) (Style.defaultFallingSpeed * Math.pow( factor, 4)); if (factor > .93) { style.maskFilter = regularFilter; } else if (factor <= .93 && factor >= .87) { style.maskFilter = slightBlurFilter; } else { style.maskFilter = blurFilter; } } /** * Configures any BitSequences parameters requiring the application context * * @param context * the application context */ public static void configure(Context context) { Style.initParameters(context); } /** * Configures the BitSequence based on the display * * @param width * the width of the screen * @param height * the height of the screen */ public static void setScreenDim(int width, int height) { HEIGHT = height; } public BitSequence(int x) { for (int i = 0; i < Style.numBits; i++) { bits.add(getRandomBit(r)); } this.x = x; reset(); } /** * Pauses the BitSequence by cancelling the ScheduledFuture */ public void pause() { if (!pause) { if (future != null) { future.cancel(true); } pause = true; } } public void stop() { pause(); } /** * Unpauses the BitSequence by scheduling BitSequences on the screen to * immediately start, and scheduling BitSequences off the screen to start * after some delay */ public void unpause() { if (pause) { if (y <= Style.initialY + style.textSize || y > HEIGHT) { scheduleThread(); } else { scheduleThread(0); } pause = false; } } /** * Schedules the changeBitRunnable with a random delay less than 6000 * milliseconds, cancelling the previous scheduled future */ private void scheduleThread() { scheduleThread(r.nextInt(6000)); } /** * Schedules the changeBitRunnable with the specified delay, cancelling the * previous scheduled future * * @param delay * the delay in milliseconds */ private void scheduleThread(int delay) { if (future != null) future.cancel(true); future = scheduler.scheduleAtFixedRate(changeBitRunnable, delay, Style.changeBitSpeed, TimeUnit.MILLISECONDS); } /** Shifts the bits back by one and adds a new bit to the end */ synchronized private void changeBit() { bits.removeFirst(); bits.addLast(getRandomBit(r)); } /** * Gets a new random bit * * @param r * the {@link Random} object to use * @return A new random bit as a {@link String} */ private String getRandomBit(Random r) { return symbols[r.nextInt(symbols.length)]; } /** * Gets the width the BitSequence would be on the screen * * @return the width of the BitSequence */ public static float getWidth() { Paint paint = new Paint(); paint.setTextSize(Style.defaultTextSize); return paint.measureText("0"); } /** * Draws this BitSequence on the screen * * @param canvas * the {@link Canvas} on which to draw the BitSequence */ synchronized public void draw(Canvas canvas) { // TODO Can the get and set alphas be optimized? Paint paint = style.paint; float bitY = y; paint.setAlpha(Style.alphaIncrement); for (int i = 0; i < bits.size(); i++) { canvas.drawText(bits.get(i), x, bitY, paint); bitY += style.textSize; paint.setAlpha(paint.getAlpha() + Style.alphaIncrement); } } }
package org.owasp.esapi.reference; import java.io.IOException; import java.util.Arrays; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.owasp.esapi.ESAPI; import org.owasp.esapi.Logger; import org.owasp.esapi.errors.AuthenticationException; import org.owasp.esapi.errors.ValidationException; import org.owasp.esapi.http.MockHttpServletRequest; import org.owasp.esapi.http.MockHttpServletResponse; /** * The Class LoggerTest. * * @author Jeff Williams (jeff.williams@aspectsecurity.com) */ public class JavaLoggerTest extends TestCase { private static int testCount = 0; private static Logger testLogger = null; /** * Instantiates a new logger test. * * @param testName the test name */ public JavaLoggerTest(String testName) { super(testName); } /** * {@inheritDoc} * @throws Exception */ protected void setUp() throws Exception { UnitTestSecurityConfiguration tmpConfig = new UnitTestSecurityConfiguration((DefaultSecurityConfiguration) ESAPI.securityConfiguration()); tmpConfig.setLogImplementation( JavaLogFactory.class.getName() ); ESAPI.override(tmpConfig); //This ensures a clean logger between tests testLogger = ESAPI.getLogger( "test" + testCount++ ); System.out.println("Test logger: " + testLogger); } /** * {@inheritDoc} * @throws Exception */ protected void tearDown() throws Exception { //this helps, with garbage collection testLogger = null; ESAPI.override(null); } /** * Suite. * * @return the test */ public static Test suite() { TestSuite suite = new TestSuite(JavaLoggerTest.class); return suite; } /** * Test of logHTTPRequest method, of class org.owasp.esapi.Logger. * * @throws ValidationException * the validation exception * @throws IOException * Signals that an I/O exception has occurred. * @throws AuthenticationException * the authentication exception */ public void testLogHTTPRequest() throws ValidationException, IOException, AuthenticationException { System.out.println("logHTTPRequest"); String[] ignore = {"password","ssn","ccn"}; MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); ESAPI.httpUtilities().setCurrentHTTP(request, response); Logger logger = ESAPI.getLogger("logger"); ESAPI.httpUtilities().logHTTPRequest( request, logger, Arrays.asList(ignore) ); request.addParameter("one","one"); request.addParameter("two","two1"); request.addParameter("two","two2"); request.addParameter("password","jwilliams"); ESAPI.httpUtilities().logHTTPRequest( request, logger, Arrays.asList(ignore) ); } /** * Test of setLevel method of the inner class org.owasp.esapi.reference.JavaLogger that is defined in * org.owasp.esapi.reference.JavaLogFactory. */ public void testSetLevel() { System.out.println("setLevel"); // The following tests that the default logging level is set to WARNING. Since the default might be changed // in the ESAPI security configuration file, these are commented out. // assertTrue(testLogger.isWarningEnabled()); // assertFalse(testLogger.isInfoEnabled()); // First, test all the different logging levels testLogger.setLevel( Logger.ALL ); assertTrue(testLogger.isFatalEnabled()); assertTrue(testLogger.isErrorEnabled()); assertTrue(testLogger.isWarningEnabled()); assertTrue(testLogger.isInfoEnabled()); assertTrue(testLogger.isDebugEnabled()); assertTrue(testLogger.isTraceEnabled()); testLogger.setLevel( Logger.TRACE ); assertTrue(testLogger.isFatalEnabled()); assertTrue(testLogger.isErrorEnabled()); assertTrue(testLogger.isWarningEnabled()); assertTrue(testLogger.isInfoEnabled()); assertTrue(testLogger.isDebugEnabled()); assertTrue(testLogger.isTraceEnabled()); testLogger.setLevel( Logger.DEBUG ); assertTrue(testLogger.isFatalEnabled()); assertTrue(testLogger.isErrorEnabled()); assertTrue(testLogger.isWarningEnabled()); assertTrue(testLogger.isInfoEnabled()); assertTrue(testLogger.isDebugEnabled()); assertFalse(testLogger.isTraceEnabled()); testLogger.setLevel( Logger.INFO ); assertTrue(testLogger.isFatalEnabled()); assertTrue(testLogger.isErrorEnabled()); assertTrue(testLogger.isWarningEnabled()); assertTrue(testLogger.isInfoEnabled()); assertFalse(testLogger.isDebugEnabled()); assertFalse(testLogger.isTraceEnabled()); testLogger.setLevel( Logger.WARNING ); assertTrue(testLogger.isFatalEnabled()); assertTrue(testLogger.isErrorEnabled()); assertTrue(testLogger.isWarningEnabled()); assertFalse(testLogger.isInfoEnabled()); assertFalse(testLogger.isDebugEnabled()); assertFalse(testLogger.isTraceEnabled()); testLogger.setLevel( Logger.ERROR ); assertTrue(testLogger.isFatalEnabled()); assertTrue(testLogger.isErrorEnabled()); assertFalse(testLogger.isWarningEnabled()); assertFalse(testLogger.isInfoEnabled()); assertFalse(testLogger.isDebugEnabled()); assertFalse(testLogger.isTraceEnabled()); testLogger.setLevel( Logger.FATAL ); assertTrue(testLogger.isFatalEnabled()); assertFalse(testLogger.isErrorEnabled()); assertFalse(testLogger.isWarningEnabled()); assertFalse(testLogger.isInfoEnabled()); assertFalse(testLogger.isDebugEnabled()); assertFalse(testLogger.isTraceEnabled()); testLogger.setLevel( Logger.OFF ); assertFalse(testLogger.isFatalEnabled()); assertFalse(testLogger.isErrorEnabled()); assertFalse(testLogger.isWarningEnabled()); assertFalse(testLogger.isInfoEnabled()); assertFalse(testLogger.isDebugEnabled()); assertFalse(testLogger.isTraceEnabled()); //Now test to see if a change to the logging level in one log affects other logs Logger newLogger = ESAPI.getLogger( "test_num2" ); testLogger.setLevel( Logger.OFF ); newLogger.setLevel( Logger.INFO ); assertFalse(testLogger.isFatalEnabled()); assertFalse(testLogger.isErrorEnabled()); assertFalse(testLogger.isWarningEnabled()); assertFalse(testLogger.isInfoEnabled()); assertFalse(testLogger.isDebugEnabled()); assertFalse(testLogger.isTraceEnabled()); assertTrue(newLogger.isFatalEnabled()); assertTrue(newLogger.isErrorEnabled()); assertTrue(newLogger.isWarningEnabled()); assertTrue(newLogger.isInfoEnabled()); assertFalse(newLogger.isDebugEnabled()); assertFalse(newLogger.isTraceEnabled()); } /** * Test of info method, of class org.owasp.esapi.Logger. */ public void testInfo() { System.out.println("info"); testLogger.info(Logger.SECURITY_SUCCESS, "test message" ); testLogger.info(Logger.SECURITY_SUCCESS, "test message", null ); testLogger.info(Logger.SECURITY_SUCCESS, "%3escript%3f test message", null ); testLogger.info(Logger.SECURITY_SUCCESS, "<script> test message", null ); } /** * Test of trace method, of class org.owasp.esapi.Logger. */ public void testTrace() { System.out.println("trace"); testLogger.trace(Logger.SECURITY_SUCCESS, "test message trace" ); testLogger.trace(Logger.SECURITY_SUCCESS, "test message trace", null ); } /** * Test of debug method, of class org.owasp.esapi.Logger. */ public void testDebug() { System.out.println("debug"); testLogger.debug(Logger.SECURITY_SUCCESS, "test message debug" ); testLogger.debug(Logger.SECURITY_SUCCESS, "test message debug", null ); } /** * Test of error method, of class org.owasp.esapi.Logger. */ public void testError() { System.out.println("error"); testLogger.error(Logger.SECURITY_SUCCESS, "test message error" ); testLogger.error(Logger.SECURITY_SUCCESS, "test message error", null ); } /** * Test of warning method, of class org.owasp.esapi.Logger. */ public void testWarning() { System.out.println("warning"); testLogger.warning(Logger.SECURITY_SUCCESS, "test message warning" ); testLogger.warning(Logger.SECURITY_SUCCESS, "test message warning", null ); } /** * Test of fatal method, of class org.owasp.esapi.Logger. */ public void testFatal() { System.out.println("fatal"); testLogger.fatal(Logger.SECURITY_SUCCESS, "test message fatal" ); testLogger.fatal(Logger.SECURITY_SUCCESS, "test message fatal", null ); } /** * Test of always method, of class org.owasp.esapi.Logger. */ public void testAlways() { System.out.println("always"); testLogger.always(Logger.SECURITY_SUCCESS, "test message always 1 (SECURITY_SUCCESS)" ); testLogger.always(Logger.SECURITY_AUDIT, "test message always 2 (SECURITY_AUDIT)" ); testLogger.always(Logger.SECURITY_SUCCESS, "test message always 3 (SECURITY_SUCCESS)", null ); testLogger.always(Logger.SECURITY_AUDIT, "test message always 4 (SECURITY_AUDIT)", null ); try { throw new RuntimeException("What? You call that a 'throw'? My grandmother throws " + "better than that and she's been dead for more than 10 years!"); } catch(RuntimeException rtex) { testLogger.always(Logger.SECURITY_AUDIT, "test message always 5", rtex ); } } }
package turing123; import java.util.ArrayList; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import turing123.lockmanager.SimpleReadWriteLockManager; public class SimpleReadWriteLockManagerTest { private SimpleReadWriteLockManager<String> lockmanager; @Before public void initLockManager() { this.lockmanager = new SimpleReadWriteLockManager<String>(); } /** * For two threads trying to acquire the read locks on the same key, both succeed. */ @Test public void testAcquireReadLocksOnSameKey() throws InterruptedException { final String key = "key"; final ArrayList<Integer> threadsCompleted = new ArrayList<Integer>(); Runnable runnable1 = new Runnable() { public void run() { lockmanager.acquireReadLock(key); threadsCompleted.add(1); } }; Runnable runnable2 = new Runnable() { public void run() { lockmanager.acquireReadLock(key); threadsCompleted.add(2); } }; Thread t1 = new Thread( runnable1 ); Thread t2 = new Thread( runnable2 ); t1.start(); t2.start(); t1.join(); t2.join(); Assert.assertEquals(2, threadsCompleted.size()); } /** * For two threads trying to respectively acquire the read and write locks on the same key, only one succeeds. */ @Test public void testAcquireReadWriteLocksOnSameKey() throws InterruptedException { final String key = "key"; final ArrayList<Integer> threadsCompleted = new ArrayList<Integer>(); Runnable runnable1 = new Runnable() { public void run() { lockmanager.acquireReadLock(key); threadsCompleted.add(1); } }; Runnable runnable2 = new Runnable() { public void run() { lockmanager.acquireWriteLock(key); threadsCompleted.add(2); } }; Thread t1 = new Thread( runnable1 ); Thread t2 = new Thread( runnable2 ); t1.start(); t2.start(); t1.join(3000); t2.join(3000); // only one thread can acquire the read or write lock for the key Assert.assertEquals(1, threadsCompleted.size()); } /** * For two threads trying to respectively acquire the read and write locks on the same key, * if each of them release the key, then both succeed. */ @Test public void testAcquireAndReleaseReadWriteLocksOnSameKey() throws InterruptedException { final String key = "key"; final ArrayList<Integer> threadsCompleted = new ArrayList<Integer>(); Runnable runnable1 = new Runnable() { public void run() { lockmanager.acquireReadLock(key); threadsCompleted.add(1); lockmanager.releaseReadLock(key); } }; Runnable runnable2 = new Runnable() { public void run() { lockmanager.acquireWriteLock(key); threadsCompleted.add(2); lockmanager.releaseWriteLock(key); } }; Thread t1 = new Thread( runnable1 ); Thread t2 = new Thread( runnable2 ); t1.start(); t2.start(); t1.join(3000); t2.join(3000); // both threads can run correctly since each of them release the lock Assert.assertEquals(2, threadsCompleted.size()); } /** * For two threads trying to respectively acquire the read and write locks on two different keys, both succeed. */ @Test public void testAcquireReadWriteLocksOnDifferentKeys() throws InterruptedException { final String key1 = "key1"; final String key2 = "key2"; final ArrayList<Integer> threadsCompleted = new ArrayList<Integer>(); Runnable runnable1 = new Runnable() { public void run() { lockmanager.acquireReadLock(key1); threadsCompleted.add(1); } }; Runnable runnable2 = new Runnable() { public void run() { lockmanager.acquireWriteLock(key2); threadsCompleted.add(2); } }; Thread t1 = new Thread( runnable1 ); Thread t2 = new Thread( runnable2 ); t1.start(); t2.start(); t1.join(); t2.join(); Assert.assertEquals(2, threadsCompleted.size()); } }
package controllers; import play.*; import play.mvc.*; import views.html.*; public class Application extends Controller { public Result index() { return ok("Welcome to Breakout API. Nothing to see here by now").as("text/plain"); } }
package x2x.translator.xcodeml; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.NamedNodeMap; public class CLAWloop { protected Element _pragmaElement = null; protected Element _loopElement = null; protected Element _rangeElement = null; protected Element _rangeVarElement = null; protected String _iterationVar; protected String _lowerBoundValue; protected String _upperBoundValue; protected String _stepValue; public CLAWloop(Element pragma, Element loop){ _pragmaElement = pragma; _loopElement = loop; NodeList vars = _loopElement.getElementsByTagName("Var"); Element var = (Element) vars.item(0); _rangeVarElement = var; _iterationVar = var.getTextContent(); NodeList ranges = _loopElement.getElementsByTagName("indexRange"); Element range = (Element) ranges.item(0); _rangeElement = range; _lowerBoundValue = getRangeValue("lowerBound"); _upperBoundValue = getRangeValue("upperBound"); _stepValue = getRangeValue("step"); } protected void findRangeElements(){ NodeList vars = _loopElement.getElementsByTagName("Var"); Element var = (Element) vars.item(0); _rangeVarElement = var; _iterationVar = var.getTextContent(); NodeList ranges = _loopElement.getElementsByTagName("indexRange"); Element range = (Element) ranges.item(0); _rangeElement = range; _lowerBoundValue = getRangeValue("lowerBound"); _upperBoundValue = getRangeValue("upperBound"); _stepValue = getRangeValue("step"); } private String getRangeValue(String tag){ NodeList rangeElements = _loopElement.getElementsByTagName(tag); Element rangeElement = (Element) rangeElements.item(0); NodeList constants = rangeElement.getElementsByTagName("FintConstant"); // TODO string constant Element constant = (Element) constants.item(0); NodeList vars = rangeElement.getElementsByTagName("Var"); // TODO string constant Element var = (Element) constants.item(0); if(constant != null){ return constant.getTextContent(); } if(var != null){ return var.getTextContent(); } return null; // TODO probably throws an exception } public void setNewRange(Node var, Node range){ Element body = getBodyElement(); Node newVar = var.cloneNode(true); Node newRange = range.cloneNode(true); _loopElement.insertBefore(newVar, body); _loopElement.insertBefore(newRange, body); findRangeElements(); //_rangeVarElement = var; //_rangeElement = range; } public void deleteRangeElements(){ _loopElement.removeChild(_rangeVarElement); _loopElement.removeChild(_rangeElement); } protected void swapRangeElementsWith(CLAWloop otherLoop){ otherLoop.setNewRange(_rangeVarElement, _rangeElement); setNewRange(otherLoop.getRangeVarElement(), otherLoop.getRangeElement()); } public Element getLoopElement(){ return _loopElement; } public Element getPragmaElement(){ return _pragmaElement; } public Element getBodyElement(){ // TODO be sure that there is only one body per loop NodeList bodies = _loopElement.getElementsByTagName("body"); Element body = (Element) bodies.item(0); return body; } private String getAttributeValue(Element el, String attrName){ NamedNodeMap attributes = el.getAttributes(); for (int j = 0; j < attributes.getLength(); j++) { if(attributes.item(j).getNodeName().equals(attrName)){ return attributes.item(j).getNodeValue(); } } return ""; } public String getOriginalFilename(){ return getAttributeValue(_pragmaElement, "file"); // TODO use constant } public String getPragmaLine(){ return getAttributeValue(_pragmaElement, "lineno"); // TODO use constant } /* <Var type="Fint" scope="local">i</Var> <indexRange> <lowerBound> <FintConstant type="Fint">1</FintConstant> </lowerBound> <upperBound> <FintConstant type="Fint">10</FintConstant> </upperBound> <step> <FintConstant type="Fint">1</FintConstant> </step> </indexRange> */ public String getIterationVariableValue(){ return _iterationVar; } public String getLowerBoundValue(){ return _lowerBoundValue; } public String getUpperBoundValue(){ return _upperBoundValue; } public String getStepValue(){ return _stepValue; } public String getFormattedRange(){ return _iterationVar + "=" + _lowerBoundValue + "," + _upperBoundValue + "," + _stepValue; } public boolean hasSameRangeWith(CLAWloop otherLoop){ return _lowerBoundValue == otherLoop.getLowerBoundValue() && _upperBoundValue == otherLoop.getUpperBoundValue() && _stepValue == otherLoop.getStepValue() && _iterationVar == otherLoop.getIterationVariableValue(); } public Element getRangeElement(){ return _rangeElement; } public Element getRangeVarElement(){ return _rangeVarElement; } }
package king.flow.common; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.io.File; import java.nio.charset.Charset; import java.util.List; import java.util.Map; import king.flow.action.business.ShowClockAction; import king.flow.data.TLSResult; import king.flow.view.Action.CleanAction; import king.flow.view.Action.EncryptKeyboardAction; import king.flow.view.Action.InsertICardAction; import king.flow.view.Action.LimitInputAction; import king.flow.view.Action.MoveCursorAction; import king.flow.view.Action.OpenBrowserAction; import king.flow.view.Action.PlayMediaAction; import king.flow.view.Action.PlayVideoAction; import king.flow.view.Action.PrintPassbookAction; import king.flow.view.Action.RunCommandAction; import king.flow.view.Action.RwFingerPrintAction; import king.flow.view.Action.SetFontAction; import king.flow.view.Action.SetPrinterAction; import king.flow.view.Action.ShowComboBoxAction; import king.flow.view.Action.ShowTableAction; import king.flow.view.Action.Swipe2In1CardAction; import king.flow.view.Action.SwipeCardAction; import king.flow.view.Action.UploadFileAction; import king.flow.view.Action.UseTipAction; import king.flow.view.Action.VirtualKeyboardAction; import king.flow.view.Action.WriteICardAction; import king.flow.view.ComponentEnum; import king.flow.view.DefinedAction; import king.flow.view.JumpAction; import king.flow.view.MsgSendAction; /** * * @author LiuJin */ public class CommonConstants { public static final Charset UTF8 = Charset.forName("UTF-8"); static final File[] SYS_ROOTS = File.listRoots(); public static final int DRIVER_COUNT = SYS_ROOTS.length; public static final String XML_NODE_PREFIX = "N_"; public static final String REVERT = "re_"; public static final String BID = "bid"; public static final String UID_PREFIX = "<" + TLSResult.UID + ">"; public static final String UID_AFFIX = "</" + TLSResult.UID + ">"; public static final String DEFAULT_DATE_FORMATE = "yyyy-MM-dd"; public static final String VALID_BANK_CARD = "validBankCard"; public static final String BALANCED_PAY_MAC = "balancedPayMAC"; public static final String CANCEL_ENCRYPTION_KEYBOARD = "[CANCEL]"; public static final String QUIT_ENCRYPTION_KEYBOARD = "[QUIT]"; public static final String INVALID_ENCRYPTION_LENGTH = "encryption.keyboard.type.length.prompt"; public static final String TIMEOUT_ENCRYPTION_TYPE = "encryption.keyboard.type.timeout.prompt"; public static final String ERROR_ENCRYPTION_TYPE = "encryption.keyboard.type.fail.prompt"; public static final int CONTAINER_KEY = Integer.MAX_VALUE; public static final int NORMAL = 0; public static final int ABNORMAL = 1; public static final int BALANCE = 12345; public static final int RESTART_SIGNAL = 1; public static final int DOWNLOAD_KEY_SIGNAL = 1; public static final int UPDATE_SIGNAL = 1; public static final String VERSION; // public static final String VERSION = Paths.get(".").toAbsolutePath().normalize().toString(); static { String workingPath = System.getProperty("user.dir"); final int lastIndexOf = workingPath.lastIndexOf('_'); if (lastIndexOf != -1 && lastIndexOf < workingPath.length() - 1) { VERSION = workingPath.substring(lastIndexOf + 1); } else { VERSION = "Unknown"; } } /* system variable pattern */ public static final String SYSTEM_VAR_PATTERN = "\\$\\{(_?\\p{Alpha}+_\\p{Alpha}+)+\\}"; public static final String TEXT_MINGLED_SYSTEM_VAR_PATTERN = ".*" + SYSTEM_VAR_PATTERN + ".*"; public static final String TERMINAL_ID_SYS_VAR = "TERMINAL_ID"; /* swing default config */ public static final int DEFAULT_TABLE_ROW_COUNT = 15; public static final int DEFAULT_VIDEO_REPLAY_INTERVAL_SECOND = 20; /* packet header ID */ public static final int GENERAL_MSG_CODE = 0; //common message public static final int REGISTRY_MSG_CODE = 1; //terminal registration message public static final int KEY_DOWNLOAD_MSG_CODE = 2; //download secret key message public static final int MANAGER_MSG_CODE = 100; //management message /*MAX_MESSAGES_PER_READ refers to DefaultChannelConfig, AdaptiveRecvByteBufAllocator, FixedRecvByteBufAllocator */ public static final int MAX_MESSAGES_PER_READ = 6; //how many read actions in one message conversation public static final int MIN_RECEIVED_BUFFER_SIZE = 64; //64 bytes public static final int RECEIVED_BUFFER_SIZE = 6 * 1024; //6k bytes public static final int MAX_RECEIVED_BUFFER_SIZE = 64 * 1024; //64k bytes /* keyboard cipher key */ public static final String WORK_SECRET_KEY = "workSecretKey"; public static final String MA_KEY = "maKey"; public static final String MASTER_KEY = "masterKey"; /* packet result flag */ public static final int SUCCESSFUL_MSG_CODE = 0; /* xml jaxb context */ public static final String NET_CONF_PACKAGE_CONTEXT = "king.flow.net"; public static final String TLS_PACKAGE_CONTEXT = "king.flow.data"; public static final String UI_CONF_PACKAGE_CONTEXT = "king.flow.view"; public static final String KING_FLOW_BACKGROUND = "king.flow.background"; public static final String KING_FLOW_PROGRESS = "king.flow.progress"; public static final String TEXT_TYPE_TOOL_CONFIG = "chinese.text.type.config"; public static final int TABLE_ROW_HEIGHT = 25; public static final String COMBOBOX_ITEMS_PROPERTY_PATTERN = "([^,/]*/[^,/]*,)*+([^,/]*/[^,/]*){1}+"; public static final String ADVANCED_TABLE_TOTAL_PAGES = "total"; public static final String ADVANCED_TABLE_VALUE = "value"; public static final String ADVANCED_TABLE_CURRENT_PAGE = "current"; /* card-reading state */ public static final int INVALID_CARD_STATE = -1; public static final int MAGNET_CARD_STATE = 2; public static final int IC_CARD_STATE = 3; /* union-pay transaction type */ public static final String UNION_PAY_REGISTRATION = "1"; public static final String UNION_PAY_TRANSACTION = "3"; public static final String UNION_PAY_TRANSACTION_BALANCE = "4"; /* card affiliation type */ public static final String CARD_AFFILIATION_INTERNAL = "1"; public static final String CARD_AFFILIATION_EXTERNAL = "2"; /* action-component relationship map */ public static final String JUMP_ACTION = JumpAction.class.getSimpleName(); public static final String SET_FONT_ACTION = SetFontAction.class.getSimpleName(); public static final String CLEAN_ACTION = CleanAction.class.getSimpleName(); public static final String USE_TIP_ACTION = UseTipAction.class.getSimpleName(); public static final String PLAY_MEDIA_ACTION = PlayMediaAction.class.getSimpleName(); public static final String SEND_MSG_ACTION = MsgSendAction.class.getSimpleName(); public static final String MOVE_CURSOR_ACTION = MoveCursorAction.class.getSimpleName(); public static final String LIMIT_INPUT_ACTION = LimitInputAction.class.getSimpleName(); public static final String SHOW_COMBOBOX_ACTION = ShowComboBoxAction.class.getSimpleName(); public static final String SHOW_TABLE_ACTION = ShowTableAction.class.getSimpleName(); public static final String SHOW_CLOCK_ACTION = ShowClockAction.class.getSimpleName(); public static final String OPEN_BROWSER_ACTION = OpenBrowserAction.class.getSimpleName(); public static final String RUN_COMMAND_ACTION = RunCommandAction.class.getSimpleName(); public static final String OPEN_VIRTUAL_KEYBOARD_ACTION = VirtualKeyboardAction.class.getSimpleName(); public static final String PRINT_RECEIPT_ACTION = SetPrinterAction.class.getSimpleName(); public static final String INSERT_IC_ACTION = InsertICardAction.class.getSimpleName(); public static final String WRITE_IC_ACTION = WriteICardAction.class.getSimpleName(); public static final String BALANCE_TRANS_ACTION = "BalanceTransAction"; public static final String PRINT_PASSBOOK_ACTION = PrintPassbookAction.class.getSimpleName(); public static final String UPLOAD_FILE_ACTION = UploadFileAction.class.getSimpleName(); public static final String SWIPE_CARD_ACTION = SwipeCardAction.class.getSimpleName(); public static final String SWIPE_TWO_IN_ONE_CARD_ACTION = Swipe2In1CardAction.class.getSimpleName(); public static final String READ_WRITE_FINGERPRINT_ACTION = RwFingerPrintAction.class.getSimpleName(); public static final String PLAY_VIDEO_ACTION = PlayVideoAction.class.getSimpleName(); public static final String CUSTOMIZED_ACTION = DefinedAction.class.getSimpleName(); public static final String ENCRYPT_KEYBORAD_ACTION = EncryptKeyboardAction.class.getSimpleName(); static final Map<ComponentEnum, List<String>> ACTION_COMPONENT_MAP = new ImmutableMap.Builder<ComponentEnum, List<String>>() .put(ComponentEnum.BUTTON, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(JUMP_ACTION) .add(SET_FONT_ACTION) .add(CLEAN_ACTION) .add(USE_TIP_ACTION) .add(PLAY_MEDIA_ACTION) .add(OPEN_BROWSER_ACTION) .add(RUN_COMMAND_ACTION) .add(OPEN_VIRTUAL_KEYBOARD_ACTION) .add(PRINT_RECEIPT_ACTION) .add(SEND_MSG_ACTION) .add(INSERT_IC_ACTION) .add(WRITE_IC_ACTION) .add(MOVE_CURSOR_ACTION) .add(PRINT_PASSBOOK_ACTION) .add(UPLOAD_FILE_ACTION) .add(BALANCE_TRANS_ACTION) .build()) .put(ComponentEnum.COMBO_BOX, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(USE_TIP_ACTION) .add(SHOW_COMBOBOX_ACTION) .add(SWIPE_CARD_ACTION) .add(SWIPE_TWO_IN_ONE_CARD_ACTION) .add(PLAY_MEDIA_ACTION) .add(MOVE_CURSOR_ACTION) .build()) .put(ComponentEnum.LABEL, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(USE_TIP_ACTION) .add(SHOW_CLOCK_ACTION) .build()) .put(ComponentEnum.TEXT_FIELD, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(LIMIT_INPUT_ACTION) .add(USE_TIP_ACTION) .add(PLAY_MEDIA_ACTION) .add(READ_WRITE_FINGERPRINT_ACTION) .add(OPEN_VIRTUAL_KEYBOARD_ACTION) .add(MOVE_CURSOR_ACTION) .build()) .put(ComponentEnum.PASSWORD_FIELD, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(LIMIT_INPUT_ACTION) .add(USE_TIP_ACTION) .add(PLAY_MEDIA_ACTION) .add(READ_WRITE_FINGERPRINT_ACTION) .add(MOVE_CURSOR_ACTION) .add(ENCRYPT_KEYBORAD_ACTION) .build()) .put(ComponentEnum.TABLE, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(USE_TIP_ACTION) .add(SHOW_TABLE_ACTION) .build()) .put(ComponentEnum.ADVANCED_TABLE, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(SHOW_TABLE_ACTION) .add(SEND_MSG_ACTION) .build()) .put(ComponentEnum.VIDEO_PLAYER, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(PLAY_VIDEO_ACTION) .build()) .build(); }
package com.vortexwolf.chan.common.utils; import java.io.File; import java.util.Locale; import pl.droidsonroids.gif.GifDrawable; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.content.res.Resources.Theme; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.webkit.MimeTypeMap; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.VideoView; import com.davemorrissey.labs.subscaleview.FixedSubsamplingScaleImageView; import com.davemorrissey.labs.subscaleview.ImageSource; import com.vortexwolf.chan.R; import com.vortexwolf.chan.common.Constants; import com.vortexwolf.chan.common.Factory; import com.vortexwolf.chan.common.MainApplication; import com.vortexwolf.chan.common.controls.TouchGifView; import com.vortexwolf.chan.common.controls.WebViewFixed; import com.vortexwolf.chan.common.library.MyLog; import com.vortexwolf.chan.models.presentation.GalleryItemViewBag; import com.vortexwolf.chan.services.TimerService; import com.vortexwolf.chan.settings.ApplicationSettings; import org.apache.http.protocol.HTTP; public class AppearanceUtils { private static final String TAG = "AppearanceUtils"; private static Toast toast; public final static ViewGroup.LayoutParams MATCH_PARAMS = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); public static void showToastMessage(Context context, String msg) { if(toast != null){ toast.cancel(); } toast = Toast.makeText(context, msg, Toast.LENGTH_LONG); toast.show(); } public static ListViewPosition getCurrentListPosition(ListView listView) { int index = 0; int top = 0; if (listView != null) { index = listView.getFirstVisiblePosition(); View v = listView.getChildAt(0); top = (v == null) ? 0 : v.getTop(); } ListViewPosition position = new ListViewPosition(index, top); return position; } public static View getListItemAtPosition(ListView listView, int position) { int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount(); // This is the same as child int wantedChild = position - firstPosition; if (wantedChild < 0 || wantedChild >= listView.getChildCount()) { return null; } // Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead. return listView.getChildAt(wantedChild); } public static void showImageProgressBar(final View indeterminateProgressBar, final ImageView imageView) { if (indeterminateProgressBar != null) { indeterminateProgressBar.setVisibility(View.VISIBLE); } } public static void hideImageProgressBar(final View indeterminateProgressBar, final ImageView imageView) { if (indeterminateProgressBar != null) { indeterminateProgressBar.setVisibility(View.GONE); } } public static void clearImage(ImageView image) { image.setImageResource(android.R.color.transparent); } public static Bitmap reduceBitmapSize(Resources resources, Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); int oldSize = Math.max(width, height); int newSize = resources.getDimensionPixelSize(R.dimen.thumbnail_size); float scale = newSize / (float) oldSize; if (scale >= 1.0) { return bitmap; } Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, (int) (width * scale), (int) (height * scale), true); bitmap.recycle(); return resizedBitmap; } public static void prepareWebViewForImage(WebView webView, int backgroundColor) { webView.setBackgroundColor(backgroundColor); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); WebSettings settings = webView.getSettings(); settings.setBuiltInZoomControls(true); settings.setSupportZoom(true); settings.setCacheMode(WebSettings.LOAD_NO_CACHE); settings.setJavaScriptEnabled(true); if (Constants.SDK_VERSION >= 5) { CompatibilityUtilsImpl.setScrollbarFadingEnabled(webView, true); } if (Constants.SDK_VERSION >= 8) { CompatibilityUtilsImpl.setBlockNetworkLoads(settings, true); } if (MainApplication.MULTITOUCH_SUPPORT && Constants.SDK_VERSION >= 11) { boolean isDisplayZoomControls = Factory.getContainer().resolve(ApplicationSettings.class).isDisplayZoomControls(); CompatibilityUtilsImpl.setDisplayZoomControls(settings, isDisplayZoomControls); } } public static void prepareWebViewForVideo(WebView webView, int backgroundColor) { webView.setBackgroundColor(backgroundColor); WebSettings settings = webView.getSettings(); settings.setCacheMode(WebSettings.LOAD_NO_CACHE); if (Constants.SDK_VERSION >= 8) { CompatibilityUtilsImpl.setBlockNetworkLoads(settings, true); } } private static Point getImageSize(File file) { return IoUtils.getImageSize(file); } private static Point getResolution(View view) { return new Point(view.getWidth(), view.getHeight()); } public static int getThemeColor(Theme theme, int styleableId) { TypedArray a = theme.obtainStyledAttributes(R.styleable.Theme); int color = a.getColor(styleableId, 0); a.recycle(); return color; } public static Drawable getThemeDrawable(Theme theme, int styleableId) { TypedArray a = theme.obtainStyledAttributes(R.styleable.Theme); Drawable drawable = a.getDrawable(styleableId); a.recycle(); return drawable; } public static void setImage(final File file, final Activity context, final FrameLayout layout, final int background) { setImage(file, context, layout, background, false); } public static void setImage(final File file, final Activity context, final FrameLayout layout, final int background, boolean forceWebView) { final ApplicationSettings mSettings = Factory.getContainer().resolve(ApplicationSettings.class); int gifMethod = forceWebView ? Constants.GIF_WEB_VIEW : mSettings.getGifView(); int picMethod = forceWebView ? Constants.IMAGE_VIEW_WEB_VIEW : mSettings.getImageView(); boolean isDone = false; layout.removeAllViews(); try { if (RegexUtils.getFileExtension(file.getAbsolutePath()).equalsIgnoreCase("gif")) { if (gifMethod == Constants.GIF_NATIVE_LIB) { GifDrawable gifDrawable = new GifDrawable(file.getAbsolutePath()); ImageView gifView; if (Constants.SDK_VERSION >= 8) { gifView = new TouchGifView(context); } else { gifView = new ImageView(context); } gifView.setImageDrawable(gifDrawable); gifView.setLayoutParams(MATCH_PARAMS); gifView.setBackgroundColor(background); layout.addView(gifView); isDone = true; } } else if (picMethod == Constants.IMAGE_VIEW_SUBSCALEVIEW && !IoUtils.isNonStandardGrayscaleImage(file)) { final FixedSubsamplingScaleImageView imageView = new FixedSubsamplingScaleImageView(context); imageView.setImage(ImageSource.uri(Uri.fromFile(file))); imageView.setOnImageEventListener(new FixedSubsamplingScaleImageView.DefaultOnImageEventListener() { @Override public void onTileLoadError(Throwable e) { AppearanceUtils.setImage(file, context, layout, background, true); } @Override public void onImageLoadError(Throwable e) { AppearanceUtils.setImage(file, context, layout, background, true); } }); imageView.setLayoutParams(MATCH_PARAMS); imageView.setBackgroundColor(background); imageView.setMaxScale(4F); layout.addView(imageView); isDone = true; } } catch (Exception e) { MyLog.e(TAG, e); } catch (OutOfMemoryError e) { MyLog.e(TAG, e); System.gc(); } if (!isDone) { setWebViewFile(file, context, layout, background); } } public static void setVideoFile(final File file, final Activity context, final GalleryItemViewBag viewBag, final int background, final Theme theme) { final ApplicationSettings settings = Factory.getContainer().resolve(ApplicationSettings.class); viewBag.layout.removeAllViews(); if (settings.getVideoPlayer() == Constants.VIDEO_PLAYER_WEBVIEW) { setWebViewFile(file, context, viewBag.layout, background); return; } View container = LayoutInflater.from(context).inflate(R.layout.video_view, viewBag.layout); final VideoViewViewBag videoViewViewBag = VideoViewViewBag.fromContainer(container); videoViewViewBag.speakerDrawable = getThemeDrawable(theme, R.styleable.Theme_iconSoundSpeaker); videoViewViewBag.muteDrawable = getThemeDrawable(theme, R.styleable.Theme_iconSoundMute); videoViewViewBag.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(final MediaPlayer mp) { mp.setLooping(true); videoViewViewBag.durationView.setText("00:00 / " + formatVideoTime(mp.getDuration())); viewBag.timer = new TimerService(1, context); viewBag.timer.runTask(new Runnable() { @Override public void run() { try { videoViewViewBag.durationView.setText(formatVideoTime(mp.getCurrentPosition()) + " / " + formatVideoTime(mp.getDuration())); } catch (Exception e) { viewBag.timer.stop(); } } }); if (settings.isVideoMute()) { mp.setVolume(0, 0); videoViewViewBag.setVolume(0); } else { mp.setVolume(1, 1); videoViewViewBag.setVolume(1); } videoViewViewBag.muteButton.setOnClickListener(new ImageButton.OnClickListener() { @Override public void onClick(View v) { if (videoViewViewBag.volume > 0) { mp.setVolume(0, 0); videoViewViewBag.setVolume(0); } else { mp.setVolume(1, 1); videoViewViewBag.setVolume(1); } } }); mp.start(); } }); videoViewViewBag.videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { MyLog.e(TAG, "Error code: " + what); viewBag.switchToErrorView(context.getString(R.string.error_video_playing)); return true; } }); videoViewViewBag.videoView.setVideoPath(file.getAbsolutePath()); } public static void setWebViewFile(File file, Activity context, FrameLayout layout, int background) { WebViewFixed webView = new WebViewFixed(context); webView.setLayoutParams(MATCH_PARAMS); layout.addView(webView); ApplicationSettings settings = Factory.getContainer().resolve(ApplicationSettings.class); Uri uri = Uri.fromFile(file); if (UriUtils.isImageUri(uri)) { AppearanceUtils.prepareWebViewForImage(webView, background); webView.loadDataWithBaseURL(null, createHtmlForImage(uri), "text/html", HTTP.UTF_8, null); } else if (UriUtils.isWebmUri(uri)) { String mutedAttr = settings.isVideoMute() ? "muted" : ""; String attributes = String.format("src='%1$s' controls autoplay %2$s", uri, mutedAttr); AppearanceUtils.prepareWebViewForVideo(webView, background); webView.loadDataWithBaseURL(null, createHtmlForVideo(attributes), "text/html", HTTP.UTF_8, null); } else { webView.loadUrl(uri.toString()); } } private static String createHtmlForVideo(String attributes) { String elementHtml = "<video" + " style='position:absolute;left:0;right:0;top:0;bottom:0;margin:auto;width:100%;height:100%;' " + attributes + ">" + "HTML5 video is not supported." + "</video>"; return "<body style='margin:0;'>" + elementHtml + "</body>"; } private static String createHtmlForImage(Uri uri) { StringBuffer img = new StringBuffer("<img src='" + uri + "'" + " style='position:absolute;left:0;right:0;top:0;bottom:0;margin:auto;width:0;height:0;' />"); img.append("<script type='text/javascript'>"); img.append("function updateImageSize() {"); img.append("var img = document.getElementsByTagName('img')[0];"); img.append("if(!img) return;"); img.append("var widthRatio = img.clientWidth / window.innerWidth;"); img.append("var heightRatio = img.clientHeight / window.innerHeight;"); img.append("var isWide = widthRatio >= heightRatio;"); img.append("img.style.height = isWide ? 'auto' : '100%';"); img.append("img.style.width = isWide ? '100%' : 'auto';"); img.append("}"); // call when loaded and on each resize img.append("updateImageSize();"); img.append("window.onload = updateImageSize;"); img.append("window.addEventListener('resize', updateImageSize, false);"); img.append("</script>"); String bodyHtml = "<body style='margin:0;'>" + img + "</body>"; return bodyHtml; } private static String formatVideoTime(int milliseconds) { int seconds = milliseconds / 1000 % 60; int minutes = milliseconds / 60000; return String.format(Locale.US, "%02d:%02d", minutes, seconds); } public static void callWhenLoaded(final View view, final Runnable runnable){ view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if(Constants.SDK_VERSION < 16) { view.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { CompatibilityUtilsImpl.removeOnGlobalLayoutListener(view, this); } runnable.run(); } }); } public static class ListViewPosition { public ListViewPosition(int position, int top) { this.position = position; this.top = top; } public int position; public int top; } private static class VideoViewViewBag { public View container; public VideoView videoView; public TextView durationView; public ImageButton muteButton; public Drawable speakerDrawable; public Drawable muteDrawable; public float volume; public static VideoViewViewBag fromContainer(View container) { VideoViewViewBag vb = new VideoViewViewBag(); vb.container = container; vb.videoView = (VideoView)container.findViewById(R.id.video_view); vb.durationView = (TextView)container.findViewById(R.id.video_duration); vb.muteButton = (ImageButton)container.findViewById(R.id.mute_speaker_image); return vb; } public void setVolume(float volume) { this.volume = volume; if (this.volume > 0) { this.muteButton.setImageDrawable(this.speakerDrawable); } else { this.muteButton.setImageDrawable(this.muteDrawable); } } } }
package org.yamcs.tctm; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.nio.ByteBuffer; import org.yamcs.ConfigurationException; import org.yamcs.TmPacket; import org.yamcs.YConfiguration; /** * Receives telemetry packets via UDP. One UDP datagram = one TM packet. * * Keeps simple statistics about the number of datagram received and the number of too short datagrams * * @author nm * */ public class UdpTmDataLink extends AbstractTmDataLink implements Runnable { private volatile int invalidDatagramCount = 0; private DatagramSocket tmSocket; private int port; final static int MAX_LENGTH = 1500; final DatagramPacket datagram; final int maxLength; /** * Creates a new UDP TM Data Link * * @throws ConfigurationException * if port is not defined in the configuration */ public UdpTmDataLink(String instance, String name, YConfiguration config) throws ConfigurationException { super(instance, name, config); port = config.getInt("port"); maxLength = config.getInt("maxLength", MAX_LENGTH); datagram = new DatagramPacket(new byte[maxLength], maxLength); initPreprocessor(instance, config); } @Override public void doStart() { if (!isDisabled()) { try { tmSocket = new DatagramSocket(port); new Thread(this).start(); } catch (SocketException e) { notifyFailed(e); } } notifyStarted(); } @Override public void doStop() { tmSocket.close(); notifyStopped(); } @Override public void run() { while (isRunningAndEnabled()) { TmPacket pwrt = getNextPacket(); if (pwrt != null) { tmSink.processPacket(pwrt); } } } /** * * Called to retrieve the next packet. It blocks in readining on the multicast socket * * @return anything that looks as a valid packet, just the size is taken into account to decide if it's valid or not */ public TmPacket getNextPacket() { ByteBuffer packet = null; while (isRunning()) { try { tmSocket.receive(datagram); updateStats(datagram.getLength()); packet = ByteBuffer.allocate(datagram.getLength()); packet.put(datagram.getData(), datagram.getOffset(), datagram.getLength()); break; } catch (IOException e) { if (!isRunning() || isDisabled()) {// the shutdown or disable will close the socket and that will // generate an exception // which we ignore here return null; } log.warn("exception thrown when reading from the UDP socket at port {}", port, e); } } if (packet != null) { return packetPreprocessor.process(new TmPacket(timeService.getMissionTime(), packet.array())); } else { return null; } } /** * returns statistics with the number of datagram received and the number of invalid datagrams */ @Override public String getDetailedStatus() { if (isDisabled()) { return "DISABLED"; } else { return String.format("OK (%s) %nValid datagrams received: %d%nInvalid datagrams received: %d", port, packetCount, invalidDatagramCount); } } /** * Sets the disabled to true such that getNextPacket ignores the received datagrams */ @Override public void doDisable() { if (tmSocket != null) { tmSocket.close(); } } /** * Sets the disabled to false such that getNextPacket does not ignore the received datagrams * * @throws SocketException */ @Override public void doEnable() throws SocketException { tmSocket = new DatagramSocket(port); new Thread(this).start(); } @Override protected Status connectionStatus() { return Status.OK; } }
package javaslang.collection; import javaslang.*; import javaslang.collection.VectorModule.Combinations; import javaslang.control.Option; import java.io.Serializable; import java.util.*; import java.util.function.*; import java.util.stream.Collector; import static javaslang.collection.ArrayType.asArray; import static javaslang.collection.Collections.areEqual; public final class Vector<T> implements Kind1<Vector<?>, T>, IndexedSeq<T>, Serializable { private static final long serialVersionUID = 1L; private static final Vector<?> EMPTY = new Vector<>(BitMappedTrie.empty()); final BitMappedTrie<T> trie; private Vector(BitMappedTrie<T> trie) { this.trie = trie; assert (EMPTY == null) || (length() > 0); } @SuppressWarnings("ObjectEquality") private Vector<T> wrap(BitMappedTrie<T> trie) { return (trie == this.trie) ? this : ofAll(trie); } private static <T> Vector<T> ofAll(BitMappedTrie<T> trie) { return (trie.length() == 0) ? empty() : new Vector<>(trie); } /** * Returns the empty Vector. * * @param <T> Component type. * @return The empty Vector. */ @SuppressWarnings("unchecked") public static <T> Vector<T> empty() { return (Vector<T>) EMPTY; } /** * Returns a {@link Collector} which may be used in conjunction with * {@link java.util.stream.Stream#collect(Collector)} to obtain a {@link Vector}. * * @param <T> Component type of the Vector. * @return A javaslang.collection.List Collector. */ public static <T> Collector<T, ArrayList<T>, Vector<T>> collector() { final Supplier<ArrayList<T>> supplier = ArrayList::new; final BiConsumer<ArrayList<T>, T> accumulator = ArrayList::add; final BinaryOperator<ArrayList<T>> combiner = (left, right) -> { left.addAll(right); return left; }; final Function<ArrayList<T>, Vector<T>> finisher = Vector::ofAll; return Collector.of(supplier, accumulator, combiner, finisher); } /** * Narrows a widened {@code Vector<? extends T>} to {@code Vector<T>} * by performing a type-safe cast. This is eligible because immutable/read-only * collections are covariant. * * @param vector An {@code Vector}. * @param <T> Component type of the {@code Vector}. * @return the given {@code vector} instance as narrowed type {@code Vector<T>}. */ @SuppressWarnings("unchecked") public static <T> Vector<T> narrow(Vector<? extends T> vector) { return (Vector<T>) vector; } /** * Returns a singleton {@code Vector}, i.e. a {@code Vector} of one element. * * @param element An element. * @param <T> The component type * @return A new Vector instance containing the given element */ public static <T> Vector<T> of(T element) { return ofAll(Iterator.of(element)); } /** * Creates a Vector of the given elements. * * @param <T> Component type of the Vector. * @param elements Zero or more elements. * @return A vector containing the given elements in the same order. * @throws NullPointerException if {@code elements} is null */ @SafeVarargs @SuppressWarnings("varargs") public static <T> Vector<T> of(T... elements) { return ofAll(Iterator.of(elements)); } /** * Returns a Vector containing {@code n} values of a given Function {@code f} * over a range of integer values from 0 to {@code n - 1}. * * @param <T> Component type of the Vector * @param n The number of elements in the Vector * @param f The Function computing element values * @return A Vector consisting of elements {@code f(0),f(1), ..., f(n - 1)} * @throws NullPointerException if {@code f} is null */ public static <T> Vector<T> tabulate(int n, Function<? super Integer, ? extends T> f) { Objects.requireNonNull(f, "f is null"); return Collections.tabulate(n, f, empty(), Vector::of); } /** * Returns a Vector containing {@code n} values supplied by a given Supplier {@code s}. * * @param <T> Component type of the Vector * @param n The number of elements in the Vector * @param s The Supplier computing element values * @return A Vector of size {@code n}, where each element contains the result supplied by {@code s}. * @throws NullPointerException if {@code s} is null */ public static <T> Vector<T> fill(int n, Supplier<? extends T> s) { Objects.requireNonNull(s, "s is null"); return Collections.fill(n, s, empty(), Vector::of); } /** * Creates a Vector of the given elements. * <p> * The resulting vector has the same iteration order as the given iterable of elements * if the iteration order of the elements is stable. * * @param <T> Component type of the Vector. * @param iterable An Iterable of elements. * @return A vector containing the given elements in the same order. * @throws NullPointerException if {@code elements} is null */ @SuppressWarnings("unchecked") public static <T> Vector<T> ofAll(Iterable<? extends T> iterable) { Objects.requireNonNull(iterable, "iterable is null"); if (iterable instanceof Vector) { return (Vector<T>) iterable; } else { final BitMappedTrie<T> trie = BitMappedTrie.ofAll(asArray(iterable)); return ofAll(trie); } } /** * Creates a Vector that contains the elements of the given {@link java.util.stream.Stream}. * * @param javaStream A {@link java.util.stream.Stream} * @param <T> Component type of the Stream. * @return A Vector containing the given elements in the same order. */ public static <T> Vector<T> ofAll(java.util.stream.Stream<? extends T> javaStream) { Objects.requireNonNull(javaStream, "javaStream is null"); return ofAll(Iterator.ofAll(javaStream.iterator())); } /** * Creates a Vector based on the elements of a boolean array. * * @param array a boolean array * @return A new Vector of Boolean values */ public static Vector<Boolean> ofAll(boolean... array) { Objects.requireNonNull(array, "array is null"); return ofAll(BitMappedTrie.ofAll(array)); } /** * Creates a Vector based on the elements of a byte array. * * @param array a byte array * @return A new Vector of Byte values */ public static Vector<Byte> ofAll(byte... array) { Objects.requireNonNull(array, "array is null"); return ofAll(BitMappedTrie.ofAll(array)); } /** * Creates a Vector based on the elements of a char array. * * @param array a char array * @return A new Vector of Character values */ public static Vector<Character> ofAll(char... array) { Objects.requireNonNull(array, "array is null"); return ofAll(BitMappedTrie.ofAll(array)); } /** * Creates a Vector based on the elements of a double array. * * @param array a double array * @return A new Vector of Double values */ public static Vector<Double> ofAll(double... array) { Objects.requireNonNull(array, "array is null"); return ofAll(BitMappedTrie.ofAll(array)); } /** * Creates a Vector based on the elements of a float array. * * @param array a float array * @return A new Vector of Float values */ public static Vector<Float> ofAll(float... array) { Objects.requireNonNull(array, "array is null"); return ofAll(BitMappedTrie.ofAll(array)); } /** * Creates a Vector based on the elements of an int array. * * @param array an int array * @return A new Vector of Integer values */ public static Vector<Integer> ofAll(int... array) { Objects.requireNonNull(array, "array is null"); return ofAll(BitMappedTrie.ofAll(array)); } /** * Creates a Vector based on the elements of a long array. * * @param array a long array * @return A new Vector of Long values */ public static Vector<Long> ofAll(long... array) { Objects.requireNonNull(array, "array is null"); return ofAll(BitMappedTrie.ofAll(array)); } /** * Creates a Vector based on the elements of a short array. * * @param array a short array * @return A new Vector of Short values */ public static Vector<Short> ofAll(short... array) { Objects.requireNonNull(array, "array is null"); return ofAll(BitMappedTrie.ofAll(array)); } public static Vector<Character> range(char from, char toExclusive) { return ofAll(ArrayType.<char[]> asPrimitives(char.class, Iterator.range(from, toExclusive))); } public static Vector<Character> rangeBy(char from, char toExclusive, int step) { return ofAll(ArrayType.<char[]> asPrimitives(char.class, Iterator.rangeBy(from, toExclusive, step))); } @GwtIncompatible public static Vector<Double> rangeBy(double from, double toExclusive, double step) { return ofAll(ArrayType.<double[]> asPrimitives(double.class, Iterator.rangeBy(from, toExclusive, step))); } /** * Creates a Vector of int numbers starting from {@code from}, extending to {@code toExclusive - 1}. * <p> * Examples: * <pre> * <code> * Vector.range(0, 0) // = Vector() * Vector.range(2, 0) // = Vector() * Vector.range(-2, 2) // = Vector(-2, -1, 0, 1) * </code> * </pre> * * @param from the first number * @param toExclusive the last number + 1 * @return a range of int values as specified or the empty range if {@code from >= toExclusive} */ public static Vector<Integer> range(int from, int toExclusive) { return ofAll(ArrayType.<int[]> asPrimitives(int.class, Iterator.range(from, toExclusive))); } public static Vector<Integer> rangeBy(int from, int toExclusive, int step) { return ofAll(ArrayType.<int[]> asPrimitives(int.class, Iterator.rangeBy(from, toExclusive, step))); } /** * Creates a Vector of long numbers starting from {@code from}, extending to {@code toExclusive - 1}. * <p> * Examples: * <pre> * <code> * Vector.range(0L, 0L) // = Vector() * Vector.range(2L, 0L) // = Vector() * Vector.range(-2L, 2L) // = Vector(-2L, -1L, 0L, 1L) * </code> * </pre> * * @param from the first number * @param toExclusive the last number + 1 * @return a range of long values as specified or the empty range if {@code from >= toExclusive} */ public static Vector<Long> range(long from, long toExclusive) { return ofAll(ArrayType.<long[]> asPrimitives(long.class, Iterator.range(from, toExclusive))); } public static Vector<Long> rangeBy(long from, long toExclusive, long step) { return ofAll(ArrayType.<long[]> asPrimitives(long.class, Iterator.rangeBy(from, toExclusive, step))); } public static Vector<Character> rangeClosed(char from, char toInclusive) { return ofAll(ArrayType.<char[]> asPrimitives(char.class, Iterator.rangeClosed(from, toInclusive))); } public static Vector<Character> rangeClosedBy(char from, char toInclusive, int step) { return ofAll(ArrayType.<char[]> asPrimitives(char.class, Iterator.rangeClosedBy(from, toInclusive, step))); } @GwtIncompatible public static Vector<Double> rangeClosedBy(double from, double toInclusive, double step) { return ofAll(ArrayType.<double[]> asPrimitives(double.class, Iterator.rangeClosedBy(from, toInclusive, step))); } /** * Creates a Vector of int numbers starting from {@code from}, extending to {@code toInclusive}. * <p> * Examples: * <pre> * <code> * Vector.rangeClosed(0, 0) // = Vector(0) * Vector.rangeClosed(2, 0) // = Vector() * Vector.rangeClosed(-2, 2) // = Vector(-2, -1, 0, 1, 2) * </code> * </pre> * * @param from the first number * @param toInclusive the last number * @return a range of int values as specified or the empty range if {@code from > toInclusive} */ public static Vector<Integer> rangeClosed(int from, int toInclusive) { return ofAll(ArrayType.<int[]> asPrimitives(int.class, Iterator.rangeClosed(from, toInclusive))); } public static Vector<Integer> rangeClosedBy(int from, int toInclusive, int step) { return ofAll(ArrayType.<int[]> asPrimitives(int.class, Iterator.rangeClosedBy(from, toInclusive, step))); } /** * Creates a Vector of long numbers starting from {@code from}, extending to {@code toInclusive}. * <p> * Examples: * <pre> * <code> * Vector.rangeClosed(0L, 0L) // = Vector(0L) * Vector.rangeClosed(2L, 0L) // = Vector() * Vector.rangeClosed(-2L, 2L) // = Vector(-2L, -1L, 0L, 1L, 2L) * </code> * </pre> * * @param from the first number * @param toInclusive the last number * @return a range of long values as specified or the empty range if {@code from > toInclusive} */ public static Vector<Long> rangeClosed(long from, long toInclusive) { return ofAll(ArrayType.<long[]> asPrimitives(long.class, Iterator.rangeClosed(from, toInclusive))); } public static Vector<Long> rangeClosedBy(long from, long toInclusive, long step) { return ofAll(ArrayType.<long[]> asPrimitives(long.class, Iterator.rangeClosedBy(from, toInclusive, step))); } /** * Creates a Vector from a seed value and a function. * The function takes the seed at first. * The function should return {@code None} when it's * done generating the Vector, otherwise {@code Some} {@code Tuple} * of the element for the next call and the value to add to the * resulting Vector. * <p> * Example: * <pre> * <code> * Vector.unfoldRight(10, x -&gt; x == 0 * ? Option.none() * : Option.of(new Tuple2&lt;&gt;(x, x-1))); * // Vector(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)) * </code> * </pre> * * @param <T> type of seeds * @param <U> type of unfolded values * @param seed the start value for the iteration * @param f the function to get the next step of the iteration * @return a Vector with the values built up by the iteration * @throws NullPointerException if {@code f} is null */ public static <T, U> Vector<U> unfoldRight(T seed, Function<? super T, Option<Tuple2<? extends U, ? extends T>>> f) { return Iterator.unfoldRight(seed, f).toVector(); } /** * Creates a Vector from a seed value and a function. * The function takes the seed at first. * The function should return {@code None} when it's * done generating the Vector, otherwise {@code Some} {@code Tuple} * of the value to add to the resulting Vector and * the element for the next call. * <p> * Example: * <pre> * <code> * Vector.unfoldLeft(10, x -&gt; x == 0 * ? Option.none() * : Option.of(new Tuple2&lt;&gt;(x-1, x))); * // Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) * </code> * </pre> * * @param <T> type of seeds * @param <U> type of unfolded values * @param seed the start value for the iteration * @param f the function to get the next step of the iteration * @return a Vector with the values built up by the iteration * @throws NullPointerException if {@code f} is null */ public static <T, U> Vector<U> unfoldLeft(T seed, Function<? super T, Option<Tuple2<? extends T, ? extends U>>> f) { return Iterator.unfoldLeft(seed, f).toVector(); } /** * Creates a Vector from a seed value and a function. * The function takes the seed at first. * The function should return {@code None} when it's * done generating the Vector, otherwise {@code Some} {@code Tuple} * of the value to add to the resulting Vector and * the element for the next call. * <p> * Example: * <pre> * <code> * Vector.unfold(10, x -&gt; x == 0 * ? Option.none() * : Option.of(new Tuple2&lt;&gt;(x-1, x))); * // Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) * </code> * </pre> * * @param <T> type of seeds and unfolded values * @param seed the start value for the iteration * @param f the function to get the next step of the iteration * @return a Vector with the values built up by the iteration * @throws NullPointerException if {@code f} is null */ public static <T> Vector<T> unfold(T seed, Function<? super T, Option<Tuple2<? extends T, ? extends T>>> f) { return Iterator.unfold(seed, f).toVector(); } @Override public Vector<T> append(T element) { return appendAll(List.of(element)); } @Override public Vector<T> appendAll(Iterable<? extends T> iterable) { Objects.requireNonNull(iterable, "iterable is null"); return isEmpty() ? ofAll(iterable) : wrap(trie.appendAll(iterable)); } @Override public Vector<Vector<T>> combinations() { return rangeClosed(0, length()).map(this::combinations).flatMap(Function.identity()); } @Override public Vector<Vector<T>> combinations(int k) { return Combinations.apply(this, Math.max(k, 0)); } @Override public Iterator<Vector<T>> crossProduct(int power) { return Collections.crossProduct(empty(), this, power); } @Override public Vector<T> distinct() { return distinctBy(Function.identity()); } @Override public Vector<T> distinctBy(Comparator<? super T> comparator) { Objects.requireNonNull(comparator, "comparator is null"); final java.util.Set<T> seen = new java.util.TreeSet<>(comparator); return filter(seen::add); } @Override public <U> Vector<T> distinctBy(Function<? super T, ? extends U> keyExtractor) { Objects.requireNonNull(keyExtractor, "keyExtractor is null"); final java.util.Set<U> seen = new java.util.HashSet<>(length()); return filter(t -> seen.add(keyExtractor.apply(t))); } @Override public Vector<T> drop(int n) { return wrap(trie.drop(n)); } @Override public Vector<T> dropWhile(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return dropUntil(predicate.negate()); } @Override public Vector<T> dropUntil(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (int i = 0; i < length(); i++) { if (predicate.test(get(i))) { return drop(i); } } return empty(); } @Override public Vector<T> dropRight(int n) { return take(length() - n); } public Vector<T> dropRightWhile(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return dropRightUntil(predicate.negate()); } public Vector<T> dropRightUntil(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (int i = length() - 1; i >= 0; i if (predicate.test(get(i))) { return take(i + 1); } } return empty(); } @Override public Vector<T> filter(Predicate<? super T> predicate) { return wrap(trie.filter(predicate)); } @Override public <U> Vector<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); final Iterator<? extends U> results = iterator().flatMap(mapper); return ofAll(results); } @Override public T get(int index) { if ((index < 0) || (index >= length())) { throw new IndexOutOfBoundsException("get(" + index + ")"); } else { return trie.get(index); } } @Override public T head() { if (isEmpty()) { throw new NoSuchElementException("head of empty Vector"); } else { return get(0); } } @Override public <C> Map<C, Vector<T>> groupBy(Function<? super T, ? extends C> classifier) { return Collections.groupBy(this, classifier, Vector::ofAll); } @Override public Iterator<Vector<T>> grouped(int size) { return sliding(size, size); } @Override public boolean hasDefiniteSize() { return true; } @Override public int indexOf(T element, int from) { for (int i = from; i < length(); i++) { if (Objects.equals(get(i), element)) { return i; } } return -1; } @Override public Vector<T> init() { if (isEmpty()) { throw new UnsupportedOperationException("init of empty Vector"); } else { return dropRight(1); } } @Override public Option<Vector<T>> initOption() { return isEmpty() ? Option.none() : Option.some(init()); } @Override public Vector<T> insert(int index, T element) { return insertAll(index, Iterator.of(element)); } @Override public Vector<T> insertAll(int index, Iterable<? extends T> elements) { if ((index < 0) || (index > length())) { throw new IndexOutOfBoundsException("insert(" + index + ", e) on Vector of length " + length()); } else { final Vector<T> begin = take(index).appendAll(elements); final Vector<T> end = drop(index); return (begin.size() > end.size()) ? begin.appendAll(end) : end.prependAll(begin); } } @Override public Vector<T> intersperse(T element) { return ofAll(iterator().intersperse(element)); } @Override public boolean isEmpty() { return length() == 0; } @Override public boolean isTraversableAgain() { return true; } @Override public Iterator<T> iterator() { return isEmpty() ? Iterator.empty() : trie.iterator(); } @Override public int lastIndexOf(T element, int end) { for (int i = Math.min(end, length() - 1); i >= 0; i if (Objects.equals(get(i), element)) { return i; } } return -1; } @Override public int length() { return trie.length(); } @Override public <U> Vector<U> map(Function<? super T, ? extends U> mapper) { return ofAll(trie.map(mapper)); } @Override public Vector<T> padTo(int length, T element) { final int actualLength = length(); return (length <= actualLength) ? this : appendAll(Iterator.continually(element) .take(length - actualLength)); } @Override public Vector<T> leftPadTo(int length, T element) { if (length <= length()) { return this; } else { final Iterator<T> prefix = Iterator.continually(element).take(length - length()); return prependAll(prefix); } } @Override public Vector<T> patch(int from, Iterable<? extends T> that, int replaced) { from = Math.max(from, 0); replaced = Math.max(replaced, 0); Vector<T> result = take(from).appendAll(that); from += replaced; result = result.appendAll(drop(from)); return result; } @Override public Tuple2<Vector<T>, Vector<T>> partition(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); final ArrayList<T> left = new ArrayList<>(), right = new ArrayList<>(); for (int i = 0; i < length(); i++) { final T t = get(i); (predicate.test(t) ? left : right).add(t); } return Tuple.of(ofAll(left), ofAll(right)); } @Override public Vector<T> peek(Consumer<? super T> action) { Objects.requireNonNull(action, "action is null"); if (!isEmpty()) { action.accept(head()); } return this; } @Override public Vector<Vector<T>> permutations() { if (isEmpty()) { return empty(); } else if (length() == 1) { return of(this); } else { Vector<Vector<T>> results = empty(); for (T t : distinct()) { for (Vector<T> ts : remove(t).permutations()) { results = results.append(of(t).appendAll(ts)); } } return results; } } @Override public Vector<T> prepend(T element) { return prependAll(List.of(element)); } @Override public Vector<T> prependAll(Iterable<? extends T> iterable) { Objects.requireNonNull(iterable, "iterable is null"); return isEmpty() ? ofAll(iterable) : wrap(trie.prependAll(iterable)); } @Override public Vector<T> remove(T element) { for (int i = 0; i < length(); i++) { if (Objects.equals(get(i), element)) { return removeAt(i); } } return this; } @Override public Vector<T> removeFirst(Predicate<T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (int i = 0; i < length(); i++) { if (predicate.test(get(i))) { return removeAt(i); } } return this; } @Override public Vector<T> removeLast(Predicate<T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (int i = length() - 1; i >= 0; i if (predicate.test(get(i))) { return removeAt(i); } } return this; } @Override public Vector<T> removeAt(int index) { if ((index < 0) || (index >= length())) { throw new IndexOutOfBoundsException("removeAt(" + index + ")"); } else { final Vector<T> begin = take(index); final Vector<T> end = drop(index + 1); return begin.appendAll(end); } } @Override public Vector<T> removeAll(T element) { return Collections.removeAll(this, element); } @Override public Vector<T> removeAll(Iterable<? extends T> elements) { return Collections.removeAll(this, elements); } @Override public Vector<T> removeAll(Predicate<? super T> predicate) { return Collections.removeAll(this, predicate); } @Override public Vector<T> replace(T currentElement, T newElement) { return indexOfOption(currentElement) .map(i -> update(i, newElement)) .getOrElse(this); } @Override public Vector<T> replaceAll(T currentElement, T newElement) { Vector<T> result = this; int index = 0; for (T value : iterator()) { if (Objects.equals(value, currentElement)) { result = result.update(index, newElement); } index++; } return result; } @Override public Vector<T> retainAll(Iterable<? extends T> elements) { return Collections.retainAll(this, elements); } @Override public Vector<T> reverse() { return (length() <= 1) ? this : ofAll(reverseIterator()); } @Override public Vector<T> scan(T zero, BiFunction<? super T, ? super T, ? extends T> operation) { return scanLeft(zero, operation); } @Override public <U> Vector<U> scanLeft(U zero, BiFunction<? super U, ? super T, ? extends U> operation) { return Collections.scanLeft(this, zero, operation, Iterator::toVector); } @Override public <U> Vector<U> scanRight(U zero, BiFunction<? super T, ? super U, ? extends U> operation) { return Collections.scanRight(this, zero, operation, Iterator::toVector); } @Override public Vector<T> slice(int beginIndex, int endIndex) { if ((beginIndex >= endIndex) || (beginIndex >= size()) || isEmpty()) { return empty(); } else if ((beginIndex <= 0) && (endIndex >= length())) { return this; } else { return take(endIndex).drop(beginIndex); } } @Override public Iterator<Vector<T>> sliding(int size) { return sliding(size, 1); } @Override public Iterator<Vector<T>> sliding(int size, int step) { return iterator().sliding(size, step).map(Vector::ofAll); } @Override public Vector<T> sorted() { return isEmpty() ? this : toJavaStream().sorted().collect(collector()); } @Override public Vector<T> sorted(Comparator<? super T> comparator) { Objects.requireNonNull(comparator, "comparator is null"); return isEmpty() ? this : toJavaStream().sorted(comparator).collect(collector()); } @Override public <U extends Comparable<? super U>> Vector<T> sortBy(Function<? super T, ? extends U> mapper) { return sortBy(U::compareTo, mapper); } @Override public <U> Vector<T> sortBy(Comparator<? super U> comparator, Function<? super T, ? extends U> mapper) { final Function<? super T, ? extends U> domain = Function1.of(mapper::apply).memoized(); return toJavaStream() .sorted((e1, e2) -> comparator.compare(domain.apply(e1), domain.apply(e2))) .collect(collector()); } @Override public Tuple2<Vector<T>, Vector<T>> span(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return Tuple.of(takeWhile(predicate), dropWhile(predicate)); } @Override public Tuple2<Vector<T>, Vector<T>> splitAt(int n) { return Tuple.of(take(n), drop(n)); } @Override public Tuple2<Vector<T>, Vector<T>> splitAt(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); final Vector<T> init = takeWhile(predicate.negate()); return Tuple.of(init, drop(init.size())); } @Override public Tuple2<Vector<T>, Vector<T>> splitAtInclusive(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (int i = 0; i < length(); i++) { final T value = get(i); if (predicate.test(value)) { return (i == (length() - 1)) ? Tuple.of(this, empty()) : Tuple.of(take(i + 1), drop(i + 1)); } } return Tuple.of(this, empty()); } @Override public Spliterator<T> spliterator() { return Spliterators.spliterator(iterator(), length(), Spliterator.ORDERED | Spliterator.IMMUTABLE); } @Override public Vector<T> subSequence(int beginIndex) { if ((beginIndex < 0) || (beginIndex > length())) { throw new IndexOutOfBoundsException("subSequence(" + beginIndex + ")"); } else { return drop(beginIndex); } } @Override public Vector<T> subSequence(int beginIndex, int endIndex) { if ((beginIndex < 0) || (beginIndex > endIndex) || (endIndex > length())) { throw new IndexOutOfBoundsException("subSequence(" + beginIndex + ", " + endIndex + ") on Vector of size " + length()); } else { return slice(beginIndex, endIndex); } } @Override public Vector<T> tail() { if (isEmpty()) { throw new UnsupportedOperationException("tail of empty Vector"); } else { return drop(1); } } @Override public Option<Vector<T>> tailOption() { return isEmpty() ? Option.none() : Option.some(tail()); } @Override public Vector<T> take(int n) { return wrap(trie.take(n)); } @Override public Vector<T> takeRight(int n) { return drop(length() - n); } @Override public Vector<T> takeUntil(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return takeWhile(predicate.negate()); } @Override public Vector<T> takeWhile(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (int i = 0; i < length(); i++) { final T value = get(i); if (!predicate.test(value)) { return take(i); } } return this; } /** * Transforms this {@code Vector}. * * @param f A transformation * @param <U> Type of transformation result * @return An instance of type {@code U} * @throws NullPointerException if {@code f} is null */ public <U> U transform(Function<? super Vector<T>, ? extends U> f) { Objects.requireNonNull(f, "f is null"); return f.apply(this); } @Override public <U> Vector<U> unit(Iterable<? extends U> iterable) { return ofAll(iterable); } @Override public <T1, T2> Tuple2<Vector<T1>, Vector<T2>> unzip(Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) { Objects.requireNonNull(unzipper, "unzipper is null"); Vector<T1> xs = empty(); Vector<T2> ys = empty(); for (int i = 0; i < length(); i++) { final Tuple2<? extends T1, ? extends T2> t = unzipper.apply(get(i)); xs = xs.append(t._1); ys = ys.append(t._2); } return Tuple.of(xs, ys); } @Override public <T1, T2, T3> Tuple3<Vector<T1>, Vector<T2>, Vector<T3>> unzip3(Function<? super T, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) { Objects.requireNonNull(unzipper, "unzipper is null"); Vector<T1> xs = empty(); Vector<T2> ys = empty(); Vector<T3> zs = empty(); for (int i = 0; i < length(); i++) { final Tuple3<? extends T1, ? extends T2, ? extends T3> t = unzipper.apply(get(i)); xs = xs.append(t._1); ys = ys.append(t._2); zs = zs.append(t._3); } return Tuple.of(xs, ys, zs); } @Override public Vector<T> update(int index, T element) { if ((index < 0) || (index >= length())) { throw new IndexOutOfBoundsException("update(" + index + ")"); } else { return wrap(trie.update(index, element)); } } @Override public <U> Vector<Tuple2<T, U>> zip(Iterable<? extends U> that) { return zipWith(that, Tuple::of); } @Override public <U, R> Vector<R> zipWith(Iterable<? extends U> that, BiFunction<? super T, ? super U, ? extends R> mapper) { Objects.requireNonNull(that, "that is null"); Objects.requireNonNull(mapper, "mapper is null"); return ofAll(iterator().zipWith(that, mapper)); } @Override public <U> Vector<Tuple2<T, U>> zipAll(Iterable<? extends U> that, T thisElem, U thatElem) { Objects.requireNonNull(that, "that is null"); return ofAll(iterator().zipAll(that, thisElem, thatElem)); } @Override public Vector<Tuple2<T, Integer>> zipWithIndex() { return zipWithIndex(Tuple::of); } @Override public <U> Vector<U> zipWithIndex(BiFunction<? super T, ? super Integer, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return ofAll(iterator().zipWithIndex(mapper)); } private Object readResolve() { return isEmpty() ? EMPTY : this; } @Override public boolean equals(Object that) { return (that == this) || ((that instanceof Vector) && areEqual(this, (Vector<?>) that)); } @Override public int hashCode() { return Collections.hash(this); } @Override public String stringPrefix() { return "Vector"; } @Override public String toString() { return mkString(stringPrefix() + "(", ", ", ")"); } } interface VectorModule { final class Combinations { static <T> Vector<Vector<T>> apply(Vector<T> elements, int k) { return (k == 0) ? Vector.of(Vector.empty()) : elements.zipWithIndex().flatMap( t -> apply(elements.drop(t._2 + 1), (k - 1)).map((Vector<T> c) -> c.prepend(t._1))); } } }
package org.ccnx.ccn.config; import java.io.File; import java.io.FileOutputStream; import java.lang.reflect.Method; import java.math.BigInteger; import java.util.HashMap; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.ccnx.ccn.impl.CCNNetworkManager.NetworkProtocol; import org.ccnx.ccn.impl.encoding.BinaryXMLCodec; import org.ccnx.ccn.impl.encoding.XMLEncodable; import org.ccnx.ccn.impl.security.crypto.CCNDigestHelper; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.io.content.ContentEncodingException; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; /** * A class encapsulating a number of system-level default parameters as well as helper * functionality for managing log output and printing debug data. Eventually will * be supported by an external configuration file for controlling key parameters. * * The current basic logging infrastructure uses standard Java logging, * controlled only by a system-wide Level value. * That value, as well as other logging-related parameters are currently managed by the * Log class, but should eventually migrate here. There is a facility for selective logging * control, by turning on and off logging for individual named "modules"; though that has * not yet been widely utilized. Eventually we should support separate log Level settings * for each module when necessary. */ public class SystemConfiguration { /** * System operation timeout. Very long timeout used to wait for system events * such as stopping Daemons. */ public final static int SYSTEM_STOP_TIMEOUT = 30000; /** * Very long timeout for network operations, in msec.. */ public final static int MAX_TIMEOUT = 10000; /** * Extra-long timeout, e.g. to get around reexpression timing issues. */ public final static int EXTRA_LONG_TIMEOUT = 6000; /** * Longer timeout, for e.g. waiting for a latest version and being sure you * have anything available locally in msec. */ public final static int LONG_TIMEOUT = 3000; /** * Medium timeout, used as system default. */ public static final int MEDIUM_TIMEOUT = 1000; /** * Short timeout; for things you expect to exist or not exist locally. */ public static final int SHORT_TIMEOUT = 300; public enum DEBUGGING_FLAGS {DEBUG_SIGNATURES, DUMP_DAEMONCMD, REPO_EXITDUMP}; protected static HashMap<DEBUGGING_FLAGS,Boolean> DEBUG_FLAG_VALUES = new HashMap<DEBUGGING_FLAGS,Boolean>(); protected static String FILE_SEP = System.getProperty("file.separator"); protected static final String CCN_PROTOCOL_PROPERTY = "org.ccnx.protocol"; public static final String DEFAULT_PROTOCOL = "TCP"; // UDP or TCP allowed public static NetworkProtocol AGENT_PROTOCOL = null; // Set up below public static final String AGENT_PROTOCOL_PROPERTY = "org.ccnx.agent.protocol"; public static final String AGENT_PROTOCOL_ENVIRONMENT_VARIABLE = "CCN_AGENT_PROTOCOL"; /** * Controls whether we should exit on severe errors in the network manager. This should only be * set true in automated tests. In live running code, we hope to be able to recover instead. */ public static final boolean DEFAULT_EXIT_ON_NETWORK_ERROR = false; public static boolean EXIT_ON_NETWORK_ERROR = DEFAULT_EXIT_ON_NETWORK_ERROR; public static final String CCN_EXIT_ON_NETWORK_ERROR_PROPERTY = "org.ccnx.ExitOnNetworkError"; public static final String CCN_EXIT_ON_NETWORK_ERROR_ENVIRONMENT_VARIABLE = "CCN_EXIT_ON_NETERROR"; /** * Property to set debug flags. */ public static final String DEBUG_FLAG_PROPERTY = "com.parc.ccn.DebugFlags"; /** * Property to set directory to dump debug data. */ public static final String DEBUG_DATA_DIRECTORY_PROPERTY = "com.parc.ccn.DebugDataDirectory"; protected static final String DEFAULT_DEBUG_DATA_DIRECTORY = "./CCN_DEBUG_DATA"; protected static String DEBUG_DATA_DIRECTORY = null; /** * Tunable timeouts as well as timeout defaults. */ /** * Enumerated Name List looping timeout in ms. * Default is 300ms */ protected static final String CHILD_WAIT_INTERVAL_PROPERTY = "org.ccnx.EnumList.WaitInterval"; public final static int CHILD_WAIT_INTERVAL_DEFAULT = 300; public static int CHILD_WAIT_INTERVAL = CHILD_WAIT_INTERVAL_DEFAULT; /** * Default timeout for the flow controller */ protected static final String FC_TIMEOUT_PROPERTY = "org.ccnx.fc.timeout"; public final static int FC_TIMEOUT_DEFAULT = MAX_TIMEOUT; public static int FC_TIMEOUT = FC_TIMEOUT_DEFAULT; /** * How long to wait for a ping timeout in CCNNetworkManager */ protected static final String PING_TIMEOUT_PROPERTY = "org.ccnx.ping.timeout"; public final static int PING_TIMEOUT_DEFAULT = 1000; public static int PING_TIMEOUT = PING_TIMEOUT_DEFAULT; /** * Pipeline size for pipeline in CCNAbstractInputStream * Default is 4 */ protected static final String PIPELINE_SIZE_PROPERTY = "org.ccnx.PipelineSize"; protected static final String PIPELINE_SIZE_ENV_VAR = "JAVA_PIPELINE_SIZE"; public static int PIPELINE_SIZE = 4; /** * Pipeline segment attempts for pipeline in CCNAbstractInputStream * Default is 5 */ protected static final String PIPELINE_ATTEMPTS_PROPERTY = "org.ccnx.PipelineAttempts"; protected static final String PIPELINE_ATTEMPTS_ENV_VAR = "JAVA_PIPELINE_ATTEMPTS"; public static int PIPELINE_SEGMENTATTEMPTS = 5; /** * Pipeline round trip time factor for pipeline in CCNAbstractInputStream * Default is 2 */ protected static final String PIPELINE_RTT_PROPERTY = "org.ccnx.PipelineRTTFactor"; protected static final String PIPELINE_RTT_ENV_VAR = "JAVA_PIPELINE_RTTFACTOR"; public static int PIPELINE_RTTFACTOR = 2; /** * Pipeline stat printouts in CCNAbstractInputStream * Default is off */ protected static final String PIPELINE_STATS_PROPERTY = "org.ccnx.PipelineStats"; protected static final String PIPELINE_STATS_ENV_VAR = "JAVA_PIPELINE_STATS"; public static boolean PIPELINE_STATS = false; /** * Backwards-compatible handling of old header names. * Current default is true; eventually will be false. */ protected static final String OLD_HEADER_NAMES_PROPERTY = "org.ccnx.OldHeaderNames"; protected static final String OLD_HEADER_NAMES_ENV_VAR = "CCNX_OLD_HEADER_NAMES"; public static boolean OLD_HEADER_NAMES = true; /** * Timeout used for communication with local 'ccnd' for control operations. * An example is Face Creation and Prefix Registration. */ protected static final String CCND_OP_TIMEOUT_PROPERTY = "org.ccnx.ccnop.timeout"; public final static int CCND_OP_TIMEOUT_DEFAULT = 1000; public static int CCND_OP_TIMEOUT = CCND_OP_TIMEOUT_DEFAULT; /** * Settable system default timeout. */ protected static int _defaultTimeout = EXTRA_LONG_TIMEOUT; /** * Get system default timeout. * @return the default timeout. */ public static int getDefaultTimeout() { return _defaultTimeout; } /** * Set system default timeout. */ public static void setDefaultTimeout(int newTimeout) { _defaultTimeout = newTimeout; } /** * No timeout. Should be single value used in all places in the code where you * want to block forever. */ public final static int NO_TIMEOUT = -1; /** * Set the maximum number of attempts that VersioningProfile.getLatestVersion will * try to get a later version of an object. */ public static final int GET_LATEST_VERSION_ATTEMPTS = 10; /** * Can set compile-time default encoding here. Choices are * currently "Text" and "Binary", or better yet * BinaryXMLCodec.codecName() or TextXMLCodec.codecName(). */ protected static final String SYSTEM_DEFAULT_ENCODING = BinaryXMLCodec.codecName(); /** * Run-time default. Set to command line property if given, if not, * the system default above. */ protected static String DEFAULT_ENCODING = null; /** * Command-line property to set default encoding * @return */ protected static final String DEFAULT_ENCODING_PROPERTY = "com.parc.ccn.data.DefaultEncoding"; public static final int DEBUG_RADIX = 34; /** * Obtain the management bean for this runtime if it is available. * The class of the management bean is discovered at runtime and there * should be no static dependency on any particular bean class. * @return the bean or null if none available */ public static Object getManagementBean() { // Check if we already have a management bean; retrieve only // once per VM if (null != runtimeMXBean) { return runtimeMXBean; } ClassLoader cl = SystemConfiguration.class.getClassLoader(); try { Class<?> mgmtclass = cl.loadClass("java.lang.management.ManagementFactory"); Method getRuntimeMXBean = mgmtclass.getDeclaredMethod("getRuntimeMXBean", (Class[])null); runtimeMXBean = getRuntimeMXBean.invoke(mgmtclass, (Object[])null); } catch (Exception ex) { Log.log(Level.WARNING, "Management bean unavailable: {0}", ex.getMessage()); } return runtimeMXBean; } static { // Allow override of default debug information. String debugFlags = System.getProperty(DEBUG_FLAG_PROPERTY); if (null != debugFlags) { String [] flags = debugFlags.split(":"); for (int i=0; i < flags.length; ++i) { setDebugFlag(flags[i]); } } DEBUG_DATA_DIRECTORY = System.getProperty(DEBUG_DATA_DIRECTORY_PROPERTY, DEFAULT_DEBUG_DATA_DIRECTORY); } static { // Allow override of basic protocol String proto = SystemConfiguration.retrievePropertyOrEnvironmentVariable(AGENT_PROTOCOL_PROPERTY, AGENT_PROTOCOL_ENVIRONMENT_VARIABLE, DEFAULT_PROTOCOL); boolean found = false; for (NetworkProtocol p : NetworkProtocol.values()) { String pAsString = p.toString(); if (proto.equalsIgnoreCase(pAsString)) { Log.warning("CCN agent protocol changed to " + pAsString + " per property"); AGENT_PROTOCOL = p; found = true; break; } } if (!found) { System.err.println("The protocol must be UDP(17) or TCP (6)"); throw new IllegalArgumentException("Invalid protocol '" + proto + "' specified in " + AGENT_PROTOCOL_PROPERTY); } // Allow override of exit on network error try { EXIT_ON_NETWORK_ERROR = Boolean.parseBoolean(retrievePropertyOrEnvironmentVariable(CCN_EXIT_ON_NETWORK_ERROR_PROPERTY, CCN_EXIT_ON_NETWORK_ERROR_ENVIRONMENT_VARIABLE, Boolean.toString(DEFAULT_EXIT_ON_NETWORK_ERROR))); // Log.fine("CCND_OP_TIMEOUT = " + CCND_OP_TIMEOUT); } catch (NumberFormatException e) { System.err.println("The exit on network error must be an boolean."); throw e; } // Allow override of default enumerated name list child wait timeout. try { CHILD_WAIT_INTERVAL = Integer.parseInt(System.getProperty(CHILD_WAIT_INTERVAL_PROPERTY, Integer.toString(CHILD_WAIT_INTERVAL_DEFAULT))); // Log.fine("CHILD_WAIT_INTERVAL = " + CHILD_WAIT_INTERVAL); } catch (NumberFormatException e) { System.err.println("The ChildWaitInterval must be an integer."); throw e; } // Allow override of default pipeline size for CCNAbstractInputStream try { PIPELINE_SIZE = Integer.parseInt(retrievePropertyOrEnvironmentVariable(PIPELINE_SIZE_PROPERTY, PIPELINE_SIZE_ENV_VAR, "4")); //PIPELINE_SIZE = Integer.parseInt(System.getProperty(PIPELINE_SIZE_PROPERTY, "4")); } catch (NumberFormatException e) { System.err.println("The PipelineSize must be an integer."); throw e; } // Allow override of default pipeline size for CCNAbstractInputStream try { PIPELINE_SEGMENTATTEMPTS = Integer.parseInt(retrievePropertyOrEnvironmentVariable(PIPELINE_ATTEMPTS_PROPERTY, PIPELINE_ATTEMPTS_ENV_VAR, "5")); //PIPELINE_SIZE = Integer.parseInt(System.getProperty(PIPELINE_SIZE_PROPERTY, "4")); } catch (NumberFormatException e) { System.err.println("The PipelineAttempts must be an integer."); } // Allow override of default pipeline rtt multiplication factor for CCNAbstractInputStream try { PIPELINE_RTTFACTOR = Integer.parseInt(retrievePropertyOrEnvironmentVariable(PIPELINE_RTT_PROPERTY, PIPELINE_RTT_ENV_VAR, "2")); } catch (NumberFormatException e) { System.err.println("The PipelineRTTFactor must be an integer."); } // Allow printing of pipeline stats in CCNAbstractInputStream PIPELINE_STATS = Boolean.parseBoolean(retrievePropertyOrEnvironmentVariable(PIPELINE_STATS_PROPERTY, PIPELINE_STATS_ENV_VAR, "false")); // Allow override of default ping timeout. try { PING_TIMEOUT = Integer.parseInt(System.getProperty(PING_TIMEOUT_PROPERTY, Integer.toString(PING_TIMEOUT_DEFAULT))); // Log.fine("PING_TIMEOUT = " + PING_TIMEOUT); } catch (NumberFormatException e) { System.err.println("The ping timeout must be an integer."); throw e; } // Allow override of default flow controller timeout. try { FC_TIMEOUT = Integer.parseInt(System.getProperty(FC_TIMEOUT_PROPERTY, Integer.toString(FC_TIMEOUT_DEFAULT))); // Log.fine("PING_TIMEOUT = " + PING_TIMEOUT); } catch (NumberFormatException e) { System.err.println("The default flow controller timeout must be an integer."); throw e; } // Allow override of ccn op timeout. try { CCND_OP_TIMEOUT = Integer.parseInt(System.getProperty(CCND_OP_TIMEOUT_PROPERTY, Integer.toString(CCND_OP_TIMEOUT_DEFAULT))); // Log.fine("CCND_OP_TIMEOUT = " + CCND_OP_TIMEOUT); } catch (NumberFormatException e) { System.err.println("The ccnd op timeout must be an integer."); throw e; } // Handle old-style header names OLD_HEADER_NAMES = Boolean.parseBoolean( retrievePropertyOrEnvironmentVariable(OLD_HEADER_NAMES_PROPERTY, OLD_HEADER_NAMES_ENV_VAR, "true")); } public static String getLocalHost() { // InetAddress.getLocalHost().toString(), return "127.0.0.1"; // using InetAddress.getLocalHost gives bad results } /** * Order of precedence (highest to lowest): * * 1) dynamic setting on an individual encoder or decoder, * or in a single encode or decode call * * 2) command-line property * * 3) compiled-in default * * The latter two are handled here, the former in the encoder/decoder * machinery itself. * @return */ public static String getDefaultEncoding() { if (null == DEFAULT_ENCODING) { // First time, check for argument String commandLineProperty = System.getProperty(DEFAULT_ENCODING_PROPERTY); if (null == commandLineProperty) DEFAULT_ENCODING = SYSTEM_DEFAULT_ENCODING; else DEFAULT_ENCODING = commandLineProperty; } return DEFAULT_ENCODING; } public static void setDefaultEncoding(String encoding) { DEFAULT_ENCODING = encoding; } public static boolean checkDebugFlag(DEBUGGING_FLAGS debugFlag) { Boolean result = DEBUG_FLAG_VALUES.get(debugFlag); if (null == result) return false; return result.booleanValue(); } /** * Management bean for this runtime, if available. This is not dependent * upon availability of any particular class but discovered dynamically * from what is available at runtime. */ private static Object runtimeMXBean = null; public static void setDebugFlag(DEBUGGING_FLAGS debugFlag, boolean value) { Log.info("Debug Flag {0} set to {1}", debugFlag.toString(), value); DEBUG_FLAG_VALUES.put(debugFlag, Boolean.valueOf(value)); } public static void setDebugFlag(String debugFlag, boolean value) { try { DEBUGGING_FLAGS df = DEBUGGING_FLAGS.valueOf(debugFlag); setDebugFlag(df, value); } catch (IllegalArgumentException ax) { Log.info("Cannot set debugging flag, no known flag: " + debugFlag + ". Choices are: " + debugFlagList()); } } public static String debugFlagList() { DEBUGGING_FLAGS [] availableFlags = DEBUGGING_FLAGS.values(); StringBuffer flags = new StringBuffer(); for (int i=0; i < availableFlags.length; ++i) { if (i > 0) flags.append(":"); flags.append(availableFlags); } return flags.toString(); } public static void setDebugFlag(String debugFlag) { setDebugFlag(debugFlag, true); } public static void outputDebugData(ContentName name, XMLEncodable data) { try { byte [] encoded = data.encode(); outputDebugData(name, encoded); } catch (ContentEncodingException ex) { Log.warning("Cannot encode object : " + name + " to output for debug."); } } public static void outputDebugData(ContentName name, byte [] data) { // Output debug data under a given name. try { File dataDir = new File(DEBUG_DATA_DIRECTORY); if (!dataDir.exists()) { if (!dataDir.mkdirs()) { Log.warning("outputDebugData: Cannot create default debug data directory: " + dataDir.getAbsolutePath()); return; } } File outputParent = new File(dataDir, name.toString()); if (!outputParent.exists()) { if (!outputParent.mkdirs()) { Log.warning("outputDebugData: cannot create data parent directory: " + outputParent); } } byte [] contentDigest = CCNDigestHelper.digest(data); String contentName = new BigInteger(1, contentDigest).toString(DEBUG_RADIX); File outputFile = new File(outputParent, contentName); Log.finest("Attempting to output debug data for name " + name.toString() + " to file " + outputFile.getAbsolutePath()); FileOutputStream fos = new FileOutputStream(outputFile); fos.write(data); fos.close(); } catch (Exception e) { Log.warning("Exception attempting to log debug data for name: " + name.toString() + " " + e.getClass().getName() + ": " + e.getMessage()); } } /** * Log information about an object at level Level.INFO. See logObject(Level, String, ContentObject) for details. * @param message String to prefix output with * @param co ContentObject to print debugging information about. * @see logObject(Level, String, ContentObject) */ public static void logObject(String message, ContentObject co) { logObject(Level.INFO, message, co); } /** * Log the gory details of an object, including debugging information relevant to object signing. * @param level log Level to control printing of log messages * @param message message to prefix output with * @param co ContentObject to print debugging information for */ public static void logObject(Level level, String message, ContentObject co) { try { byte [] coDigest = CCNDigestHelper.digest(co.encode()); byte [] tbsDigest = CCNDigestHelper.digest(ContentObject.prepareContent(co.name(), co.signedInfo(), co.content())); Log.log(level, message + " name: {0} timestamp: {1} digest: {2} tbs: {3}.", co.name(), co.signedInfo().getTimestamp(), CCNDigestHelper.printBytes(coDigest, DEBUG_RADIX), CCNDigestHelper.printBytes(tbsDigest, DEBUG_RADIX)); } catch (ContentEncodingException xs) { Log.log(level, "Cannot encode object for logging: {0}.", co.name()); } } protected static String _loggingConfiguration; /** * Property to turn off access control flags. Set it to any value and it will turn off * access control; used for testing. */ public static final String LOGGING_CONFIGURATION_PROPERTY = "com.parc.ccn.LoggingConfiguration"; /** * Strings of interest to be set in the logging configuration */ public static final String DETAILED_LOGGER = "DetailedLogger"; /** * Configure logging itself. This is a set of concatenated strings set as a * command line property; it can be used to set transparent properties read * at various points in the code. */ public static String getLoggingConfiguration() { if (null == _loggingConfiguration) { _loggingConfiguration = System.getProperty(LOGGING_CONFIGURATION_PROPERTY, ""); } return _loggingConfiguration; } public static boolean hasLoggingConfigurationProperty(String property) { if (null == property) return false; return getLoggingConfiguration().contains(property); } public static String getPID() { // We try the JVM mgmt bean if available, reported to work on variety // of operating systems on the Sun JVM. The bean is obtained once per VM, // the other work to get the ID is done here. Object bean = getManagementBean(); if (null == getManagementBean()) { return null; } try { String pid = null; String vmname = null; Method getName = bean.getClass().getDeclaredMethod("getName", (Class[]) null); if (null == getName) { return null; } getName.setAccessible(true); vmname = (String) getName.invoke(bean, (Object[]) null); if (null == vmname) { return null; } // Hopefully the string is in the form "60447@ice.local", where we can pull // out the integer hoping it is identical to the OS PID Pattern exp = Pattern.compile("^(\\d+)@\\S+$"); Matcher match = exp.matcher(vmname); if (match.matches()) { pid = match.group(1); } else { // We don't have a candidate to match the OS PID, but we have the JVM name // from the mgmt bean itself so that will have to do, cleaned of spaces pid = vmname.replaceAll("\\s+", "_"); } return pid; } catch (Exception e) { return null; } } protected static Boolean _accessControlDisabled; /** * Property to turn off access control flags. Set it to any value and it will turn off * access control; used for testing. */ public static final String ACCESS_CONTROL_DISABLED_PROPERTY = "com.parc.ccn.DisableAccessControl"; /** * Allow control of access control at the command line. */ public static boolean disableAccessControl() { if (null == _accessControlDisabled) { _accessControlDisabled = (null != System.getProperty(ACCESS_CONTROL_DISABLED_PROPERTY)); } return _accessControlDisabled; } public static void setAccessControlDisabled(boolean accessControlDisabled) { _accessControlDisabled = accessControlDisabled; } /** * Retrieve a string that might be stored as an environment variable, or * overridden on the command line. If the command line variable is set, return * its (String) value; if not, return the environment variable value if available; * Caller should synchronize as appropriate. * @return The value in force for this variable, or null if unset. */ public static String retrievePropertyOrEnvironmentVariable(String javaPropertyName, String environmentVariableName, String defaultValue) { // First try the command line property. String value = null; if (null != javaPropertyName) { value = System.getProperty(javaPropertyName); } if ((null == value) && (null != environmentVariableName)) { // Try for an environment variable. value = System.getenv(environmentVariableName); } if (null == value) value = defaultValue; return value; } }
package org.ccnx.ccn.io; import java.io.IOException; import java.util.EnumSet; import java.util.logging.Level; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.impl.security.crypto.ContentKeys; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.profiles.SegmentationProfile; import org.ccnx.ccn.profiles.VersionMissingException; import org.ccnx.ccn.profiles.VersioningProfile; import org.ccnx.ccn.protocol.CCNTime; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.PublisherPublicKeyDigest; /** * A CCNInputStream that reads and writes versioned streams. * Names are versioned using the VersioningProfile. If you * ask to open a name that is already versioned, it opens that * version for you. If you ask to open a name without a version, * it attempts to open the latest version of that name. If you * attempt to open a name with a segment marker on it as well, * it opens that version of that content at that segment. * * The only behavior we have to change from superclass is that * involved in getting the first segment -- header or regular segment. * We need to make an interest that gets the latest version, and * then fills in the version information on the name we * are working with, to make sure we continue to get blocks * from the same version (even if, say someone writes another * version on top of us). */ public class CCNVersionedInputStream extends CCNInputStream { /** * Set up an input stream to read segmented CCN content under a given versioned name. * Content is assumed to be unencrypted, or keys will be retrieved automatically via another * process. * Will use the default handle given by CCNHandle#getHandle(). * Note that this constructor does not currently retrieve any * data; data is not retrieved until read() is called. This will change in the future, and * this constructor will retrieve the first block. * * @param baseName Name to read from. If it ends with a version, will retrieve that * specific version. If not, will find the latest version available. If it ends with * both a version and a segment number, will start to read from that segment of that version. * @throws IOException Not currently thrown, will be thrown when constructors retrieve first block. */ public CCNVersionedInputStream(ContentName baseName) throws IOException { super(baseName); } /** * Set up an input stream to read segmented CCN content under a given versioned name. * Content is assumed to be unencrypted, or keys will be retrieved automatically via another * process. * Will use the default handle given by CCNHandle#getHandle(). * Note that this constructor does not currently retrieve any * data; data is not retrieved until read() is called. This will change in the future, and * this constructor will retrieve the first block. * * @param baseName Name to read from. If it ends with a version, will retrieve that * specific version. If not, will find the latest version available. If it ends with * both a version and a segment number, will start to read from that segment of that version. * @param handle The CCN handle to use for data retrieval. If null, the default handle * given by CCNHandle#getHandle() will be used. * @throws IOException Not currently thrown, will be thrown when constructors retrieve first block. */ public CCNVersionedInputStream(ContentName baseName, CCNHandle handle) throws IOException { super(baseName, handle); } /** * Set up an input stream to read segmented CCN content under a given versioned name. * Content is assumed to be unencrypted, or keys will be retrieved automatically via another * process. * Will use the default handle given by CCNHandle#getHandle(). * Note that this constructor does not currently retrieve any * data; data is not retrieved until read() is called. This will change in the future, and * this constructor will retrieve the first block. * * @param baseName Name to read from. If it ends with a version, will retrieve that * specific version. If not, will find the latest version available. If it ends with * both a version and a segment number, will start to read from that segment of that version. * @param publisher The key we require to have signed this content. If null, will accept any publisher * (subject to higher-level verification). * @param handle The CCN handle to use for data retrieval. If null, the default handle * given by CCNHandle#getHandle() will be used. * @throws IOException Not currently thrown, will be thrown when constructors retrieve first block. */ public CCNVersionedInputStream(ContentName baseName, PublisherPublicKeyDigest publisher, CCNHandle handle) throws IOException { super(baseName, publisher, handle); } /** * Set up an input stream to read segmented CCN content under a given versioned name. * Content is assumed to be unencrypted, or keys will be retrieved automatically via another * process. * Will use the default handle given by CCNHandle#getHandle(). * Note that this constructor does not currently retrieve any * data; data is not retrieved until read() is called. This will change in the future, and * this constructor will retrieve the first block. * * @param baseName Name to read from. If it ends with a version, will retrieve that * specific version. If not, will find the latest version available. If it ends with * both a version and a segment number, will start to read from that segment of that version. * @param startingSegmentNumber Alternative specification of starting segment number. If * null, will be SegmentationProfile#baseSegment(). * @param handle The CCN handle to use for data retrieval. If null, the default handle * given by CCNHandle#getHandle() will be used. * @throws IOException Not currently thrown, will be thrown when constructors retrieve first block. */ public CCNVersionedInputStream(ContentName baseName, Long startingSegmentNumber, CCNHandle handle) throws IOException { super(baseName, startingSegmentNumber, handle); } /** * Set up an input stream to read segmented CCN content under a given versioned name. * Content is assumed to be unencrypted, or keys will be retrieved automatically via another * process. * Will use the default handle given by CCNHandle#getHandle(). * Note that this constructor does not currently retrieve any * data; data is not retrieved until read() is called. This will change in the future, and * this constructor will retrieve the first block. * * @param baseName Name to read from. If it ends with a version, will retrieve that * specific version. If not, will find the latest version available. If it ends with * both a version and a segment number, will start to read from that segment of that version. * @param startingSegmentNumber Alternative specification of starting segment number. If * null, will beSegmentationProfile#baseSegment(). * @param publisher The key we require to have signed this content. If null, will accept any publisher * (subject to higher-level verification). * @param handle The CCN handle to use for data retrieval. If null, the default handle * given by CCNHandle#getHandle() will be used. * @throws IOException Not currently thrown, will be thrown when constructors retrieve first block. */ public CCNVersionedInputStream(ContentName baseName, Long startingSegmentNumber, PublisherPublicKeyDigest publisher, CCNHandle handle) throws IOException { super(baseName, startingSegmentNumber, publisher, handle); } /** * Set up an input stream to read segmented CCN content under a given versioned name. * Will use the default handle given by CCNHandle#getHandle(). * Note that this constructor does not currently retrieve any * data; data is not retrieved until read() is called. This will change in the future, and * this constructor will retrieve the first block. * * @param baseName Name to read from. If it ends with a version, will retrieve that * specific version. If not, will find the latest version available. If it ends with * both a version and a segment number, will start to read from that segment of that version. * @param startingSegmentNumber Alternative specification of starting segment number. If * null, will be SegmentationProfile#baseSegment(). * @param publisher The key we require to have signed this content. If null, will accept any publisher * (subject to higher-level verification). * @param keys The keys to use to decrypt this content. If null, assumes content unencrypted, or another * process will be used to retrieve the keys. * @param handle The CCN handle to use for data retrieval. If null, the default handle * given by CCNHandle#getHandle() will be used. * @throws IOException Not currently thrown, will be thrown when constructors retrieve first block. */ public CCNVersionedInputStream(ContentName baseName, Long startingSegmentNumber, PublisherPublicKeyDigest publisher, ContentKeys keys, CCNHandle handle) throws IOException { super(baseName, startingSegmentNumber, publisher, keys, handle); } /** * Set up an input stream to read segmented CCN content starting with a given * ContentObject that has already been retrieved. Content is assumed * to be unencrypted, or keys will be retrieved automatically via another * process. * @param startingSegment The first segment to read from. If this is not the * first segment of the stream, reading will begin from this point. * We assume that the signature on this segment was verified by our caller. * @param flags any stream flags that must be set to handle even this first block (otherwise * they can be set with setFlags prior to read). Can be null. * @param handle The CCN handle to use for data retrieval. If null, the default handle * given by CCNHandle#getHandle() will be used. * @throws IOException if startingSegment does not contain a valid segment ID */ public CCNVersionedInputStream(ContentObject startingSegment, EnumSet<FlagTypes> flags, CCNHandle handle) throws IOException { super(startingSegment, flags, handle); } /** * Set up an input stream to read segmented CCN content starting with a given * ContentObject that has already been retrieved. * @param startingSegment The first segment to read from. If this is not the * first segment of the stream, reading will begin from this point. * We assume that the signature on this segment was verified by our caller. * @param keys The keys to use to decrypt this content. Null if content unencrypted, or another * process will be used to retrieve the keys. * @param flags any stream flags that must be set to handle even this first block (otherwise * they can be set with setFlags prior to read). Can be null. * @param handle The CCN handle to use for data retrieval. If null, the default handle * given by CCNHandle#getHandle() will be used. * @throws IOException if startingSegment does not contain a valid segment ID */ public CCNVersionedInputStream(ContentObject startingSegment, ContentKeys keys, EnumSet<FlagTypes> flags, CCNHandle handle) throws IOException { super(startingSegment, keys, flags, handle); } /** * Implementation of getFirstSegment() that expects segments to be versioned. If a version * (and optionally a segment) is specified in the name, gets that specific version (and segment). Otherwise, * gets the latest version available. Uses VersioningProfile#getFirstBlockOfLatestVersion(ContentName, Long, PublisherPublicKeyDigest, long, org.ccnx.ccn.ContentVerifier, CCNHandle). * @throws IOException If no block found (NoMatchingContentFoundException}), or there is * an error retrieving the block. */ @Override public ContentObject getFirstSegment() throws IOException { if (VersioningProfile.hasTerminalVersion(_baseName)) { // Get exactly this version return super.getFirstSegment(); } Log.info(Log.FAC_IO, "getFirstSegment: getting latest version of {0}", _baseName); ContentObject result = VersioningProfile.getFirstBlockOfLatestVersion(_baseName, _startingSegmentNumber, _publisher, _timeout, _handle.defaultVerifier(), _handle); if (null != result){ if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "getFirstSegment: retrieved latest version object {0} type: {1}", result.name(), result.signedInfo().getTypeName()); _baseName = SegmentationProfile.segmentRoot(result.name()); } else { Log.info(Log.FAC_IO, "getFirstSegment: no segment available for latest version of {0}", _baseName); } return result; } /** * Determines whether a given content object is the first block of the versioned stream specified. */ @Override protected boolean isFirstSegment(ContentName desiredName, ContentObject potentialFirstSegment) { return VersioningProfile.isVersionedFirstSegment(desiredName, potentialFirstSegment, _startingSegmentNumber); } /** * Convenience method. * @return The version of this content as a CCNTime. * @throws VersionMissingException If we do not yet have a versioned content name. */ public CCNTime getVersionAsTimestamp() throws VersionMissingException { if (null == _baseName) throw new VersionMissingException("Have not yet retrieved content name!"); return VersioningProfile.getLastVersionAsTimestamp(_baseName); } }
package helper; import java.net.URL; import java.text.Normalizer; import java.util.Collection; import java.util.Iterator; import org.eclipse.rdf4j.model.BNode; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.rio.RDFFormat; /** * @author Jan Schnasse * */ @SuppressWarnings("javadoc") public class GndLabelResolver { final public static String namespace = "https://d-nb.info/standards/elementset/gnd final public static String preferredName = namespace + "preferredName"; final public static String preferredNameForTheConferenceOrEvent = namespace + "preferredNameForTheConferenceOrEvent"; final public static String preferredNameForTheCorporateBody = namespace + "preferredNameForTheCorporateBody"; final public static String preferredNameForThePerson = namespace + "preferredNameForThePerson"; final public static String preferredNameForThePlaceOrGeographicName = namespace + "preferredNameForThePlaceOrGeographicName"; final public static String preferredNameForTheSubjectHeading = namespace + "preferredNameForTheSubjectHeading"; final public static String preferredNameForTheWork = namespace + "preferredNameForTheWork"; final public static String id = "http://d-nb.info/gnd/"; final public static String id2 = "https://d-nb.info/gnd/"; /** * @param uri * analyes data from the url to find a proper label * @return a label */ public static String lookup(String uri, String language) { try { play.Logger.info("Lookup Label from GND. Language selection is not supported yet! " + uri); Collection<Statement> statement = RdfUtils.readRdfToGraph(new URL(uri + "/about/lds"), RDFFormat.RDFXML, "application/rdf+xml"); play.Logger.debug("Statement ArraySize= " + statement.size()); Iterator<Statement> sit = statement.iterator(); while (sit.hasNext()) { Statement s = sit.next(); play.Logger.debug("Gefundenes Statement0: " + s.getObject().stringValue()); boolean isLiteral = s.getObject() instanceof Literal; if (!(s.getSubject() instanceof BNode)) { // if (isLiteral) { ValueFactory v = SimpleValueFactory.getInstance(); Statement newS = v.createStatement(s.getSubject(), s.getPredicate(), v.createLiteral(Normalizer.normalize(s.getObject().stringValue(), Normalizer.Form.NFKC))); play.Logger.debug("Gefundenes Statement1: " + newS.getObject().stringValue()); play.Logger.debug("Gefundenes Statement2: " + s.getObject().stringValue()); String label = findLabel(newS, uri); play.Logger.debug("Gefundenes Label: " + label); if (label != null) play.Logger.info("Found Label: " + label); return label; } } } catch (Exception e) { play.Logger.error("Failed to find label for " + uri, e); } return null; } private static String findLabel(Statement s, String uri) { if (!uri.equals(s.getSubject().stringValue())) return null; if (preferredName.equals(s.getPredicate().stringValue())) { return s.getObject().stringValue(); } if (preferredNameForThePerson.equals(s.getPredicate().stringValue())) { return s.getObject().stringValue(); } if (preferredNameForTheConferenceOrEvent.equals(s.getPredicate().stringValue())) { return s.getObject().stringValue(); } if (preferredNameForTheCorporateBody.equals(s.getPredicate().stringValue())) { return s.getObject().stringValue(); } if (preferredNameForThePerson.equals(s.getPredicate().stringValue())) { return s.getObject().stringValue(); } if (preferredNameForThePlaceOrGeographicName.equals(s.getPredicate().stringValue())) { return s.getObject().stringValue(); } if (preferredNameForTheSubjectHeading.equals(s.getPredicate().stringValue())) { return s.getObject().stringValue(); } if (preferredNameForTheWork.equals(s.getPredicate().stringValue())) { return s.getObject().stringValue(); } return null; } }
package de.gurkenlabs.litiengine.entities; import java.util.EventObject; import de.gurkenlabs.litiengine.abilities.Ability; public class EntityHitEvent extends EventObject { private static final long serialVersionUID = 1582822545149624579L; private final int damage; private final boolean kill; private final transient ICombatEntity executor; private final transient ICombatEntity hitEntity; private final transient Ability ability; public EntityHitEvent(final ICombatEntity hitEntity, final Ability ability, final int damage, final boolean kill) { super(hitEntity); this.executor = ability != null ? ability.getExecutor() : null; this.hitEntity = hitEntity; this.ability = ability; this.damage = damage; this.kill = kill; } public int getDamage() { return this.damage; } public ICombatEntity getExecutor() { return this.executor; } public ICombatEntity getHitEntity() { return this.hitEntity; } public boolean wasKilled() { return this.kill; } public Ability getAbility() { return this.ability; } }
package de.hshannover.operation_muehle.logic; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class IOOperation { /** * Loads the SaveState from the file specified with name. * @param name Name of the file. * @return A SaveState from the file. * @see SaveState */ public static SaveState loadGameInfo(String name) { SaveState s = null; //Eclipse complaining if not initializing here.... Boolean problems = true; while(problems) { try { FileInputStream file = new FileInputStream(name); ObjectInputStream pump = new ObjectInputStream(file); s = (SaveState) pump.readObject(); pump.close(); problems = false; } catch (FileNotFoundException e) { System.out.println("Can't find/acces file "+name); e.printStackTrace(); } catch (IOException e) { // TODO Errormessage? e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Someone help me with this one, whats the problem? e.printStackTrace(); } } return s; } /** * Saves the given GameState in a file with the given Name. * @param name Name of the Savefile. * @param data The Data thats to be saved. * @see GameState */ public static void saveGameInfo(String name, GameState data) { boolean problems = true; while(problems) { try { FileOutputStream file = new FileOutputStream(name); ObjectOutputStream pump = new ObjectOutputStream(file); pump.writeObject(data); pump.close(); problems = false; System.out.println("Game Saved"); //GUI should print this. How? } catch (FileNotFoundException e) { System.out.println("Can't create/access the file "+name); //TODO Errormessage? e.printStackTrace(); } catch (IOException e) { // TODO Errormessage? e.printStackTrace(); } } } }