diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/com/massivecraft/factions/listeners/FactionsEntityListener.java b/src/com/massivecraft/factions/listeners/FactionsEntityListener.java index 1e471af6..a3002ff4 100644 --- a/src/com/massivecraft/factions/listeners/FactionsEntityListener.java +++ b/src/com/massivecraft/factions/listeners/FactionsEntityListener.java @@ -1,324 +1,324 @@ package com.massivecraft.factions.listeners; import java.text.MessageFormat; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EndermanPickupEvent; import org.bukkit.event.entity.EndermanPlaceEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityListener; import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.event.painting.PaintingBreakByEntityEvent; import org.bukkit.event.painting.PaintingBreakEvent; import org.bukkit.event.painting.PaintingPlaceEvent; import com.massivecraft.factions.Board; import com.massivecraft.factions.Conf; import com.massivecraft.factions.FLocation; import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayers; import com.massivecraft.factions.Faction; import com.massivecraft.factions.P; import com.massivecraft.factions.struct.FFlag; import com.massivecraft.factions.struct.Rel; import com.massivecraft.factions.util.MiscUtil; public class FactionsEntityListener extends EntityListener { public P p; public FactionsEntityListener(P p) { this.p = p; } @Override public void onEntityDeath(EntityDeathEvent event) { Entity entity = event.getEntity(); if ( ! (entity instanceof Player)) return; Player player = (Player) entity; FPlayer fplayer = FPlayers.i.get(player); Faction faction = Board.getFactionAt(new FLocation(player.getLocation())); if ( ! faction.getFlag(FFlag.POWERLOSS)) { fplayer.msg("<i>You didn't lose any power since the territory you died in works that way."); return; } if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName())) { fplayer.msg("<i>You didn't lose any power due to the world you died in."); return; } fplayer.onDeath(); fplayer.msg("<i>Your power is now <h>"+fplayer.getPowerRounded()+" / "+fplayer.getPowerMaxRounded()); } @Override public void onEntityDamage(EntityDamageEvent event) { if ( event.isCancelled()) return; if (event instanceof EntityDamageByEntityEvent) { EntityDamageByEntityEvent sub = (EntityDamageByEntityEvent)event; if ( ! this.canDamagerHurtDamagee(sub)) { event.setCancelled(true); } } // TODO: Add a no damage at all flag?? /*else if (Conf.safeZonePreventAllDamageToPlayers && isPlayerInSafeZone(event.getEntity())) { // Players can not take any damage in a Safe Zone event.setCancelled(true); }*/ } @Override public void onEntityExplode(EntityExplodeEvent event) { if ( event.isCancelled()) return; for (Block block : event.blockList()) { Faction faction = Board.getFactionAt(new FLocation(block)); if (faction.getFlag(FFlag.EXPLOSIONS) == false) { // faction is peaceful and has explosions set to disabled event.setCancelled(true); return; } } } public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub) { Entity damager = sub.getDamager(); Entity damagee = sub.getEntity(); int damage = sub.getDamage(); if ( ! (damagee instanceof Player)) return true; FPlayer defender = FPlayers.i.get((Player)damagee); if (defender == null || defender.getPlayer() == null) { return true; } Location defenderLoc = defender.getPlayer().getLocation(); if (Conf.worldsIgnorePvP.contains(defenderLoc.getWorld().getName())) { return true; } Faction defLocFaction = Board.getFactionAt(new FLocation(defenderLoc)); // for damage caused by projectiles, getDamager() returns the projectile... what we need to know is the source if (damager instanceof Projectile) { damager = ((Projectile)damager).getShooter(); } // Players can not take attack damage in a SafeZone, or possibly peaceful territory if (defLocFaction.getFlag(FFlag.PVP) == false) { if (damager instanceof Player) { FPlayer attacker = FPlayers.i.get((Player)damager); attacker.msg("<i>PVP is disabled in %s.", defLocFaction.describeTo(attacker)); return false; } return defLocFaction.getFlag(FFlag.MONSTERS); } if ( ! (damager instanceof Player)) { return true; } FPlayer attacker = FPlayers.i.get((Player)damager); if (attacker == null || attacker.getPlayer() == null) { return true; } if (attacker.hasLoginPvpDisabled()) { attacker.msg("<i>You can't hurt other players for " + Conf.noPVPDamageToOthersForXSecondsAfterLogin + " seconds after logging in."); return false; } Faction locFaction = Board.getFactionAt(new FLocation(attacker)); // so we know from above that the defender isn't in a safezone... what about the attacker, sneaky dog that he might be? if (locFaction.getFlag(FFlag.PVP) == false) { attacker.msg("<i>PVP is disabled in %s.", locFaction.describeTo(attacker)); return false; } Faction defendFaction = defender.getFaction(); Faction attackFaction = attacker.getFaction(); if (attackFaction.isNone() && Conf.disablePVPForFactionlessPlayers) { attacker.msg("<i>You can't hurt other players until you join a faction."); return false; } else if (defendFaction.isNone()) { if (defLocFaction == attackFaction && Conf.enablePVPAgainstFactionlessInAttackersLand) { // Allow PVP vs. Factionless in attacker's faction territory return true; } else if (Conf.disablePVPForFactionlessPlayers) { attacker.msg("<i>You can't hurt players who are not currently in a faction."); return false; } } Rel relation = defendFaction.getRelationTo(attackFaction); // Check the relation if (relation.isAtLeast(Conf.friendlyFireFromRel) && defLocFaction.getFlag(FFlag.FRIENDLYFIRE) == false) { attacker.msg("<i>You can't hurt %s<i>.", relation.getDescPlayerMany()); return false; } // You can not hurt neutrals in their own territory. boolean ownTerritory = defender.isInOwnTerritory(); - if (ownTerritory && relation == Rel.NEUTRAL) + if (defender.hasFaction() && ownTerritory && relation == Rel.NEUTRAL) { attacker.msg("<i>You can't hurt %s<i> in their own territory unless you declare them as an enemy.", defender.describeTo(attacker)); defender.msg("%s<i> tried to hurt you.", attacker.describeTo(defender, true)); return false; } // Damage will be dealt. However check if the damage should be reduced. if (ownTerritory && Conf.territoryShieldFactor > 0) { int newDamage = (int)Math.ceil(damage * (1D - Conf.territoryShieldFactor)); sub.setDamage(newDamage); // Send message String perc = MessageFormat.format("{0,number,#%}", (Conf.territoryShieldFactor)); // TODO does this display correctly?? defender.msg("<i>Enemy damage reduced by <rose>%s<i>.", perc); } return true; } @Override public void onCreatureSpawn(CreatureSpawnEvent event) { if (event.isCancelled()) return; if (event.getLocation() == null) return; FLocation floc = new FLocation(event.getLocation()); Faction faction = Board.getFactionAt(floc); if (faction.getFlag(FFlag.MONSTERS)) return; if ( ! Conf.monsters.contains(event.getCreatureType())) return; event.setCancelled(true); } @Override public void onEntityTarget(EntityTargetEvent event) { if (event.isCancelled()) return; // if there is a target Entity target = event.getTarget(); if (target == null) return; // We are interested in blocking targeting for certain mobs: if ( ! Conf.monsters.contains(MiscUtil.creatureTypeFromEntity(event.getEntity()))) return; FLocation floc = new FLocation(target.getLocation()); Faction faction = Board.getFactionAt(floc); if (faction.getFlag(FFlag.MONSTERS)) return; event.setCancelled(true); } @Override public void onPaintingBreak(PaintingBreakEvent event) { if (event.isCancelled()) return; if (! (event instanceof PaintingBreakByEntityEvent)) { return; } Entity breaker = ((PaintingBreakByEntityEvent)event).getRemover(); if (! (breaker instanceof Player)) { return; } if ( ! FactionsBlockListener.playerCanBuildDestroyBlock((Player)breaker, event.getPainting().getLocation().getBlock(), "remove paintings", false)) { event.setCancelled(true); } } @Override public void onPaintingPlace(PaintingPlaceEvent event) { if (event.isCancelled()) return; if ( ! FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation().getBlock(), "place paintings", false) ) { event.setCancelled(true); } } @Override public void onEndermanPickup(EndermanPickupEvent event) { if (event.isCancelled()) return; FLocation floc = new FLocation(event.getBlock()); Faction faction = Board.getFactionAt(floc); if (faction.getFlag(FFlag.ENDERGRIEF)) return; event.setCancelled(true); } @Override public void onEndermanPlace(EndermanPlaceEvent event) { if (event.isCancelled()) return; FLocation floc = new FLocation(event.getLocation()); Faction faction = Board.getFactionAt(floc); if (faction.getFlag(FFlag.ENDERGRIEF)) return; event.setCancelled(true); } }
true
true
public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub) { Entity damager = sub.getDamager(); Entity damagee = sub.getEntity(); int damage = sub.getDamage(); if ( ! (damagee instanceof Player)) return true; FPlayer defender = FPlayers.i.get((Player)damagee); if (defender == null || defender.getPlayer() == null) { return true; } Location defenderLoc = defender.getPlayer().getLocation(); if (Conf.worldsIgnorePvP.contains(defenderLoc.getWorld().getName())) { return true; } Faction defLocFaction = Board.getFactionAt(new FLocation(defenderLoc)); // for damage caused by projectiles, getDamager() returns the projectile... what we need to know is the source if (damager instanceof Projectile) { damager = ((Projectile)damager).getShooter(); } // Players can not take attack damage in a SafeZone, or possibly peaceful territory if (defLocFaction.getFlag(FFlag.PVP) == false) { if (damager instanceof Player) { FPlayer attacker = FPlayers.i.get((Player)damager); attacker.msg("<i>PVP is disabled in %s.", defLocFaction.describeTo(attacker)); return false; } return defLocFaction.getFlag(FFlag.MONSTERS); } if ( ! (damager instanceof Player)) { return true; } FPlayer attacker = FPlayers.i.get((Player)damager); if (attacker == null || attacker.getPlayer() == null) { return true; } if (attacker.hasLoginPvpDisabled()) { attacker.msg("<i>You can't hurt other players for " + Conf.noPVPDamageToOthersForXSecondsAfterLogin + " seconds after logging in."); return false; } Faction locFaction = Board.getFactionAt(new FLocation(attacker)); // so we know from above that the defender isn't in a safezone... what about the attacker, sneaky dog that he might be? if (locFaction.getFlag(FFlag.PVP) == false) { attacker.msg("<i>PVP is disabled in %s.", locFaction.describeTo(attacker)); return false; } Faction defendFaction = defender.getFaction(); Faction attackFaction = attacker.getFaction(); if (attackFaction.isNone() && Conf.disablePVPForFactionlessPlayers) { attacker.msg("<i>You can't hurt other players until you join a faction."); return false; } else if (defendFaction.isNone()) { if (defLocFaction == attackFaction && Conf.enablePVPAgainstFactionlessInAttackersLand) { // Allow PVP vs. Factionless in attacker's faction territory return true; } else if (Conf.disablePVPForFactionlessPlayers) { attacker.msg("<i>You can't hurt players who are not currently in a faction."); return false; } } Rel relation = defendFaction.getRelationTo(attackFaction); // Check the relation if (relation.isAtLeast(Conf.friendlyFireFromRel) && defLocFaction.getFlag(FFlag.FRIENDLYFIRE) == false) { attacker.msg("<i>You can't hurt %s<i>.", relation.getDescPlayerMany()); return false; } // You can not hurt neutrals in their own territory. boolean ownTerritory = defender.isInOwnTerritory(); if (ownTerritory && relation == Rel.NEUTRAL) { attacker.msg("<i>You can't hurt %s<i> in their own territory unless you declare them as an enemy.", defender.describeTo(attacker)); defender.msg("%s<i> tried to hurt you.", attacker.describeTo(defender, true)); return false; } // Damage will be dealt. However check if the damage should be reduced. if (ownTerritory && Conf.territoryShieldFactor > 0) { int newDamage = (int)Math.ceil(damage * (1D - Conf.territoryShieldFactor)); sub.setDamage(newDamage); // Send message String perc = MessageFormat.format("{0,number,#%}", (Conf.territoryShieldFactor)); // TODO does this display correctly?? defender.msg("<i>Enemy damage reduced by <rose>%s<i>.", perc); } return true; }
public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub) { Entity damager = sub.getDamager(); Entity damagee = sub.getEntity(); int damage = sub.getDamage(); if ( ! (damagee instanceof Player)) return true; FPlayer defender = FPlayers.i.get((Player)damagee); if (defender == null || defender.getPlayer() == null) { return true; } Location defenderLoc = defender.getPlayer().getLocation(); if (Conf.worldsIgnorePvP.contains(defenderLoc.getWorld().getName())) { return true; } Faction defLocFaction = Board.getFactionAt(new FLocation(defenderLoc)); // for damage caused by projectiles, getDamager() returns the projectile... what we need to know is the source if (damager instanceof Projectile) { damager = ((Projectile)damager).getShooter(); } // Players can not take attack damage in a SafeZone, or possibly peaceful territory if (defLocFaction.getFlag(FFlag.PVP) == false) { if (damager instanceof Player) { FPlayer attacker = FPlayers.i.get((Player)damager); attacker.msg("<i>PVP is disabled in %s.", defLocFaction.describeTo(attacker)); return false; } return defLocFaction.getFlag(FFlag.MONSTERS); } if ( ! (damager instanceof Player)) { return true; } FPlayer attacker = FPlayers.i.get((Player)damager); if (attacker == null || attacker.getPlayer() == null) { return true; } if (attacker.hasLoginPvpDisabled()) { attacker.msg("<i>You can't hurt other players for " + Conf.noPVPDamageToOthersForXSecondsAfterLogin + " seconds after logging in."); return false; } Faction locFaction = Board.getFactionAt(new FLocation(attacker)); // so we know from above that the defender isn't in a safezone... what about the attacker, sneaky dog that he might be? if (locFaction.getFlag(FFlag.PVP) == false) { attacker.msg("<i>PVP is disabled in %s.", locFaction.describeTo(attacker)); return false; } Faction defendFaction = defender.getFaction(); Faction attackFaction = attacker.getFaction(); if (attackFaction.isNone() && Conf.disablePVPForFactionlessPlayers) { attacker.msg("<i>You can't hurt other players until you join a faction."); return false; } else if (defendFaction.isNone()) { if (defLocFaction == attackFaction && Conf.enablePVPAgainstFactionlessInAttackersLand) { // Allow PVP vs. Factionless in attacker's faction territory return true; } else if (Conf.disablePVPForFactionlessPlayers) { attacker.msg("<i>You can't hurt players who are not currently in a faction."); return false; } } Rel relation = defendFaction.getRelationTo(attackFaction); // Check the relation if (relation.isAtLeast(Conf.friendlyFireFromRel) && defLocFaction.getFlag(FFlag.FRIENDLYFIRE) == false) { attacker.msg("<i>You can't hurt %s<i>.", relation.getDescPlayerMany()); return false; } // You can not hurt neutrals in their own territory. boolean ownTerritory = defender.isInOwnTerritory(); if (defender.hasFaction() && ownTerritory && relation == Rel.NEUTRAL) { attacker.msg("<i>You can't hurt %s<i> in their own territory unless you declare them as an enemy.", defender.describeTo(attacker)); defender.msg("%s<i> tried to hurt you.", attacker.describeTo(defender, true)); return false; } // Damage will be dealt. However check if the damage should be reduced. if (ownTerritory && Conf.territoryShieldFactor > 0) { int newDamage = (int)Math.ceil(damage * (1D - Conf.territoryShieldFactor)); sub.setDamage(newDamage); // Send message String perc = MessageFormat.format("{0,number,#%}", (Conf.territoryShieldFactor)); // TODO does this display correctly?? defender.msg("<i>Enemy damage reduced by <rose>%s<i>.", perc); } return true; }
diff --git a/jbpm-persistence-jpa/src/test/java/org/jbpm/persistence/util/PersistenceUtil.java b/jbpm-persistence-jpa/src/test/java/org/jbpm/persistence/util/PersistenceUtil.java index ed692794e..942d2977a 100644 --- a/jbpm-persistence-jpa/src/test/java/org/jbpm/persistence/util/PersistenceUtil.java +++ b/jbpm-persistence-jpa/src/test/java/org/jbpm/persistence/util/PersistenceUtil.java @@ -1,95 +1,95 @@ package org.jbpm.persistence.util; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.Properties; import org.h2.tools.DeleteDbFiles; import org.h2.tools.Server; import org.junit.Assert; import bitronix.tm.resource.jdbc.PoolingDataSource; public class PersistenceUtil { public static final String PERSISTENCE_UNIT_NAME = "org.jbpm.persistence.jpa"; protected static final String DATASOURCE_PROPERTIES = "/datasource.properties"; private static TestH2Server h2Server = new TestH2Server(); private static Properties getDatasourceProperties() { String propertiesNotFound = "Unable to load datasource properties ["+ DATASOURCE_PROPERTIES + "]"; InputStream propsInputStream = PersistenceUtil.class.getResourceAsStream(DATASOURCE_PROPERTIES); Assert.assertNotNull(propertiesNotFound, propsInputStream); Properties props = new Properties(); try { props.load(propsInputStream); } catch (IOException ioe) { Assert.fail(propertiesNotFound + ": " + ioe.getMessage()); ioe.printStackTrace(); } return props; } public static PoolingDataSource setupPoolingDataSource() { Properties dsProps = getDatasourceProperties(); PoolingDataSource pds = new PoolingDataSource(); // The name must match what's in the persistence.xml! pds.setUniqueName("jdbc/testDS1"); pds.setClassName(dsProps.getProperty("className")); pds.setMaxPoolSize(Integer.parseInt(dsProps.getProperty("maxPoolSize"))); pds.setAllowLocalTransactions(Boolean.parseBoolean(dsProps .getProperty("allowLocalTransactions"))); - for (String propertyName : new String[] { "user", "password", "driverClassName" }) { + for (String propertyName : new String[] { "user", "password" }) { pds.getDriverProperties().put(propertyName, dsProps.getProperty(propertyName)); } String driverClass = dsProps.getProperty("driverClassName"); if (driverClass.startsWith("org.h2")) { h2Server.start(); - for (String propertyName : new String[] { "url" }) { + for (String propertyName : new String[] { "url", "driverClassName" }) { pds.getDriverProperties().put(propertyName, dsProps.getProperty(propertyName)); } } else { for (String propertyName : new String[] { "serverName", "portNumber", "databaseName" }) { pds.getDriverProperties().put(propertyName, dsProps.getProperty(propertyName)); } } return pds; } private static class TestH2Server { private Server realH2Server; public void start() { if (realH2Server == null || !realH2Server.isRunning(false)) { try { DeleteDbFiles.execute("", "JPADroolsFlow", true); realH2Server = Server.createTcpServer(new String[0]); realH2Server.start(); } catch (SQLException e) { throw new RuntimeException("can't start h2 server db", e); } } } @Override protected void finalize() throws Throwable { if (realH2Server != null) { realH2Server.stop(); } DeleteDbFiles.execute("", "JPADroolsFlow", true); super.finalize(); } } }
false
true
public static PoolingDataSource setupPoolingDataSource() { Properties dsProps = getDatasourceProperties(); PoolingDataSource pds = new PoolingDataSource(); // The name must match what's in the persistence.xml! pds.setUniqueName("jdbc/testDS1"); pds.setClassName(dsProps.getProperty("className")); pds.setMaxPoolSize(Integer.parseInt(dsProps.getProperty("maxPoolSize"))); pds.setAllowLocalTransactions(Boolean.parseBoolean(dsProps .getProperty("allowLocalTransactions"))); for (String propertyName : new String[] { "user", "password", "driverClassName" }) { pds.getDriverProperties().put(propertyName, dsProps.getProperty(propertyName)); } String driverClass = dsProps.getProperty("driverClassName"); if (driverClass.startsWith("org.h2")) { h2Server.start(); for (String propertyName : new String[] { "url" }) { pds.getDriverProperties().put(propertyName, dsProps.getProperty(propertyName)); } } else { for (String propertyName : new String[] { "serverName", "portNumber", "databaseName" }) { pds.getDriverProperties().put(propertyName, dsProps.getProperty(propertyName)); } } return pds; }
public static PoolingDataSource setupPoolingDataSource() { Properties dsProps = getDatasourceProperties(); PoolingDataSource pds = new PoolingDataSource(); // The name must match what's in the persistence.xml! pds.setUniqueName("jdbc/testDS1"); pds.setClassName(dsProps.getProperty("className")); pds.setMaxPoolSize(Integer.parseInt(dsProps.getProperty("maxPoolSize"))); pds.setAllowLocalTransactions(Boolean.parseBoolean(dsProps .getProperty("allowLocalTransactions"))); for (String propertyName : new String[] { "user", "password" }) { pds.getDriverProperties().put(propertyName, dsProps.getProperty(propertyName)); } String driverClass = dsProps.getProperty("driverClassName"); if (driverClass.startsWith("org.h2")) { h2Server.start(); for (String propertyName : new String[] { "url", "driverClassName" }) { pds.getDriverProperties().put(propertyName, dsProps.getProperty(propertyName)); } } else { for (String propertyName : new String[] { "serverName", "portNumber", "databaseName" }) { pds.getDriverProperties().put(propertyName, dsProps.getProperty(propertyName)); } } return pds; }
diff --git a/src/com/android/settings/jellybam/BamHaloSettings.java b/src/com/android/settings/jellybam/BamHaloSettings.java index 725c8d606..4149722e5 100644 --- a/src/com/android/settings/jellybam/BamHaloSettings.java +++ b/src/com/android/settings/jellybam/BamHaloSettings.java @@ -1,204 +1,204 @@ /* * Copyright (C) 2012 ParanoidAndroid Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings.jellybam; import android.app.ActivityManager; import android.app.AlertDialog; import android.app.INotificationManager; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnMultiChoiceClickListener; import android.os.Bundle; import android.os.RemoteException; import android.os.ServiceManager; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceCategory; import android.preference.PreferenceScreen; import android.preference.Preference.OnPreferenceClickListener; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.view.IWindowManager; import com.android.settings.R; import com.android.settings.SettingsPreferenceFragment; import com.android.settings.Utils; import com.android.settings.util.Helpers; import net.margaritov.preference.colorpicker.ColorPickerPreference; public class BamHaloSettings extends SettingsPreferenceFragment implements Preference.OnPreferenceChangeListener { private static final String KEY_HALO_ENABLED = "halo_enabled"; private static final String KEY_HALO_STATE = "halo_state"; private static final String KEY_HALO_HIDE = "halo_hide"; private static final String KEY_HALO_REVERSED = "halo_reversed"; private static final String KEY_HALO_PAUSE = "halo_pause"; private static final String PREF_HALO_COLORS = "halo_colors"; private static final String PREF_HALO_CIRCLE_COLOR = "halo_circle_color"; private static final String PREF_HALO_EFFECT_COLOR = "halo_effect_color"; private static final String PREF_HALO_BUBBLE_COLOR = "halo_bubble_color"; private static final String PREF_HALO_BUBBLE_TEXT_COLOR = "halo_bubble_text_color"; private ListPreference mHaloState; private CheckBoxPreference mHaloEnabled; private CheckBoxPreference mHaloHide; private CheckBoxPreference mHaloReversed; private CheckBoxPreference mHaloPause; private CheckBoxPreference mHaloColors; private ColorPickerPreference mHaloCircleColor; private ColorPickerPreference mHaloEffectColor; private ColorPickerPreference mHaloBubbleColor; private ColorPickerPreference mHaloBubbleTextColor; private Context mContext; private INotificationManager mNotificationManager; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = getActivity(); - addPreferencesFromResource(R.xml.halo_settings); + addPreferencesFromResource(R.xml.jellybam_halo_settings); mNotificationManager = INotificationManager.Stub.asInterface( ServiceManager.getService(Context.NOTIFICATION_SERVICE)); mHaloEnabled = (CheckBoxPreference) findPreference(KEY_HALO_ENABLED); mHaloEnabled.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_ENABLED, 0) == 1); mHaloState = (ListPreference) findPreference(KEY_HALO_STATE); mHaloState.setValue(String.valueOf((isHaloPolicyBlack() ? "1" : "0"))); mHaloState.setOnPreferenceChangeListener(this); mHaloHide = (CheckBoxPreference) findPreference(KEY_HALO_HIDE); mHaloHide.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_HIDE, 0) == 1); mHaloReversed = (CheckBoxPreference) findPreference(KEY_HALO_REVERSED); mHaloReversed.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_REVERSED, 1) == 1); int isLowRAM = (ActivityManager.isLargeRAM()) ? 0 : 1; mHaloPause = (CheckBoxPreference) findPreference(KEY_HALO_PAUSE); mHaloPause.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_PAUSE, isLowRAM) == 1); mHaloColors = (CheckBoxPreference) findPreference(PREF_HALO_COLORS); mHaloColors.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_COLORS, 0) == 1); mHaloEffectColor = (ColorPickerPreference) findPreference(PREF_HALO_EFFECT_COLOR); mHaloEffectColor.setOnPreferenceChangeListener(this); mHaloCircleColor = (ColorPickerPreference) findPreference(PREF_HALO_CIRCLE_COLOR); mHaloCircleColor.setOnPreferenceChangeListener(this); mHaloBubbleColor = (ColorPickerPreference) findPreference(PREF_HALO_BUBBLE_COLOR); mHaloBubbleColor.setOnPreferenceChangeListener(this); mHaloBubbleTextColor = (ColorPickerPreference) findPreference(PREF_HALO_BUBBLE_TEXT_COLOR); mHaloBubbleTextColor.setOnPreferenceChangeListener(this); } private boolean isHaloPolicyBlack() { try { return mNotificationManager.isHaloPolicyBlack(); } catch (android.os.RemoteException ex) { // System dead } return true; } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (preference == mHaloHide) { Settings.System.putInt(mContext.getContentResolver(), Settings.System.HALO_HIDE, mHaloHide.isChecked() ? 1 : 0); } else if (preference == mHaloEnabled) { Settings.System.putInt(mContext.getContentResolver(), Settings.System.HALO_ENABLED, mHaloEnabled.isChecked() ? 1 : 0); } else if (preference == mHaloReversed) { Settings.System.putInt(mContext.getContentResolver(), Settings.System.HALO_REVERSED, mHaloReversed.isChecked() ? 1 : 0); } else if (preference == mHaloPause) { Settings.System.putInt(mContext.getContentResolver(), Settings.System.HALO_PAUSE, mHaloPause.isChecked() ? 1 : 0); } else if (preference == mHaloColors) { Settings.System.putInt(mContext.getContentResolver(), Settings.System.HALO_COLORS, mHaloColors.isChecked() ? 1 : 0); Helpers.restartSystemUI(); } return super.onPreferenceTreeClick(preferenceScreen, preference); } public boolean onPreferenceChange(Preference preference, Object Value) { if (preference == mHaloState) { boolean state = Integer.valueOf((String) Value) == 1; try { mNotificationManager.setHaloPolicyBlack(state); } catch (android.os.RemoteException ex) { // System dead } return true; } else if (preference == mHaloCircleColor) { String hex = ColorPickerPreference.convertToARGB( Integer.valueOf(String.valueOf(Value))); preference.setSummary(hex); int intHex = ColorPickerPreference.convertToColorInt(hex); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.HALO_CIRCLE_COLOR, intHex); return true; } else if (preference == mHaloEffectColor) { String hex = ColorPickerPreference.convertToARGB( Integer.valueOf(String.valueOf(Value))); preference.setSummary(hex); int intHex = ColorPickerPreference.convertToColorInt(hex); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.HALO_EFFECT_COLOR, intHex); Helpers.restartSystemUI(); return true; } else if (preference == mHaloBubbleColor) { String hex = ColorPickerPreference.convertToARGB( Integer.valueOf(String.valueOf(Value))); preference.setSummary(hex); int intHex = ColorPickerPreference.convertToColorInt(hex); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.HALO_BUBBLE_COLOR, intHex); return true; } else if (preference == mHaloBubbleTextColor) { String hex = ColorPickerPreference.convertToARGB( Integer.valueOf(String.valueOf(Value))); preference.setSummary(hex); int intHex = ColorPickerPreference.convertToColorInt(hex); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.HALO_BUBBLE_TEXT_COLOR, intHex); return true; } return false; } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = getActivity(); addPreferencesFromResource(R.xml.halo_settings); mNotificationManager = INotificationManager.Stub.asInterface( ServiceManager.getService(Context.NOTIFICATION_SERVICE)); mHaloEnabled = (CheckBoxPreference) findPreference(KEY_HALO_ENABLED); mHaloEnabled.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_ENABLED, 0) == 1); mHaloState = (ListPreference) findPreference(KEY_HALO_STATE); mHaloState.setValue(String.valueOf((isHaloPolicyBlack() ? "1" : "0"))); mHaloState.setOnPreferenceChangeListener(this); mHaloHide = (CheckBoxPreference) findPreference(KEY_HALO_HIDE); mHaloHide.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_HIDE, 0) == 1); mHaloReversed = (CheckBoxPreference) findPreference(KEY_HALO_REVERSED); mHaloReversed.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_REVERSED, 1) == 1); int isLowRAM = (ActivityManager.isLargeRAM()) ? 0 : 1; mHaloPause = (CheckBoxPreference) findPreference(KEY_HALO_PAUSE); mHaloPause.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_PAUSE, isLowRAM) == 1); mHaloColors = (CheckBoxPreference) findPreference(PREF_HALO_COLORS); mHaloColors.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_COLORS, 0) == 1); mHaloEffectColor = (ColorPickerPreference) findPreference(PREF_HALO_EFFECT_COLOR); mHaloEffectColor.setOnPreferenceChangeListener(this); mHaloCircleColor = (ColorPickerPreference) findPreference(PREF_HALO_CIRCLE_COLOR); mHaloCircleColor.setOnPreferenceChangeListener(this); mHaloBubbleColor = (ColorPickerPreference) findPreference(PREF_HALO_BUBBLE_COLOR); mHaloBubbleColor.setOnPreferenceChangeListener(this); mHaloBubbleTextColor = (ColorPickerPreference) findPreference(PREF_HALO_BUBBLE_TEXT_COLOR); mHaloBubbleTextColor.setOnPreferenceChangeListener(this); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = getActivity(); addPreferencesFromResource(R.xml.jellybam_halo_settings); mNotificationManager = INotificationManager.Stub.asInterface( ServiceManager.getService(Context.NOTIFICATION_SERVICE)); mHaloEnabled = (CheckBoxPreference) findPreference(KEY_HALO_ENABLED); mHaloEnabled.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_ENABLED, 0) == 1); mHaloState = (ListPreference) findPreference(KEY_HALO_STATE); mHaloState.setValue(String.valueOf((isHaloPolicyBlack() ? "1" : "0"))); mHaloState.setOnPreferenceChangeListener(this); mHaloHide = (CheckBoxPreference) findPreference(KEY_HALO_HIDE); mHaloHide.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_HIDE, 0) == 1); mHaloReversed = (CheckBoxPreference) findPreference(KEY_HALO_REVERSED); mHaloReversed.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_REVERSED, 1) == 1); int isLowRAM = (ActivityManager.isLargeRAM()) ? 0 : 1; mHaloPause = (CheckBoxPreference) findPreference(KEY_HALO_PAUSE); mHaloPause.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_PAUSE, isLowRAM) == 1); mHaloColors = (CheckBoxPreference) findPreference(PREF_HALO_COLORS); mHaloColors.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_COLORS, 0) == 1); mHaloEffectColor = (ColorPickerPreference) findPreference(PREF_HALO_EFFECT_COLOR); mHaloEffectColor.setOnPreferenceChangeListener(this); mHaloCircleColor = (ColorPickerPreference) findPreference(PREF_HALO_CIRCLE_COLOR); mHaloCircleColor.setOnPreferenceChangeListener(this); mHaloBubbleColor = (ColorPickerPreference) findPreference(PREF_HALO_BUBBLE_COLOR); mHaloBubbleColor.setOnPreferenceChangeListener(this); mHaloBubbleTextColor = (ColorPickerPreference) findPreference(PREF_HALO_BUBBLE_TEXT_COLOR); mHaloBubbleTextColor.setOnPreferenceChangeListener(this); }
diff --git a/src/test/net/jpountz/lz4/LZ4FactoryTest.java b/src/test/net/jpountz/lz4/LZ4FactoryTest.java index 5262ae5..1eedb73 100644 --- a/src/test/net/jpountz/lz4/LZ4FactoryTest.java +++ b/src/test/net/jpountz/lz4/LZ4FactoryTest.java @@ -1,41 +1,41 @@ package net.jpountz.lz4; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import junit.framework.TestCase; public class LZ4FactoryTest extends TestCase { public void test() { assertEquals(LZ4JNICompressor.FAST, LZ4Factory.nativeInstance().fastCompressor()); assertEquals(LZ4JNICompressor.HIGH_COMPRESSION, LZ4Factory.nativeInstance().highCompressor()); assertEquals(LZ4JavaUnsafeCompressor.FAST, LZ4Factory.unsafeInstance().fastCompressor()); assertEquals(LZ4JavaUnsafeCompressor.HIGH_COMPRESSION, LZ4Factory.unsafeInstance().highCompressor()); assertEquals(LZ4JavaSafeCompressor.FAST, LZ4Factory.safeInstance().fastCompressor()); assertEquals(LZ4JavaSafeCompressor.HIGH_COMPRESSION, LZ4Factory.safeInstance().highCompressor()); assertEquals(LZ4JNIUncompressor.INSTANCE, LZ4Factory.nativeInstance().uncompressor()); assertEquals(LZ4JavaUnsafeUncompressor.INSTANCE, LZ4Factory.unsafeInstance().uncompressor()); assertEquals(LZ4JavaSafeUncompressor.INSTANCE, LZ4Factory.safeInstance().uncompressor()); - assertEquals(LZ4JNIUncompressor.INSTANCE, LZ4Factory.nativeInstance().unknwonSizeUncompressor()); - assertEquals(LZ4JavaUnsafeUncompressor.INSTANCE, LZ4Factory.unsafeInstance().unknwonSizeUncompressor()); - assertEquals(LZ4JavaSafeUncompressor.INSTANCE, LZ4Factory.safeInstance().unknwonSizeUncompressor()); + assertEquals(LZ4JNIUnknownSizeUncompressor.INSTANCE, LZ4Factory.nativeInstance().unknwonSizeUncompressor()); + assertEquals(LZ4JavaUnsafeUnknownSizeUncompressor.INSTANCE, LZ4Factory.unsafeInstance().unknwonSizeUncompressor()); + assertEquals(LZ4JavaSafeUnknownSizeUncompressor.INSTANCE, LZ4Factory.safeInstance().unknwonSizeUncompressor()); } }
true
true
public void test() { assertEquals(LZ4JNICompressor.FAST, LZ4Factory.nativeInstance().fastCompressor()); assertEquals(LZ4JNICompressor.HIGH_COMPRESSION, LZ4Factory.nativeInstance().highCompressor()); assertEquals(LZ4JavaUnsafeCompressor.FAST, LZ4Factory.unsafeInstance().fastCompressor()); assertEquals(LZ4JavaUnsafeCompressor.HIGH_COMPRESSION, LZ4Factory.unsafeInstance().highCompressor()); assertEquals(LZ4JavaSafeCompressor.FAST, LZ4Factory.safeInstance().fastCompressor()); assertEquals(LZ4JavaSafeCompressor.HIGH_COMPRESSION, LZ4Factory.safeInstance().highCompressor()); assertEquals(LZ4JNIUncompressor.INSTANCE, LZ4Factory.nativeInstance().uncompressor()); assertEquals(LZ4JavaUnsafeUncompressor.INSTANCE, LZ4Factory.unsafeInstance().uncompressor()); assertEquals(LZ4JavaSafeUncompressor.INSTANCE, LZ4Factory.safeInstance().uncompressor()); assertEquals(LZ4JNIUncompressor.INSTANCE, LZ4Factory.nativeInstance().unknwonSizeUncompressor()); assertEquals(LZ4JavaUnsafeUncompressor.INSTANCE, LZ4Factory.unsafeInstance().unknwonSizeUncompressor()); assertEquals(LZ4JavaSafeUncompressor.INSTANCE, LZ4Factory.safeInstance().unknwonSizeUncompressor()); }
public void test() { assertEquals(LZ4JNICompressor.FAST, LZ4Factory.nativeInstance().fastCompressor()); assertEquals(LZ4JNICompressor.HIGH_COMPRESSION, LZ4Factory.nativeInstance().highCompressor()); assertEquals(LZ4JavaUnsafeCompressor.FAST, LZ4Factory.unsafeInstance().fastCompressor()); assertEquals(LZ4JavaUnsafeCompressor.HIGH_COMPRESSION, LZ4Factory.unsafeInstance().highCompressor()); assertEquals(LZ4JavaSafeCompressor.FAST, LZ4Factory.safeInstance().fastCompressor()); assertEquals(LZ4JavaSafeCompressor.HIGH_COMPRESSION, LZ4Factory.safeInstance().highCompressor()); assertEquals(LZ4JNIUncompressor.INSTANCE, LZ4Factory.nativeInstance().uncompressor()); assertEquals(LZ4JavaUnsafeUncompressor.INSTANCE, LZ4Factory.unsafeInstance().uncompressor()); assertEquals(LZ4JavaSafeUncompressor.INSTANCE, LZ4Factory.safeInstance().uncompressor()); assertEquals(LZ4JNIUnknownSizeUncompressor.INSTANCE, LZ4Factory.nativeInstance().unknwonSizeUncompressor()); assertEquals(LZ4JavaUnsafeUnknownSizeUncompressor.INSTANCE, LZ4Factory.unsafeInstance().unknwonSizeUncompressor()); assertEquals(LZ4JavaSafeUnknownSizeUncompressor.INSTANCE, LZ4Factory.safeInstance().unknwonSizeUncompressor()); }
diff --git a/graph/src/main/java/edu/jhuapl/graphs/controller/GraphController.java b/graph/src/main/java/edu/jhuapl/graphs/controller/GraphController.java old mode 100644 new mode 100755 index 4f5a012..c93905e --- a/graph/src/main/java/edu/jhuapl/graphs/controller/GraphController.java +++ b/graph/src/main/java/edu/jhuapl/graphs/controller/GraphController.java @@ -1,1199 +1,1199 @@ /* * Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory * All rights reserved. * * This material may be used, modified, or reproduced by or for the U.S. * Government pursuant to the rights granted under the clauses at * DFARS 252.227-7013/7014 or FAR 52.227-14. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * NO WARRANTY. THIS MATERIAL IS PROVIDED "AS IS." JHU/APL DISCLAIMS ALL * WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING (BUT NOT * LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE, * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF * INTELLECTUAL PROPERTY RIGHTS. ANY USER OF THE MATERIAL ASSUMES THE ENTIRE * RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL JHU/APL BE * LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT, * CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR * INABILITY TO USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES * FOR LOST PROFITS. */ package edu.jhuapl.graphs.controller; import edu.jhuapl.graphs.DataPoint; import edu.jhuapl.graphs.DataSeries; import edu.jhuapl.graphs.Encoding; import edu.jhuapl.graphs.GraphException; import edu.jhuapl.graphs.GraphSource; import edu.jhuapl.graphs.PointInterface; import edu.jhuapl.graphs.RenderedGraph; import edu.jhuapl.graphs.jfreechart.JFreeChartBarGraphSource; import edu.jhuapl.graphs.jfreechart.JFreeChartCategoryGraphSource; import edu.jhuapl.graphs.jfreechart.JFreeChartGraphSource; import edu.jhuapl.graphs.jfreechart.utils.CustomLabelNumberAxis; import edu.jhuapl.graphs.jfreechart.utils.SparselyLabeledCategoryAxis; import org.jfree.chart.JFreeChart; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.CategoryLabelPositions; import org.jfree.chart.labels.StandardPieSectionLabelGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PiePlot; import org.jfree.chart.plot.PlotOrientation; import java.awt.*; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class GraphController { private static final int defaultMaxLegendItems = 50; private static final int maxCategoryLabelWidthRatio = 15; private static final Color noDataColor = Color.GRAY; private static final Color warningDataColor = Color.YELLOW; private static final Color alertDataColor = Color.RED; private static final Color severeDataColor = Color.MAGENTA; private static final Font graphFont = new Font("Arial", Font.BOLD, 14); private static final Font rangeAxisFont = new Font("Arial", Font.BOLD, 12); private static final Font rangeAxisLabelFont = new Font("Arial", Font.BOLD, 12); private static final Font domainAxisFont = new Font("Arial", Font.PLAIN, 11); private static final Font domainAxisLabelFont = new Font("Arial", Font.BOLD, 12); private static final Font legendFont = new Font("Arial", Font.PLAIN, 11); private String graphDataId = null; private GraphDataHandlerInterface graphDataHandler = null; private int maxLegendItems = defaultMaxLegendItems; private Map<String, String> translationMap = new HashMap<String, String>(0); public GraphController(String graphDataId, GraphDataHandlerInterface graphDataHandler, String userId) { if (graphDataId != null && graphDataId.length() > 0) { this.graphDataId = graphDataId; } else { this.graphDataId = getUniqueId(userId); } this.graphDataHandler = graphDataHandler; } public Map<String, String> getTranslationMap() { if (translationMap == null) { translationMap = new HashMap<String, String>(0); } return translationMap; } /** * Set a key value map to be used for translations. */ public void setTranslationMap(Map<String, String> translationMap) { this.translationMap = translationMap; } /** * Returns a translation of <code>word</code> if available. Note: matches case. * * @return a translation from translationMap or <code>word</code> */ protected String getTranslation(String word) { if (getTranslationMap() != null && getTranslationMap().containsKey(word)) { return getTranslationMap().get(word); } return word; } public String getGraphDataId() { return graphDataId; } /** * @param maxLegendItems Maximum number of items to display in the legend */ public void setMaxLegendItems(int maxLegendItems) { this.maxLegendItems = maxLegendItems; } public GraphObject writeTimeSeriesGraph(PrintWriter out, GraphDataInterface graphData, boolean useImageMap, boolean includeFooter, String callBackURL, boolean graphExpected) { StringBuffer sb = new StringBuffer(); GraphObject graph = writeTimeSeriesGraph(sb, graphData, useImageMap, includeFooter, callBackURL, graphExpected); out.println(sb); return graph; } public GraphObject writeTimeSeriesGraph(StringBuffer sb, GraphDataInterface graphData, boolean useImageMap, boolean includeFooter, String callBackURL, boolean graphExpected) { return writeTimeSeriesGraph(sb, graphData, useImageMap, includeFooter, true, callBackURL, graphExpected); } public GraphObject writeTimeSeriesGraph(StringBuffer sb, GraphDataInterface graphData, boolean useImageMap, boolean includeFooter, boolean includeButtons, String callBackURL, boolean graphExpected) { GraphObject graph = createTimeSeriesGraph(graphData, graphExpected); writeGraph(sb, graphData, useImageMap, includeFooter, includeButtons, callBackURL, null, null, graph); return graph; } public void dumpWriteTsGraph(PrintWriter out, GraphDataInterface graphData, boolean includeFooter, String callBackURL) { StringBuffer sb = new StringBuffer(); dumpWriteTsGraph(sb, graphData, includeFooter, callBackURL); out.println(sb); return; } public void dumpWriteTsGraph(StringBuffer sb, GraphDataInterface graphData, boolean includeFooter, String callBackURL) { Map<String, Object> graphMetaData = dumpGraph(graphData); writeGraph(sb, graphData, includeFooter, callBackURL, "imageMap" + graphDataId, null, null, graphMetaData); } public void dumpWriteTsGraph(PrintWriter out, GraphDataInterface graphData, boolean includeFooter, String callBackURL, String graphURL) { StringBuffer sb = new StringBuffer(); dumpWriteTsGraph(sb, graphData, includeFooter, callBackURL, graphURL); out.println(sb); return; } public void dumpWriteTsGraph(StringBuffer sb, GraphDataInterface graphData, boolean includeFooter, String callBackURL, String graphURL) { Map<String, Object> graphMetaData = dumpGraph(graphData); writeGraph(sb, graphData, includeFooter, graphURL, callBackURL, "imageMap" + graphDataId, null, null, graphMetaData); } public GraphObject writePieGraph(PrintWriter out, GraphDataInterface graphData, boolean useImageMap, String callBackURL) { StringBuffer sb = new StringBuffer(); GraphObject graph = writePieGraph(sb, graphData, useImageMap, callBackURL); out.println(sb); return graph; } public GraphObject writePieGraph(StringBuffer sb, GraphDataInterface graphData, boolean useImageMap, String callBackURL) { GraphObject graph = createPieGraph(graphData); writeGraph(sb, graphData, useImageMap, false, false, callBackURL, null, null, graph); return graph; } public GraphObject writeBarGraph(PrintWriter out, GraphDataInterface graphData, boolean stackGraph, boolean useImageMap, String callBackURL) { StringBuffer sb = new StringBuffer(); GraphObject graph = writeBarGraph(sb, graphData, stackGraph, useImageMap, callBackURL); out.println(sb); return graph; } public GraphObject writeBarGraph(StringBuffer sb, GraphDataInterface graphData, boolean stackGraph, boolean useImageMap, String callBackURL) { GraphObject graph = createBarGraph(graphData, stackGraph); writeGraph(sb, graphData, useImageMap, false, false, callBackURL, null, null, graph); return graph; } public GraphObject writeSeverityGraph(PrintWriter out, GraphDataInterface graphData, boolean useImageMap, String callBackURL) { StringBuffer sb = new StringBuffer(); GraphObject graph = writeSeverityGraph(sb, graphData, useImageMap, callBackURL); out.println(sb); return graph; } public GraphObject writeSeverityGraph(StringBuffer sb, GraphDataInterface graphData, boolean useImageMap, String callBackURL) { GraphObject graph = createSeverityGraph(graphData); writeGraph(sb, graphData, useImageMap, false, false, callBackURL, null, null, graph); return graph; } public GraphObject writeDualAxisGraph(PrintWriter out, GraphDataInterface graphData, boolean useImageMap, String callBackURL) { StringBuffer sb = new StringBuffer(); GraphObject graph = writeDualAxisGraph(sb, graphData, useImageMap, callBackURL); out.println(sb); return graph; } public GraphObject writeDualAxisGraph(StringBuffer sb, GraphDataInterface graphData, boolean useImageMap, String callBackURL) { GraphObject graph = createDualAxisGraph(graphData); writeGraph(sb, graphData, useImageMap, false, false, callBackURL, null, null, graph); return graph; } public GraphObject createTimeSeriesGraph(GraphDataInterface graphData, boolean graphExpected) { return createTimeSeriesGraph(graphData, null, null, null, graphExpected); } public GraphObject createTimeSeriesGraph(GraphDataInterface graphData, Double yAxisMin, Double yAxisMax, String displayKey, boolean graphExpected) { List<DataSeries> dataSeries = new ArrayList<DataSeries>(); LegendItemCollection legendItems = new LegendItemCollection(); Map<String, Object> graphMetaData = new HashMap<String, Object>(); double maxCount = setDataSeries(graphData, displayKey, false, dataSeries, legendItems, graphExpected); setTimeSeriesGraphMetaData(graphData, yAxisMin, yAxisMax, maxCount, graphMetaData); return getGraph(graphData, dataSeries, graphMetaData, legendItems, "tsgraph"); } public GraphObject createBarGraph(GraphDataInterface graphData, boolean stackGraph) { return createBarGraph(graphData, stackGraph, false); } /** * The useItemColor is still under development to allow each bar to be a different color. */ public GraphObject createBarGraph(GraphDataInterface graphData, boolean stackGraph, boolean useItemColor) { List<DataSeries> dataSeries = new ArrayList<DataSeries>(); LegendItemCollection legendItems = new LegendItemCollection(); Map<String, Object> graphMetaData = new HashMap<String, Object>(); setDataSeries(graphData, null, false, dataSeries, legendItems, useItemColor); setBarGraphMetaData(graphData, stackGraph, graphMetaData); return getGraph(graphData, dataSeries, graphMetaData, legendItems, "bargraph"); } public GraphObject createPieGraph(GraphDataInterface graphData) { return createPieGraph(graphData, Encoding.PNG); } public GraphObject createPieGraph(GraphDataInterface graphData, Encoding encoding) { GraphObject graph = null; Map<String, Object> graphMetaData = new HashMap<String, Object>(); List<PointInterface> points = new ArrayList<PointInterface>(); setPieGraphMetaData(graphData, graphMetaData, points); // I'm ashamed of this code in so many ways String graphTitle = (String) graphMetaData.get(GraphSource.GRAPH_TITLE); try { // add the created chart properties JFreeChartGraphSource graphSource = new JFreeChartGraphSource(); graphSource.setData(Arrays.asList(new DataSeries(points, new HashMap<String, Object>()))); graphSource.setParams(graphMetaData); graphSource.initialize(); if (graphData.showLegend()) { PiePlot plot = (PiePlot) graphSource.getChart().getPlot(); // use rectangles as the legend shapes plot.setLegendItemShape(new Rectangle(7, 8)); // generate tooltip for the legend items in the following format: "lineSetLabels - count" if (graphData.percentBased()) { plot.setLegendLabelToolTipGenerator(new StandardPieSectionLabelGenerator("{0} - {1} ({2})", new DecimalFormat("#.##"), new DecimalFormat( "#.##%"))); } else { plot.setLegendLabelToolTipGenerator(new StandardPieSectionLabelGenerator("{0} - {1} ({2})", new DecimalFormat("#"), new DecimalFormat( "#.##%"))); } } // render the graph to get the image map RenderedGraph renderedGraph = graphSource.renderGraph(graphData.getGraphWidth(), graphData.getGraphHeight(), encoding); String extension = ".dat"; switch (encoding) { case JPEG: extension = ".jpg"; break; case PNG: case PNG_WITH_TRANSPARENCY: extension = ".png"; break; } String imageFileName = getCleanValue(graphTitle) + "_piegraph" + extension; // get the image map String imageMapName = "imageMap" + graphDataId; String imageMap = appendImageMapTarget(renderedGraph.getImageMap(imageMapName), graphData.getLineSetURLTarget()); try { // store away the graph data file graphDataHandler.putGraphData(graphData, graphDataId); graph = new GraphObject(graphSource, renderedGraph, imageFileName, imageMapName, imageMap, graphDataId); } catch (GraphException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } catch (GraphException e) { System.out.println("Could not create pie graph " + graphTitle); e.printStackTrace(); } return graph; } public GraphObject createSeverityGraph(GraphDataInterface graphData) { List<DataSeries> dataSeries = new ArrayList<DataSeries>(); Map<String, Object> graphMetaData = new HashMap<String, Object>(); LegendItemCollection legendItems = new LegendItemCollection(); Color[] graphBaseColors = graphData.getGraphBaseColors(); Map<Double, String> tickValueToLabelMapping = new HashMap<Double, String>(); setDataSeries(graphData, null, true, dataSeries, null, false); setBarGraphMetaData(graphData, true, graphMetaData); // create a custom legend legendItems.add(new LegendItem(getTranslation("Severe"), severeDataColor)); legendItems.add(new LegendItem(getTranslation("Not Severe"), graphBaseColors[0])); legendItems.add(new LegendItem(getTranslation("No Data Available"), noDataColor)); // create custom value axis labels String[] lineSetLabels = graphData.getLineSetLabels(); double lowestTickValue = 0.5; int tickCount = lineSetLabels.length; for (int i = 0; i < tickCount; i++) { tickValueToLabelMapping.put(lowestTickValue + i, lineSetLabels[i]); } CustomLabelNumberAxis rangeAxis = new CustomLabelNumberAxis(tickValueToLabelMapping); rangeAxis.setLowestTickValue(lowestTickValue); rangeAxis.setTickCount(tickCount); graphMetaData.put(JFreeChartCategoryGraphSource.RANGE_AXIS, rangeAxis); return getGraph(graphData, dataSeries, graphMetaData, legendItems, "tsgraph"); } public GraphObject createDualAxisGraph(GraphDataInterface graphData) { List<DataSeries> dataSeries = new ArrayList<DataSeries>(); LegendItemCollection legendItems = new LegendItemCollection(); Map<String, Object> graphMetaData = new HashMap<String, Object>(); double maxCount = setDataSeries(graphData, null, false, dataSeries, legendItems, false); setTimeSeriesGraphMetaData(graphData, null, null, maxCount, graphMetaData); setBarGraphMetaData(graphData, false, graphMetaData); graphMetaData.put(GraphSource.GRAPH_TYPE, GraphSource.GRAPH_TYPE_DUAL_AXIS); return getGraph(graphData, dataSeries, graphMetaData, legendItems, "dualAxisGraph"); } public static String zipGraphs(List<GraphObject> graphs, String tempDir, String userId) throws GraphException { if (graphs != null && graphs.size() > 0) { byte[] byteBuffer = new byte[1024]; String zipFileName = getUniqueId(userId) + ".zip"; try { File zipFile = new File(tempDir, zipFileName); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)); boolean hasGraphs = false; for (GraphObject graph : graphs) { if (graph != null) { byte[] renderedGraph = graph.getRenderedGraph().getData(); ByteArrayInputStream in = new ByteArrayInputStream(renderedGraph); int len; zos.putNextEntry(new ZipEntry(graph.getImageFileName())); while ((len = in.read(byteBuffer)) > 0) { zos.write(byteBuffer, 0, len); } in.close(); zos.closeEntry(); hasGraphs = true; } } zos.close(); if (hasGraphs) { return zipFileName; } else { return null; } } catch (IOException e) { throw new GraphException("Could not write zip", e); } } return null; } private void writeSimpleLinkTSGraph(StringBuffer sb, GraphDataInterface graphData, String callbackURL, String linkURL, GraphObject graph) { int graphWidth = graphData.getGraphWidth(); int graphHeight = graphData.getGraphHeight(); sb.append("<div style=\"background-color:white; width:" + graphWidth + "px; height:" + graphHeight + "px;\">\n"); sb.append("<a href=\"").append(linkURL).append("\">"); String graphURL = callbackURL + "?graphDataId=" + graphDataId; ; sb.append("<img src=\"").append(graphURL).append("\" title=\"").append(graphData.getGraphTitle()) .append("\" border=\"0\"/></a>").append("</div>\n"); } private void writeGraph(StringBuffer sb, GraphDataInterface graphData, boolean useImageMap, boolean includeFooter, String callBackURL, String graphOptionsHelpLink, String downloadHelpLink, GraphObject graph) { writeGraph(sb, graphData, useImageMap, includeFooter, true, callBackURL, graphOptionsHelpLink, downloadHelpLink, graph); } private void writeGraph(StringBuffer sb, GraphDataInterface graphData, boolean useImageMap, boolean includeFooter, boolean includeButtons, String callBackURL, String graphOptionsHelpLink, String downloadHelpLink, GraphObject graph) { int graphWidth = graphData.getGraphWidth(); int graphHeight = graphData.getGraphHeight(); String imageMapName = graph.getImageMapName(); String graphURL = callBackURL + (callBackURL.indexOf('?') > -1 ? "&" : "?") + "graphDataId=" + graphDataId; sb.append("<div style=\"background-color:white; width:" + graphWidth + "px\">\n"); sb.append("<div id=\"graphDiv" + imageMapName + "\" style=\"width:" + graphWidth + "px; height:" + graphHeight + "px;\">\n"); if (useImageMap) { // write the graph with an image map sb.append(graph.getImageMap()); sb.append("<img src=\"" + graphURL + "\" usemap=\"#" + imageMapName + "\" border=\"0\"/>\n"); } else { // just write the graph with the option to turn it into an interactive graph sb.append("<img src=\"" + graphURL + "\" title=\"Switch to Interactive View\" onclick=\"makeInteractiveGraph('" + callBackURL + "', '" + imageMapName + "', '" + graphDataId + "');\" border=\"0\"/>\n"); } sb.append("</div>\n"); JFreeChart chart = graph.getGraphSource().getChart(); String graphTitle = chart.getTitle().getText(); String xAxisLabel = ""; String yAxisLabel = ""; double yAxisMin = 0; double yAxisMax = 0; if (chart.getPlot() instanceof CategoryPlot) { CategoryPlot plot = chart.getCategoryPlot(); xAxisLabel = plot.getDomainAxis().getLabel(); yAxisLabel = plot.getRangeAxis().getLabel(); // get the y-axis minimum and maximum range yAxisMin = plot.getRangeAxis().getRange().getLowerBound(); yAxisMax = plot.getRangeAxis().getRange().getUpperBound(); // get the y-axis minimum and maximum range graph.setYAxisMin(yAxisMin); graph.setYAxisMax(yAxisMax); //set series information for configuration graph.setDataSeriesJSON(getDataSeriesJSON(graphData.getLineSetLabels(), graphData.displayAlerts(), graphData.displaySeverityAlerts(), "\"")); } //added option to not bring back the button area - cjh if (includeButtons) { // write the footer sb.append("<div style=\"padding:5px; text-align:center;\">\n"); if (includeFooter) { //this keys it to be a timeseries graph so we can do getCategoryPlot String dataSeriesJSON = getDataSeriesJSON(graphData.getLineSetLabels(), graphData.displayAlerts(), graphData.displaySeverityAlerts(), "&quot;"); sb.append( "<input type=\"button\" style=\"font-family:Arial; font-size:0.6em;\" value=\"Graph Options\" onclick=\"showTimeSeriesGraphOptions('" + callBackURL + "', '" + imageMapName + "', '" + graphDataId + "', '" + graphTitle + "', '" + xAxisLabel + "', '" + yAxisLabel + "', " + yAxisMin + ", " + yAxisMax + ", '" + dataSeriesJSON + "');\"/>"); if (graphOptionsHelpLink != null) { sb.append(graphOptionsHelpLink); } } sb.append( "<input type=\"button\" style=\"font-family:Arial; font-size:0.6em;\" value=\"Download\" onclick=\"showDownloadOptions('" + callBackURL + "', '" + imageMapName + "', '" + graphDataId + "');\"/>"); if (downloadHelpLink != null) { sb.append(downloadHelpLink); } sb.append("</div>\n"); } sb.append("</div>\n"); if (!useImageMap) { sb.append("<div id=\"linkDiv" + imageMapName + "\" style=\"font-family: Arial; font-size: 0.7em; text-align: right\">\n"); sb.append("*Click anywhere on the graph to <a href=\"#\" onclick=\"makeInteractiveGraph('" + callBackURL + "', '" + imageMapName + "', '" + graphDataId + "'); return false;\">switch to interactive view</a>\n"); sb.append("</div>\n"); } } private void writeGraph(StringBuffer sb, GraphDataInterface graphData, boolean includeFooter, String callBackURL, String imageMapName, String graphOptionsHelpLink, String downloadHelpLink, Map<String, Object> graphMetaData) { writeGraph(sb, graphData, includeFooter, callBackURL + "?graphDataId=" + graphDataId, callBackURL, imageMapName, graphOptionsHelpLink, downloadHelpLink, graphMetaData); } public void writeGraph(StringBuffer sb, GraphDataInterface graphData, boolean includeFooter, String graphURL, String callBackURL, String imageMapName, String graphOptionsHelpLink, String downloadHelpLink, Map<String, Object> graphMetaData) { int graphWidth = graphData.getGraphWidth(); int graphHeight = graphData.getGraphHeight(); sb.append("<div style=\"background-color:white; width:" + graphWidth + "px\">\n"); sb.append("<div id=\"graphDiv" + imageMapName + "\" style=\"width:" + graphWidth + "px; height:" + graphHeight + "px;\">\n"); // just write the graph with the option to turn it into an interactive graph sb.append("<img src=\"" + graphURL + "\" title=\"Switch to Interactive View\" onclick=\"makeInteractiveGraph('" + callBackURL + "', '" + imageMapName + "', '" + graphDataId + "');\" border=\"0\"/>\n"); sb.append("</div>\n"); // write the footer sb.append("<div style=\"padding:5px; text-align:center;\">\n"); if (includeFooter) { String graphTitle = (String) graphMetaData.get(GraphSource.GRAPH_TITLE); String xAxisLabel = (String) graphMetaData.get(GraphSource.GRAPH_X_LABEL); String yAxisLabel = (String) graphMetaData.get(GraphSource.GRAPH_Y_LABEL); String dataSeriesJSON = getDataSeriesJSON(graphData.getLineSetLabels(), graphData.displayAlerts(), graphData.displaySeverityAlerts(), "&quot;"); // get the y-axis minimum and maximum range double yAxisMin = (Double) graphMetaData.get(GraphSource.GRAPH_RANGE_LOWER_BOUND); double yAxisMax = (Double) graphMetaData.get(GraphSource.GRAPH_RANGE_UPPER_BOUND); sb.append( "<input type=\"button\" style=\"font-family:Arial; font-size:0.6em;\" value=\"Graph Options\" onclick=\"showTimeSeriesGraphOptions('" + callBackURL + "', '" + imageMapName + "', '" + graphDataId + "', '" + graphTitle + "', '" + xAxisLabel + "', '" + yAxisLabel + "', " + yAxisMin + ", " + yAxisMax + ", '" + dataSeriesJSON + "');\"/>"); if (graphOptionsHelpLink != null) { sb.append(graphOptionsHelpLink); } } sb.append( "<input type=\"button\" style=\"font-family:Arial; font-size:0.6em;\" value=\"Download\" onclick=\"showDownloadOptions('" + callBackURL + "', '" + imageMapName + "', '" + graphDataId + "');\"/>"); if (downloadHelpLink != null) { sb.append(downloadHelpLink); } sb.append("</div>\n"); sb.append("</div>\n"); sb.append("<div id=\"linkDiv" + imageMapName + "\" style=\"font-family: Arial; font-size: 0.7em; text-align: right\">\n"); sb.append("*Click anywhere on the graph to <a href=\"#\" onclick=\"makeInteractiveGraph('" + callBackURL + "', '" + imageMapName + "', '" + graphDataId + "'); return false;\">switch to interactive view</a>\n"); sb.append("</div>\n"); } private double setDataSeries(GraphDataInterface graphData, String displayKey, boolean useNoDataColor, List<DataSeries> dataSeries, LegendItemCollection legendItems, boolean graphExpected) { return setDataSeries(graphData, displayKey, useNoDataColor, dataSeries, legendItems, false, graphExpected); } /** * The useItemColor is still under development to allow each bar to be a different color. */ private double setDataSeries(GraphDataInterface graphData, String displayKey, boolean useNoDataColor, List<DataSeries> dataSeries, LegendItemCollection legendItems, boolean useItemColor, boolean graphExpected) { double[][] counts = graphData.getCounts(); double[][] expecteds = graphData.getExpecteds(); int[][] colors = graphData.getColors(); String[][] altTexts = graphData.getAltTexts(); String[][] lineSetURLs = graphData.getLineSetURLs(); String[] xLabels = graphData.getXLabels(); String[] lineSetLabels = graphData.getLineSetLabels(); boolean[] displayAlerts = graphData.displayAlerts(); boolean[] displaySeverityAlerts = graphData.displaySeverityAlerts(); double[] lineSymbolSizes = graphData.getLineSymbolSizes(); Color[] graphBaseColors = graphData.getGraphBaseColors(); int displayKeyIndex = 0; double maxCount = 0; boolean singleAlertLegend = graphData.getShowSingleAlertLegend(); boolean singleSeverityLegend = graphData.getShowSingleSeverityLegend(); for (int i = 0; i < counts.length; i++) { String lineSetLabel = "series" + (i + 1); boolean displayAlert = false; boolean displaySeverityAlert = false; double lineSymbolSize = 7.0; try { lineSetLabel = lineSetLabels[i]; } catch (Exception e) { } try { displayAlert = displayAlerts[i]; } catch (Exception e) { } try { displaySeverityAlert = displaySeverityAlerts[i]; } catch (Exception e) { } try { lineSymbolSize = lineSymbolSizes[i]; } catch (Exception e) { } double xy = lineSymbolSize / 2.0 * -1; Color seriesColor = graphBaseColors[i % graphBaseColors.length]; boolean displayNormalData = displaySeries(displayKey, displayKeyIndex++) ? true : false; boolean displayWarningData = displayAlert && displaySeries(displayKey, displayKeyIndex++) ? true : false; boolean displayAlertData = displayAlert && displaySeries(displayKey, displayKeyIndex++) ? true : false; boolean displaySevereData = displaySeverityAlert && displaySeries(displayKey, displayKeyIndex++) ? true : false; List<DataPoint> points = new ArrayList<DataPoint>(); List<DataPoint> epoints = new ArrayList<DataPoint>(); /** get graph data */ for (int j = 0; j < counts[i].length; j++) { boolean alertDataExists = false; String altText = null; String lineSetURL = null; int color = 1; try { altText = altTexts[i][j]; } catch (Exception e) { } try { lineSetURL = lineSetURLs[i][j]; } catch (Exception e) { } try { color = colors[i][j]; } catch (Exception e) { } Map<String, Object> epointMetaData = new HashMap<String, Object>(); Map<String, Object> pointMetaData = new HashMap<String, Object>(); pointMetaData.put(GraphSource.ITEM_TOOL_TIP, altText); pointMetaData.put(GraphSource.ITEM_URL, lineSetURL); pointMetaData.put(GraphSource.ITEM_SHAPE, new Ellipse2D.Double(xy, xy, lineSymbolSize, lineSymbolSize)); pointMetaData.put(GraphSource.ITEM_COLOR, seriesColor); epointMetaData.put(GraphSource.ITEM_COLOR, seriesColor.brighter()); epointMetaData.put(GraphSource.ITEM_SHAPE, new Rectangle2D.Double(xy, xy, 7, 7)); epointMetaData.put(GraphSource.ITEM_TOOL_TIP, altText); // color 0 = GRAY (no data), color 2 = YELLOW (warning), 3 = RED (alert), // 4 = PURPLE (severe) if (useNoDataColor && color == 0) { pointMetaData.put(GraphSource.ITEM_COLOR, noDataColor); } else if (displayWarningData && color == 2) { alertDataExists = true; pointMetaData.put(GraphSource.ITEM_COLOR, warningDataColor); } else if (displayAlertData && color == 3) { alertDataExists = true; pointMetaData.put(GraphSource.ITEM_COLOR, alertDataColor); } else if (displaySevereData && color == 4) { alertDataExists = true; pointMetaData.put(GraphSource.ITEM_COLOR, severeDataColor); } if (useItemColor) { seriesColor = graphBaseColors[j % graphBaseColors.length]; pointMetaData.put(GraphSource.ITEM_COLOR, seriesColor); } if (displayNormalData || alertDataExists) { // only update the maxCount if this data point is visible if (counts[i][j] > maxCount) { maxCount = counts[i][j]; } } else { // if normal data is supposed to be hidden and no alert data exists, then hide this // data point pointMetaData.put(GraphSource.ITEM_VISIBLE, false); epointMetaData.put(GraphSource.ITEM_VISIBLE, false); } // if the data is set to the Double.MIN_VALUE, then add it as a null. if (counts[i][j] != Double.MIN_VALUE) { points.add(new DataPoint(counts[i][j], xLabels[j], pointMetaData)); } else { points.add(new DataPoint(null, xLabels[j], pointMetaData)); } - if (expecteds[i][j] != Double.MIN_VALUE) { + if (expecteds != null && expecteds[i][j] != Double.MIN_VALUE) { epoints.add(new DataPoint(expecteds[i][j], xLabels[j], epointMetaData)); } else { epoints.add(new DataPoint(null, xLabels[j], epointMetaData)); } } /** add the series */ // series properties Map<String, Object> dataSeriesMetaData = new HashMap<String, Object>(); dataSeriesMetaData.put(GraphSource.SERIES_TITLE, lineSetLabel); dataSeriesMetaData.put(GraphSource.SERIES_COLOR, seriesColor); // if normal data is hidden for this series, hide the series connector line dataSeriesMetaData.put(GraphSource.SERIES_LINES_VISIBLE, displayNormalData); dataSeries.add(new DataSeries(points, dataSeriesMetaData)); Map<String, Object> eDataSeriesMetaData = new HashMap<String, Object>(); eDataSeriesMetaData.put(GraphSource.SERIES_COLOR, seriesColor); eDataSeriesMetaData.put(GraphSource.SERIES_STROKE, new BasicStroke( 1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[]{10.0f, 6.0f}, 0.0f)); if (graphExpected) { dataSeries.add(new DataSeries(epoints, eDataSeriesMetaData)); } // code to set the text in the legend if (legendItems != null) { if (displayNormalData && legendItems.getItemCount() < maxLegendItems) { if (displayAlert && !singleAlertLegend) { legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Normal"), seriesColor)); } if (graphExpected) { legendItems.add(new LegendItem(lineSetLabel, seriesColor)); legendItems.add(new LegendItem(("Expected " + lineSetLabel), seriesColor)); } else { legendItems.add(new LegendItem(lineSetLabel, seriesColor)); } } if (!singleAlertLegend && displayWarningData && legendItems.getItemCount() < maxLegendItems) { legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Warning"), warningDataColor)); } if (!singleAlertLegend && displayAlertData && legendItems.getItemCount() < maxLegendItems) { legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Alert"), alertDataColor)); } if (!singleSeverityLegend && displaySevereData && legendItems.getItemCount() < maxLegendItems) { legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Severe"), severeDataColor)); } } } if (singleAlertLegend && legendItems.getItemCount() < maxLegendItems) { legendItems.add(new LegendItem(getTranslation("Warning"), warningDataColor)); legendItems.add(new LegendItem(getTranslation("Alert"), alertDataColor)); } if (singleSeverityLegend && legendItems.getItemCount() < maxLegendItems) { legendItems.add(new LegendItem(getTranslation("Severe"), severeDataColor)); } return maxCount; } public void setTimeSeriesGraphMetaData(GraphDataInterface graphData, double maxCount, Map<String, Object> graphMetaData) { setTimeSeriesGraphMetaData(graphData, null, null, maxCount, graphMetaData); } public void setTimeSeriesGraphMetaData(GraphDataInterface graphData, Double yAxisMin, Double yAxisMax, double maxCount, Map<String, Object> graphMetaData) { String graphTitle = graphData.getGraphTitle() != null ? graphData.getGraphTitle() : ""; String xAxisLabel = graphData.getXAxisLabel() != null ? graphData.getXAxisLabel() : ""; String yAxisLabel = graphData.getYAxisLabel() != null ? graphData.getYAxisLabel() : ""; int graphWidth = graphData.getGraphWidth(); int graphHeight = graphData.getGraphHeight(); boolean percentBased = graphData.percentBased(); int maxLabeledCategoryTicks = graphData.getMaxLabeledCategoryTicks(); graphMetaData.put(GraphSource.GRAPH_TYPE, GraphSource.GRAPH_TYPE_LINE); graphMetaData.put(GraphSource.BACKGROUND_COLOR, Color.WHITE); graphMetaData.put(GraphSource.GRAPH_TITLE, graphTitle); graphMetaData.put(GraphSource.GRAPH_FONT, graphFont); graphMetaData.put(GraphSource.GRAPH_MINOR_TICKS, 0); graphMetaData.put(GraphSource.GRAPH_LEGEND, graphData.showLegend()); graphMetaData.put(GraphSource.LEGEND_FONT, legendFont); SparselyLabeledCategoryAxis domainAxis; if (graphWidth >= 500 && graphHeight >= 300) { // this is a larger graph so we can add some additional properties to pretty it up graphMetaData.put(GraphSource.GRAPH_BORDER, true); graphMetaData.put(GraphSource.AXIS_OFFSET, 5.0); graphMetaData.put(GraphSource.GRAPH_RANGE_GRIDLINE_PAINT, Color.lightGray); if (yAxisLabel == null && percentBased) { yAxisLabel = getTranslation("Percent"); } else if (yAxisLabel == null) { yAxisLabel = getTranslation("Counts"); } if (xAxisLabel == null) { xAxisLabel = getTranslation("Date"); } domainAxis = new SparselyLabeledCategoryAxis(maxLabeledCategoryTicks, Color.lightGray); } else { yAxisLabel = ""; xAxisLabel = ""; domainAxis = new SparselyLabeledCategoryAxis(maxLabeledCategoryTicks); } domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createDownRotationLabelPositions(45)); domainAxis.setMaximumCategoryLabelWidthRatio(maxCategoryLabelWidthRatio); graphMetaData.put(JFreeChartCategoryGraphSource.DOMAIN_AXIS, domainAxis); graphMetaData.put(GraphSource.GRAPH_RANGE_INTEGER_TICK, !percentBased); graphMetaData.put(GraphSource.GRAPH_RANGE_MINOR_TICK_VISIBLE, false); if (yAxisMin != null && yAxisMax != null) { graphMetaData.put(GraphSource.GRAPH_RANGE_LOWER_BOUND, yAxisMin); graphMetaData.put(GraphSource.GRAPH_RANGE_UPPER_BOUND, yAxisMax); } else { graphMetaData.put(GraphSource.GRAPH_RANGE_LOWER_BOUND, 0.0); if (maxCount == 0) { // if there is no data, set the upper bound to 1.0, otherwise we // get a weird looking y-axis graphMetaData.put(GraphSource.GRAPH_RANGE_UPPER_BOUND, 1.0); } // if the maxCount is less than 1, Y-Axis labels are not displayed. // Found during testing % data that may be 1% else if (maxCount < 1) { graphMetaData.put(GraphSource.GRAPH_RANGE_INTEGER_TICK, false); graphMetaData.put(GraphSource.GRAPH_RANGE_UPPER_BOUND, maxCount * 1.05); } else { graphMetaData.put(GraphSource.GRAPH_RANGE_UPPER_BOUND, maxCount * 1.05); } } graphMetaData.put(GraphSource.GRAPH_Y_LABEL, yAxisLabel); graphMetaData.put(GraphSource.GRAPH_Y_AXIS_FONT, rangeAxisFont); graphMetaData.put(GraphSource.GRAPH_Y_AXIS_LABEL_FONT, rangeAxisLabelFont); graphMetaData.put(GraphSource.GRAPH_X_LABEL, xAxisLabel); graphMetaData.put(GraphSource.GRAPH_X_AXIS_FONT, domainAxisFont); graphMetaData.put(GraphSource.GRAPH_X_AXIS_LABEL_FONT, domainAxisLabelFont); } public void setBarGraphMetaData(GraphDataInterface graphData, boolean stackGraph, Map<String, Object> graphMetaData) { String graphTitle = graphData.getGraphTitle() != null ? graphData.getGraphTitle() : ""; String xAxisLabel = graphData.getXAxisLabel() != null ? graphData.getXAxisLabel() : ""; String yAxisLabel = graphData.getYAxisLabel() != null ? graphData.getYAxisLabel() : ""; int graphWidth = graphData.getGraphWidth(); int graphHeight = graphData.getGraphHeight(); boolean percentBased = graphData.percentBased(); boolean plotHorizontal = graphData.plotHorizontal(); int maxLabeledCategoryTicks = graphData.getMaxLabeledCategoryTicks(); if (stackGraph) { graphMetaData.put(GraphSource.GRAPH_TYPE, GraphSource.GRAPH_TYPE_STACKED_BAR); } else { graphMetaData.put(GraphSource.GRAPH_TYPE, GraphSource.GRAPH_TYPE_BAR); } if (plotHorizontal) { graphMetaData.put(JFreeChartBarGraphSource.PLOT_ORIENTATION, PlotOrientation.HORIZONTAL); } graphMetaData.put(GraphSource.GRAPH_LABEL_BACKGROUND_COLOR, Color.WHITE); graphMetaData.put(GraphSource.BACKGROUND_COLOR, Color.WHITE); graphMetaData.put(GraphSource.GRAPH_TITLE, graphTitle); graphMetaData.put(GraphSource.GRAPH_FONT, graphFont); graphMetaData.put(GraphSource.GRAPH_BORDER, false); graphMetaData.put(GraphSource.GRAPH_LEGEND, graphData.showLegend()); graphMetaData.put(GraphSource.LEGEND_FONT, legendFont); SparselyLabeledCategoryAxis domainAxis; if (graphWidth >= 500 && graphHeight >= 300) { // this is a larger graph so we can add some additional properties to pretty it up graphMetaData.put(GraphSource.GRAPH_BORDER, true); graphMetaData.put(GraphSource.AXIS_OFFSET, 5.0); graphMetaData.put(GraphSource.GRAPH_RANGE_GRIDLINE_PAINT, Color.lightGray); domainAxis = new SparselyLabeledCategoryAxis(maxLabeledCategoryTicks, Color.lightGray); } else { domainAxis = new SparselyLabeledCategoryAxis(maxLabeledCategoryTicks); } if (!plotHorizontal) { // don't rotate labels if this is a horizontal graph domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createDownRotationLabelPositions(45)); } domainAxis.setMaximumCategoryLabelWidthRatio(maxCategoryLabelWidthRatio); graphMetaData.put(JFreeChartCategoryGraphSource.DOMAIN_AXIS, domainAxis); graphMetaData.put(GraphSource.GRAPH_RANGE_AXIS_LOCATION, AxisLocation.BOTTOM_OR_LEFT); graphMetaData.put(GraphSource.GRAPH_RANGE_INTEGER_TICK, !percentBased); graphMetaData.put(GraphSource.GRAPH_RANGE_MINOR_TICK_VISIBLE, false); graphMetaData.put(GraphSource.GRAPH_Y_LABEL, yAxisLabel); graphMetaData.put(GraphSource.GRAPH_Y_AXIS_FONT, rangeAxisFont); graphMetaData.put(GraphSource.GRAPH_Y_AXIS_LABEL_FONT, rangeAxisLabelFont); graphMetaData.put(GraphSource.GRAPH_X_LABEL, xAxisLabel); graphMetaData.put(GraphSource.GRAPH_X_AXIS_FONT, domainAxisFont); graphMetaData.put(GraphSource.GRAPH_X_AXIS_LABEL_FONT, domainAxisLabelFont); } public void setPieGraphMetaData(GraphDataInterface graphData, Map<String, Object> graphMetaData, List<PointInterface> points) { double[][] counts = graphData.getCounts(); String[][] altTexts = graphData.getAltTexts(); String[][] lineSetURLs = graphData.getLineSetURLs(); String[] lineSetLabels = graphData.getLineSetLabels(); String graphTitle = graphData.getGraphTitle() != null ? graphData.getGraphTitle() : ""; String graphNoDataMessage = graphData.getNoDataMessage(); Color[] graphBaseColors = graphData.getGraphBaseColors(); boolean graphDisplayLabel = graphData.getShowGraphLabels(); for (int i = 0; i < counts.length; i++) { String lineSetLabel = "series" + (i + 1); String altText = null; String lineSetURL = null; try { lineSetLabel = lineSetLabels[i]; } catch (Exception e) { } try { altText = altTexts[i][0]; } catch (Exception e) { } try { lineSetURL = lineSetURLs[i][0]; } catch (Exception e) { } Map<String, Object> pointMetaData = new HashMap<String, Object>(); pointMetaData.put(GraphSource.ITEM_TOOL_TIP, altText); pointMetaData.put(GraphSource.ITEM_URL, lineSetURL); pointMetaData.put(GraphSource.ITEM_COLOR, graphBaseColors[i % graphBaseColors.length]); points.add(new DataPoint(counts[i][0], lineSetLabel, pointMetaData)); } Font font = graphFont; if (graphData.getTitleFont() != null) { font = graphData.getTitleFont(); } graphMetaData.put(GraphSource.GRAPH_TYPE, GraphSource.GRAPH_TYPE_PIE); graphMetaData.put(GraphSource.BACKGROUND_COLOR, graphData.getBackgroundColor()); //edit to get graph data background color, defaults to white graphMetaData.put(GraphSource.GRAPH_LABEL_BACKGROUND_COLOR, graphData.getLabelBackgroundColor()); graphMetaData.put(GraphSource.GRAPH_TITLE, graphTitle); graphMetaData.put(GraphSource.GRAPH_FONT, font); graphMetaData.put(GraphSource.GRAPH_BORDER, false); graphMetaData.put(GraphSource.GRAPH_DISPLAY_LABEL, graphDisplayLabel); graphMetaData.put(GraphSource.GRAPH_NO_DATA_MESSAGE, graphNoDataMessage); graphMetaData.put(GraphSource.GRAPH_LEGEND, graphData.showLegend()); graphMetaData.put(GraphSource.LEGEND_FONT, legendFont); } private GraphObject getGraph(GraphDataInterface graphData, List<DataSeries> series, Map<String, Object> graphMetaData, LegendItemCollection legendItems, String graphType) { GraphObject graph = null; String graphTitle = graphData.getGraphTitle(); try { // add the created chart properties JFreeChartGraphSource graphSource = new JFreeChartGraphSource(); graphSource.setData(series); graphSource.setParams(graphMetaData); graphSource.initialize(); // add the custom legend graphSource.getChart().getCategoryPlot().setFixedLegendItems(legendItems); // render the graph to get the image map RenderedGraph renderedGraph = graphSource.renderGraph(graphData.getGraphWidth(), graphData.getGraphHeight(), Encoding.PNG); String imageFileName = getCleanValue(graphTitle) + "_" + graphType + ".png"; // get the image map String imageMapName = "imageMap" + graphDataId; String imageMap = appendImageMapTarget(renderedGraph.getImageMap(imageMapName), graphData.getLineSetURLTarget()); try { // store away the graph data file graphDataHandler.putGraphData(graphData, graphDataId); graph = new GraphObject(graphSource, renderedGraph, imageFileName, imageMapName, imageMap, graphDataId); } catch (GraphException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } catch (GraphException e) { System.out.println("Could not create graph " + graphTitle); e.printStackTrace(); } return graph; } private Map<String, Object> dumpGraph(GraphDataInterface graphData) { // setup the default metadata List<DataSeries> dataSeries = new ArrayList<DataSeries>(); LegendItemCollection legendItems = new LegendItemCollection(); Map<String, Object> graphMetaData = new HashMap<String, Object>(); double maxCount = setDataSeries(graphData, null, false, dataSeries, legendItems, false); setTimeSeriesGraphMetaData(graphData, null, null, maxCount, graphMetaData); // store away the graph data file try { graphDataHandler.putGraphData(graphData, graphDataId); } catch (GraphException e) { System.out.println(e.getMessage()); e.printStackTrace(); } return graphMetaData; } private static String getUniqueId(String userId) { Date currentTime = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMMdd_hh_mm_ss_SSS"); if (userId != null && userId.length() > 0) { return userId + "_" + sdf.format(currentTime) + "_" + (int) (Math.random() * 10000); } else { return sdf.format(currentTime) + "_" + (int) (Math.random() * 10000); } } private String appendImageMapTarget(String imageMap, String target) { if (target != null && target.length() > 0) { return imageMap.replace("<area ", "<area target=\"" + target + "\" "); } return imageMap; } private String getCleanValue(String value) { if (value == null) { return ""; } // illegal characters for file names on windows are \/:*?"<>| String cleanValue = value.replaceAll("\\\\", "-"); cleanValue = cleanValue.replaceAll("/", "-"); cleanValue = cleanValue.replaceAll(":", "-"); cleanValue = cleanValue.replaceAll("\\*", "-"); cleanValue = cleanValue.replaceAll("\\?", "-"); cleanValue = cleanValue.replaceAll("\"", "-"); cleanValue = cleanValue.replaceAll("<", "-"); cleanValue = cleanValue.replaceAll(">", "-"); cleanValue = cleanValue.replaceAll("\\|", "-"); cleanValue = cleanValue.replaceAll(";", "-"); cleanValue = cleanValue.replaceAll("\\+", "-"); return cleanValue; } private boolean displaySeries(String displayKey, int seriesIndex) { if (displayKey != null && displayKey.length() > seriesIndex && displayKey.charAt(seriesIndex) == '0') { return false; } else { return true; } } private String getDataSeriesJSON(String[] lineSetLabels, boolean[] displayAlerts, boolean[] displaySeverityAlerts, String quoteStr) { String json = ""; if (lineSetLabels != null) { for (int i = 0; i < lineSetLabels.length; i++) { boolean displayAlert = false; boolean displaySeverityAlert = false; try { displayAlert = displayAlerts[i]; } catch (Exception e) { } try { displaySeverityAlert = displaySeverityAlerts[i]; } catch (Exception e) { } if (displayAlert) { json += getDataSeriesJSONHelper(lineSetLabels[i], lineSetLabels[i] + ": " + getTranslation("Normal"), true, quoteStr); json += ", "; json += getDataSeriesJSONHelper(lineSetLabels[i], lineSetLabels[i] + ": " + getTranslation("Warning"), true, quoteStr); json += ", "; json += getDataSeriesJSONHelper(lineSetLabels[i], lineSetLabels[i] + ": " + getTranslation("Alert"), true, quoteStr); json += ", "; if (displaySeverityAlert) { json += getDataSeriesJSONHelper(lineSetLabels[i], lineSetLabels[i] + ": " + getTranslation("Severe"), true, quoteStr); json += ", "; } } else { json += getDataSeriesJSONHelper(lineSetLabels[i], lineSetLabels[i], false, quoteStr); json += ", "; } } if (json.length() > 0) { json = json.substring(0, json.length() - 2); } } return "{ [ " + json + " ] }"; } private String getDataSeriesJSONHelper(String seriesName, String displayName, boolean displayAlerts, String quoteStr) { String json = ""; json += "{ "; json += "seriesName:"; json += quoteStr + seriesName + quoteStr; json += ", displayName:"; json += quoteStr + displayName + quoteStr; json += ", displayAlerts:" + displayAlerts + " "; json += "}"; return json; } }
true
true
private double setDataSeries(GraphDataInterface graphData, String displayKey, boolean useNoDataColor, List<DataSeries> dataSeries, LegendItemCollection legendItems, boolean useItemColor, boolean graphExpected) { double[][] counts = graphData.getCounts(); double[][] expecteds = graphData.getExpecteds(); int[][] colors = graphData.getColors(); String[][] altTexts = graphData.getAltTexts(); String[][] lineSetURLs = graphData.getLineSetURLs(); String[] xLabels = graphData.getXLabels(); String[] lineSetLabels = graphData.getLineSetLabels(); boolean[] displayAlerts = graphData.displayAlerts(); boolean[] displaySeverityAlerts = graphData.displaySeverityAlerts(); double[] lineSymbolSizes = graphData.getLineSymbolSizes(); Color[] graphBaseColors = graphData.getGraphBaseColors(); int displayKeyIndex = 0; double maxCount = 0; boolean singleAlertLegend = graphData.getShowSingleAlertLegend(); boolean singleSeverityLegend = graphData.getShowSingleSeverityLegend(); for (int i = 0; i < counts.length; i++) { String lineSetLabel = "series" + (i + 1); boolean displayAlert = false; boolean displaySeverityAlert = false; double lineSymbolSize = 7.0; try { lineSetLabel = lineSetLabels[i]; } catch (Exception e) { } try { displayAlert = displayAlerts[i]; } catch (Exception e) { } try { displaySeverityAlert = displaySeverityAlerts[i]; } catch (Exception e) { } try { lineSymbolSize = lineSymbolSizes[i]; } catch (Exception e) { } double xy = lineSymbolSize / 2.0 * -1; Color seriesColor = graphBaseColors[i % graphBaseColors.length]; boolean displayNormalData = displaySeries(displayKey, displayKeyIndex++) ? true : false; boolean displayWarningData = displayAlert && displaySeries(displayKey, displayKeyIndex++) ? true : false; boolean displayAlertData = displayAlert && displaySeries(displayKey, displayKeyIndex++) ? true : false; boolean displaySevereData = displaySeverityAlert && displaySeries(displayKey, displayKeyIndex++) ? true : false; List<DataPoint> points = new ArrayList<DataPoint>(); List<DataPoint> epoints = new ArrayList<DataPoint>(); /** get graph data */ for (int j = 0; j < counts[i].length; j++) { boolean alertDataExists = false; String altText = null; String lineSetURL = null; int color = 1; try { altText = altTexts[i][j]; } catch (Exception e) { } try { lineSetURL = lineSetURLs[i][j]; } catch (Exception e) { } try { color = colors[i][j]; } catch (Exception e) { } Map<String, Object> epointMetaData = new HashMap<String, Object>(); Map<String, Object> pointMetaData = new HashMap<String, Object>(); pointMetaData.put(GraphSource.ITEM_TOOL_TIP, altText); pointMetaData.put(GraphSource.ITEM_URL, lineSetURL); pointMetaData.put(GraphSource.ITEM_SHAPE, new Ellipse2D.Double(xy, xy, lineSymbolSize, lineSymbolSize)); pointMetaData.put(GraphSource.ITEM_COLOR, seriesColor); epointMetaData.put(GraphSource.ITEM_COLOR, seriesColor.brighter()); epointMetaData.put(GraphSource.ITEM_SHAPE, new Rectangle2D.Double(xy, xy, 7, 7)); epointMetaData.put(GraphSource.ITEM_TOOL_TIP, altText); // color 0 = GRAY (no data), color 2 = YELLOW (warning), 3 = RED (alert), // 4 = PURPLE (severe) if (useNoDataColor && color == 0) { pointMetaData.put(GraphSource.ITEM_COLOR, noDataColor); } else if (displayWarningData && color == 2) { alertDataExists = true; pointMetaData.put(GraphSource.ITEM_COLOR, warningDataColor); } else if (displayAlertData && color == 3) { alertDataExists = true; pointMetaData.put(GraphSource.ITEM_COLOR, alertDataColor); } else if (displaySevereData && color == 4) { alertDataExists = true; pointMetaData.put(GraphSource.ITEM_COLOR, severeDataColor); } if (useItemColor) { seriesColor = graphBaseColors[j % graphBaseColors.length]; pointMetaData.put(GraphSource.ITEM_COLOR, seriesColor); } if (displayNormalData || alertDataExists) { // only update the maxCount if this data point is visible if (counts[i][j] > maxCount) { maxCount = counts[i][j]; } } else { // if normal data is supposed to be hidden and no alert data exists, then hide this // data point pointMetaData.put(GraphSource.ITEM_VISIBLE, false); epointMetaData.put(GraphSource.ITEM_VISIBLE, false); } // if the data is set to the Double.MIN_VALUE, then add it as a null. if (counts[i][j] != Double.MIN_VALUE) { points.add(new DataPoint(counts[i][j], xLabels[j], pointMetaData)); } else { points.add(new DataPoint(null, xLabels[j], pointMetaData)); } if (expecteds[i][j] != Double.MIN_VALUE) { epoints.add(new DataPoint(expecteds[i][j], xLabels[j], epointMetaData)); } else { epoints.add(new DataPoint(null, xLabels[j], epointMetaData)); } } /** add the series */ // series properties Map<String, Object> dataSeriesMetaData = new HashMap<String, Object>(); dataSeriesMetaData.put(GraphSource.SERIES_TITLE, lineSetLabel); dataSeriesMetaData.put(GraphSource.SERIES_COLOR, seriesColor); // if normal data is hidden for this series, hide the series connector line dataSeriesMetaData.put(GraphSource.SERIES_LINES_VISIBLE, displayNormalData); dataSeries.add(new DataSeries(points, dataSeriesMetaData)); Map<String, Object> eDataSeriesMetaData = new HashMap<String, Object>(); eDataSeriesMetaData.put(GraphSource.SERIES_COLOR, seriesColor); eDataSeriesMetaData.put(GraphSource.SERIES_STROKE, new BasicStroke( 1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[]{10.0f, 6.0f}, 0.0f)); if (graphExpected) { dataSeries.add(new DataSeries(epoints, eDataSeriesMetaData)); } // code to set the text in the legend if (legendItems != null) { if (displayNormalData && legendItems.getItemCount() < maxLegendItems) { if (displayAlert && !singleAlertLegend) { legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Normal"), seriesColor)); } if (graphExpected) { legendItems.add(new LegendItem(lineSetLabel, seriesColor)); legendItems.add(new LegendItem(("Expected " + lineSetLabel), seriesColor)); } else { legendItems.add(new LegendItem(lineSetLabel, seriesColor)); } } if (!singleAlertLegend && displayWarningData && legendItems.getItemCount() < maxLegendItems) { legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Warning"), warningDataColor)); } if (!singleAlertLegend && displayAlertData && legendItems.getItemCount() < maxLegendItems) { legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Alert"), alertDataColor)); } if (!singleSeverityLegend && displaySevereData && legendItems.getItemCount() < maxLegendItems) { legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Severe"), severeDataColor)); } } } if (singleAlertLegend && legendItems.getItemCount() < maxLegendItems) { legendItems.add(new LegendItem(getTranslation("Warning"), warningDataColor)); legendItems.add(new LegendItem(getTranslation("Alert"), alertDataColor)); } if (singleSeverityLegend && legendItems.getItemCount() < maxLegendItems) { legendItems.add(new LegendItem(getTranslation("Severe"), severeDataColor)); } return maxCount; }
private double setDataSeries(GraphDataInterface graphData, String displayKey, boolean useNoDataColor, List<DataSeries> dataSeries, LegendItemCollection legendItems, boolean useItemColor, boolean graphExpected) { double[][] counts = graphData.getCounts(); double[][] expecteds = graphData.getExpecteds(); int[][] colors = graphData.getColors(); String[][] altTexts = graphData.getAltTexts(); String[][] lineSetURLs = graphData.getLineSetURLs(); String[] xLabels = graphData.getXLabels(); String[] lineSetLabels = graphData.getLineSetLabels(); boolean[] displayAlerts = graphData.displayAlerts(); boolean[] displaySeverityAlerts = graphData.displaySeverityAlerts(); double[] lineSymbolSizes = graphData.getLineSymbolSizes(); Color[] graphBaseColors = graphData.getGraphBaseColors(); int displayKeyIndex = 0; double maxCount = 0; boolean singleAlertLegend = graphData.getShowSingleAlertLegend(); boolean singleSeverityLegend = graphData.getShowSingleSeverityLegend(); for (int i = 0; i < counts.length; i++) { String lineSetLabel = "series" + (i + 1); boolean displayAlert = false; boolean displaySeverityAlert = false; double lineSymbolSize = 7.0; try { lineSetLabel = lineSetLabels[i]; } catch (Exception e) { } try { displayAlert = displayAlerts[i]; } catch (Exception e) { } try { displaySeverityAlert = displaySeverityAlerts[i]; } catch (Exception e) { } try { lineSymbolSize = lineSymbolSizes[i]; } catch (Exception e) { } double xy = lineSymbolSize / 2.0 * -1; Color seriesColor = graphBaseColors[i % graphBaseColors.length]; boolean displayNormalData = displaySeries(displayKey, displayKeyIndex++) ? true : false; boolean displayWarningData = displayAlert && displaySeries(displayKey, displayKeyIndex++) ? true : false; boolean displayAlertData = displayAlert && displaySeries(displayKey, displayKeyIndex++) ? true : false; boolean displaySevereData = displaySeverityAlert && displaySeries(displayKey, displayKeyIndex++) ? true : false; List<DataPoint> points = new ArrayList<DataPoint>(); List<DataPoint> epoints = new ArrayList<DataPoint>(); /** get graph data */ for (int j = 0; j < counts[i].length; j++) { boolean alertDataExists = false; String altText = null; String lineSetURL = null; int color = 1; try { altText = altTexts[i][j]; } catch (Exception e) { } try { lineSetURL = lineSetURLs[i][j]; } catch (Exception e) { } try { color = colors[i][j]; } catch (Exception e) { } Map<String, Object> epointMetaData = new HashMap<String, Object>(); Map<String, Object> pointMetaData = new HashMap<String, Object>(); pointMetaData.put(GraphSource.ITEM_TOOL_TIP, altText); pointMetaData.put(GraphSource.ITEM_URL, lineSetURL); pointMetaData.put(GraphSource.ITEM_SHAPE, new Ellipse2D.Double(xy, xy, lineSymbolSize, lineSymbolSize)); pointMetaData.put(GraphSource.ITEM_COLOR, seriesColor); epointMetaData.put(GraphSource.ITEM_COLOR, seriesColor.brighter()); epointMetaData.put(GraphSource.ITEM_SHAPE, new Rectangle2D.Double(xy, xy, 7, 7)); epointMetaData.put(GraphSource.ITEM_TOOL_TIP, altText); // color 0 = GRAY (no data), color 2 = YELLOW (warning), 3 = RED (alert), // 4 = PURPLE (severe) if (useNoDataColor && color == 0) { pointMetaData.put(GraphSource.ITEM_COLOR, noDataColor); } else if (displayWarningData && color == 2) { alertDataExists = true; pointMetaData.put(GraphSource.ITEM_COLOR, warningDataColor); } else if (displayAlertData && color == 3) { alertDataExists = true; pointMetaData.put(GraphSource.ITEM_COLOR, alertDataColor); } else if (displaySevereData && color == 4) { alertDataExists = true; pointMetaData.put(GraphSource.ITEM_COLOR, severeDataColor); } if (useItemColor) { seriesColor = graphBaseColors[j % graphBaseColors.length]; pointMetaData.put(GraphSource.ITEM_COLOR, seriesColor); } if (displayNormalData || alertDataExists) { // only update the maxCount if this data point is visible if (counts[i][j] > maxCount) { maxCount = counts[i][j]; } } else { // if normal data is supposed to be hidden and no alert data exists, then hide this // data point pointMetaData.put(GraphSource.ITEM_VISIBLE, false); epointMetaData.put(GraphSource.ITEM_VISIBLE, false); } // if the data is set to the Double.MIN_VALUE, then add it as a null. if (counts[i][j] != Double.MIN_VALUE) { points.add(new DataPoint(counts[i][j], xLabels[j], pointMetaData)); } else { points.add(new DataPoint(null, xLabels[j], pointMetaData)); } if (expecteds != null && expecteds[i][j] != Double.MIN_VALUE) { epoints.add(new DataPoint(expecteds[i][j], xLabels[j], epointMetaData)); } else { epoints.add(new DataPoint(null, xLabels[j], epointMetaData)); } } /** add the series */ // series properties Map<String, Object> dataSeriesMetaData = new HashMap<String, Object>(); dataSeriesMetaData.put(GraphSource.SERIES_TITLE, lineSetLabel); dataSeriesMetaData.put(GraphSource.SERIES_COLOR, seriesColor); // if normal data is hidden for this series, hide the series connector line dataSeriesMetaData.put(GraphSource.SERIES_LINES_VISIBLE, displayNormalData); dataSeries.add(new DataSeries(points, dataSeriesMetaData)); Map<String, Object> eDataSeriesMetaData = new HashMap<String, Object>(); eDataSeriesMetaData.put(GraphSource.SERIES_COLOR, seriesColor); eDataSeriesMetaData.put(GraphSource.SERIES_STROKE, new BasicStroke( 1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[]{10.0f, 6.0f}, 0.0f)); if (graphExpected) { dataSeries.add(new DataSeries(epoints, eDataSeriesMetaData)); } // code to set the text in the legend if (legendItems != null) { if (displayNormalData && legendItems.getItemCount() < maxLegendItems) { if (displayAlert && !singleAlertLegend) { legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Normal"), seriesColor)); } if (graphExpected) { legendItems.add(new LegendItem(lineSetLabel, seriesColor)); legendItems.add(new LegendItem(("Expected " + lineSetLabel), seriesColor)); } else { legendItems.add(new LegendItem(lineSetLabel, seriesColor)); } } if (!singleAlertLegend && displayWarningData && legendItems.getItemCount() < maxLegendItems) { legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Warning"), warningDataColor)); } if (!singleAlertLegend && displayAlertData && legendItems.getItemCount() < maxLegendItems) { legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Alert"), alertDataColor)); } if (!singleSeverityLegend && displaySevereData && legendItems.getItemCount() < maxLegendItems) { legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Severe"), severeDataColor)); } } } if (singleAlertLegend && legendItems.getItemCount() < maxLegendItems) { legendItems.add(new LegendItem(getTranslation("Warning"), warningDataColor)); legendItems.add(new LegendItem(getTranslation("Alert"), alertDataColor)); } if (singleSeverityLegend && legendItems.getItemCount() < maxLegendItems) { legendItems.add(new LegendItem(getTranslation("Severe"), severeDataColor)); } return maxCount; }
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/sharing/ExistingOrNewPage.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/sharing/ExistingOrNewPage.java index db781e79..edf8ec6e 100644 --- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/sharing/ExistingOrNewPage.java +++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/sharing/ExistingOrNewPage.java @@ -1,299 +1,301 @@ /******************************************************************************* * Copyright (C) 2009, Robin Rosenberg * Copyright (C) 2009, Mykola Nikishov <[email protected]> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.egit.ui.internal.sharing; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.egit.core.RepositoryUtil; import org.eclipse.egit.core.project.RepositoryFinder; import org.eclipse.egit.core.project.RepositoryMapping; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIIcons; import org.eclipse.egit.ui.UIText; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.storage.file.FileRepository; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.swt.widgets.TreeItem; /** * Wizard page for connecting projects to Git repositories. */ class ExistingOrNewPage extends WizardPage { private final SharingWizard myWizard; private Button button; private Tree tree; private Text repositoryToCreate; private IPath minumumPath; private Text dotGitSegment; ExistingOrNewPage(SharingWizard w) { super(ExistingOrNewPage.class.getName()); setTitle(UIText.ExistingOrNewPage_title); setDescription(UIText.ExistingOrNewPage_description); setImageDescriptor(UIIcons.WIZBAN_CONNECT_REPO); this.myWizard = w; } public void createControl(Composite parent) { Group g = new Group(parent, SWT.NONE); g.setLayout(new GridLayout(3,false)); g.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).create()); tree = new Tree(g, SWT.BORDER|SWT.MULTI|SWT.FULL_SELECTION); tree.setHeaderVisible(true); tree.setLayout(new GridLayout()); tree.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).span(3,1).create()); tree.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { TreeItem t = (TreeItem) e.item; for(TreeItem ti : t.getItems()) tree.deselect(ti); if (t.getParentItem() != null) { tree.deselect(t.getParentItem()); for(TreeItem ti : t.getParentItem().getItems()) if (ti != t) tree.deselect(ti); } Set<IProject> projects = new HashSet<IProject>(); for (TreeItem treeItem : tree.getSelection()) { if (treeItem.getData() == null && treeItem.getParentItem() != null) { treeItem = treeItem.getParentItem(); } final IProject project = (IProject) treeItem.getData(); if (projects.contains(project)) tree.deselect(treeItem); projects.add(project); } } }); TreeColumn c1 = new TreeColumn(tree,SWT.NONE); c1.setText(UIText.ExistingOrNewPage_HeaderProject); c1.setWidth(100); TreeColumn c2 = new TreeColumn(tree,SWT.NONE); c2.setText(UIText.ExistingOrNewPage_HeaderPath); c2.setWidth(400); TreeColumn c3 = new TreeColumn(tree,SWT.NONE); c3.setText(UIText.ExistingOrNewPage_HeaderRepository); c3.setWidth(200); for (IProject project : myWizard.projects) { TreeItem treeItem = new TreeItem(tree, SWT.NONE); treeItem.setData(project); treeItem.setText(0, project.getName()); treeItem.setText(1, project.getLocation().toOSString()); RepositoryFinder repositoryFinder = new RepositoryFinder(project); Collection<RepositoryMapping> mappings; try { mappings = repositoryFinder.find(new NullProgressMonitor()); Iterator<RepositoryMapping> mi = mappings.iterator(); RepositoryMapping m = mi.hasNext() ? mi.next() : null; if (m == null) { // no mapping found, enable repository creation treeItem.setText(2, ""); //$NON-NLS-1$ } else { // at least one mapping found fillTreeItemWithGitDirectory(m, treeItem, false); } while (mi.hasNext()) { // fill in additional mappings m = mi.next(); TreeItem treeItem2 = new TreeItem(treeItem, SWT.NONE); treeItem2.setData(m.getContainer().getProject()); fillTreeItemWithGitDirectory(m, treeItem2, true); } } catch (CoreException e) { TreeItem treeItem2 = new TreeItem(treeItem, SWT.BOLD|SWT.ITALIC); treeItem2.setText(e.getMessage()); } } button = new Button(g, SWT.PUSH); button.setLayoutData(GridDataFactory.fillDefaults().create()); button.setText(UIText.ExistingOrNewPage_CreateButton); button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { File gitDir = new File(repositoryToCreate.getText(),Constants.DOT_GIT); try { Repository repository = new FileRepository(gitDir); repository.create(); for (IProject project : getProjects().keySet()) { // If we don't refresh the project directories right // now we won't later know that a .git directory // exists within it and we won't mark the .git // directory as a team-private member. Failure // to do so might allow someone to delete // the .git directory without us stopping them. // (Half lie, we should optimize so we do not // refresh when the .git is not within the project) // if (!gitDir.toString().contains("..")) //$NON-NLS-1$ project.refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor()); } RepositoryUtil util = Activator.getDefault().getRepositoryUtil(); util.addConfiguredRepository(gitDir); } catch (IOException e1) { String msg = NLS .bind( UIText.ExistingOrNewPage_ErrorFailedToCreateRepository, gitDir.toString()); org.eclipse.egit.ui.Activator.handleError(msg, e1, true); } catch (CoreException e2) { String msg = NLS .bind( UIText.ExistingOrNewPage_ErrorFailedToRefreshRepository, gitDir); org.eclipse.egit.ui.Activator.handleError(msg, e2, true); } for (TreeItem ti : tree.getSelection()) { ti.setText(2, gitDir.toString()); } updateCreateOptions(); getContainer().updateButtons(); } }); repositoryToCreate = new Text(g, SWT.SINGLE | SWT.BORDER); repositoryToCreate.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).span(1,1).create()); repositoryToCreate.addListener(SWT.Modify, new Listener() { public void handleEvent(Event e) { - if (e.text == null) + if (repositoryToCreate.getText().equals("")) { //$NON-NLS-1$ + button.setEnabled(false); return; - IPath fromOSString = Path.fromOSString(e.text); + } + IPath fromOSString = Path.fromOSString(repositoryToCreate.getText()); button.setEnabled(minumumPath .matchingFirstSegments(fromOSString) == fromOSString .segmentCount()); } }); dotGitSegment = new Text(g ,SWT.NONE); dotGitSegment.setEnabled(false); dotGitSegment.setEditable(false); dotGitSegment.setText(File.separatorChar + Constants.DOT_GIT); dotGitSegment.setLayoutData(GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).create()); tree.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updateCreateOptions(); } }); updateCreateOptions(); Dialog.applyDialogFont(g); setControl(g); } private void fillTreeItemWithGitDirectory(RepositoryMapping m, TreeItem treeItem2, boolean isAlternative) { if (m.getGitDir() == null) treeItem2.setText(2, UIText.ExistingOrNewPage_SymbolicValueEmptyMapping); else { IPath container = m.getContainerPath(); if (!container.isEmpty()) container = container.addTrailingSeparator(); IPath relativePath = container.append(m.getGitDir()); if (isAlternative) treeItem2.setText(0, relativePath.removeLastSegments(1).addTrailingSeparator().toString()); treeItem2.setText(2, relativePath.toString()); } } private void updateCreateOptions() { minumumPath = null; IPath p = null; for (TreeItem ti : tree.getSelection()) { String path = ti.getText(2); if (!path.equals("")) { //$NON-NLS-1$ p = null; break; } String gitDirParentCandidate = ti.getText(1); IPath thisPath = Path.fromOSString(gitDirParentCandidate); if (p == null) p = thisPath; else { int n = p.matchingFirstSegments(thisPath); p = p.removeLastSegments(p.segmentCount() - n); } } minumumPath = p; if (p != null) { repositoryToCreate.setText(p.toOSString()); } else { repositoryToCreate.setText(""); //$NON-NLS-1$ } button.setEnabled(p != null); repositoryToCreate.setEnabled(p != null); dotGitSegment.setEnabled(p != null); getContainer().updateButtons(); } @Override public boolean isPageComplete() { if (tree.getSelectionCount() == 0) return false; for (TreeItem ti : tree.getSelection()) { String path = ti.getText(2); if (path.equals("")) { //$NON-NLS-1$ return false; } } return true; } /** * @return map between project and repository root directory (converted to an * absolute path) for all projects selected by user */ public Map<IProject, File> getProjects() { final TreeItem[] selection = tree.getSelection(); Map<IProject, File> ret = new HashMap<IProject, File>(selection.length); for (int i = 0; i < selection.length; ++i) { TreeItem treeItem = selection[i]; while (treeItem.getData() == null && treeItem.getParentItem() != null) { treeItem = treeItem.getParentItem(); } final IProject project = (IProject) treeItem.getData(); final IPath selectedRepo = Path.fromOSString(treeItem.getText(2)); IPath localPathToRepo = selectedRepo; if (!selectedRepo.isAbsolute()) { localPathToRepo = project.getLocation().append(selectedRepo); } ret.put(project, localPathToRepo.toFile()); } return ret; } }
false
true
public void createControl(Composite parent) { Group g = new Group(parent, SWT.NONE); g.setLayout(new GridLayout(3,false)); g.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).create()); tree = new Tree(g, SWT.BORDER|SWT.MULTI|SWT.FULL_SELECTION); tree.setHeaderVisible(true); tree.setLayout(new GridLayout()); tree.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).span(3,1).create()); tree.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { TreeItem t = (TreeItem) e.item; for(TreeItem ti : t.getItems()) tree.deselect(ti); if (t.getParentItem() != null) { tree.deselect(t.getParentItem()); for(TreeItem ti : t.getParentItem().getItems()) if (ti != t) tree.deselect(ti); } Set<IProject> projects = new HashSet<IProject>(); for (TreeItem treeItem : tree.getSelection()) { if (treeItem.getData() == null && treeItem.getParentItem() != null) { treeItem = treeItem.getParentItem(); } final IProject project = (IProject) treeItem.getData(); if (projects.contains(project)) tree.deselect(treeItem); projects.add(project); } } }); TreeColumn c1 = new TreeColumn(tree,SWT.NONE); c1.setText(UIText.ExistingOrNewPage_HeaderProject); c1.setWidth(100); TreeColumn c2 = new TreeColumn(tree,SWT.NONE); c2.setText(UIText.ExistingOrNewPage_HeaderPath); c2.setWidth(400); TreeColumn c3 = new TreeColumn(tree,SWT.NONE); c3.setText(UIText.ExistingOrNewPage_HeaderRepository); c3.setWidth(200); for (IProject project : myWizard.projects) { TreeItem treeItem = new TreeItem(tree, SWT.NONE); treeItem.setData(project); treeItem.setText(0, project.getName()); treeItem.setText(1, project.getLocation().toOSString()); RepositoryFinder repositoryFinder = new RepositoryFinder(project); Collection<RepositoryMapping> mappings; try { mappings = repositoryFinder.find(new NullProgressMonitor()); Iterator<RepositoryMapping> mi = mappings.iterator(); RepositoryMapping m = mi.hasNext() ? mi.next() : null; if (m == null) { // no mapping found, enable repository creation treeItem.setText(2, ""); //$NON-NLS-1$ } else { // at least one mapping found fillTreeItemWithGitDirectory(m, treeItem, false); } while (mi.hasNext()) { // fill in additional mappings m = mi.next(); TreeItem treeItem2 = new TreeItem(treeItem, SWT.NONE); treeItem2.setData(m.getContainer().getProject()); fillTreeItemWithGitDirectory(m, treeItem2, true); } } catch (CoreException e) { TreeItem treeItem2 = new TreeItem(treeItem, SWT.BOLD|SWT.ITALIC); treeItem2.setText(e.getMessage()); } } button = new Button(g, SWT.PUSH); button.setLayoutData(GridDataFactory.fillDefaults().create()); button.setText(UIText.ExistingOrNewPage_CreateButton); button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { File gitDir = new File(repositoryToCreate.getText(),Constants.DOT_GIT); try { Repository repository = new FileRepository(gitDir); repository.create(); for (IProject project : getProjects().keySet()) { // If we don't refresh the project directories right // now we won't later know that a .git directory // exists within it and we won't mark the .git // directory as a team-private member. Failure // to do so might allow someone to delete // the .git directory without us stopping them. // (Half lie, we should optimize so we do not // refresh when the .git is not within the project) // if (!gitDir.toString().contains("..")) //$NON-NLS-1$ project.refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor()); } RepositoryUtil util = Activator.getDefault().getRepositoryUtil(); util.addConfiguredRepository(gitDir); } catch (IOException e1) { String msg = NLS .bind( UIText.ExistingOrNewPage_ErrorFailedToCreateRepository, gitDir.toString()); org.eclipse.egit.ui.Activator.handleError(msg, e1, true); } catch (CoreException e2) { String msg = NLS .bind( UIText.ExistingOrNewPage_ErrorFailedToRefreshRepository, gitDir); org.eclipse.egit.ui.Activator.handleError(msg, e2, true); } for (TreeItem ti : tree.getSelection()) { ti.setText(2, gitDir.toString()); } updateCreateOptions(); getContainer().updateButtons(); } }); repositoryToCreate = new Text(g, SWT.SINGLE | SWT.BORDER); repositoryToCreate.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).span(1,1).create()); repositoryToCreate.addListener(SWT.Modify, new Listener() { public void handleEvent(Event e) { if (e.text == null) return; IPath fromOSString = Path.fromOSString(e.text); button.setEnabled(minumumPath .matchingFirstSegments(fromOSString) == fromOSString .segmentCount()); } }); dotGitSegment = new Text(g ,SWT.NONE); dotGitSegment.setEnabled(false); dotGitSegment.setEditable(false); dotGitSegment.setText(File.separatorChar + Constants.DOT_GIT); dotGitSegment.setLayoutData(GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).create()); tree.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updateCreateOptions(); } }); updateCreateOptions(); Dialog.applyDialogFont(g); setControl(g); }
public void createControl(Composite parent) { Group g = new Group(parent, SWT.NONE); g.setLayout(new GridLayout(3,false)); g.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).create()); tree = new Tree(g, SWT.BORDER|SWT.MULTI|SWT.FULL_SELECTION); tree.setHeaderVisible(true); tree.setLayout(new GridLayout()); tree.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).span(3,1).create()); tree.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { TreeItem t = (TreeItem) e.item; for(TreeItem ti : t.getItems()) tree.deselect(ti); if (t.getParentItem() != null) { tree.deselect(t.getParentItem()); for(TreeItem ti : t.getParentItem().getItems()) if (ti != t) tree.deselect(ti); } Set<IProject> projects = new HashSet<IProject>(); for (TreeItem treeItem : tree.getSelection()) { if (treeItem.getData() == null && treeItem.getParentItem() != null) { treeItem = treeItem.getParentItem(); } final IProject project = (IProject) treeItem.getData(); if (projects.contains(project)) tree.deselect(treeItem); projects.add(project); } } }); TreeColumn c1 = new TreeColumn(tree,SWT.NONE); c1.setText(UIText.ExistingOrNewPage_HeaderProject); c1.setWidth(100); TreeColumn c2 = new TreeColumn(tree,SWT.NONE); c2.setText(UIText.ExistingOrNewPage_HeaderPath); c2.setWidth(400); TreeColumn c3 = new TreeColumn(tree,SWT.NONE); c3.setText(UIText.ExistingOrNewPage_HeaderRepository); c3.setWidth(200); for (IProject project : myWizard.projects) { TreeItem treeItem = new TreeItem(tree, SWT.NONE); treeItem.setData(project); treeItem.setText(0, project.getName()); treeItem.setText(1, project.getLocation().toOSString()); RepositoryFinder repositoryFinder = new RepositoryFinder(project); Collection<RepositoryMapping> mappings; try { mappings = repositoryFinder.find(new NullProgressMonitor()); Iterator<RepositoryMapping> mi = mappings.iterator(); RepositoryMapping m = mi.hasNext() ? mi.next() : null; if (m == null) { // no mapping found, enable repository creation treeItem.setText(2, ""); //$NON-NLS-1$ } else { // at least one mapping found fillTreeItemWithGitDirectory(m, treeItem, false); } while (mi.hasNext()) { // fill in additional mappings m = mi.next(); TreeItem treeItem2 = new TreeItem(treeItem, SWT.NONE); treeItem2.setData(m.getContainer().getProject()); fillTreeItemWithGitDirectory(m, treeItem2, true); } } catch (CoreException e) { TreeItem treeItem2 = new TreeItem(treeItem, SWT.BOLD|SWT.ITALIC); treeItem2.setText(e.getMessage()); } } button = new Button(g, SWT.PUSH); button.setLayoutData(GridDataFactory.fillDefaults().create()); button.setText(UIText.ExistingOrNewPage_CreateButton); button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { File gitDir = new File(repositoryToCreate.getText(),Constants.DOT_GIT); try { Repository repository = new FileRepository(gitDir); repository.create(); for (IProject project : getProjects().keySet()) { // If we don't refresh the project directories right // now we won't later know that a .git directory // exists within it and we won't mark the .git // directory as a team-private member. Failure // to do so might allow someone to delete // the .git directory without us stopping them. // (Half lie, we should optimize so we do not // refresh when the .git is not within the project) // if (!gitDir.toString().contains("..")) //$NON-NLS-1$ project.refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor()); } RepositoryUtil util = Activator.getDefault().getRepositoryUtil(); util.addConfiguredRepository(gitDir); } catch (IOException e1) { String msg = NLS .bind( UIText.ExistingOrNewPage_ErrorFailedToCreateRepository, gitDir.toString()); org.eclipse.egit.ui.Activator.handleError(msg, e1, true); } catch (CoreException e2) { String msg = NLS .bind( UIText.ExistingOrNewPage_ErrorFailedToRefreshRepository, gitDir); org.eclipse.egit.ui.Activator.handleError(msg, e2, true); } for (TreeItem ti : tree.getSelection()) { ti.setText(2, gitDir.toString()); } updateCreateOptions(); getContainer().updateButtons(); } }); repositoryToCreate = new Text(g, SWT.SINGLE | SWT.BORDER); repositoryToCreate.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).span(1,1).create()); repositoryToCreate.addListener(SWT.Modify, new Listener() { public void handleEvent(Event e) { if (repositoryToCreate.getText().equals("")) { //$NON-NLS-1$ button.setEnabled(false); return; } IPath fromOSString = Path.fromOSString(repositoryToCreate.getText()); button.setEnabled(minumumPath .matchingFirstSegments(fromOSString) == fromOSString .segmentCount()); } }); dotGitSegment = new Text(g ,SWT.NONE); dotGitSegment.setEnabled(false); dotGitSegment.setEditable(false); dotGitSegment.setText(File.separatorChar + Constants.DOT_GIT); dotGitSegment.setLayoutData(GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).create()); tree.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updateCreateOptions(); } }); updateCreateOptions(); Dialog.applyDialogFont(g); setControl(g); }
diff --git a/src/org/openstreetmap/josm/tools/BugReportExceptionHandler.java b/src/org/openstreetmap/josm/tools/BugReportExceptionHandler.java index 01bbfef8..6982b4e6 100644 --- a/src/org/openstreetmap/josm/tools/BugReportExceptionHandler.java +++ b/src/org/openstreetmap/josm/tools/BugReportExceptionHandler.java @@ -1,127 +1,138 @@ // License: GPL. Copyright 2007 by Immanuel Scholz and others package org.openstreetmap.josm.tools; import static org.openstreetmap.josm.tools.I18n.tr; import java.awt.GridBagLayout; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.io.PrintWriter; import java.io.StringWriter; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.actions.ShowStatusReportAction; import org.openstreetmap.josm.plugins.PluginHandler; import org.openstreetmap.josm.tools.Base64; import java.net.URL; import java.net.URLEncoder; import org.openstreetmap.josm.tools.UrlLabel; /** * An exception handler that asks the user to send a bug report. * * @author imi */ public final class BugReportExceptionHandler implements Thread.UncaughtExceptionHandler { public void uncaughtException(Thread t, Throwable e) { handleException(e); } public static void handleException(Throwable e) { e.printStackTrace(); if (Main.parent != null) { if (e instanceof OutOfMemoryError) { // do not translate the string, as translation may raise an exception JOptionPane.showMessageDialog(Main.parent, "JOSM is out of memory. " + "Strange things may happen.\nPlease restart JOSM with the -Xmx###M option,\n" + "where ### is the number of MB assigned to JOSM (e.g. 256).\n" + "Currently, " + Runtime.getRuntime().maxMemory()/1024/1024 + " MB are available to JOSM.", tr("Error"), JOptionPane.ERROR_MESSAGE ); return; } if(PluginHandler.checkException(e)) return; Object[] options = new String[]{tr("Do nothing"), tr("Report Bug")}; int answer = JOptionPane.showOptionDialog(Main.parent, tr("An unexpected exception occurred.\n\n" + "This is always a coding error. If you are running the latest\n" + "version of JOSM, please consider being kind and file a bug report."), tr("Unexpected Exception"), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE,null, options, options[0]); if (answer == 1) { try { + final int maxlen = 7000; StringWriter stack = new StringWriter(); e.printStackTrace(new PrintWriter(stack)); String text = ShowStatusReportAction.getReportHeader() + stack.getBuffer().toString(); + String urltext = text.replaceAll("\r",""); /* strip useless return chars */ + if(urltext.length() > maxlen) + { + urltext = urltext.substring(0,maxlen); + int idx = urltext.lastIndexOf("\n"); + /* cut whole line when not loosing too much */ + if(maxlen-idx < 200) + urltext = urltext.substring(0,idx+1); + urltext += "...<snip>...\n"; + } URL url = new URL("http://josm.openstreetmap.de/josmticket?" + "data="+ Base64.encode( // To note that it came from this code "keywords=template_report&" + "description=" + java.net.URLEncoder.encode( // Note: This doesn't use tr() intentionally, we want bug reports in English "What steps will reproduce the problem?\n" + " 1. \n" + " 2. \n" + " 3. \n" + "\n" + "What is the expected result?\n\n" + "What happens instead?\n\n" + "Please provide any additional information below. Attach a screenshot if\n" + "possible.\n\n" - + "{{{\n" + text + "\n}}}\n", + + "{{{\n" + urltext + "\n}}}\n", "UTF-8"))); JPanel p = new JPanel(new GridBagLayout()); p.add(new JLabel(tr("<html>" + "<p>You've encountered an error in JOSM. Before you file a bug<br>" + "make sure you've updated to the latest version of JOSM here:</p></html>")), GBC.eol()); p.add(new UrlLabel("http://josm.openstreetmap.de/#Download"), GBC.eop().insets(8,0,0,0)); p.add(new JLabel(tr("<html>You should also update your plugins. If neither of those help please<br>" + "file a bug in our bugtracker using this link:</p></html>")), GBC.eol()); p.add(new UrlLabel(url.toString(), "http://josm.openstreetmap.de/josmticket?..."), GBC.eop().insets(8,0,0,0)); p.add(new JLabel(tr("<html><p>" + "There the error information provided below should already be<br>" + "filled out for you. Please include information on how to reproduce<br>" + "the error and try to supply as much detail as possible.</p></html>")), GBC.eop()); p.add(new JLabel(tr("<html><p>" + "Alternatively if that doesn't work you can manually fill in the information<br>" + "below at this URL:</p></html>")), GBC.eol()); p.add(new UrlLabel("http://josm.openstreetmap.de/newticket"), GBC.eop().insets(8,0,0,0)); try { Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(text), new ClipboardOwner(){ public void lostOwnership(Clipboard clipboard, Transferable contents) {} }); p.add(new JLabel(tr("(The text has already been copied to your clipboard.)")), GBC.eop()); } catch (RuntimeException x) {} JTextArea info = new JTextArea(text, 20, 60); info.setCaretPosition(0); info.setEditable(false); p.add(new JScrollPane(info), GBC.eop()); JOptionPane.showMessageDialog(Main.parent, p, tr("You've encountered a bug in JOSM"), JOptionPane.ERROR_MESSAGE); } catch (Exception e1) { e1.printStackTrace(); } } } } }
false
true
public static void handleException(Throwable e) { e.printStackTrace(); if (Main.parent != null) { if (e instanceof OutOfMemoryError) { // do not translate the string, as translation may raise an exception JOptionPane.showMessageDialog(Main.parent, "JOSM is out of memory. " + "Strange things may happen.\nPlease restart JOSM with the -Xmx###M option,\n" + "where ### is the number of MB assigned to JOSM (e.g. 256).\n" + "Currently, " + Runtime.getRuntime().maxMemory()/1024/1024 + " MB are available to JOSM.", tr("Error"), JOptionPane.ERROR_MESSAGE ); return; } if(PluginHandler.checkException(e)) return; Object[] options = new String[]{tr("Do nothing"), tr("Report Bug")}; int answer = JOptionPane.showOptionDialog(Main.parent, tr("An unexpected exception occurred.\n\n" + "This is always a coding error. If you are running the latest\n" + "version of JOSM, please consider being kind and file a bug report."), tr("Unexpected Exception"), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE,null, options, options[0]); if (answer == 1) { try { StringWriter stack = new StringWriter(); e.printStackTrace(new PrintWriter(stack)); String text = ShowStatusReportAction.getReportHeader() + stack.getBuffer().toString(); URL url = new URL("http://josm.openstreetmap.de/josmticket?" + "data="+ Base64.encode( // To note that it came from this code "keywords=template_report&" + "description=" + java.net.URLEncoder.encode( // Note: This doesn't use tr() intentionally, we want bug reports in English "What steps will reproduce the problem?\n" + " 1. \n" + " 2. \n" + " 3. \n" + "\n" + "What is the expected result?\n\n" + "What happens instead?\n\n" + "Please provide any additional information below. Attach a screenshot if\n" + "possible.\n\n" + "{{{\n" + text + "\n}}}\n", "UTF-8"))); JPanel p = new JPanel(new GridBagLayout()); p.add(new JLabel(tr("<html>" + "<p>You've encountered an error in JOSM. Before you file a bug<br>" + "make sure you've updated to the latest version of JOSM here:</p></html>")), GBC.eol()); p.add(new UrlLabel("http://josm.openstreetmap.de/#Download"), GBC.eop().insets(8,0,0,0)); p.add(new JLabel(tr("<html>You should also update your plugins. If neither of those help please<br>" + "file a bug in our bugtracker using this link:</p></html>")), GBC.eol()); p.add(new UrlLabel(url.toString(), "http://josm.openstreetmap.de/josmticket?..."), GBC.eop().insets(8,0,0,0)); p.add(new JLabel(tr("<html><p>" + "There the error information provided below should already be<br>" + "filled out for you. Please include information on how to reproduce<br>" + "the error and try to supply as much detail as possible.</p></html>")), GBC.eop()); p.add(new JLabel(tr("<html><p>" + "Alternatively if that doesn't work you can manually fill in the information<br>" + "below at this URL:</p></html>")), GBC.eol()); p.add(new UrlLabel("http://josm.openstreetmap.de/newticket"), GBC.eop().insets(8,0,0,0)); try { Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(text), new ClipboardOwner(){ public void lostOwnership(Clipboard clipboard, Transferable contents) {} }); p.add(new JLabel(tr("(The text has already been copied to your clipboard.)")), GBC.eop()); } catch (RuntimeException x) {} JTextArea info = new JTextArea(text, 20, 60); info.setCaretPosition(0); info.setEditable(false); p.add(new JScrollPane(info), GBC.eop()); JOptionPane.showMessageDialog(Main.parent, p, tr("You've encountered a bug in JOSM"), JOptionPane.ERROR_MESSAGE); } catch (Exception e1) { e1.printStackTrace(); } } } }
public static void handleException(Throwable e) { e.printStackTrace(); if (Main.parent != null) { if (e instanceof OutOfMemoryError) { // do not translate the string, as translation may raise an exception JOptionPane.showMessageDialog(Main.parent, "JOSM is out of memory. " + "Strange things may happen.\nPlease restart JOSM with the -Xmx###M option,\n" + "where ### is the number of MB assigned to JOSM (e.g. 256).\n" + "Currently, " + Runtime.getRuntime().maxMemory()/1024/1024 + " MB are available to JOSM.", tr("Error"), JOptionPane.ERROR_MESSAGE ); return; } if(PluginHandler.checkException(e)) return; Object[] options = new String[]{tr("Do nothing"), tr("Report Bug")}; int answer = JOptionPane.showOptionDialog(Main.parent, tr("An unexpected exception occurred.\n\n" + "This is always a coding error. If you are running the latest\n" + "version of JOSM, please consider being kind and file a bug report."), tr("Unexpected Exception"), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE,null, options, options[0]); if (answer == 1) { try { final int maxlen = 7000; StringWriter stack = new StringWriter(); e.printStackTrace(new PrintWriter(stack)); String text = ShowStatusReportAction.getReportHeader() + stack.getBuffer().toString(); String urltext = text.replaceAll("\r",""); /* strip useless return chars */ if(urltext.length() > maxlen) { urltext = urltext.substring(0,maxlen); int idx = urltext.lastIndexOf("\n"); /* cut whole line when not loosing too much */ if(maxlen-idx < 200) urltext = urltext.substring(0,idx+1); urltext += "...<snip>...\n"; } URL url = new URL("http://josm.openstreetmap.de/josmticket?" + "data="+ Base64.encode( // To note that it came from this code "keywords=template_report&" + "description=" + java.net.URLEncoder.encode( // Note: This doesn't use tr() intentionally, we want bug reports in English "What steps will reproduce the problem?\n" + " 1. \n" + " 2. \n" + " 3. \n" + "\n" + "What is the expected result?\n\n" + "What happens instead?\n\n" + "Please provide any additional information below. Attach a screenshot if\n" + "possible.\n\n" + "{{{\n" + urltext + "\n}}}\n", "UTF-8"))); JPanel p = new JPanel(new GridBagLayout()); p.add(new JLabel(tr("<html>" + "<p>You've encountered an error in JOSM. Before you file a bug<br>" + "make sure you've updated to the latest version of JOSM here:</p></html>")), GBC.eol()); p.add(new UrlLabel("http://josm.openstreetmap.de/#Download"), GBC.eop().insets(8,0,0,0)); p.add(new JLabel(tr("<html>You should also update your plugins. If neither of those help please<br>" + "file a bug in our bugtracker using this link:</p></html>")), GBC.eol()); p.add(new UrlLabel(url.toString(), "http://josm.openstreetmap.de/josmticket?..."), GBC.eop().insets(8,0,0,0)); p.add(new JLabel(tr("<html><p>" + "There the error information provided below should already be<br>" + "filled out for you. Please include information on how to reproduce<br>" + "the error and try to supply as much detail as possible.</p></html>")), GBC.eop()); p.add(new JLabel(tr("<html><p>" + "Alternatively if that doesn't work you can manually fill in the information<br>" + "below at this URL:</p></html>")), GBC.eol()); p.add(new UrlLabel("http://josm.openstreetmap.de/newticket"), GBC.eop().insets(8,0,0,0)); try { Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(text), new ClipboardOwner(){ public void lostOwnership(Clipboard clipboard, Transferable contents) {} }); p.add(new JLabel(tr("(The text has already been copied to your clipboard.)")), GBC.eop()); } catch (RuntimeException x) {} JTextArea info = new JTextArea(text, 20, 60); info.setCaretPosition(0); info.setEditable(false); p.add(new JScrollPane(info), GBC.eop()); JOptionPane.showMessageDialog(Main.parent, p, tr("You've encountered a bug in JOSM"), JOptionPane.ERROR_MESSAGE); } catch (Exception e1) { e1.printStackTrace(); } } } }
diff --git a/src/main/java/ch/entwine/weblounge/dispatcher/impl/SiteServlet.java b/src/main/java/ch/entwine/weblounge/dispatcher/impl/SiteServlet.java index 4381f153b..14b0b74cf 100644 --- a/src/main/java/ch/entwine/weblounge/dispatcher/impl/SiteServlet.java +++ b/src/main/java/ch/entwine/weblounge/dispatcher/impl/SiteServlet.java @@ -1,363 +1,363 @@ /* * Weblounge: Web Content Management System * Copyright (c) 2003 - 2011 The Weblounge Team * http://entwinemedia.com/weblounge * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package ch.entwine.weblounge.dispatcher.impl; import ch.entwine.weblounge.common.Times; import ch.entwine.weblounge.common.impl.request.Http11ProtocolHandler; import ch.entwine.weblounge.common.impl.request.Http11ResponseType; import ch.entwine.weblounge.common.impl.request.SiteRequestWrapper; import ch.entwine.weblounge.common.impl.request.WebloungeRequestImpl; import ch.entwine.weblounge.common.impl.request.WebloungeResponseImpl; import ch.entwine.weblounge.common.request.WebloungeRequest; import ch.entwine.weblounge.common.site.Site; import ch.entwine.weblounge.common.url.UrlUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.tika.Tika; import org.eclipse.jetty.util.resource.Resource; import org.ops4j.pax.web.jsp.JspServletWrapper; import org.osgi.framework.Bundle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that knows how to deal with resources loaded from <code>OSGi</code> * context. */ public class SiteServlet extends HttpServlet { /** The serial version UID */ private static final long serialVersionUID = 6443055837961417300L; /** The logging facility */ private static final Logger logger = LoggerFactory.getLogger(SiteServlet.class); /** The supported formats */ public enum Format { Processed, Raw }; /** Parameter name for the output format */ public static final String PARAM_FORMAT = "format"; /** The site */ private final Site site; /** The site bundle */ private final Bundle bundle; /** The Jasper servlet */ protected final Servlet jasperServlet; /** Path rules */ private List<ResourceSet> resourceSets = null; /** Tika mimetype library */ private Tika tika = null; /** Flag to reflect servlet initialization */ private boolean initialized = false; /** * Creates a new site servlet for the given bundle and context. * * @param site * the site * @param bundle * the site bundle * @param bundle * the site bundle */ public SiteServlet(final Site site, final Bundle bundle) { this.site = site; this.bundle = bundle; this.jasperServlet = new JspServletWrapper(bundle); this.resourceSets = new ArrayList<ResourceSet>(); this.resourceSets.add(new SiteResourceSet()); this.resourceSets.add(new ModuleResourceSet()); this.tika = new Tika(); } /** * Delegates to the jasper servlet with a controlled context class loader. * * @see JspServletWrapper#init(ServletConfig) */ public void init(final ServletConfig config) throws ServletException { jasperServlet.init(config); initialized = true; } /** * Returns <code>true</code> if the servlet has been initialized. * * @return <code>true</code> if the servlet has been initialized */ public boolean isInitialized() { return initialized; } /** * Returns the site that is serving content through this servlet. * * @return the site */ public Site getSite() { return site; } /** * Returns the site's bundle. * * @return the bundle */ public Bundle getBundle() { return bundle; } /** * Delegates to the jasper servlet. * * @see JspServletWrapper#getServletConfig() */ public ServletConfig getServletConfig() { return jasperServlet.getServletConfig(); } /** * Depending on whether a call to a jsp is made or not, delegates to the * jasper servlet with a controlled context class loader or tries to load the * requested file from the bundle as a static resource. * * @see HttpServlet#service(HttpServletRequest, HttpServletResponse) */ public void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { String filename = FilenameUtils.getName(request.getPathInfo()); // Don't allow listing the root directory? if (StringUtils.isBlank(filename)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } // Check the requested format. In case of a JSP, this can either be // processed (default) or raw, in which case the file contents are // returned rather than Jasper's output of it. Format format = Format.Processed; String f = request.getParameter(PARAM_FORMAT); if (StringUtils.isNotBlank(f)) { try { format = Format.valueOf(StringUtils.capitalize(f.toLowerCase())); } catch (IllegalArgumentException e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } } if (Format.Processed.equals(format) && filename.endsWith(".jsp")) { serviceJavaServerPage(request, response); } else { serviceResource(request, response); } } /** * Delegates to jasper servlet with a controlled context class loader. * * @see JspServletWrapper#service(HttpServletRequest, HttpServletResponse) */ public void serviceJavaServerPage(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) throws ServletException, IOException { final HttpServletRequest request; final HttpServletResponse response; // Wrap request and response if necessary if (httpRequest instanceof SiteRequestWrapper) { request = httpRequest; response = httpResponse; } else if (httpRequest instanceof WebloungeRequest) { request = new SiteRequestWrapper((WebloungeRequest)httpRequest, httpRequest.getPathInfo(), false); response = httpResponse; } else { WebloungeRequestImpl webloungeRequest = new WebloungeRequestImpl(httpRequest); webloungeRequest.init(site); String requestPath = UrlUtils.concat("/site", httpRequest.getPathInfo()); request = new SiteRequestWrapper(webloungeRequest, requestPath, false); response = new WebloungeResponseImpl(httpResponse); ((WebloungeResponseImpl) response).setRequest(webloungeRequest); } // Configure request and response objects try { jasperServlet.service(request, response); } catch (ServletException e) { // re-thrown throw e; } catch (IOException e) { // re-thrown throw e; } catch (Throwable t) { // re-thrown logger.error("Error while serving jsp {}: {}", request.getRequestURI(), t.getMessage()); throw new ServletException(t); } } /** * Tries to serve the request as a static resource from the bundle. * * @param request * the http servlet request * @param response * the http servlet response * @throws ServletException * if serving the request fails * @throws IOException * if writing the response back to the client fails */ protected void serviceResource(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { Http11ResponseType responseType = null; - String requestPath = request.getPathInfo(); + String requestPath = UrlUtils.concat("/site", request.getPathInfo()); // There is also a special set of resources that we don't want to expose if (isProtected(requestPath)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // Does the resource exist? final URL url = bundle.getResource(requestPath); if (url == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Load the resource from the bundle final Resource resource = Resource.newResource(url); if (!resource.exists()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // We don't allow directory listings if (resource.isDirectory()) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } URLConnection conn = url.openConnection(); String mimeType = tika.detect(requestPath); String encoding = null; // Try to get mime type and content encoding from resource if (mimeType == null) mimeType = conn.getContentType(); encoding = conn.getContentEncoding(); if (mimeType != null) { if (encoding != null) mimeType += ";" + encoding; response.setContentType(mimeType); } // Send the response back to the client InputStream is = resource.getInputStream(); try { logger.debug("Serving {}", url); responseType = Http11ProtocolHandler.analyzeRequest(request, resource.lastModified(), Times.MS_PER_DAY + System.currentTimeMillis(), resource.length()); if (!Http11ProtocolHandler.generateResponse(response, responseType, is)) { logger.warn("I/O error while generating content from {}", url); } } finally { IOUtils.closeQuietly(is); } } /** * Returns <code>true</code> if the resource is protected. Examples of * protected resources are <code>web.xml</code> inside of the * <code>WEB-INF</code> directory etc. * * @param path * the path to the resource that is about to be served * @return <code>true</code> if the resource needs to be protected */ public boolean isProtected(String path) { for (ResourceSet resourceSet : resourceSets) { if (resourceSet.includes(path) && resourceSet.excludes(path)) return true; } return false; } /** * Delegates to jasper servlet. * * @see JspServletWrapper#getServletInfo() */ public String getServletInfo() { return jasperServlet.getServletInfo(); } /** * Delegates to jasper servlet with a controlled context class loader. * * @see JspServletWrapper#destroy() */ public void destroy() { jasperServlet.destroy(); } /** * {@inheritDoc} * * @see java.lang.Object#toString() */ @Override public String toString() { return "site " + site; } }
true
true
protected void serviceResource(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { Http11ResponseType responseType = null; String requestPath = request.getPathInfo(); // There is also a special set of resources that we don't want to expose if (isProtected(requestPath)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // Does the resource exist? final URL url = bundle.getResource(requestPath); if (url == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Load the resource from the bundle final Resource resource = Resource.newResource(url); if (!resource.exists()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // We don't allow directory listings if (resource.isDirectory()) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } URLConnection conn = url.openConnection(); String mimeType = tika.detect(requestPath); String encoding = null; // Try to get mime type and content encoding from resource if (mimeType == null) mimeType = conn.getContentType(); encoding = conn.getContentEncoding(); if (mimeType != null) { if (encoding != null) mimeType += ";" + encoding; response.setContentType(mimeType); } // Send the response back to the client InputStream is = resource.getInputStream(); try { logger.debug("Serving {}", url); responseType = Http11ProtocolHandler.analyzeRequest(request, resource.lastModified(), Times.MS_PER_DAY + System.currentTimeMillis(), resource.length()); if (!Http11ProtocolHandler.generateResponse(response, responseType, is)) { logger.warn("I/O error while generating content from {}", url); } } finally { IOUtils.closeQuietly(is); } }
protected void serviceResource(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { Http11ResponseType responseType = null; String requestPath = UrlUtils.concat("/site", request.getPathInfo()); // There is also a special set of resources that we don't want to expose if (isProtected(requestPath)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // Does the resource exist? final URL url = bundle.getResource(requestPath); if (url == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Load the resource from the bundle final Resource resource = Resource.newResource(url); if (!resource.exists()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // We don't allow directory listings if (resource.isDirectory()) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } URLConnection conn = url.openConnection(); String mimeType = tika.detect(requestPath); String encoding = null; // Try to get mime type and content encoding from resource if (mimeType == null) mimeType = conn.getContentType(); encoding = conn.getContentEncoding(); if (mimeType != null) { if (encoding != null) mimeType += ";" + encoding; response.setContentType(mimeType); } // Send the response back to the client InputStream is = resource.getInputStream(); try { logger.debug("Serving {}", url); responseType = Http11ProtocolHandler.analyzeRequest(request, resource.lastModified(), Times.MS_PER_DAY + System.currentTimeMillis(), resource.length()); if (!Http11ProtocolHandler.generateResponse(response, responseType, is)) { logger.warn("I/O error while generating content from {}", url); } } finally { IOUtils.closeQuietly(is); } }
diff --git a/main/src/main/java/com/bloatit/model/FollowSoftware.java b/main/src/main/java/com/bloatit/model/FollowSoftware.java index 1fd878137..b863e007f 100644 --- a/main/src/main/java/com/bloatit/model/FollowSoftware.java +++ b/main/src/main/java/com/bloatit/model/FollowSoftware.java @@ -1,91 +1,91 @@ // // Copyright (c) 2011 Linkeos. // // This file is part of Elveos.org. // Elveos.org is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the // Free Software Foundation, either version 3 of the License, or (at your // option) any later version. // // Elveos.org is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for // more details. // You should have received a copy of the GNU General Public License along // with Elveos.org. If not, see http://www.gnu.org/licenses/. // package com.bloatit.model; import com.bloatit.data.DaoFollowSoftware; import com.bloatit.model.right.Action; import com.bloatit.model.right.AuthToken; import com.bloatit.model.right.UnauthorizedOperationException; import com.bloatit.model.visitor.ModelClassVisitor; public final class FollowSoftware extends Identifiable<DaoFollowSoftware> { // ///////////////////////////////////////////////////////////////////////////////////////// // CONSTRUCTION // ///////////////////////////////////////////////////////////////////////////////////////// private static final class MyCreator extends Creator<DaoFollowSoftware, FollowSoftware> { @SuppressWarnings("synthetic-access") @Override public FollowSoftware doCreate(final DaoFollowSoftware dao) { return new FollowSoftware(dao); } } @SuppressWarnings("synthetic-access") public static FollowSoftware create(final DaoFollowSoftware dao) { return new MyCreator().create(dao); } private FollowSoftware(final DaoFollowSoftware id) { super(id); } // ///////////////////////////////////////////////////////////////////////////////////////// // Getters // ///////////////////////////////////////////////////////////////////////////////////////// public final Member getFollower() { return Member.create(getDao().getFollower()); } public final Software getFollowed() { return Software.create(getDao().getFollowed()); } public final boolean isMail() { return getDao().isMail(); } // ///////////////////////////////////////////////////////////////////////////////////////// // Setters // ///////////////////////////////////////////////////////////////////////////////////////// public final void setMail(final boolean mail) throws UnauthorizedOperationException { final Member follower = Member.create(getDao().getFollower()); if (!(AuthToken.isAdmin() || (AuthToken.isAuthenticated() && AuthToken.getMember().equals(follower)))) { throw new UnauthorizedOperationException(Action.WRITE); } getDao().setMail(mail); for (final FollowFeature followFeature : getFollower().getFollowedFeatures()) { - if (followFeature.getFollowed().getSoftware().equals(getFollowed())) { + if (followFeature.getFollowed().getSoftware() != null && followFeature.getFollowed().getSoftware().equals(getFollowed())) { followFeature.setMail(mail); } } } // ///////////////////////////////////////////////////////////////////////////////////////// // Visitor // ///////////////////////////////////////////////////////////////////////////////////////// @Override public <ReturnType> ReturnType accept(final ModelClassVisitor<ReturnType> visitor) { return visitor.visit(this); } }
true
true
public final void setMail(final boolean mail) throws UnauthorizedOperationException { final Member follower = Member.create(getDao().getFollower()); if (!(AuthToken.isAdmin() || (AuthToken.isAuthenticated() && AuthToken.getMember().equals(follower)))) { throw new UnauthorizedOperationException(Action.WRITE); } getDao().setMail(mail); for (final FollowFeature followFeature : getFollower().getFollowedFeatures()) { if (followFeature.getFollowed().getSoftware().equals(getFollowed())) { followFeature.setMail(mail); } } }
public final void setMail(final boolean mail) throws UnauthorizedOperationException { final Member follower = Member.create(getDao().getFollower()); if (!(AuthToken.isAdmin() || (AuthToken.isAuthenticated() && AuthToken.getMember().equals(follower)))) { throw new UnauthorizedOperationException(Action.WRITE); } getDao().setMail(mail); for (final FollowFeature followFeature : getFollower().getFollowedFeatures()) { if (followFeature.getFollowed().getSoftware() != null && followFeature.getFollowed().getSoftware().equals(getFollowed())) { followFeature.setMail(mail); } } }
diff --git a/cuke4duke-maven-plugin/src/main/java/cuke4duke/mojo/CucumberMojo.java b/cuke4duke-maven-plugin/src/main/java/cuke4duke/mojo/CucumberMojo.java index c3c1da88..60f355f9 100755 --- a/cuke4duke-maven-plugin/src/main/java/cuke4duke/mojo/CucumberMojo.java +++ b/cuke4duke-maven-plugin/src/main/java/cuke4duke/mojo/CucumberMojo.java @@ -1,73 +1,75 @@ package cuke4duke.mojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.Java; import java.util.ArrayList; import java.util.List; import java.util.Arrays; import java.io.File; /** * @goal features */ public class CucumberMojo extends AbstractJRubyMojo { /** * @parameter expression="${cucumber.features}" */ private String features; /** * @parameter expression="${cucumber.installGems}" */ private boolean installGems = false; /** * @parameter expression="${cucumber.gems}" */ protected String[] gems; /** * @parameter expression="${cucumber.args}" */ protected String[] args; /** * @parameter expression="${cucumber.bin}" */ private File cucumberBin; @SuppressWarnings({"unchecked"}) public void execute() throws MojoFailureException, MojoExecutionException { if (installGems) { for (String s : gems) { installGem(parseGem(s)); } } List<String> allArgs = new ArrayList<String>(); + allArgs.add("-r"); + allArgs.add("cuke4duke/cucumber_ext"); allArgs.add(cucumberBin().getAbsolutePath()); allArgs.addAll(Arrays.asList(args)); allArgs.add((features != null) ? features : "features"); Java jruby = jruby(allArgs); try { jruby.execute(); } catch (BuildException e) { throw new MojoFailureException("Cucumber failed", e); } } private File cucumberBin() { return (cucumberBin != null) ? cucumberBin : gemCucumberBin(); } private File gemCucumberBin() { return new File(binDir(), "cucumber"); } }
true
true
public void execute() throws MojoFailureException, MojoExecutionException { if (installGems) { for (String s : gems) { installGem(parseGem(s)); } } List<String> allArgs = new ArrayList<String>(); allArgs.add(cucumberBin().getAbsolutePath()); allArgs.addAll(Arrays.asList(args)); allArgs.add((features != null) ? features : "features"); Java jruby = jruby(allArgs); try { jruby.execute(); } catch (BuildException e) { throw new MojoFailureException("Cucumber failed", e); } }
public void execute() throws MojoFailureException, MojoExecutionException { if (installGems) { for (String s : gems) { installGem(parseGem(s)); } } List<String> allArgs = new ArrayList<String>(); allArgs.add("-r"); allArgs.add("cuke4duke/cucumber_ext"); allArgs.add(cucumberBin().getAbsolutePath()); allArgs.addAll(Arrays.asList(args)); allArgs.add((features != null) ? features : "features"); Java jruby = jruby(allArgs); try { jruby.execute(); } catch (BuildException e) { throw new MojoFailureException("Cucumber failed", e); } }
diff --git a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddPersonToRoleTwoStageGenerator.java b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddPersonToRoleTwoStageGenerator.java index 16dc0ea..9ca4fdd 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddPersonToRoleTwoStageGenerator.java +++ b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddPersonToRoleTwoStageGenerator.java @@ -1,921 +1,921 @@ /* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.vivoweb.webapp.util.ModelUtils; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import com.hp.hpl.jena.vocabulary.XSD; import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.RoleToActivityPredicatePreprocessor; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation; import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode; import edu.cornell.mannlib.vitro.webapp.utils.generators.EditModeUtils; /** * Generates the edit configuration for adding a Role to a Person. Stage one is selecting the type of the non-person thing associated with the Role with the intention of reducing the number of Individuals that the user has to select from. Stage two is selecting the non-person Individual to associate with the Role. This is intended to create a set of statements like: ?person core:hasResearchActivityRole ?newRole. ?newRole rdf:type core:ResearchActivityRole ; roleToActivityPredicate ?someActivity . ?someActivity rdf:type core:ResearchActivity . ?someActivity rdfs:label "activity title" . Important: This form cannot be directly used as a custom form. It has parameters that must be set. See addClinicalRoleToPerson.jsp for an example. roleToActivityPredicate and activityToRolePredicate are both dependent on the type of the activity itself. For a new statement, the predicate type is not known. For an existing statement, the predicate is known but may change based on the type of the activity newly selected. bdc34: TODO: figure out what needs to be customized per role form, document it here in comments TODO: rewrite class as an abstract class with simple, documented, required methods to override AddRoleToPersonTwoStageGenerator is abstract, each subclass will need to configure: From the old JSP version: showRoleLabelField boolean roleType URI roleToActivityPredicate URI activityToRolePredicate URI roleActivityType_optionsType roleActivityType_objectClassURI roleActivityType_literalOptions For the new generator version: template * */ public abstract class AddPersonToRoleTwoStageGenerator extends BaseEditConfigurationGenerator implements EditConfigurationGenerator { private Log log = LogFactory.getLog(AddPersonToRoleTwoStageGenerator.class); /* ***** Methods that are REQUIRED to be implemented in subclasses ***** */ /** Freemarker template to use */ abstract String getTemplate(); /** URI of type for the role context node */ abstract String getRoleType(); /** In the case of literal options, subclass generator will set the options to be returned */ abstract HashMap<String, String> getRoleActivityTypeLiteralOptions(); /** * Each subclass generator will return its own type of option here: * whether literal hardcoded, based on class group, or subclasses of a specific class * The latter two will apparently lend some kind of uri to objectClassUri ? */ abstract RoleActivityOptionTypes getRoleActivityTypeOptionsType(); /** The URI of a Class to use with options if required. An option type like * CHILD_VCLASSES would reqire a role activity object class URI. */ abstract String getRoleActivityTypeObjectClassUri(VitroRequest vreq); /** If true an input should be shown on the form for a * label for the role context node * TODO: move this to the FTL and have label optional. */ abstract boolean isShowRoleLabelField(); /** URI of predicate between role context node and activity */ //Bdc34: not used anywhere? that's odd // abstract String getActivityToRolePredicate(); @Override public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) { EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo(); initProcessParameters(vreq, session, editConfiguration); editConfiguration.setVarNameForSubject("grant"); editConfiguration.setVarNameForPredicate("rolePredicate"); editConfiguration.setVarNameForObject("role"); // Required N3 editConfiguration.setN3Required(list( N3_PREFIX + "\n" + "?grant ?rolePredicate ?role .\n" + "?role a ?roleType .\n" )); // Optional N3 //Note here we are placing the role to activity relationships as optional, since //it's possible to delete this relationship from the activity //On submission, if we kept these statements in n3required, the retractions would //not have all variables substituted, leading to an error //Note also we are including the relationship as a separate string in the array, to allow it to be //independently evaluated and passed back with substitutions even if the other strings are not //substituted correctly. editConfiguration.setN3Optional( list( - "?role core:researcherRoleOf" + /*getRoleToActivityPlaceholder() + */" ?roleActivity .\n"+ - "?roleActivity core:hasResearcherRole" + /*getActivityToRolePlaceholder() + */" ?role .", + "?role <http://vivoweb.org/ontology/core#researcherRoleOf>" + /*getRoleToActivityPlaceholder() + */" ?roleActivity .\n"+ + "?roleActivity <http://vivoweb.org/ontology/core#hasResearcherRole>" + /*getActivityToRolePlaceholder() + */" ?role .", "?role ?inverseRolePredicate ?grant .", getN3ForActivityLabel(), getN3ForActivityType(), getN3RoleLabelAssertion(), getN3ForStart(), getN3ForEnd() )); editConfiguration.setNewResources( newResources(vreq) ); //In scope setUrisAndLiteralsInScope(editConfiguration, vreq); //on Form setUrisAndLiteralsOnForm(editConfiguration, vreq); //Sparql queries setSparqlQueries(editConfiguration, vreq); //set fields setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq)); //Form title and submit label now moved to edit configuration template //TODO: check if edit configuration template correct place to set those or whether //additional methods here should be used and reference instead, e.g. edit configuration template could call //default obj property form.populateTemplate or some such method //Select from existing also set within template itself editConfiguration.setTemplate(getTemplate()); //Add validator //editConfiguration.addValidator(new DateTimeIntervalValidationVTwo("startField","endField") ); //editConfiguration.addValidator(new AntiXssValidation()); //Add preprocessors addPreprocessors(editConfiguration, vreq.getWebappDaoFactory()); //Adding additional data, specifically edit mode addFormSpecificData(editConfiguration, vreq); //prepare prepare(vreq, editConfiguration); return editConfiguration; } private void initProcessParameters(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) { editConfiguration.setFormUrl(EditConfigurationUtils.getFormUrlWithoutContext(vreq)); editConfiguration.setEntityToReturnTo(EditConfigurationUtils.getSubjectUri(vreq)); } /* N3 Required and Optional Generators as well as supporting methods */ private String getN3ForActivityLabel() { return "?roleActivity <" + RDFS.label.getURI() + "> ?activityLabel ."; } private String getN3ForActivityType() { return "?roleActivity a ?roleActivityType ."; } private String getN3RoleLabelAssertion() { return "?role <" + RDFS.label.getURI() + "> ?roleLabel ."; } //Method b/c used in two locations, n3 optional and n3 assertions private List<String> getN3ForStart() { List<String> n3ForStart = new ArrayList<String>(); n3ForStart.add("?role <" + RoleToIntervalURI + "> ?intervalNode ." + "?intervalNode <" + RDF.type.getURI() + "> <" + IntervalTypeURI + "> ." + "?intervalNode <" + IntervalToStartURI + "> ?startNode ." + "?startNode <" + RDF.type.getURI() + "> <" + DateTimeValueTypeURI + "> ." + "?startNode <" + DateTimeValueURI + "> ?startField-value ." + "?startNode <" + DateTimePrecisionURI + "> ?startField-precision ."); return n3ForStart; } private List<String> getN3ForEnd() { List<String> n3ForEnd = new ArrayList<String>(); n3ForEnd.add("?role <" + RoleToIntervalURI + "> ?intervalNode . " + "?intervalNode <" + RDF.type.getURI() + "> <" + IntervalTypeURI + "> ." + "?intervalNode <" + IntervalToEndURI + "> ?endNode ." + "?endNode <" + RDF.type.getURI() + "> <" + DateTimeValueTypeURI + "> ." + "?endNode <" + DateTimeValueURI + "> ?endField-value ." + "?endNode <" + DateTimePrecisionURI+ "> ?endField-precision ."); return n3ForEnd; } /** Get new resources */ private Map<String, String> newResources(VitroRequest vreq) { String DEFAULT_NS_TOKEN=null; //null forces the default NS HashMap<String, String> newResources = new HashMap<String, String>(); newResources.put("role", DEFAULT_NS_TOKEN); newResources.put("roleActivity", DEFAULT_NS_TOKEN); newResources.put("intervalNode", DEFAULT_NS_TOKEN); newResources.put("startNode", DEFAULT_NS_TOKEN); newResources.put("endNode", DEFAULT_NS_TOKEN); return newResources; } /** Set URIS and Literals In Scope and on form and supporting methods */ private void setUrisAndLiteralsInScope(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>(); //Setting inverse role predicate urisInScope.put("inverseRolePredicate", getInversePredicate(vreq)); urisInScope.put("roleType", list( getRoleType() ) ); //Uris in scope include subject, predicate, and object var editConfiguration.setUrisInScope(urisInScope); //literals in scope empty initially, usually populated by code in prepare for update //with existing values for variables } private List<String> getInversePredicate(VitroRequest vreq) { List<String> inversePredicateArray = new ArrayList<String>(); ObjectProperty op = EditConfigurationUtils.getObjectProperty(vreq); if(op != null && op.getURIInverse() != null) { inversePredicateArray.add(op.getURIInverse()); } return inversePredicateArray; } private void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { List<String> urisOnForm = new ArrayList<String>(); //add role activity and roleActivityType to uris on form urisOnForm.add("roleActivity"); urisOnForm.add("roleActivityType"); //Also adding the predicates //TODO: Check how to override this in case of default parameter? Just write hidden input to form? urisOnForm.add("roleToActivityPredicate"); urisOnForm.add("activityToRolePredicate"); editConfiguration.setUrisOnform(urisOnForm); //activity label and role label are literals on form List<String> literalsOnForm = new ArrayList<String>(); literalsOnForm.add("activityLabel"); literalsOnForm.add("roleLabel"); editConfiguration.setLiteralsOnForm(literalsOnForm); } /** Set SPARQL Queries and supporting methods. */ private void setSparqlQueries(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { //Queries for activity label, role label, start Field value, end Field value HashMap<String, String> map = new HashMap<String, String>(); map.put("activityLabel", getActivityLabelQuery(vreq)); map.put("roleLabel", getRoleLabelQuery(vreq)); map.put("startField-value", getExistingStartDateQuery(vreq)); map.put("endField-value", getExistingEndDateQuery(vreq)); editConfiguration.setSparqlForExistingLiterals(map); //Queries for role activity, activity type query, interval node, // start node, end node, start field precision, endfield precision map = new HashMap<String, String>(); map.put("roleActivity", getRoleActivityQuery(vreq)); map.put("roleActivityType", getActivityTypeQuery(vreq)); map.put("intervalNode", getIntervalNodeQuery(vreq)); map.put("startNode", getStartNodeQuery(vreq)); map.put("endNode", getEndNodeQuery(vreq)); map.put("startField-precision", getStartPrecisionQuery(vreq)); map.put("endField-precision", getEndPrecisionQuery(vreq)); //Also need sparql queries for roleToActivityPredicate and activityToRolePredicate map.put("roleToActivityPredicate", getRoleToActivityPredicateQuery(vreq)); map.put("activityToRolePredicate", getActivityToRolePredicateQuery(vreq)); editConfiguration.setSparqlForExistingUris(map); } private String getActivityToRolePredicateQuery(VitroRequest vreq) { String query = "SELECT ?existingActivityToRolePredicate \n " + "WHERE { \n" + "?roleActivity ?existingActivityToRolePredicate ?role .\n"; //Get possible predicates List<String> addToQuery = new ArrayList<String>(); List<String> predicates = getPossibleActivityToRolePredicates(); for(String p:predicates) { addToQuery.add("(?existingActivityToRolePredicate=<" + p + ">)"); } query += "FILTER (" + StringUtils.join(addToQuery, " || ") + ")\n"; query += "}"; return query; } private String getRoleToActivityPredicateQuery(VitroRequest vreq) { String query = "SELECT ?existingRoleToActivityPredicate \n " + "WHERE { \n" + "?role ?existingRoleToActivityPredicate ?roleActivity .\n"; //Get possible predicates query += getFilterRoleToActivityPredicate("existingRoleToActivityPredicate"); query += "\n}"; return query; } private String getEndPrecisionQuery(VitroRequest vreq) { String query = "SELECT ?existingEndPrecision WHERE {\n" + "?role <" + RoleToIntervalURI + "> ?intervalNode .\n" + "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n" + "?intervalNode <" + IntervalToEndURI + "> ?endNode .\n" + "?endNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> . \n" + "?endNode <" + DateTimePrecisionURI + "> ?existingEndPrecision . }"; return query; } private String getStartPrecisionQuery(VitroRequest vreq) { String query = "SELECT ?existingStartPrecision WHERE {\n" + "?role <" + RoleToIntervalURI + "> ?intervalNode .\n" + "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n" + "?intervalNode <" + IntervalToStartURI + "> ?startNode .\n" + "?startNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> . \n" + "?startNode <" + DateTimePrecisionURI + "> ?existingStartPrecision . }"; return query; } private String getEndNodeQuery(VitroRequest vreq) { String query = "SELECT ?existingEndNode WHERE {\n"+ "?role <" + RoleToIntervalURI + "> ?intervalNode .\n"+ "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n"+ "?intervalNode <" + IntervalToEndURI + "> ?existingEndNode . \n"+ "?existingEndNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> .}\n"; return query; } private String getStartNodeQuery(VitroRequest vreq) { String query = "SELECT ?existingStartNode WHERE {\n"+ "?role <" + RoleToIntervalURI + "> ?intervalNode .\n"+ "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n"+ "?intervalNode <" + IntervalToStartURI + "> ?existingStartNode . \n"+ "?existingStartNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> .}"; return query; } private String getIntervalNodeQuery(VitroRequest vreq) { String query = "SELECT ?existingIntervalNode WHERE { \n" + "?role <" + RoleToIntervalURI + "> ?existingIntervalNode . \n" + " ?existingIntervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> . }\n"; return query; } /* * The activity type query results must be limited to the values in the activity type select element. * Sometimes the query returns a superclass such as owl:Thing instead. * Make use of vitro:mostSpecificType so that, for example, an individual is both a * core:InvitedTalk and a core:Presentation, core:InvitedTalk is selected. * vitro:mostSpecificType alone may not suffice, since it does not guarantee that the value returned * is in the select list. * We could still have problems if the value from the select list is not a vitro:mostSpecificType, * but that is unlikely. */ //This method had some code already setup in the jsp file private String getActivityTypeQuery(VitroRequest vreq) { String activityTypeQuery = null; //roleActivityType_optionsType: This gets you whether this is a literal // RoleActivityOptionTypes optionsType = getRoleActivityTypeOptionsType(); // Note that this value is overloaded to specify either object class uri or classgroup uri String objectClassUri = getRoleActivityTypeObjectClassUri(vreq); if (StringUtils.isNotBlank(objectClassUri)) { log.debug("objectClassUri = " + objectClassUri); if (RoleActivityOptionTypes.VCLASSGROUP.equals(optionsType)) { activityTypeQuery = getClassgroupActivityTypeQuery(vreq); activityTypeQuery = QueryUtils.subUriForQueryVar(activityTypeQuery, "classgroup", objectClassUri); } else if (RoleActivityOptionTypes.CHILD_VCLASSES.equals(optionsType)) { activityTypeQuery = getSubclassActivityTypeQuery(vreq); activityTypeQuery = QueryUtils.subUriForQueryVar(activityTypeQuery, "objectClassUri", objectClassUri); } else { activityTypeQuery = getDefaultActivityTypeQuery(vreq); } // Select options are hardcoded } else if (RoleActivityOptionTypes.HARDCODED_LITERALS.equals(optionsType)) { //literal options HashMap<String, String> typeLiteralOptions = getRoleActivityTypeLiteralOptions(); if (typeLiteralOptions.size() > 0) { try { List<String> typeUris = new ArrayList<String>(); Set<String> optionUris = typeLiteralOptions.keySet(); for(String uri: optionUris) { if(!uri.isEmpty()) { typeUris.add("(?existingActivityType = <" + uri + ">)"); } } String typeFilters = "FILTER (" + StringUtils.join(typeUris, "||") + ")"; String defaultActivityTypeQuery = getDefaultActivityTypeQuery(vreq); activityTypeQuery = defaultActivityTypeQuery.replaceAll("}$", "") + typeFilters + "}"; } catch (Exception e) { activityTypeQuery = getDefaultActivityTypeQuery(vreq); } } else { activityTypeQuery = getDefaultActivityTypeQuery(vreq); } } else { activityTypeQuery = getDefaultActivityTypeQuery(vreq); } //The replacement of activity type query's predicate was only relevant when we actually //know which predicate is definitely being used here //Here we have multiple values possible for predicate so the original //Replacement should only happen when we have an actual predicate String replaceRoleToActivityPredicate = getRoleToActivityPredicate(vreq); activityTypeQuery = QueryUtils.replaceQueryVar(activityTypeQuery, "predicate", getRoleToActivityPlaceholderName()); log.debug("Activity type query: " + activityTypeQuery); return activityTypeQuery; } private String getDefaultActivityTypeQuery(VitroRequest vreq) { String query = "PREFIX core: <" + VIVO_NS + ">\n" + "PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" + "SELECT ?existingActivityType WHERE { \n" + " ?role ?predicate ?existingActivity . \n" + " ?existingActivity vitro:mostSpecificType ?existingActivityType . \n"; query += getFilterRoleToActivityPredicate("predicate"); query+= "}"; return query; } private String getSubclassActivityTypeQuery(VitroRequest vreq) { String query = "PREFIX core: <" + VIVO_NS + ">\n" + "PREFIX rdfs: <" + VitroVocabulary.RDFS + ">\n" + "PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" + "SELECT ?existingActivityType WHERE {\n" + " ?role ?predicate ?existingActivity . \n" + " ?existingActivity vitro:mostSpecificType ?existingActivityType . \n" + " ?existingActivityType rdfs:subClassOf ?objectClassUri . \n"; query += getFilterRoleToActivityPredicate("predicate"); query+= "}"; return query; } private String getClassgroupActivityTypeQuery(VitroRequest vreq) { String query = "PREFIX core: <" + VIVO_NS + ">\n" + "PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" + "SELECT ?existingActivityType WHERE { \n" + " ?role ?predicate ?existingActivity . \n" + " ?existingActivity vitro:mostSpecificType ?existingActivityType . \n" + " ?existingActivityType vitro:inClassGroup ?classgroup . \n"; query += getFilterRoleToActivityPredicate("predicate"); query+= "}"; return query; } private String getRoleActivityQuery(VitroRequest vreq) { //If role to activity predicate is the default query, then we need to replace with a union //of both realizedIn and the other String query = "PREFIX core: <" + VIVO_NS + ">"; //Portion below for multiple possible predicates List<String> predicates = getPossibleRoleToActivityPredicates(); List<String> addToQuery = new ArrayList<String>(); query += "SELECT ?existingActivity WHERE { \n" + " ?role ?predicate ?existingActivity . \n "; query += getFilterRoleToActivityPredicate("predicate"); query += "}"; return query; } private String getExistingEndDateQuery(VitroRequest vreq) { String query = " SELECT ?existingEndDate WHERE {\n" + "?role <" + RoleToIntervalURI + "> ?intervalNode .\n" + "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n" + "?intervalNode <" + IntervalToEndURI + "> ?endNode .\n" + "?endNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> .\n" + "?endNode <" + DateTimeValueURI + "> ?existingEndDate . }"; return query; } private String getExistingStartDateQuery(VitroRequest vreq) { String query = "SELECT ?existingDateStart WHERE {\n" + "?role <" + RoleToIntervalURI + "> ?intervalNode .\n" + "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n" + "?intervalNode <" + IntervalToStartURI+ "> ?startNode .\n" + "?startNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> .\n" + "?startNode <" + DateTimeValueURI + "> ?existingDateStart . }"; return query; } private String getRoleLabelQuery(VitroRequest vreq) { String query = "SELECT ?existingRoleLabel WHERE { \n" + "?role <" + VitroVocabulary.LABEL + "> ?existingRoleLabel . }"; return query; } private String getActivityLabelQuery(VitroRequest vreq) { String query = "PREFIX core: <" + VIVO_NS + ">" + "PREFIX rdfs: <" + RDFS.getURI() + "> \n"; query += "SELECT ?existingTitle WHERE { \n" + "?role ?predicate ?existingActivity . \n" + "?existingActivity rdfs:label ?existingTitle . \n"; query += getFilterRoleToActivityPredicate("predicate"); query += "}"; return query; } /** * * Set Fields and supporting methods */ private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) { Map<String, FieldVTwo> fields = new HashMap<String, FieldVTwo>(); //Multiple fields getActivityLabelField(editConfiguration, vreq, fields); getRoleActivityTypeField(editConfiguration, vreq, fields); getRoleActivityField(editConfiguration, vreq, fields); getRoleLabelField(editConfiguration, vreq, fields); getStartField(editConfiguration, vreq, fields); getEndField(editConfiguration, vreq, fields); //These fields are for the predicates that will be set later //TODO: Do these only if not using a parameter for the predicate? getRoleToActivityPredicateField(editConfiguration, vreq, fields); getActivityToRolePredicateField(editConfiguration, vreq, fields); editConfiguration.setFields(fields); } //This is a literal technically? private void getActivityToRolePredicateField( EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "activityToRolePredicate"; //get range data type uri and range language String stringDatatypeUri = XSD.xstring.toString(); FieldVTwo field = new FieldVTwo(); field.setName(fieldName); //queryForExisting is not being used anywhere in Field //Not really interested in validators here List<String> validators = new ArrayList<String>(); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(null); field.setLiteralOptions(new ArrayList<List<String>>()); fields.put(field.getName(), field); } private void getRoleToActivityPredicateField( EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "roleToActivityPredicate"; //get range data type uri and range language String stringDatatypeUri = XSD.xstring.toString(); FieldVTwo field = new FieldVTwo(); field.setName(fieldName); //queryForExisting is not being used anywhere in Field //Not really interested in validators here List<String> validators = new ArrayList<String>(); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(null); field.setLiteralOptions(new ArrayList<List<String>>()); fields.put(field.getName(), field); } //Label of "right side" of role, i.e. label for role roleIn Activity private void getActivityLabelField(EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "activityLabel"; //get range data type uri and range language String stringDatatypeUri = XSD.xstring.toString(); FieldVTwo field = new FieldVTwo(); field.setName(fieldName); //queryForExisting is not being used anywhere in Field List<String> validators = new ArrayList<String>(); //If add mode or repair, etc. need to add label required validator if(isAddMode(vreq) || isRepairMode(vreq)) { validators.add("nonempty"); } validators.add("datatype:" + stringDatatypeUri); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(stringDatatypeUri); field.setLiteralOptions(new ArrayList<List<String>>()); fields.put(field.getName(), field); } //type of "right side" of role, i.e. type of activity from role roleIn activity private void getRoleActivityTypeField( EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "roleActivityType"; //get range data type uri and range language FieldVTwo field = new FieldVTwo(); field.setName(fieldName); List<String> validators = new ArrayList<String>(); if(isAddMode(vreq) || isRepairMode(vreq)) { validators.add("nonempty"); } field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field //TODO: Check if this is correct field.setOptionsType(getRoleActivityTypeOptionsType().toString()); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(getRoleActivityTypeObjectClassUri(vreq)); field.setRangeDatatypeUri(null); HashMap<String, String> literalOptionsMap = getRoleActivityTypeLiteralOptions(); List<List<String>> fieldLiteralOptions = new ArrayList<List<String>>(); Set<String> optionUris = literalOptionsMap.keySet(); for(String optionUri: optionUris) { List<String> uriLabelArray = new ArrayList<String>(); uriLabelArray.add(optionUri); uriLabelArray.add(literalOptionsMap.get(optionUri)); fieldLiteralOptions.add(uriLabelArray); } field.setLiteralOptions(fieldLiteralOptions); fields.put(field.getName(), field); } //Assuming URI for activity for role? private void getRoleActivityField(EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "roleActivity"; //get range data type uri and range language FieldVTwo field = new FieldVTwo(); field.setName(fieldName); List<String> validators = new ArrayList<String>(); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(null); //empty field.setLiteralOptions(new ArrayList<List<String>>()); fields.put(field.getName(), field); } private void getRoleLabelField(EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "roleLabel"; String stringDatatypeUri = XSD.xstring.toString(); FieldVTwo field = new FieldVTwo(); field.setName(fieldName); List<String> validators = new ArrayList<String>(); validators.add("datatype:" + stringDatatypeUri); if(isShowRoleLabelField()) { validators.add("nonempty"); } field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(stringDatatypeUri); //empty field.setLiteralOptions(new ArrayList<List<String>>()); fields.put(field.getName(), field); } private void getStartField(EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "startField"; FieldVTwo field = new FieldVTwo(); field.setName(fieldName); List<String> validators = new ArrayList<String>(); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(null); //empty field.setLiteralOptions(new ArrayList<List<String>>()); //This logic was originally after edit configuration object created from json in original jsp field.setEditElement( new DateTimeWithPrecisionVTwo(field, VitroVocabulary.Precision.YEAR.uri(), VitroVocabulary.Precision.NONE.uri())); fields.put(field.getName(), field); } private void getEndField(EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "endField"; FieldVTwo field = new FieldVTwo(); field.setName(fieldName); List<String> validators = new ArrayList<String>(); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(null); //empty field.setLiteralOptions(new ArrayList<List<String>>()); //Set edit element field.setEditElement( new DateTimeWithPrecisionVTwo(field, VitroVocabulary.Precision.YEAR.uri(), VitroVocabulary.Precision.NONE.uri())); fields.put(field.getName(), field); } private void addPreprocessors(EditConfigurationVTwo editConfiguration, WebappDaoFactory wadf) { //Add preprocessor that will replace the role to activity predicate and inverse //with correct properties based on the activity type editConfiguration.addEditSubmissionPreprocessor( new RoleToActivityPredicatePreprocessor(editConfiguration, wadf)); } //This has a default value, but note that even that will not be used //in the update with realized in or contributes to //Overridden when need be in subclassed generator //Also note that for now we're going to actually going to return a //placeholder value by default public String getRoleToActivityPredicate(VitroRequest vreq) { //TODO: <uri> and ?placeholder are incompatible return getRoleToActivityPlaceholder(); } //Ensure when overwritten that this includes the <> b/c otherwise the query won't work //Some values will have a default value public List<String> getPossibleRoleToActivityPredicates() { return ModelUtils.getPossiblePropertiesForRole(); } public List<String> getPossibleActivityToRolePredicates() { return ModelUtils.getPossibleInversePropertiesForRole(); } /* Methods that check edit mode */ public EditMode getEditMode(VitroRequest vreq) { List<String> roleToGrantPredicates = getPossibleRoleToActivityPredicates(); return EditModeUtils.getEditMode(vreq, roleToGrantPredicates); } private boolean isAddMode(VitroRequest vreq) { return EditModeUtils.isAddMode(getEditMode(vreq)); } private boolean isEditMode(VitroRequest vreq) { return EditModeUtils.isEditMode(getEditMode(vreq)); } private boolean isRepairMode(VitroRequest vreq) { return EditModeUtils.isRepairMode(getEditMode(vreq)); } /* URIS for various predicates */ private final String VIVO_NS="http://vivoweb.org/ontology/core#"; private final String RoleToIntervalURI = VIVO_NS + "dateTimeInterval"; private final String IntervalTypeURI = VIVO_NS + "DateTimeInterval"; private final String IntervalToStartURI = VIVO_NS + "start"; private final String IntervalToEndURI = VIVO_NS + "end"; private final String StartYearPredURI = VIVO_NS + "startYear"; private final String EndYearPredURI = VIVO_NS + "endYear"; private final String DateTimeValueTypeURI=VIVO_NS + "DateTimeValue"; private final String DateTimePrecisionURI=VIVO_NS + "dateTimePrecision"; private final String DateTimeValueURI = VIVO_NS + "dateTime"; //Form specific data public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { HashMap<String, Object> formSpecificData = new HashMap<String, Object>(); formSpecificData.put("editMode", getEditMode(vreq).name().toLowerCase()); //Fields that will need select lists generated //Store field names List<String> objectSelect = new ArrayList<String>(); objectSelect.add("roleActivityType"); //TODO: Check if this is the proper way to do this? formSpecificData.put("objectSelect", objectSelect); //Also put in show role label field formSpecificData.put("showRoleLabelField", isShowRoleLabelField()); //Put in the fact that we require field editConfiguration.setFormSpecificData(formSpecificData); } public String getFilterRoleToActivityPredicate(String predicateVar) { String addFilter = "FILTER ("; List<String> predicates = getPossibleRoleToActivityPredicates(); List<String> filterPortions = new ArrayList<String>(); for(String p: predicates) { filterPortions.add("(?" + predicateVar + "=<" + p + ">)"); } addFilter += StringUtils.join(filterPortions, " || "); addFilter += ")"; return addFilter; } private String getRoleToActivityPlaceholder() { return "?" + getRoleToActivityPlaceholderName(); } private String getRoleToActivityPlaceholderName() { return "roleToActivityPredicate"; } private String getActivityToRolePlaceholder() { return "?activityToRolePredicate"; } //Types of options to populate drop-down for types for the "right side" of the role public static enum RoleActivityOptionTypes { VCLASSGROUP, CHILD_VCLASSES, HARDCODED_LITERALS }; private final String N3_PREFIX = "@prefix core: <http://vivoweb.org/ontology/core#> ."; }
true
true
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) { EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo(); initProcessParameters(vreq, session, editConfiguration); editConfiguration.setVarNameForSubject("grant"); editConfiguration.setVarNameForPredicate("rolePredicate"); editConfiguration.setVarNameForObject("role"); // Required N3 editConfiguration.setN3Required(list( N3_PREFIX + "\n" + "?grant ?rolePredicate ?role .\n" + "?role a ?roleType .\n" )); // Optional N3 //Note here we are placing the role to activity relationships as optional, since //it's possible to delete this relationship from the activity //On submission, if we kept these statements in n3required, the retractions would //not have all variables substituted, leading to an error //Note also we are including the relationship as a separate string in the array, to allow it to be //independently evaluated and passed back with substitutions even if the other strings are not //substituted correctly. editConfiguration.setN3Optional( list( "?role core:researcherRoleOf" + /*getRoleToActivityPlaceholder() + */" ?roleActivity .\n"+ "?roleActivity core:hasResearcherRole" + /*getActivityToRolePlaceholder() + */" ?role .", "?role ?inverseRolePredicate ?grant .", getN3ForActivityLabel(), getN3ForActivityType(), getN3RoleLabelAssertion(), getN3ForStart(), getN3ForEnd() )); editConfiguration.setNewResources( newResources(vreq) ); //In scope setUrisAndLiteralsInScope(editConfiguration, vreq); //on Form setUrisAndLiteralsOnForm(editConfiguration, vreq); //Sparql queries setSparqlQueries(editConfiguration, vreq); //set fields setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq)); //Form title and submit label now moved to edit configuration template //TODO: check if edit configuration template correct place to set those or whether //additional methods here should be used and reference instead, e.g. edit configuration template could call //default obj property form.populateTemplate or some such method //Select from existing also set within template itself editConfiguration.setTemplate(getTemplate()); //Add validator //editConfiguration.addValidator(new DateTimeIntervalValidationVTwo("startField","endField") ); //editConfiguration.addValidator(new AntiXssValidation()); //Add preprocessors addPreprocessors(editConfiguration, vreq.getWebappDaoFactory()); //Adding additional data, specifically edit mode addFormSpecificData(editConfiguration, vreq); //prepare prepare(vreq, editConfiguration); return editConfiguration; }
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) { EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo(); initProcessParameters(vreq, session, editConfiguration); editConfiguration.setVarNameForSubject("grant"); editConfiguration.setVarNameForPredicate("rolePredicate"); editConfiguration.setVarNameForObject("role"); // Required N3 editConfiguration.setN3Required(list( N3_PREFIX + "\n" + "?grant ?rolePredicate ?role .\n" + "?role a ?roleType .\n" )); // Optional N3 //Note here we are placing the role to activity relationships as optional, since //it's possible to delete this relationship from the activity //On submission, if we kept these statements in n3required, the retractions would //not have all variables substituted, leading to an error //Note also we are including the relationship as a separate string in the array, to allow it to be //independently evaluated and passed back with substitutions even if the other strings are not //substituted correctly. editConfiguration.setN3Optional( list( "?role <http://vivoweb.org/ontology/core#researcherRoleOf>" + /*getRoleToActivityPlaceholder() + */" ?roleActivity .\n"+ "?roleActivity <http://vivoweb.org/ontology/core#hasResearcherRole>" + /*getActivityToRolePlaceholder() + */" ?role .", "?role ?inverseRolePredicate ?grant .", getN3ForActivityLabel(), getN3ForActivityType(), getN3RoleLabelAssertion(), getN3ForStart(), getN3ForEnd() )); editConfiguration.setNewResources( newResources(vreq) ); //In scope setUrisAndLiteralsInScope(editConfiguration, vreq); //on Form setUrisAndLiteralsOnForm(editConfiguration, vreq); //Sparql queries setSparqlQueries(editConfiguration, vreq); //set fields setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq)); //Form title and submit label now moved to edit configuration template //TODO: check if edit configuration template correct place to set those or whether //additional methods here should be used and reference instead, e.g. edit configuration template could call //default obj property form.populateTemplate or some such method //Select from existing also set within template itself editConfiguration.setTemplate(getTemplate()); //Add validator //editConfiguration.addValidator(new DateTimeIntervalValidationVTwo("startField","endField") ); //editConfiguration.addValidator(new AntiXssValidation()); //Add preprocessors addPreprocessors(editConfiguration, vreq.getWebappDaoFactory()); //Adding additional data, specifically edit mode addFormSpecificData(editConfiguration, vreq); //prepare prepare(vreq, editConfiguration); return editConfiguration; }
diff --git a/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/test/java/org/xwiki/rendering/internal/macro/DefaultMacroManagerTest.java b/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/test/java/org/xwiki/rendering/internal/macro/DefaultMacroManagerTest.java index 2459c659f..5406c1a3f 100644 --- a/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/test/java/org/xwiki/rendering/internal/macro/DefaultMacroManagerTest.java +++ b/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/test/java/org/xwiki/rendering/internal/macro/DefaultMacroManagerTest.java @@ -1,162 +1,162 @@ /* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.rendering.internal.macro; import java.util.Collections; import org.jmock.Expectations; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.xwiki.component.descriptor.DefaultComponentDescriptor; import org.xwiki.component.manager.ComponentManager; import org.xwiki.component.util.ReflectionUtils; import org.xwiki.rendering.internal.transformation.macro.TestSimpleMacro; import org.xwiki.rendering.macro.Macro; import org.xwiki.rendering.macro.MacroId; import org.xwiki.rendering.macro.MacroIdFactory; import org.xwiki.rendering.macro.MacroLookupException; import org.xwiki.rendering.syntax.Syntax; import org.xwiki.rendering.syntax.SyntaxFactory; import org.xwiki.rendering.syntax.SyntaxType; import org.xwiki.test.AbstractMockingComponentTestCase; import org.xwiki.test.annotation.MockingRequirement; /** * Unit tests for {@link org.xwiki.rendering.internal.macro.DefaultMacroManager}. * * @version $Id$ * @since 1.9M1 */ public class DefaultMacroManagerTest extends AbstractMockingComponentTestCase { // Mock all required components except for some for which we want to use the real implementations since they make // the test easier to write (no need to mock them). @MockingRequirement(exceptions = { ComponentManager.class, MacroIdFactory.class }) private DefaultMacroManager macroManager; @Test public void testMacroExists() { Assert.assertTrue(this.macroManager.exists(new MacroId("testsimplemacro"))); } @Test public void testGetExistingMacro() throws Exception { Assert.assertNotNull(this.macroManager.getMacro(new MacroId("testsimplemacro"))); } @Test public void testGetNotExistingMacro() { try { this.macroManager.getMacro(new MacroId("notregisteredmacro")); Assert.fail("Expected a macro lookup exception when looking for not registered macro"); } catch (MacroLookupException expected) { Assert.assertEquals("No macro [notregisteredmacro] could be found.", expected.getMessage()); } } @Test public void testSyntaxSpecificMacroExistsWhenMacroIsRegisteredForAllSyntaxes() { Assert.assertFalse(this.macroManager.exists(new MacroId("testsimplemacro", new Syntax(SyntaxType.XWIKI, "2.0")))); } @Test public void testGetExistingMacroForASpecificSyntaxWhenMacroIsRegisteredForAllSyntaxes() throws Exception { Assert.assertNotNull(this.macroManager.getMacro(new MacroId("testsimplemacro", new Syntax(SyntaxType.XWIKI, "2.0")))); } public void testMacroRegisteredForAGivenSyntaxOnly() throws Exception { Macro< ? > macro = new TestSimpleMacro(); DefaultComponentDescriptor<Macro> descriptor = new DefaultComponentDescriptor<Macro>(); descriptor.setRole(Macro.class); descriptor.setRoleHint("macro/xwiki/2.0"); getComponentManager().registerComponent(descriptor, macro); Assert.assertFalse(this.macroManager.exists(new MacroId("macro"))); Assert.assertTrue(this.macroManager.exists(new MacroId("macro", new Syntax(SyntaxType.XWIKI, "2.0")))); Macro< ? > macroResult = this.macroManager.getMacro(new MacroId("macro", new Syntax(SyntaxType.XWIKI, "2.0"))); Assert.assertSame(macro, macroResult); } @Test public void testMacroRegisteredForAGivenSyntaxOverridesMacroRegisteredForAllSyntaxes() throws Exception { Macro< ? > macro1 = new TestSimpleMacro(); Macro< ? > macro2 = new TestSimpleMacro(); DefaultComponentDescriptor<Macro> descriptor = new DefaultComponentDescriptor<Macro>(); descriptor.setRole(Macro.class); descriptor.setRoleHint("macro"); getComponentManager().registerComponent(descriptor, macro1); descriptor = new DefaultComponentDescriptor<Macro>(); descriptor.setRole(Macro.class); descriptor.setRoleHint("macro/xwiki/2.0"); getComponentManager().registerComponent(descriptor, macro2); Assert.assertTrue(this.macroManager.exists(new MacroId("macro"))); Assert.assertTrue(this.macroManager.exists(new MacroId("macro", new Syntax(SyntaxType.XWIKI, "2.0")))); Macro< ? > macroResult1 = this.macroManager.getMacro(new MacroId("macro", new Syntax(SyntaxType.XWIKI, "2.0"))); Assert.assertSame(macro2, macroResult1); Macro< ? > macroResult2 = this.macroManager.getMacro(new MacroId("macro")); Assert.assertSame(macro1, macroResult2); } /** * Tests what happens when a macro is registered with an invalid hint. */ @Test public void testInvalidMacroHint() throws Exception { // Control the list of macros found in the system by replacing the real ComponentManager in MacroManager with // a mock one. final ComponentManager mockRootComponentManager = getMockery().mock(ComponentManager.class); ReflectionUtils.setFieldValue(this.macroManager, "rootComponentManager", mockRootComponentManager); - final Logger logger = getComponentManager().lookup(Logger.class); + final Logger logger = getMockLogger(); getMockery().checking(new Expectations() {{ allowing(mockRootComponentManager).lookup(ComponentManager.class, "context"); will(returnValue(mockRootComponentManager)); allowing(mockRootComponentManager).lookupMap(Macro.class); will(returnValue(Collections.singletonMap("macro/invalidsyntax", "dummy"))); // Test: Make sure the logger is called with the following content. This is the assert for this test. oneOf(logger).warn("Invalid Macro descriptor format for hint " + "[macro/invalidsyntax]. The hint should contain either the macro name only or the macro name " + "followed by the syntax for which it is valid. In that case the macro name should be followed by " + "a \"/\" followed by the syntax name followed by another \"/\" followed by the syntax version. " + "For example \"html/xwiki/2.0\". This macro will not be available in the system."); }}); SyntaxFactory syntaxFactory = getComponentManager().lookup(SyntaxFactory.class); this.macroManager.getMacroIds(syntaxFactory.createSyntaxFromIdString("macro/xwiki/2.0")); } }
true
true
public void testInvalidMacroHint() throws Exception { // Control the list of macros found in the system by replacing the real ComponentManager in MacroManager with // a mock one. final ComponentManager mockRootComponentManager = getMockery().mock(ComponentManager.class); ReflectionUtils.setFieldValue(this.macroManager, "rootComponentManager", mockRootComponentManager); final Logger logger = getComponentManager().lookup(Logger.class); getMockery().checking(new Expectations() {{ allowing(mockRootComponentManager).lookup(ComponentManager.class, "context"); will(returnValue(mockRootComponentManager)); allowing(mockRootComponentManager).lookupMap(Macro.class); will(returnValue(Collections.singletonMap("macro/invalidsyntax", "dummy"))); // Test: Make sure the logger is called with the following content. This is the assert for this test. oneOf(logger).warn("Invalid Macro descriptor format for hint " + "[macro/invalidsyntax]. The hint should contain either the macro name only or the macro name " + "followed by the syntax for which it is valid. In that case the macro name should be followed by " + "a \"/\" followed by the syntax name followed by another \"/\" followed by the syntax version. " + "For example \"html/xwiki/2.0\". This macro will not be available in the system."); }}); SyntaxFactory syntaxFactory = getComponentManager().lookup(SyntaxFactory.class); this.macroManager.getMacroIds(syntaxFactory.createSyntaxFromIdString("macro/xwiki/2.0")); }
public void testInvalidMacroHint() throws Exception { // Control the list of macros found in the system by replacing the real ComponentManager in MacroManager with // a mock one. final ComponentManager mockRootComponentManager = getMockery().mock(ComponentManager.class); ReflectionUtils.setFieldValue(this.macroManager, "rootComponentManager", mockRootComponentManager); final Logger logger = getMockLogger(); getMockery().checking(new Expectations() {{ allowing(mockRootComponentManager).lookup(ComponentManager.class, "context"); will(returnValue(mockRootComponentManager)); allowing(mockRootComponentManager).lookupMap(Macro.class); will(returnValue(Collections.singletonMap("macro/invalidsyntax", "dummy"))); // Test: Make sure the logger is called with the following content. This is the assert for this test. oneOf(logger).warn("Invalid Macro descriptor format for hint " + "[macro/invalidsyntax]. The hint should contain either the macro name only or the macro name " + "followed by the syntax for which it is valid. In that case the macro name should be followed by " + "a \"/\" followed by the syntax name followed by another \"/\" followed by the syntax version. " + "For example \"html/xwiki/2.0\". This macro will not be available in the system."); }}); SyntaxFactory syntaxFactory = getComponentManager().lookup(SyntaxFactory.class); this.macroManager.getMacroIds(syntaxFactory.createSyntaxFromIdString("macro/xwiki/2.0")); }
diff --git a/src/simpleserver/stream/StreamTunnel.java b/src/simpleserver/stream/StreamTunnel.java index 41f73b9..72e6d3a 100644 --- a/src/simpleserver/stream/StreamTunnel.java +++ b/src/simpleserver/stream/StreamTunnel.java @@ -1,781 +1,781 @@ /******************************************************************************* * Open Source Initiative OSI - The MIT License:Licensing * The MIT License * Copyright (c) 2010 Charles Wagner Jr. ([email protected]) * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ package simpleserver.stream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.IllegalFormatException; import java.util.regex.Matcher; import java.util.regex.Pattern; import simpleserver.Group; import simpleserver.Player; import simpleserver.Server; public class StreamTunnel { private static final boolean EXPENSIVE_DEBUG_LOGGING = Boolean.getBoolean("EXPENSIVE_DEBUG_LOGGING"); private static final int IDLE_TIME = 30000; private static final int BUFFER_SIZE = 1024; private static final int DESTROY_HITS = 14; private static final byte BLOCK_DESTROYED_STATUS = 3; private static final Pattern MESSAGE_PATTERN = Pattern.compile("^<([^>]+)> (.*)$"); private final boolean isServerTunnel; private final String streamType; private final Player player; private final Server server; private final byte[] buffer; private final Tunneler tunneler; private DataInput in; private DataOutput out; private StreamDumper inputDumper; private StreamDumper outputDumper; private int motionCounter = 0; private boolean inGame = false; private volatile long lastRead; private volatile boolean run = true; public StreamTunnel(InputStream in, OutputStream out, boolean isServerTunnel, Player player) { this.isServerTunnel = isServerTunnel; if (isServerTunnel) { streamType = "ServerStream"; } else { streamType = "PlayerStream"; } this.player = player; server = player.getServer(); DataInputStream dIn = new DataInputStream(new BufferedInputStream(in)); DataOutputStream dOut = new DataOutputStream(new BufferedOutputStream(out)); if (EXPENSIVE_DEBUG_LOGGING) { try { OutputStream dump = new FileOutputStream(streamType + "Input.debug"); InputStreamDumper dumper = new InputStreamDumper(dIn, dump); inputDumper = dumper; this.in = dumper; } catch (FileNotFoundException e) { System.out.println("Unable to open input debug dump!"); throw new RuntimeException(e); } try { OutputStream dump = new FileOutputStream(streamType + "Output.debug"); OutputStreamDumper dumper = new OutputStreamDumper(dOut, dump); outputDumper = dumper; this.out = dumper; } catch (FileNotFoundException e) { System.out.println("Unable to open output debug dump!"); throw new RuntimeException(e); } } else { this.in = dIn; this.out = dOut; } buffer = new byte[BUFFER_SIZE]; tunneler = new Tunneler(); tunneler.start(); lastRead = System.currentTimeMillis(); } public void stop() { run = false; } public boolean isAlive() { return tunneler.isAlive(); } public boolean isActive() { return System.currentTimeMillis() - lastRead < IDLE_TIME || player.isRobot(); } private void handlePacket() throws IOException { Byte packetId = in.readByte(); switch (packetId) { case 0x00: // Keep Alive write(packetId); break; case 0x01: // Login Request/Response write(packetId); write(in.readInt()); write(in.readUTF()); write(in.readUTF()); write(in.readLong()); write(in.readByte()); break; case 0x02: // Handshake String name = in.readUTF(); if (isServerTunnel || player.setName(name)) { tunneler.setName(streamType + "-" + player.getName()); write(packetId); write(name); } break; case 0x03: // Chat Message String message = in.readUTF(); if (isServerTunnel && server.options.getBoolean("useMsgFormats")) { Matcher messageMatcher = MESSAGE_PATTERN.matcher(message); if (messageMatcher.find()) { Player friend = server.findPlayerExact(messageMatcher.group(1)); if (friend != null) { String color = "f"; String title = ""; String format = server.options.get("msgFormat"); Group group = friend.getGroup(); if (group != null) { color = group.getColor(); if (group.showTitle()) { title = group.getName(); format = server.options.get("msgTitleFormat"); } } try { message = String.format(format, friend.getName(), title, color) + messageMatcher.group(2); } catch (IllegalFormatException e) { System.out.println("[SimpleServer] There is an error in your msgFormat/msgTitleFormat settings!"); } } } } if (!isServerTunnel) { if (player.isMuted() && !message.startsWith("/") && !message.startsWith("!")) { player.addMessage("You are muted! You may not send messages to all players."); break; } if (server.options.getBoolean("useSlashes") && message.startsWith("/") || message.startsWith("!") && player.parseCommand(message)) { break; } } write(packetId); write(message); break; case 0x04: // Time Update write(packetId); copyNBytes(8); break; case 0x05: // Player Inventory write(packetId); write(in.readInt()); write(in.readShort()); write(in.readShort()); break; /* boolean guest = player.getGroupId() < 0; int inventoryType = in.readInt(); short itemCount = in.readShort(); if (!guest) { write(packetId); write(inventoryType); write(itemCount); } for (int c = 0; c < itemCount; ++c) { short itemId = in.readShort(); if (!guest) { write(itemId); } if (itemId != -1) { byte itemAmount = in.readByte(); short itemUses = in.readShort(); if (!guest) { write(itemAmount); write(itemUses); } if (!server.itemWatch.playerAllowed(player, itemId, itemAmount)) { server.adminLog("ItemWatchList banned player:\t" + player.getName()); server.banKick(player.getName()); } } } break; */ case 0x06: // Spawn Position write(packetId); copyNBytes(12); break; case 0x07: // Use Entity? write(packetId); copyNBytes(9); break; case 0x08: // Update Health write(packetId); copyNBytes(2); break; case 0x09: // Respawn write(packetId); break; case 0x0a: // Player write(packetId); copyNBytes(1); if (!inGame && !isServerTunnel) { player.sendMOTD(); inGame = true; } break; case 0x0b: // Player Position write(packetId); copyPlayerLocation(); break; case 0x0c: // Player Look write(packetId); copyNBytes(9); break; case 0x0d: // Player Position & Look write(packetId); copyPlayerLocation(); copyNBytes(8); break; case 0x0e: // Player Digging if (!isServerTunnel) { if (player.getGroupId() < 0) { skipNBytes(11); } else { byte status = in.readByte(); int x = in.readInt(); byte y = in.readByte(); int z = in.readInt(); byte face = in.readByte(); if (!server.chests.hasLock(x, y, z) || player.isAdmin()) { if (server.chests.hasLock(x, y, z) && status == BLOCK_DESTROYED_STATUS) { server.chests.releaseLock(x, y, z); } write(packetId); write(status); write(x); write(y); write(z); write(face); if (player.instantDestroyEnabled()) { for (int c = 1; c < DESTROY_HITS; ++c) { packetFinished(); write(packetId); write(status); write(x); write(y); write(z); write(face); } packetFinished(); write(packetId); write(BLOCK_DESTROYED_STATUS); write(x); write(y); write(z); write(face); } } } } else { write(packetId); copyNBytes(11); } break; case 0x0f: // Player Block Placement write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readByte()); short dropItem = in.readShort(); write(dropItem); if (dropItem != -1) { write(in.readByte()); write(in.readByte()); } break; /* short blockId = in.readShort(); if (!isServerTunnel && (player.getGroupId() < 0) || !server.blockFirewall.playerAllowed(player, blockId)) { int x = in.readInt(); skipNBytes(6); if (x != -1) { server.runCommand("say", String.format(server.l.get("BAD_BLOCK"), player.getName(), Short.toString(blockId))); } } else if (!isServerTunnel && (blockId == 54) && player.isAttemptLock()) { int x = in.readInt(); byte y = in.readByte(); int z = in.readInt(); byte direction = in.readByte(); write(packetId); write(blockId); write(x); write(y); write(z); write(direction); switch (direction) { case 0: y--; break; case 1: y++; break; case 2: z--; break; case 3: z++; break; case 4: x--; break; case 5: x++; break; } // create chest entry if (server.chests.hasLock(x, y, z)) { player.addMessage("This block is locked already!"); } else if (server.chests.giveLock(player.getName(), x, y, z, false)) { player.addMessage("Your locked chest is created! Do not add another chest to it!"); } else { player.addMessage("You already have a lock, or this block is locked already!"); } player.setAttemptLock(false); } else { write(packetId); write(blockId); copyNBytes(10); } break; */ case 0x10: // Holding Change write(packetId); copyNBytes(2); break; case 0x12: // Animation write(packetId); copyNBytes(5); break; case 0x14: // Named Entity Spawn write(packetId); write(in.readInt()); write(in.readUTF()); copyNBytes(16); break; case 0x15: // Pickup spawn if (player.getGroupId() < 0) { skipNBytes(22); break; } write(packetId); copyNBytes(22); break; case 0x16: // Collect Item write(packetId); copyNBytes(8); break; case 0x17: // Add Object/Vehicle write(packetId); copyNBytes(17); break; case 0x18: // Mob Spawn write(packetId); copyNBytes(19); break; case 0x1c: // Entity Velocity? write(packetId); copyNBytes(10); break; case 0x1D: // Destroy Entity write(packetId); copyNBytes(4); break; case 0x1E: // Entity write(packetId); copyNBytes(4); break; case 0x1F: // Entity Relative Move write(packetId); copyNBytes(7); break; case 0x20: // Entity Look write(packetId); copyNBytes(6); break; case 0x21: // Entity Look and Relative Move write(packetId); copyNBytes(9); break; case 0x22: // Entity Teleport write(packetId); copyNBytes(18); break; case 0x26: // Entity status? write(packetId); copyNBytes(5); break; case 0x27: // Attach Entity? write(packetId); copyNBytes(8); break; case 0x32: // Pre-Chunk write(packetId); copyNBytes(9); break; case 0x33: // Map Chunk write(packetId); copyNBytes(13); int chunkSize = in.readInt(); write(chunkSize); copyNBytes(chunkSize); break; case 0x34: // Multi Block Change write(packetId); copyNBytes(8); short arraySize = in.readShort(); write(arraySize); copyNBytes(arraySize * 4); break; case 0x35: // Block Change write(packetId); copyNBytes(11); break; /* case 0x3b: // Complex Entities int x = in.readInt(); short y = in.readShort(); int z = in.readInt(); short payloadSize = in.readShort(); if (server.chests.hasLock(x, (byte) y, z) && !player.isAdmin() && !server.chests.ownsLock(player.getName(), x, (byte) y, z)) { skipNBytes(payloadSize); } else if (player.getGroupId() < 0 && !server.options.getBoolean("guestsCanViewComplex")) { skipNBytes(payloadSize); } else { write(packetId); write(x); write(y); write(z); write(payloadSize); copyNBytes(payloadSize); } break; */ case 0x3c: // Explosion write(packetId); copyNBytes(28); int recordCount = in.readInt(); write(recordCount); copyNBytes(recordCount * 3); break; case 0x64: write(packetId); write(in.readByte()); write(in.readByte()); - write(in.readInt()); + write(in.readUTF()); write(in.readByte()); break; case 0x65: write(packetId); write(in.readByte()); break; case 0x66: // Inventory Item Move write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); write(in.readShort()); short moveItem = in.readShort(); write(moveItem); if (moveItem != -1) { write(in.readByte()); write(in.readByte()); } break; case 0x67: // Inventory Item Update write(packetId); write(in.readByte()); write(in.readShort()); short setItem = in.readShort(); write(setItem); if (setItem != -1) { write(in.readByte()); write(in.readByte()); } break; case 0x68: // Inventory write(packetId); write(in.readByte()); short count = in.readShort(); write(count); for (int c = 0; c < count; ++c) { short item = in.readShort(); write(item); if (item != -1) { write(in.readByte()); write(in.readShort()); } } break; case 0x69: write(packetId); write(in.readByte()); write(in.readShort()); write(in.readShort()); break; case 0x6a: write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); break; case (byte) 0x82: // Update Sign write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(in.readUTF()); write(in.readUTF()); write(in.readUTF()); write(in.readUTF()); break; case (byte) 0xff: // Disconnect/Kick write(packetId); String reason = in.readUTF(); write(reason); if (reason.startsWith("Took too long")) { server.addRobot(player); } player.close(); break; default: if (EXPENSIVE_DEBUG_LOGGING) { while (true) { skipNBytes(1); flushAll(); } } else { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName()); } } packetFinished(); } private void copyPlayerLocation() throws IOException { if (!isServerTunnel) { motionCounter++; } if (!isServerTunnel && motionCounter % 8 == 0) { double x = in.readDouble(); double y = in.readDouble(); double stance = in.readDouble(); double z = in.readDouble(); player.updateLocation(x, y, z, stance); write(x); write(y); write(stance); write(z); copyNBytes(1); } else { copyNBytes(33); } } private void write(byte b) throws IOException { out.writeByte(b); } private void write(short s) throws IOException { out.writeShort(s); } private void write(int i) throws IOException { out.writeInt(i); } private void write(long l) throws IOException { out.writeLong(l); } @SuppressWarnings("unused") private void write(float f) throws IOException { out.writeFloat(f); } private void write(double d) throws IOException { out.writeDouble(d); } private void write(String s) throws IOException { out.writeUTF(s); } @SuppressWarnings("unused") private void write(boolean b) throws IOException { out.writeBoolean(b); } private void skipNBytes(int bytes) throws IOException { int overflow = bytes / buffer.length; for (int c = 0; c < overflow; ++c) { in.readFully(buffer, 0, buffer.length); } in.readFully(buffer, 0, bytes % buffer.length); } private void copyNBytes(int bytes) throws IOException { int overflow = bytes / buffer.length; for (int c = 0; c < overflow; ++c) { in.readFully(buffer, 0, buffer.length); out.write(buffer, 0, buffer.length); } in.readFully(buffer, 0, bytes % buffer.length); out.write(buffer, 0, bytes % buffer.length); } private void kick(String reason) throws IOException { write((byte) 0xff); write(reason); packetFinished(); } private void sendMessage(String message) throws IOException { write(0x03); write(message); packetFinished(); } private void packetFinished() throws IOException { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.packetFinished(); outputDumper.packetFinished(); } } private void flushAll() throws IOException { try { ((OutputStream) out).flush(); } finally { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.flush(); } } } private final class Tunneler extends Thread { @Override public void run() { try { while (run) { lastRead = System.currentTimeMillis(); try { handlePacket(); if (isServerTunnel) { while (player.hasMessages()) { sendMessage(player.getMessage()); } } flushAll(); } catch (IOException e) { if (run) { e.printStackTrace(); System.out.println(streamType + " error handling traffic for " + player.getName()); } break; } } try { if (player.isKicked()) { kick(player.getKickMsg()); } flushAll(); } catch (IOException e) { } } finally { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.cleanup(); outputDumper.cleanup(); } } } } }
true
true
private void handlePacket() throws IOException { Byte packetId = in.readByte(); switch (packetId) { case 0x00: // Keep Alive write(packetId); break; case 0x01: // Login Request/Response write(packetId); write(in.readInt()); write(in.readUTF()); write(in.readUTF()); write(in.readLong()); write(in.readByte()); break; case 0x02: // Handshake String name = in.readUTF(); if (isServerTunnel || player.setName(name)) { tunneler.setName(streamType + "-" + player.getName()); write(packetId); write(name); } break; case 0x03: // Chat Message String message = in.readUTF(); if (isServerTunnel && server.options.getBoolean("useMsgFormats")) { Matcher messageMatcher = MESSAGE_PATTERN.matcher(message); if (messageMatcher.find()) { Player friend = server.findPlayerExact(messageMatcher.group(1)); if (friend != null) { String color = "f"; String title = ""; String format = server.options.get("msgFormat"); Group group = friend.getGroup(); if (group != null) { color = group.getColor(); if (group.showTitle()) { title = group.getName(); format = server.options.get("msgTitleFormat"); } } try { message = String.format(format, friend.getName(), title, color) + messageMatcher.group(2); } catch (IllegalFormatException e) { System.out.println("[SimpleServer] There is an error in your msgFormat/msgTitleFormat settings!"); } } } } if (!isServerTunnel) { if (player.isMuted() && !message.startsWith("/") && !message.startsWith("!")) { player.addMessage("You are muted! You may not send messages to all players."); break; } if (server.options.getBoolean("useSlashes") && message.startsWith("/") || message.startsWith("!") && player.parseCommand(message)) { break; } } write(packetId); write(message); break; case 0x04: // Time Update write(packetId); copyNBytes(8); break; case 0x05: // Player Inventory write(packetId); write(in.readInt()); write(in.readShort()); write(in.readShort()); break; /* boolean guest = player.getGroupId() < 0; int inventoryType = in.readInt(); short itemCount = in.readShort(); if (!guest) { write(packetId); write(inventoryType); write(itemCount); } for (int c = 0; c < itemCount; ++c) { short itemId = in.readShort(); if (!guest) { write(itemId); } if (itemId != -1) { byte itemAmount = in.readByte(); short itemUses = in.readShort(); if (!guest) { write(itemAmount); write(itemUses); } if (!server.itemWatch.playerAllowed(player, itemId, itemAmount)) { server.adminLog("ItemWatchList banned player:\t" + player.getName()); server.banKick(player.getName()); } } } break; */ case 0x06: // Spawn Position write(packetId); copyNBytes(12); break; case 0x07: // Use Entity? write(packetId); copyNBytes(9); break; case 0x08: // Update Health write(packetId); copyNBytes(2); break; case 0x09: // Respawn write(packetId); break; case 0x0a: // Player write(packetId); copyNBytes(1); if (!inGame && !isServerTunnel) { player.sendMOTD(); inGame = true; } break; case 0x0b: // Player Position write(packetId); copyPlayerLocation(); break; case 0x0c: // Player Look write(packetId); copyNBytes(9); break; case 0x0d: // Player Position & Look write(packetId); copyPlayerLocation(); copyNBytes(8); break; case 0x0e: // Player Digging if (!isServerTunnel) { if (player.getGroupId() < 0) { skipNBytes(11); } else { byte status = in.readByte(); int x = in.readInt(); byte y = in.readByte(); int z = in.readInt(); byte face = in.readByte(); if (!server.chests.hasLock(x, y, z) || player.isAdmin()) { if (server.chests.hasLock(x, y, z) && status == BLOCK_DESTROYED_STATUS) { server.chests.releaseLock(x, y, z); } write(packetId); write(status); write(x); write(y); write(z); write(face); if (player.instantDestroyEnabled()) { for (int c = 1; c < DESTROY_HITS; ++c) { packetFinished(); write(packetId); write(status); write(x); write(y); write(z); write(face); } packetFinished(); write(packetId); write(BLOCK_DESTROYED_STATUS); write(x); write(y); write(z); write(face); } } } } else { write(packetId); copyNBytes(11); } break; case 0x0f: // Player Block Placement write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readByte()); short dropItem = in.readShort(); write(dropItem); if (dropItem != -1) { write(in.readByte()); write(in.readByte()); } break; /* short blockId = in.readShort(); if (!isServerTunnel && (player.getGroupId() < 0) || !server.blockFirewall.playerAllowed(player, blockId)) { int x = in.readInt(); skipNBytes(6); if (x != -1) { server.runCommand("say", String.format(server.l.get("BAD_BLOCK"), player.getName(), Short.toString(blockId))); } } else if (!isServerTunnel && (blockId == 54) && player.isAttemptLock()) { int x = in.readInt(); byte y = in.readByte(); int z = in.readInt(); byte direction = in.readByte(); write(packetId); write(blockId); write(x); write(y); write(z); write(direction); switch (direction) { case 0: y--; break; case 1: y++; break; case 2: z--; break; case 3: z++; break; case 4: x--; break; case 5: x++; break; } // create chest entry if (server.chests.hasLock(x, y, z)) { player.addMessage("This block is locked already!"); } else if (server.chests.giveLock(player.getName(), x, y, z, false)) { player.addMessage("Your locked chest is created! Do not add another chest to it!"); } else { player.addMessage("You already have a lock, or this block is locked already!"); } player.setAttemptLock(false); } else { write(packetId); write(blockId); copyNBytes(10); } break; */ case 0x10: // Holding Change write(packetId); copyNBytes(2); break; case 0x12: // Animation write(packetId); copyNBytes(5); break; case 0x14: // Named Entity Spawn write(packetId); write(in.readInt()); write(in.readUTF()); copyNBytes(16); break; case 0x15: // Pickup spawn if (player.getGroupId() < 0) { skipNBytes(22); break; } write(packetId); copyNBytes(22); break; case 0x16: // Collect Item write(packetId); copyNBytes(8); break; case 0x17: // Add Object/Vehicle write(packetId); copyNBytes(17); break; case 0x18: // Mob Spawn write(packetId); copyNBytes(19); break; case 0x1c: // Entity Velocity? write(packetId); copyNBytes(10); break; case 0x1D: // Destroy Entity write(packetId); copyNBytes(4); break; case 0x1E: // Entity write(packetId); copyNBytes(4); break; case 0x1F: // Entity Relative Move write(packetId); copyNBytes(7); break; case 0x20: // Entity Look write(packetId); copyNBytes(6); break; case 0x21: // Entity Look and Relative Move write(packetId); copyNBytes(9); break; case 0x22: // Entity Teleport write(packetId); copyNBytes(18); break; case 0x26: // Entity status? write(packetId); copyNBytes(5); break; case 0x27: // Attach Entity? write(packetId); copyNBytes(8); break; case 0x32: // Pre-Chunk write(packetId); copyNBytes(9); break; case 0x33: // Map Chunk write(packetId); copyNBytes(13); int chunkSize = in.readInt(); write(chunkSize); copyNBytes(chunkSize); break; case 0x34: // Multi Block Change write(packetId); copyNBytes(8); short arraySize = in.readShort(); write(arraySize); copyNBytes(arraySize * 4); break; case 0x35: // Block Change write(packetId); copyNBytes(11); break; /* case 0x3b: // Complex Entities int x = in.readInt(); short y = in.readShort(); int z = in.readInt(); short payloadSize = in.readShort(); if (server.chests.hasLock(x, (byte) y, z) && !player.isAdmin() && !server.chests.ownsLock(player.getName(), x, (byte) y, z)) { skipNBytes(payloadSize); } else if (player.getGroupId() < 0 && !server.options.getBoolean("guestsCanViewComplex")) { skipNBytes(payloadSize); } else { write(packetId); write(x); write(y); write(z); write(payloadSize); copyNBytes(payloadSize); } break; */ case 0x3c: // Explosion write(packetId); copyNBytes(28); int recordCount = in.readInt(); write(recordCount); copyNBytes(recordCount * 3); break; case 0x64: write(packetId); write(in.readByte()); write(in.readByte()); write(in.readInt()); write(in.readByte()); break; case 0x65: write(packetId); write(in.readByte()); break; case 0x66: // Inventory Item Move write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); write(in.readShort()); short moveItem = in.readShort(); write(moveItem); if (moveItem != -1) { write(in.readByte()); write(in.readByte()); } break; case 0x67: // Inventory Item Update write(packetId); write(in.readByte()); write(in.readShort()); short setItem = in.readShort(); write(setItem); if (setItem != -1) { write(in.readByte()); write(in.readByte()); } break; case 0x68: // Inventory write(packetId); write(in.readByte()); short count = in.readShort(); write(count); for (int c = 0; c < count; ++c) { short item = in.readShort(); write(item); if (item != -1) { write(in.readByte()); write(in.readShort()); } } break; case 0x69: write(packetId); write(in.readByte()); write(in.readShort()); write(in.readShort()); break; case 0x6a: write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); break; case (byte) 0x82: // Update Sign write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(in.readUTF()); write(in.readUTF()); write(in.readUTF()); write(in.readUTF()); break; case (byte) 0xff: // Disconnect/Kick write(packetId); String reason = in.readUTF(); write(reason); if (reason.startsWith("Took too long")) { server.addRobot(player); } player.close(); break; default: if (EXPENSIVE_DEBUG_LOGGING) { while (true) { skipNBytes(1); flushAll(); } } else { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName()); } } packetFinished(); }
private void handlePacket() throws IOException { Byte packetId = in.readByte(); switch (packetId) { case 0x00: // Keep Alive write(packetId); break; case 0x01: // Login Request/Response write(packetId); write(in.readInt()); write(in.readUTF()); write(in.readUTF()); write(in.readLong()); write(in.readByte()); break; case 0x02: // Handshake String name = in.readUTF(); if (isServerTunnel || player.setName(name)) { tunneler.setName(streamType + "-" + player.getName()); write(packetId); write(name); } break; case 0x03: // Chat Message String message = in.readUTF(); if (isServerTunnel && server.options.getBoolean("useMsgFormats")) { Matcher messageMatcher = MESSAGE_PATTERN.matcher(message); if (messageMatcher.find()) { Player friend = server.findPlayerExact(messageMatcher.group(1)); if (friend != null) { String color = "f"; String title = ""; String format = server.options.get("msgFormat"); Group group = friend.getGroup(); if (group != null) { color = group.getColor(); if (group.showTitle()) { title = group.getName(); format = server.options.get("msgTitleFormat"); } } try { message = String.format(format, friend.getName(), title, color) + messageMatcher.group(2); } catch (IllegalFormatException e) { System.out.println("[SimpleServer] There is an error in your msgFormat/msgTitleFormat settings!"); } } } } if (!isServerTunnel) { if (player.isMuted() && !message.startsWith("/") && !message.startsWith("!")) { player.addMessage("You are muted! You may not send messages to all players."); break; } if (server.options.getBoolean("useSlashes") && message.startsWith("/") || message.startsWith("!") && player.parseCommand(message)) { break; } } write(packetId); write(message); break; case 0x04: // Time Update write(packetId); copyNBytes(8); break; case 0x05: // Player Inventory write(packetId); write(in.readInt()); write(in.readShort()); write(in.readShort()); break; /* boolean guest = player.getGroupId() < 0; int inventoryType = in.readInt(); short itemCount = in.readShort(); if (!guest) { write(packetId); write(inventoryType); write(itemCount); } for (int c = 0; c < itemCount; ++c) { short itemId = in.readShort(); if (!guest) { write(itemId); } if (itemId != -1) { byte itemAmount = in.readByte(); short itemUses = in.readShort(); if (!guest) { write(itemAmount); write(itemUses); } if (!server.itemWatch.playerAllowed(player, itemId, itemAmount)) { server.adminLog("ItemWatchList banned player:\t" + player.getName()); server.banKick(player.getName()); } } } break; */ case 0x06: // Spawn Position write(packetId); copyNBytes(12); break; case 0x07: // Use Entity? write(packetId); copyNBytes(9); break; case 0x08: // Update Health write(packetId); copyNBytes(2); break; case 0x09: // Respawn write(packetId); break; case 0x0a: // Player write(packetId); copyNBytes(1); if (!inGame && !isServerTunnel) { player.sendMOTD(); inGame = true; } break; case 0x0b: // Player Position write(packetId); copyPlayerLocation(); break; case 0x0c: // Player Look write(packetId); copyNBytes(9); break; case 0x0d: // Player Position & Look write(packetId); copyPlayerLocation(); copyNBytes(8); break; case 0x0e: // Player Digging if (!isServerTunnel) { if (player.getGroupId() < 0) { skipNBytes(11); } else { byte status = in.readByte(); int x = in.readInt(); byte y = in.readByte(); int z = in.readInt(); byte face = in.readByte(); if (!server.chests.hasLock(x, y, z) || player.isAdmin()) { if (server.chests.hasLock(x, y, z) && status == BLOCK_DESTROYED_STATUS) { server.chests.releaseLock(x, y, z); } write(packetId); write(status); write(x); write(y); write(z); write(face); if (player.instantDestroyEnabled()) { for (int c = 1; c < DESTROY_HITS; ++c) { packetFinished(); write(packetId); write(status); write(x); write(y); write(z); write(face); } packetFinished(); write(packetId); write(BLOCK_DESTROYED_STATUS); write(x); write(y); write(z); write(face); } } } } else { write(packetId); copyNBytes(11); } break; case 0x0f: // Player Block Placement write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readByte()); short dropItem = in.readShort(); write(dropItem); if (dropItem != -1) { write(in.readByte()); write(in.readByte()); } break; /* short blockId = in.readShort(); if (!isServerTunnel && (player.getGroupId() < 0) || !server.blockFirewall.playerAllowed(player, blockId)) { int x = in.readInt(); skipNBytes(6); if (x != -1) { server.runCommand("say", String.format(server.l.get("BAD_BLOCK"), player.getName(), Short.toString(blockId))); } } else if (!isServerTunnel && (blockId == 54) && player.isAttemptLock()) { int x = in.readInt(); byte y = in.readByte(); int z = in.readInt(); byte direction = in.readByte(); write(packetId); write(blockId); write(x); write(y); write(z); write(direction); switch (direction) { case 0: y--; break; case 1: y++; break; case 2: z--; break; case 3: z++; break; case 4: x--; break; case 5: x++; break; } // create chest entry if (server.chests.hasLock(x, y, z)) { player.addMessage("This block is locked already!"); } else if (server.chests.giveLock(player.getName(), x, y, z, false)) { player.addMessage("Your locked chest is created! Do not add another chest to it!"); } else { player.addMessage("You already have a lock, or this block is locked already!"); } player.setAttemptLock(false); } else { write(packetId); write(blockId); copyNBytes(10); } break; */ case 0x10: // Holding Change write(packetId); copyNBytes(2); break; case 0x12: // Animation write(packetId); copyNBytes(5); break; case 0x14: // Named Entity Spawn write(packetId); write(in.readInt()); write(in.readUTF()); copyNBytes(16); break; case 0x15: // Pickup spawn if (player.getGroupId() < 0) { skipNBytes(22); break; } write(packetId); copyNBytes(22); break; case 0x16: // Collect Item write(packetId); copyNBytes(8); break; case 0x17: // Add Object/Vehicle write(packetId); copyNBytes(17); break; case 0x18: // Mob Spawn write(packetId); copyNBytes(19); break; case 0x1c: // Entity Velocity? write(packetId); copyNBytes(10); break; case 0x1D: // Destroy Entity write(packetId); copyNBytes(4); break; case 0x1E: // Entity write(packetId); copyNBytes(4); break; case 0x1F: // Entity Relative Move write(packetId); copyNBytes(7); break; case 0x20: // Entity Look write(packetId); copyNBytes(6); break; case 0x21: // Entity Look and Relative Move write(packetId); copyNBytes(9); break; case 0x22: // Entity Teleport write(packetId); copyNBytes(18); break; case 0x26: // Entity status? write(packetId); copyNBytes(5); break; case 0x27: // Attach Entity? write(packetId); copyNBytes(8); break; case 0x32: // Pre-Chunk write(packetId); copyNBytes(9); break; case 0x33: // Map Chunk write(packetId); copyNBytes(13); int chunkSize = in.readInt(); write(chunkSize); copyNBytes(chunkSize); break; case 0x34: // Multi Block Change write(packetId); copyNBytes(8); short arraySize = in.readShort(); write(arraySize); copyNBytes(arraySize * 4); break; case 0x35: // Block Change write(packetId); copyNBytes(11); break; /* case 0x3b: // Complex Entities int x = in.readInt(); short y = in.readShort(); int z = in.readInt(); short payloadSize = in.readShort(); if (server.chests.hasLock(x, (byte) y, z) && !player.isAdmin() && !server.chests.ownsLock(player.getName(), x, (byte) y, z)) { skipNBytes(payloadSize); } else if (player.getGroupId() < 0 && !server.options.getBoolean("guestsCanViewComplex")) { skipNBytes(payloadSize); } else { write(packetId); write(x); write(y); write(z); write(payloadSize); copyNBytes(payloadSize); } break; */ case 0x3c: // Explosion write(packetId); copyNBytes(28); int recordCount = in.readInt(); write(recordCount); copyNBytes(recordCount * 3); break; case 0x64: write(packetId); write(in.readByte()); write(in.readByte()); write(in.readUTF()); write(in.readByte()); break; case 0x65: write(packetId); write(in.readByte()); break; case 0x66: // Inventory Item Move write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); write(in.readShort()); short moveItem = in.readShort(); write(moveItem); if (moveItem != -1) { write(in.readByte()); write(in.readByte()); } break; case 0x67: // Inventory Item Update write(packetId); write(in.readByte()); write(in.readShort()); short setItem = in.readShort(); write(setItem); if (setItem != -1) { write(in.readByte()); write(in.readByte()); } break; case 0x68: // Inventory write(packetId); write(in.readByte()); short count = in.readShort(); write(count); for (int c = 0; c < count; ++c) { short item = in.readShort(); write(item); if (item != -1) { write(in.readByte()); write(in.readShort()); } } break; case 0x69: write(packetId); write(in.readByte()); write(in.readShort()); write(in.readShort()); break; case 0x6a: write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); break; case (byte) 0x82: // Update Sign write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(in.readUTF()); write(in.readUTF()); write(in.readUTF()); write(in.readUTF()); break; case (byte) 0xff: // Disconnect/Kick write(packetId); String reason = in.readUTF(); write(reason); if (reason.startsWith("Took too long")) { server.addRobot(player); } player.close(); break; default: if (EXPENSIVE_DEBUG_LOGGING) { while (true) { skipNBytes(1); flushAll(); } } else { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName()); } } packetFinished(); }
diff --git a/SewTiffs.java b/SewTiffs.java index 6370d7e..9bb4d44 100644 --- a/SewTiffs.java +++ b/SewTiffs.java @@ -1,86 +1,86 @@ // // SewTiffs.java // import java.awt.image.BufferedImage; import java.io.File; import java.util.Hashtable; import loci.formats.FilePattern; import loci.formats.RandomAccessStream; import loci.formats.TiffTools; import loci.formats.in.TiffReader; import loci.formats.out.TiffWriter; /** Stitches the first plane from a collection of TIFFs into a single file. */ public class SewTiffs { private static final int DOTS = 50; public static void main(String[] args) throws Exception { if (args.length < 2) { System.out.println( "Usage: java SewTiffs base_name channel_num [time_count]"); System.exit(1); } String base = args[0]; int c = Integer.parseInt(args[1]); int num; if (args.length < 3) { FilePattern fp = new FilePattern(new File(base + "_C" + c + "_TP1.tiff")); int[] count = fp.getCount(); num = count[count.length - 1]; } else num = Integer.parseInt(args[2]); System.out.println("Fixing " + base + "_C" + c + "_TP<1-" + num + ">.tiff"); TiffReader in = new TiffReader(); TiffWriter out = new TiffWriter(); String outId = base + "_C" + c + ".tiff"; System.out.println("Writing " + outId); System.out.print(" "); boolean comment = false; for (int t=0; t<num; t++) { String inId = base + "_C" + c + "_TP" + (t + 1) + ".tiff"; // read first image plane BufferedImage image = in.openImage(inId, 0); in.close(); if (t == 0) { // read first IFD RandomAccessStream ras = new RandomAccessStream(inId); - Hashtable ifd = TiffTools.getFirstIFD(ras, 0); + Hashtable ifd = TiffTools.getFirstIFD(ras); ras.close(); // preserve TIFF comment Object descObj = TiffTools.getIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION); String desc = null; if (descObj instanceof String) desc = (String) descObj; else if (descObj instanceof String[]) desc = ((String[]) descObj)[0]; if (desc != null) { ifd = new Hashtable(); TiffTools.putIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION, desc); comment = true; out.saveImage(outId, image, ifd, t == num - 1); System.out.print("."); continue; } } // write image plane out.save(outId, image, t == num - 1); // update status System.out.print("."); if (t % DOTS == DOTS - 1) { System.out.println(" " + (t + 1)); System.out.print(" "); } } System.out.println(); if (comment) System.out.println("OME-TIFF comment saved."); else System.out.println("No OME-TIFF comment found."); } }
true
true
public static void main(String[] args) throws Exception { if (args.length < 2) { System.out.println( "Usage: java SewTiffs base_name channel_num [time_count]"); System.exit(1); } String base = args[0]; int c = Integer.parseInt(args[1]); int num; if (args.length < 3) { FilePattern fp = new FilePattern(new File(base + "_C" + c + "_TP1.tiff")); int[] count = fp.getCount(); num = count[count.length - 1]; } else num = Integer.parseInt(args[2]); System.out.println("Fixing " + base + "_C" + c + "_TP<1-" + num + ">.tiff"); TiffReader in = new TiffReader(); TiffWriter out = new TiffWriter(); String outId = base + "_C" + c + ".tiff"; System.out.println("Writing " + outId); System.out.print(" "); boolean comment = false; for (int t=0; t<num; t++) { String inId = base + "_C" + c + "_TP" + (t + 1) + ".tiff"; // read first image plane BufferedImage image = in.openImage(inId, 0); in.close(); if (t == 0) { // read first IFD RandomAccessStream ras = new RandomAccessStream(inId); Hashtable ifd = TiffTools.getFirstIFD(ras, 0); ras.close(); // preserve TIFF comment Object descObj = TiffTools.getIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION); String desc = null; if (descObj instanceof String) desc = (String) descObj; else if (descObj instanceof String[]) desc = ((String[]) descObj)[0]; if (desc != null) { ifd = new Hashtable(); TiffTools.putIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION, desc); comment = true; out.saveImage(outId, image, ifd, t == num - 1); System.out.print("."); continue; } } // write image plane out.save(outId, image, t == num - 1); // update status System.out.print("."); if (t % DOTS == DOTS - 1) { System.out.println(" " + (t + 1)); System.out.print(" "); } } System.out.println(); if (comment) System.out.println("OME-TIFF comment saved."); else System.out.println("No OME-TIFF comment found."); }
public static void main(String[] args) throws Exception { if (args.length < 2) { System.out.println( "Usage: java SewTiffs base_name channel_num [time_count]"); System.exit(1); } String base = args[0]; int c = Integer.parseInt(args[1]); int num; if (args.length < 3) { FilePattern fp = new FilePattern(new File(base + "_C" + c + "_TP1.tiff")); int[] count = fp.getCount(); num = count[count.length - 1]; } else num = Integer.parseInt(args[2]); System.out.println("Fixing " + base + "_C" + c + "_TP<1-" + num + ">.tiff"); TiffReader in = new TiffReader(); TiffWriter out = new TiffWriter(); String outId = base + "_C" + c + ".tiff"; System.out.println("Writing " + outId); System.out.print(" "); boolean comment = false; for (int t=0; t<num; t++) { String inId = base + "_C" + c + "_TP" + (t + 1) + ".tiff"; // read first image plane BufferedImage image = in.openImage(inId, 0); in.close(); if (t == 0) { // read first IFD RandomAccessStream ras = new RandomAccessStream(inId); Hashtable ifd = TiffTools.getFirstIFD(ras); ras.close(); // preserve TIFF comment Object descObj = TiffTools.getIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION); String desc = null; if (descObj instanceof String) desc = (String) descObj; else if (descObj instanceof String[]) desc = ((String[]) descObj)[0]; if (desc != null) { ifd = new Hashtable(); TiffTools.putIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION, desc); comment = true; out.saveImage(outId, image, ifd, t == num - 1); System.out.print("."); continue; } } // write image plane out.save(outId, image, t == num - 1); // update status System.out.print("."); if (t % DOTS == DOTS - 1) { System.out.println(" " + (t + 1)); System.out.print(" "); } } System.out.println(); if (comment) System.out.println("OME-TIFF comment saved."); else System.out.println("No OME-TIFF comment found."); }
diff --git a/src/com/android/phone/InCallTouchUi.java b/src/com/android/phone/InCallTouchUi.java index 0359b226..20630576 100644 --- a/src/com/android/phone/InCallTouchUi.java +++ b/src/com/android/phone/InCallTouchUi.java @@ -1,650 +1,651 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.phone; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.SystemClock; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.TextView; import android.widget.ToggleButton; import com.android.internal.telephony.Call; import com.android.internal.telephony.Phone; import com.android.internal.widget.SlidingTab; /** * In-call onscreen touch UI elements, used on some platforms. * * This widget is a fullscreen overlay, drawn on top of the * non-touch-sensitive parts of the in-call UI (i.e. the call card). */ public class InCallTouchUi extends FrameLayout implements View.OnClickListener, SlidingTab.OnTriggerListener { private static final int IN_CALL_WIDGET_TRANSITION_TIME = 250; // in ms private static final String LOG_TAG = "InCallTouchUi"; private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 2); /** * Reference to the InCallScreen activity that owns us. This may be * null if we haven't been initialized yet *or* after the InCallScreen * activity has been destroyed. */ private InCallScreen mInCallScreen; // Phone app instance private PhoneApp mApplication; // UI containers / elements private SlidingTab mIncomingCallWidget; // UI used for an incoming call private View mInCallControls; // UI elements while on a regular call // private Button mAddButton; private Button mMergeButton; private Button mEndButton; private Button mDialpadButton; private ToggleButton mBluetoothButton; private ToggleButton mMuteButton; private ToggleButton mSpeakerButton; // private View mHoldButtonContainer; private ImageButton mHoldButton; private TextView mHoldButtonLabel; private View mSwapButtonContainer; private ImageButton mSwapButton; private TextView mSwapButtonLabel; private View mCdmaMergeButtonContainer; private ImageButton mCdmaMergeButton; // private Drawable mHoldIcon; private Drawable mUnholdIcon; private Drawable mShowDialpadIcon; private Drawable mHideDialpadIcon; // Time of the most recent "answer" or "reject" action (see updateState()) private long mLastIncomingCallActionTime; // in SystemClock.uptimeMillis() time base // Overall enabledness of the "touch UI" features private boolean mAllowIncomingCallTouchUi; private boolean mAllowInCallTouchUi; public InCallTouchUi(Context context, AttributeSet attrs) { super(context, attrs); if (DBG) log("InCallTouchUi constructor..."); if (DBG) log("- this = " + this); if (DBG) log("- context " + context + ", attrs " + attrs); // Inflate our contents, and add it (to ourself) as a child. LayoutInflater inflater = LayoutInflater.from(context); inflater.inflate( R.layout.incall_touch_ui, // resource this, // root true); mApplication = PhoneApp.getInstance(); // The various touch UI features are enabled on a per-product // basis. (These flags in config.xml may be overridden by // product-specific overlay files.) mAllowIncomingCallTouchUi = getResources().getBoolean(R.bool.allow_incoming_call_touch_ui); if (DBG) log("- incoming call touch UI: " + (mAllowIncomingCallTouchUi ? "ENABLED" : "DISABLED")); mAllowInCallTouchUi = getResources().getBoolean(R.bool.allow_in_call_touch_ui); if (DBG) log("- regular in-call touch UI: " + (mAllowInCallTouchUi ? "ENABLED" : "DISABLED")); } void setInCallScreenInstance(InCallScreen inCallScreen) { mInCallScreen = inCallScreen; } @Override protected void onFinishInflate() { super.onFinishInflate(); if (DBG) log("InCallTouchUi onFinishInflate(this = " + this + ")..."); // Look up the various UI elements. // "Dial-to-answer" widget for incoming calls. mIncomingCallWidget = (SlidingTab) findViewById(R.id.incomingCallWidget); mIncomingCallWidget.setLeftTabResources( R.drawable.ic_jog_dial_answer, com.android.internal.R.drawable.jog_tab_target_green, com.android.internal.R.drawable.jog_tab_bar_left_answer, com.android.internal.R.drawable.jog_tab_left_answer ); mIncomingCallWidget.setRightTabResources( R.drawable.ic_jog_dial_decline, com.android.internal.R.drawable.jog_tab_target_red, com.android.internal.R.drawable.jog_tab_bar_right_decline, com.android.internal.R.drawable.jog_tab_right_decline ); // For now, we only need to show two states: answer and decline. mIncomingCallWidget.setLeftHintText(R.string.slide_to_answer_hint); mIncomingCallWidget.setRightHintText(R.string.slide_to_decline_hint); mIncomingCallWidget.setOnTriggerListener(this); // Container for the UI elements shown while on a regular call. mInCallControls = findViewById(R.id.inCallControls); // Regular (single-tap) buttons, where we listen for click events: // Main cluster of buttons: mAddButton = (Button) mInCallControls.findViewById(R.id.addButton); mAddButton.setOnClickListener(this); mMergeButton = (Button) mInCallControls.findViewById(R.id.mergeButton); mMergeButton.setOnClickListener(this); mEndButton = (Button) mInCallControls.findViewById(R.id.endButton); mEndButton.setOnClickListener(this); mDialpadButton = (Button) mInCallControls.findViewById(R.id.dialpadButton); mDialpadButton.setOnClickListener(this); mBluetoothButton = (ToggleButton) mInCallControls.findViewById(R.id.bluetoothButton); mBluetoothButton.setOnClickListener(this); mMuteButton = (ToggleButton) mInCallControls.findViewById(R.id.muteButton); mMuteButton.setOnClickListener(this); mSpeakerButton = (ToggleButton) mInCallControls.findViewById(R.id.speakerButton); mSpeakerButton.setOnClickListener(this); // Upper corner buttons: mHoldButtonContainer = mInCallControls.findViewById(R.id.holdButtonContainer); mHoldButton = (ImageButton) mInCallControls.findViewById(R.id.holdButton); mHoldButton.setOnClickListener(this); mHoldButtonLabel = (TextView) mInCallControls.findViewById(R.id.holdButtonLabel); // mSwapButtonContainer = mInCallControls.findViewById(R.id.swapButtonContainer); mSwapButton = (ImageButton) mInCallControls.findViewById(R.id.swapButton); mSwapButton.setOnClickListener(this); mSwapButtonLabel = (TextView) mInCallControls.findViewById(R.id.swapButtonLabel); if (PhoneApp.getInstance().phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { // In CDMA we use a generalized text - "Manage call", as behavior on selecting // this option depends entirely on what the current call state is. mSwapButtonLabel.setText(R.string.onscreenManageCallsText); } else { mSwapButtonLabel.setText(R.string.onscreenSwapCallsText); } // mCdmaMergeButtonContainer = mInCallControls.findViewById(R.id.cdmaMergeButtonContainer); mCdmaMergeButton = (ImageButton) mInCallControls.findViewById(R.id.cdmaMergeButton); mCdmaMergeButton.setOnClickListener(this); // Icons we need to change dynamically. (Most other icons are specified // directly in incall_touch_ui.xml.) mHoldIcon = getResources().getDrawable(R.drawable.ic_in_call_touch_round_hold); mUnholdIcon = getResources().getDrawable(R.drawable.ic_in_call_touch_round_unhold); mShowDialpadIcon = getResources().getDrawable(R.drawable.ic_in_call_touch_dialpad); mHideDialpadIcon = getResources().getDrawable(R.drawable.ic_in_call_touch_dialpad_close); } /** * Updates the visibility and/or state of our UI elements, based on * the current state of the phone. */ void updateState(Phone phone) { if (DBG) log("updateState(" + phone + ")..."); if (mInCallScreen == null) { log("- updateState: mInCallScreen has been destroyed; bailing out..."); return; } Phone.State state = phone.getState(); // IDLE, RINGING, or OFFHOOK if (DBG) log("- updateState: phone state is " + state); boolean showIncomingCallControls = false; boolean showInCallControls = false; if (state == Phone.State.RINGING) { // A phone call is ringing *or* call waiting. if (mAllowIncomingCallTouchUi) { // Watch out: even if the phone state is RINGING, it's // possible for the ringing call to be in the DISCONNECTING // state. (This typically happens immediately after the user // rejects an incoming call, and in that case we *don't* show // the incoming call controls.) final Call ringingCall = phone.getRingingCall(); if (ringingCall.getState().isAlive()) { if (DBG) log("- updateState: RINGING! Showing incoming call controls..."); showIncomingCallControls = true; } // Ugly hack to cover up slow response from the radio: // if we attempted to answer or reject an incoming call // within the last 500 msec, *don't* show the incoming call // UI even if the phone is still in the RINGING state. long now = SystemClock.uptimeMillis(); if (now < mLastIncomingCallActionTime + 500) { log("updateState: Too soon after last action; not drawing!"); showIncomingCallControls = false; } // TODO: UI design issue: if the device is NOT currently // locked, we probably don't need to make the user // double-tap the "incoming call" buttons. (The device // presumably isn't in a pocket or purse, so we don't need // to worry about false touches while it's ringing.) // But OTOH having "inconsistent" buttons might just make // it *more* confusing. } } else { if (mAllowInCallTouchUi) { // Ok, the in-call touch UI is available on this platform, // so make it visible (with some exceptions): if (mInCallScreen.okToShowInCallTouchUi()) { showInCallControls = true; } else { if (DBG) log("- updateState: NOT OK to show touch UI; disabling..."); } } } if (showInCallControls) { updateInCallControls(phone); } if (showIncomingCallControls && showInCallControls) { throw new IllegalStateException( "'Incoming' and 'in-call' touch controls visible at the same time!"); } if (showIncomingCallControls) { showIncomingCallWidget(); } else { hideIncomingCallWidget(); } mInCallControls.setVisibility(showInCallControls ? View.VISIBLE : View.GONE); // TODO: As an optimization, also consider setting the visibility // of the overall InCallTouchUi widget to GONE if *nothing at all* // is visible right now. } // View.OnClickListener implementation public void onClick(View view) { int id = view.getId(); if (DBG) log("onClick(View " + view + ", id " + id + ")..."); switch (id) { case R.id.addButton: case R.id.mergeButton: case R.id.endButton: case R.id.dialpadButton: case R.id.bluetoothButton: case R.id.muteButton: case R.id.speakerButton: case R.id.holdButton: case R.id.swapButton: case R.id.cdmaMergeButton: // Clicks on the regular onscreen buttons get forwarded // straight to the InCallScreen. mInCallScreen.handleOnscreenButtonClick(id); break; default: Log.w(LOG_TAG, "onClick: unexpected click: View " + view + ", id " + id); break; } } /** * Updates the enabledness and "checked" state of the buttons on the * "inCallControls" panel, based on the current telephony state. */ void updateInCallControls(Phone phone) { int phoneType = phone.getPhoneType(); // Note we do NOT need to worry here about cases where the entire // in-call touch UI is disabled, like during an OTA call or if the // dtmf dialpad is up. (That's handled by updateState(), which // calls InCallScreen.okToShowInCallTouchUi().) // // If we get here, it *is* OK to show the in-call touch UI, so we // now need to update the enabledness and/or "checked" state of // each individual button. // // The InCallControlState object tells us the enabledness and/or // state of the various onscreen buttons: InCallControlState inCallControlState = mInCallScreen.getUpdatedInCallControlState(); // "Add" or "Merge": // These two buttons occupy the same space onscreen, so only // one of them should be available at a given moment. if (inCallControlState.canAddCall) { mAddButton.setVisibility(View.VISIBLE); mAddButton.setEnabled(true); mMergeButton.setVisibility(View.GONE); } else if (inCallControlState.canMerge) { if (phoneType == Phone.PHONE_TYPE_CDMA) { // In CDMA "Add" option is always given to the user and the // "Merge" option is provided as a button on the top left corner of the screen, // we always set the mMergeButton to GONE mMergeButton.setVisibility(View.GONE); } else if (phoneType == Phone.PHONE_TYPE_GSM) { mMergeButton.setVisibility(View.VISIBLE); mMergeButton.setEnabled(true); mAddButton.setVisibility(View.GONE); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } else { // Neither "Add" nor "Merge" is available. (This happens in // some transient states, like while dialing an outgoing call, // and in other rare cases like if you have both lines in use // *and* there are already 5 people on the conference call.) // Since the common case here is "while dialing", we show the // "Add" button in a disabled state so that there won't be any // jarring change in the UI when the call finally connects. mAddButton.setVisibility(View.VISIBLE); mAddButton.setEnabled(false); mMergeButton.setVisibility(View.GONE); } if (inCallControlState.canAddCall && inCallControlState.canMerge) { if (phoneType == Phone.PHONE_TYPE_GSM) { // Uh oh, the InCallControlState thinks that "Add" *and* "Merge" // should both be available right now. This *should* never // happen with GSM, but if it's possible on any // future devices we may need to re-layout Add and Merge so // they can both be visible at the same time... Log.w(LOG_TAG, "updateInCallControls: Add *and* Merge enabled," + " but can't show both!"); } else if (phoneType == Phone.PHONE_TYPE_CDMA) { // In CDMA "Add" option is always given to the user and the hence // in this case both "Add" and "Merge" options would be available to user if (DBG) log("updateInCallControls: CDMA: Add and Merge both enabled"); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } // "End call": this button has no state and it's always enabled. mEndButton.setEnabled(true); // "Dialpad": Enabled only when it's OK to use the dialpad in the // first place. mDialpadButton.setEnabled(inCallControlState.dialpadEnabled); // if (inCallControlState.dialpadVisible) { // Show the "hide dialpad" state. mDialpadButton.setText(R.string.onscreenHideDialpadText); mDialpadButton.setCompoundDrawablesWithIntrinsicBounds( null, mHideDialpadIcon, null, null); } else { // Show the "show dialpad" state. mDialpadButton.setText(R.string.onscreenShowDialpadText); mDialpadButton.setCompoundDrawablesWithIntrinsicBounds( null, mShowDialpadIcon, null, null); } // "Bluetooth" mBluetoothButton.setEnabled(inCallControlState.bluetoothEnabled); mBluetoothButton.setChecked(inCallControlState.bluetoothIndicatorOn); // "Mute" mMuteButton.setEnabled(inCallControlState.canMute); mMuteButton.setChecked(inCallControlState.muteIndicatorOn); // "Speaker" mSpeakerButton.setEnabled(inCallControlState.speakerEnabled); mSpeakerButton.setChecked(inCallControlState.speakerOn); // "Hold" // (Note "Hold" and "Swap" are never both available at // the same time. That's why it's OK for them to both be in the // same position onscreen.) // This button is totally hidden (rather than just disabled) // when the operation isn't available. mHoldButtonContainer.setVisibility( inCallControlState.canHold ? View.VISIBLE : View.GONE); if (inCallControlState.canHold) { // The Hold button icon and label (either "Hold" or "Unhold") // depend on the current Hold state. if (inCallControlState.onHold) { mHoldButton.setImageDrawable(mUnholdIcon); mHoldButtonLabel.setText(R.string.onscreenUnholdText); } else { mHoldButton.setImageDrawable(mHoldIcon); mHoldButtonLabel.setText(R.string.onscreenHoldText); } } // "Swap" // This button is totally hidden (rather than just disabled) // when the operation isn't available. mSwapButtonContainer.setVisibility( inCallControlState.canSwap ? View.VISIBLE : View.GONE); if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { // "Merge" // This button is totally hidden (rather than just disabled) // when the operation isn't available. mCdmaMergeButtonContainer.setVisibility( inCallControlState.canMerge ? View.VISIBLE : View.GONE); } if (inCallControlState.canSwap && inCallControlState.canHold) { // Uh oh, the InCallControlState thinks that Swap *and* Hold // should both be available. This *should* never happen with // either GSM or CDMA, but if it's possible on any future // devices we may need to re-layout Hold and Swap so they can // both be visible at the same time... Log.w(LOG_TAG, "updateInCallControls: Hold *and* Swap enabled, but can't show both!"); } if (phoneType == Phone.PHONE_TYPE_CDMA) { if (inCallControlState.canSwap && inCallControlState.canMerge) { // Uh oh, the InCallControlState thinks that Swap *and* Merge // should both be available. This *should* never happen with // CDMA, but if it's possible on any future // devices we may need to re-layout Merge and Swap so they can // both be visible at the same time... Log.w(LOG_TAG, "updateInCallControls: Merge *and* Swap" + "enabled, but can't show both!"); } } // One final special case: if the dialpad is visible, that trumps // *any* of the upper corner buttons: if (inCallControlState.dialpadVisible) { mHoldButtonContainer.setVisibility(View.GONE); mSwapButtonContainer.setVisibility(View.GONE); + mCdmaMergeButtonContainer.setVisibility(View.GONE); } } // // InCallScreen API // /** * @return true if the onscreen touch UI is enabled (for regular * "ongoing call" states) on the current device. */ /* package */ boolean isTouchUiEnabled() { return mAllowInCallTouchUi; } // // SlidingTab.OnTriggerListener implementation // /** * Handles "Answer" and "Reject" actions for an incoming call. * We get this callback from the SlidingTab * when the user triggers an action. * * To answer or reject the incoming call, we call * InCallScreen.handleOnscreenButtonClick() and pass one of the * special "virtual button" IDs: * - R.id.answerButton to answer the call * or * - R.id.rejectButton to reject the call. */ public void onTrigger(View v, int whichHandle) { log("onDialTrigger(whichHandle = " + whichHandle + ")..."); switch (whichHandle) { case SlidingTab.OnTriggerListener.LEFT_HANDLE: if (DBG) log("LEFT_HANDLE: answer!"); hideIncomingCallWidget(); // ...and also prevent it from reappearing right away. // (This covers up a slow response from the radio; see updateState().) mLastIncomingCallActionTime = SystemClock.uptimeMillis(); // Do the appropriate action. if (mInCallScreen != null) { // Send this to the InCallScreen as a virtual "button click" event: mInCallScreen.handleOnscreenButtonClick(R.id.answerButton); } else { Log.e(LOG_TAG, "answer trigger: mInCallScreen is null"); } break; case SlidingTab.OnTriggerListener.RIGHT_HANDLE: if (DBG) log("RIGHT_HANDLE: reject!"); hideIncomingCallWidget(); // ...and also prevent it from reappearing right away. // (This covers up a slow response from the radio; see updateState().) mLastIncomingCallActionTime = SystemClock.uptimeMillis(); // Do the appropriate action. if (mInCallScreen != null) { // Send this to the InCallScreen as a virtual "button click" event: mInCallScreen.handleOnscreenButtonClick(R.id.rejectButton); } else { Log.e(LOG_TAG, "reject trigger: mInCallScreen is null"); } break; default: Log.e(LOG_TAG, "onDialTrigger: unexpected whichHandle value: " + whichHandle); break; } // Regardless of what action the user did, be sure to clear out // the hint text we were displaying while the user was dragging. mInCallScreen.updateSlidingTabHint(0, 0); } /** * Apply an animation to hide the incoming call widget. */ private void hideIncomingCallWidget() { if (mIncomingCallWidget.getVisibility() != View.VISIBLE || mIncomingCallWidget.getAnimation() != null) { // Widget is already hidden or in the process of being hidden return; } // Hide the incoming call screen with a transition AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f); anim.setDuration(IN_CALL_WIDGET_TRANSITION_TIME); anim.setAnimationListener(new AnimationListener() { public void onAnimationStart(Animation animation) { } public void onAnimationRepeat(Animation animation) { } public void onAnimationEnd(Animation animation) { // hide the incoming call UI. mIncomingCallWidget.clearAnimation(); mIncomingCallWidget.setVisibility(View.GONE); } }); mIncomingCallWidget.startAnimation(anim); } /** * Shows the incoming call widget and cancels any animation that may be fading it out. */ private void showIncomingCallWidget() { Animation anim = mIncomingCallWidget.getAnimation(); if (anim != null) { anim.reset(); mIncomingCallWidget.clearAnimation(); } mIncomingCallWidget.setVisibility(View.VISIBLE); } /** * Handles state changes of the SlidingTabSelector widget. While the user * is dragging one of the handles, we display an onscreen hint; see * CallCard.getRotateWidgetHint(). */ public void onGrabbedStateChange(View v, int grabbedState) { if (mInCallScreen != null) { // Look up the hint based on which handle is currently grabbed. // (Note we don't simply pass grabbedState thru to the InCallScreen, // since *this* class is the only place that knows that the left // handle means "Answer" and the right handle means "Decline".) int hintTextResId, hintColorResId; switch (grabbedState) { case SlidingTab.OnTriggerListener.NO_HANDLE: hintTextResId = 0; hintColorResId = 0; break; case SlidingTab.OnTriggerListener.LEFT_HANDLE: // TODO: Use different variants of "Slide to answer" in some cases // depending on the phone state, like slide_to_answer_and_hold // for a call waiting call, or slide_to_answer_and_end_active or // slide_to_answer_and_end_onhold for the 2-lines-in-use case. // (Note these are GSM-only cases, though.) hintTextResId = R.string.slide_to_answer; hintColorResId = R.color.incall_textConnected; // green break; case SlidingTab.OnTriggerListener.RIGHT_HANDLE: hintTextResId = R.string.slide_to_decline; hintColorResId = R.color.incall_textEnded; // red break; default: Log.e(LOG_TAG, "onGrabbedStateChange: unexpected grabbedState: " + grabbedState); hintTextResId = 0; hintColorResId = 0; break; } // Tell the InCallScreen to update the CallCard and force the // screen to redraw. mInCallScreen.updateSlidingTabHint(hintTextResId, hintColorResId); } } // Debugging / testing code private void log(String msg) { Log.d(LOG_TAG, msg); } }
true
true
void updateInCallControls(Phone phone) { int phoneType = phone.getPhoneType(); // Note we do NOT need to worry here about cases where the entire // in-call touch UI is disabled, like during an OTA call or if the // dtmf dialpad is up. (That's handled by updateState(), which // calls InCallScreen.okToShowInCallTouchUi().) // // If we get here, it *is* OK to show the in-call touch UI, so we // now need to update the enabledness and/or "checked" state of // each individual button. // // The InCallControlState object tells us the enabledness and/or // state of the various onscreen buttons: InCallControlState inCallControlState = mInCallScreen.getUpdatedInCallControlState(); // "Add" or "Merge": // These two buttons occupy the same space onscreen, so only // one of them should be available at a given moment. if (inCallControlState.canAddCall) { mAddButton.setVisibility(View.VISIBLE); mAddButton.setEnabled(true); mMergeButton.setVisibility(View.GONE); } else if (inCallControlState.canMerge) { if (phoneType == Phone.PHONE_TYPE_CDMA) { // In CDMA "Add" option is always given to the user and the // "Merge" option is provided as a button on the top left corner of the screen, // we always set the mMergeButton to GONE mMergeButton.setVisibility(View.GONE); } else if (phoneType == Phone.PHONE_TYPE_GSM) { mMergeButton.setVisibility(View.VISIBLE); mMergeButton.setEnabled(true); mAddButton.setVisibility(View.GONE); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } else { // Neither "Add" nor "Merge" is available. (This happens in // some transient states, like while dialing an outgoing call, // and in other rare cases like if you have both lines in use // *and* there are already 5 people on the conference call.) // Since the common case here is "while dialing", we show the // "Add" button in a disabled state so that there won't be any // jarring change in the UI when the call finally connects. mAddButton.setVisibility(View.VISIBLE); mAddButton.setEnabled(false); mMergeButton.setVisibility(View.GONE); } if (inCallControlState.canAddCall && inCallControlState.canMerge) { if (phoneType == Phone.PHONE_TYPE_GSM) { // Uh oh, the InCallControlState thinks that "Add" *and* "Merge" // should both be available right now. This *should* never // happen with GSM, but if it's possible on any // future devices we may need to re-layout Add and Merge so // they can both be visible at the same time... Log.w(LOG_TAG, "updateInCallControls: Add *and* Merge enabled," + " but can't show both!"); } else if (phoneType == Phone.PHONE_TYPE_CDMA) { // In CDMA "Add" option is always given to the user and the hence // in this case both "Add" and "Merge" options would be available to user if (DBG) log("updateInCallControls: CDMA: Add and Merge both enabled"); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } // "End call": this button has no state and it's always enabled. mEndButton.setEnabled(true); // "Dialpad": Enabled only when it's OK to use the dialpad in the // first place. mDialpadButton.setEnabled(inCallControlState.dialpadEnabled); // if (inCallControlState.dialpadVisible) { // Show the "hide dialpad" state. mDialpadButton.setText(R.string.onscreenHideDialpadText); mDialpadButton.setCompoundDrawablesWithIntrinsicBounds( null, mHideDialpadIcon, null, null); } else { // Show the "show dialpad" state. mDialpadButton.setText(R.string.onscreenShowDialpadText); mDialpadButton.setCompoundDrawablesWithIntrinsicBounds( null, mShowDialpadIcon, null, null); } // "Bluetooth" mBluetoothButton.setEnabled(inCallControlState.bluetoothEnabled); mBluetoothButton.setChecked(inCallControlState.bluetoothIndicatorOn); // "Mute" mMuteButton.setEnabled(inCallControlState.canMute); mMuteButton.setChecked(inCallControlState.muteIndicatorOn); // "Speaker" mSpeakerButton.setEnabled(inCallControlState.speakerEnabled); mSpeakerButton.setChecked(inCallControlState.speakerOn); // "Hold" // (Note "Hold" and "Swap" are never both available at // the same time. That's why it's OK for them to both be in the // same position onscreen.) // This button is totally hidden (rather than just disabled) // when the operation isn't available. mHoldButtonContainer.setVisibility( inCallControlState.canHold ? View.VISIBLE : View.GONE); if (inCallControlState.canHold) { // The Hold button icon and label (either "Hold" or "Unhold") // depend on the current Hold state. if (inCallControlState.onHold) { mHoldButton.setImageDrawable(mUnholdIcon); mHoldButtonLabel.setText(R.string.onscreenUnholdText); } else { mHoldButton.setImageDrawable(mHoldIcon); mHoldButtonLabel.setText(R.string.onscreenHoldText); } } // "Swap" // This button is totally hidden (rather than just disabled) // when the operation isn't available. mSwapButtonContainer.setVisibility( inCallControlState.canSwap ? View.VISIBLE : View.GONE); if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { // "Merge" // This button is totally hidden (rather than just disabled) // when the operation isn't available. mCdmaMergeButtonContainer.setVisibility( inCallControlState.canMerge ? View.VISIBLE : View.GONE); } if (inCallControlState.canSwap && inCallControlState.canHold) { // Uh oh, the InCallControlState thinks that Swap *and* Hold // should both be available. This *should* never happen with // either GSM or CDMA, but if it's possible on any future // devices we may need to re-layout Hold and Swap so they can // both be visible at the same time... Log.w(LOG_TAG, "updateInCallControls: Hold *and* Swap enabled, but can't show both!"); } if (phoneType == Phone.PHONE_TYPE_CDMA) { if (inCallControlState.canSwap && inCallControlState.canMerge) { // Uh oh, the InCallControlState thinks that Swap *and* Merge // should both be available. This *should* never happen with // CDMA, but if it's possible on any future // devices we may need to re-layout Merge and Swap so they can // both be visible at the same time... Log.w(LOG_TAG, "updateInCallControls: Merge *and* Swap" + "enabled, but can't show both!"); } } // One final special case: if the dialpad is visible, that trumps // *any* of the upper corner buttons: if (inCallControlState.dialpadVisible) { mHoldButtonContainer.setVisibility(View.GONE); mSwapButtonContainer.setVisibility(View.GONE); } }
void updateInCallControls(Phone phone) { int phoneType = phone.getPhoneType(); // Note we do NOT need to worry here about cases where the entire // in-call touch UI is disabled, like during an OTA call or if the // dtmf dialpad is up. (That's handled by updateState(), which // calls InCallScreen.okToShowInCallTouchUi().) // // If we get here, it *is* OK to show the in-call touch UI, so we // now need to update the enabledness and/or "checked" state of // each individual button. // // The InCallControlState object tells us the enabledness and/or // state of the various onscreen buttons: InCallControlState inCallControlState = mInCallScreen.getUpdatedInCallControlState(); // "Add" or "Merge": // These two buttons occupy the same space onscreen, so only // one of them should be available at a given moment. if (inCallControlState.canAddCall) { mAddButton.setVisibility(View.VISIBLE); mAddButton.setEnabled(true); mMergeButton.setVisibility(View.GONE); } else if (inCallControlState.canMerge) { if (phoneType == Phone.PHONE_TYPE_CDMA) { // In CDMA "Add" option is always given to the user and the // "Merge" option is provided as a button on the top left corner of the screen, // we always set the mMergeButton to GONE mMergeButton.setVisibility(View.GONE); } else if (phoneType == Phone.PHONE_TYPE_GSM) { mMergeButton.setVisibility(View.VISIBLE); mMergeButton.setEnabled(true); mAddButton.setVisibility(View.GONE); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } else { // Neither "Add" nor "Merge" is available. (This happens in // some transient states, like while dialing an outgoing call, // and in other rare cases like if you have both lines in use // *and* there are already 5 people on the conference call.) // Since the common case here is "while dialing", we show the // "Add" button in a disabled state so that there won't be any // jarring change in the UI when the call finally connects. mAddButton.setVisibility(View.VISIBLE); mAddButton.setEnabled(false); mMergeButton.setVisibility(View.GONE); } if (inCallControlState.canAddCall && inCallControlState.canMerge) { if (phoneType == Phone.PHONE_TYPE_GSM) { // Uh oh, the InCallControlState thinks that "Add" *and* "Merge" // should both be available right now. This *should* never // happen with GSM, but if it's possible on any // future devices we may need to re-layout Add and Merge so // they can both be visible at the same time... Log.w(LOG_TAG, "updateInCallControls: Add *and* Merge enabled," + " but can't show both!"); } else if (phoneType == Phone.PHONE_TYPE_CDMA) { // In CDMA "Add" option is always given to the user and the hence // in this case both "Add" and "Merge" options would be available to user if (DBG) log("updateInCallControls: CDMA: Add and Merge both enabled"); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } // "End call": this button has no state and it's always enabled. mEndButton.setEnabled(true); // "Dialpad": Enabled only when it's OK to use the dialpad in the // first place. mDialpadButton.setEnabled(inCallControlState.dialpadEnabled); // if (inCallControlState.dialpadVisible) { // Show the "hide dialpad" state. mDialpadButton.setText(R.string.onscreenHideDialpadText); mDialpadButton.setCompoundDrawablesWithIntrinsicBounds( null, mHideDialpadIcon, null, null); } else { // Show the "show dialpad" state. mDialpadButton.setText(R.string.onscreenShowDialpadText); mDialpadButton.setCompoundDrawablesWithIntrinsicBounds( null, mShowDialpadIcon, null, null); } // "Bluetooth" mBluetoothButton.setEnabled(inCallControlState.bluetoothEnabled); mBluetoothButton.setChecked(inCallControlState.bluetoothIndicatorOn); // "Mute" mMuteButton.setEnabled(inCallControlState.canMute); mMuteButton.setChecked(inCallControlState.muteIndicatorOn); // "Speaker" mSpeakerButton.setEnabled(inCallControlState.speakerEnabled); mSpeakerButton.setChecked(inCallControlState.speakerOn); // "Hold" // (Note "Hold" and "Swap" are never both available at // the same time. That's why it's OK for them to both be in the // same position onscreen.) // This button is totally hidden (rather than just disabled) // when the operation isn't available. mHoldButtonContainer.setVisibility( inCallControlState.canHold ? View.VISIBLE : View.GONE); if (inCallControlState.canHold) { // The Hold button icon and label (either "Hold" or "Unhold") // depend on the current Hold state. if (inCallControlState.onHold) { mHoldButton.setImageDrawable(mUnholdIcon); mHoldButtonLabel.setText(R.string.onscreenUnholdText); } else { mHoldButton.setImageDrawable(mHoldIcon); mHoldButtonLabel.setText(R.string.onscreenHoldText); } } // "Swap" // This button is totally hidden (rather than just disabled) // when the operation isn't available. mSwapButtonContainer.setVisibility( inCallControlState.canSwap ? View.VISIBLE : View.GONE); if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { // "Merge" // This button is totally hidden (rather than just disabled) // when the operation isn't available. mCdmaMergeButtonContainer.setVisibility( inCallControlState.canMerge ? View.VISIBLE : View.GONE); } if (inCallControlState.canSwap && inCallControlState.canHold) { // Uh oh, the InCallControlState thinks that Swap *and* Hold // should both be available. This *should* never happen with // either GSM or CDMA, but if it's possible on any future // devices we may need to re-layout Hold and Swap so they can // both be visible at the same time... Log.w(LOG_TAG, "updateInCallControls: Hold *and* Swap enabled, but can't show both!"); } if (phoneType == Phone.PHONE_TYPE_CDMA) { if (inCallControlState.canSwap && inCallControlState.canMerge) { // Uh oh, the InCallControlState thinks that Swap *and* Merge // should both be available. This *should* never happen with // CDMA, but if it's possible on any future // devices we may need to re-layout Merge and Swap so they can // both be visible at the same time... Log.w(LOG_TAG, "updateInCallControls: Merge *and* Swap" + "enabled, but can't show both!"); } } // One final special case: if the dialpad is visible, that trumps // *any* of the upper corner buttons: if (inCallControlState.dialpadVisible) { mHoldButtonContainer.setVisibility(View.GONE); mSwapButtonContainer.setVisibility(View.GONE); mCdmaMergeButtonContainer.setVisibility(View.GONE); } }
diff --git a/src/org/openstreetmap/josm/gui/preferences/PluginPreference.java b/src/org/openstreetmap/josm/gui/preferences/PluginPreference.java index d4f5af86..b71f3d87 100644 --- a/src/org/openstreetmap/josm/gui/preferences/PluginPreference.java +++ b/src/org/openstreetmap/josm/gui/preferences/PluginPreference.java @@ -1,394 +1,393 @@ //License: GPL. Copyright 2007 by Immanuel Scholz and others package org.openstreetmap.josm.gui.preferences; import static org.openstreetmap.josm.tools.I18n.tr; import static org.openstreetmap.josm.tools.I18n.trn; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.Map.Entry; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.plugins.PluginDownloader; import org.openstreetmap.josm.plugins.PluginException; import org.openstreetmap.josm.plugins.PluginInformation; import org.openstreetmap.josm.plugins.PluginProxy; import org.openstreetmap.josm.tools.GBC; import org.openstreetmap.josm.tools.XmlObjectParser.Uniform; public class PluginPreference implements PreferenceSetting { /** * Only the plugin name, its jar location and the description. * In other words, this is the minimal requirement the plugin preference page * needs to show the plugin as available * * @author imi */ public static class PluginDescription implements Comparable<Object> { // Note: All the following need to be public instance variables of // type String. (Plugin description XMLs from the server are parsed // with tools.XmlObjectParser, which uses reflection to access them.) public String name; public String description; public String resource; public String version; public PluginDescription(String name, String description, String resource, String version) { this.name = name; this.description = description; this.resource = resource; this.version = version; } public PluginDescription() { } public int compareTo(Object n) { if(n instanceof PluginDescription) return name.compareToIgnoreCase(((PluginDescription)n).name); return -1; } } private Map<PluginDescription, Boolean> pluginMap; private JPanel plugin; private class MyBox extends Box { int lastwidth; int offset = 40; public MyBox() { super(BoxLayout.Y_AXIS); } public int myGetWidth() { int w = plugin.getWidth()-offset; if(w <= 0) w = 450; lastwidth = w; return w; } public void paint(Graphics g) { if(lastwidth != plugin.getWidth()-offset) refreshPluginPanel(gui); super.paint(g); } } private MyBox pluginPanel = new MyBox(); private PreferenceDialog gui; public void addGui(final PreferenceDialog gui) { this.gui = gui; plugin = gui.createPreferenceTab("plugin", tr("Plugins"), tr("Configure available plugins."), false); JScrollPane pluginPane = new JScrollPane(pluginPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); pluginPane.setBorder(null); plugin.add(pluginPane, GBC.eol().fill(GBC.BOTH)); plugin.add(GBC.glue(0,10), GBC.eol()); JButton morePlugins = new JButton(tr("Download List")); morePlugins.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { int count = PluginDownloader.downloadDescription(); if (count > 0) JOptionPane.showMessageDialog(Main.parent, trn("Downloaded plugin information from {0} site", "Downloaded plugin information from {0} sites", count, count)); else JOptionPane.showMessageDialog(Main.parent, tr("No plugin information found.")); refreshPluginPanel(gui); } }); plugin.add(morePlugins, GBC.std().insets(0,0,10,0)); JButton update = new JButton(tr("Update")); update.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { update(); refreshPluginPanel(gui); } }); plugin.add(update, GBC.std().insets(0,0,10,0)); JButton configureSites = new JButton(tr("Configure Sites ...")); configureSites.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { configureSites(); } }); plugin.add(configureSites, GBC.std()); refreshPluginPanel(gui); } private void configureSites() { JPanel p = new JPanel(new GridBagLayout()); p.add(new JLabel(tr("Add either site-josm.xml or Wiki Pages.")), GBC.eol()); final DefaultListModel model = new DefaultListModel(); for (String s : PluginDownloader.getSites()) model.addElement(s); final JList list = new JList(model); p.add(new JScrollPane(list), GBC.std().fill()); JPanel buttons = new JPanel(new GridBagLayout()); buttons.add(new JButton(new AbstractAction(tr("Add")){ public void actionPerformed(ActionEvent e) { String s = JOptionPane.showInputDialog(gui, tr("Add either site-josm.xml or Wiki Pages.")); if (s != null) model.addElement(s); } }), GBC.eol().fill(GBC.HORIZONTAL)); buttons.add(new JButton(new AbstractAction(tr("Edit")){ public void actionPerformed(ActionEvent e) { if (list.getSelectedValue() == null) { JOptionPane.showMessageDialog(gui, tr("Please select an entry.")); return; } String s = JOptionPane.showInputDialog(gui, tr("Add either site-josm.xml or Wiki Pages."), list.getSelectedValue()); model.setElementAt(s, list.getSelectedIndex()); } }), GBC.eol().fill(GBC.HORIZONTAL)); buttons.add(new JButton(new AbstractAction(tr("Delete")){ public void actionPerformed(ActionEvent event) { if (list.getSelectedValue() == null) { JOptionPane.showMessageDialog(gui, tr("Please select an entry.")); return; } model.removeElement(list.getSelectedValue()); } }), GBC.eol().fill(GBC.HORIZONTAL)); p.add(buttons, GBC.eol()); int answer = JOptionPane.showConfirmDialog(gui, p, tr("Configure Plugin Sites"), JOptionPane.OK_CANCEL_OPTION); if (answer != JOptionPane.OK_OPTION) return; StringBuilder b = new StringBuilder(); for (int i = 0; i < model.getSize(); ++i) { b.append(model.getElementAt(i)); if (i < model.getSize()-1) b.append(" "); } Main.pref.put("pluginmanager.sites", b.toString()); } private void update() { // refresh description int num = PluginDownloader.downloadDescription(); Boolean done = false; refreshPluginPanel(gui); Set<PluginDescription> toUpdate = new HashSet<PluginDescription>(); StringBuilder toUpdateStr = new StringBuilder(); for (PluginProxy proxy : Main.plugins) { PluginDescription description = findDescription(proxy.info.name); if (description != null && (description.version == null || description.version.equals("")) ? (proxy.info.version != null && proxy.info.version.equals("")) : !description.version.equals(proxy.info.version)) { toUpdate.add(description); toUpdateStr.append(description.name+"\n"); } } if (toUpdate.isEmpty()) { JOptionPane.showMessageDialog(Main.parent, tr("All installed plugins are up to date.")); done = true; } else { int answer = JOptionPane.showConfirmDialog(Main.parent, tr("Update the following plugins:\n\n{0}", toUpdateStr.toString()), tr("Update"), JOptionPane.OK_CANCEL_OPTION); if (answer == JOptionPane.OK_OPTION) { PluginDownloader.update(toUpdate); done = true; } } if(done && num >= 1) Main.pref.put("pluginmanager.lastupdate", Long.toString(System.currentTimeMillis())); } private PluginDescription findDescription(String name) { for (PluginDescription d : pluginMap.keySet()) if (d.name.equals(name)) return d; return null; } private void refreshPluginPanel(final PreferenceDialog gui) { Collection<PluginDescription> availablePlugins = getAvailablePlugins(); pluginMap = new HashMap<PluginDescription, Boolean>(); pluginPanel.removeAll(); int width = pluginPanel.myGetWidth(); - // the following could probably be done more elegantly? Collection<String> enabledPlugins = Main.pref.getCollection("plugins", null); for (final PluginDescription plugin : availablePlugins) { - boolean enabled = enabledPlugins.contains(plugin.name); + boolean enabled = enabledPlugins != null && enabledPlugins.contains(plugin.name); String remoteversion = plugin.version; if(remoteversion == null || remoteversion.equals("")) remoteversion = tr("unknown"); String localversion; PluginInformation p = PluginInformation.findPlugin(plugin.name); if(p != null) { if(p.version != null && !p.version.equals("")) localversion = p.version; else localversion = tr("unknown"); localversion = " (" + localversion + ")"; } else localversion = ""; final JCheckBox pluginCheck = new JCheckBox(tr("{0}: Version {1}{2}", plugin.name, remoteversion, localversion), enabled); pluginPanel.add(pluginCheck); pluginCheck.setToolTipText(plugin.resource != null ? ""+plugin.resource : tr("Plugin bundled with JOSM")); JLabel label = new JLabel("<html><i>"+(plugin.description==null?tr("no description available"):plugin.description)+"</i></html>"); label.setBorder(BorderFactory.createEmptyBorder(0,20,0,0)); label.setMaximumSize(new Dimension(width,1000)); pluginPanel.add(label); pluginPanel.add(Box.createVerticalStrut(5)); pluginMap.put(plugin, enabled); pluginCheck.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { // if user enabled a plugin, it is not loaded but found somewhere on disk: offer to delete jar if (pluginCheck.isSelected()) { PluginInformation plinfo = PluginInformation.findPlugin(plugin.name); if ((PluginInformation.getLoaded(plugin.name) == null) && (plinfo != null)) { try { int answer = JOptionPane.showConfirmDialog(Main.parent, tr("Plugin archive already available. Do you want to download current version by deleting existing archive?\n\n{0}", plinfo.file.getCanonicalPath()), tr("Plugin already exists"), JOptionPane.OK_CANCEL_OPTION); if (answer == JOptionPane.OK_OPTION) { if (!plinfo.file.delete()) { JOptionPane.showMessageDialog(Main.parent, tr("Error deleting plugin file: {0}", plinfo.file.getCanonicalPath())); } } } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(Main.parent, tr("Error deleting plugin file: {0}", e1.getMessage())); } } } pluginMap.put(plugin, pluginCheck.isSelected()); } }); } plugin.updateUI(); } private Collection<PluginDescription> getAvailablePlugins() { SortedMap<String, PluginDescription> availablePlugins = new TreeMap<String, PluginDescription>(new Comparator<String>(){ public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); for (String location : PluginInformation.getPluginLocations()) { File[] pluginFiles = new File(location).listFiles(); if (pluginFiles != null) { Arrays.sort(pluginFiles); for (File f : pluginFiles) { if (!f.isFile()) continue; if (f.getName().endsWith(".jar")) { try { PluginInformation info = new PluginInformation(f); if (!availablePlugins.containsKey(info.name)) availablePlugins.put(info.name, new PluginDescription( info.name, info.description, PluginInformation.fileToURL(f).toString(), info.version)); } catch (PluginException x) { } } else if (f.getName().matches("^[0-9]+-site.*\\.xml$")) { try { Uniform<PluginDescription> parser = new Uniform<PluginDescription>(new FileReader(f), "plugin", PluginDescription.class); for (PluginDescription pd : parser) if (!availablePlugins.containsKey(pd.name)) availablePlugins.put(pd.name, pd); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(Main.parent, tr("Error reading plugin information file: {0}", f.getName())); } } } } } for (PluginProxy proxy : Main.plugins) if (!availablePlugins.containsKey(proxy.info.name)) availablePlugins.put(proxy.info.name, new PluginDescription( proxy.info.name, proxy.info.description, proxy.info.file == null ? null : PluginInformation.fileToURL(proxy.info.file).toString(), proxy.info.version)); return availablePlugins.values(); } public void ok() { Collection<PluginDescription> toDownload = new LinkedList<PluginDescription>(); String msg = ""; for (Entry<PluginDescription, Boolean> entry : pluginMap.entrySet()) { if (entry.getValue() && PluginInformation.findPlugin(entry.getKey().name) == null) { toDownload.add(entry.getKey()); msg += entry.getKey().name+"\n"; } } if (!toDownload.isEmpty()) { int answer = JOptionPane.showConfirmDialog(Main.parent, tr("Download the following plugins?\n\n{0}", msg), tr("Download missing plugins"), JOptionPane.YES_NO_OPTION); if (answer != JOptionPane.OK_OPTION) for (PluginDescription pd : toDownload) pluginMap.put(pd, false); else for (PluginDescription pd : toDownload) if (!PluginDownloader.downloadPlugin(pd)) pluginMap.put(pd, false); } String oldPlugins = Main.pref.get("plugins"); LinkedList<String> plugins = new LinkedList<String>(); Object pd[] = pluginMap.keySet().toArray(); Arrays.sort(pd); for (Object d : pd) { if (pluginMap.get(d)) plugins.add(((PluginDescription)d).name); } Main.pref.putCollection("plugins", plugins); String newPlugins = Main.pref.get("plugins"); if(oldPlugins == null && plugins == null) return; if(plugins == null || oldPlugins == null || !plugins.equals(oldPlugins)) gui.requiresRestart = true; } }
false
true
private void refreshPluginPanel(final PreferenceDialog gui) { Collection<PluginDescription> availablePlugins = getAvailablePlugins(); pluginMap = new HashMap<PluginDescription, Boolean>(); pluginPanel.removeAll(); int width = pluginPanel.myGetWidth(); // the following could probably be done more elegantly? Collection<String> enabledPlugins = Main.pref.getCollection("plugins", null); for (final PluginDescription plugin : availablePlugins) { boolean enabled = enabledPlugins.contains(plugin.name); String remoteversion = plugin.version; if(remoteversion == null || remoteversion.equals("")) remoteversion = tr("unknown"); String localversion; PluginInformation p = PluginInformation.findPlugin(plugin.name); if(p != null) { if(p.version != null && !p.version.equals("")) localversion = p.version; else localversion = tr("unknown"); localversion = " (" + localversion + ")"; } else localversion = ""; final JCheckBox pluginCheck = new JCheckBox(tr("{0}: Version {1}{2}", plugin.name, remoteversion, localversion), enabled); pluginPanel.add(pluginCheck); pluginCheck.setToolTipText(plugin.resource != null ? ""+plugin.resource : tr("Plugin bundled with JOSM")); JLabel label = new JLabel("<html><i>"+(plugin.description==null?tr("no description available"):plugin.description)+"</i></html>"); label.setBorder(BorderFactory.createEmptyBorder(0,20,0,0)); label.setMaximumSize(new Dimension(width,1000)); pluginPanel.add(label); pluginPanel.add(Box.createVerticalStrut(5)); pluginMap.put(plugin, enabled); pluginCheck.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { // if user enabled a plugin, it is not loaded but found somewhere on disk: offer to delete jar if (pluginCheck.isSelected()) { PluginInformation plinfo = PluginInformation.findPlugin(plugin.name); if ((PluginInformation.getLoaded(plugin.name) == null) && (plinfo != null)) { try { int answer = JOptionPane.showConfirmDialog(Main.parent, tr("Plugin archive already available. Do you want to download current version by deleting existing archive?\n\n{0}", plinfo.file.getCanonicalPath()), tr("Plugin already exists"), JOptionPane.OK_CANCEL_OPTION); if (answer == JOptionPane.OK_OPTION) { if (!plinfo.file.delete()) { JOptionPane.showMessageDialog(Main.parent, tr("Error deleting plugin file: {0}", plinfo.file.getCanonicalPath())); } } } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(Main.parent, tr("Error deleting plugin file: {0}", e1.getMessage())); } } } pluginMap.put(plugin, pluginCheck.isSelected()); } }); } plugin.updateUI(); }
private void refreshPluginPanel(final PreferenceDialog gui) { Collection<PluginDescription> availablePlugins = getAvailablePlugins(); pluginMap = new HashMap<PluginDescription, Boolean>(); pluginPanel.removeAll(); int width = pluginPanel.myGetWidth(); Collection<String> enabledPlugins = Main.pref.getCollection("plugins", null); for (final PluginDescription plugin : availablePlugins) { boolean enabled = enabledPlugins != null && enabledPlugins.contains(plugin.name); String remoteversion = plugin.version; if(remoteversion == null || remoteversion.equals("")) remoteversion = tr("unknown"); String localversion; PluginInformation p = PluginInformation.findPlugin(plugin.name); if(p != null) { if(p.version != null && !p.version.equals("")) localversion = p.version; else localversion = tr("unknown"); localversion = " (" + localversion + ")"; } else localversion = ""; final JCheckBox pluginCheck = new JCheckBox(tr("{0}: Version {1}{2}", plugin.name, remoteversion, localversion), enabled); pluginPanel.add(pluginCheck); pluginCheck.setToolTipText(plugin.resource != null ? ""+plugin.resource : tr("Plugin bundled with JOSM")); JLabel label = new JLabel("<html><i>"+(plugin.description==null?tr("no description available"):plugin.description)+"</i></html>"); label.setBorder(BorderFactory.createEmptyBorder(0,20,0,0)); label.setMaximumSize(new Dimension(width,1000)); pluginPanel.add(label); pluginPanel.add(Box.createVerticalStrut(5)); pluginMap.put(plugin, enabled); pluginCheck.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { // if user enabled a plugin, it is not loaded but found somewhere on disk: offer to delete jar if (pluginCheck.isSelected()) { PluginInformation plinfo = PluginInformation.findPlugin(plugin.name); if ((PluginInformation.getLoaded(plugin.name) == null) && (plinfo != null)) { try { int answer = JOptionPane.showConfirmDialog(Main.parent, tr("Plugin archive already available. Do you want to download current version by deleting existing archive?\n\n{0}", plinfo.file.getCanonicalPath()), tr("Plugin already exists"), JOptionPane.OK_CANCEL_OPTION); if (answer == JOptionPane.OK_OPTION) { if (!plinfo.file.delete()) { JOptionPane.showMessageDialog(Main.parent, tr("Error deleting plugin file: {0}", plinfo.file.getCanonicalPath())); } } } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(Main.parent, tr("Error deleting plugin file: {0}", e1.getMessage())); } } } pluginMap.put(plugin, pluginCheck.isSelected()); } }); } plugin.updateUI(); }
diff --git a/jsf-ri/systest/src/com/sun/faces/jsptest/ViewTagTestCase.java b/jsf-ri/systest/src/com/sun/faces/jsptest/ViewTagTestCase.java index ee9878e24..6c7ed524f 100644 --- a/jsf-ri/systest/src/com/sun/faces/jsptest/ViewTagTestCase.java +++ b/jsf-ri/systest/src/com/sun/faces/jsptest/ViewTagTestCase.java @@ -1,126 +1,126 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package com.sun.faces.jsptest; import com.gargoylesoftware.htmlunit.html.*; import com.sun.faces.htmlunit.AbstractTestCase; import junit.framework.Test; import junit.framework.TestSuite; import javax.faces.component.NamingContainer; /** * <p>Test Case for JSP Interoperability.</p> */ public class ViewTagTestCase extends AbstractTestCase { // ------------------------------------------------------------ Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public ViewTagTestCase(String name) { super(name); } // ------------------------------------------------------ Instance Variables // ---------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ public void setUp() throws Exception { super.setUp(); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(ViewTagTestCase.class)); } /** * Tear down instance variables required by this test case. */ public void tearDown() { super.tearDown(); } // ------------------------------------------------- Individual Test Methods public void testLocaleOnViewTag() throws Exception { HtmlForm form; HtmlSubmitInput submit; HtmlAnchor link; HtmlTextInput input; HtmlPage page; page = getPage("/faces/viewLocale.jsp"); form = getFormById(page, "form"); submit = (HtmlSubmitInput) form.getInputByName("form" + NamingContainer.SEPARATOR_CHAR + "button"); // press the button page = (HtmlPage) submit.click(); - assertTrue(-1 != page.asText().indexOf("Erreur")); + assertTrue(-1 != page.asText().indexOf("erreur")); } public void testReplaceViewRoot() throws Exception { HtmlPage page; HtmlAnchor link; page = getPage("/faces/replaceViewRoot.jsp"); link = page.getAnchorByName("examine"); page = (HtmlPage) link.click(); assertTrue(-1 != page.asText().indexOf("Replaced ViewRoot is com.sun.faces.systest.model.ViewRootExtension")); } }
true
true
public void testLocaleOnViewTag() throws Exception { HtmlForm form; HtmlSubmitInput submit; HtmlAnchor link; HtmlTextInput input; HtmlPage page; page = getPage("/faces/viewLocale.jsp"); form = getFormById(page, "form"); submit = (HtmlSubmitInput) form.getInputByName("form" + NamingContainer.SEPARATOR_CHAR + "button"); // press the button page = (HtmlPage) submit.click(); assertTrue(-1 != page.asText().indexOf("Erreur")); }
public void testLocaleOnViewTag() throws Exception { HtmlForm form; HtmlSubmitInput submit; HtmlAnchor link; HtmlTextInput input; HtmlPage page; page = getPage("/faces/viewLocale.jsp"); form = getFormById(page, "form"); submit = (HtmlSubmitInput) form.getInputByName("form" + NamingContainer.SEPARATOR_CHAR + "button"); // press the button page = (HtmlPage) submit.click(); assertTrue(-1 != page.asText().indexOf("erreur")); }
diff --git a/java/src/jp/gr/java_conf/neko_daisuki/fsyscall/io/SyscallInputStream.java b/java/src/jp/gr/java_conf/neko_daisuki/fsyscall/io/SyscallInputStream.java index 3e76717..e8fc66f 100644 --- a/java/src/jp/gr/java_conf/neko_daisuki/fsyscall/io/SyscallInputStream.java +++ b/java/src/jp/gr/java_conf/neko_daisuki/fsyscall/io/SyscallInputStream.java @@ -1,75 +1,75 @@ package jp.gr.java_conf.neko_daisuki.fsyscall.io; import java.io.IOException; import java.io.InputStream; import jp.gr.java_conf.neko_daisuki.fsyscall.Command; import jp.gr.java_conf.neko_daisuki.fsyscall.Pid; public class SyscallInputStream { private enum Status { OPEN, CLOSED }; private Status mStatus; private InputStream mIn; public SyscallInputStream(InputStream in) { mStatus = Status.OPEN; mIn = in; } public boolean isReady() throws IOException { return (mStatus == Status.OPEN) && (0 < mIn.available()); } public Command readCommand() throws IOException { return Command.fromInteger(readInteger()); } public void close() throws IOException { mStatus = Status.CLOSED; mIn.close(); } /** * Reads signed int (32bits). This method cannot handle unsigned int. */ public int readInteger() throws IOException { int n = 0; int shift = 0; int m; while (((m = mIn.read()) & 0x80) != 0) { n += ((m & 0x7f) << shift); shift += 7; } - return n; + return n + ((m & 0x7f) << shift); } public int readPayloadSize() throws IOException { return readInteger(); } public byte readByte() throws IOException { return (byte)mIn.read(); } public Pid readPid() throws IOException { return new Pid(readInteger()); } public byte[] read(int len) throws IOException { byte[] buffer = new byte[len]; int nBytes = 0; while (nBytes < len) { nBytes += mIn.read(buffer, nBytes, len - nBytes); } return buffer; } } /** * vim: tabstop=4 shiftwidth=4 expandtab softtabstop=4 */
true
true
public int readInteger() throws IOException { int n = 0; int shift = 0; int m; while (((m = mIn.read()) & 0x80) != 0) { n += ((m & 0x7f) << shift); shift += 7; } return n; }
public int readInteger() throws IOException { int n = 0; int shift = 0; int m; while (((m = mIn.read()) & 0x80) != 0) { n += ((m & 0x7f) << shift); shift += 7; } return n + ((m & 0x7f) << shift); }
diff --git a/src/com/android/phone/CallCard.java b/src/com/android/phone/CallCard.java index 06927269..531253d0 100644 --- a/src/com/android/phone/CallCard.java +++ b/src/com/android/phone/CallCard.java @@ -1,1823 +1,1825 @@ /* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.phone; import android.animation.LayoutTransition; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.mokee.location.PhoneLocation; import android.net.Uri; import android.os.Handler; import android.os.Message; import android.provider.ContactsContract.Contacts; import android.telephony.PhoneNumberUtils; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewStub; import android.view.accessibility.AccessibilityEvent; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.android.internal.telephony.Call; import com.android.internal.telephony.CallManager; import com.android.internal.telephony.CallerInfo; import com.android.internal.telephony.CallerInfoAsyncQuery; import com.android.internal.telephony.Connection; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneConstants; import java.util.List; /** * "Call card" UI element: the in-call screen contains a tiled layout of call * cards, each representing the state of a current "call" (ie. an active call, * a call on hold, or an incoming call.) */ public class CallCard extends LinearLayout implements CallTime.OnTickListener, CallerInfoAsyncQuery.OnQueryCompleteListener, ContactsAsyncHelper.OnImageLoadCompleteListener { private static final String LOG_TAG = "CallCard"; private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2); private static final int TOKEN_UPDATE_PHOTO_FOR_CALL_STATE = 0; private static final int TOKEN_DO_NOTHING = 1; /** * Used with {@link ContactsAsyncHelper#startObtainPhotoAsync(int, Context, Uri, * ContactsAsyncHelper.OnImageLoadCompleteListener, Object)} */ private static class AsyncLoadCookie { public final ImageView imageView; public final CallerInfo callerInfo; public final Call call; public AsyncLoadCookie(ImageView imageView, CallerInfo callerInfo, Call call) { this.imageView = imageView; this.callerInfo = callerInfo; this.call = call; } } /** * Reference to the InCallScreen activity that owns us. This may be * null if we haven't been initialized yet *or* after the InCallScreen * activity has been destroyed. */ private InCallScreen mInCallScreen; // Phone app instance private PhoneGlobals mApplication; // Top-level subviews of the CallCard /** Container for info about the current call(s) */ private ViewGroup mCallInfoContainer; /** Primary "call info" block (the foreground or ringing call) */ private ViewGroup mPrimaryCallInfo; /** "Call banner" for the primary call */ private ViewGroup mPrimaryCallBanner; /** Secondary "call info" block (the background "on hold" call) */ private ViewStub mSecondaryCallInfo; /** * Container for both provider info and call state. This will take care of showing/hiding * animation for those views. */ private ViewGroup mSecondaryInfoContainer; private ViewGroup mProviderInfo; private TextView mProviderLabel; private TextView mProviderAddress; // "Call state" widgets private TextView mCallStateLabel; private TextView mElapsedTime; // Text colors, used for various labels / titles private int mTextColorDefault; private int mTextColorCallTypeSip; // The main block of info about the "primary" or "active" call, // including photo / name / phone number / etc. private ImageView mPhoto; private View mPhotoDimEffect; private TextView mName; private TextView mPhoneNumber; private TextView mLabel; private TextView mCallTypeLabel; // private TextView mSocialStatus; /** * Uri being used to load contact photo for mPhoto. Will be null when nothing is being loaded, * or a photo is already loaded. */ private Uri mLoadingPersonUri; // Info about the "secondary" call, which is the "call on hold" when // two lines are in use. private TextView mSecondaryCallName; private ImageView mSecondaryCallPhoto; private View mSecondaryCallPhotoDimEffect; // Onscreen hint for the incoming call RotarySelector widget. private int mIncomingCallWidgetHintTextResId; private int mIncomingCallWidgetHintColorResId; private CallTime mCallTime; // Track the state for the photo. private ContactsAsyncHelper.ImageTracker mPhotoTracker; // Cached DisplayMetrics density. private float mDensity; /** * Sent when it takes too long (MESSAGE_DELAY msec) to load a contact photo for the given * person, at which we just start showing the default avatar picture instead of the person's * one. Note that we will *not* cancel the ongoing query and eventually replace the avatar * with the person's photo, when it is available anyway. */ private static final int MESSAGE_SHOW_UNKNOWN_PHOTO = 101; private static final int MESSAGE_DELAY = 500; // msec private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE_SHOW_UNKNOWN_PHOTO: showImage(mPhoto, R.drawable.picture_unknown); break; default: Log.wtf(LOG_TAG, "mHandler: unexpected message: " + msg); break; } } }; public CallCard(Context context, AttributeSet attrs) { super(context, attrs); if (DBG) log("CallCard constructor..."); if (DBG) log("- this = " + this); if (DBG) log("- context " + context + ", attrs " + attrs); mApplication = PhoneGlobals.getInstance(); mCallTime = new CallTime(this); // create a new object to track the state for the photo. mPhotoTracker = new ContactsAsyncHelper.ImageTracker(); mDensity = getResources().getDisplayMetrics().density; if (DBG) log("- Density: " + mDensity); } /* package */ void setInCallScreenInstance(InCallScreen inCallScreen) { mInCallScreen = inCallScreen; } @Override public void onTickForCallTimeElapsed(long timeElapsed) { // While a call is in progress, update the elapsed time shown // onscreen. updateElapsedTimeWidget(timeElapsed); } /* package */ void stopTimer() { mCallTime.cancelTimer(); } @Override protected void onFinishInflate() { super.onFinishInflate(); if (DBG) log("CallCard onFinishInflate(this = " + this + ")..."); mCallInfoContainer = (ViewGroup) findViewById(R.id.call_info_container); mPrimaryCallInfo = (ViewGroup) findViewById(R.id.primary_call_info); mPrimaryCallBanner = (ViewGroup) findViewById(R.id.primary_call_banner); mSecondaryInfoContainer = (ViewGroup) findViewById(R.id.secondary_info_container); mProviderInfo = (ViewGroup) findViewById(R.id.providerInfo); mProviderLabel = (TextView) findViewById(R.id.providerLabel); mProviderAddress = (TextView) findViewById(R.id.providerAddress); mCallStateLabel = (TextView) findViewById(R.id.callStateLabel); mElapsedTime = (TextView) findViewById(R.id.elapsedTime); // Text colors Resources res = getResources(); mTextColorDefault = res.getColor(R.color.incall_call_banner_text_color); mTextColorCallTypeSip = res.getColor(R.color.incall_callTypeSip); // "Caller info" area, including photo / name / phone numbers / etc mPhoto = (ImageView) findViewById(R.id.photo); mPhotoDimEffect = findViewById(R.id.dim_effect_for_primary_photo); mName = (TextView) findViewById(R.id.name); mPhoneNumber = (TextView) findViewById(R.id.phoneNumber); mLabel = (TextView) findViewById(R.id.label); mCallTypeLabel = (TextView) findViewById(R.id.callTypeLabel); // mSocialStatus = (TextView) findViewById(R.id.socialStatus); // Secondary info area, for the background ("on hold") call mSecondaryCallInfo = (ViewStub) findViewById(R.id.secondary_call_info); } /** * Updates the state of all UI elements on the CallCard, based on the * current state of the phone. */ /* package */ void updateState(CallManager cm) { if (DBG) log("updateState(" + cm + ")..."); // Update the onscreen UI based on the current state of the phone. PhoneConstants.State state = cm.getState(); // IDLE, RINGING, or OFFHOOK Call ringingCall = cm.getFirstActiveRingingCall(); Call fgCall = cm.getActiveFgCall(); Call bgCall = cm.getFirstActiveBgCall(); // Update the overall layout of the onscreen elements, if in PORTRAIT. // Portrait uses a programatically altered layout, whereas landscape uses layout xml's. // Landscape view has the views side by side, so no shifting of the picture is needed if (!PhoneUtils.isLandscape(this.getContext())) { updateCallInfoLayout(state); } // If the FG call is dialing/alerting, we should display for that call // and ignore the ringing call. This case happens when the telephony // layer rejects the ringing call while the FG call is dialing/alerting, // but the incoming call *does* briefly exist in the DISCONNECTING or // DISCONNECTED state. if ((ringingCall.getState() != Call.State.IDLE) && !fgCall.getState().isDialing()) { // A phone call is ringing, call waiting *or* being rejected // (ie. another call may also be active as well.) updateRingingCall(cm); } else if ((fgCall.getState() != Call.State.IDLE) || (bgCall.getState() != Call.State.IDLE)) { // We are here because either: // (1) the phone is off hook. At least one call exists that is // dialing, active, or holding, and no calls are ringing or waiting, // or: // (2) the phone is IDLE but a call just ended and it's still in // the DISCONNECTING or DISCONNECTED state. In this case, we want // the main CallCard to display "Hanging up" or "Call ended". // The normal "foreground call" code path handles both cases. updateForegroundCall(cm); } else { // We don't have any DISCONNECTED calls, which means that the phone // is *truly* idle. if (mApplication.inCallUiState.showAlreadyDisconnectedState) { // showAlreadyDisconnectedState implies the phone call is disconnected // and we want to show the disconnected phone call for a moment. // // This happens when a phone call ends while the screen is off, // which means the user had no chance to see the last status of // the call. We'll turn off showAlreadyDisconnectedState flag // and bail out of the in-call screen soon. updateAlreadyDisconnected(cm); } else { // It's very rare to be on the InCallScreen at all in this // state, but it can happen in some cases: // - A stray onPhoneStateChanged() event came in to the // InCallScreen *after* it was dismissed. // - We're allowed to be on the InCallScreen because // an MMI or USSD is running, but there's no actual "call" // to display. // - We're displaying an error dialog to the user // (explaining why the call failed), so we need to stay on // the InCallScreen so that the dialog will be visible. // // In these cases, put the callcard into a sane but "blank" state: updateNoCall(cm); } } } /** * Updates the overall size and positioning of mCallInfoContainer and * the "Call info" blocks, based on the phone state. */ private void updateCallInfoLayout(PhoneConstants.State state) { boolean ringing = (state == PhoneConstants.State.RINGING); if (DBG) log("updateCallInfoLayout()... ringing = " + ringing); // Based on the current state, update the overall // CallCard layout: // - Update the bottom margin of mCallInfoContainer to make sure // the call info area won't overlap with the touchable // controls on the bottom part of the screen. int reservedVerticalSpace = mInCallScreen.getInCallTouchUi().getTouchUiHeight(); ViewGroup.MarginLayoutParams callInfoLp = (ViewGroup.MarginLayoutParams) mCallInfoContainer.getLayoutParams(); callInfoLp.bottomMargin = reservedVerticalSpace; // Equivalent to setting // android:layout_marginBottom in XML if (DBG) log(" ==> callInfoLp.bottomMargin: " + reservedVerticalSpace); mCallInfoContainer.setLayoutParams(callInfoLp); } /** * Updates the UI for the state where the phone is in use, but not ringing. */ private void updateForegroundCall(CallManager cm) { if (DBG) log("updateForegroundCall()..."); // if (DBG) PhoneUtils.dumpCallManager(); Call fgCall = cm.getActiveFgCall(); Call bgCall = cm.getFirstActiveBgCall(); if (fgCall.getState() == Call.State.IDLE) { if (DBG) log("updateForegroundCall: no active call, show holding call"); // TODO: make sure this case agrees with the latest UI spec. // Display the background call in the main info area of the // CallCard, since there is no foreground call. Note that // displayMainCallStatus() will notice if the call we passed in is on // hold, and display the "on hold" indication. fgCall = bgCall; // And be sure to not display anything in the "on hold" box. bgCall = null; } displayMainCallStatus(cm, fgCall); Phone phone = fgCall.getPhone(); int phoneType = phone.getPhoneType(); if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) { if ((mApplication.cdmaPhoneCallState.getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) && mApplication.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()) { displaySecondaryCallStatus(cm, fgCall); } else { //This is required so that even if a background call is not present // we need to clean up the background call area. displaySecondaryCallStatus(cm, bgCall); } } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM) || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) { displaySecondaryCallStatus(cm, bgCall); } } /** * Updates the UI for the state where an incoming call is ringing (or * call waiting), regardless of whether the phone's already offhook. */ private void updateRingingCall(CallManager cm) { if (DBG) log("updateRingingCall()..."); Call ringingCall = cm.getFirstActiveRingingCall(); // Display caller-id info and photo from the incoming call: displayMainCallStatus(cm, ringingCall); // And even in the Call Waiting case, *don't* show any info about // the current ongoing call and/or the current call on hold. // (Since the caller-id info for the incoming call totally trumps // any info about the current call(s) in progress.) displaySecondaryCallStatus(cm, null); } /** * Updates the UI for the state where an incoming call is just disconnected while we want to * show the screen for a moment. * * This case happens when the whole in-call screen is in background when phone calls are hanged * up, which means there's no way to determine which call was the last call finished. Right now * this method simply shows the previous primary call status with a photo, closing the * secondary call status. In most cases (including conference call or misc call happening in * CDMA) this behaves right. * * If there were two phone calls both of which were hung up but the primary call was the * first, this would behave a bit odd (since the first one still appears as the * "last disconnected"). */ private void updateAlreadyDisconnected(CallManager cm) { // For the foreground call, we manually set up every component based on previous state. mPrimaryCallInfo.setVisibility(View.VISIBLE); mSecondaryInfoContainer.setLayoutTransition(null); mProviderInfo.setVisibility(View.GONE); mCallStateLabel.setVisibility(View.VISIBLE); mCallStateLabel.setText(mContext.getString(R.string.card_title_call_ended)); mElapsedTime.setVisibility(View.VISIBLE); mCallTime.cancelTimer(); // Just hide it. displaySecondaryCallStatus(cm, null); } /** * Updates the UI for the state where the phone is not in use. * This is analogous to updateForegroundCall() and updateRingingCall(), * but for the (uncommon) case where the phone is * totally idle. (See comments in updateState() above.) * * This puts the callcard into a sane but "blank" state. */ private void updateNoCall(CallManager cm) { if (DBG) log("updateNoCall()..."); displayMainCallStatus(cm, null); displaySecondaryCallStatus(cm, null); } /** * Updates the main block of caller info on the CallCard * (ie. the stuff in the primaryCallInfo block) based on the specified Call. */ private void displayMainCallStatus(CallManager cm, Call call) { if (DBG) log("displayMainCallStatus(call " + call + ")..."); if (call == null) { // There's no call to display, presumably because the phone is idle. mPrimaryCallInfo.setVisibility(View.GONE); return; } mPrimaryCallInfo.setVisibility(View.VISIBLE); Call.State state = call.getState(); if (DBG) log(" - call.state: " + call.getState()); switch (state) { case ACTIVE: case DISCONNECTING: // update timer field if (DBG) log("displayMainCallStatus: start periodicUpdateTimer"); mCallTime.setActiveCallMode(call); mCallTime.reset(); mCallTime.periodicUpdateTimer(); break; case HOLDING: // update timer field mCallTime.cancelTimer(); break; case DISCONNECTED: // Stop getting timer ticks from this call mCallTime.cancelTimer(); break; case DIALING: case ALERTING: // Stop getting timer ticks from a previous call mCallTime.cancelTimer(); break; case INCOMING: case WAITING: // Stop getting timer ticks from a previous call mCallTime.cancelTimer(); break; case IDLE: // The "main CallCard" should never be trying to display // an idle call! In updateState(), if the phone is idle, // we call updateNoCall(), which means that we shouldn't // have passed a call into this method at all. Log.w(LOG_TAG, "displayMainCallStatus: IDLE call in the main call card!"); // (It is possible, though, that we had a valid call which // became idle *after* the check in updateState() but // before we get here... So continue the best we can, // with whatever (stale) info we can get from the // passed-in Call object.) break; default: Log.w(LOG_TAG, "displayMainCallStatus: unexpected call state: " + state); break; } updateCallStateWidgets(call); if (PhoneUtils.isConferenceCall(call)) { // Update onscreen info for a conference call. updateDisplayForConference(call); } else { // Update onscreen info for a regular call (which presumably // has only one connection.) Connection conn = null; int phoneType = call.getPhone().getPhoneType(); if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) { conn = call.getLatestConnection(); } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM) || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) { conn = call.getEarliestConnection(); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } if (conn == null) { if (DBG) log("displayMainCallStatus: connection is null, using default values."); // if the connection is null, we run through the behaviour // we had in the past, which breaks down into trivial steps // with the current implementation of getCallerInfo and // updateDisplayForPerson. CallerInfo info = PhoneUtils.getCallerInfo(getContext(), null /* conn */); updateDisplayForPerson(info, PhoneConstants.PRESENTATION_ALLOWED, false, call, conn); } else { if (DBG) log(" - CONN: " + conn + ", state = " + conn.getState()); int presentation = conn.getNumberPresentation(); // make sure that we only make a new query when the current // callerinfo differs from what we've been requested to display. boolean runQuery = true; Object o = conn.getUserData(); if (o instanceof PhoneUtils.CallerInfoToken) { runQuery = mPhotoTracker.isDifferentImageRequest( ((PhoneUtils.CallerInfoToken) o).currentInfo); } else { runQuery = mPhotoTracker.isDifferentImageRequest(conn); } // Adding a check to see if the update was caused due to a Phone number update // or CNAP update. If so then we need to start a new query if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) { Object obj = conn.getUserData(); String updatedNumber = conn.getAddress(); String updatedCnapName = conn.getCnapName(); CallerInfo info = null; if (obj instanceof PhoneUtils.CallerInfoToken) { info = ((PhoneUtils.CallerInfoToken) o).currentInfo; } else if (o instanceof CallerInfo) { info = (CallerInfo) o; } if (info != null) { if (updatedNumber != null && !updatedNumber.equals(info.phoneNumber)) { if (DBG) log("- displayMainCallStatus: updatedNumber = " + updatedNumber); runQuery = true; } if (updatedCnapName != null && !updatedCnapName.equals(info.cnapName)) { if (DBG) log("- displayMainCallStatus: updatedCnapName = " + updatedCnapName); runQuery = true; } } } if (runQuery) { if (DBG) log("- displayMainCallStatus: starting CallerInfo query..."); PhoneUtils.CallerInfoToken info = PhoneUtils.startGetCallerInfo(getContext(), conn, this, call); updateDisplayForPerson(info.currentInfo, presentation, !info.isFinal, call, conn); } else { // No need to fire off a new query. We do still need // to update the display, though (since we might have // previously been in the "conference call" state.) if (DBG) log("- displayMainCallStatus: using data we already have..."); if (o instanceof CallerInfo) { CallerInfo ci = (CallerInfo) o; // Update CNAP information if Phone state change occurred ci.cnapName = conn.getCnapName(); ci.numberPresentation = conn.getNumberPresentation(); ci.namePresentation = conn.getCnapNamePresentation(); if (DBG) log("- displayMainCallStatus: CNAP data from Connection: " + "CNAP name=" + ci.cnapName + ", Number/Name Presentation=" + ci.numberPresentation); if (DBG) log(" ==> Got CallerInfo; updating display: ci = " + ci); updateDisplayForPerson(ci, presentation, false, call, conn); } else if (o instanceof PhoneUtils.CallerInfoToken){ CallerInfo ci = ((PhoneUtils.CallerInfoToken) o).currentInfo; if (DBG) log("- displayMainCallStatus: CNAP data from Connection: " + "CNAP name=" + ci.cnapName + ", Number/Name Presentation=" + ci.numberPresentation); if (DBG) log(" ==> Got CallerInfoToken; updating display: ci = " + ci); updateDisplayForPerson(ci, presentation, true, call, conn); } else { Log.w(LOG_TAG, "displayMainCallStatus: runQuery was false, " + "but we didn't have a cached CallerInfo object! o = " + o); // TODO: any easy way to recover here (given that // the CallCard is probably displaying stale info // right now?) Maybe force the CallCard into the // "Unknown" state? } } } } // In some states we override the "photo" ImageView to be an // indication of the current state, rather than displaying the // regular photo as set above. updatePhotoForCallState(call); // One special feature of the "number" text field: For incoming // calls, while the user is dragging the RotarySelector widget, we // use mPhoneNumber to display a hint like "Rotate to answer". if (mIncomingCallWidgetHintTextResId != 0) { // Display the hint! mPhoneNumber.setText(mIncomingCallWidgetHintTextResId); mPhoneNumber.setTextColor(getResources().getColor(mIncomingCallWidgetHintColorResId)); mPhoneNumber.setVisibility(View.VISIBLE); mLabel.setVisibility(View.GONE); } // If we don't have a hint to display, just don't touch // mPhoneNumber and mLabel. (Their text / color / visibility have // already been set correctly, by either updateDisplayForPerson() // or updateDisplayForConference().) } /** * Implemented for CallerInfoAsyncQuery.OnQueryCompleteListener interface. * refreshes the CallCard data when it called. */ @Override public void onQueryComplete(int token, Object cookie, CallerInfo ci) { if (DBG) log("onQueryComplete: token " + token + ", cookie " + cookie + ", ci " + ci); if (cookie instanceof Call) { // grab the call object and update the display for an individual call, // as well as the successive call to update image via call state. // If the object is a textview instead, we update it as we need to. if (DBG) log("callerinfo query complete, updating ui from displayMainCallStatus()"); Call call = (Call) cookie; Connection conn = null; int phoneType = call.getPhone().getPhoneType(); if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) { conn = call.getLatestConnection(); } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM) || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) { conn = call.getEarliestConnection(); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } PhoneUtils.CallerInfoToken cit = PhoneUtils.startGetCallerInfo(getContext(), conn, this, null); int presentation = PhoneConstants.PRESENTATION_ALLOWED; if (conn != null) presentation = conn.getNumberPresentation(); if (DBG) log("- onQueryComplete: presentation=" + presentation + ", contactExists=" + ci.contactExists); // Depending on whether there was a contact match or not, we want to pass in different // CallerInfo (for CNAP). Therefore if ci.contactExists then use the ci passed in. // Otherwise, regenerate the CIT from the Connection and use the CallerInfo from there. if (ci.contactExists) { updateDisplayForPerson(ci, PhoneConstants.PRESENTATION_ALLOWED, false, call, conn); } else { updateDisplayForPerson(cit.currentInfo, presentation, false, call, conn); } updatePhotoForCallState(call); } else if (cookie instanceof TextView){ if (DBG) log("callerinfo query complete, updating ui from ongoing or onhold"); ((TextView) cookie).setText(PhoneUtils.getCompactNameFromCallerInfo(ci, mContext)); } } /** * Implemented for ContactsAsyncHelper.OnImageLoadCompleteListener interface. * make sure that the call state is reflected after the image is loaded. */ @Override public void onImageLoadComplete(int token, Drawable photo, Bitmap photoIcon, Object cookie) { mHandler.removeMessages(MESSAGE_SHOW_UNKNOWN_PHOTO); if (mLoadingPersonUri != null) { // Start sending view notification after the current request being done. // New image may possibly be available from the next phone calls. // // TODO: may be nice to update the image view again once the newer one // is available on contacts database. PhoneUtils.sendViewNotificationAsync(mApplication, mLoadingPersonUri); } else { // This should not happen while we need some verbose info if it happens.. Log.w(LOG_TAG, "Person Uri isn't available while Image is successfully loaded."); } mLoadingPersonUri = null; AsyncLoadCookie asyncLoadCookie = (AsyncLoadCookie) cookie; CallerInfo callerInfo = asyncLoadCookie.callerInfo; ImageView imageView = asyncLoadCookie.imageView; Call call = asyncLoadCookie.call; callerInfo.cachedPhoto = photo; callerInfo.cachedPhotoIcon = photoIcon; callerInfo.isCachedPhotoCurrent = true; // Note: previously ContactsAsyncHelper has done this job. // TODO: We will need fade-in animation. See issue 5236130. if (photo != null) { showImage(imageView, photo); } else if (photoIcon != null) { showImage(imageView, photoIcon); } else { showImage(imageView, R.drawable.picture_unknown); } if (token == TOKEN_UPDATE_PHOTO_FOR_CALL_STATE) { updatePhotoForCallState(call); } } /** * Updates the "call state label" and the elapsed time widget based on the * current state of the call. */ private void updateCallStateWidgets(Call call) { if (DBG) log("updateCallStateWidgets(call " + call + ")..."); final Call.State state = call.getState(); final Context context = getContext(); final Phone phone = call.getPhone(); final int phoneType = phone.getPhoneType(); String callStateLabel = null; // Label to display as part of the call banner int bluetoothIconId = 0; // Icon to display alongside the call state label switch (state) { case IDLE: // "Call state" is meaningless in this state. break; case ACTIVE: // We normally don't show a "call state label" at all in // this state (but see below for some special cases). break; case HOLDING: callStateLabel = context.getString(R.string.card_title_on_hold); break; case DIALING: case ALERTING: if (mApplication.notifier.isCallWaiting(call)) { callStateLabel = context.getString(R.string.card_title_dialing_waiting); } else { callStateLabel = context.getString(R.string.card_title_dialing); } break; case INCOMING: case WAITING: callStateLabel = context.getString(R.string.card_title_incoming_call); // Also, display a special icon (alongside the "Incoming call" // label) if there's an incoming call and audio will be routed // to bluetooth when you answer it. if (mApplication.showBluetoothIndication()) { bluetoothIconId = R.drawable.ic_incoming_call_bluetooth; } break; case DISCONNECTING: // While in the DISCONNECTING state we display a "Hanging up" // message in order to make the UI feel more responsive. (In // GSM it's normal to see a delay of a couple of seconds while // negotiating the disconnect with the network, so the "Hanging // up" state at least lets the user know that we're doing // something. This state is currently not used with CDMA.) callStateLabel = context.getString(R.string.card_title_hanging_up); break; case DISCONNECTED: callStateLabel = getCallFailedString(call); break; default: Log.wtf(LOG_TAG, "updateCallStateWidgets: unexpected call state: " + state); break; } // Check a couple of other special cases if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) { if ((state == Call.State.ACTIVE) && mApplication.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()) { // Display "Dialing" while dialing a 3Way call, even // though the foreground call state is actually ACTIVE. callStateLabel = context.getString(R.string.card_title_dialing); } else if (PhoneGlobals.getInstance().notifier.getIsCdmaRedialCall()) { callStateLabel = context.getString(R.string.card_title_redialing); } } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM) { if (state == Call.State.ACTIVE && mApplication.notifier.isCallWaiting(call)) { callStateLabel = context.getString(R.string.card_title_waiting_call); } } if (PhoneUtils.isPhoneInEcm(phone)) { // In emergency callback mode (ECM), use a special label // that shows your own phone number. callStateLabel = getECMCardTitle(context, phone); } final InCallUiState inCallUiState = mApplication.inCallUiState; if (DBG) { log("==> callStateLabel: '" + callStateLabel + "', bluetoothIconId = " + bluetoothIconId + ", providerInfoVisible = " + inCallUiState.providerInfoVisible); } // Animation will be done by mCallerDetail's LayoutTransition, but in some cases, we don't // want that. // - DIALING: This is at the beginning of the phone call. // - DISCONNECTING, DISCONNECTED: Screen will disappear soon; we have no time for animation. final boolean skipAnimation = (state == Call.State.DIALING || state == Call.State.DISCONNECTING || state == Call.State.DISCONNECTED); LayoutTransition layoutTransition = null; if (skipAnimation) { // Evict LayoutTransition object to skip animation. layoutTransition = mSecondaryInfoContainer.getLayoutTransition(); mSecondaryInfoContainer.setLayoutTransition(null); } if (inCallUiState.providerInfoVisible) { mProviderInfo.setVisibility(View.VISIBLE); mProviderLabel.setText(context.getString(R.string.calling_via_template, inCallUiState.providerLabel)); mProviderAddress.setText(inCallUiState.providerAddress); mInCallScreen.requestRemoveProviderInfoWithDelay(); } else { mProviderInfo.setVisibility(View.GONE); } if (!TextUtils.isEmpty(callStateLabel)) { mCallStateLabel.setVisibility(View.VISIBLE); mCallStateLabel.setText(callStateLabel); // ...and display the icon too if necessary. if (bluetoothIconId != 0) { mCallStateLabel.setCompoundDrawablesWithIntrinsicBounds(bluetoothIconId, 0, 0, 0); mCallStateLabel.setCompoundDrawablePadding((int) (mDensity * 5)); } else { // Clear out any icons mCallStateLabel.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); } } else { mCallStateLabel.setVisibility(View.GONE); // Gravity is aligned left when receiving an incoming call in landscape. // In that rare case, the gravity needs to be reset to the right. // Also, setText("") is used since there is a delay in making the view GONE, // so the user will otherwise see the text jump to the right side before disappearing. if(mCallStateLabel.getGravity() != Gravity.RIGHT) { mCallStateLabel.setText(""); mCallStateLabel.setGravity(Gravity.RIGHT); } } if (skipAnimation) { // Restore LayoutTransition object to recover animation. mSecondaryInfoContainer.setLayoutTransition(layoutTransition); } // ...and update the elapsed time widget too. switch (state) { case ACTIVE: case DISCONNECTING: // Show the time with fade-in animation. AnimationUtils.Fade.show(mElapsedTime); updateElapsedTimeWidget(call); break; case DISCONNECTED: // In the "Call ended" state, leave the mElapsedTime widget // visible, but don't touch it (so we continue to see the // elapsed time of the call that just ended.) // Check visibility to keep possible fade-in animation. if (mElapsedTime.getVisibility() != View.VISIBLE) { mElapsedTime.setVisibility(View.VISIBLE); } break; default: // Call state here is IDLE, ACTIVE, HOLDING, DIALING, ALERTING, // INCOMING, or WAITING. // In all of these states, the "elapsed time" is meaningless, so // don't show it. AnimationUtils.Fade.hide(mElapsedTime, View.INVISIBLE); // Additionally, in call states that can only occur at the start // of a call, reset the elapsed time to be sure we won't display // stale info later (like if we somehow go straight from DIALING // or ALERTING to DISCONNECTED, which can actually happen in // some failure cases like "line busy"). if ((state == Call.State.DIALING) || (state == Call.State.ALERTING)) { updateElapsedTimeWidget(0); } break; } } /** * Updates mElapsedTime based on the given {@link Call} object's information. * * @see CallTime#getCallDuration(Call) * @see Connection#getDurationMillis() */ /* package */ void updateElapsedTimeWidget(Call call) { long duration = CallTime.getCallDuration(call); // msec updateElapsedTimeWidget(duration / 1000); // Also see onTickForCallTimeElapsed(), which updates this // widget once per second while the call is active. } /** * Updates mElapsedTime based on the specified number of seconds. */ private void updateElapsedTimeWidget(long timeElapsed) { // if (DBG) log("updateElapsedTimeWidget: " + timeElapsed); mElapsedTime.setText(DateUtils.formatElapsedTime(timeElapsed)); } /** * Updates the "on hold" box in the "other call" info area * (ie. the stuff in the secondaryCallInfo block) * based on the specified Call. * Or, clear out the "on hold" box if the specified call * is null or idle. */ private void displaySecondaryCallStatus(CallManager cm, Call call) { if (DBG) log("displayOnHoldCallStatus(call =" + call + ")..."); if ((call == null) || (PhoneGlobals.getInstance().isOtaCallInActiveState())) { mSecondaryCallInfo.setVisibility(View.GONE); return; } Call.State state = call.getState(); switch (state) { case HOLDING: // Ok, there actually is a background call on hold. // Display the "on hold" box. // Note this case occurs only on GSM devices. (On CDMA, // the "call on hold" is actually the 2nd connection of // that ACTIVE call; see the ACTIVE case below.) showSecondaryCallInfo(); if (PhoneUtils.isConferenceCall(call)) { if (DBG) log("==> conference call."); mSecondaryCallName.setText(getContext().getString(R.string.confCall)); showImage(mSecondaryCallPhoto, R.drawable.picture_conference); } else { // perform query and update the name temporarily // make sure we hand the textview we want updated to the // callback function. if (DBG) log("==> NOT a conf call; call startGetCallerInfo..."); PhoneUtils.CallerInfoToken infoToken = PhoneUtils.startGetCallerInfo( getContext(), call, this, mSecondaryCallName); mSecondaryCallName.setText( PhoneUtils.getCompactNameFromCallerInfo(infoToken.currentInfo, getContext())); // Also pull the photo out of the current CallerInfo. // (Note we assume we already have a valid photo at // this point, since *presumably* the caller-id query // was already run at some point *before* this call // got put on hold. If there's no cached photo, just // fall back to the default "unknown" image.) if (infoToken.isFinal) { showCachedImage(mSecondaryCallPhoto, infoToken.currentInfo); } else { showImage(mSecondaryCallPhoto, R.drawable.picture_unknown); } } AnimationUtils.Fade.show(mSecondaryCallPhotoDimEffect); break; case ACTIVE: // CDMA: This is because in CDMA when the user originates the second call, // although the Foreground call state is still ACTIVE in reality the network // put the first call on hold. if (mApplication.phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) { showSecondaryCallInfo(); List<Connection> connections = call.getConnections(); if (connections.size() > 2) { // This means that current Mobile Originated call is the not the first 3-Way // call the user is making, which in turn tells the PhoneGlobals that we no // longer know which previous caller/party had dropped out before the user // made this call. mSecondaryCallName.setText( getContext().getString(R.string.card_title_in_call)); showImage(mSecondaryCallPhoto, R.drawable.picture_unknown); } else { // This means that the current Mobile Originated call IS the first 3-Way // and hence we display the first callers/party's info here. Connection conn = call.getEarliestConnection(); PhoneUtils.CallerInfoToken infoToken = PhoneUtils.startGetCallerInfo( getContext(), conn, this, mSecondaryCallName); // Get the compactName to be displayed, but then check that against // the number presentation value for the call. If it's not an allowed // presentation, then display the appropriate presentation string instead. CallerInfo info = infoToken.currentInfo; String name = PhoneUtils.getCompactNameFromCallerInfo(info, getContext()); boolean forceGenericPhoto = false; if (info != null && info.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) { name = PhoneUtils.getPresentationString( getContext(), info.numberPresentation); forceGenericPhoto = true; } mSecondaryCallName.setText(name); // Also pull the photo out of the current CallerInfo. // (Note we assume we already have a valid photo at // this point, since *presumably* the caller-id query // was already run at some point *before* this call // got put on hold. If there's no cached photo, just // fall back to the default "unknown" image.) if (!forceGenericPhoto && infoToken.isFinal) { showCachedImage(mSecondaryCallPhoto, info); } else { showImage(mSecondaryCallPhoto, R.drawable.picture_unknown); } } } else { // We shouldn't ever get here at all for non-CDMA devices. Log.w(LOG_TAG, "displayOnHoldCallStatus: ACTIVE state on non-CDMA device"); mSecondaryCallInfo.setVisibility(View.GONE); } AnimationUtils.Fade.hide(mSecondaryCallPhotoDimEffect, View.GONE); break; default: // There's actually no call on hold. (Presumably this call's // state is IDLE, since any other state is meaningless for the // background call.) mSecondaryCallInfo.setVisibility(View.GONE); break; } } private void showSecondaryCallInfo() { // This will call ViewStub#inflate() when needed. mSecondaryCallInfo.setVisibility(View.VISIBLE); if (mSecondaryCallName == null) { mSecondaryCallName = (TextView) findViewById(R.id.secondaryCallName); } if (mSecondaryCallPhoto == null) { mSecondaryCallPhoto = (ImageView) findViewById(R.id.secondaryCallPhoto); } if (mSecondaryCallPhotoDimEffect == null) { mSecondaryCallPhotoDimEffect = findViewById(R.id.dim_effect_for_secondary_photo); mSecondaryCallPhotoDimEffect.setOnClickListener(mInCallScreen); // Add a custom OnTouchListener to manually shrink the "hit target". mSecondaryCallPhotoDimEffect.setOnTouchListener(new SmallerHitTargetTouchListener()); } mInCallScreen.updateButtonStateOutsideInCallTouchUi(); } /** * Method which is expected to be called from * {@link InCallScreen#updateButtonStateOutsideInCallTouchUi()}. */ /* package */ void setSecondaryCallClickable(boolean clickable) { if (mSecondaryCallPhotoDimEffect != null) { mSecondaryCallPhotoDimEffect.setEnabled(clickable); } } private String getCallFailedString(Call call) { Connection c = call.getEarliestConnection(); int resID; if (c == null) { if (DBG) log("getCallFailedString: connection is null, using default values."); // if this connection is null, just assume that the // default case occurs. resID = R.string.card_title_call_ended; } else { Connection.DisconnectCause cause = c.getDisconnectCause(); // TODO: The card *title* should probably be "Call ended" in all // cases, but if the DisconnectCause was an error condition we should // probably also display the specific failure reason somewhere... switch (cause) { case BUSY: resID = R.string.callFailed_userBusy; break; case CONGESTION: resID = R.string.callFailed_congestion; break; case TIMED_OUT: resID = R.string.callFailed_timedOut; break; case SERVER_UNREACHABLE: resID = R.string.callFailed_server_unreachable; break; case NUMBER_UNREACHABLE: resID = R.string.callFailed_number_unreachable; break; case INVALID_CREDENTIALS: resID = R.string.callFailed_invalid_credentials; break; case SERVER_ERROR: resID = R.string.callFailed_server_error; break; case OUT_OF_NETWORK: resID = R.string.callFailed_out_of_network; break; case LOST_SIGNAL: case CDMA_DROP: resID = R.string.callFailed_noSignal; break; case LIMIT_EXCEEDED: resID = R.string.callFailed_limitExceeded; break; case POWER_OFF: resID = R.string.callFailed_powerOff; break; case ICC_ERROR: resID = R.string.callFailed_simError; break; case OUT_OF_SERVICE: resID = R.string.callFailed_outOfService; break; case INVALID_NUMBER: case UNOBTAINABLE_NUMBER: resID = R.string.callFailed_unobtainable_number; break; default: resID = R.string.card_title_call_ended; break; } } return getContext().getString(resID); } /** * Updates the name / photo / number / label fields on the CallCard * based on the specified CallerInfo. * * If the current call is a conference call, use * updateDisplayForConference() instead. */ private void updateDisplayForPerson(CallerInfo info, int presentation, boolean isTemporary, Call call, Connection conn) { if (DBG) log("updateDisplayForPerson(" + info + ")\npresentation:" + presentation + " isTemporary:" + isTemporary); // inform the state machine that we are displaying a photo. mPhotoTracker.setPhotoRequest(info); mPhotoTracker.setPhotoState(ContactsAsyncHelper.ImageTracker.DISPLAY_IMAGE); // The actual strings we're going to display onscreen: boolean displayNameIsNumber = false; String displayName; String displayNumber = null; String label = null; Uri personUri = null; // String socialStatusText = null; // Drawable socialStatusBadge = null; if (info != null) { // It appears that there is a small change in behaviour with the // PhoneUtils' startGetCallerInfo whereby if we query with an // empty number, we will get a valid CallerInfo object, but with // fields that are all null, and the isTemporary boolean input // parameter as true. // In the past, we would see a NULL callerinfo object, but this // ends up causing null pointer exceptions elsewhere down the // line in other cases, so we need to make this fix instead. It // appears that this was the ONLY call to PhoneUtils // .getCallerInfo() that relied on a NULL CallerInfo to indicate // an unknown contact. // Currently, info.phoneNumber may actually be a SIP address, and // if so, it might sometimes include the "sip:" prefix. That // prefix isn't really useful to the user, though, so strip it off // if present. (For any other URI scheme, though, leave the // prefix alone.) // TODO: It would be cleaner for CallerInfo to explicitly support // SIP addresses instead of overloading the "phoneNumber" field. // Then we could remove this hack, and instead ask the CallerInfo // for a "user visible" form of the SIP address. String number = info.phoneNumber; if ((number != null) && number.startsWith("sip:")) { number = number.substring(4); } if (TextUtils.isEmpty(info.name)) { // No valid "name" in the CallerInfo, so fall back to // something else. // (Typically, we promote the phone number up to the "name" slot // onscreen, and possibly display a descriptive string in the // "number" slot.) if (TextUtils.isEmpty(number)) { // No name *or* number! Display a generic "unknown" string // (or potentially some other default based on the presentation.) displayName = PhoneUtils.getPresentationString(getContext(), presentation); if (DBG) log(" ==> no name *or* number! displayName = " + displayName); } else if (presentation != PhoneConstants.PRESENTATION_ALLOWED) { // This case should never happen since the network should never send a phone # // AND a restricted presentation. However we leave it here in case of weird // network behavior displayName = PhoneUtils.getPresentationString(getContext(), presentation); if (DBG) log(" ==> presentation not allowed! displayName = " + displayName); } else if (!TextUtils.isEmpty(info.cnapName)) { // No name, but we do have a valid CNAP name, so use that. displayName = info.cnapName; info.name = info.cnapName; displayNumber = number; if (DBG) log(" ==> cnapName available: displayName '" + displayName + "', displayNumber '" + displayNumber + "'"); } else { // No name; all we have is a number. This is the typical // case when an incoming call doesn't match any contact, // or if you manually dial an outgoing number using the // dialpad. // Promote the phone number up to the "name" slot: displayName = number; displayNameIsNumber = true; // ...and use the "number" slot for a geographical description // string if available (but only for incoming calls.) if ((conn != null) && (conn.isIncoming())) { // TODO (CallerInfoAsyncQuery cleanup): Fix the CallerInfo // query to only do the geoDescription lookup in the first // place for incoming calls. displayNumber = info.geoDescription; // may be null } if (DBG) log(" ==> no name; falling back to number: displayName '" + displayName + "', displayNumber '" + displayNumber + "'"); } } else { // We do have a valid "name" in the CallerInfo. Display that // in the "name" slot, and the phone number in the "number" slot. if (presentation != PhoneConstants.PRESENTATION_ALLOWED) { // This case should never happen since the network should never send a name // AND a restricted presentation. However we leave it here in case of weird // network behavior displayName = PhoneUtils.getPresentationString(getContext(), presentation); if (DBG) log(" ==> valid name, but presentation not allowed!" + " displayName = " + displayName); } else { displayName = info.name; displayNumber = number; label = info.phoneLabel; if (DBG) log(" ==> name is present in CallerInfo: displayName '" + displayName + "', displayNumber '" + displayNumber + "'"); } } personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, info.person_id); if (DBG) log("- got personUri: '" + personUri + "', based on info.person_id: " + info.person_id); } else { displayName = PhoneUtils.getPresentationString(getContext(), presentation); } boolean updateNameAndNumber = true; // If the new info is just a phone number, check to make sure it's not less // information than what's already being displayed. if (displayNameIsNumber) { // If the new number is the same as the number already displayed, ignore it // because that means we're also already displaying a name for it. // If the new number is the same as the name currently being displayed, only // display if the new number is longer (ie, has formatting). String visiblePhoneNumber = null; if (mPhoneNumber.getVisibility() == View.VISIBLE) { visiblePhoneNumber = mPhoneNumber.getText().toString(); } if ((visiblePhoneNumber != null && PhoneNumberUtils.compare(visiblePhoneNumber, displayName)) || (PhoneNumberUtils.compare(mName.getText().toString(), displayName) && displayName.length() < mName.length())) { if (DBG) log("chose not to update display {" + mName.getText() + ", " + visiblePhoneNumber + "} with number " + displayName); updateNameAndNumber = false; } } if (updateNameAndNumber) { if (call.isGeneric()) { mName.setText(R.string.card_title_in_call); } else { mName.setText(displayName); } mName.setVisibility(View.VISIBLE); if (displayNumber != null && !call.isGeneric()) { mPhoneNumber.setText(displayNumber); mPhoneNumber.setVisibility(View.VISIBLE); } else { mPhoneNumber.setVisibility(View.GONE); } if (label != null && !call.isGeneric()) { mLabel.setText(label); mLabel.setVisibility(View.VISIBLE); } else { mLabel.setVisibility(View.GONE); } } // Update mPhoto // if the temporary flag is set, we know we'll be getting another call after // the CallerInfo has been correctly updated. So, we can skip the image // loading until then. // If the photoResource is filled in for the CallerInfo, (like with the // Emergency Number case), then we can just set the photo image without // requesting for an image load. Please refer to CallerInfoAsyncQuery.java // for cases where CallerInfo.photoResource may be set. We can also avoid // the image load step if the image data is cached. if (isTemporary && (info == null || !info.isCachedPhotoCurrent)) { mPhoto.setTag(null); mPhoto.setVisibility(View.INVISIBLE); } else if (info != null && info.photoResource != 0){ showImage(mPhoto, info.photoResource); } else if (!showCachedImage(mPhoto, info)) { if (personUri == null) { Log.w(LOG_TAG, "personPri is null. Just use Unknown picture."); showImage(mPhoto, R.drawable.picture_unknown); } else if (personUri.equals(mLoadingPersonUri)) { if (DBG) { log("The requested Uri (" + personUri + ") is being loaded already." + " Ignoret the duplicate load request."); } } else { // Remember which person's photo is being loaded right now so that we won't issue // unnecessary load request multiple times, which will mess up animation around // the contact photo. mLoadingPersonUri = personUri; // Forget the drawable previously used. mPhoto.setTag(null); // Show empty screen for a moment. mPhoto.setVisibility(View.INVISIBLE); // Load the image with a callback to update the image state. // When the load is finished, onImageLoadComplete() will be called. ContactsAsyncHelper.startObtainPhotoAsync(TOKEN_UPDATE_PHOTO_FOR_CALL_STATE, getContext(), personUri, this, new AsyncLoadCookie(mPhoto, info, call)); // If the image load is too slow, we show a default avatar icon afterward. // If it is fast enough, this message will be canceled on onImageLoadComplete(). mHandler.removeMessages(MESSAGE_SHOW_UNKNOWN_PHOTO); mHandler.sendEmptyMessageDelayed(MESSAGE_SHOW_UNKNOWN_PHOTO, MESSAGE_DELAY); } } // If the phone call is on hold, show it with darker status. // Right now we achieve it by overlaying opaque View. // Note: See also layout file about why so and what is the other possibilities. if (call.getState() == Call.State.HOLDING) { AnimationUtils.Fade.show(mPhotoDimEffect); } else { AnimationUtils.Fade.hide(mPhotoDimEffect, View.GONE); } // Other text fields: updateCallTypeLabel(call); // updateSocialStatus(socialStatusText, socialStatusBadge, call); // Currently unused // display Phone Location + if(TextUtils.isEmpty(info.phoneNumber)) + return; if(mContext.getResources().getConfiguration().locale.getCountry().equals("CN")||mContext.getResources().getConfiguration().locale.getCountry().equals("TW")) { String PhoneLocationStr=PhoneLocation.getCityFromPhone(info.phoneNumber, mContext); setLocationText(label, PhoneLocationStr); } else { info.updateGeoDescription(mContext, info.phoneNumber); setLocationText(label, info.geoDescription); } } private void setLocationText(String label, String location) { if(label != null && !TextUtils.isEmpty(location)) { mLabel.setText(label + " " +location); mLabel.setVisibility(View.VISIBLE); } else if(!TextUtils.isEmpty(location)) { mPhoneNumber.setText(location); mPhoneNumber.setVisibility(View.VISIBLE); } } /** * Updates the name / photo / number / label fields * for the special "conference call" state. * * If the current call has only a single connection, use * updateDisplayForPerson() instead. */ private void updateDisplayForConference(Call call) { if (DBG) log("updateDisplayForConference()..."); int phoneType = call.getPhone().getPhoneType(); if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) { // This state corresponds to both 3-Way merged call and // Call Waiting accepted call. // In this case we display the UI in a "generic" state, with // the generic "dialing" icon and no caller information, // because in this state in CDMA the user does not really know // which caller party he is talking to. showImage(mPhoto, R.drawable.picture_dialing); mName.setText(R.string.card_title_in_call); } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM) || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) { // Normal GSM (or possibly SIP?) conference call. // Display the "conference call" image as the contact photo. // TODO: Better visual treatment for contact photos in a // conference call (see bug 1313252). showImage(mPhoto, R.drawable.picture_conference); mName.setText(R.string.card_title_conf_call); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } mName.setVisibility(View.VISIBLE); // TODO: For a conference call, the "phone number" slot is specced // to contain a summary of who's on the call, like "Bill Foldes // and Hazel Nutt" or "Bill Foldes and 2 others". // But for now, just hide it: mPhoneNumber.setVisibility(View.GONE); mLabel.setVisibility(View.GONE); // Other text fields: updateCallTypeLabel(call); // updateSocialStatus(null, null, null); // socialStatus is never visible in this state // TODO: for a GSM conference call, since we do actually know who // you're talking to, consider also showing names / numbers / // photos of some of the people on the conference here, so you can // see that info without having to click "Manage conference". We // probably have enough space to show info for 2 people, at least. // // To do this, our caller would pass us the activeConnections // list, and we'd call PhoneUtils.getCallerInfo() separately for // each connection. } /** * Updates the CallCard "photo" IFF the specified Call is in a state * that needs a special photo (like "busy" or "dialing".) * * If the current call does not require a special image in the "photo" * slot onscreen, don't do anything, since presumably the photo image * has already been set (to the photo of the person we're talking, or * the generic "picture_unknown" image, or the "conference call" * image.) */ private void updatePhotoForCallState(Call call) { if (DBG) log("updatePhotoForCallState(" + call + ")..."); int photoImageResource = 0; // Check for the (relatively few) telephony states that need a // special image in the "photo" slot. Call.State state = call.getState(); switch (state) { case DISCONNECTED: // Display the special "busy" photo for BUSY or CONGESTION. // Otherwise (presumably the normal "call ended" state) // leave the photo alone. Connection c = call.getEarliestConnection(); // if the connection is null, we assume the default case, // otherwise update the image resource normally. if (c != null) { Connection.DisconnectCause cause = c.getDisconnectCause(); if ((cause == Connection.DisconnectCause.BUSY) || (cause == Connection.DisconnectCause.CONGESTION)) { photoImageResource = R.drawable.picture_busy; } } else if (DBG) { log("updatePhotoForCallState: connection is null, ignoring."); } // TODO: add special images for any other DisconnectCauses? break; case ALERTING: case DIALING: default: // Leave the photo alone in all other states. // If this call is an individual call, and the image is currently // displaying a state, (rather than a photo), we'll need to update // the image. // This is for the case where we've been displaying the state and // now we need to restore the photo. This can happen because we // only query the CallerInfo once, and limit the number of times // the image is loaded. (So a state image may overwrite the photo // and we would otherwise have no way of displaying the photo when // the state goes away.) // if the photoResource field is filled-in in the Connection's // caller info, then we can just use that instead of requesting // for a photo load. // look for the photoResource if it is available. CallerInfo ci = null; { Connection conn = null; int phoneType = call.getPhone().getPhoneType(); if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) { conn = call.getLatestConnection(); } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM) || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) { conn = call.getEarliestConnection(); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } if (conn != null) { Object o = conn.getUserData(); if (o instanceof CallerInfo) { ci = (CallerInfo) o; } else if (o instanceof PhoneUtils.CallerInfoToken) { ci = ((PhoneUtils.CallerInfoToken) o).currentInfo; } } } if (ci != null) { photoImageResource = ci.photoResource; } // If no photoResource found, check to see if this is a conference call. If // it is not a conference call: // 1. Try to show the cached image // 2. If the image is not cached, check to see if a load request has been // made already. // 3. If the load request has not been made [DISPLAY_DEFAULT], start the // request and note that it has started by updating photo state with // [DISPLAY_IMAGE]. if (photoImageResource == 0) { if (!PhoneUtils.isConferenceCall(call)) { if (!showCachedImage(mPhoto, ci) && (mPhotoTracker.getPhotoState() == ContactsAsyncHelper.ImageTracker.DISPLAY_DEFAULT)) { Uri photoUri = mPhotoTracker.getPhotoUri(); if (photoUri == null) { Log.w(LOG_TAG, "photoUri became null. Show default avatar icon"); showImage(mPhoto, R.drawable.picture_unknown); } else { if (DBG) { log("start asynchronous load inside updatePhotoForCallState()"); } mPhoto.setTag(null); // Make it invisible for a moment mPhoto.setVisibility(View.INVISIBLE); ContactsAsyncHelper.startObtainPhotoAsync(TOKEN_DO_NOTHING, getContext(), photoUri, this, new AsyncLoadCookie(mPhoto, ci, null)); } mPhotoTracker.setPhotoState( ContactsAsyncHelper.ImageTracker.DISPLAY_IMAGE); } } } else { showImage(mPhoto, photoImageResource); mPhotoTracker.setPhotoState(ContactsAsyncHelper.ImageTracker.DISPLAY_IMAGE); return; } break; } if (photoImageResource != 0) { if (DBG) log("- overrriding photo image: " + photoImageResource); showImage(mPhoto, photoImageResource); // Track the image state. mPhotoTracker.setPhotoState(ContactsAsyncHelper.ImageTracker.DISPLAY_DEFAULT); } } /** * Try to display the cached image from the callerinfo object. * * @return true if we were able to find the image in the cache, false otherwise. */ private static final boolean showCachedImage(ImageView view, CallerInfo ci) { if ((ci != null) && ci.isCachedPhotoCurrent) { if (ci.cachedPhoto != null) { showImage(view, ci.cachedPhoto); } else { showImage(view, R.drawable.picture_unknown); } return true; } return false; } /** Helper function to display the resource in the imageview AND ensure its visibility.*/ private static final void showImage(ImageView view, int resource) { showImage(view, view.getContext().getResources().getDrawable(resource)); } private static final void showImage(ImageView view, Bitmap bitmap) { showImage(view, new BitmapDrawable(view.getContext().getResources(), bitmap)); } /** Helper function to display the drawable in the imageview AND ensure its visibility.*/ private static final void showImage(ImageView view, Drawable drawable) { Resources res = view.getContext().getResources(); Drawable current = (Drawable) view.getTag(); if (current == null) { if (DBG) log("Start fade-in animation for " + view); view.setImageDrawable(drawable); AnimationUtils.Fade.show(view); view.setTag(drawable); } else { AnimationUtils.startCrossFade(view, current, drawable); view.setVisibility(View.VISIBLE); } } /** * Returns the special card title used in emergency callback mode (ECM), * which shows your own phone number. */ private String getECMCardTitle(Context context, Phone phone) { String rawNumber = phone.getLine1Number(); // may be null or empty String formattedNumber; if (!TextUtils.isEmpty(rawNumber)) { formattedNumber = PhoneNumberUtils.formatNumber(rawNumber); } else { formattedNumber = context.getString(R.string.unknown); } String titleFormat = context.getString(R.string.card_title_my_phone_number); return String.format(titleFormat, formattedNumber); } /** * Updates the "Call type" label, based on the current foreground call. * This is a special label and/or branding we display for certain * kinds of calls. * * (So far, this is used only for SIP calls, which get an * "Internet call" label. TODO: But eventually, the telephony * layer might allow each pluggable "provider" to specify a string * and/or icon to be displayed here.) */ private void updateCallTypeLabel(Call call) { int phoneType = (call != null) ? call.getPhone().getPhoneType() : PhoneConstants.PHONE_TYPE_NONE; if (phoneType == PhoneConstants.PHONE_TYPE_SIP) { mCallTypeLabel.setVisibility(View.VISIBLE); mCallTypeLabel.setText(R.string.incall_call_type_label_sip); mCallTypeLabel.setTextColor(mTextColorCallTypeSip); // If desired, we could also display a "badge" next to the label, as follows: // mCallTypeLabel.setCompoundDrawablesWithIntrinsicBounds( // callTypeSpecificBadge, null, null, null); // mCallTypeLabel.setCompoundDrawablePadding((int) (mDensity * 6)); } else if (call != null && mApplication.notifier.isCallForwarded(call)) { mCallTypeLabel.setVisibility(View.VISIBLE); mCallTypeLabel.setText(R.string.incall_call_type_label_forwarded); mCallTypeLabel.setTextColor(mTextColorDefault); } else { mCallTypeLabel.setVisibility(View.GONE); } } /** * Updates the "social status" label with the specified text and * (optional) badge. */ /*private void updateSocialStatus(String socialStatusText, Drawable socialStatusBadge, Call call) { // The socialStatus field is *only* visible while an incoming call // is ringing, never in any other call state. if ((socialStatusText != null) && (call != null) && call.isRinging() && !call.isGeneric()) { mSocialStatus.setVisibility(View.VISIBLE); mSocialStatus.setText(socialStatusText); mSocialStatus.setCompoundDrawablesWithIntrinsicBounds( socialStatusBadge, null, null, null); mSocialStatus.setCompoundDrawablePadding((int) (mDensity * 6)); } else { mSocialStatus.setVisibility(View.GONE); } }*/ /** * Hides the top-level UI elements of the call card: The "main * call card" element representing the current active or ringing call, * and also the info areas for "ongoing" or "on hold" calls in some * states. * * This is intended to be used in special states where the normal * in-call UI is totally replaced by some other UI, like OTA mode on a * CDMA device. * * To bring back the regular CallCard UI, just re-run the normal * updateState() call sequence. */ public void hideCallCardElements() { mPrimaryCallInfo.setVisibility(View.GONE); mSecondaryCallInfo.setVisibility(View.GONE); } /* * Updates the hint (like "Rotate to answer") that we display while * the user is dragging the incoming call RotarySelector widget. */ /* package */ void setIncomingCallWidgetHint(int hintTextResId, int hintColorResId) { mIncomingCallWidgetHintTextResId = hintTextResId; mIncomingCallWidgetHintColorResId = hintColorResId; } // Accessibility event support. // Since none of the CallCard elements are focusable, we need to manually // fill in the AccessibilityEvent here (so that the name / number / etc will // get pronounced by a screen reader, for example.) @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { dispatchPopulateAccessibilityEvent(event, mName); dispatchPopulateAccessibilityEvent(event, mPhoneNumber); return true; } dispatchPopulateAccessibilityEvent(event, mCallStateLabel); dispatchPopulateAccessibilityEvent(event, mPhoto); dispatchPopulateAccessibilityEvent(event, mName); dispatchPopulateAccessibilityEvent(event, mPhoneNumber); dispatchPopulateAccessibilityEvent(event, mLabel); // dispatchPopulateAccessibilityEvent(event, mSocialStatus); if (mSecondaryCallName != null) { dispatchPopulateAccessibilityEvent(event, mSecondaryCallName); } if (mSecondaryCallPhoto != null) { dispatchPopulateAccessibilityEvent(event, mSecondaryCallPhoto); } return true; } private void dispatchPopulateAccessibilityEvent(AccessibilityEvent event, View view) { List<CharSequence> eventText = event.getText(); int size = eventText.size(); view.dispatchPopulateAccessibilityEvent(event); // if no text added write null to keep relative position if (size == eventText.size()) { eventText.add(null); } } // Debugging / testing code private static void log(String msg) { Log.d(LOG_TAG, msg); } }
true
true
private void updateDisplayForPerson(CallerInfo info, int presentation, boolean isTemporary, Call call, Connection conn) { if (DBG) log("updateDisplayForPerson(" + info + ")\npresentation:" + presentation + " isTemporary:" + isTemporary); // inform the state machine that we are displaying a photo. mPhotoTracker.setPhotoRequest(info); mPhotoTracker.setPhotoState(ContactsAsyncHelper.ImageTracker.DISPLAY_IMAGE); // The actual strings we're going to display onscreen: boolean displayNameIsNumber = false; String displayName; String displayNumber = null; String label = null; Uri personUri = null; // String socialStatusText = null; // Drawable socialStatusBadge = null; if (info != null) { // It appears that there is a small change in behaviour with the // PhoneUtils' startGetCallerInfo whereby if we query with an // empty number, we will get a valid CallerInfo object, but with // fields that are all null, and the isTemporary boolean input // parameter as true. // In the past, we would see a NULL callerinfo object, but this // ends up causing null pointer exceptions elsewhere down the // line in other cases, so we need to make this fix instead. It // appears that this was the ONLY call to PhoneUtils // .getCallerInfo() that relied on a NULL CallerInfo to indicate // an unknown contact. // Currently, info.phoneNumber may actually be a SIP address, and // if so, it might sometimes include the "sip:" prefix. That // prefix isn't really useful to the user, though, so strip it off // if present. (For any other URI scheme, though, leave the // prefix alone.) // TODO: It would be cleaner for CallerInfo to explicitly support // SIP addresses instead of overloading the "phoneNumber" field. // Then we could remove this hack, and instead ask the CallerInfo // for a "user visible" form of the SIP address. String number = info.phoneNumber; if ((number != null) && number.startsWith("sip:")) { number = number.substring(4); } if (TextUtils.isEmpty(info.name)) { // No valid "name" in the CallerInfo, so fall back to // something else. // (Typically, we promote the phone number up to the "name" slot // onscreen, and possibly display a descriptive string in the // "number" slot.) if (TextUtils.isEmpty(number)) { // No name *or* number! Display a generic "unknown" string // (or potentially some other default based on the presentation.) displayName = PhoneUtils.getPresentationString(getContext(), presentation); if (DBG) log(" ==> no name *or* number! displayName = " + displayName); } else if (presentation != PhoneConstants.PRESENTATION_ALLOWED) { // This case should never happen since the network should never send a phone # // AND a restricted presentation. However we leave it here in case of weird // network behavior displayName = PhoneUtils.getPresentationString(getContext(), presentation); if (DBG) log(" ==> presentation not allowed! displayName = " + displayName); } else if (!TextUtils.isEmpty(info.cnapName)) { // No name, but we do have a valid CNAP name, so use that. displayName = info.cnapName; info.name = info.cnapName; displayNumber = number; if (DBG) log(" ==> cnapName available: displayName '" + displayName + "', displayNumber '" + displayNumber + "'"); } else { // No name; all we have is a number. This is the typical // case when an incoming call doesn't match any contact, // or if you manually dial an outgoing number using the // dialpad. // Promote the phone number up to the "name" slot: displayName = number; displayNameIsNumber = true; // ...and use the "number" slot for a geographical description // string if available (but only for incoming calls.) if ((conn != null) && (conn.isIncoming())) { // TODO (CallerInfoAsyncQuery cleanup): Fix the CallerInfo // query to only do the geoDescription lookup in the first // place for incoming calls. displayNumber = info.geoDescription; // may be null } if (DBG) log(" ==> no name; falling back to number: displayName '" + displayName + "', displayNumber '" + displayNumber + "'"); } } else { // We do have a valid "name" in the CallerInfo. Display that // in the "name" slot, and the phone number in the "number" slot. if (presentation != PhoneConstants.PRESENTATION_ALLOWED) { // This case should never happen since the network should never send a name // AND a restricted presentation. However we leave it here in case of weird // network behavior displayName = PhoneUtils.getPresentationString(getContext(), presentation); if (DBG) log(" ==> valid name, but presentation not allowed!" + " displayName = " + displayName); } else { displayName = info.name; displayNumber = number; label = info.phoneLabel; if (DBG) log(" ==> name is present in CallerInfo: displayName '" + displayName + "', displayNumber '" + displayNumber + "'"); } } personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, info.person_id); if (DBG) log("- got personUri: '" + personUri + "', based on info.person_id: " + info.person_id); } else { displayName = PhoneUtils.getPresentationString(getContext(), presentation); } boolean updateNameAndNumber = true; // If the new info is just a phone number, check to make sure it's not less // information than what's already being displayed. if (displayNameIsNumber) { // If the new number is the same as the number already displayed, ignore it // because that means we're also already displaying a name for it. // If the new number is the same as the name currently being displayed, only // display if the new number is longer (ie, has formatting). String visiblePhoneNumber = null; if (mPhoneNumber.getVisibility() == View.VISIBLE) { visiblePhoneNumber = mPhoneNumber.getText().toString(); } if ((visiblePhoneNumber != null && PhoneNumberUtils.compare(visiblePhoneNumber, displayName)) || (PhoneNumberUtils.compare(mName.getText().toString(), displayName) && displayName.length() < mName.length())) { if (DBG) log("chose not to update display {" + mName.getText() + ", " + visiblePhoneNumber + "} with number " + displayName); updateNameAndNumber = false; } } if (updateNameAndNumber) { if (call.isGeneric()) { mName.setText(R.string.card_title_in_call); } else { mName.setText(displayName); } mName.setVisibility(View.VISIBLE); if (displayNumber != null && !call.isGeneric()) { mPhoneNumber.setText(displayNumber); mPhoneNumber.setVisibility(View.VISIBLE); } else { mPhoneNumber.setVisibility(View.GONE); } if (label != null && !call.isGeneric()) { mLabel.setText(label); mLabel.setVisibility(View.VISIBLE); } else { mLabel.setVisibility(View.GONE); } } // Update mPhoto // if the temporary flag is set, we know we'll be getting another call after // the CallerInfo has been correctly updated. So, we can skip the image // loading until then. // If the photoResource is filled in for the CallerInfo, (like with the // Emergency Number case), then we can just set the photo image without // requesting for an image load. Please refer to CallerInfoAsyncQuery.java // for cases where CallerInfo.photoResource may be set. We can also avoid // the image load step if the image data is cached. if (isTemporary && (info == null || !info.isCachedPhotoCurrent)) { mPhoto.setTag(null); mPhoto.setVisibility(View.INVISIBLE); } else if (info != null && info.photoResource != 0){ showImage(mPhoto, info.photoResource); } else if (!showCachedImage(mPhoto, info)) { if (personUri == null) { Log.w(LOG_TAG, "personPri is null. Just use Unknown picture."); showImage(mPhoto, R.drawable.picture_unknown); } else if (personUri.equals(mLoadingPersonUri)) { if (DBG) { log("The requested Uri (" + personUri + ") is being loaded already." + " Ignoret the duplicate load request."); } } else { // Remember which person's photo is being loaded right now so that we won't issue // unnecessary load request multiple times, which will mess up animation around // the contact photo. mLoadingPersonUri = personUri; // Forget the drawable previously used. mPhoto.setTag(null); // Show empty screen for a moment. mPhoto.setVisibility(View.INVISIBLE); // Load the image with a callback to update the image state. // When the load is finished, onImageLoadComplete() will be called. ContactsAsyncHelper.startObtainPhotoAsync(TOKEN_UPDATE_PHOTO_FOR_CALL_STATE, getContext(), personUri, this, new AsyncLoadCookie(mPhoto, info, call)); // If the image load is too slow, we show a default avatar icon afterward. // If it is fast enough, this message will be canceled on onImageLoadComplete(). mHandler.removeMessages(MESSAGE_SHOW_UNKNOWN_PHOTO); mHandler.sendEmptyMessageDelayed(MESSAGE_SHOW_UNKNOWN_PHOTO, MESSAGE_DELAY); } } // If the phone call is on hold, show it with darker status. // Right now we achieve it by overlaying opaque View. // Note: See also layout file about why so and what is the other possibilities. if (call.getState() == Call.State.HOLDING) { AnimationUtils.Fade.show(mPhotoDimEffect); } else { AnimationUtils.Fade.hide(mPhotoDimEffect, View.GONE); } // Other text fields: updateCallTypeLabel(call); // updateSocialStatus(socialStatusText, socialStatusBadge, call); // Currently unused // display Phone Location if(mContext.getResources().getConfiguration().locale.getCountry().equals("CN")||mContext.getResources().getConfiguration().locale.getCountry().equals("TW")) { String PhoneLocationStr=PhoneLocation.getCityFromPhone(info.phoneNumber, mContext); setLocationText(label, PhoneLocationStr); } else { info.updateGeoDescription(mContext, info.phoneNumber); setLocationText(label, info.geoDescription); } }
private void updateDisplayForPerson(CallerInfo info, int presentation, boolean isTemporary, Call call, Connection conn) { if (DBG) log("updateDisplayForPerson(" + info + ")\npresentation:" + presentation + " isTemporary:" + isTemporary); // inform the state machine that we are displaying a photo. mPhotoTracker.setPhotoRequest(info); mPhotoTracker.setPhotoState(ContactsAsyncHelper.ImageTracker.DISPLAY_IMAGE); // The actual strings we're going to display onscreen: boolean displayNameIsNumber = false; String displayName; String displayNumber = null; String label = null; Uri personUri = null; // String socialStatusText = null; // Drawable socialStatusBadge = null; if (info != null) { // It appears that there is a small change in behaviour with the // PhoneUtils' startGetCallerInfo whereby if we query with an // empty number, we will get a valid CallerInfo object, but with // fields that are all null, and the isTemporary boolean input // parameter as true. // In the past, we would see a NULL callerinfo object, but this // ends up causing null pointer exceptions elsewhere down the // line in other cases, so we need to make this fix instead. It // appears that this was the ONLY call to PhoneUtils // .getCallerInfo() that relied on a NULL CallerInfo to indicate // an unknown contact. // Currently, info.phoneNumber may actually be a SIP address, and // if so, it might sometimes include the "sip:" prefix. That // prefix isn't really useful to the user, though, so strip it off // if present. (For any other URI scheme, though, leave the // prefix alone.) // TODO: It would be cleaner for CallerInfo to explicitly support // SIP addresses instead of overloading the "phoneNumber" field. // Then we could remove this hack, and instead ask the CallerInfo // for a "user visible" form of the SIP address. String number = info.phoneNumber; if ((number != null) && number.startsWith("sip:")) { number = number.substring(4); } if (TextUtils.isEmpty(info.name)) { // No valid "name" in the CallerInfo, so fall back to // something else. // (Typically, we promote the phone number up to the "name" slot // onscreen, and possibly display a descriptive string in the // "number" slot.) if (TextUtils.isEmpty(number)) { // No name *or* number! Display a generic "unknown" string // (or potentially some other default based on the presentation.) displayName = PhoneUtils.getPresentationString(getContext(), presentation); if (DBG) log(" ==> no name *or* number! displayName = " + displayName); } else if (presentation != PhoneConstants.PRESENTATION_ALLOWED) { // This case should never happen since the network should never send a phone # // AND a restricted presentation. However we leave it here in case of weird // network behavior displayName = PhoneUtils.getPresentationString(getContext(), presentation); if (DBG) log(" ==> presentation not allowed! displayName = " + displayName); } else if (!TextUtils.isEmpty(info.cnapName)) { // No name, but we do have a valid CNAP name, so use that. displayName = info.cnapName; info.name = info.cnapName; displayNumber = number; if (DBG) log(" ==> cnapName available: displayName '" + displayName + "', displayNumber '" + displayNumber + "'"); } else { // No name; all we have is a number. This is the typical // case when an incoming call doesn't match any contact, // or if you manually dial an outgoing number using the // dialpad. // Promote the phone number up to the "name" slot: displayName = number; displayNameIsNumber = true; // ...and use the "number" slot for a geographical description // string if available (but only for incoming calls.) if ((conn != null) && (conn.isIncoming())) { // TODO (CallerInfoAsyncQuery cleanup): Fix the CallerInfo // query to only do the geoDescription lookup in the first // place for incoming calls. displayNumber = info.geoDescription; // may be null } if (DBG) log(" ==> no name; falling back to number: displayName '" + displayName + "', displayNumber '" + displayNumber + "'"); } } else { // We do have a valid "name" in the CallerInfo. Display that // in the "name" slot, and the phone number in the "number" slot. if (presentation != PhoneConstants.PRESENTATION_ALLOWED) { // This case should never happen since the network should never send a name // AND a restricted presentation. However we leave it here in case of weird // network behavior displayName = PhoneUtils.getPresentationString(getContext(), presentation); if (DBG) log(" ==> valid name, but presentation not allowed!" + " displayName = " + displayName); } else { displayName = info.name; displayNumber = number; label = info.phoneLabel; if (DBG) log(" ==> name is present in CallerInfo: displayName '" + displayName + "', displayNumber '" + displayNumber + "'"); } } personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, info.person_id); if (DBG) log("- got personUri: '" + personUri + "', based on info.person_id: " + info.person_id); } else { displayName = PhoneUtils.getPresentationString(getContext(), presentation); } boolean updateNameAndNumber = true; // If the new info is just a phone number, check to make sure it's not less // information than what's already being displayed. if (displayNameIsNumber) { // If the new number is the same as the number already displayed, ignore it // because that means we're also already displaying a name for it. // If the new number is the same as the name currently being displayed, only // display if the new number is longer (ie, has formatting). String visiblePhoneNumber = null; if (mPhoneNumber.getVisibility() == View.VISIBLE) { visiblePhoneNumber = mPhoneNumber.getText().toString(); } if ((visiblePhoneNumber != null && PhoneNumberUtils.compare(visiblePhoneNumber, displayName)) || (PhoneNumberUtils.compare(mName.getText().toString(), displayName) && displayName.length() < mName.length())) { if (DBG) log("chose not to update display {" + mName.getText() + ", " + visiblePhoneNumber + "} with number " + displayName); updateNameAndNumber = false; } } if (updateNameAndNumber) { if (call.isGeneric()) { mName.setText(R.string.card_title_in_call); } else { mName.setText(displayName); } mName.setVisibility(View.VISIBLE); if (displayNumber != null && !call.isGeneric()) { mPhoneNumber.setText(displayNumber); mPhoneNumber.setVisibility(View.VISIBLE); } else { mPhoneNumber.setVisibility(View.GONE); } if (label != null && !call.isGeneric()) { mLabel.setText(label); mLabel.setVisibility(View.VISIBLE); } else { mLabel.setVisibility(View.GONE); } } // Update mPhoto // if the temporary flag is set, we know we'll be getting another call after // the CallerInfo has been correctly updated. So, we can skip the image // loading until then. // If the photoResource is filled in for the CallerInfo, (like with the // Emergency Number case), then we can just set the photo image without // requesting for an image load. Please refer to CallerInfoAsyncQuery.java // for cases where CallerInfo.photoResource may be set. We can also avoid // the image load step if the image data is cached. if (isTemporary && (info == null || !info.isCachedPhotoCurrent)) { mPhoto.setTag(null); mPhoto.setVisibility(View.INVISIBLE); } else if (info != null && info.photoResource != 0){ showImage(mPhoto, info.photoResource); } else if (!showCachedImage(mPhoto, info)) { if (personUri == null) { Log.w(LOG_TAG, "personPri is null. Just use Unknown picture."); showImage(mPhoto, R.drawable.picture_unknown); } else if (personUri.equals(mLoadingPersonUri)) { if (DBG) { log("The requested Uri (" + personUri + ") is being loaded already." + " Ignoret the duplicate load request."); } } else { // Remember which person's photo is being loaded right now so that we won't issue // unnecessary load request multiple times, which will mess up animation around // the contact photo. mLoadingPersonUri = personUri; // Forget the drawable previously used. mPhoto.setTag(null); // Show empty screen for a moment. mPhoto.setVisibility(View.INVISIBLE); // Load the image with a callback to update the image state. // When the load is finished, onImageLoadComplete() will be called. ContactsAsyncHelper.startObtainPhotoAsync(TOKEN_UPDATE_PHOTO_FOR_CALL_STATE, getContext(), personUri, this, new AsyncLoadCookie(mPhoto, info, call)); // If the image load is too slow, we show a default avatar icon afterward. // If it is fast enough, this message will be canceled on onImageLoadComplete(). mHandler.removeMessages(MESSAGE_SHOW_UNKNOWN_PHOTO); mHandler.sendEmptyMessageDelayed(MESSAGE_SHOW_UNKNOWN_PHOTO, MESSAGE_DELAY); } } // If the phone call is on hold, show it with darker status. // Right now we achieve it by overlaying opaque View. // Note: See also layout file about why so and what is the other possibilities. if (call.getState() == Call.State.HOLDING) { AnimationUtils.Fade.show(mPhotoDimEffect); } else { AnimationUtils.Fade.hide(mPhotoDimEffect, View.GONE); } // Other text fields: updateCallTypeLabel(call); // updateSocialStatus(socialStatusText, socialStatusBadge, call); // Currently unused // display Phone Location if(TextUtils.isEmpty(info.phoneNumber)) return; if(mContext.getResources().getConfiguration().locale.getCountry().equals("CN")||mContext.getResources().getConfiguration().locale.getCountry().equals("TW")) { String PhoneLocationStr=PhoneLocation.getCityFromPhone(info.phoneNumber, mContext); setLocationText(label, PhoneLocationStr); } else { info.updateGeoDescription(mContext, info.phoneNumber); setLocationText(label, info.geoDescription); } }
diff --git a/src/common/com/kaijin/InventoryStocker/TileEntityInventoryStocker.java b/src/common/com/kaijin/InventoryStocker/TileEntityInventoryStocker.java index 09102d2..f5eafd1 100644 --- a/src/common/com/kaijin/InventoryStocker/TileEntityInventoryStocker.java +++ b/src/common/com/kaijin/InventoryStocker/TileEntityInventoryStocker.java @@ -1,1509 +1,1509 @@ /* Inventory Stocker * Copyright (c) 2012 Yancarlo Ramsey and CJ Bowman * Licensed as open source with restrictions. Please see attached LICENSE.txt. */ package com.kaijin.InventoryStocker; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.lang.reflect.*; import com.kaijin.InventoryStocker.*; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Side; import cpw.mods.fml.common.asm.SideOnly; import cpw.mods.fml.common.network.Player; import net.minecraft.src.*; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.common.ISidedInventory; public class TileEntityInventoryStocker extends TileEntity implements IInventory, ISidedInventory { private ItemStack[] contents = new ItemStack[this.getSizeInventory()]; private ItemStack remoteSnapshot[]; private ItemStack extendedChestSnapshot[]; private boolean guiTakeSnapshot = false; private boolean guiClearSnapshot = false; private boolean tileLoaded = false; private boolean previousPoweredState = false; private boolean lightState = false; private boolean hasSnapshot = false; private boolean serverHasSnapshot = false; private boolean lastSnapshotState = false; private boolean reactorWorkaround = false; private int reactorWidth = 0; private TileEntity lastTileEntity = null; private TileEntity tileFrontFace = null; private TileEntityChest extendedChest = null; private int remoteNumSlots = 0; private String targetTileName = "none"; private List<EntityPlayerMP> remoteUsers = new ArrayList<EntityPlayerMP>(); final String classnameIC2ReactorCore = "TileEntityNuclearReactor"; final String classnameIC2ReactorChamber = "TileEntityReactorChamber"; //How long (in ticks) to wait between stocking operations private int tickDelay = 9; private int tickTime = 0; private boolean[] doorState = new boolean[6]; @Override public boolean canUpdate() { return true; } // public TileEntityInventoryStocker() // { // contents = new ItemStack [this.getSizeInventory()]; // if (Utils.isDebug()) System.out.println("TileEntityInventoryStocker().clearSnapshot()"); //// clearSnapshot(); // doorState = new boolean[6]; // } @SideOnly(Side.CLIENT) public void setSnapshotState(boolean state) { this.serverHasSnapshot = state; } @SideOnly(Side.CLIENT) public boolean serverSnapshotState() { return serverHasSnapshot; } public void entityOpenList(List crafters) { if (Utils.isDebug()) System.out.println("entityOpenList"); this.remoteUsers = crafters; } public void recvSnapshotRequest(boolean state) { if(state) { if (Utils.isDebug()) System.out.println("GUI: take snapshot request"); guiTakeSnapshot = true; } else { if (Utils.isDebug()) System.out.println("GUI: clear snapshot request"); guiClearSnapshot = true; } } /** * Returns current value of hasSnapshot * @return */ public boolean validSnapshot() { String s = new Boolean(hasSnapshot).toString(); if (Utils.isDebug()) System.out.println("tile.validSnapshot(): " + s); return hasSnapshot; } private Packet250CustomPayload createSnapshotPacket() { String s = new Boolean(hasSnapshot).toString(); if (Utils.isDebug()) System.out.println("createSnapshotPacket: " + s); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); DataOutputStream data = new DataOutputStream(bytes); try { data.writeInt(0); data.writeInt(this.xCoord); data.writeInt(this.yCoord); data.writeInt(this.zCoord); data.writeBoolean(hasSnapshot); } catch(IOException e) { e.printStackTrace(); } Packet250CustomPayload packet = new Packet250CustomPayload(); packet.channel = "InventoryStocker"; // CHANNEL MAX 16 CHARS packet.data = bytes.toByteArray(); packet.length = packet.data.length; return packet; } /** * Sends a snapshot state to the client that just opened the GUI. * @param EntityPlayer */ public void sendSnapshotStateClient(EntityPlayerMP player) { String s = new Boolean(hasSnapshot).toString(); if (Utils.isDebug()) System.out.println("sendSnapshotStateClient: " + s); Packet250CustomPayload packet = createSnapshotPacket(); CommonProxy.sendPacketToPlayer(player, packet); } /** * Send snapshot state to all clients in the GUI open list. */ private void sendSnapshotStateClients() { String s = new Boolean(hasSnapshot).toString(); if (Utils.isDebug()) System.out.println("sendSnapshotStateClients(): " + s); Packet250CustomPayload packet = createSnapshotPacket(); if (this.remoteUsers != null) { for (int i = 0; i < this.remoteUsers.size(); ++i) { String n = remoteUsers.get(i).username; if (Utils.isDebug()) System.out.println("sendSnapshotStateClients.name: " + n); CommonProxy.sendPacketToPlayer(remoteUsers.get(i), packet); } } } /** * Sends a snapshot state request to the server. * @param state */ private void sendSnapshotRequestServer(boolean state) { if (Utils.isDebug()) System.out.println("sendSnapshotRequestServer"); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); DataOutputStream data = new DataOutputStream(bytes); try { data.writeInt(0); data.writeInt(this.xCoord); data.writeInt(this.yCoord); data.writeInt(this.zCoord); data.writeBoolean(state); } catch(IOException e) { e.printStackTrace(); } Packet250CustomPayload packet = new Packet250CustomPayload(); packet.channel = "InventoryStocker"; // CHANNEL MAX 16 CHARS packet.data = bytes.toByteArray(); packet.length = packet.data.length; CommonProxy.sendPacketToServer(packet); } public void guiTakeSnapshot() { if(InventoryStocker.proxy.isClient(worldObj)) { if (Utils.isDebug()) System.out.println("guiTakeSnapshot.sendSnapshotRequestServer"); sendSnapshotRequestServer(true); } else { guiTakeSnapshot = true; } } public void guiClearSnapshot() { if(InventoryStocker.proxy.isClient(worldObj)) { if (Utils.isDebug()) System.out.println("guiClearSnapshot.sendSnapshotRequestServer"); sendSnapshotRequestServer(false); } else { guiClearSnapshot = true; } } public void clearSnapshot() { lastTileEntity = null; hasSnapshot = false; targetTileName = "none"; remoteSnapshot = null; remoteNumSlots = 0; extendedChest = null; extendedChestSnapshot = null; reactorWorkaround = false; reactorWidth = 0; if (Utils.isDebug()) System.out.println("clearSnapshot()"); // if (InventoryStocker.proxy.isServer()) // { String s = new Boolean(hasSnapshot).toString(); if (Utils.isDebug()) System.out.println("clearSnapshot: " + s); sendSnapshotStateClients(); // } } public void onUpdate() { if(!InventoryStocker.proxy.isClient(worldObj)) { if (checkInvalidSnapshot() && validSnapshot()) { if (Utils.isDebug()) System.out.println("onUpdate.!isClient.checkInvalidSnapshot.clearSnapshot"); clearSnapshot(); } String s = new Boolean(hasSnapshot).toString(); if (Utils.isDebug()) System.out.println("onUpdate.!isClient.sendSnapshotStateClients: " + s); sendSnapshotStateClients(); } if (!InventoryStocker.proxy.isServer()) { // Check adjacent blocks for tubes or pipes and update list accordingly updateDoorStates(); } } private void updateDoorStates() { doorState[0] = findTubeOrPipeAt(xCoord, yCoord-1, zCoord); doorState[1] = findTubeOrPipeAt(xCoord, yCoord+1, zCoord); doorState[2] = findTubeOrPipeAt(xCoord, yCoord, zCoord-1); doorState[3] = findTubeOrPipeAt(xCoord, yCoord, zCoord+1); doorState[4] = findTubeOrPipeAt(xCoord-1, yCoord, zCoord); doorState[5] = findTubeOrPipeAt(xCoord+1, yCoord, zCoord); } /** * @param x * @param y * @param z * @return boolean * <pre> * RedPower connections: * * Meta Tile Entity * 8 eloraam.machine.TileTube * 9 eloraam.machine.TileRestrictTube * 10 eloraam.machine.TileRedstoneTube * * All are block class: eloraam.base.BlockMicro * * Buildcraft connections: * * Block class: buildcraft.transport.BlockGenericPipe * * Unable to distinguish water and power pipes from transport pipes. * Would Buildcraft API help?</pre> */ private boolean findTubeOrPipeAt(int x, int y, int z) { int ID = worldObj.getBlockId(x, y, z); if (ID > 0) { String type = Block.blocksList[ID].getClass().getName(); if (type.endsWith("BlockGenericPipe")) { /* if (Utils.isDebug()) { try { TileEntity tile = worldObj.getBlockTileEntity(x, y, z); Class cls = tile.getClass(); Field fldpipe = cls.getDeclaredField("pipe"); Object pipeobj = fldpipe.get(tile); Class pipecls = pipeobj.getClass(); Method methlist[] = pipecls.getDeclaredMethods(); Field fieldlist[] = pipecls.getDeclaredFields(); Class[] intfs = pipecls.getInterfaces(); System.out.println("***METHODS***"); for (int i = 0; i < methlist.length; i++) { Method m = methlist[i]; System.out.println("name = " + m.getName()); // System.out.println("decl class = " + m.getDeclaringClass()); // this will not change between different methods of the same class Class pvec[] = m.getParameterTypes(); for (int j = 0; j < pvec.length; j++) { System.out.println("param #" + j + " " + pvec[j]); } System.out.println("return type = " + m.getReturnType()); System.out.println("-----"); } System.out.println("***FIELDS***"); for (int i = 0; i < fieldlist.length; i++) { Field fld = fieldlist[i]; System.out.println("name = " + fld.getName()); // System.out.println("decl class = " + fld.getDeclaringClass()); // this will not change between different fields of the same class System.out.println("type = " + fld.getType()); int mod = fld.getModifiers(); System.out.println("modifiers = " + Modifier.toString(mod)); System.out.println("-----"); } System.out.println("***INTERFACES***"); for (int i = 0; i < intfs.length; i++) { System.out.println(intfs[i]); } } catch (Throwable e) { System.err.println(e); } } */ // Buildcraft Pipe boolean founditempipe = false; try { TileEntity tile = worldObj.getBlockTileEntity(x, y, z); Class cls = tile.getClass(); Field fldpipe = cls.getDeclaredField("pipe"); Object pipe = fldpipe.get(tile); Class pipecls = Class.forName("buildcraft.transport.Pipe"); // TODO Correct the class name? Field fldtransport = pipecls.getDeclaredField("transport"); Object transport = fldtransport.get(pipe); String transportType = transport.getClass().getName(); if (transportType.endsWith("Items")) { // then this door should be open founditempipe = true; } } catch (Throwable e) { System.err.println(e); } return founditempipe; } else if (type.endsWith("eloraam.base.BlockMicro")) { // RedPower Tube test int m = worldObj.getBlockMetadata(x, y, z); return (m >= 8) && (m <= 10); } } return false; } /** * Return whether the neighboring block is a tube or pipe. * @param i * @return boolean */ public boolean doorOpenOnSide(int i) { return doorState[i]; } public int getStartInventorySide(int i) { // Sides (0-5) are: Front, Back, Top, Bottom, Right, Left int side = getRotatedSideFromMetadata(i); if (side == 1) { return 9; // access output section, 9-17 } return 0; // access input section, 0-8 } public int getSizeInventorySide(int i) { // Sides (0-5) are: Top, Bottom, Front, Back, Left, Right int side = getRotatedSideFromMetadata(i); if (side == 0) { return 0; // Front has no inventory access } return 9; } public int getRotatedSideFromMetadata(int side) { int dir = worldObj.getBlockMetadata(xCoord, yCoord, zCoord) & 7; return Utils.lookupRotatedSide(side, dir); } public int getBlockIDAtFace(int i) { int x = xCoord; int y = yCoord; int z = zCoord; switch (i) { case 0: y--; break; case 1: y++; break; case 2: z--; break; case 3: z++; break; case 4: x--; break; case 5: x++; break; default: return 0; } return worldObj.getBlockId(x, y, z); } public TileEntity getTileAtFrontFace() { int dir = worldObj.getBlockMetadata(xCoord, yCoord, zCoord) & 7; /** * 0: -Y (bottom side) * 1: +Y (top side) * 2: -Z (west side) * 3: +Z (east side) * 4: -X (north side) * 5: +x (south side) */ int x = xCoord; int y = yCoord; int z = zCoord; switch (dir) { case 0: y--; break; case 1: y++; break; case 2: z--; break; case 3: z++; break; case 4: x--; break; case 5: x++; break; default: return null; } return worldObj.getBlockTileEntity(x, y, z); } public int getSizeInventory() { return 18; } public ItemStack getStackInSlot(int i) { return contents[i]; } public ItemStack decrStackSize(int par1, int par2) { if (this.contents[par1] != null) { ItemStack var3; if (this.contents[par1].stackSize <= par2) { var3 = this.contents[par1]; this.contents[par1] = null; this.onInventoryChanged(); return var3; } else { var3 = this.contents[par1].splitStack(par2); if (this.contents[par1].stackSize == 0) { this.contents[par1] = null; } this.onInventoryChanged(); return var3; } } else { return null; } } public ItemStack getStackInSlotOnClosing(int var1) { if (this.contents[var1] == null) { return null; } ItemStack stack = this.contents[var1]; this.contents[var1] = null; return stack; } public void setInventorySlotContents(int i, ItemStack itemstack) { this.contents[i] = itemstack; if (itemstack != null && itemstack.stackSize > getInventoryStackLimit()) { itemstack.stackSize = getInventoryStackLimit(); } } public String getInvName() { return "Stocker"; } /** * Reads a tile entity from NBT. */ public void readFromNBT(NBTTagCompound nbttagcompound) { if(!InventoryStocker.proxy.isClient(worldObj)) { super.readFromNBT(nbttagcompound); // Read extra NBT stuff here targetTileName = nbttagcompound.getString("targetTileName"); remoteNumSlots = nbttagcompound.getInteger("remoteSnapshotSize"); reactorWorkaround = nbttagcompound.getBoolean("reactorWorkaround"); reactorWidth = nbttagcompound.getInteger("reactorWidth"); boolean extendedChestFlag = nbttagcompound.getBoolean("extendedChestFlag"); if (Utils.isDebug()) System.out.println("ReadNBT: "+targetTileName+" remoteInvSize:"+remoteNumSlots); NBTTagList nbttaglist = nbttagcompound.getTagList("Items"); NBTTagList nbttagremote = nbttagcompound.getTagList("remoteSnapshot"); contents = new ItemStack[this.getSizeInventory()]; remoteSnapshot = null; if (remoteNumSlots != 0) { remoteSnapshot = new ItemStack[remoteNumSlots]; } // Our inventory for (int i = 0; i < nbttaglist.tagCount(); ++i) { NBTTagCompound nbttagcompound1 = (NBTTagCompound)nbttaglist.tagAt(i); int j = nbttagcompound1.getByte("Slot") & 255; if (j >= 0 && j < contents.length) { contents[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1); } } // Remote inventory snapshot if (Utils.isDebug()) System.out.println("ReadNBT tagRemoteCount: " + nbttagremote.tagCount()); if (nbttagremote.tagCount() != 0) { for (int i = 0; i < nbttagremote.tagCount(); ++i) { NBTTagCompound remoteSnapshot1 = (NBTTagCompound)nbttagremote.tagAt(i); int j = remoteSnapshot1.getByte("Slot") & 255; if (j >= 0 && j < remoteSnapshot.length) { remoteSnapshot[j] = ItemStack.loadItemStackFromNBT(remoteSnapshot1); if (Utils.isDebug()) System.out.println("ReadNBT Remote Slot: " + j + " ItemID: " + remoteSnapshot[j].itemID); } } } // Double chest second inventory snapshot if (extendedChestFlag) { extendedChestSnapshot = new ItemStack[remoteNumSlots]; NBTTagList nbttagextended = nbttagcompound.getTagList("extendedSnapshot"); if (nbttagextended.tagCount() != 0) { for (int i = 0; i < nbttagextended.tagCount(); ++i) { NBTTagCompound extSnapshot1 = (NBTTagCompound)nbttagextended.tagAt(i); int j = extSnapshot1.getByte("Slot") & 255; if (j >= 0 && j < extendedChestSnapshot.length) { extendedChestSnapshot[j] = ItemStack.loadItemStackFromNBT(extSnapshot1); if (Utils.isDebug()) System.out.println("ReadNBT Extended Slot: " + j + " ItemID: " + extendedChestSnapshot[j].itemID); } } } } } } /** * Writes a tile entity to NBT. */ public void writeToNBT(NBTTagCompound nbttagcompound) { if(!InventoryStocker.proxy.isClient(worldObj)) { super.writeToNBT(nbttagcompound); // Our inventory NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < contents.length; ++i) { if (this.contents[i] != null) { NBTTagCompound nbttagcompound1 = new NBTTagCompound(); nbttagcompound1.setByte("Slot", (byte)i); contents[i].writeToNBT(nbttagcompound1); nbttaglist.appendTag(nbttagcompound1); } } nbttagcompound.setTag("Items", nbttaglist); // Remote inventory snapshot NBTTagList nbttagremote = new NBTTagList(); if (remoteSnapshot != null) { if (Utils.isDebug()) System.out.println("writeNBT Target: " + targetTileName + " remoteInvSize:" + remoteSnapshot.length); for (int i = 0; i < remoteSnapshot.length; i++) { if (remoteSnapshot[i] != null) { if (Utils.isDebug()) System.out.println("writeNBT Remote Slot: " + i + " ItemID: " + remoteSnapshot[i].itemID + " StackSize: " + this.remoteSnapshot[i].stackSize + " meta: " + this.remoteSnapshot[i].getItemDamage()); NBTTagCompound remoteSnapshot1 = new NBTTagCompound(); remoteSnapshot1.setByte("Slot", (byte)i); remoteSnapshot[i].writeToNBT(remoteSnapshot1); nbttagremote.appendTag(remoteSnapshot1); } } } else { // if (Utils.isDebug()) System.out.println("writeNBT Remote Items is NULL!"); } nbttagcompound.setTag("remoteSnapshot", nbttagremote); if (extendedChest != null) { // Double chest second inventory snapshot NBTTagList nbttagextended = new NBTTagList(); for (int i = 0; i < extendedChestSnapshot.length; i++) { if (extendedChestSnapshot[i] != null) { if (Utils.isDebug()) System.out.println("writeNBT Extended Slot: " + i + " ItemID: " + extendedChestSnapshot[i].itemID + " StackSize: " + this.extendedChestSnapshot[i].stackSize + " meta: " + this.extendedChestSnapshot[i].getItemDamage()); NBTTagCompound extSnapshot1 = new NBTTagCompound(); extSnapshot1.setByte("Slot", (byte)i); extendedChestSnapshot[i].writeToNBT(extSnapshot1); nbttagremote.appendTag(extSnapshot1); } } nbttagcompound.setTag("extendedSnapshot", nbttagextended); } nbttagcompound.setString("targetTileName", targetTileName); nbttagcompound.setInteger("remoteSnapshotSize", remoteNumSlots); nbttagcompound.setBoolean("reactorWorkaround", reactorWorkaround); nbttagcompound.setInteger("reactorWidth", reactorWidth); nbttagcompound.setBoolean("extendedChestFlag", extendedChest != null); } } /** * This function fires only once on first load of an instance of our tile and attempts to see * if we should have a valid inventory or not. It will set the lastTileEntity and * hasSnapshot state. The actual remoteInventory object will be loaded (or not) via the NBT calls. */ public void onLoad() { if (!InventoryStocker.proxy.isClient(worldObj)) { tileLoaded = true; if (Utils.isDebug()) System.out.println("onLoad, remote inv size = " + remoteNumSlots); TileEntity tile = getTileAtFrontFace(); if (tile == null) { if (Utils.isDebug()) System.out.println("onLoad tile = null"); clearSnapshot(); } else { String tempName = tile.getClass().getName(); if (tempName.equals(targetTileName) && ((IInventory)tile).getSizeInventory() == remoteNumSlots) { if (Utils.isDebug()) System.out.println("onLoad, target name="+tempName+" stored name="+targetTileName+" MATCHED!"); lastTileEntity = tile; if (tile instanceof TileEntityChest) extendedChest = findDoubleChest(); hasSnapshot = true; } else { if (Utils.isDebug()) System.out.println("onLoad, target name="+tempName+" stored name="+targetTileName+" NOT matched."); clearSnapshot(); } } } } public int getInventoryStackLimit() { return 64; } public boolean isUseableByPlayer(EntityPlayer entityplayer) { if (worldObj.getBlockTileEntity(xCoord, yCoord, zCoord) != this) { return false; } return entityplayer.getDistanceSq((double)xCoord + 0.5D, (double)yCoord + 0.5D, (double)zCoord + 0.5D) <= 64D; } public void openChest() {} public void closeChest() {} /** * * @param tile * @return boolean<p> * This function will take a snapshot of the IInventory of the TileEntity passed to it. * This will be a copy of the remote inventory as it looks when this function is called. * * It will check that the TileEntity passed to it actually implements IInventory and * return false doing nothing if it does not. * * Will return true if it successfully took a snapshot. */ public boolean takeSnapShot(TileEntity tile) { if (!(tile instanceof IInventory)) { return false; } ItemStack tempCopy; // Get number of slots in the remote inventory TileEntity core = findReactorCore(tile); if (core != null) { // IC2 nuclear reactors with under 6 chambers do not correctly report the size of their inventory - it's always 54 regardless. // Instead they internally remap slots in all "nonexistent" columns to the rightmost valid column. // Also, because the inventory contents are listed row by row, correcting the size manually is not sufficient. // The snapshot and stocking loops must skip over the remapped slots on each row to reach the valid slots in the next row. reactorWorkaround = true; reactorWidth = countReactorChambers(core) + 3; remoteNumSlots = 54; remoteSnapshot = new ItemStack[remoteNumSlots]; // Iterate through remote slots and make a copy of it for (int row = 0; row < 6; row++) { // skip the useless mirrored slots for (int i = 0; i < reactorWidth; i++) { // Reactor inventory rows are always 9 wide internally tempCopy = ((IInventory)tile).getStackInSlot(row * 9 + i); if (tempCopy == null) { remoteSnapshot[row * 9 + i] = null; } else { remoteSnapshot[row * 9 + i] = new ItemStack(tempCopy.itemID, tempCopy.stackSize, tempCopy.getItemDamage()); if (tempCopy.stackTagCompound != null) { remoteSnapshot[row * 9 + i].stackTagCompound = (NBTTagCompound)tempCopy.stackTagCompound.copy(); } } // else } // for i } // for row } // if (core != null) else { remoteNumSlots = ((IInventory)tile).getSizeInventory(); remoteSnapshot = new ItemStack[remoteNumSlots]; if (tile instanceof TileEntityChest) extendedChest = findDoubleChest(); // Iterate through remote slots and make a copy of it for (int i = 0; i < remoteNumSlots; i++) { tempCopy = ((IInventory)tile).getStackInSlot(i); if (tempCopy == null) { remoteSnapshot[i] = null; } else { remoteSnapshot[i] = new ItemStack(tempCopy.itemID, tempCopy.stackSize, tempCopy.getItemDamage()); if (tempCopy.stackTagCompound != null) { remoteSnapshot[i].stackTagCompound = (NBTTagCompound)tempCopy.stackTagCompound.copy(); } } } if (extendedChest != null) { // More work to do: Record the other half of the double chest too! extendedChestSnapshot = new ItemStack[remoteNumSlots]; for (int i = 0; i < remoteNumSlots; i++) { tempCopy = ((IInventory)extendedChest).getStackInSlot(i); if (tempCopy == null) { extendedChestSnapshot[i] = null; } else { extendedChestSnapshot[i] = new ItemStack(tempCopy.itemID, tempCopy.stackSize, tempCopy.getItemDamage()); if (tempCopy.stackTagCompound != null) { extendedChestSnapshot[i].stackTagCompound = (NBTTagCompound)tempCopy.stackTagCompound.copy(); } } } } // if extendedChest } // else (core == null) /* * get remote entity class name and store it as targetTile, which also ends up being stored in our * own NBT tables so our tile will remember what was there after chunk unloads/restarts/etc */ this.targetTileName = tile.getClass().getName(); lastTileEntity = tile; hasSnapshot = true; if (Utils.isDebug()) System.out.println("Shapshot taken of targetTileName: " + this.targetTileName); return true; } public boolean inputGridIsEmpty() { for (int i=0; i<9; i++) { if (contents[i] != null) { return false; } } return true; } protected void stockInventory() { int startSlot = 0; int endSlot = remoteNumSlots; boolean workDone; int pass = 0; // Check special cases first if (reactorWorkaround) { do { workDone = false; for (int row = 0; row < 6; row++) { for (int col = 0; col < reactorWidth; col++) { int slot = row * 9 + col; workDone |= processSlot(slot, (IInventory)lastTileEntity, remoteSnapshot); } // for slot } // for row pass++; } while (workDone && pass < 100); } else if (extendedChest != null) { do { workDone = false; for (int slot = startSlot; slot < endSlot; slot++) { workDone |= processSlot(slot, (IInventory)lastTileEntity, remoteSnapshot); workDone |= processSlot(slot, extendedChest, extendedChestSnapshot); // Concurrent second chest processing, for great justice! (and less looping) } pass++; } while (workDone && pass < 100); } else do { workDone = false; for (int slot = startSlot; slot < endSlot; slot++) { workDone |= processSlot(slot, (IInventory)lastTileEntity, remoteSnapshot); } pass++; } while (workDone && pass < 100); } protected boolean processSlot(int slot, IInventory tile, ItemStack[] snapshot) { ItemStack i = tile.getStackInSlot(slot); ItemStack s = snapshot[slot]; if (i == null) { if (s == null) return false; // Slot is and should be empty. Next! // Slot is empty but shouldn't be. Add what belongs there. return addItemToRemote(slot, tile, snapshot, snapshot[slot].stackSize); } else { // Slot is occupied. Figure out if contents belong there. if (s == null) { // Nope! Slot should be empty. Need to remove this. // Call helper function to do that here, and then move on to next slot return removeItemFromRemote(slot, tile, tile.getStackInSlot(slot).stackSize); } // Compare contents of slot between remote inventory and snapshot. if (checkItemTypesMatch(i, s)) { // Matched. Compare stack sizes. Try to ensure there's not too much or too little. int amtNeeded = snapshot[slot].stackSize - tile.getStackInSlot(slot).stackSize; if (amtNeeded > 0) return addItemToRemote(slot, tile, snapshot, amtNeeded); if (amtNeeded < 0) return removeItemFromRemote(slot, tile, -amtNeeded); // Note the negation. // The size is already the same and we've nothing to do. Hooray! return false; } else { // Wrong item type in slot! Try to remove what doesn't belong and add what does. boolean ret; ret = removeItemFromRemote(slot, tile, tile.getStackInSlot(slot).stackSize); if (tile.getStackInSlot(slot) == null) ret = addItemToRemote(slot, tile, snapshot, snapshot[slot].stackSize); return ret; } } // else } // Test if two item stacks' types match, while ignoring damage level if needed. protected boolean checkItemTypesMatch(ItemStack a, ItemStack b) { // if (Utils.isDebug()) System.out.println("checkItemTypesMatch: a: "+ a +" b: "+ b +""); // if (Utils.isDebug()) System.out.println("checkItemTypesMatch: .isStackable() a: "+ a.isStackable() +" b: "+ b.isStackable() +""); // if (Utils.isDebug()) System.out.println("checkItemTypesMatch: .getItemDamage() a: "+ a.getItemDamage() +" b: "+ b.getItemDamage() +""); // if (Utils.isDebug()) System.out.println("checkItemTypesMatch: .isItemStackDamageable() a: "+ a.isItemStackDamageable() +" b: "+ b.isItemStackDamageable() +""); if (a.itemID == b.itemID) { // Ignore damage value of damageable items while testing for match! if (a.isItemStackDamageable()) return true; // Already tested ItemID, so a.isItemEqual(b) would be partially redundant. if (a.getItemDamage() == b.getItemDamage()) return true; } return false; } protected boolean removeItemFromRemote(int slot, IInventory remote, int amount) { // Find room in output grid // Use checkItemTypesMatch on any existing contents to see if the new output will stack // If all existing ItemStacks become full, and there is no room left for a new stack, // leave the untransferred remainder in the remote inventory. boolean partialMove = false; ItemStack remoteStack = remote.getStackInSlot(slot); if (remoteStack == null) return false; int max = remoteStack.getMaxStackSize(); int amtLeft = amount; if (amtLeft > max) amtLeft = max; int delayedDestination = -1; for (int i = 9; i < 18; i++) // Pull only into the Output section { if (contents[i] == null) { if (delayedDestination == -1) // Remember this parking space in case we don't find a matching partial slot. delayedDestination = i; // Remember to car-pool, boys and girls! } else if (checkItemTypesMatch(contents[i], remoteStack)) { int room = max - contents[i].stackSize; if (room >= amtLeft) { // Space for all, so toss it in. contents[i].stackSize += amtLeft; remoteStack.stackSize -= amtLeft; if (remoteStack.stackSize <= 0) remote.setInventorySlotContents(slot, null); return true; } else { // Room for some of it, so add what we can, then keep looking. contents[i].stackSize += room; remoteStack.stackSize -= room; amtLeft -= room; partialMove = true; } } } if (amtLeft > 0 && delayedDestination >= 0) { // Not enough room in existing stacks, so transfer whatever's left to a new one. contents[delayedDestination] = remoteStack; remote.setInventorySlotContents(slot, null); return true; } return partialMove; } protected boolean addItemToRemote(int slot, IInventory remote, ItemStack[] snapshot, int amount) { boolean partialMove = false; int max = snapshot[slot].getMaxStackSize(); int amtNeeded = amount; if (amtNeeded > max) amtNeeded = max; for (int i = 17; i >= 0; i--) // Scan Output section as well in case desired items were removed for being in the wrong slot { if (contents[i] != null && checkItemTypesMatch(contents[i], snapshot[slot])) { if (remote.getStackInSlot(slot) == null) { // It's currently empty, so toss what we can into remote slot. if (contents[i].stackSize > amtNeeded) { // Found more than enough to meet the quota, so shift it on over. ItemStack extra = contents[i].splitStack(amtNeeded); remote.setInventorySlotContents(slot, extra); return true; } else { amtNeeded -= contents[i].stackSize; remote.setInventorySlotContents(slot, contents[i]); contents[i] = null; if (amtNeeded <= 0) return true; partialMove = true; } } else { // There's already some present, so transfer from one stack to the other. if (contents[i].stackSize > amtNeeded) { // More than enough here, just add and subtract. contents[i].stackSize -= amtNeeded; remote.getStackInSlot(slot).stackSize += amtNeeded; return true; } else { // This stack matches or is smaller than what we need. Consume it entirely. amtNeeded -= contents[i].stackSize; remote.getStackInSlot(slot).stackSize += contents[i].stackSize; contents[i] = null; if (amtNeeded <= 0) return true; partialMove = true; } } // else } // if } // for return partialMove; } private void debugSnapshotDataClient() { if(InventoryStocker.proxy.isClient(worldObj)) { TileEntity tile = getTileAtFrontFace(); if (!(tile instanceof IInventory)) // A null pointer will fail an instanceof test, so there's no need to independently check it. { return; } String tempName = tile.getClass().getName(); System.out.println("Client detected TileName=" + tempName + " expected TileName=" + targetTileName); } } private void debugSnapshotDataServer() { if(InventoryStocker.proxy.isServer()) { TileEntity tile = getTileAtFrontFace(); if (!(tile instanceof IInventory)) // A null pointer will fail an instanceof test, so there's no need to independently check it. { return; } String tempName = tile.getClass().getName(); System.out.println("Server detected TileName=" + tempName + " expected TileName=" + targetTileName); } } /** * Will check if our snapshot should be invalidated. * Returns true if snapshot is invalid, false otherwise. * @return boolean */ public boolean checkInvalidSnapshot() { /* TODO Add code here to check if the chunk that the tile at front face * is in is actually loaded or not. Return false immediately if it * isn't loaded so that other code doesn't clear the snapshot. */ TileEntity tile = getTileAtFrontFace(); if (!(tile instanceof IInventory)) // A null pointer will fail an instanceof test, so there's no need to independently check it. { if (Utils.isDebug()) { if (tile == null) System.out.println("Invalid snapshot: Tile = null"); else System.out.println("Invalid snapshot: tileEntity has no IInventory interface"); } return true; } String tempName = tile.getClass().getName(); if (!tempName.equals(targetTileName)) { if (Utils.isDebug()) System.out.println("Invalid snapshot: TileName Mismatched, detected TileName=" + tempName + " expected TileName=" + targetTileName); return true; } if (tile != lastTileEntity) { if (Utils.isDebug()) System.out.println("Invalid snapshot: tileEntity does not match lastTileEntity"); return true; } if (((IInventory)tile).getSizeInventory() != this.remoteNumSlots) { if (Utils.isDebug()) { System.out.println("Invalid snapshot: tileEntity inventory size has changed"); System.out.println("RemoteInvSize: " + ((IInventory)tile).getSizeInventory()+", Expecting: "+this.remoteNumSlots); } return true; } // Deal with double-chest special case if (tile instanceof TileEntityChest) { // Look for adjacent chest TileEntityChest foundChest = findDoubleChest(); if (Utils.isDebug()) { if (foundChest == null) System.out.println("Single Wooden Chest Found"); else System.out.println("Double Wooden Chest Found"); } // Check if it matches previous conditions if (extendedChest != foundChest) { if (Utils.isDebug()) System.out.println("Invalid snapshot: Double chest configuration changed!"); return true; } } // Deal with nuclear reactor special case if (reactorWorkaround) { TileEntity core = findReactorCore(tile); if (core != null) { int currentWidth = countReactorChambers(core) + 3; if (currentWidth != reactorWidth) { if (Utils.isDebug()) System.out.println("Invalid snapshot: Reactor size has changed!"); return true; } } } return false; } /** * Will find a double chest * @return TileEntityChest */ private TileEntityChest findDoubleChest() { TileEntity temp; TileEntity front = getTileAtFrontFace(); if (front == null) return null; temp = worldObj.getBlockTileEntity(front.xCoord + 1, front.yCoord, front.zCoord); if (temp instanceof TileEntityChest) return (TileEntityChest)temp; temp = worldObj.getBlockTileEntity(front.xCoord - 1, front.yCoord, front.zCoord); if (temp instanceof TileEntityChest) return (TileEntityChest)temp; temp = worldObj.getBlockTileEntity(front.xCoord, front.yCoord, front.zCoord + 1); if (temp instanceof TileEntityChest) return (TileEntityChest)temp; temp = worldObj.getBlockTileEntity(front.xCoord, front.yCoord, front.zCoord - 1); if (temp instanceof TileEntityChest) return (TileEntityChest)temp; return null; } private TileEntity findReactorCore(TileEntity start) { TileEntity temp; if (start == null) return null; if (start.getClass().getSimpleName().endsWith(classnameIC2ReactorCore)) return start; if (!start.getClass().getSimpleName().endsWith(classnameIC2ReactorChamber)) return null; // If it's not a core and it's not a chamber we have no business continuing. temp = worldObj.getBlockTileEntity(start.xCoord + 1, start.yCoord, start.zCoord); if (temp != null) if (temp.getClass().getSimpleName().endsWith(classnameIC2ReactorCore)) return temp; temp = worldObj.getBlockTileEntity(start.xCoord - 1, start.yCoord, start.zCoord); if (temp != null) if (temp.getClass().getSimpleName().endsWith(classnameIC2ReactorCore)) return temp; temp = worldObj.getBlockTileEntity(start.xCoord, start.yCoord, start.zCoord + 1); if (temp != null) if (temp.getClass().getSimpleName().endsWith(classnameIC2ReactorCore)) return temp; temp = worldObj.getBlockTileEntity(start.xCoord, start.yCoord, start.zCoord - 1); if (temp != null) if (temp.getClass().getSimpleName().endsWith(classnameIC2ReactorCore)) return temp; temp = worldObj.getBlockTileEntity(start.xCoord, start.yCoord + 1, start.zCoord); if (temp != null) if (temp.getClass().getSimpleName().endsWith(classnameIC2ReactorCore)) return temp; temp = worldObj.getBlockTileEntity(start.xCoord, start.yCoord - 1, start.zCoord); if (temp != null) if (temp.getClass().getSimpleName().endsWith(classnameIC2ReactorCore)) return temp; return null; } private int addIfChamber(int x, int y, int z) { TileEntity temp = worldObj.getBlockTileEntity(x, y, z); if (temp != null) return temp.getClass().getSimpleName().endsWith(classnameIC2ReactorChamber) ? 1 : 0; return 0; } private int countReactorChambers(TileEntity core) { int count = 0; if (core == null) return 0; count += addIfChamber(core.xCoord + 1, core.yCoord, core.zCoord); count += addIfChamber(core.xCoord - 1, core.yCoord, core.zCoord); count += addIfChamber(core.xCoord, core.yCoord, core.zCoord + 1); count += addIfChamber(core.xCoord, core.yCoord, core.zCoord - 1); count += addIfChamber(core.xCoord, core.yCoord + 1, core.zCoord); count += addIfChamber(core.xCoord, core.yCoord - 1, core.zCoord); return count; } private void lightsOff() { lightState = false; int meta = worldObj.getBlockMetadata(xCoord, yCoord, zCoord); // Grab current meta data meta &= 7; // Clear bit 4 worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, meta); // And store it worldObj.markBlockNeedsUpdate(xCoord, yCoord, zCoord); } private void lightsOn() { lightState = true; // Turn on das blinkenlights! int meta = worldObj.getBlockMetadata(xCoord, yCoord, zCoord); // Grab current meta data meta |= 8; // Set bit 4 worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, meta); // And store it worldObj.markBlockNeedsUpdate(xCoord, yCoord, zCoord); } @Override public void updateEntity() { // debugSnapshotDataClient(); // debugSnapshotDataServer(); // Check if this or one of the blocks next to this is getting power from a neighboring block. boolean isPowered = worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord); // This code is probably not needed, but maintaining it here just in case if(InventoryStocker.proxy.isClient(worldObj)) { //Check the door states client side in SMP here updateDoorStates(); if (isPowered) { // This allows client-side animation of texture over time, which would not happen without updating the block worldObj.markBlockNeedsUpdate(xCoord, yCoord, zCoord); } return; } // See if this tileEntity instance has been properly loaded, if not, do some onLoad stuff to initialize or restore prior state // String tl = new Boolean(tileLoaded).toString(); // if (Utils.isDebug()) System.out.println("te.updateEntity.tileLoaded: " + tl); if (!tileLoaded) { if (Utils.isDebug()) System.out.println("tileLoaded false, running onLoad"); onLoad(); } // Check if the GUI or a client is asking us to take a snapshot // if so, clear the existing snapshot and take a new one if (guiTakeSnapshot) { guiTakeSnapshot = false; if (Utils.isDebug()) System.out.println("GUI take snapshot request"); TileEntity tile = getTileAtFrontFace(); if (tile != null && tile instanceof IInventory) { if (takeSnapShot(tile)) { - if (InventoryStocker.proxy.isServer()) - { +// if (InventoryStocker.proxy.isServer()) +// { // server has no GUI, but this code works for our purposes. // We need to send the snapshot state flag here to all clients that have the GUI open String s = new Boolean(hasSnapshot).toString(); if (Utils.isDebug()) System.out.println("guiTakeSnapshot.sendSnapshotStateClients: " + s); sendSnapshotStateClients(); - } +// } } else { // Failed to get a valid snapshot. Run this just in case to cleanly reset everything. if (Utils.isDebug()) System.out.println("updateEntity.guiTakeSnapshot_failed.clearSnapshot()"); clearSnapshot(); } } } // Check if a snapshot clear has been requested if (guiClearSnapshot) { guiClearSnapshot = false; if (Utils.isDebug()) System.out.println("updateEntity.guiClearSnapshot.clearSnapshot()"); clearSnapshot(); } if (!isPowered) { // Reset tick time on losing power tickTime = 0; // Shut off glowing light textures. if (lightState)lightsOff(); } // If we are powered and previously weren't or timer has expired, it's time to go to work. if (isPowered && tickTime == 0) { tickTime = tickDelay; if (Utils.isDebug()) System.out.println("Powered"); // Turn on das blinkenlights! if(!lightState)lightsOn(); if (hasSnapshot) { // Check for any situation in which the snapshot should be invalidated. if (checkInvalidSnapshot()) { if (Utils.isDebug()) System.out.println("updateEntity.checkInvalidSnapshot.clearSnapshot()"); clearSnapshot(); } else { // If we've made it here, it's time to stock the remote inventory. if (Utils.isDebug()) System.out.println("updateEntity.stockInventory()"); stockInventory(); } } } else if (tickTime > 0) { tickTime--; } } @Override public int getStartInventorySide(ForgeDirection side) { // TODO Auto-generated method stub return 0; } @Override public int getSizeInventorySide(ForgeDirection side) { // TODO Auto-generated method stub return 0; } }
false
true
public void updateEntity() { // debugSnapshotDataClient(); // debugSnapshotDataServer(); // Check if this or one of the blocks next to this is getting power from a neighboring block. boolean isPowered = worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord); // This code is probably not needed, but maintaining it here just in case if(InventoryStocker.proxy.isClient(worldObj)) { //Check the door states client side in SMP here updateDoorStates(); if (isPowered) { // This allows client-side animation of texture over time, which would not happen without updating the block worldObj.markBlockNeedsUpdate(xCoord, yCoord, zCoord); } return; } // See if this tileEntity instance has been properly loaded, if not, do some onLoad stuff to initialize or restore prior state // String tl = new Boolean(tileLoaded).toString(); // if (Utils.isDebug()) System.out.println("te.updateEntity.tileLoaded: " + tl); if (!tileLoaded) { if (Utils.isDebug()) System.out.println("tileLoaded false, running onLoad"); onLoad(); } // Check if the GUI or a client is asking us to take a snapshot // if so, clear the existing snapshot and take a new one if (guiTakeSnapshot) { guiTakeSnapshot = false; if (Utils.isDebug()) System.out.println("GUI take snapshot request"); TileEntity tile = getTileAtFrontFace(); if (tile != null && tile instanceof IInventory) { if (takeSnapShot(tile)) { if (InventoryStocker.proxy.isServer()) { // server has no GUI, but this code works for our purposes. // We need to send the snapshot state flag here to all clients that have the GUI open String s = new Boolean(hasSnapshot).toString(); if (Utils.isDebug()) System.out.println("guiTakeSnapshot.sendSnapshotStateClients: " + s); sendSnapshotStateClients(); } } else { // Failed to get a valid snapshot. Run this just in case to cleanly reset everything. if (Utils.isDebug()) System.out.println("updateEntity.guiTakeSnapshot_failed.clearSnapshot()"); clearSnapshot(); } } } // Check if a snapshot clear has been requested if (guiClearSnapshot) { guiClearSnapshot = false; if (Utils.isDebug()) System.out.println("updateEntity.guiClearSnapshot.clearSnapshot()"); clearSnapshot(); } if (!isPowered) { // Reset tick time on losing power tickTime = 0; // Shut off glowing light textures. if (lightState)lightsOff(); } // If we are powered and previously weren't or timer has expired, it's time to go to work. if (isPowered && tickTime == 0) { tickTime = tickDelay; if (Utils.isDebug()) System.out.println("Powered"); // Turn on das blinkenlights! if(!lightState)lightsOn(); if (hasSnapshot) { // Check for any situation in which the snapshot should be invalidated. if (checkInvalidSnapshot()) { if (Utils.isDebug()) System.out.println("updateEntity.checkInvalidSnapshot.clearSnapshot()"); clearSnapshot(); } else { // If we've made it here, it's time to stock the remote inventory. if (Utils.isDebug()) System.out.println("updateEntity.stockInventory()"); stockInventory(); } } } else if (tickTime > 0) { tickTime--; } }
public void updateEntity() { // debugSnapshotDataClient(); // debugSnapshotDataServer(); // Check if this or one of the blocks next to this is getting power from a neighboring block. boolean isPowered = worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord); // This code is probably not needed, but maintaining it here just in case if(InventoryStocker.proxy.isClient(worldObj)) { //Check the door states client side in SMP here updateDoorStates(); if (isPowered) { // This allows client-side animation of texture over time, which would not happen without updating the block worldObj.markBlockNeedsUpdate(xCoord, yCoord, zCoord); } return; } // See if this tileEntity instance has been properly loaded, if not, do some onLoad stuff to initialize or restore prior state // String tl = new Boolean(tileLoaded).toString(); // if (Utils.isDebug()) System.out.println("te.updateEntity.tileLoaded: " + tl); if (!tileLoaded) { if (Utils.isDebug()) System.out.println("tileLoaded false, running onLoad"); onLoad(); } // Check if the GUI or a client is asking us to take a snapshot // if so, clear the existing snapshot and take a new one if (guiTakeSnapshot) { guiTakeSnapshot = false; if (Utils.isDebug()) System.out.println("GUI take snapshot request"); TileEntity tile = getTileAtFrontFace(); if (tile != null && tile instanceof IInventory) { if (takeSnapShot(tile)) { // if (InventoryStocker.proxy.isServer()) // { // server has no GUI, but this code works for our purposes. // We need to send the snapshot state flag here to all clients that have the GUI open String s = new Boolean(hasSnapshot).toString(); if (Utils.isDebug()) System.out.println("guiTakeSnapshot.sendSnapshotStateClients: " + s); sendSnapshotStateClients(); // } } else { // Failed to get a valid snapshot. Run this just in case to cleanly reset everything. if (Utils.isDebug()) System.out.println("updateEntity.guiTakeSnapshot_failed.clearSnapshot()"); clearSnapshot(); } } } // Check if a snapshot clear has been requested if (guiClearSnapshot) { guiClearSnapshot = false; if (Utils.isDebug()) System.out.println("updateEntity.guiClearSnapshot.clearSnapshot()"); clearSnapshot(); } if (!isPowered) { // Reset tick time on losing power tickTime = 0; // Shut off glowing light textures. if (lightState)lightsOff(); } // If we are powered and previously weren't or timer has expired, it's time to go to work. if (isPowered && tickTime == 0) { tickTime = tickDelay; if (Utils.isDebug()) System.out.println("Powered"); // Turn on das blinkenlights! if(!lightState)lightsOn(); if (hasSnapshot) { // Check for any situation in which the snapshot should be invalidated. if (checkInvalidSnapshot()) { if (Utils.isDebug()) System.out.println("updateEntity.checkInvalidSnapshot.clearSnapshot()"); clearSnapshot(); } else { // If we've made it here, it's time to stock the remote inventory. if (Utils.isDebug()) System.out.println("updateEntity.stockInventory()"); stockInventory(); } } } else if (tickTime > 0) { tickTime--; } }
diff --git a/servo-aws/src/test/java/com/netflix/servo/publish/cloudwatch/CloudWatchMetricObserverTest.java b/servo-aws/src/test/java/com/netflix/servo/publish/cloudwatch/CloudWatchMetricObserverTest.java index 6b68d37..c39f6b5 100644 --- a/servo-aws/src/test/java/com/netflix/servo/publish/cloudwatch/CloudWatchMetricObserverTest.java +++ b/servo-aws/src/test/java/com/netflix/servo/publish/cloudwatch/CloudWatchMetricObserverTest.java @@ -1,68 +1,70 @@ /* * #%L * servo-cloudwatch * %% * Copyright (C) 2011 - 2012 Netflix * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.netflix.servo.publish.cloudwatch; import com.amazonaws.AmazonClientException; import com.amazonaws.auth.BasicAWSCredentials; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.Metric; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; /** * User: gorzell * Date: 1/9/12 * Time: 2:24 PM */ public class CloudWatchMetricObserverTest { private CloudWatchMetricObserver observer = new CloudWatchMetricObserver("testObserver", "testDomain", new BasicAWSCredentials("", "")); @Test public void testUpdate() throws Exception { List<Metric> metrics = new ArrayList<Metric>(33); for (int i = 0; i < 33; i++) { metrics.add(new Metric("test", BasicTagList.EMPTY, System.currentTimeMillis(), 10)); } try{ observer.update(metrics); - } catch (AmazonClientException e){} + } catch (AmazonClientException e){ + e.printStackTrace(); + } } @Test public void testCreateDimensions() throws Exception { } @Test public void testCreateMetricDatum() throws Exception { } @Test public void testCreatePutRequest() throws Exception { } }
true
true
public void testUpdate() throws Exception { List<Metric> metrics = new ArrayList<Metric>(33); for (int i = 0; i < 33; i++) { metrics.add(new Metric("test", BasicTagList.EMPTY, System.currentTimeMillis(), 10)); } try{ observer.update(metrics); } catch (AmazonClientException e){} }
public void testUpdate() throws Exception { List<Metric> metrics = new ArrayList<Metric>(33); for (int i = 0; i < 33; i++) { metrics.add(new Metric("test", BasicTagList.EMPTY, System.currentTimeMillis(), 10)); } try{ observer.update(metrics); } catch (AmazonClientException e){ e.printStackTrace(); } }
diff --git a/src/com/ceco/gm2/gravitybox/quicksettings/GpsTile.java b/src/com/ceco/gm2/gravitybox/quicksettings/GpsTile.java index 888598c..074308c 100644 --- a/src/com/ceco/gm2/gravitybox/quicksettings/GpsTile.java +++ b/src/com/ceco/gm2/gravitybox/quicksettings/GpsTile.java @@ -1,128 +1,128 @@ /* * Copyright (C) 2013 Peter Gregus for GravityBox Project (C3C076@xda) * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ceco.gm2.gravitybox.quicksettings; import com.ceco.gm2.gravitybox.R; import de.robv.android.xposed.XposedBridge; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.LocationManager; import android.provider.Settings; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; public class GpsTile extends AQuickSettingsTile { private static final String TAG = "GB:GpsTile"; private static final boolean DEBUG = false; public static final String GPS_ENABLED_CHANGE_ACTION = "android.location.GPS_ENABLED_CHANGE"; public static final String GPS_FIX_CHANGE_ACTION = "android.location.GPS_FIX_CHANGE"; public static final String EXTRA_GPS_ENABLED = "enabled"; private boolean mGpsEnabled; private boolean mGpsFixed; private TextView mTextView; private static void log(String message) { XposedBridge.log(TAG + ": " + message); } private BroadcastReceiver mLocationManagerReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) log("Broadcast received: " + intent.toString()); final String action = intent.getAction(); if (action.equals(LocationManager.PROVIDERS_CHANGED_ACTION)) { mGpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); mGpsFixed = false; } else if (action.equals(GPS_FIX_CHANGE_ACTION)) { mGpsFixed = intent.getBooleanExtra(EXTRA_GPS_ENABLED, false); } else if (action.equals(GPS_ENABLED_CHANGE_ACTION)) { mGpsFixed = false; } if (DEBUG) log("mGpsEnabled = " + mGpsEnabled + "; mGpsFixed = " + mGpsFixed); updateResources(); } }; public GpsTile(Context context, Context gbContext, Object statusBar, Object panelBar) { super(context, gbContext, statusBar, panelBar); mOnClick = new View.OnClickListener() { @Override public void onClick(View v) { Settings.Secure.setLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER, !mGpsEnabled); } }; mOnLongClick = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startActivity(Settings.ACTION_LOCATION_SOURCE_SETTINGS); - return false; + return true; } }; mGpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); mGpsFixed = false; } @Override protected void onTileCreate() { LayoutInflater inflater = LayoutInflater.from(mGbContext); inflater.inflate(R.layout.quick_settings_tile_gps, mTile); mTextView = (TextView) mTile.findViewById(R.id.gps_tileview); } @Override protected void onTilePostCreate() { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION); intentFilter.addAction(GPS_ENABLED_CHANGE_ACTION); intentFilter.addAction(GPS_FIX_CHANGE_ACTION); mContext.registerReceiver(mLocationManagerReceiver, intentFilter); super.onTilePostCreate(); } @Override protected synchronized void updateTile() { if (mGpsEnabled) { mLabel = mGpsFixed ? mGbContext.getString(R.string.qs_tile_gps_locked) : mGbContext.getString(R.string.qs_tile_gps_enabled); mDrawableId = mGpsFixed ? R.drawable.ic_qs_gps_locked : R.drawable.ic_qs_gps_enable; } else { mLabel = mGbContext.getString(R.string.qs_tile_gps_disabled); mDrawableId = R.drawable.ic_qs_gps_disable; } mTextView.setText(mLabel); mTextView.setCompoundDrawablesWithIntrinsicBounds(0, mDrawableId, 0, 0); } }
true
true
public GpsTile(Context context, Context gbContext, Object statusBar, Object panelBar) { super(context, gbContext, statusBar, panelBar); mOnClick = new View.OnClickListener() { @Override public void onClick(View v) { Settings.Secure.setLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER, !mGpsEnabled); } }; mOnLongClick = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startActivity(Settings.ACTION_LOCATION_SOURCE_SETTINGS); return false; } }; mGpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); mGpsFixed = false; }
public GpsTile(Context context, Context gbContext, Object statusBar, Object panelBar) { super(context, gbContext, statusBar, panelBar); mOnClick = new View.OnClickListener() { @Override public void onClick(View v) { Settings.Secure.setLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER, !mGpsEnabled); } }; mOnLongClick = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startActivity(Settings.ACTION_LOCATION_SOURCE_SETTINGS); return true; } }; mGpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); mGpsFixed = false; }
diff --git a/src/com/michalmazur/orphanedtexts/RawSmsReader.java b/src/com/michalmazur/orphanedtexts/RawSmsReader.java index 076a90e..765124f 100644 --- a/src/com/michalmazur/orphanedtexts/RawSmsReader.java +++ b/src/com/michalmazur/orphanedtexts/RawSmsReader.java @@ -1,79 +1,83 @@ package com.michalmazur.orphanedtexts; import java.util.ArrayList; import java.util.Date; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.telephony.SmsMessage; import android.util.Log; public class RawSmsReader { private ArrayList<Orphan> orphans = new ArrayList<Orphan>(); private Context context; public RawSmsReader() { } public RawSmsReader(Context c) { this.context = c; } public ArrayList<Orphan> getOrphans() { if (this.context == null) { Log.d("ORPHAN", "No context. Will return fake data."); return getFakeOrphans(); } String uriString = "content://sms/raw"; Uri uri = Uri.parse(uriString); Cursor c = context.getContentResolver() .query(uri, null, null, null, null /* "_id limit 10" */); while (c.moveToNext()) { Orphan newOrphan = new Orphan(); newOrphan.setId(c.getInt(c.getColumnIndex("_id"))); newOrphan.setDate(new Date(c.getLong(c.getColumnIndex("date")))); newOrphan.setReferenceNumber(c.getInt(c.getColumnIndex("reference_number"))); newOrphan.setCount(c.getInt(c.getColumnIndex("count"))); newOrphan.setSequence(c.getInt(c.getColumnIndex("sequence"))); newOrphan.setDestinationPort(c.getInt(c.getColumnIndex("destination_port"))); newOrphan.setAddress(c.getString(c.getColumnIndex("address"))); SmsMessage message = SmsMessage.createFromPdu(this.hexStringToByteArray(c.getString(c.getColumnIndex("pdu")))); - newOrphan.setMessageBody(message.getMessageBody()); + try { + newOrphan.setMessageBody(message.getMessageBody()); + } catch (NullPointerException e) { + newOrphan.setMessageBody("<cannot read message body>"); + } orphans.add(newOrphan); } return orphans; } private ArrayList<Orphan> getFakeOrphans() { ArrayList<Orphan> orphans = new ArrayList<Orphan>(); for (int i = 0; i < 10; i++) { Orphan o = new Orphan(); o.setId(i); o.setDate(new Date()); o.setReferenceNumber(0); o.setCount(1); o.setSequence(2); o.setDestinationPort(5); o.setAddress("+1 123 456 7890"); o.setMessageBody("this is my message"); orphans.add(o); } return orphans; } // http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java public byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit( s.charAt(i + 1), 16)); } return data; } }
true
true
public ArrayList<Orphan> getOrphans() { if (this.context == null) { Log.d("ORPHAN", "No context. Will return fake data."); return getFakeOrphans(); } String uriString = "content://sms/raw"; Uri uri = Uri.parse(uriString); Cursor c = context.getContentResolver() .query(uri, null, null, null, null /* "_id limit 10" */); while (c.moveToNext()) { Orphan newOrphan = new Orphan(); newOrphan.setId(c.getInt(c.getColumnIndex("_id"))); newOrphan.setDate(new Date(c.getLong(c.getColumnIndex("date")))); newOrphan.setReferenceNumber(c.getInt(c.getColumnIndex("reference_number"))); newOrphan.setCount(c.getInt(c.getColumnIndex("count"))); newOrphan.setSequence(c.getInt(c.getColumnIndex("sequence"))); newOrphan.setDestinationPort(c.getInt(c.getColumnIndex("destination_port"))); newOrphan.setAddress(c.getString(c.getColumnIndex("address"))); SmsMessage message = SmsMessage.createFromPdu(this.hexStringToByteArray(c.getString(c.getColumnIndex("pdu")))); newOrphan.setMessageBody(message.getMessageBody()); orphans.add(newOrphan); } return orphans; }
public ArrayList<Orphan> getOrphans() { if (this.context == null) { Log.d("ORPHAN", "No context. Will return fake data."); return getFakeOrphans(); } String uriString = "content://sms/raw"; Uri uri = Uri.parse(uriString); Cursor c = context.getContentResolver() .query(uri, null, null, null, null /* "_id limit 10" */); while (c.moveToNext()) { Orphan newOrphan = new Orphan(); newOrphan.setId(c.getInt(c.getColumnIndex("_id"))); newOrphan.setDate(new Date(c.getLong(c.getColumnIndex("date")))); newOrphan.setReferenceNumber(c.getInt(c.getColumnIndex("reference_number"))); newOrphan.setCount(c.getInt(c.getColumnIndex("count"))); newOrphan.setSequence(c.getInt(c.getColumnIndex("sequence"))); newOrphan.setDestinationPort(c.getInt(c.getColumnIndex("destination_port"))); newOrphan.setAddress(c.getString(c.getColumnIndex("address"))); SmsMessage message = SmsMessage.createFromPdu(this.hexStringToByteArray(c.getString(c.getColumnIndex("pdu")))); try { newOrphan.setMessageBody(message.getMessageBody()); } catch (NullPointerException e) { newOrphan.setMessageBody("<cannot read message body>"); } orphans.add(newOrphan); } return orphans; }
diff --git a/src/vooga/rts/gui/Button.java b/src/vooga/rts/gui/Button.java index c340803d..33f670c5 100755 --- a/src/vooga/rts/gui/Button.java +++ b/src/vooga/rts/gui/Button.java @@ -1,70 +1,70 @@ package vooga.rts.gui; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.util.Observable; import vooga.rts.IGameLoop; import vooga.rts.resourcemanager.ResourceManager; import vooga.rts.util.Location; public abstract class Button extends Observable implements IGameLoop { private BufferedImage myImage; protected Dimension mySize; protected Location myPos; protected boolean isFocused; /* * TODO: Add onFocus behavior for each button. */ public Button (String image, Dimension size, Location pos) { if (image != null) { - myImage = ResourceManager.getInstance().<BufferedImage>getFile(image, BufferedImage.class); + myImage = ResourceManager.getInstance().<BufferedImage> getFile(image, BufferedImage.class); } mySize = size; myPos = pos; isFocused = false; } @Override public abstract void update (double elapsedTime); @Override public void paint (Graphics2D pen) { if (myImage != null) { pen.drawImage(myImage, (int) myPos.x, (int) myPos.y, mySize.width, mySize.height, null); } } public abstract void processClick (); public abstract void processHover (); public boolean checkWithinBounds (int x, int y) { return (x > myPos.x && y > myPos.y && x < (myPos.x + mySize.width) && y < (myPos.y + mySize.height)); } public Dimension getSize () { return mySize; } public void setSize (Dimension s) { mySize = s; } public Location getPos () { return myPos; } public void setPos (Location l) { myPos = l; } public void setFocused (boolean b) { isFocused = b; } }
true
true
public Button (String image, Dimension size, Location pos) { if (image != null) { myImage = ResourceManager.getInstance().<BufferedImage>getFile(image, BufferedImage.class); } mySize = size; myPos = pos; isFocused = false; }
public Button (String image, Dimension size, Location pos) { if (image != null) { myImage = ResourceManager.getInstance().<BufferedImage> getFile(image, BufferedImage.class); } mySize = size; myPos = pos; isFocused = false; }
diff --git a/src/com/vaadin/terminal/gwt/server/ApplicationPortlet.java b/src/com/vaadin/terminal/gwt/server/ApplicationPortlet.java index 755994577..51e148a76 100644 --- a/src/com/vaadin/terminal/gwt/server/ApplicationPortlet.java +++ b/src/com/vaadin/terminal/gwt/server/ApplicationPortlet.java @@ -1,244 +1,244 @@ package com.vaadin.terminal.gwt.server; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Serializable; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortalContext; import javax.portlet.Portlet; import javax.portlet.PortletConfig; import javax.portlet.PortletException; import javax.portlet.PortletRequestDispatcher; import javax.portlet.PortletSession; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import com.liferay.portal.kernel.util.PropsUtil; import com.vaadin.Application; @SuppressWarnings("serial") public class ApplicationPortlet implements Portlet, Serializable { // portlet configuration parameters private static final String PORTLET_PARAMETER_APPLICATION = "application"; private static final String PORTLET_PARAMETER_STYLE = "style"; private static final String PORTLET_PARAMETER_WIDGETSET = "widgetset"; // portal configuration parameters private static final String PORTAL_PARAMETER_VAADIN_WIDGETSET = "vaadin.widgetset"; private static final String PORTAL_PARAMETER_VAADIN_RESOURCE_PATH = "vaadin.resources.path"; private static final String PORTAL_PARAMETER_VAADIN_THEME = "vaadin.theme"; // The application to show protected String app = null; // some applications might require forced height (and, more seldom, width) protected String style = null; // e.g "height:500px;" // force the portlet to use this widgetset - portlet level setting protected String portletWidgetset = null; public void destroy() { } public void init(PortletConfig config) throws PortletException { app = config.getInitParameter(PORTLET_PARAMETER_APPLICATION); if (app == null) { throw new PortletException( "No porlet application url defined in portlet.xml. Define the '" + PORTLET_PARAMETER_APPLICATION + "' init parameter to be the servlet deployment path."); } style = config.getInitParameter(PORTLET_PARAMETER_STYLE); // enable forcing the selection of the widgetset in portlet // configuration for a single portlet (backwards compatibility) portletWidgetset = config.getInitParameter(PORTLET_PARAMETER_WIDGETSET); } public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException { PortletApplicationContext.dispatchRequest(this, request, response); } public void render(RenderRequest request, RenderResponse response) throws PortletException, IOException { // display the Vaadin application writeAjaxWindow(request, response); } protected void writeAjaxWindow(RenderRequest request, RenderResponse response) throws IOException { response.setContentType("text/html"); if (app != null) { PortletSession sess = request.getPortletSession(); PortletApplicationContext ctx = PortletApplicationContext .getApplicationContext(sess); PortletRequestDispatcher dispatcher = sess.getPortletContext() .getRequestDispatcher("/" + app); try { // portal-wide settings PortalContext portalCtx = request.getPortalContext(); boolean isLifeRay = portalCtx.getPortalInfo().toLowerCase() .contains("liferay"); request.setAttribute(ApplicationServlet.REQUEST_FRAGMENT, "true"); // fixed base theme to use - all portal pages with Vaadin // applications will load this exactly once String portalTheme = getPortalProperty( PORTAL_PARAMETER_VAADIN_THEME, portalCtx); String portalWidgetset = getPortalProperty( PORTAL_PARAMETER_VAADIN_WIDGETSET, portalCtx); // location of the widgetset(s) and default theme (to which // /VAADIN/widgetsets/... // is appended) String portalResourcePath = getPortalProperty( PORTAL_PARAMETER_VAADIN_RESOURCE_PATH, portalCtx); // by default on LifeRay, widgetset and default theme is in // /html/VAADIN/widgetsets/... if (isLifeRay && portalResourcePath == null) { portalResourcePath = "/html"; } // - if the user has specified a widgetset for this portlet, use // it from the portlet (not fully supported) // - otherwise, if specified, use the portal-wide widgetset // and widgetset path settings (recommended) // - finally, default to use the default widgetset if nothing // else is found if (portalWidgetset != null) { if (portalResourcePath != null) { request .setAttribute( ApplicationServlet.REQUEST_VAADIN_WIDGETSET_PATH, portalResourcePath); } request.setAttribute(ApplicationServlet.REQUEST_WIDGETSET, portalWidgetset); } else if (portletWidgetset != null) { request.setAttribute(ApplicationServlet.REQUEST_WIDGETSET, portletWidgetset); } if (style != null) { request.setAttribute(ApplicationServlet.REQUEST_APPSTYLE, style); } String themeUri = null; if (portalTheme != null) { themeUri = portalResourcePath + "/" + AbstractApplicationServlet.THEME_DIRECTORY_PATH + portalTheme; request.setAttribute( ApplicationServlet.REQUEST_DEFAULT_THEME_URI, portalTheme); } /* * Make sure portal default Vaadin theme is included exactly * once in DOM. */ if (portalTheme != null) { OutputStream out = response.getPortletOutputStream(); // Using portal-wide theme String loadDefaultTheme = ("<script type=\"text/javascript\">\n" + "if(!vaadin) { var vaadin = {} } \n" + "if(!vaadin.themesLoaded) { vaadin.themesLoaded = {} } \n" + "if(!vaadin.themesLoaded['" + portalTheme + "']) {\n" + "var stylesheet = document.createElement('link');\n" + "stylesheet.setAttribute('rel', 'stylesheet');\n" + "stylesheet.setAttribute('type', 'text/css');\n" + "stylesheet.setAttribute('href', '" + themeUri + "/styles.css');\n" + "document.getElementsByTagName('head')[0].appendChild(stylesheet);\n" + "vaadin.themesLoaded['" + portalTheme + "'] = true;\n}\n" + "</script>\n"); out.write(loadDefaultTheme.getBytes()); } dispatcher.include(request, response); if (isLifeRay) { /* * Temporary support to heartbeat Liferay session when using * Vaadin based portlet. We hit an extra xhr to liferay * servlet to extend the session lifetime after each Vaadin * request. This hack can be removed when supporting portlet * 2.0 and resourceRequests. * * TODO make this configurable, this is not necessary with * some custom session configurations. */ OutputStream out = response.getPortletOutputStream(); String lifeRaySessionHearbeatHack = ("<script type=\"text/javascript\">" + "if(!vaadin.postRequestHooks) {" + " vaadin.postRequestHooks = {};" + "}" + "vaadin.postRequestHooks.liferaySessionHeartBeat = function() {" - + " if (Liferay && Liferay.Session) {" - + " Liferay.Session.extend();" + + " if (Liferay && Liferay.Session && Liferay.Session.setCookie) {" + + " Liferay.Session.setCookie();" + " }" + "};" + "</script>"); out.write(lifeRaySessionHearbeatHack.getBytes()); } } catch (PortletException e) { PrintWriter out = response.getWriter(); out.print("<h1>Servlet include failed!</h1>"); out.print("<div>" + e + "</div>"); ctx.setPortletApplication(this, null); return; } Application app = (Application) request .getAttribute(Application.class.getName()); ctx.setPortletApplication(this, app); ctx.firePortletRenderRequest(this, request, response); } } private String getPortalProperty(String name, PortalContext context) { boolean isLifeRay = context.getPortalInfo().toLowerCase().contains( "liferay"); // TODO test on non-LifeRay platforms String value; if (isLifeRay) { value = getLifeRayPortalProperty(name); } else { value = context.getProperty(name); } return value; } private String getLifeRayPortalProperty(String name) { String value; try { value = PropsUtil.get(name); } catch (Exception e) { value = null; } return value; } }
true
true
protected void writeAjaxWindow(RenderRequest request, RenderResponse response) throws IOException { response.setContentType("text/html"); if (app != null) { PortletSession sess = request.getPortletSession(); PortletApplicationContext ctx = PortletApplicationContext .getApplicationContext(sess); PortletRequestDispatcher dispatcher = sess.getPortletContext() .getRequestDispatcher("/" + app); try { // portal-wide settings PortalContext portalCtx = request.getPortalContext(); boolean isLifeRay = portalCtx.getPortalInfo().toLowerCase() .contains("liferay"); request.setAttribute(ApplicationServlet.REQUEST_FRAGMENT, "true"); // fixed base theme to use - all portal pages with Vaadin // applications will load this exactly once String portalTheme = getPortalProperty( PORTAL_PARAMETER_VAADIN_THEME, portalCtx); String portalWidgetset = getPortalProperty( PORTAL_PARAMETER_VAADIN_WIDGETSET, portalCtx); // location of the widgetset(s) and default theme (to which // /VAADIN/widgetsets/... // is appended) String portalResourcePath = getPortalProperty( PORTAL_PARAMETER_VAADIN_RESOURCE_PATH, portalCtx); // by default on LifeRay, widgetset and default theme is in // /html/VAADIN/widgetsets/... if (isLifeRay && portalResourcePath == null) { portalResourcePath = "/html"; } // - if the user has specified a widgetset for this portlet, use // it from the portlet (not fully supported) // - otherwise, if specified, use the portal-wide widgetset // and widgetset path settings (recommended) // - finally, default to use the default widgetset if nothing // else is found if (portalWidgetset != null) { if (portalResourcePath != null) { request .setAttribute( ApplicationServlet.REQUEST_VAADIN_WIDGETSET_PATH, portalResourcePath); } request.setAttribute(ApplicationServlet.REQUEST_WIDGETSET, portalWidgetset); } else if (portletWidgetset != null) { request.setAttribute(ApplicationServlet.REQUEST_WIDGETSET, portletWidgetset); } if (style != null) { request.setAttribute(ApplicationServlet.REQUEST_APPSTYLE, style); } String themeUri = null; if (portalTheme != null) { themeUri = portalResourcePath + "/" + AbstractApplicationServlet.THEME_DIRECTORY_PATH + portalTheme; request.setAttribute( ApplicationServlet.REQUEST_DEFAULT_THEME_URI, portalTheme); } /* * Make sure portal default Vaadin theme is included exactly * once in DOM. */ if (portalTheme != null) { OutputStream out = response.getPortletOutputStream(); // Using portal-wide theme String loadDefaultTheme = ("<script type=\"text/javascript\">\n" + "if(!vaadin) { var vaadin = {} } \n" + "if(!vaadin.themesLoaded) { vaadin.themesLoaded = {} } \n" + "if(!vaadin.themesLoaded['" + portalTheme + "']) {\n" + "var stylesheet = document.createElement('link');\n" + "stylesheet.setAttribute('rel', 'stylesheet');\n" + "stylesheet.setAttribute('type', 'text/css');\n" + "stylesheet.setAttribute('href', '" + themeUri + "/styles.css');\n" + "document.getElementsByTagName('head')[0].appendChild(stylesheet);\n" + "vaadin.themesLoaded['" + portalTheme + "'] = true;\n}\n" + "</script>\n"); out.write(loadDefaultTheme.getBytes()); } dispatcher.include(request, response); if (isLifeRay) { /* * Temporary support to heartbeat Liferay session when using * Vaadin based portlet. We hit an extra xhr to liferay * servlet to extend the session lifetime after each Vaadin * request. This hack can be removed when supporting portlet * 2.0 and resourceRequests. * * TODO make this configurable, this is not necessary with * some custom session configurations. */ OutputStream out = response.getPortletOutputStream(); String lifeRaySessionHearbeatHack = ("<script type=\"text/javascript\">" + "if(!vaadin.postRequestHooks) {" + " vaadin.postRequestHooks = {};" + "}" + "vaadin.postRequestHooks.liferaySessionHeartBeat = function() {" + " if (Liferay && Liferay.Session) {" + " Liferay.Session.extend();" + " }" + "};" + "</script>"); out.write(lifeRaySessionHearbeatHack.getBytes()); } } catch (PortletException e) { PrintWriter out = response.getWriter(); out.print("<h1>Servlet include failed!</h1>"); out.print("<div>" + e + "</div>"); ctx.setPortletApplication(this, null); return; } Application app = (Application) request .getAttribute(Application.class.getName()); ctx.setPortletApplication(this, app); ctx.firePortletRenderRequest(this, request, response); } }
protected void writeAjaxWindow(RenderRequest request, RenderResponse response) throws IOException { response.setContentType("text/html"); if (app != null) { PortletSession sess = request.getPortletSession(); PortletApplicationContext ctx = PortletApplicationContext .getApplicationContext(sess); PortletRequestDispatcher dispatcher = sess.getPortletContext() .getRequestDispatcher("/" + app); try { // portal-wide settings PortalContext portalCtx = request.getPortalContext(); boolean isLifeRay = portalCtx.getPortalInfo().toLowerCase() .contains("liferay"); request.setAttribute(ApplicationServlet.REQUEST_FRAGMENT, "true"); // fixed base theme to use - all portal pages with Vaadin // applications will load this exactly once String portalTheme = getPortalProperty( PORTAL_PARAMETER_VAADIN_THEME, portalCtx); String portalWidgetset = getPortalProperty( PORTAL_PARAMETER_VAADIN_WIDGETSET, portalCtx); // location of the widgetset(s) and default theme (to which // /VAADIN/widgetsets/... // is appended) String portalResourcePath = getPortalProperty( PORTAL_PARAMETER_VAADIN_RESOURCE_PATH, portalCtx); // by default on LifeRay, widgetset and default theme is in // /html/VAADIN/widgetsets/... if (isLifeRay && portalResourcePath == null) { portalResourcePath = "/html"; } // - if the user has specified a widgetset for this portlet, use // it from the portlet (not fully supported) // - otherwise, if specified, use the portal-wide widgetset // and widgetset path settings (recommended) // - finally, default to use the default widgetset if nothing // else is found if (portalWidgetset != null) { if (portalResourcePath != null) { request .setAttribute( ApplicationServlet.REQUEST_VAADIN_WIDGETSET_PATH, portalResourcePath); } request.setAttribute(ApplicationServlet.REQUEST_WIDGETSET, portalWidgetset); } else if (portletWidgetset != null) { request.setAttribute(ApplicationServlet.REQUEST_WIDGETSET, portletWidgetset); } if (style != null) { request.setAttribute(ApplicationServlet.REQUEST_APPSTYLE, style); } String themeUri = null; if (portalTheme != null) { themeUri = portalResourcePath + "/" + AbstractApplicationServlet.THEME_DIRECTORY_PATH + portalTheme; request.setAttribute( ApplicationServlet.REQUEST_DEFAULT_THEME_URI, portalTheme); } /* * Make sure portal default Vaadin theme is included exactly * once in DOM. */ if (portalTheme != null) { OutputStream out = response.getPortletOutputStream(); // Using portal-wide theme String loadDefaultTheme = ("<script type=\"text/javascript\">\n" + "if(!vaadin) { var vaadin = {} } \n" + "if(!vaadin.themesLoaded) { vaadin.themesLoaded = {} } \n" + "if(!vaadin.themesLoaded['" + portalTheme + "']) {\n" + "var stylesheet = document.createElement('link');\n" + "stylesheet.setAttribute('rel', 'stylesheet');\n" + "stylesheet.setAttribute('type', 'text/css');\n" + "stylesheet.setAttribute('href', '" + themeUri + "/styles.css');\n" + "document.getElementsByTagName('head')[0].appendChild(stylesheet);\n" + "vaadin.themesLoaded['" + portalTheme + "'] = true;\n}\n" + "</script>\n"); out.write(loadDefaultTheme.getBytes()); } dispatcher.include(request, response); if (isLifeRay) { /* * Temporary support to heartbeat Liferay session when using * Vaadin based portlet. We hit an extra xhr to liferay * servlet to extend the session lifetime after each Vaadin * request. This hack can be removed when supporting portlet * 2.0 and resourceRequests. * * TODO make this configurable, this is not necessary with * some custom session configurations. */ OutputStream out = response.getPortletOutputStream(); String lifeRaySessionHearbeatHack = ("<script type=\"text/javascript\">" + "if(!vaadin.postRequestHooks) {" + " vaadin.postRequestHooks = {};" + "}" + "vaadin.postRequestHooks.liferaySessionHeartBeat = function() {" + " if (Liferay && Liferay.Session && Liferay.Session.setCookie) {" + " Liferay.Session.setCookie();" + " }" + "};" + "</script>"); out.write(lifeRaySessionHearbeatHack.getBytes()); } } catch (PortletException e) { PrintWriter out = response.getWriter(); out.print("<h1>Servlet include failed!</h1>"); out.print("<div>" + e + "</div>"); ctx.setPortletApplication(this, null); return; } Application app = (Application) request .getAttribute(Application.class.getName()); ctx.setPortletApplication(this, app); ctx.firePortletRenderRequest(this, request, response); } }
diff --git a/src/org/nutz/dao/util/Pojos.java b/src/org/nutz/dao/util/Pojos.java index aad7ac65c..3ddfd2f1e 100644 --- a/src/org/nutz/dao/util/Pojos.java +++ b/src/org/nutz/dao/util/Pojos.java @@ -1,236 +1,234 @@ package org.nutz.dao.util; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.nutz.dao.Chain; import org.nutz.dao.Condition; import org.nutz.dao.FieldFilter; import org.nutz.dao.FieldMatcher; import org.nutz.dao.entity.Entity; import org.nutz.dao.entity.EntityField; import org.nutz.dao.entity.MappingField; import org.nutz.dao.entity.PkType; import org.nutz.dao.impl.jdbc.NutPojo; import org.nutz.dao.impl.sql.pojo.SingleColumnCondtionPItem; import org.nutz.dao.impl.sql.pojo.PkConditionPItem; import org.nutz.dao.impl.sql.pojo.QueryEntityFieldsPItem; import org.nutz.dao.impl.sql.pojo.ConditionPItem; import org.nutz.dao.impl.sql.pojo.EntityTableNamePItem; import org.nutz.dao.impl.sql.pojo.EntityViewNamePItem; import org.nutz.dao.impl.sql.pojo.InsertFieldsPItem; import org.nutz.dao.impl.sql.pojo.InsertValuesPItem; import org.nutz.dao.impl.sql.pojo.SqlTypePItem; import org.nutz.dao.impl.sql.pojo.StaticPItem; import org.nutz.dao.impl.sql.pojo.UpdateFieldsByChainPItem; import org.nutz.dao.impl.sql.pojo.UpdateFieldsPItem; import org.nutz.dao.jdbc.JdbcExpert; import org.nutz.dao.jdbc.ValueAdaptor; import org.nutz.dao.pager.Pager; import org.nutz.dao.sql.Criteria; import org.nutz.dao.sql.PItem; import org.nutz.dao.sql.Pojo; import org.nutz.dao.sql.PojoCallback; import org.nutz.dao.sql.SqlType; import org.nutz.lang.Lang; import org.nutz.lang.Strings; import org.nutz.log.Log; import org.nutz.log.Logs; public abstract class Pojos { private static final Log log = Logs.get(); // ========================================================== // 以下是创建 POJO 语句元素的帮助方法 public static class Items { public static PItem sqlType() { return new SqlTypePItem(); } public static PItem entityTableName() { return new EntityTableNamePItem(); } public static PItem entityViewName() { return new EntityViewNamePItem(); } public static PItem wrap(String str) { return new StaticPItem(str); } public static PItem wrapf(String fmt, Object... args) { return new StaticPItem(String.format(fmt, args)); } public static PItem insertFields() { return new InsertFieldsPItem(); } public static PItem insertValues() { return new InsertValuesPItem(); } public static PItem updateFields(Object refer) { return new UpdateFieldsPItem(refer); } public static PItem updateFieldsBy(Chain chain) { return new UpdateFieldsByChainPItem(chain); } public static PItem queryEntityFields() { return new QueryEntityFieldsPItem(); } public static PItem cndId(Entity<?> en, Number id) { return cndColumn(en.getIdField(), id); } public static PItem cndName(Entity<?> en, String name) { return cndColumn(en.getNameField(), name); } public static PItem cndColumn(MappingField mappingField, Object def) { SingleColumnCondtionPItem re = new SingleColumnCondtionPItem(mappingField, def); re.setCasesensitive(mappingField.isCasesensitive()); return re; } public static PItem cndColumn(String colName, MappingField mappingField, Object def) { return new SingleColumnCondtionPItem( colName, mappingField.getTypeClass(), mappingField.getAdaptor(), def); } public static PItem cndPk(Entity<?> en, Object[] pks) { ValueAdaptor[] vas = new ValueAdaptor[en.getCompositePKFields().size()]; int i = 0; for (MappingField mf : en.getCompositePKFields()) vas[i++] = mf.getAdaptor(); return new PkConditionPItem(vas, pks); } public static PItem cndAuto(Entity<?> en, Object obj) { obj = Lang.first(obj); switch (en.getPkType()) { case ID: Number id = null != obj ? ((Number) en.getIdField().getValue(obj)) : null; return cndId(en, id); case NAME: String name = null != obj ? en.getNameField().getValue(obj).toString() : null; return cndName(en, name); case COMPOSITE: Object[] pks = null; if (null != obj) { pks = new Object[en.getCompositePKFields().size()]; int i = 0; for (EntityField ef : en.getCompositePKFields()) pks[i++] = ef.getValue(obj); } return cndPk(en, pks); default: if (Map.class.isAssignableFrom(en.getType())){ - log.infof("Don't know how to make fetch key %s:'%s'", en.getType() - .getName(), obj); - return null; + return null; //Map形式的话,不一定需要主键嘛 } throw Lang.makeThrow("Don't know how to make fetch key %s:'%s'", en.getType() .getName(), obj); } } public static PItem[] cnd(Condition cnd) { List<PItem> list = new LinkedList<PItem>(); if (null == cnd) {} // 高级条件 else if (cnd instanceof Criteria) { list.add((Criteria) cnd); } // 普通条件 else { list.add(new ConditionPItem(cnd)); } return list.toArray(new PItem[list.size()]); } public static Pager pager(Condition cnd) { if (null == cnd) { return null; } // 高级条件 else if (cnd instanceof Criteria) { return ((Criteria) cnd).getPager(); } // 普通条件 else { return null; } } } // 以上是创建 POJO 语句元素的帮助方法 // ========================================================== public static Pojo createRun(PojoCallback callback) { return new NutPojo().setSqlType(SqlType.RUN).setAfter(callback); } public static List<MappingField> getFieldsForInsert(Entity<?> en, FieldMatcher fm) { List<MappingField> re = new ArrayList<MappingField>(en.getMappingFields().size()); for (MappingField mf : en.getMappingFields()) { if (!mf.isAutoIncreasement() && !mf.isReadonly()) if (null == fm || fm.match(mf.getName())) re.add(mf); } return re; } public static List<MappingField> getFieldsForUpdate(Entity<?> en, FieldMatcher fm, Object refer) { List<MappingField> re = new ArrayList<MappingField>(en.getMappingFields().size()); for (MappingField mf : en.getMappingFields()) { if (mf.isPk()) { if (en.getPkType() == PkType.ID && mf.isId()) continue; if (en.getPkType() == PkType.NAME && mf.isName()) continue; if (en.getPkType() == PkType.COMPOSITE && mf.isCompositePk()) continue; } if (mf.isReadonly() || mf.isAutoIncreasement()) continue; else if (null != fm && null != refer && fm.isIgnoreNull() && null == mf.getValue(refer)) continue; if (null == fm || fm.match(mf.getName())) re.add(mf); } return re; } private static final Pattern ptn = Pattern.compile( "^(WHERE|ORDER BY)(.+)", Pattern.CASE_INSENSITIVE); public static String formatCondition(Entity<?> en, Condition cnd) { if (null != cnd) { String str = Strings.trim(cnd.toSql(en)); if (!ptn.matcher(str).find()) return "WHERE " + str; return str; } return ""; } public static Pojo pojo(JdbcExpert expert, Entity<?> en, SqlType type) { Pojo pojo = expert.createPojo(type); pojo.getContext().setFieldMatcher(FieldFilter.get(en.getType())); return pojo; } }
true
true
public static PItem cndAuto(Entity<?> en, Object obj) { obj = Lang.first(obj); switch (en.getPkType()) { case ID: Number id = null != obj ? ((Number) en.getIdField().getValue(obj)) : null; return cndId(en, id); case NAME: String name = null != obj ? en.getNameField().getValue(obj).toString() : null; return cndName(en, name); case COMPOSITE: Object[] pks = null; if (null != obj) { pks = new Object[en.getCompositePKFields().size()]; int i = 0; for (EntityField ef : en.getCompositePKFields()) pks[i++] = ef.getValue(obj); } return cndPk(en, pks); default: if (Map.class.isAssignableFrom(en.getType())){ log.infof("Don't know how to make fetch key %s:'%s'", en.getType() .getName(), obj); return null; } throw Lang.makeThrow("Don't know how to make fetch key %s:'%s'", en.getType() .getName(), obj); } }
public static PItem cndAuto(Entity<?> en, Object obj) { obj = Lang.first(obj); switch (en.getPkType()) { case ID: Number id = null != obj ? ((Number) en.getIdField().getValue(obj)) : null; return cndId(en, id); case NAME: String name = null != obj ? en.getNameField().getValue(obj).toString() : null; return cndName(en, name); case COMPOSITE: Object[] pks = null; if (null != obj) { pks = new Object[en.getCompositePKFields().size()]; int i = 0; for (EntityField ef : en.getCompositePKFields()) pks[i++] = ef.getValue(obj); } return cndPk(en, pks); default: if (Map.class.isAssignableFrom(en.getType())){ return null; //Map形式的话,不一定需要主键嘛 } throw Lang.makeThrow("Don't know how to make fetch key %s:'%s'", en.getType() .getName(), obj); } }
diff --git a/src/org/ohmage/request/survey/SurveyUploadRequest.java b/src/org/ohmage/request/survey/SurveyUploadRequest.java index 21e4fe39..00253dd6 100644 --- a/src/org/ohmage/request/survey/SurveyUploadRequest.java +++ b/src/org/ohmage/request/survey/SurveyUploadRequest.java @@ -1,398 +1,402 @@ /******************************************************************************* * Copyright 2012 The Regents of the University of California * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.ohmage.request.survey; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.json.JSONObject; import org.ohmage.annotator.Annotator.ErrorCode; import org.ohmage.domain.Image; import org.ohmage.domain.Video; import org.ohmage.domain.campaign.Campaign; import org.ohmage.domain.campaign.SurveyResponse; import org.ohmage.exception.InvalidRequestException; import org.ohmage.exception.ServiceException; import org.ohmage.exception.ValidationException; import org.ohmage.request.InputKeys; import org.ohmage.request.UserRequest; import org.ohmage.service.CampaignServices; import org.ohmage.service.SurveyResponseServices; import org.ohmage.service.UserCampaignServices; import org.ohmage.util.DateTimeUtils; import org.ohmage.validator.CampaignValidators; import org.ohmage.validator.ImageValidators; import org.ohmage.validator.SurveyResponseValidators; /** * <p>Stores a survey and its associated images (if any are present in the payload)</p> * <table border="1"> * <tr> * <td>Parameter Name</td> * <td>Description</td> * <td>Required</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#CLIENT}</td> * <td>A string describing the client that is making this request.</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#USERNAME}</td> * <td>The username of the uploader.</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#PASSWORD}</td> * <td>The password for the associated username/</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#CAMPAIGN_URN}</td> * <td>The campaign URN for the survey(s) being uploaded.</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#CAMPAIGN_CREATION_TIMESTAMP}</td> * <td>The creation timestamp for the campaign. This parameter is used to * ensure that the client's campaign is up-to-date.</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#SURVEYS}</td> * <td>The survey data payload for the survey(s) being uploaded.</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#IMAGES}</td> * <td>A JSON object where the keys are the image IDs and the values are * the images' contents BASE64-encoded.</td> * <td>Either this or the deprecated imageId/imageContents * multipart/form-post method must define all images in the payload.</td> * </tr> * <tr> * <td>The image's ID.</td> * <td>The image's constants.</td> * <td>One for every image in the payload. This is deprecated in favor of * the {@value org.ohmage.request.InputKeys#IMAGES} parameter.</td> * </tr> * </table> * * @author Joshua Selsky */ public class SurveyUploadRequest extends UserRequest { private static final Logger LOGGER = Logger.getLogger(SurveyUploadRequest.class); // The campaign creation timestamp is stored as a String because it is // never used in any kind of calculation. private final String campaignUrn; private final DateTime campaignCreationTimestamp; private List<JSONObject> jsonData; private final Map<UUID, Image> imageContentsMap; private final Map<String, Video> videoContentsMap; private Collection<UUID> surveyResponseIds; /** * Creates a new image upload request. * * @param httpRequest The HttpServletRequest with the parameters for this * request. * * @throws InvalidRequestException Thrown if the parameters cannot be * parsed. * * @throws IOException There was an error reading from the request. */ public SurveyUploadRequest(HttpServletRequest httpRequest) throws IOException, InvalidRequestException { super(httpRequest, false, null, null); LOGGER.info("Creating a survey upload request."); String tCampaignUrn = null; DateTime tCampaignCreationTimestamp = null; List<JSONObject> tJsonData = null; Map<UUID, Image> tImageContentsMap = null; Map<String, Video> tVideoContentsMap = null; if(! isFailed()) { try { Map<String, String[]> parameters = getParameters(); // Validate the campaign URN String[] t = parameters.get(InputKeys.CAMPAIGN_URN); if(t == null || t.length != 1) { throw new ValidationException(ErrorCode.CAMPAIGN_INVALID_ID, "campaign_urn is missing or there is more than one."); } else { tCampaignUrn = CampaignValidators.validateCampaignId(t[0]); if(tCampaignUrn == null) { throw new ValidationException(ErrorCode.CAMPAIGN_INVALID_ID, "The campaign ID is invalid."); } } // Validate the campaign creation timestamp t = parameters.get(InputKeys.CAMPAIGN_CREATION_TIMESTAMP); if(t == null || t.length != 1) { throw new ValidationException(ErrorCode.SERVER_INVALID_TIMESTAMP, "campaign_creation_timestamp is missing or there is more than one"); } else { - // Make sure it's a valid timestamp + // Make sure it's a valid timestamp. try { - tCampaignCreationTimestamp = DateTimeUtils.getDateTimeFromString(t[0]); + tCampaignCreationTimestamp = + DateTimeUtils.getDateTimeFromString(t[0]); } catch(IllegalArgumentException e) { - setFailed(ErrorCode.SERVER_INVALID_DATE, e.getMessage()); - throw e; + throw + new ValidationException( + ErrorCode.SERVER_INVALID_DATE, + e.getMessage(), + e); } } t = parameters.get(InputKeys.SURVEYS); if(t == null || t.length != 1) { throw new ValidationException( ErrorCode.SURVEY_INVALID_RESPONSES, "No value found for 'surveys' parameter or multiple surveys parameters were found."); } else { try { tJsonData = CampaignValidators.validateUploadedJson(t[0]); } catch(IllegalArgumentException e) { throw new ValidationException( ErrorCode.SURVEY_INVALID_RESPONSES, "The survey responses could not be URL decoded.", e); } } tImageContentsMap = new HashMap<UUID, Image>(); t = getParameterValues(InputKeys.IMAGES); if(t.length > 1) { throw new ValidationException( ErrorCode.SURVEY_INVALID_IMAGES_VALUE, "Multiple images parameters were given: " + InputKeys.IMAGES); } else if(t.length == 1) { LOGGER.debug("Validating the BASE64-encoded images."); Map<UUID, Image> images = SurveyResponseValidators.validateImages(t[0]); if(images != null) { tImageContentsMap.putAll(images); } } // Retrieve and validate images and videos. List<UUID> imageIds = new ArrayList<UUID>(); tVideoContentsMap = new HashMap<String, Video>(); Collection<Part> parts = null; try { // FIXME - push to base class especially because of the ServletException that gets thrown parts = httpRequest.getParts(); for(Part p : parts) { UUID id; String name = p.getName(); try { id = UUID.fromString(name); } catch (IllegalArgumentException e) { LOGGER.info("Ignoring part: " + name); continue; } String contentType = p.getContentType(); if(contentType.startsWith("image")) { imageIds.add(id); } else if(contentType.startsWith("video/")) { tVideoContentsMap.put( name, new Video( UUID.fromString(name), contentType.split("/")[1], getMultipartValue(httpRequest, name))); } } } catch(ServletException e) { LOGGER.info("This is not a multipart/form-post."); } catch(IOException e) { LOGGER.error("cannot parse parts", e); setFailed(); throw new ValidationException(e); } Set<UUID> stringSet = new HashSet<UUID>(imageIds); if(stringSet.size() != imageIds.size()) { throw new ValidationException(ErrorCode.IMAGE_INVALID_DATA, "a duplicate image key was detected in the multi-part upload"); } for(UUID imageId : imageIds) { Image image = ImageValidators .validateImageContents( imageId, getMultipartValue( httpRequest, imageId.toString())); if(image == null) { throw new ValidationException( ErrorCode.IMAGE_INVALID_DATA, "The image data is missing: " + imageId); } tImageContentsMap.put(imageId, image); if(LOGGER.isDebugEnabled()) { LOGGER.debug("succesfully created a BufferedImage for key " + imageId); } } } catch(ValidationException e) { e.failRequest(this); e.logException(LOGGER, true); } } this.campaignUrn = tCampaignUrn; this.campaignCreationTimestamp = tCampaignCreationTimestamp; this.jsonData = tJsonData; this.imageContentsMap = tImageContentsMap; this.videoContentsMap = tVideoContentsMap; surveyResponseIds = null; } /** * Services the request. */ @Override public void service() { LOGGER.info("Servicing a survey upload request."); if(! authenticate(AllowNewAccount.NEW_ACCOUNT_DISALLOWED)) { return; } try { LOGGER.info("Verifying that the user is a participant in the campaign."); UserCampaignServices.instance().verifyUserCanUploadSurveyResponses(getUser().getUsername(), campaignUrn); LOGGER.info("Verifying that the campaign is running."); CampaignServices.instance().verifyCampaignIsRunning(campaignUrn); LOGGER.info("Verifying that the uploaded survey responses aren't out of date."); CampaignServices.instance().verifyCampaignIsUpToDate(campaignUrn, campaignCreationTimestamp); LOGGER.info("Generating the campaign object."); Campaign campaign = CampaignServices.instance().getCampaign(campaignUrn); LOGGER.info("Verifying the uploaded data against the campaign."); List<SurveyResponse> surveyResponses = CampaignServices.instance().getSurveyResponses( getUser().getUsername(), getClient(), campaign, jsonData); surveyResponseIds = new ArrayList<UUID>(surveyResponses.size()); for(SurveyResponse surveyResponse : surveyResponses) { surveyResponseIds.add(surveyResponse.getSurveyResponseId()); } LOGGER.info("Validating that all photo prompt responses have their corresponding images attached."); SurveyResponseServices.instance().verifyImagesExistForPhotoPromptResponses(surveyResponses, imageContentsMap); LOGGER.info("Validating that all video prompt responses have their corresponding videos attached."); SurveyResponseServices.instance().verifyVideosExistForVideoPromptResponses(surveyResponses, videoContentsMap); LOGGER.info("Inserting the data into the database."); List<Integer> duplicateIndexList = SurveyResponseServices.instance().createSurveyResponses( getUser().getUsername(), getClient(), campaignUrn, surveyResponses, imageContentsMap, videoContentsMap); LOGGER.info("Found " + duplicateIndexList.size() + " duplicate survey uploads"); } catch(ServiceException e) { e.failRequest(this); e.logException(LOGGER, true); } } /** * Responds to the image upload request with success or a failure message * that contains a failure code and failure text. */ @Override public void respond(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { LOGGER.info("Responding to the survey upload request."); super.respond(httpRequest, httpResponse, (JSONObject) null); } /** * If the upload was successful, this records the UUIDs of the successfully * uploaded survey responses to the audit's extras table. * * @return The parents audit information with the successfully uploaded * survey responses if the request was successful. */ @Override public Map<String, String[]> getAuditInformation() { Map<String, String[]> result = super.getAuditInformation(); if((! isFailed()) && (surveyResponseIds != null)) { int numSurveyResponseIdsAdded = 0; String[] surveyResponseIdsArray = new String[surveyResponseIds.size()]; for(UUID surveyResponseId : surveyResponseIds) { surveyResponseIdsArray[numSurveyResponseIdsAdded] = surveyResponseId.toString(); numSurveyResponseIdsAdded++; } result.put( "successfully_uploaded_survey_response_ids", surveyResponseIdsArray); } return result; } }
false
true
public SurveyUploadRequest(HttpServletRequest httpRequest) throws IOException, InvalidRequestException { super(httpRequest, false, null, null); LOGGER.info("Creating a survey upload request."); String tCampaignUrn = null; DateTime tCampaignCreationTimestamp = null; List<JSONObject> tJsonData = null; Map<UUID, Image> tImageContentsMap = null; Map<String, Video> tVideoContentsMap = null; if(! isFailed()) { try { Map<String, String[]> parameters = getParameters(); // Validate the campaign URN String[] t = parameters.get(InputKeys.CAMPAIGN_URN); if(t == null || t.length != 1) { throw new ValidationException(ErrorCode.CAMPAIGN_INVALID_ID, "campaign_urn is missing or there is more than one."); } else { tCampaignUrn = CampaignValidators.validateCampaignId(t[0]); if(tCampaignUrn == null) { throw new ValidationException(ErrorCode.CAMPAIGN_INVALID_ID, "The campaign ID is invalid."); } } // Validate the campaign creation timestamp t = parameters.get(InputKeys.CAMPAIGN_CREATION_TIMESTAMP); if(t == null || t.length != 1) { throw new ValidationException(ErrorCode.SERVER_INVALID_TIMESTAMP, "campaign_creation_timestamp is missing or there is more than one"); } else { // Make sure it's a valid timestamp try { tCampaignCreationTimestamp = DateTimeUtils.getDateTimeFromString(t[0]); } catch(IllegalArgumentException e) { setFailed(ErrorCode.SERVER_INVALID_DATE, e.getMessage()); throw e; } } t = parameters.get(InputKeys.SURVEYS); if(t == null || t.length != 1) { throw new ValidationException( ErrorCode.SURVEY_INVALID_RESPONSES, "No value found for 'surveys' parameter or multiple surveys parameters were found."); } else { try { tJsonData = CampaignValidators.validateUploadedJson(t[0]); } catch(IllegalArgumentException e) { throw new ValidationException( ErrorCode.SURVEY_INVALID_RESPONSES, "The survey responses could not be URL decoded.", e); } } tImageContentsMap = new HashMap<UUID, Image>(); t = getParameterValues(InputKeys.IMAGES); if(t.length > 1) { throw new ValidationException( ErrorCode.SURVEY_INVALID_IMAGES_VALUE, "Multiple images parameters were given: " + InputKeys.IMAGES); } else if(t.length == 1) { LOGGER.debug("Validating the BASE64-encoded images."); Map<UUID, Image> images = SurveyResponseValidators.validateImages(t[0]); if(images != null) { tImageContentsMap.putAll(images); } } // Retrieve and validate images and videos. List<UUID> imageIds = new ArrayList<UUID>(); tVideoContentsMap = new HashMap<String, Video>(); Collection<Part> parts = null; try { // FIXME - push to base class especially because of the ServletException that gets thrown parts = httpRequest.getParts(); for(Part p : parts) { UUID id; String name = p.getName(); try { id = UUID.fromString(name); } catch (IllegalArgumentException e) { LOGGER.info("Ignoring part: " + name); continue; } String contentType = p.getContentType(); if(contentType.startsWith("image")) { imageIds.add(id); } else if(contentType.startsWith("video/")) { tVideoContentsMap.put( name, new Video( UUID.fromString(name), contentType.split("/")[1], getMultipartValue(httpRequest, name))); } } } catch(ServletException e) { LOGGER.info("This is not a multipart/form-post."); } catch(IOException e) { LOGGER.error("cannot parse parts", e); setFailed(); throw new ValidationException(e); } Set<UUID> stringSet = new HashSet<UUID>(imageIds); if(stringSet.size() != imageIds.size()) { throw new ValidationException(ErrorCode.IMAGE_INVALID_DATA, "a duplicate image key was detected in the multi-part upload"); } for(UUID imageId : imageIds) { Image image = ImageValidators .validateImageContents( imageId, getMultipartValue( httpRequest, imageId.toString())); if(image == null) { throw new ValidationException( ErrorCode.IMAGE_INVALID_DATA, "The image data is missing: " + imageId); } tImageContentsMap.put(imageId, image); if(LOGGER.isDebugEnabled()) { LOGGER.debug("succesfully created a BufferedImage for key " + imageId); } } } catch(ValidationException e) { e.failRequest(this); e.logException(LOGGER, true); } } this.campaignUrn = tCampaignUrn; this.campaignCreationTimestamp = tCampaignCreationTimestamp; this.jsonData = tJsonData; this.imageContentsMap = tImageContentsMap; this.videoContentsMap = tVideoContentsMap; surveyResponseIds = null; }
public SurveyUploadRequest(HttpServletRequest httpRequest) throws IOException, InvalidRequestException { super(httpRequest, false, null, null); LOGGER.info("Creating a survey upload request."); String tCampaignUrn = null; DateTime tCampaignCreationTimestamp = null; List<JSONObject> tJsonData = null; Map<UUID, Image> tImageContentsMap = null; Map<String, Video> tVideoContentsMap = null; if(! isFailed()) { try { Map<String, String[]> parameters = getParameters(); // Validate the campaign URN String[] t = parameters.get(InputKeys.CAMPAIGN_URN); if(t == null || t.length != 1) { throw new ValidationException(ErrorCode.CAMPAIGN_INVALID_ID, "campaign_urn is missing or there is more than one."); } else { tCampaignUrn = CampaignValidators.validateCampaignId(t[0]); if(tCampaignUrn == null) { throw new ValidationException(ErrorCode.CAMPAIGN_INVALID_ID, "The campaign ID is invalid."); } } // Validate the campaign creation timestamp t = parameters.get(InputKeys.CAMPAIGN_CREATION_TIMESTAMP); if(t == null || t.length != 1) { throw new ValidationException(ErrorCode.SERVER_INVALID_TIMESTAMP, "campaign_creation_timestamp is missing or there is more than one"); } else { // Make sure it's a valid timestamp. try { tCampaignCreationTimestamp = DateTimeUtils.getDateTimeFromString(t[0]); } catch(IllegalArgumentException e) { throw new ValidationException( ErrorCode.SERVER_INVALID_DATE, e.getMessage(), e); } } t = parameters.get(InputKeys.SURVEYS); if(t == null || t.length != 1) { throw new ValidationException( ErrorCode.SURVEY_INVALID_RESPONSES, "No value found for 'surveys' parameter or multiple surveys parameters were found."); } else { try { tJsonData = CampaignValidators.validateUploadedJson(t[0]); } catch(IllegalArgumentException e) { throw new ValidationException( ErrorCode.SURVEY_INVALID_RESPONSES, "The survey responses could not be URL decoded.", e); } } tImageContentsMap = new HashMap<UUID, Image>(); t = getParameterValues(InputKeys.IMAGES); if(t.length > 1) { throw new ValidationException( ErrorCode.SURVEY_INVALID_IMAGES_VALUE, "Multiple images parameters were given: " + InputKeys.IMAGES); } else if(t.length == 1) { LOGGER.debug("Validating the BASE64-encoded images."); Map<UUID, Image> images = SurveyResponseValidators.validateImages(t[0]); if(images != null) { tImageContentsMap.putAll(images); } } // Retrieve and validate images and videos. List<UUID> imageIds = new ArrayList<UUID>(); tVideoContentsMap = new HashMap<String, Video>(); Collection<Part> parts = null; try { // FIXME - push to base class especially because of the ServletException that gets thrown parts = httpRequest.getParts(); for(Part p : parts) { UUID id; String name = p.getName(); try { id = UUID.fromString(name); } catch (IllegalArgumentException e) { LOGGER.info("Ignoring part: " + name); continue; } String contentType = p.getContentType(); if(contentType.startsWith("image")) { imageIds.add(id); } else if(contentType.startsWith("video/")) { tVideoContentsMap.put( name, new Video( UUID.fromString(name), contentType.split("/")[1], getMultipartValue(httpRequest, name))); } } } catch(ServletException e) { LOGGER.info("This is not a multipart/form-post."); } catch(IOException e) { LOGGER.error("cannot parse parts", e); setFailed(); throw new ValidationException(e); } Set<UUID> stringSet = new HashSet<UUID>(imageIds); if(stringSet.size() != imageIds.size()) { throw new ValidationException(ErrorCode.IMAGE_INVALID_DATA, "a duplicate image key was detected in the multi-part upload"); } for(UUID imageId : imageIds) { Image image = ImageValidators .validateImageContents( imageId, getMultipartValue( httpRequest, imageId.toString())); if(image == null) { throw new ValidationException( ErrorCode.IMAGE_INVALID_DATA, "The image data is missing: " + imageId); } tImageContentsMap.put(imageId, image); if(LOGGER.isDebugEnabled()) { LOGGER.debug("succesfully created a BufferedImage for key " + imageId); } } } catch(ValidationException e) { e.failRequest(this); e.logException(LOGGER, true); } } this.campaignUrn = tCampaignUrn; this.campaignCreationTimestamp = tCampaignCreationTimestamp; this.jsonData = tJsonData; this.imageContentsMap = tImageContentsMap; this.videoContentsMap = tVideoContentsMap; surveyResponseIds = null; }
diff --git a/web/src/main/java/org/eurekastreams/web/client/ui/common/GadgetMetaDataPanel.java b/web/src/main/java/org/eurekastreams/web/client/ui/common/GadgetMetaDataPanel.java index a79e881a7..963533a0a 100644 --- a/web/src/main/java/org/eurekastreams/web/client/ui/common/GadgetMetaDataPanel.java +++ b/web/src/main/java/org/eurekastreams/web/client/ui/common/GadgetMetaDataPanel.java @@ -1,292 +1,293 @@ /* * Copyright (c) 2009-2010 Lockheed Martin Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.eurekastreams.web.client.ui.common; import java.util.HashMap; import org.eurekastreams.server.action.request.start.ReorderGadgetRequest; import org.eurekastreams.server.domain.Page; import org.eurekastreams.server.domain.gadgetspec.GadgetMetaDataDTO; import org.eurekastreams.server.search.modelview.PersonModelView.Role; import org.eurekastreams.web.client.events.EventBus; import org.eurekastreams.web.client.events.GadgetAddedToStartPageEvent; import org.eurekastreams.web.client.events.Observer; import org.eurekastreams.web.client.events.ShowNotificationEvent; import org.eurekastreams.web.client.events.SwitchToFilterOnPagedFilterPanelEvent; import org.eurekastreams.web.client.events.UpdatedHistoryParametersEvent; import org.eurekastreams.web.client.history.CreateUrlRequest; import org.eurekastreams.web.client.jsni.WidgetJSNIFacadeImpl; import org.eurekastreams.web.client.model.Deletable; import org.eurekastreams.web.client.model.GadgetModel; import org.eurekastreams.web.client.model.requests.AddGadgetToStartPageRequest; import org.eurekastreams.web.client.ui.Session; import org.eurekastreams.web.client.ui.common.EditPanel.Mode; import org.eurekastreams.web.client.ui.common.notifier.Notification; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.user.client.History; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Hyperlink; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Panel; /** * Displays gadget metadata for the gallery. (and anything else I guess). * */ public class GadgetMetaDataPanel extends FlowPanel { /** * The tab id. */ private Long tabId; /** * Apply Gadget link. */ private Hyperlink applyGadget; /** * Drop zone id. */ private Integer dropZoneId = null; /** * Default constructor. * * @param metaData * the gadget meta data. * @param inTabId * the tab id. * @param model * the model to delete from. * @param deleteMessage * the delete message. */ public GadgetMetaDataPanel(final GadgetMetaDataDTO metaData, final Long inTabId, final Deletable<Long> model, final String deleteMessage) { Session.getInstance().getEventBus().addObserver(UpdatedHistoryParametersEvent.class, new Observer<UpdatedHistoryParametersEvent>() { public void update(final UpdatedHistoryParametersEvent event) { if (event.getParameters().get("dropzone") != null) { dropZoneId = Integer.valueOf(event.getParameters().get("dropzone")); } else { dropZoneId = null; } } }, true); tabId = inTabId; final FlowPanel thisBuffered = this; if (Session.getInstance().getCurrentPersonRoles().contains(Role.ORG_COORDINATOR)) { EditPanel editControls = new EditPanel(this, Mode.EDIT_AND_DELETE); if (tabId != null) { final HashMap<String, String> params = new HashMap<String, String>(); params.put("action", "editApp"); params.put("url", metaData.getGadgetDefinition().getUrl()); params.put("category", metaData.getGadgetDefinition().getCategory().toString()); params.put("id", String.valueOf(metaData.getGadgetDefinition().getId())); + params.put("tab", Session.getInstance().getParameterValue("tab")); final WidgetJSNIFacadeImpl jsni = new WidgetJSNIFacadeImpl(); editControls.addEditClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { jsni.setHistoryToken(Session.getInstance().generateUrl( new CreateUrlRequest(Page.GALLERY, params)), true); } }); } this.add(editControls); editControls.addDeleteClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { if (new WidgetJSNIFacadeImpl().confirm(deleteMessage)) { model.delete(metaData.getGadgetDefinition().getId()); Session.getInstance().getEventBus() .notifyObservers( new ShowNotificationEvent(new Notification(metaData.getTitle() + " has been deleted."))); thisBuffered.setVisible(false); } } }); } FlowPanel imageContainer = new FlowPanel(); imageContainer.addStyleName("image-container"); this.addStyleName("gadget-meta-data"); // Im a gadget. if (tabId != null) { if (metaData.getThumbnail() != null && !metaData.getThumbnail().equals("")) { imageContainer.add(new Image(metaData.getThumbnail())); } else { imageContainer.add(new Image("/style/images/gadget-gallery-default.png")); } applyGadget = new Hyperlink("Apply App", History.getToken()); applyGadget.addStyleName("apply-gadget"); applyGadget.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { GadgetModel.getInstance() .insert( new AddGadgetToStartPageRequest("{" + metaData.getGadgetDefinition().getUUID() + "}", tabId)); } }); Session.getInstance().getEventBus().addObserver(GadgetAddedToStartPageEvent.class, new Observer<GadgetAddedToStartPageEvent>() { public void update(final GadgetAddedToStartPageEvent arg1) { - Session.getInstance().getEventBus().notifyObservers(new ShowNotificationEvent( - new Notification("App has been added"))); + Session.getInstance().getEventBus().notifyObservers( + new ShowNotificationEvent(new Notification("App has been added"))); if (arg1.getGadget().getGadgetDefinition().getId() == metaData.getGadgetDefinition() .getId()) { setActive(true); if (dropZoneId != null) { GadgetModel.getInstance().reorder( new ReorderGadgetRequest(tabId, new Long(arg1.getGadget().getId()), dropZoneId, 0)); } } } }); imageContainer.add(applyGadget); } // Im a plugin else { if (metaData.getScreenshot() != null && !metaData.getScreenshot().equals("")) { FlowPanel screenShot = new FlowPanel(); screenShot.addStyleName("stream-plugins-screenshot"); imageContainer.add(screenShot); screenShot.add(new Image(metaData.getScreenshot())); } } FlowPanel dataPanel = new FlowPanel(); dataPanel.addStyleName("gadget-data"); Label title = new Label(metaData.getTitle()); title.addStyleName("title"); dataPanel.add(title); dataPanel.add(new HTML(metaData.getDescription())); Anchor titleUrl = new Anchor(metaData.getTitleUrl(), metaData.getTitleUrl(), "_blank"); titleUrl.addStyleName("gadget-title-url"); dataPanel.add(titleUrl); FlowPanel gadgetExtInfo = new FlowPanel(); gadgetExtInfo.addStyleName("gadget-ext-info"); gadgetExtInfo.add(new HTML("Category: ")); Anchor category = new Anchor(); category.setText(metaData.getGadgetDefinition().getCategory().getName()); category.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent arg0) { EventBus.getInstance().notifyObservers( new SwitchToFilterOnPagedFilterPanelEvent("gadgets", metaData.getGadgetDefinition() .getCategory().getName(), "Recent")); } }); gadgetExtInfo.add(category); insertActionSeparator(gadgetExtInfo); gadgetExtInfo.add(new HTML(" Users: <span class='light'>" + metaData.getGadgetDefinition().getNumberOfUsers() + "</span>")); insertActionSeparator(gadgetExtInfo); gadgetExtInfo.add(new HTML(" Author: <a href='mailto:" + metaData.getAuthorEmail() + "'>" + metaData.getAuthor() + "</a>")); insertActionSeparator(gadgetExtInfo); gadgetExtInfo.add(new HTML(" Publish date: <span class='light'>" + DateTimeFormat.getLongDateFormat().format(metaData.getGadgetDefinition().getCreated()) + "</span>")); dataPanel.add(gadgetExtInfo); this.add(imageContainer); this.add(dataPanel); } /** * Adds a separator (dot). * * @param panel * Panel to put the separator in. */ private void insertActionSeparator(final Panel panel) { Label sep = new InlineLabel("\u2219"); sep.addStyleName("action-link-separator"); panel.add(sep); } /** * Sets the theme as active or not. * * @param active * value. */ public void setActive(final Boolean active) { if (active) { applyGadget.addStyleName("active"); } else { applyGadget.removeStyleName("active"); } } }
false
true
public GadgetMetaDataPanel(final GadgetMetaDataDTO metaData, final Long inTabId, final Deletable<Long> model, final String deleteMessage) { Session.getInstance().getEventBus().addObserver(UpdatedHistoryParametersEvent.class, new Observer<UpdatedHistoryParametersEvent>() { public void update(final UpdatedHistoryParametersEvent event) { if (event.getParameters().get("dropzone") != null) { dropZoneId = Integer.valueOf(event.getParameters().get("dropzone")); } else { dropZoneId = null; } } }, true); tabId = inTabId; final FlowPanel thisBuffered = this; if (Session.getInstance().getCurrentPersonRoles().contains(Role.ORG_COORDINATOR)) { EditPanel editControls = new EditPanel(this, Mode.EDIT_AND_DELETE); if (tabId != null) { final HashMap<String, String> params = new HashMap<String, String>(); params.put("action", "editApp"); params.put("url", metaData.getGadgetDefinition().getUrl()); params.put("category", metaData.getGadgetDefinition().getCategory().toString()); params.put("id", String.valueOf(metaData.getGadgetDefinition().getId())); final WidgetJSNIFacadeImpl jsni = new WidgetJSNIFacadeImpl(); editControls.addEditClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { jsni.setHistoryToken(Session.getInstance().generateUrl( new CreateUrlRequest(Page.GALLERY, params)), true); } }); } this.add(editControls); editControls.addDeleteClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { if (new WidgetJSNIFacadeImpl().confirm(deleteMessage)) { model.delete(metaData.getGadgetDefinition().getId()); Session.getInstance().getEventBus() .notifyObservers( new ShowNotificationEvent(new Notification(metaData.getTitle() + " has been deleted."))); thisBuffered.setVisible(false); } } }); } FlowPanel imageContainer = new FlowPanel(); imageContainer.addStyleName("image-container"); this.addStyleName("gadget-meta-data"); // Im a gadget. if (tabId != null) { if (metaData.getThumbnail() != null && !metaData.getThumbnail().equals("")) { imageContainer.add(new Image(metaData.getThumbnail())); } else { imageContainer.add(new Image("/style/images/gadget-gallery-default.png")); } applyGadget = new Hyperlink("Apply App", History.getToken()); applyGadget.addStyleName("apply-gadget"); applyGadget.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { GadgetModel.getInstance() .insert( new AddGadgetToStartPageRequest("{" + metaData.getGadgetDefinition().getUUID() + "}", tabId)); } }); Session.getInstance().getEventBus().addObserver(GadgetAddedToStartPageEvent.class, new Observer<GadgetAddedToStartPageEvent>() { public void update(final GadgetAddedToStartPageEvent arg1) { Session.getInstance().getEventBus().notifyObservers(new ShowNotificationEvent( new Notification("App has been added"))); if (arg1.getGadget().getGadgetDefinition().getId() == metaData.getGadgetDefinition() .getId()) { setActive(true); if (dropZoneId != null) { GadgetModel.getInstance().reorder( new ReorderGadgetRequest(tabId, new Long(arg1.getGadget().getId()), dropZoneId, 0)); } } } }); imageContainer.add(applyGadget); } // Im a plugin else { if (metaData.getScreenshot() != null && !metaData.getScreenshot().equals("")) { FlowPanel screenShot = new FlowPanel(); screenShot.addStyleName("stream-plugins-screenshot"); imageContainer.add(screenShot); screenShot.add(new Image(metaData.getScreenshot())); } } FlowPanel dataPanel = new FlowPanel(); dataPanel.addStyleName("gadget-data"); Label title = new Label(metaData.getTitle()); title.addStyleName("title"); dataPanel.add(title); dataPanel.add(new HTML(metaData.getDescription())); Anchor titleUrl = new Anchor(metaData.getTitleUrl(), metaData.getTitleUrl(), "_blank"); titleUrl.addStyleName("gadget-title-url"); dataPanel.add(titleUrl); FlowPanel gadgetExtInfo = new FlowPanel(); gadgetExtInfo.addStyleName("gadget-ext-info"); gadgetExtInfo.add(new HTML("Category: ")); Anchor category = new Anchor(); category.setText(metaData.getGadgetDefinition().getCategory().getName()); category.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent arg0) { EventBus.getInstance().notifyObservers( new SwitchToFilterOnPagedFilterPanelEvent("gadgets", metaData.getGadgetDefinition() .getCategory().getName(), "Recent")); } }); gadgetExtInfo.add(category); insertActionSeparator(gadgetExtInfo); gadgetExtInfo.add(new HTML(" Users: <span class='light'>" + metaData.getGadgetDefinition().getNumberOfUsers() + "</span>")); insertActionSeparator(gadgetExtInfo); gadgetExtInfo.add(new HTML(" Author: <a href='mailto:" + metaData.getAuthorEmail() + "'>" + metaData.getAuthor() + "</a>")); insertActionSeparator(gadgetExtInfo); gadgetExtInfo.add(new HTML(" Publish date: <span class='light'>" + DateTimeFormat.getLongDateFormat().format(metaData.getGadgetDefinition().getCreated()) + "</span>")); dataPanel.add(gadgetExtInfo); this.add(imageContainer); this.add(dataPanel); }
public GadgetMetaDataPanel(final GadgetMetaDataDTO metaData, final Long inTabId, final Deletable<Long> model, final String deleteMessage) { Session.getInstance().getEventBus().addObserver(UpdatedHistoryParametersEvent.class, new Observer<UpdatedHistoryParametersEvent>() { public void update(final UpdatedHistoryParametersEvent event) { if (event.getParameters().get("dropzone") != null) { dropZoneId = Integer.valueOf(event.getParameters().get("dropzone")); } else { dropZoneId = null; } } }, true); tabId = inTabId; final FlowPanel thisBuffered = this; if (Session.getInstance().getCurrentPersonRoles().contains(Role.ORG_COORDINATOR)) { EditPanel editControls = new EditPanel(this, Mode.EDIT_AND_DELETE); if (tabId != null) { final HashMap<String, String> params = new HashMap<String, String>(); params.put("action", "editApp"); params.put("url", metaData.getGadgetDefinition().getUrl()); params.put("category", metaData.getGadgetDefinition().getCategory().toString()); params.put("id", String.valueOf(metaData.getGadgetDefinition().getId())); params.put("tab", Session.getInstance().getParameterValue("tab")); final WidgetJSNIFacadeImpl jsni = new WidgetJSNIFacadeImpl(); editControls.addEditClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { jsni.setHistoryToken(Session.getInstance().generateUrl( new CreateUrlRequest(Page.GALLERY, params)), true); } }); } this.add(editControls); editControls.addDeleteClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { if (new WidgetJSNIFacadeImpl().confirm(deleteMessage)) { model.delete(metaData.getGadgetDefinition().getId()); Session.getInstance().getEventBus() .notifyObservers( new ShowNotificationEvent(new Notification(metaData.getTitle() + " has been deleted."))); thisBuffered.setVisible(false); } } }); } FlowPanel imageContainer = new FlowPanel(); imageContainer.addStyleName("image-container"); this.addStyleName("gadget-meta-data"); // Im a gadget. if (tabId != null) { if (metaData.getThumbnail() != null && !metaData.getThumbnail().equals("")) { imageContainer.add(new Image(metaData.getThumbnail())); } else { imageContainer.add(new Image("/style/images/gadget-gallery-default.png")); } applyGadget = new Hyperlink("Apply App", History.getToken()); applyGadget.addStyleName("apply-gadget"); applyGadget.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { GadgetModel.getInstance() .insert( new AddGadgetToStartPageRequest("{" + metaData.getGadgetDefinition().getUUID() + "}", tabId)); } }); Session.getInstance().getEventBus().addObserver(GadgetAddedToStartPageEvent.class, new Observer<GadgetAddedToStartPageEvent>() { public void update(final GadgetAddedToStartPageEvent arg1) { Session.getInstance().getEventBus().notifyObservers( new ShowNotificationEvent(new Notification("App has been added"))); if (arg1.getGadget().getGadgetDefinition().getId() == metaData.getGadgetDefinition() .getId()) { setActive(true); if (dropZoneId != null) { GadgetModel.getInstance().reorder( new ReorderGadgetRequest(tabId, new Long(arg1.getGadget().getId()), dropZoneId, 0)); } } } }); imageContainer.add(applyGadget); } // Im a plugin else { if (metaData.getScreenshot() != null && !metaData.getScreenshot().equals("")) { FlowPanel screenShot = new FlowPanel(); screenShot.addStyleName("stream-plugins-screenshot"); imageContainer.add(screenShot); screenShot.add(new Image(metaData.getScreenshot())); } } FlowPanel dataPanel = new FlowPanel(); dataPanel.addStyleName("gadget-data"); Label title = new Label(metaData.getTitle()); title.addStyleName("title"); dataPanel.add(title); dataPanel.add(new HTML(metaData.getDescription())); Anchor titleUrl = new Anchor(metaData.getTitleUrl(), metaData.getTitleUrl(), "_blank"); titleUrl.addStyleName("gadget-title-url"); dataPanel.add(titleUrl); FlowPanel gadgetExtInfo = new FlowPanel(); gadgetExtInfo.addStyleName("gadget-ext-info"); gadgetExtInfo.add(new HTML("Category: ")); Anchor category = new Anchor(); category.setText(metaData.getGadgetDefinition().getCategory().getName()); category.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent arg0) { EventBus.getInstance().notifyObservers( new SwitchToFilterOnPagedFilterPanelEvent("gadgets", metaData.getGadgetDefinition() .getCategory().getName(), "Recent")); } }); gadgetExtInfo.add(category); insertActionSeparator(gadgetExtInfo); gadgetExtInfo.add(new HTML(" Users: <span class='light'>" + metaData.getGadgetDefinition().getNumberOfUsers() + "</span>")); insertActionSeparator(gadgetExtInfo); gadgetExtInfo.add(new HTML(" Author: <a href='mailto:" + metaData.getAuthorEmail() + "'>" + metaData.getAuthor() + "</a>")); insertActionSeparator(gadgetExtInfo); gadgetExtInfo.add(new HTML(" Publish date: <span class='light'>" + DateTimeFormat.getLongDateFormat().format(metaData.getGadgetDefinition().getCreated()) + "</span>")); dataPanel.add(gadgetExtInfo); this.add(imageContainer); this.add(dataPanel); }
diff --git a/src/com/limelight/nvstream/av/video/MediaCodecDecoderRenderer.java b/src/com/limelight/nvstream/av/video/MediaCodecDecoderRenderer.java index c802683..18a0332 100644 --- a/src/com/limelight/nvstream/av/video/MediaCodecDecoderRenderer.java +++ b/src/com/limelight/nvstream/av/video/MediaCodecDecoderRenderer.java @@ -1,186 +1,186 @@ package com.limelight.nvstream.av.video; import java.nio.ByteBuffer; import java.util.LinkedList; import java.util.List; import com.limelight.nvstream.av.AvByteBufferDescriptor; import com.limelight.nvstream.av.AvDecodeUnit; import android.annotation.TargetApi; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaCodecList; import android.media.MediaFormat; import android.media.MediaCodec.BufferInfo; import android.os.Build; import android.view.Surface; @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public class MediaCodecDecoderRenderer implements DecoderRenderer { private ByteBuffer[] videoDecoderInputBuffers; private MediaCodec videoDecoder; private Thread rendererThread; public static final List<String> blacklistedDecoderPrefixes; static { blacklistedDecoderPrefixes = new LinkedList<String>(); blacklistedDecoderPrefixes.add("omx.google"); blacklistedDecoderPrefixes.add("omx.nvidia"); blacklistedDecoderPrefixes.add("omx.TI"); blacklistedDecoderPrefixes.add("omx.RK"); blacklistedDecoderPrefixes.add("AVCDecoder"); } public static MediaCodecInfo findSafeDecoder() { for (int i = 0; i < MediaCodecList.getCodecCount(); i++) { MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i); boolean badCodec = false; // Skip encoders if (codecInfo.isEncoder()) { continue; } for (String badPrefix : blacklistedDecoderPrefixes) { String name = codecInfo.getName(); - if (name.length() > badPrefix.length()) { + if (name.length() >= badPrefix.length()) { String prefix = name.substring(0, badPrefix.length()); if (prefix.equalsIgnoreCase(badPrefix)) { badCodec = true; break; } } } if (badCodec) { System.out.println("Blacklisted decoder: "+codecInfo.getName()); continue; } for (String mime : codecInfo.getSupportedTypes()) { if (mime.equalsIgnoreCase("video/avc")) { System.out.println("Selected decoder: "+codecInfo.getName()); return codecInfo; } } } return null; } @Override public void setup(int width, int height, Surface renderTarget) { videoDecoder = MediaCodec.createByCodecName(findSafeDecoder().getName()); MediaFormat videoFormat = MediaFormat.createVideoFormat("video/avc", width, height); videoDecoder.configure(videoFormat, renderTarget, null, 0); videoDecoder.setVideoScalingMode(MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT); videoDecoder.start(); videoDecoderInputBuffers = videoDecoder.getInputBuffers(); System.out.println("Using hardware decoding"); } private void startRendererThread() { rendererThread = new Thread() { @Override public void run() { long nextFrameTimeUs = 0; while (!isInterrupted()) { BufferInfo info = new BufferInfo(); int outIndex = videoDecoder.dequeueOutputBuffer(info, 100); switch (outIndex) { case MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED: System.out.println("Output buffers changed"); break; case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED: System.out.println("Output format changed"); System.out.println("New output Format: " + videoDecoder.getOutputFormat()); break; default: break; } if (outIndex >= 0) { boolean render = false; if (currentTimeUs() >= nextFrameTimeUs) { render = true; nextFrameTimeUs = computePresentationTime(60); } videoDecoder.releaseOutputBuffer(outIndex, render); } } } }; rendererThread.setName("Video - Renderer (MediaCodec)"); rendererThread.start(); } private static long currentTimeUs() { return System.nanoTime() / 1000; } private long computePresentationTime(int frameRate) { return currentTimeUs() + (1000000 / frameRate); } @Override public void start() { startRendererThread(); } @Override public void stop() { rendererThread.interrupt(); try { rendererThread.join(); } catch (InterruptedException e) { } } @Override public void release() { if (videoDecoder != null) { videoDecoder.release(); } } @Override public boolean submitDecodeUnit(AvDecodeUnit decodeUnit) { if (decodeUnit.getType() != AvDecodeUnit.TYPE_H264) { System.err.println("Unknown decode unit type"); return false; } int inputIndex = videoDecoder.dequeueInputBuffer(-1); if (inputIndex >= 0) { ByteBuffer buf = videoDecoderInputBuffers[inputIndex]; // Clear old input data buf.clear(); // Copy data from our buffer list into the input buffer for (AvByteBufferDescriptor desc : decodeUnit.getBufferList()) { buf.put(desc.data, desc.offset, desc.length); } videoDecoder.queueInputBuffer(inputIndex, 0, decodeUnit.getDataLength(), 0, decodeUnit.getFlags()); } return true; } }
true
true
public static MediaCodecInfo findSafeDecoder() { for (int i = 0; i < MediaCodecList.getCodecCount(); i++) { MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i); boolean badCodec = false; // Skip encoders if (codecInfo.isEncoder()) { continue; } for (String badPrefix : blacklistedDecoderPrefixes) { String name = codecInfo.getName(); if (name.length() > badPrefix.length()) { String prefix = name.substring(0, badPrefix.length()); if (prefix.equalsIgnoreCase(badPrefix)) { badCodec = true; break; } } } if (badCodec) { System.out.println("Blacklisted decoder: "+codecInfo.getName()); continue; } for (String mime : codecInfo.getSupportedTypes()) { if (mime.equalsIgnoreCase("video/avc")) { System.out.println("Selected decoder: "+codecInfo.getName()); return codecInfo; } } } return null; }
public static MediaCodecInfo findSafeDecoder() { for (int i = 0; i < MediaCodecList.getCodecCount(); i++) { MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i); boolean badCodec = false; // Skip encoders if (codecInfo.isEncoder()) { continue; } for (String badPrefix : blacklistedDecoderPrefixes) { String name = codecInfo.getName(); if (name.length() >= badPrefix.length()) { String prefix = name.substring(0, badPrefix.length()); if (prefix.equalsIgnoreCase(badPrefix)) { badCodec = true; break; } } } if (badCodec) { System.out.println("Blacklisted decoder: "+codecInfo.getName()); continue; } for (String mime : codecInfo.getSupportedTypes()) { if (mime.equalsIgnoreCase("video/avc")) { System.out.println("Selected decoder: "+codecInfo.getName()); return codecInfo; } } } return null; }
diff --git a/vcat-core/src/main/java/vcat/graphviz/GraphvizExternal.java b/vcat-core/src/main/java/vcat/graphviz/GraphvizExternal.java index 7bf8158..2214f85 100644 --- a/vcat-core/src/main/java/vcat/graphviz/GraphvizExternal.java +++ b/vcat-core/src/main/java/vcat/graphviz/GraphvizExternal.java @@ -1,103 +1,108 @@ package vcat.graphviz; import java.io.File; import java.io.IOException; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import vcat.params.GraphvizParams; /** * Graphviz renderer which uses the Graphviz command line tools (dot, fdp etc.). * * @author Peter Schlömer */ public class GraphvizExternal implements Graphviz { private final Log log = LogFactory.getLog(this.getClass()); private final File programPath; public GraphvizExternal(File programPath) { if (!programPath.exists() || !programPath.isDirectory() || !programPath.canRead()) { throw new InvalidParameterException("Program path '" + programPath.getAbsolutePath() + "' must exist, be a directory and be readable."); } this.programPath = programPath; if (!this.programPath.exists() || !this.programPath.isDirectory() || !this.programPath.canRead()) { throw new InvalidParameterException("Program path '" + this.programPath.getAbsolutePath() + "' must exist, be a directory and be readable."); } } public List<String> buildCommandParts(final String command, GraphvizParams params, File inputFile, File outputFile) { ArrayList<String> commandParts = new ArrayList<String>(4); commandParts.add(command); commandParts.add("-T" + params.getOutputFormat().getGraphvizTypeParameter()); commandParts.add("-o" + outputFile.getAbsolutePath()); commandParts.add(inputFile.getAbsolutePath()); return commandParts; } @Override public void render(File inputFile, File outputFile, GraphvizParams params) throws GraphvizException { final Runtime runtime = Runtime.getRuntime(); final long startMillis = System.currentTimeMillis(); final File programFile = new File(programPath, params.getAlgorithm().getProgram()); if (!programFile.exists() || !programFile.canExecute()) { throw new InvalidParameterException("Program file '" + programFile.getAbsolutePath() + "' must exist and be executable. Is Graphviz installed?"); } final String command = programFile.getAbsolutePath(); - final String[] commandArray = (String[]) buildCommandParts(command, params, inputFile, outputFile).toArray(); + final List<String> commandList = buildCommandParts(command, params, inputFile, outputFile); + final int len = commandList.size(); + final String[] commandArray = new String[len]; + for (int i = 0; i < len; i++) { + commandArray[i] = commandList.get(i); + } Process graphvizProcess; try { graphvizProcess = runtime.exec(commandArray); } catch (IOException e) { throw new GraphvizException("Error running graphviz executable '" + command + "'", e); } try { // Close stdin graphvizProcess.getOutputStream().close(); } catch (IOException e) { throw new GraphvizException("Error running graphviz: cannot close program stdin", e); } boolean running = true; int exitValue = 0; do { try { exitValue = graphvizProcess.exitValue(); running = false; } catch (IllegalThreadStateException e) { // still running try { Thread.sleep(10); } catch (InterruptedException ee) { // ignore } } } while (running); long endMillis = System.currentTimeMillis(); if (exitValue == 0) { log.info("Graphviz run on input file '" + inputFile.getAbsolutePath() + "'. Total run time: " + (endMillis - startMillis) + " ms."); } else { log.error("Graphviz run on input file '" + inputFile.getAbsolutePath() + "' failed with exit code " + exitValue + "."); outputFile.delete(); throw new GraphvizException("Error running graphviz: returned exit code " + exitValue); } } }
true
true
public void render(File inputFile, File outputFile, GraphvizParams params) throws GraphvizException { final Runtime runtime = Runtime.getRuntime(); final long startMillis = System.currentTimeMillis(); final File programFile = new File(programPath, params.getAlgorithm().getProgram()); if (!programFile.exists() || !programFile.canExecute()) { throw new InvalidParameterException("Program file '" + programFile.getAbsolutePath() + "' must exist and be executable. Is Graphviz installed?"); } final String command = programFile.getAbsolutePath(); final String[] commandArray = (String[]) buildCommandParts(command, params, inputFile, outputFile).toArray(); Process graphvizProcess; try { graphvizProcess = runtime.exec(commandArray); } catch (IOException e) { throw new GraphvizException("Error running graphviz executable '" + command + "'", e); } try { // Close stdin graphvizProcess.getOutputStream().close(); } catch (IOException e) { throw new GraphvizException("Error running graphviz: cannot close program stdin", e); } boolean running = true; int exitValue = 0; do { try { exitValue = graphvizProcess.exitValue(); running = false; } catch (IllegalThreadStateException e) { // still running try { Thread.sleep(10); } catch (InterruptedException ee) { // ignore } } } while (running); long endMillis = System.currentTimeMillis(); if (exitValue == 0) { log.info("Graphviz run on input file '" + inputFile.getAbsolutePath() + "'. Total run time: " + (endMillis - startMillis) + " ms."); } else { log.error("Graphviz run on input file '" + inputFile.getAbsolutePath() + "' failed with exit code " + exitValue + "."); outputFile.delete(); throw new GraphvizException("Error running graphviz: returned exit code " + exitValue); } }
public void render(File inputFile, File outputFile, GraphvizParams params) throws GraphvizException { final Runtime runtime = Runtime.getRuntime(); final long startMillis = System.currentTimeMillis(); final File programFile = new File(programPath, params.getAlgorithm().getProgram()); if (!programFile.exists() || !programFile.canExecute()) { throw new InvalidParameterException("Program file '" + programFile.getAbsolutePath() + "' must exist and be executable. Is Graphviz installed?"); } final String command = programFile.getAbsolutePath(); final List<String> commandList = buildCommandParts(command, params, inputFile, outputFile); final int len = commandList.size(); final String[] commandArray = new String[len]; for (int i = 0; i < len; i++) { commandArray[i] = commandList.get(i); } Process graphvizProcess; try { graphvizProcess = runtime.exec(commandArray); } catch (IOException e) { throw new GraphvizException("Error running graphviz executable '" + command + "'", e); } try { // Close stdin graphvizProcess.getOutputStream().close(); } catch (IOException e) { throw new GraphvizException("Error running graphviz: cannot close program stdin", e); } boolean running = true; int exitValue = 0; do { try { exitValue = graphvizProcess.exitValue(); running = false; } catch (IllegalThreadStateException e) { // still running try { Thread.sleep(10); } catch (InterruptedException ee) { // ignore } } } while (running); long endMillis = System.currentTimeMillis(); if (exitValue == 0) { log.info("Graphviz run on input file '" + inputFile.getAbsolutePath() + "'. Total run time: " + (endMillis - startMillis) + " ms."); } else { log.error("Graphviz run on input file '" + inputFile.getAbsolutePath() + "' failed with exit code " + exitValue + "."); outputFile.delete(); throw new GraphvizException("Error running graphviz: returned exit code " + exitValue); } }
diff --git a/src/main/java/to/networld/soap/security/security/SOAPSecMessageFactory.java b/src/main/java/to/networld/soap/security/security/SOAPSecMessageFactory.java index 433c3ce..d299938 100644 --- a/src/main/java/to/networld/soap/security/security/SOAPSecMessageFactory.java +++ b/src/main/java/to/networld/soap/security/security/SOAPSecMessageFactory.java @@ -1,101 +1,101 @@ /** * SOAP Security Framework * * Copyright (C) 2010 by Networld Project * Written by Alex Oberhauser <[email protected]> * All Rights Reserved * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software. If not, see <http://www.gnu.org/licenses/> */ package to.networld.soap.security.security; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.Calendar; import java.util.UUID; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPHeader; import javax.xml.soap.SOAPMessage; import javax.xml.soap.SOAPPart; import org.apache.ws.security.components.crypto.CredentialException; import to.networld.soap.security.common.DateHandler; import to.networld.soap.security.interfaces.ISecSOAPMessage; /** * @author Alex Oberhauser */ public abstract class SOAPSecMessageFactory { /** * Creates a SOAP message with basic security constraints. * * @param _expiresInMinutes The expire time in minutes from the current data. If 0 or negative than ignored. * @return The generated SOAP message. * @throws SOAPException * @throws InvalidAlgorithmParameterException * @throws NoSuchAlgorithmException * @throws IOException * @throws CredentialException * @throws CertificateException * @throws KeyStoreException */ public static ISecSOAPMessage newInstance(int _expiresInMinutes) throws SOAPException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, CredentialException, IOException, CertificateException, KeyStoreException { - SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); + SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPBody soapBody = soapMessage.getSOAPBody(); SOAPHeader soapHeader = soapMessage.getSOAPHeader(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); soapEnvelope.addNamespaceDeclaration("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); soapEnvelope.addNamespaceDeclaration("SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"); soapMessage.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true"); /* * Header Part */ soapHeader.addNamespaceDeclaration("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); SOAPElement secElement = soapHeader.addChildElement(soapHeader.createQName("Security", "wsse")); secElement.addAttribute(soapEnvelope.createQName("mustUnderstand", soapEnvelope.getPrefix()), "1"); SOAPElement timestampElement = secElement.addChildElement(soapEnvelope.createQName("Timestamp", "wsu")); timestampElement.addAttribute(soapEnvelope.createQName("Id", "wsu"), UUID.randomUUID().toString()); - Calendar currentDate = Calendar.getInstance(); - timestampElement.addChildElement(soapEnvelope.createQName("Created", "wsu")).addTextNode(DateHandler.getDateString(currentDate, 0)); - if ( _expiresInMinutes > 0 ) - timestampElement.addChildElement(soapEnvelope.createQName("Expires", "wsu")).addTextNode(DateHandler.getDateString(currentDate, _expiresInMinutes)); - timestampElement.addAttribute(soapEnvelope.createQName("id", "SOAP-SEC"), "Timestamp"); + Calendar currentDate = Calendar.getInstance(); + timestampElement.addChildElement(soapEnvelope.createQName("Created", "wsu")).addTextNode(DateHandler.getDateString(currentDate, 0)); + if ( _expiresInMinutes > 0 ) + timestampElement.addChildElement(soapEnvelope.createQName("Expires", "wsu")).addTextNode(DateHandler.getDateString(currentDate, _expiresInMinutes)); + timestampElement.addAttribute(soapEnvelope.createQName("id", "SOAP-SEC"), "Timestamp"); /* * Body Part */ soapBody.addAttribute(soapEnvelope.createQName("Id", "wsu"), UUID.randomUUID().toString()); soapBody.addAttribute(soapEnvelope.createQName("id", "SOAP-SEC"), "Body"); soapMessage.saveChanges(); return new SecSOAPMessage(soapMessage); } }
false
true
public static ISecSOAPMessage newInstance(int _expiresInMinutes) throws SOAPException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, CredentialException, IOException, CertificateException, KeyStoreException { SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPBody soapBody = soapMessage.getSOAPBody(); SOAPHeader soapHeader = soapMessage.getSOAPHeader(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); soapEnvelope.addNamespaceDeclaration("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); soapEnvelope.addNamespaceDeclaration("SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"); soapMessage.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true"); /* * Header Part */ soapHeader.addNamespaceDeclaration("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); SOAPElement secElement = soapHeader.addChildElement(soapHeader.createQName("Security", "wsse")); secElement.addAttribute(soapEnvelope.createQName("mustUnderstand", soapEnvelope.getPrefix()), "1"); SOAPElement timestampElement = secElement.addChildElement(soapEnvelope.createQName("Timestamp", "wsu")); timestampElement.addAttribute(soapEnvelope.createQName("Id", "wsu"), UUID.randomUUID().toString()); Calendar currentDate = Calendar.getInstance(); timestampElement.addChildElement(soapEnvelope.createQName("Created", "wsu")).addTextNode(DateHandler.getDateString(currentDate, 0)); if ( _expiresInMinutes > 0 ) timestampElement.addChildElement(soapEnvelope.createQName("Expires", "wsu")).addTextNode(DateHandler.getDateString(currentDate, _expiresInMinutes)); timestampElement.addAttribute(soapEnvelope.createQName("id", "SOAP-SEC"), "Timestamp"); /* * Body Part */ soapBody.addAttribute(soapEnvelope.createQName("Id", "wsu"), UUID.randomUUID().toString()); soapBody.addAttribute(soapEnvelope.createQName("id", "SOAP-SEC"), "Body"); soapMessage.saveChanges(); return new SecSOAPMessage(soapMessage); }
public static ISecSOAPMessage newInstance(int _expiresInMinutes) throws SOAPException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, CredentialException, IOException, CertificateException, KeyStoreException { SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPBody soapBody = soapMessage.getSOAPBody(); SOAPHeader soapHeader = soapMessage.getSOAPHeader(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); soapEnvelope.addNamespaceDeclaration("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); soapEnvelope.addNamespaceDeclaration("SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"); soapMessage.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true"); /* * Header Part */ soapHeader.addNamespaceDeclaration("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); SOAPElement secElement = soapHeader.addChildElement(soapHeader.createQName("Security", "wsse")); secElement.addAttribute(soapEnvelope.createQName("mustUnderstand", soapEnvelope.getPrefix()), "1"); SOAPElement timestampElement = secElement.addChildElement(soapEnvelope.createQName("Timestamp", "wsu")); timestampElement.addAttribute(soapEnvelope.createQName("Id", "wsu"), UUID.randomUUID().toString()); Calendar currentDate = Calendar.getInstance(); timestampElement.addChildElement(soapEnvelope.createQName("Created", "wsu")).addTextNode(DateHandler.getDateString(currentDate, 0)); if ( _expiresInMinutes > 0 ) timestampElement.addChildElement(soapEnvelope.createQName("Expires", "wsu")).addTextNode(DateHandler.getDateString(currentDate, _expiresInMinutes)); timestampElement.addAttribute(soapEnvelope.createQName("id", "SOAP-SEC"), "Timestamp"); /* * Body Part */ soapBody.addAttribute(soapEnvelope.createQName("Id", "wsu"), UUID.randomUUID().toString()); soapBody.addAttribute(soapEnvelope.createQName("id", "SOAP-SEC"), "Body"); soapMessage.saveChanges(); return new SecSOAPMessage(soapMessage); }
diff --git a/src/NDFAtoDFATransformer.java b/src/NDFAtoDFATransformer.java index 449edee..7c3c548 100644 --- a/src/NDFAtoDFATransformer.java +++ b/src/NDFAtoDFATransformer.java @@ -1,153 +1,153 @@ import java.io.IOException; import java.util.Hashtable; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Stack; public class NDFAtoDFATransformer { public Hashtable<String, Action> ndfa; public Hashtable<String, Action> dfa; public static State moveDFA(State state, String input){ for (Action a : state.actions) if(a.symbol.equals("input")) return a.toState; return null; } public static Hashtable<String,State> moveNFA(DFAState state, String input){ //HashSet<State> states = state.states; Hashtable <String,State> states = state.states; Hashtable <String,State> result = new Hashtable<String,State>(); Iterator <State> it = states.values().iterator(); while(it.hasNext()){ State s = it.next(); for (Action a : s.actions){ if (a.symbol.equals(input)) result.put(a.toState.id, a.toState); } } return result; } public static Hashtable<String, State> epsilonClosure(Hashtable<String, State> states){ Stack<State> remainingStates = new Stack<State>(); Hashtable <String, State> result = new Hashtable <String, State>(); Iterator <State> it = states.values().iterator(); while (it.hasNext()){ State s = it.next(); remainingStates.add(s); } while (!remainingStates.isEmpty()){ State s = remainingStates.pop(); ArrayList<Action> actions = s.actions; for (Action action : actions){ if (action.symbol.equals("epsilon")){ State actionState = action.toState; if (!result.contains(actionState)){ result.put(actionState.id, actionState); remainingStates.push(actionState); } } } } return result; } public static HashSet<State> _epsilonClosure(HashSet <State> states){ Stack<State> remainingStates = new Stack<State>(); HashSet<State> result = new HashSet<State>(); // Push all states to the stack for (State s : states){ remainingStates.add(s); } while (!remainingStates.isEmpty()){ State s = remainingStates.pop(); ArrayList<Action> actions = s.actions; for (Action action : actions){ if (action.symbol.equals("epsilon")){ State actionState = action.toState; if (!result.contains(actionState)){ result.add(actionState); remainingStates.push(actionState); } } } } return result; } public static Hashtable<String,State> acceptingStates(Hashtable<String, State> states){ Hashtable<String,State> acceptingStates = new Hashtable<String,State>(); Iterator<State> it = states.values().iterator(); while(it.hasNext()){ State s = it.next(); if(s.type == State.StateType.ACCEPTING ||s.type == State.StateType.STARTACCEPTING ){ acceptingStates.put(s.id, s); } } return acceptingStates; } public static Hashtable<String,State> startingStates(Hashtable <String,State> states){ Hashtable<String,State> startingStates = new Hashtable<String,State>(); Iterator<State> it = states.values().iterator(); while(it.hasNext()){ State s = it.next(); if(s.type == State.StateType.START ||s.type == State.StateType.STARTACCEPTING ){ startingStates.put(s.id, s); } } return startingStates; } public static DFAState nextUnmarkedState(Hashtable<String,DFAState> states){ Iterator<DFAState> it = states.values().iterator(); while(it.hasNext()){ DFAState s = it.next(); if (!s.marked) return s; } return null; } // Change this to use dictionaries instead of sets - public static Hashtable<String,State> toDFA(String inputFile) throws IOException{ + public static Hashtable<String,DFAState> toDFA(String inputFile) throws IOException{ Hashtable<String, State> nfaStates = FAReader.parseAutomata(inputFile); Hashtable<String,DFAState> dfaStates = new Hashtable<String,DFAState>(); Hashtable <String, State> startingStates = acceptingStates(nfaStates); DFAState startingState = new DFAState(); startingState.states = epsilonClosure(startingStates); dfaStates.put(startingState.name(), startingState); DFAState nextUnmarkedState = nextUnmarkedState(dfaStates); while (nextUnmarkedState != null){ nextUnmarkedState.marked = true; ArrayList <Action> actions = nextUnmarkedState.actions(); for (Action a : actions){ Hashtable <String,State> epsStates = epsilonClosure(moveNFA(nextUnmarkedState, a.symbol)); DFAState S = new DFAState(); S.states = epsStates; if (!dfaStates.contains(S)){ //Add S to SDFA (as an �unmarked� state) S.marked = false; dfaStates.put(S.name(), S); } Action action = new Action(a.symbol, S); nextUnmarkedState.actions.add(action); } //Set MoveDFA(T,a) to S T=nextUnmarkedState nextUnmarkedState = nextUnmarkedState(dfaStates); } - dfaStates; + return dfaStates; } }
false
true
public static Hashtable<String,State> toDFA(String inputFile) throws IOException{ Hashtable<String, State> nfaStates = FAReader.parseAutomata(inputFile); Hashtable<String,DFAState> dfaStates = new Hashtable<String,DFAState>(); Hashtable <String, State> startingStates = acceptingStates(nfaStates); DFAState startingState = new DFAState(); startingState.states = epsilonClosure(startingStates); dfaStates.put(startingState.name(), startingState); DFAState nextUnmarkedState = nextUnmarkedState(dfaStates); while (nextUnmarkedState != null){ nextUnmarkedState.marked = true; ArrayList <Action> actions = nextUnmarkedState.actions(); for (Action a : actions){ Hashtable <String,State> epsStates = epsilonClosure(moveNFA(nextUnmarkedState, a.symbol)); DFAState S = new DFAState(); S.states = epsStates; if (!dfaStates.contains(S)){ //Add S to SDFA (as an �unmarked� state) S.marked = false; dfaStates.put(S.name(), S); } Action action = new Action(a.symbol, S); nextUnmarkedState.actions.add(action); } //Set MoveDFA(T,a) to S T=nextUnmarkedState nextUnmarkedState = nextUnmarkedState(dfaStates); } dfaStates; }
public static Hashtable<String,DFAState> toDFA(String inputFile) throws IOException{ Hashtable<String, State> nfaStates = FAReader.parseAutomata(inputFile); Hashtable<String,DFAState> dfaStates = new Hashtable<String,DFAState>(); Hashtable <String, State> startingStates = acceptingStates(nfaStates); DFAState startingState = new DFAState(); startingState.states = epsilonClosure(startingStates); dfaStates.put(startingState.name(), startingState); DFAState nextUnmarkedState = nextUnmarkedState(dfaStates); while (nextUnmarkedState != null){ nextUnmarkedState.marked = true; ArrayList <Action> actions = nextUnmarkedState.actions(); for (Action a : actions){ Hashtable <String,State> epsStates = epsilonClosure(moveNFA(nextUnmarkedState, a.symbol)); DFAState S = new DFAState(); S.states = epsStates; if (!dfaStates.contains(S)){ //Add S to SDFA (as an �unmarked� state) S.marked = false; dfaStates.put(S.name(), S); } Action action = new Action(a.symbol, S); nextUnmarkedState.actions.add(action); } //Set MoveDFA(T,a) to S T=nextUnmarkedState nextUnmarkedState = nextUnmarkedState(dfaStates); } return dfaStates; }
diff --git a/SleepClock/src/com/pps/sleepcalc/MainActivity.java b/SleepClock/src/com/pps/sleepcalc/MainActivity.java index 3d8064a..0fde97b 100644 --- a/SleepClock/src/com/pps/sleepcalc/MainActivity.java +++ b/SleepClock/src/com/pps/sleepcalc/MainActivity.java @@ -1,209 +1,209 @@ package com.pps.sleepcalc; import java.util.Calendar; import com.pps.sleepcalc.R; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.SeekBar; import android.widget.Switch; import android.widget.TabHost; import android.widget.TabHost.TabSpec; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; public class MainActivity extends Activity implements TimePicker.OnTimeChangedListener, SeekBar.OnSeekBarChangeListener{ private Intent sensorService; private int wakeupHours; private int wakeupMinutes; private static final String SHARED_PREF_NAME = "SleepClock Prefs"; private EditText triggerDelay; private EditText gyroSensorTrigger; private EditText kalmanRnoise; private EditText kalmanQnoise; private SeekBar wakeupDeltaBar; private TextView wakeupDelta; private Switch sensorPrecisionSwitch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); //setContentView(R.layout.activity_main); //set up view setContentView(R.layout.test); //add gui elements final TimePicker timepick = (TimePicker) findViewById(R.id.timePicker); timepick.setOnTimeChangedListener(this); wakeupDelta = (TextView) findViewById(R.id.wakeupDelta); wakeupDeltaBar = (SeekBar) findViewById(R.id.wakupDeltaBar); triggerDelay = (EditText) findViewById(R.id.triggerDelay); gyroSensorTrigger = (EditText) findViewById(R.id.gyroSensorTrigger); kalmanRnoise = (EditText) findViewById(R.id.kalmanRnoise); kalmanQnoise = (EditText) findViewById(R.id.kalmanQnoise); sensorPrecisionSwitch = (Switch) findViewById(R.id.sensorPrecisionSwitch); //load default values for each UI element in settings SharedPreferences settings = getSharedPreferences(SHARED_PREF_NAME,0); triggerDelay.setText(settings.getString("triggerDelay", "1000")); gyroSensorTrigger.setText(settings.getString("gyroSensorTrigger", "0.005")); - kalmanRnoise.setText(settings.getString("kalmanRnoise", "0.0125")); - kalmanQnoise.setText(settings.getString("kalmanQnoise", "80.0")); + kalmanRnoise.setText(settings.getString("kalmanRnoise", "80.0")); + kalmanQnoise.setText(settings.getString("kalmanQnoise", "0.0125")); sensorPrecisionSwitch.setChecked(settings.getBoolean("sensorPrecisionSwitch", false)); //save settings button Button saveSettings = (Button) findViewById(R.id.saveSettings); saveSettings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Log.e("SleepCalcTag", Long.toString(wakeupDeltaBar.getProgress())); //save all settings to SHARED_PREF_NAME SharedPreferences settings = getSharedPreferences(SHARED_PREF_NAME,0); SharedPreferences.Editor editor = settings.edit(); editor.putString("triggerDelay", triggerDelay.getText().toString()); editor.putString("gyroSensorTrigger", gyroSensorTrigger.getText().toString()); editor.putString("kalmanRnoise", kalmanRnoise.getText().toString()); editor.putString("kalmanQnoise", kalmanQnoise.getText().toString()); editor.putBoolean("sensorPrecisionSwitch", sensorPrecisionSwitch.isChecked()); editor.commit(); } }); //add tabbing TabHost tabHost = (TabHost) findViewById(R.id.TabHost); tabHost.setup(); TabSpec specMain = tabHost.newTabSpec("Main"); specMain.setContent(R.id.tabMain); specMain.setIndicator("Start"); TabSpec specSettings = tabHost.newTabSpec("Settings"); specSettings.setContent(R.id.tabSettings); specSettings.setIndicator("Settings"); tabHost.addTab(specMain); tabHost.addTab(specSettings); } @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; } public void startClicked(View view){ //create and start service sensorService = new Intent(this, sensorService.class); sensorService.putExtra("wakeupHours", wakeupHours); sensorService.putExtra("wakeupMinutes", wakeupMinutes); //extras from settings sensorService.putExtra("triggerDelay", Integer.valueOf(triggerDelay.getText().toString())); sensorService.putExtra("gyroSensorTrigger", Float.valueOf(gyroSensorTrigger.getText().toString())); sensorService.putExtra("kalmanRnoise", Float.valueOf(kalmanRnoise.getText().toString())); sensorService.putExtra("kalmanQnoise", Float.valueOf(kalmanQnoise.getText().toString())); sensorService.putExtra("sensorPrecisionSwitch", Boolean.valueOf(sensorPrecisionSwitch.isChecked())); startService(sensorService); //Toast and log output for user/developper notification Toast.makeText(this, "Service started", Toast.LENGTH_SHORT).show(); Log.e("SleepCalcTag", "start clicked"); } public void stopClicked(View view){ //stop service stopService(sensorService); //Toast and log output for user/developper notification Toast.makeText(this, "Service stopped", Toast.LENGTH_SHORT).show(); Log.e("SleepCalcTag", "stop clicked"); } public void resetClicked(View view){ //reset fields triggerDelay.setText("1000"); gyroSensorTrigger.setText("0.03"); sensorPrecisionSwitch.setChecked(false); //update config SharedPreferences settings = getSharedPreferences(SHARED_PREF_NAME,0); SharedPreferences.Editor editor = settings.edit(); editor.putString("triggerDelay", triggerDelay.getText().toString()); editor.putString("gyroSensorTrigger", gyroSensorTrigger.getText().toString()); editor.putString("kalmanRnoise", kalmanRnoise.getText().toString()); editor.putString("kalmanQnoise", kalmanQnoise.getText().toString()); editor.putBoolean("sensorPrecisionSwitch", sensorPrecisionSwitch.isChecked()); editor.commit(); Log.e("SleepCalcTag", "reset clicked"); } @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { Log.e("SleepCalcTag", "Hour: "+hourOfDay+" minute: "+minute); wakeupHours=hourOfDay; wakeupMinutes=minute; // TODO Auto-generated method stub } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // TODO Auto-generated method stub } @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); //setContentView(R.layout.activity_main); //set up view setContentView(R.layout.test); //add gui elements final TimePicker timepick = (TimePicker) findViewById(R.id.timePicker); timepick.setOnTimeChangedListener(this); wakeupDelta = (TextView) findViewById(R.id.wakeupDelta); wakeupDeltaBar = (SeekBar) findViewById(R.id.wakupDeltaBar); triggerDelay = (EditText) findViewById(R.id.triggerDelay); gyroSensorTrigger = (EditText) findViewById(R.id.gyroSensorTrigger); kalmanRnoise = (EditText) findViewById(R.id.kalmanRnoise); kalmanQnoise = (EditText) findViewById(R.id.kalmanQnoise); sensorPrecisionSwitch = (Switch) findViewById(R.id.sensorPrecisionSwitch); //load default values for each UI element in settings SharedPreferences settings = getSharedPreferences(SHARED_PREF_NAME,0); triggerDelay.setText(settings.getString("triggerDelay", "1000")); gyroSensorTrigger.setText(settings.getString("gyroSensorTrigger", "0.005")); kalmanRnoise.setText(settings.getString("kalmanRnoise", "0.0125")); kalmanQnoise.setText(settings.getString("kalmanQnoise", "80.0")); sensorPrecisionSwitch.setChecked(settings.getBoolean("sensorPrecisionSwitch", false)); //save settings button Button saveSettings = (Button) findViewById(R.id.saveSettings); saveSettings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Log.e("SleepCalcTag", Long.toString(wakeupDeltaBar.getProgress())); //save all settings to SHARED_PREF_NAME SharedPreferences settings = getSharedPreferences(SHARED_PREF_NAME,0); SharedPreferences.Editor editor = settings.edit(); editor.putString("triggerDelay", triggerDelay.getText().toString()); editor.putString("gyroSensorTrigger", gyroSensorTrigger.getText().toString()); editor.putString("kalmanRnoise", kalmanRnoise.getText().toString()); editor.putString("kalmanQnoise", kalmanQnoise.getText().toString()); editor.putBoolean("sensorPrecisionSwitch", sensorPrecisionSwitch.isChecked()); editor.commit(); } }); //add tabbing TabHost tabHost = (TabHost) findViewById(R.id.TabHost); tabHost.setup(); TabSpec specMain = tabHost.newTabSpec("Main"); specMain.setContent(R.id.tabMain); specMain.setIndicator("Start"); TabSpec specSettings = tabHost.newTabSpec("Settings"); specSettings.setContent(R.id.tabSettings); specSettings.setIndicator("Settings"); tabHost.addTab(specMain); tabHost.addTab(specSettings); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); //setContentView(R.layout.activity_main); //set up view setContentView(R.layout.test); //add gui elements final TimePicker timepick = (TimePicker) findViewById(R.id.timePicker); timepick.setOnTimeChangedListener(this); wakeupDelta = (TextView) findViewById(R.id.wakeupDelta); wakeupDeltaBar = (SeekBar) findViewById(R.id.wakupDeltaBar); triggerDelay = (EditText) findViewById(R.id.triggerDelay); gyroSensorTrigger = (EditText) findViewById(R.id.gyroSensorTrigger); kalmanRnoise = (EditText) findViewById(R.id.kalmanRnoise); kalmanQnoise = (EditText) findViewById(R.id.kalmanQnoise); sensorPrecisionSwitch = (Switch) findViewById(R.id.sensorPrecisionSwitch); //load default values for each UI element in settings SharedPreferences settings = getSharedPreferences(SHARED_PREF_NAME,0); triggerDelay.setText(settings.getString("triggerDelay", "1000")); gyroSensorTrigger.setText(settings.getString("gyroSensorTrigger", "0.005")); kalmanRnoise.setText(settings.getString("kalmanRnoise", "80.0")); kalmanQnoise.setText(settings.getString("kalmanQnoise", "0.0125")); sensorPrecisionSwitch.setChecked(settings.getBoolean("sensorPrecisionSwitch", false)); //save settings button Button saveSettings = (Button) findViewById(R.id.saveSettings); saveSettings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Log.e("SleepCalcTag", Long.toString(wakeupDeltaBar.getProgress())); //save all settings to SHARED_PREF_NAME SharedPreferences settings = getSharedPreferences(SHARED_PREF_NAME,0); SharedPreferences.Editor editor = settings.edit(); editor.putString("triggerDelay", triggerDelay.getText().toString()); editor.putString("gyroSensorTrigger", gyroSensorTrigger.getText().toString()); editor.putString("kalmanRnoise", kalmanRnoise.getText().toString()); editor.putString("kalmanQnoise", kalmanQnoise.getText().toString()); editor.putBoolean("sensorPrecisionSwitch", sensorPrecisionSwitch.isChecked()); editor.commit(); } }); //add tabbing TabHost tabHost = (TabHost) findViewById(R.id.TabHost); tabHost.setup(); TabSpec specMain = tabHost.newTabSpec("Main"); specMain.setContent(R.id.tabMain); specMain.setIndicator("Start"); TabSpec specSettings = tabHost.newTabSpec("Settings"); specSettings.setContent(R.id.tabSettings); specSettings.setIndicator("Settings"); tabHost.addTab(specMain); tabHost.addTab(specSettings); }
diff --git a/net/marcuswatkins/pisaver/PiSaver.java b/net/marcuswatkins/pisaver/PiSaver.java index 6db64f1..8414012 100644 --- a/net/marcuswatkins/pisaver/PiSaver.java +++ b/net/marcuswatkins/pisaver/PiSaver.java @@ -1,282 +1,282 @@ package net.marcuswatkins.pisaver; //Original copyright header from jogl demo: /** * Copyright 2012 JogAmp Community. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ /** * <pre> * __ __|_ ___________________________________________________________________________ ___|__ __ * // /\ _ /\ \\ * //____/ \__ __ _____ _____ _____ _____ _____ | | __ _____ _____ __ __/ \____\\ * \ \ / / __| | | __| _ | | _ | | | __| | | __| | /\ \ / / * \____\/_/ | | | | | | | | | | | __| | | | | | | | | | |__ &quot; \_\/____/ * /\ \ |_____|_____|_____|__|__|_|_|_|__| | | |_____|_____|_____|_____| _ / /\ * / \____\ http://jogamp.org |_| /____/ \ * \ / &quot;' _________________________________________________________________________ `&quot; \ / * \/____. .____\/ * </pre> * * <p> * JOGL2 OpenGL ES 2 demo to expose and learn what the RAW OpenGL ES 2 API looks * like. * * Compile, run and enjoy: wget * http://jogamp.org/deployment/jogamp-current/archive/jogamp-all-platforms.7z * 7z x jogamp-all-platforms.7z cd jogamp-all-platforms wget * https://raw.github.com * /xranby/jogl-demos/master/src/demos/es2/RawGL2ES2demo.java javac -cp * jar/jogl-all.jar:jar/gluegen-rt.jar RawGL2ES2demo.java java -cp * jar/jogl-all.jar:jar/gluegen-rt.jar:. RawGL2ES2demo * </p> * * * @author Xerxes Rånby (xranby) */ import java.awt.Dimension; import java.awt.Toolkit; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; import javax.media.opengl.GL; import javax.media.opengl.GL2ES2; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; import net.marcuswatkins.pisaver.filters.ImageMetaDataFilter; import net.marcuswatkins.pisaver.gl.GLImage; import net.marcuswatkins.pisaver.gl.GLImagePreparer; import net.marcuswatkins.pisaver.gl.GLScreen; import net.marcuswatkins.pisaver.gl.GLTextureData; import net.marcuswatkins.pisaver.sources.FileImageSource; import net.marcuswatkins.pisaver.util.Util; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.util.Animator; public class PiSaver implements GLEventListener { public static final String PROPS_FILE = "pisaver.prop"; static String filename; private static int width = 640; private static int height = 480; private static Saver<GL2ES2, GLTextureData, GLScreen> saver; private static GLScreen screen; private static ImageMetaDataFilter filter; private static File folders[]; private static File cacheDir; public static void main(String[] args) { Properties props = new Properties( ); File propsFile = new File( PROPS_FILE ); if( propsFile.exists() && propsFile.canRead() ) { try { InputStream is = new FileInputStream( propsFile ); props.load( is ); is.close(); } catch( Exception e ) { System.err.println( "Error reading " + PROPS_FILE + ":" ); e.printStackTrace(); } } String folderStr = props.getProperty( "folders", args.length > 0 ? args[0] : "" ); System.out.println( "Using folders: " + folderStr ); String folderStrAr[] = folderStr.split( ";" ); folders = new File[folderStrAr.length]; for( int i = 0; i < folders.length; i++ ) { folders[i] = new File( folderStrAr[i] ); } float minRating = Util.safeParseFloat( props.getProperty( "minRating" ), -1.0f ); float maxRating = Util.safeParseFloat( props.getProperty( "maxRating" ), -1.0f ); String includedTags = props.getProperty( "includeTags" ); String includedTagsAr[] = null; if( includedTags != null ) { includedTags = includedTags.trim().toLowerCase(); if( includedTags.length() > 0 ) { includedTagsAr = includedTags.split( ";" ); } } String excludedTags = props.getProperty( "excludeTags" ); String excludedTagsAr[] = null; if( excludedTags != null ) { excludedTags = excludedTags.trim().toLowerCase(); if( excludedTags.length() > 0 ) { excludedTagsAr = excludedTags.split( ";" ); } } String cacheDirStr = props.getProperty( "cacheDir" ); if( cacheDirStr != null && cacheDirStr.length() > 0 ) { cacheDir = new File( cacheDirStr ); } int cfgWidth = Util.safeParseInt(props.getProperty( "width" ), -1); int cfgHeight = Util.safeParseInt(props.getProperty( "height" ), -1); filter = new ImageMetaDataFilter( minRating, maxRating, includedTagsAr, excludedTagsAr ); saver = new Saver<GL2ES2,GLTextureData,GLScreen>( ); GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GL2ES2)); // We may at this point tweak the caps and request a translucent // drawable caps.setNumSamples( 8 ); caps.setSampleBuffers( true ); caps.setBackgroundOpaque(true); GLWindow glWindow = GLWindow.create(caps); // In this demo we prefer to setup and view the GLWindow directly // this allows the demo to run on -Djava.awt.headless=true systems boolean fs = false; if( cfgWidth == -1 || cfgHeight == -1 ) { Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); width = (int)dim.getWidth(); height = (int)dim.getHeight(); } else { width = cfgWidth; height = cfgHeight; fs = true; } glWindow.setTitle("Collage Saver"); glWindow.setSize(width, height); glWindow.setUndecorated(false); glWindow.setPointerVisible(true); glWindow.setVisible(true); glWindow.setFullscreen( fs ); //glWindow.setSize( glWindow.getScreen().getWidth(), glWindow.getScreen().getHeight() ); //glWindow.getScreen().getWidth(); // Finally we connect the GLEventListener application code to the NEWT // GLWindow. // GLWindow will call the GLEventListener init, reshape, display and // dispose // functions when needed. glWindow.addGLEventListener(new PiSaver() /* GLEventListener */); Animator animator = new Animator(glWindow); - animator.add(glWindow); + //animator.add(glWindow); This throws an error with no jogl animator.start(); } public void init(GLAutoDrawable drawable) { GL2ES2 gl = drawable.getGL().getGL2ES2(); System.err.println("Chosen GLCapabilities: " + drawable.getChosenGLCapabilities()); System.err.println("INIT GL IS: " + gl.getClass().getName()); System.err.println("GL_VENDOR: " + gl.glGetString(GL.GL_VENDOR)); System.err.println("GL_RENDERER: " + gl.glGetString(GL.GL_RENDERER)); System.err.println("GL_VERSION: " + gl.glGetString(GL.GL_VERSION)); try { GLImage.init(gl); screen = new GLScreen( gl ); } catch (Exception e) { e.printStackTrace(); System.exit( 0 ); } gl.glEnable( GL2ES2.GL_BLEND ); gl.glBlendFunc( GL2ES2.GL_SRC_ALPHA, GL2ES2.GL_ONE_MINUS_SRC_ALPHA ); ImagePreparer<GLTextureData> preparer = new GLImagePreparer( gl ); if( cacheDir != null && cacheDir.isDirectory() ) { preparer = new CachingImagePreparer<GLTextureData>( cacheDir, preparer, new GLTextureData() ); } saver.init( new FileImageSource<GLTextureData>( folders, filter, preparer ), screen ); } public void reshape(GLAutoDrawable drawable, int x, int y, int z, int h) { System.out.println("Window resized to width=" + z + " height=" + h); width = z; height = h; screen.reshape( width, height ); saver.screenChanged(); } public void display(GLAutoDrawable drawable) { //drawable.setGL( new DebugGL2ES2( drawable.getGL().getGL2ES2() ) ); GL2ES2 gl = drawable.getGL().getGL2ES2(); gl.glClearColor(0, 0, 0, 1.0f); //Black gl.glClear(GL2ES2.GL_STENCIL_BUFFER_BIT | GL2ES2.GL_COLOR_BUFFER_BIT | GL2ES2.GL_DEPTH_BUFFER_BIT); saver.draw( gl ); } public void dispose(GLAutoDrawable drawable) { System.out.println("cleanup, remember to release shaders"); GL2ES2 gl = drawable.getGL().getGL2ES2(); gl.glUseProgram(0); System.out.println( "TODO: cleanup properly" ); saver.dispose( gl ); /* gl.glDetachShader(shaderProgram, vertShader); gl.glDeleteShader(vertShader); gl.glDetachShader(shaderProgram, fragShader); gl.glDeleteShader(fragShader); gl.glDeleteProgram(shaderProgram); */ System.exit(0); } }
true
true
public static void main(String[] args) { Properties props = new Properties( ); File propsFile = new File( PROPS_FILE ); if( propsFile.exists() && propsFile.canRead() ) { try { InputStream is = new FileInputStream( propsFile ); props.load( is ); is.close(); } catch( Exception e ) { System.err.println( "Error reading " + PROPS_FILE + ":" ); e.printStackTrace(); } } String folderStr = props.getProperty( "folders", args.length > 0 ? args[0] : "" ); System.out.println( "Using folders: " + folderStr ); String folderStrAr[] = folderStr.split( ";" ); folders = new File[folderStrAr.length]; for( int i = 0; i < folders.length; i++ ) { folders[i] = new File( folderStrAr[i] ); } float minRating = Util.safeParseFloat( props.getProperty( "minRating" ), -1.0f ); float maxRating = Util.safeParseFloat( props.getProperty( "maxRating" ), -1.0f ); String includedTags = props.getProperty( "includeTags" ); String includedTagsAr[] = null; if( includedTags != null ) { includedTags = includedTags.trim().toLowerCase(); if( includedTags.length() > 0 ) { includedTagsAr = includedTags.split( ";" ); } } String excludedTags = props.getProperty( "excludeTags" ); String excludedTagsAr[] = null; if( excludedTags != null ) { excludedTags = excludedTags.trim().toLowerCase(); if( excludedTags.length() > 0 ) { excludedTagsAr = excludedTags.split( ";" ); } } String cacheDirStr = props.getProperty( "cacheDir" ); if( cacheDirStr != null && cacheDirStr.length() > 0 ) { cacheDir = new File( cacheDirStr ); } int cfgWidth = Util.safeParseInt(props.getProperty( "width" ), -1); int cfgHeight = Util.safeParseInt(props.getProperty( "height" ), -1); filter = new ImageMetaDataFilter( minRating, maxRating, includedTagsAr, excludedTagsAr ); saver = new Saver<GL2ES2,GLTextureData,GLScreen>( ); GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GL2ES2)); // We may at this point tweak the caps and request a translucent // drawable caps.setNumSamples( 8 ); caps.setSampleBuffers( true ); caps.setBackgroundOpaque(true); GLWindow glWindow = GLWindow.create(caps); // In this demo we prefer to setup and view the GLWindow directly // this allows the demo to run on -Djava.awt.headless=true systems boolean fs = false; if( cfgWidth == -1 || cfgHeight == -1 ) { Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); width = (int)dim.getWidth(); height = (int)dim.getHeight(); } else { width = cfgWidth; height = cfgHeight; fs = true; } glWindow.setTitle("Collage Saver"); glWindow.setSize(width, height); glWindow.setUndecorated(false); glWindow.setPointerVisible(true); glWindow.setVisible(true); glWindow.setFullscreen( fs ); //glWindow.setSize( glWindow.getScreen().getWidth(), glWindow.getScreen().getHeight() ); //glWindow.getScreen().getWidth(); // Finally we connect the GLEventListener application code to the NEWT // GLWindow. // GLWindow will call the GLEventListener init, reshape, display and // dispose // functions when needed. glWindow.addGLEventListener(new PiSaver() /* GLEventListener */); Animator animator = new Animator(glWindow); animator.add(glWindow); animator.start(); }
public static void main(String[] args) { Properties props = new Properties( ); File propsFile = new File( PROPS_FILE ); if( propsFile.exists() && propsFile.canRead() ) { try { InputStream is = new FileInputStream( propsFile ); props.load( is ); is.close(); } catch( Exception e ) { System.err.println( "Error reading " + PROPS_FILE + ":" ); e.printStackTrace(); } } String folderStr = props.getProperty( "folders", args.length > 0 ? args[0] : "" ); System.out.println( "Using folders: " + folderStr ); String folderStrAr[] = folderStr.split( ";" ); folders = new File[folderStrAr.length]; for( int i = 0; i < folders.length; i++ ) { folders[i] = new File( folderStrAr[i] ); } float minRating = Util.safeParseFloat( props.getProperty( "minRating" ), -1.0f ); float maxRating = Util.safeParseFloat( props.getProperty( "maxRating" ), -1.0f ); String includedTags = props.getProperty( "includeTags" ); String includedTagsAr[] = null; if( includedTags != null ) { includedTags = includedTags.trim().toLowerCase(); if( includedTags.length() > 0 ) { includedTagsAr = includedTags.split( ";" ); } } String excludedTags = props.getProperty( "excludeTags" ); String excludedTagsAr[] = null; if( excludedTags != null ) { excludedTags = excludedTags.trim().toLowerCase(); if( excludedTags.length() > 0 ) { excludedTagsAr = excludedTags.split( ";" ); } } String cacheDirStr = props.getProperty( "cacheDir" ); if( cacheDirStr != null && cacheDirStr.length() > 0 ) { cacheDir = new File( cacheDirStr ); } int cfgWidth = Util.safeParseInt(props.getProperty( "width" ), -1); int cfgHeight = Util.safeParseInt(props.getProperty( "height" ), -1); filter = new ImageMetaDataFilter( minRating, maxRating, includedTagsAr, excludedTagsAr ); saver = new Saver<GL2ES2,GLTextureData,GLScreen>( ); GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GL2ES2)); // We may at this point tweak the caps and request a translucent // drawable caps.setNumSamples( 8 ); caps.setSampleBuffers( true ); caps.setBackgroundOpaque(true); GLWindow glWindow = GLWindow.create(caps); // In this demo we prefer to setup and view the GLWindow directly // this allows the demo to run on -Djava.awt.headless=true systems boolean fs = false; if( cfgWidth == -1 || cfgHeight == -1 ) { Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); width = (int)dim.getWidth(); height = (int)dim.getHeight(); } else { width = cfgWidth; height = cfgHeight; fs = true; } glWindow.setTitle("Collage Saver"); glWindow.setSize(width, height); glWindow.setUndecorated(false); glWindow.setPointerVisible(true); glWindow.setVisible(true); glWindow.setFullscreen( fs ); //glWindow.setSize( glWindow.getScreen().getWidth(), glWindow.getScreen().getHeight() ); //glWindow.getScreen().getWidth(); // Finally we connect the GLEventListener application code to the NEWT // GLWindow. // GLWindow will call the GLEventListener init, reshape, display and // dispose // functions when needed. glWindow.addGLEventListener(new PiSaver() /* GLEventListener */); Animator animator = new Animator(glWindow); //animator.add(glWindow); This throws an error with no jogl animator.start(); }
diff --git a/src/com/android/contacts/ContactsListActivity.java b/src/com/android/contacts/ContactsListActivity.java index 0ddb608ca..968252e3d 100644 --- a/src/com/android/contacts/ContactsListActivity.java +++ b/src/com/android/contacts/ContactsListActivity.java @@ -1,2007 +1,2004 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.app.SearchManager; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.IContentProvider; import android.content.ISyncAdapter; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.database.CharArrayBuffer; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.os.RemoteException; import android.preference.PreferenceManager; import android.provider.Contacts; import android.provider.Contacts.ContactMethods; import android.provider.Contacts.Groups; import android.provider.Contacts.Intents; import android.provider.Contacts.People; import android.provider.Contacts.Phones; import android.provider.Contacts.Presence; import android.provider.Contacts.Intents.Insert; import android.provider.Contacts.Intents.UI; import android.text.TextUtils; import android.util.Log; import android.util.SparseArray; import android.view.ContextMenu; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ContextMenu.ContextMenuInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AlphabetIndexer; import android.widget.Filter; import android.widget.ImageView; import android.widget.ListView; import android.widget.ResourceCursorAdapter; import android.widget.SectionIndexer; import android.widget.TextView; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Locale; /** * Displays a list of contacts. Usually is embedded into the ContactsActivity. */ public final class ContactsListActivity extends ListActivity implements View.OnCreateContextMenuListener, DialogInterface.OnClickListener { private static final String TAG = "ContactsListActivity"; private static final boolean ENABLE_ACTION_ICON_OVERLAYS = false; private static final String LIST_STATE_KEY = "liststate"; private static final String FOCUS_KEY = "focused"; static final int MENU_ITEM_VIEW_CONTACT = 1; static final int MENU_ITEM_CALL = 2; static final int MENU_ITEM_EDIT_BEFORE_CALL = 3; static final int MENU_ITEM_SEND_SMS = 4; static final int MENU_ITEM_SEND_IM = 5; static final int MENU_ITEM_EDIT = 6; static final int MENU_ITEM_DELETE = 7; static final int MENU_ITEM_TOGGLE_STAR = 8; public static final int MENU_SEARCH = 1; public static final int MENU_DIALER = 9; public static final int MENU_NEW_CONTACT = 10; public static final int MENU_DISPLAY_GROUP = 11; public static final int MENU_IMPORT_CONTACTS = 12; private static final int SUBACTIVITY_NEW_CONTACT = 1; /** Mask for picker mode */ static final int MODE_MASK_PICKER = 0x80000000; /** Mask for no presence mode */ static final int MODE_MASK_NO_PRESENCE = 0x40000000; /** Mask for enabling list filtering */ static final int MODE_MASK_NO_FILTER = 0x20000000; /** Mask for having a "create new contact" header in the list */ static final int MODE_MASK_CREATE_NEW = 0x10000000; /** Mask for showing photos in the list */ static final int MODE_MASK_SHOW_PHOTOS = 0x08000000; /** Unknown mode */ static final int MODE_UNKNOWN = 0; /** Show members of the "Contacts" group */ static final int MODE_GROUP = 5; /** Show all contacts sorted alphabetically */ static final int MODE_ALL_CONTACTS = 10; /** Show all contacts with phone numbers, sorted alphabetically */ static final int MODE_WITH_PHONES = 15; /** Show all starred contacts */ static final int MODE_STARRED = 20; /** Show frequently contacted contacts */ static final int MODE_FREQUENT = 30; /** Show starred and the frequent */ static final int MODE_STREQUENT = 35 | MODE_MASK_SHOW_PHOTOS; /** Show all contacts and pick them when clicking */ static final int MODE_PICK_CONTACT = 40 | MODE_MASK_PICKER; /** Show all contacts as well as the option to create a new one */ static final int MODE_PICK_OR_CREATE_CONTACT = 42 | MODE_MASK_PICKER | MODE_MASK_CREATE_NEW; /** Show all contacts and pick them when clicking, and allow creating a new contact */ static final int MODE_INSERT_OR_EDIT_CONTACT = 45 | MODE_MASK_PICKER | MODE_MASK_CREATE_NEW; /** Show all phone numbers and pick them when clicking */ static final int MODE_PICK_PHONE = 50 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE; /** Show all postal addresses and pick them when clicking */ static final int MODE_PICK_POSTAL = 55 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE | MODE_MASK_NO_FILTER; /** Run a search query */ static final int MODE_QUERY = 60 | MODE_MASK_NO_FILTER; /** Run a search query in PICK mode, but that still launches to VIEW */ static final int MODE_QUERY_PICK_TO_VIEW = 65 | MODE_MASK_NO_FILTER | MODE_MASK_PICKER; static final int DEFAULT_MODE = MODE_ALL_CONTACTS; /** * The type of data to display in the main contacts list. */ static final String PREF_DISPLAY_TYPE = "display_system_group"; /** Unknown display type. */ static final int DISPLAY_TYPE_UNKNOWN = -1; /** Display all contacts */ static final int DISPLAY_TYPE_ALL = 0; /** Display all contacts that have phone numbers */ static final int DISPLAY_TYPE_ALL_WITH_PHONES = 1; /** Display a system group */ static final int DISPLAY_TYPE_SYSTEM_GROUP = 2; /** Display a user group */ static final int DISPLAY_TYPE_USER_GROUP = 3; /** * Info about what to display. If {@link #PREF_DISPLAY_TYPE} * is {@link #DISPLAY_TYPE_SYSTEM_GROUP} then this will be the system id. * If {@link #PREF_DISPLAY_TYPE} is {@link #DISPLAY_TYPE_USER_GROUP} then this will * be the group name. */ static final String PREF_DISPLAY_INFO = "display_group"; static final String NAME_COLUMN = People.DISPLAY_NAME; static final String SORT_STRING = People.SORT_STRING; static final String[] CONTACTS_PROJECTION = new String[] { People._ID, // 0 NAME_COLUMN, // 1 People.NUMBER, // 2 People.TYPE, // 3 People.LABEL, // 4 People.STARRED, // 5 People.PRIMARY_PHONE_ID, // 6 People.PRIMARY_EMAIL_ID, // 7 People.PRESENCE_STATUS, // 8 SORT_STRING, // 9 }; static final String[] SIMPLE_CONTACTS_PROJECTION = new String[] { People._ID, // 0 NAME_COLUMN, // 1 }; static final String[] STREQUENT_PROJECTION = new String[] { People._ID, // 0 NAME_COLUMN, // 1 People.NUMBER, // 2 People.TYPE, // 3 People.LABEL, // 4 People.STARRED, // 5 People.PRIMARY_PHONE_ID, // 6 People.PRIMARY_EMAIL_ID, // 7 People.PRESENCE_STATUS, // 8 "photo_data", // 9 People.TIMES_CONTACTED, // 10 (not displayed, but required for the order by to work) }; static final String[] PHONES_PROJECTION = new String[] { Phones._ID, // 0 NAME_COLUMN, // 1 Phones.NUMBER, // 2 Phones.TYPE, // 3 Phones.LABEL, // 4 Phones.STARRED, // 5 Phones.PERSON_ID, // 6 }; static final String[] CONTACT_METHODS_PROJECTION = new String[] { ContactMethods._ID, // 0 NAME_COLUMN, // 1 ContactMethods.DATA, // 2 ContactMethods.TYPE, // 3 ContactMethods.LABEL, // 4 ContactMethods.STARRED, // 5 ContactMethods.PERSON_ID, // 6 }; static final int ID_COLUMN_INDEX = 0; static final int NAME_COLUMN_INDEX = 1; static final int NUMBER_COLUMN_INDEX = 2; static final int DATA_COLUMN_INDEX = 2; static final int TYPE_COLUMN_INDEX = 3; static final int LABEL_COLUMN_INDEX = 4; static final int STARRED_COLUMN_INDEX = 5; static final int PRIMARY_PHONE_ID_COLUMN_INDEX = 6; static final int PRIMARY_EMAIL_ID_COLUMN_INDEX = 7; static final int SERVER_STATUS_COLUMN_INDEX = 8; static final int PHOTO_COLUMN_INDEX = 9; static final int SORT_STRING_INDEX = 9; static final int PHONES_PERSON_ID_INDEX = 6; static final int SIMPLE_CONTACTS_PERSON_ID_INDEX = 0; static final int DISPLAY_GROUP_INDEX_ALL_CONTACTS = 0; static final int DISPLAY_GROUP_INDEX_ALL_CONTACTS_WITH_PHONES = 1; static final int DISPLAY_GROUP_INDEX_MY_CONTACTS = 2; private static final int QUERY_TOKEN = 42; private static final String[] GROUPS_PROJECTION = new String[] { Groups.SYSTEM_ID, // 0 Groups.NAME, // 1 }; private static final int GROUPS_COLUMN_INDEX_SYSTEM_ID = 0; private static final int GROUPS_COLUMN_INDEX_NAME = 1; static final String GROUP_WITH_PHONES = "android_smartgroup_phone"; ContactItemListAdapter mAdapter; int mMode = DEFAULT_MODE; // The current display group private String mDisplayInfo; private int mDisplayType; // The current list of display groups, during selection from menu private CharSequence[] mDisplayGroups; // If true position 2 in mDisplayGroups is the MyContacts group private boolean mDisplayGroupsIncludesMyContacts = false; private int mDisplayGroupOriginalSelection; private int mDisplayGroupCurrentSelection; private QueryHandler mQueryHandler; private String mQuery; private Uri mGroupFilterUri; private Uri mGroupUri; private boolean mJustCreated; private boolean mSyncEnabled; /** * Cursor row index that holds reference back to {@link People#_ID}, such as * {@link ContactMethods#PERSON_ID}. Used when responding to a * {@link Intent#ACTION_SEARCH} in mode {@link #MODE_QUERY_PICK_TO_VIEW}. */ private int mQueryPersonIdIndex; /** * Used to keep track of the scroll state of the list. */ private Parcelable mListState = null; private boolean mListHasFocus; private String mShortcutAction; private boolean mDefaultMode = false; /** * Internal query type when in mode {@link #MODE_QUERY_PICK_TO_VIEW}. */ private int mQueryMode = QUERY_MODE_NONE; private static final int QUERY_MODE_NONE = -1; private static final int QUERY_MODE_MAILTO = 1; private static final int QUERY_MODE_TEL = 2; /** * Data to use when in mode {@link #MODE_QUERY_PICK_TO_VIEW}. Usually * provided by scheme-specific part of incoming {@link Intent#getData()}. */ private String mQueryData; private Handler mHandler = new Handler(); private class ImportTypeSelectedListener implements DialogInterface.OnClickListener { public static final int IMPORT_FROM_SIM = 0; public static final int IMPORT_FROM_SDCARD = 1; private int mIndex; public ImportTypeSelectedListener() { mIndex = IMPORT_FROM_SIM; } public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { if (mIndex == IMPORT_FROM_SIM) { doImportFromSim(); } else { VCardImporter importer = new VCardImporter(ContactsListActivity.this, mHandler); importer.startImportVCardFromSdCard(); } } else if (which == DialogInterface.BUTTON_NEGATIVE) { } else { mIndex = which; } } } private class DeleteClickListener implements DialogInterface.OnClickListener { private Uri mUri; public DeleteClickListener(Uri uri) { mUri = uri; } public void onClick(DialogInterface dialog, int which) { getContentResolver().delete(mUri, null, null); } } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); // Resolve the intent final Intent intent = getIntent(); // Allow the title to be set to a custom String using an extra on the intent String title = intent.getStringExtra(Contacts.Intents.UI.TITLE_EXTRA_KEY); if (title != null) { setTitle(title); } final String action = intent.getAction(); mMode = MODE_UNKNOWN; setContentView(R.layout.contacts_list_content); if (UI.LIST_DEFAULT.equals(action)) { mDefaultMode = true; // When mDefaultMode is true the mode is set in onResume(), since the preferneces // activity may change it whenever this activity isn't running } else if (UI.LIST_GROUP_ACTION.equals(action)) { mMode = MODE_GROUP; String groupName = intent.getStringExtra(UI.GROUP_NAME_EXTRA_KEY); if (TextUtils.isEmpty(groupName)) { finish(); return; } buildUserGroupUris(groupName); } else if (UI.LIST_ALL_CONTACTS_ACTION.equals(action)) { mMode = MODE_ALL_CONTACTS; } else if (UI.LIST_STARRED_ACTION.equals(action)) { mMode = MODE_STARRED; } else if (UI.LIST_FREQUENT_ACTION.equals(action)) { mMode = MODE_FREQUENT; } else if (UI.LIST_STREQUENT_ACTION.equals(action)) { mMode = MODE_STREQUENT; } else if (UI.LIST_CONTACTS_WITH_PHONES_ACTION.equals(action)) { mMode = MODE_WITH_PHONES; } else if (Intent.ACTION_PICK.equals(action)) { // XXX These should be showing the data from the URI given in // the Intent. final String type = intent.resolveType(this); if (People.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_CONTACT; } else if (Phones.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (ContactMethods.CONTENT_POSTAL_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } } else if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) { if (intent.getComponent().getClassName().equals("alias.DialShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_CALL; setTitle(R.string.callShortcutActivityTitle); } else if (intent.getComponent().getClassName().equals("alias.MessageShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_SENDTO; setTitle(R.string.messageShortcutActivityTitle); } else { mMode = MODE_PICK_OR_CREATE_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } } else if (Intent.ACTION_GET_CONTENT.equals(action)) { final String type = intent.resolveType(this); if (People.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_OR_CREATE_CONTACT; } else if (Phones.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (ContactMethods.CONTENT_POSTAL_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } } else if (Intent.ACTION_INSERT_OR_EDIT.equals(action)) { mMode = MODE_INSERT_OR_EDIT_CONTACT; } else if (Intent.ACTION_SEARCH.equals(action)) { // See if the suggestion was clicked with a search action key (call button) if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG))) { String query = intent.getStringExtra(SearchManager.QUERY); if (!TextUtils.isEmpty(query)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", query, null)); startActivity(newIntent); } finish(); return; } // See if search request has extras to specify query if (intent.hasExtra(Insert.EMAIL)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_MAILTO; mQueryData = intent.getStringExtra(Insert.EMAIL); } else if (intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_TEL; mQueryData = intent.getStringExtra(Insert.PHONE); } else { // Otherwise handle the more normal search case mMode = MODE_QUERY; } // Since this is the filter activity it receives all intents // dispatched from the SearchManager for security reasons // so we need to re-dispatch from here to the intended target. } else if (Intents.SEARCH_SUGGESTION_CLICKED.equals(action)) { // See if the suggestion was clicked with a search action key (call button) Intent newIntent; if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG))) { newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData()); } else { newIntent = new Intent(Intent.ACTION_VIEW, intent.getData()); } startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED.equals(action)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData()); startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED.equals(action)) { String number = intent.getData().getSchemeSpecificPart(); Intent newIntent = new Intent(Intent.ACTION_INSERT, People.CONTENT_URI); newIntent.putExtra(Intents.Insert.PHONE, number); startActivity(newIntent); finish(); return; } if (mMode == MODE_UNKNOWN) { mMode = DEFAULT_MODE; } // Setup the UI final ListView list = getListView(); list.setFocusable(true); list.setOnCreateContextMenuListener(this); if ((mMode & MODE_MASK_NO_FILTER) != MODE_MASK_NO_FILTER) { list.setTextFilterEnabled(true); - list.setGestures(ListView.GESTURES_FILTER); - } else { - list.setGestures(ListView.GESTURES_NONE); } if ((mMode & MODE_MASK_CREATE_NEW) != 0) { // Add the header for creating a new contact final LayoutInflater inflater = getLayoutInflater(); View header = inflater.inflate(android.R.layout.simple_list_item_1, list, false); TextView text = (TextView) header.findViewById(android.R.id.text1); text.setText(R.string.pickerNewContactHeader); list.addHeaderView(header); } // Set the proper empty string setEmptyText(); mAdapter = new ContactItemListAdapter(this); setListAdapter(mAdapter); // We manually save/restore the listview state list.setSaveEnabled(false); mQueryHandler = new QueryHandler(this); mJustCreated = true; // Check to see if sync is enabled final ContentResolver resolver = getContentResolver(); IContentProvider provider = resolver.acquireProvider(Contacts.CONTENT_URI); if (provider == null) { // No contacts provider, bail. finish(); return; } try { ISyncAdapter sa = provider.getSyncAdapter(); mSyncEnabled = sa != null; } catch (RemoteException e) { mSyncEnabled = false; } finally { resolver.releaseProvider(provider); } } private void setEmptyText() { TextView empty = (TextView) findViewById(R.id.emptyText); // Center the text by default int gravity = Gravity.CENTER; switch (mMode) { case MODE_GROUP: if (Groups.GROUP_MY_CONTACTS.equals(mDisplayInfo)) { if (mSyncEnabled) { empty.setText(getText(R.string.noContactsHelpTextWithSync)); } else { empty.setText(getText(R.string.noContactsHelpText)); } gravity = Gravity.NO_GRAVITY; } else { empty.setText(getString(R.string.groupEmpty, mDisplayInfo)); } break; case MODE_STARRED: case MODE_STREQUENT: case MODE_FREQUENT: empty.setText(getText(R.string.noFavorites)); break; case MODE_WITH_PHONES: empty.setText(getText(R.string.noContactsWithPhoneNumbers)); break; default: empty.setText(getText(R.string.noContacts)); break; } empty.setGravity(gravity); } /** * Builds the URIs to query when displaying a user group * * @param groupName the group being displayed */ private void buildUserGroupUris(String groupName) { mGroupFilterUri = Uri.parse("content://contacts/groups/name/" + groupName + "/members/filter/"); mGroupUri = Uri.parse("content://contacts/groups/name/" + groupName + "/members"); } /** * Builds the URIs to query when displaying a system group * * @param systemId the system group's ID */ private void buildSystemGroupUris(String systemId) { mGroupFilterUri = Uri.parse("content://contacts/groups/system_id/" + systemId + "/members/filter/"); mGroupUri = Uri.parse("content://contacts/groups/system_id/" + systemId + "/members"); } /** * Sets the mode when the request is for "default" */ private void setDefaultMode() { // Load the preferences SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); // Lookup the group to display mDisplayType = prefs.getInt(PREF_DISPLAY_TYPE, DISPLAY_TYPE_UNKNOWN); switch (mDisplayType) { case DISPLAY_TYPE_ALL_WITH_PHONES: { mMode = MODE_WITH_PHONES; mDisplayInfo = null; break; } case DISPLAY_TYPE_SYSTEM_GROUP: { String systemId = prefs.getString( PREF_DISPLAY_INFO, null); if (!TextUtils.isEmpty(systemId)) { // Display the selected system group mMode = MODE_GROUP; buildSystemGroupUris(systemId); mDisplayInfo = systemId; } else { // No valid group is present, display everything mMode = MODE_WITH_PHONES; mDisplayInfo = null; mDisplayType = DISPLAY_TYPE_ALL; } break; } case DISPLAY_TYPE_USER_GROUP: { String displayGroup = prefs.getString( PREF_DISPLAY_INFO, null); if (!TextUtils.isEmpty(displayGroup)) { // Display the selected user group mMode = MODE_GROUP; buildUserGroupUris(displayGroup); mDisplayInfo = displayGroup; } else { // No valid group is present, display everything mMode = MODE_WITH_PHONES; mDisplayInfo = null; mDisplayType = DISPLAY_TYPE_ALL; } break; } case DISPLAY_TYPE_ALL: { mMode = MODE_ALL_CONTACTS; mDisplayInfo = null; break; } default: { // We don't know what to display, default to My Contacts mMode = MODE_GROUP; mDisplayType = DISPLAY_TYPE_SYSTEM_GROUP; buildSystemGroupUris(Groups.GROUP_MY_CONTACTS); mDisplayInfo = Groups.GROUP_MY_CONTACTS; break; } } // Update the empty text view with the proper string, as the group may have changed setEmptyText(); } @Override protected void onResume() { super.onResume(); boolean runQuery = true; Activity parent = getParent(); // Do this before setting the filter. The filter thread relies // on some state that is initialized in setDefaultMode if (mDefaultMode) { // If we're in default mode we need to possibly reset the mode due to a change // in the preferences activity while we weren't running setDefaultMode(); } // See if we were invoked with a filter if (parent != null && parent instanceof DialtactsActivity) { String filterText = ((DialtactsActivity) parent).getAndClearFilterText(); if (filterText != null && filterText.length() > 0) { getListView().setFilterText(filterText); // Don't start a new query since it will conflict with the filter runQuery = false; } else if (mJustCreated) { getListView().clearTextFilter(); } } if (mJustCreated && runQuery) { // We need to start a query here the first time the activity is launched, as long // as we aren't doing a filter. startQuery(); } mJustCreated = false; } @Override protected void onRestart() { super.onRestart(); // The cursor was killed off in onStop(), so we need to get a new one here // We do not perform the query if a filter is set on the list because the // filter will cause the query to happen anyway if (TextUtils.isEmpty(getListView().getTextFilter())) { startQuery(); } else { // Run the filtered query on the adapter ((ContactItemListAdapter) getListAdapter()).onContentChanged(); } } private void updateGroup() { if (mDefaultMode) { setDefaultMode(); } // Calling requery here may cause an ANR, so always do the async query startQuery(); } @Override protected void onSaveInstanceState(Bundle icicle) { super.onSaveInstanceState(icicle); // Save list state in the bundle so we can restore it after the QueryHandler has run icicle.putParcelable(LIST_STATE_KEY, mList.onSaveInstanceState()); icicle.putBoolean(FOCUS_KEY, mList.hasFocus()); } @Override protected void onRestoreInstanceState(Bundle icicle) { super.onRestoreInstanceState(icicle); // Retrieve list state. This will be applied after the QueryHandler has run mListState = icicle.getParcelable(LIST_STATE_KEY); mListHasFocus = icicle.getBoolean(FOCUS_KEY); } @Override protected void onStop() { super.onStop(); // We don't want the list to display the empty state, since when we resume it will still // be there and show up while the new query is happening. After the async query finished // in response to onRestart() setLoading(false) will be called. mAdapter.setLoading(true); mAdapter.changeCursor(null); if (mMode == MODE_QUERY) { // Make sure the search box is closed SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); searchManager.stopSearch(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // If Contacts was invoked by another Activity simply as a way of // picking a contact, don't show the options menu if ((mMode & MODE_MASK_PICKER) == MODE_MASK_PICKER) { return false; } // Search menu.add(0, MENU_SEARCH, 0, R.string.menu_search) .setIcon(android.R.drawable.ic_menu_search); // New contact menu.add(0, MENU_NEW_CONTACT, 0, R.string.menu_newContact) .setIcon(android.R.drawable.ic_menu_add) .setIntent(new Intent(Intents.Insert.ACTION, People.CONTENT_URI)) .setAlphabeticShortcut('n'); // Display group if (mDefaultMode) { menu.add(0, MENU_DISPLAY_GROUP, 0, R.string.menu_displayGroup) .setIcon(com.android.internal.R.drawable.ic_menu_allfriends); } // Sync settings if (mSyncEnabled) { Intent syncIntent = new Intent(Intent.ACTION_VIEW); syncIntent.setClass(this, ContactsGroupSyncSelector.class); menu.add(0, 0, 0, R.string.syncGroupPreference) .setIcon(com.android.internal.R.drawable.ic_menu_refresh) .setIntent(syncIntent); } // Contacts import (SIM/SDCard) menu.add(0, MENU_IMPORT_CONTACTS, 0, R.string.importFromSim) .setIcon(R.drawable.ic_menu_import_contact); return super.onCreateOptionsMenu(menu); } /* * Implements the handler for display group selection. */ public void onClick(DialogInterface dialogInterface, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { // The OK button was pressed if (mDisplayGroupOriginalSelection != mDisplayGroupCurrentSelection) { // Set the group to display if (mDisplayGroupCurrentSelection == DISPLAY_GROUP_INDEX_ALL_CONTACTS) { // Display all mDisplayType = DISPLAY_TYPE_ALL; mDisplayInfo = null; } else if (mDisplayGroupCurrentSelection == DISPLAY_GROUP_INDEX_ALL_CONTACTS_WITH_PHONES) { // Display all with phone numbers mDisplayType = DISPLAY_TYPE_ALL_WITH_PHONES; mDisplayInfo = null; } else if (mDisplayGroupsIncludesMyContacts && mDisplayGroupCurrentSelection == DISPLAY_GROUP_INDEX_MY_CONTACTS) { mDisplayType = DISPLAY_TYPE_SYSTEM_GROUP; mDisplayInfo = Groups.GROUP_MY_CONTACTS; } else { mDisplayType = DISPLAY_TYPE_USER_GROUP; mDisplayInfo = mDisplayGroups[mDisplayGroupCurrentSelection].toString(); } // Save the changes to the preferences SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); prefs.edit() .putInt(PREF_DISPLAY_TYPE, mDisplayType) .putString(PREF_DISPLAY_INFO, mDisplayInfo) .commit(); // Update the display state updateGroup(); } } else { // A list item was selected, cache the position mDisplayGroupCurrentSelection = which; } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_DISPLAY_GROUP: AlertDialog.Builder builder = new AlertDialog.Builder(this) .setTitle(R.string.select_group_title) .setPositiveButton(android.R.string.ok, this) .setNegativeButton(android.R.string.cancel, null); setGroupEntries(builder); builder.show(); return true; case MENU_SEARCH: startSearch(null, false, null, false); return true; case MENU_IMPORT_CONTACTS: if (getResources().getBoolean(R.bool.config_allow_import_from_sd_card)) { ImportTypeSelectedListener listener = new ImportTypeSelectedListener(); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this) .setTitle(R.string.select_import_type_title) .setPositiveButton(android.R.string.ok, listener) .setNegativeButton(android.R.string.cancel, null); dialogBuilder.setSingleChoiceItems(new String[] { getString(R.string.import_from_sim), getString(R.string.import_from_sdcard)}, ImportTypeSelectedListener.IMPORT_FROM_SIM, listener); dialogBuilder.show(); } else { doImportFromSim(); } return true; } return false; } private void doImportFromSim() { Intent importIntent = new Intent(Intent.ACTION_VIEW); importIntent.setType("vnd.android.cursor.item/sim-contact"); importIntent.setClassName("com.android.phone", "com.android.phone.SimContacts"); startActivity(importIntent); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case SUBACTIVITY_NEW_CONTACT: if (resultCode == RESULT_OK) { // Contact was created, pass it back returnPickerResult(null, data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME), data.getData(), 0); } } } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { // If Contacts was invoked by another Activity simply as a way of // picking a contact, don't show the context menu if ((mMode & MODE_MASK_PICKER) == MODE_MASK_PICKER) { return; } AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) menuInfo; } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return; } Cursor cursor = (Cursor) getListAdapter().getItem(info.position); if (cursor == null) { // For some reason the requested item isn't available, do nothing return; } long id = info.id; Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, id); // Setup the menu header menu.setHeaderTitle(cursor.getString(NAME_COLUMN_INDEX)); // View contact details menu.add(0, MENU_ITEM_VIEW_CONTACT, 0, R.string.menu_viewContact) .setIntent(new Intent(Intent.ACTION_VIEW, personUri)); // Calling contact long phoneId = cursor.getLong(PRIMARY_PHONE_ID_COLUMN_INDEX); if (phoneId > 0) { // Get the display label for the number CharSequence label = cursor.getString(LABEL_COLUMN_INDEX); int type = cursor.getInt(TYPE_COLUMN_INDEX); label = Phones.getDisplayLabel(this, type, label); Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, ContentUris.withAppendedId(Phones.CONTENT_URI, phoneId)); menu.add(0, MENU_ITEM_CALL, 0, String.format(getString(R.string.menu_callNumber), label)) .setIntent(intent); // Send SMS item menu.add(0, MENU_ITEM_SEND_SMS, 0, R.string.menu_sendSMS) .setIntent(new Intent(Intent.ACTION_SENDTO, Uri.fromParts("sms", cursor.getString(NUMBER_COLUMN_INDEX), null))); } // Star toggling int starState = cursor.getInt(STARRED_COLUMN_INDEX); if (starState == 0) { menu.add(0, MENU_ITEM_TOGGLE_STAR, 0, R.string.menu_addStar); } else { menu.add(0, MENU_ITEM_TOGGLE_STAR, 0, R.string.menu_removeStar); } // Contact editing menu.add(0, MENU_ITEM_EDIT, 0, R.string.menu_editContact) .setIntent(new Intent(Intent.ACTION_EDIT, personUri)); menu.add(0, MENU_ITEM_DELETE, 0, R.string.menu_deleteContact); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return false; } Cursor cursor = (Cursor) getListAdapter().getItem(info.position); switch (item.getItemId()) { case MENU_ITEM_TOGGLE_STAR: { // Toggle the star ContentValues values = new ContentValues(1); values.put(People.STARRED, cursor.getInt(STARRED_COLUMN_INDEX) == 0 ? 1 : 0); Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, cursor.getInt(ID_COLUMN_INDEX)); getContentResolver().update(personUri, values, null, null); return true; } case MENU_ITEM_DELETE: { // Get confirmation Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, cursor.getLong(ID_COLUMN_INDEX)); //TODO make this dialog persist across screen rotations new AlertDialog.Builder(ContactsListActivity.this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.deleteConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DeleteClickListener(uri)) .show(); return true; } } return super.onContextItemSelected(item); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_CALL: { if (callSelection()) { return true; } break; } case KeyEvent.KEYCODE_DEL: { Object o = getListView().getSelectedItem(); if (o != null) { Cursor cursor = (Cursor) o; Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, cursor.getLong(ID_COLUMN_INDEX)); //TODO make this dialog persist across screen rotations new AlertDialog.Builder(ContactsListActivity.this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.deleteConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DeleteClickListener(uri)) .setCancelable(false) .show(); return true; } break; } } return super.onKeyDown(keyCode, event); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { // Hide soft keyboard, if visible InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(mList.getWindowToken(), 0); if (mMode == MODE_INSERT_OR_EDIT_CONTACT) { Intent intent; if (position == 0) { // Insert intent = new Intent(Intent.ACTION_INSERT, People.CONTENT_URI); } else { // Edit intent = new Intent(Intent.ACTION_EDIT, ContentUris.withAppendedId(People.CONTENT_URI, id)); } intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); final Bundle extras = getIntent().getExtras(); if (extras != null) { intent.putExtras(extras); } startActivity(intent); finish(); } else if (id != -1) { if ((mMode & MODE_MASK_PICKER) == 0) { Intent intent = new Intent(Intent.ACTION_VIEW, ContentUris.withAppendedId(People.CONTENT_URI, id)); startActivity(intent); } else if (mMode == MODE_QUERY_PICK_TO_VIEW) { // Started with query that should launch to view contact Cursor c = (Cursor) mAdapter.getItem(position); long personId = c.getLong(mQueryPersonIdIndex); Intent intent = new Intent(Intent.ACTION_VIEW, ContentUris.withAppendedId(People.CONTENT_URI, personId)); startActivity(intent); finish(); } else if (mMode == MODE_PICK_CONTACT || mMode == MODE_PICK_OR_CREATE_CONTACT) { Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, id); if (mShortcutAction != null) { // Subtract one if we have Create Contact at the top Cursor c = (Cursor) mAdapter.getItem(position - (mMode == MODE_PICK_OR_CREATE_CONTACT? 1:0)); returnPickerResult(c, c.getString(NAME_COLUMN_INDEX), uri, id); } else { returnPickerResult(null, null, uri, id); } } else if (mMode == MODE_PICK_PHONE) { Uri uri = ContentUris.withAppendedId(Phones.CONTENT_URI, id); if (mShortcutAction != null) { Cursor c = (Cursor) mAdapter.getItem(position); returnPickerResult(c, c.getString(NAME_COLUMN_INDEX), uri, id); } else { returnPickerResult(null, null, uri, id); } } else if (mMode == MODE_PICK_POSTAL) { setResult(RESULT_OK, new Intent().setData( ContentUris.withAppendedId(ContactMethods.CONTENT_URI, id))); finish(); } } else if ((mMode & MODE_MASK_CREATE_NEW) == MODE_MASK_CREATE_NEW && position == 0) { Intent newContact = new Intent(Intents.Insert.ACTION, People.CONTENT_URI); startActivityForResult(newContact, SUBACTIVITY_NEW_CONTACT); } else { signalError(); } } private void returnPickerResult(Cursor c, String name, Uri uri, long id) { final Intent intent = new Intent(); if (mShortcutAction != null) { Intent shortcutIntent; if (Intent.ACTION_VIEW.equals(mShortcutAction)) { // This is a simple shortcut to view a contact. shortcutIntent = new Intent(mShortcutAction, uri); final Bitmap icon = People.loadContactPhoto(this, uri, 0, null); if (icon != null) { intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, icon); } else { intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher_shortcut_contact)); } } else { // This is a direct dial or sms shortcut. String number = c.getString(DATA_COLUMN_INDEX); int type = c.getInt(TYPE_COLUMN_INDEX); String scheme; int resid; if (Intent.ACTION_CALL.equals(mShortcutAction)) { scheme = "tel"; resid = R.drawable.badge_action_call; } else { scheme = "smsto"; resid = R.drawable.badge_action_sms; } // Make the URI a direct tel: URI so that it will always continue to work Uri phoneUri = Uri.fromParts(scheme, number, null); shortcutIntent = new Intent(mShortcutAction, phoneUri); Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, id); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, generatePhoneNumberIcon(personUri, type, resid)); } shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); setResult(RESULT_OK, intent); } else { setResult(RESULT_OK, intent.setData(uri)); } finish(); } /** * Generates a phone number shortcut icon. Adds an overlay describing the type of the phone * number, and if there is a photo also adds the call action icon. * * @param personUri The person the phone number belongs to * @param type The type of the phone number * @param actionResId The ID for the action resource * @return The bitmap for the icon */ private Bitmap generatePhoneNumberIcon(Uri personUri, int type, int actionResId) { final Resources r = getResources(); boolean drawPhoneOverlay = true; Bitmap photo = People.loadContactPhoto(this, personUri, 0, null); if (photo == null) { // If there isn't a photo use the generic phone action icon instead Bitmap phoneIcon = getPhoneActionIcon(r, actionResId); if (phoneIcon != null) { photo = phoneIcon; drawPhoneOverlay = false; } else { return null; } } // Setup the drawing classes int iconSize = (int) r.getDimension(android.R.dimen.app_icon_size); Bitmap icon = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(icon); // Copy in the photo Paint photoPaint = new Paint(); photoPaint.setDither(true); photoPaint.setFilterBitmap(true); Rect src = new Rect(0,0, photo.getWidth(),photo.getHeight()); Rect dst = new Rect(0,0, iconSize,iconSize); canvas.drawBitmap(photo, src, dst, photoPaint); // Create an overlay for the phone number type String overlay = null; switch (type) { case Phones.TYPE_HOME: overlay = "H"; break; case Phones.TYPE_MOBILE: overlay = "M"; break; case Phones.TYPE_WORK: overlay = "W"; break; case Phones.TYPE_PAGER: overlay = "P"; break; case Phones.TYPE_OTHER: overlay = "O"; break; } if (overlay != null) { Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); textPaint.setTextSize(20.0f); textPaint.setTypeface(Typeface.DEFAULT_BOLD); textPaint.setColor(r.getColor(R.color.textColorIconOverlay)); textPaint.setShadowLayer(3f, 1, 1, r.getColor(R.color.textColorIconOverlayShadow)); canvas.drawText(overlay, 2, 16, textPaint); } // Draw the phone action icon as an overlay if (ENABLE_ACTION_ICON_OVERLAYS && drawPhoneOverlay) { Bitmap phoneIcon = getPhoneActionIcon(r, actionResId); if (phoneIcon != null) { src.set(0,0, phoneIcon.getWidth(),phoneIcon.getHeight()); int iconWidth = icon.getWidth(); dst.set(iconWidth - 20, -1, iconWidth, 19); canvas.drawBitmap(phoneIcon, src, dst, photoPaint); } } return icon; } /** * Returns the icon for the phone call action. * * @param r The resources to load the icon from * @param resId The resource ID to load * @return the icon for the phone call action */ private Bitmap getPhoneActionIcon(Resources r, int resId) { Drawable phoneIcon = r.getDrawable(resId); if (phoneIcon instanceof BitmapDrawable) { BitmapDrawable bd = (BitmapDrawable) phoneIcon; return bd.getBitmap(); } else { return null; } } String[] getProjection() { switch (mMode) { case MODE_GROUP: case MODE_ALL_CONTACTS: case MODE_WITH_PHONES: case MODE_PICK_CONTACT: case MODE_PICK_OR_CREATE_CONTACT: case MODE_QUERY: case MODE_STARRED: case MODE_FREQUENT: case MODE_INSERT_OR_EDIT_CONTACT: return CONTACTS_PROJECTION; case MODE_STREQUENT: return STREQUENT_PROJECTION; case MODE_PICK_PHONE: return PHONES_PROJECTION; case MODE_PICK_POSTAL: return CONTACT_METHODS_PROJECTION; } return null; } private Uri getPeopleFilterUri(String filter) { if (!TextUtils.isEmpty(filter)) { return Uri.withAppendedPath(People.CONTENT_FILTER_URI, Uri.encode(filter)); } else { return People.CONTENT_URI; } } private static String getSortOrder(String[] projectionType) { if (Locale.getDefault().equals(Locale.JAPAN) && projectionType == CONTACTS_PROJECTION) { return SORT_STRING + " ASC"; } else { return NAME_COLUMN + " COLLATE LOCALIZED ASC"; } } void startQuery() { mAdapter.setLoading(true); // Cancel any pending queries mQueryHandler.cancelOperation(QUERY_TOKEN); // Kick off the new query switch (mMode) { case MODE_GROUP: mQueryHandler.startQuery(QUERY_TOKEN, null, mGroupUri, CONTACTS_PROJECTION, null, null, getSortOrder(CONTACTS_PROJECTION)); break; case MODE_ALL_CONTACTS: case MODE_PICK_CONTACT: case MODE_PICK_OR_CREATE_CONTACT: case MODE_INSERT_OR_EDIT_CONTACT: mQueryHandler.startQuery(QUERY_TOKEN, null, People.CONTENT_URI, CONTACTS_PROJECTION, null, null, getSortOrder(CONTACTS_PROJECTION)); break; case MODE_WITH_PHONES: mQueryHandler.startQuery(QUERY_TOKEN, null, People.CONTENT_URI, CONTACTS_PROJECTION, People.PRIMARY_PHONE_ID + " IS NOT NULL", null, getSortOrder(CONTACTS_PROJECTION)); break; case MODE_QUERY: { mQuery = getIntent().getStringExtra(SearchManager.QUERY); mQueryHandler.startQuery(QUERY_TOKEN, null, getPeopleFilterUri(mQuery), CONTACTS_PROJECTION, null, null, getSortOrder(CONTACTS_PROJECTION)); break; } case MODE_QUERY_PICK_TO_VIEW: { if (mQueryMode == QUERY_MODE_MAILTO) { // Find all contacts with the given search string as either // an E-mail or IM address. mQueryPersonIdIndex = SIMPLE_CONTACTS_PERSON_ID_INDEX; Uri uri = Uri.withAppendedPath(People.WITH_EMAIL_OR_IM_FILTER_URI, Uri.encode(mQueryData)); mQueryHandler.startQuery(QUERY_TOKEN, null, uri, SIMPLE_CONTACTS_PROJECTION, null, null, getSortOrder(CONTACTS_PROJECTION)); } else if (mQueryMode == QUERY_MODE_TEL) { mQueryPersonIdIndex = PHONES_PERSON_ID_INDEX; mQueryHandler.startQuery(QUERY_TOKEN, null, Uri.withAppendedPath(Phones.CONTENT_FILTER_URL, mQueryData), PHONES_PROJECTION, null, null, getSortOrder(PHONES_PROJECTION)); } break; } case MODE_STARRED: mQueryHandler.startQuery(QUERY_TOKEN, null, People.CONTENT_URI, CONTACTS_PROJECTION, People.STARRED + "=1", null, getSortOrder(CONTACTS_PROJECTION)); break; case MODE_FREQUENT: mQueryHandler.startQuery(QUERY_TOKEN, null, People.CONTENT_URI, CONTACTS_PROJECTION, People.TIMES_CONTACTED + " > 0", null, People.TIMES_CONTACTED + " DESC, " + getSortOrder(CONTACTS_PROJECTION)); break; case MODE_STREQUENT: mQueryHandler.startQuery(QUERY_TOKEN, null, Uri.withAppendedPath(People.CONTENT_URI, "strequent"), STREQUENT_PROJECTION, null, null, null); break; case MODE_PICK_PHONE: mQueryHandler.startQuery(QUERY_TOKEN, null, Phones.CONTENT_URI, PHONES_PROJECTION, null, null, getSortOrder(PHONES_PROJECTION)); break; case MODE_PICK_POSTAL: mQueryHandler.startQuery(QUERY_TOKEN, null, ContactMethods.CONTENT_URI, CONTACT_METHODS_PROJECTION, ContactMethods.KIND + "=" + Contacts.KIND_POSTAL, null, getSortOrder(CONTACT_METHODS_PROJECTION)); break; } } /** * Called from a background thread to do the filter and return the resulting cursor. * * @param filter the text that was entered to filter on * @return a cursor with the results of the filter */ Cursor doFilter(String filter) { final ContentResolver resolver = getContentResolver(); switch (mMode) { case MODE_GROUP: { Uri uri; if (TextUtils.isEmpty(filter)) { uri = mGroupUri; } else { uri = Uri.withAppendedPath(mGroupFilterUri, Uri.encode(filter)); } return resolver.query(uri, CONTACTS_PROJECTION, null, null, getSortOrder(CONTACTS_PROJECTION)); } case MODE_ALL_CONTACTS: case MODE_PICK_CONTACT: case MODE_PICK_OR_CREATE_CONTACT: case MODE_INSERT_OR_EDIT_CONTACT: { return resolver.query(getPeopleFilterUri(filter), CONTACTS_PROJECTION, null, null, getSortOrder(CONTACTS_PROJECTION)); } case MODE_WITH_PHONES: { return resolver.query(getPeopleFilterUri(filter), CONTACTS_PROJECTION, People.PRIMARY_PHONE_ID + " IS NOT NULL", null, getSortOrder(CONTACTS_PROJECTION)); } case MODE_STARRED: { return resolver.query(getPeopleFilterUri(filter), CONTACTS_PROJECTION, People.STARRED + "=1", null, getSortOrder(CONTACTS_PROJECTION)); } case MODE_FREQUENT: { return resolver.query(getPeopleFilterUri(filter), CONTACTS_PROJECTION, People.TIMES_CONTACTED + " > 0", null, People.TIMES_CONTACTED + " DESC, " + getSortOrder(CONTACTS_PROJECTION)); } case MODE_STREQUENT: { Uri uri; if (!TextUtils.isEmpty(filter)) { uri = Uri.withAppendedPath(People.CONTENT_URI, "strequent/filter/" + Uri.encode(filter)); } else { uri = Uri.withAppendedPath(People.CONTENT_URI, "strequent"); } return resolver.query(uri, STREQUENT_PROJECTION, null, null, null); } case MODE_PICK_PHONE: { Uri uri; if (!TextUtils.isEmpty(filter)) { uri = Uri.withAppendedPath(Phones.CONTENT_URI, "filter_name/" + Uri.encode(filter)); } else { uri = Phones.CONTENT_URI; } return resolver.query(uri, PHONES_PROJECTION, null, null, getSortOrder(PHONES_PROJECTION)); } } throw new UnsupportedOperationException("filtering not allowed in mode " + mMode); } /** * Calls the currently selected list item. * @return true if the call was initiated, false otherwise */ boolean callSelection() { ListView list = getListView(); if (list.hasFocus()) { Cursor cursor = (Cursor) list.getSelectedItem(); if (cursor != null) { long phoneId = cursor.getLong(PRIMARY_PHONE_ID_COLUMN_INDEX); if (phoneId == 0) { // There is no phone number. signalError(); return false; } Uri uri = ContentUris.withAppendedId(Phones.CONTENT_URI, phoneId); Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, uri); startActivity(intent); return true; } } return false; } /** * Signal an error to the user. */ void signalError() { //TODO play an error beep or something... } Cursor getItemForView(View view) { ListView listView = getListView(); int index = listView.getPositionForView(view); if (index < 0) { return null; } return (Cursor) listView.getAdapter().getItem(index); } private void setGroupEntries(AlertDialog.Builder builder) { boolean syncEverything; // For now we only support a single account and the UI doesn't know what // the account name is, so we're using a global setting for SYNC_EVERYTHING. // Some day when we add multiple accounts to the UI this should use the per // account setting. String value = Contacts.Settings.getSetting(getContentResolver(), null, Contacts.Settings.SYNC_EVERYTHING); if (value == null) { // If nothing is set yet we default to syncing everything syncEverything = true; } else { syncEverything = !TextUtils.isEmpty(value) && !"0".equals(value); } Cursor cursor; if (!syncEverything) { cursor = getContentResolver().query(Groups.CONTENT_URI, GROUPS_PROJECTION, Groups.SHOULD_SYNC + " != 0", null, Groups.DEFAULT_SORT_ORDER); } else { cursor = getContentResolver().query(Groups.CONTENT_URI, GROUPS_PROJECTION, null, null, Groups.DEFAULT_SORT_ORDER); } try { ArrayList<CharSequence> groups = new ArrayList<CharSequence>(); ArrayList<CharSequence> prefStrings = new ArrayList<CharSequence>(); // Add All Contacts groups.add(DISPLAY_GROUP_INDEX_ALL_CONTACTS, getString(R.string.showAllGroups)); prefStrings.add(""); // Add Contacts with phones groups.add(DISPLAY_GROUP_INDEX_ALL_CONTACTS_WITH_PHONES, getString(R.string.groupNameWithPhones)); prefStrings.add(GROUP_WITH_PHONES); int currentIndex = DISPLAY_GROUP_INDEX_ALL_CONTACTS; while (cursor.moveToNext()) { String systemId = cursor.getString(GROUPS_COLUMN_INDEX_SYSTEM_ID); String name = cursor.getString(GROUPS_COLUMN_INDEX_NAME); if (cursor.isNull(GROUPS_COLUMN_INDEX_SYSTEM_ID) && !Groups.GROUP_MY_CONTACTS.equals(systemId)) { // All groups that aren't My Contacts, since that one is localized on the phone // Localize the "Starred in Android" string which we get from the server side. if (Groups.GROUP_ANDROID_STARRED.equals(name)) { name = getString(R.string.starredInAndroid); } groups.add(name); if (name.equals(mDisplayInfo)) { currentIndex = groups.size() - 1; } } else { // The My Contacts group groups.add(DISPLAY_GROUP_INDEX_MY_CONTACTS, getString(R.string.groupNameMyContacts)); if (mDisplayType == DISPLAY_TYPE_SYSTEM_GROUP && Groups.GROUP_MY_CONTACTS.equals(mDisplayInfo)) { currentIndex = DISPLAY_GROUP_INDEX_MY_CONTACTS; } mDisplayGroupsIncludesMyContacts = true; } } if (mMode == MODE_ALL_CONTACTS) { currentIndex = DISPLAY_GROUP_INDEX_ALL_CONTACTS; } else if (mMode == MODE_WITH_PHONES) { currentIndex = DISPLAY_GROUP_INDEX_ALL_CONTACTS_WITH_PHONES; } mDisplayGroups = groups.toArray(new CharSequence[groups.size()]); builder.setSingleChoiceItems(mDisplayGroups, currentIndex, this); mDisplayGroupOriginalSelection = currentIndex; } finally { cursor.close(); } } private static final class QueryHandler extends AsyncQueryHandler { private final WeakReference<ContactsListActivity> mActivity; public QueryHandler(Context context) { super(context.getContentResolver()); mActivity = new WeakReference<ContactsListActivity>((ContactsListActivity) context); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { final ContactsListActivity activity = mActivity.get(); if (activity != null && !activity.isFinishing()) { activity.mAdapter.setLoading(false); activity.getListView().clearTextFilter(); activity.mAdapter.changeCursor(cursor); // Now that the cursor is populated again, it's possible to restore the list state if (activity.mListState != null) { activity.mList.onRestoreInstanceState(activity.mListState); if (activity.mListHasFocus) { activity.mList.requestFocus(); } activity.mListHasFocus = false; activity.mListState = null; } } else { cursor.close(); } } } final static class ContactListItemCache { public TextView nameView; public CharArrayBuffer nameBuffer = new CharArrayBuffer(128); public TextView labelView; public CharArrayBuffer labelBuffer = new CharArrayBuffer(128); public TextView numberView; public CharArrayBuffer numberBuffer = new CharArrayBuffer(128); public ImageView presenceView; public ImageView photoView; } private final class ContactItemListAdapter extends ResourceCursorAdapter implements SectionIndexer { private SectionIndexer mIndexer; private String mAlphabet; private boolean mLoading = true; private CharSequence mUnknownNameText; private CharSequence[] mLocalizedLabels; private boolean mDisplayPhotos = false; private SparseArray<SoftReference<Bitmap>> mBitmapCache = null; private int mFrequentSeparatorPos = ListView.INVALID_POSITION; public ContactItemListAdapter(Context context) { super(context, R.layout.contacts_list_item, null, false); mAlphabet = context.getString(com.android.internal.R.string.fast_scroll_alphabet); mUnknownNameText = context.getText(android.R.string.unknownName); switch (mMode) { case MODE_PICK_POSTAL: mLocalizedLabels = EditContactActivity.getLabelsForKind(mContext, Contacts.KIND_POSTAL); break; default: mLocalizedLabels = EditContactActivity.getLabelsForKind(mContext, Contacts.KIND_PHONE); break; } if ((mMode & MODE_MASK_SHOW_PHOTOS) == MODE_MASK_SHOW_PHOTOS) { mDisplayPhotos = true; setViewResource(R.layout.contacts_list_item_photo); mBitmapCache = new SparseArray<SoftReference<Bitmap>>(); } } private SectionIndexer getNewIndexer(Cursor cursor) { if (Locale.getDefault().getLanguage().equals(Locale.JAPAN.getLanguage())) { return new JapaneseContactListIndexer(cursor, SORT_STRING_INDEX); } else { return new AlphabetIndexer(cursor, NAME_COLUMN_INDEX, mAlphabet); } } /** * Callback on the UI thread when the content observer on the backing cursor fires. * Instead of calling requery we need to do an async query so that the requery doesn't * block the UI thread for a long time. */ @Override protected void onContentChanged() { CharSequence constraint = getListView().getTextFilter(); if (!TextUtils.isEmpty(constraint)) { // Reset the filter state then start an async filter operation Filter filter = getFilter(); filter.filter(constraint); } else { // Start an async query startQuery(); } } public void setLoading(boolean loading) { mLoading = loading; } @Override public boolean isEmpty() { if ((mMode & MODE_MASK_CREATE_NEW) == MODE_MASK_CREATE_NEW) { // This mode mask adds a header and we always want it to show up, even // if the list is empty, so always claim the list is not empty. return false; } else { if (mLoading) { // We don't want the empty state to show when loading. return false; } else { return super.isEmpty(); } } } @Override public int getItemViewType(int position) { if (position == mFrequentSeparatorPos) { // We don't want the separator view to be recycled. return IGNORE_ITEM_VIEW_TYPE; } return super.getItemViewType(position); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (!mDataValid) { throw new IllegalStateException( "this should only be called when the cursor is valid"); } // Handle the separator specially if (position == mFrequentSeparatorPos) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); TextView view = (TextView) inflater.inflate(R.layout.list_separator, parent, false); view.setText(R.string.favoritesFrquentSeparator); return view; } if (!mCursor.moveToPosition(getRealPosition(position))) { throw new IllegalStateException("couldn't move cursor to position " + position); } View v; if (convertView == null) { v = newView(mContext, mCursor, parent); } else { v = convertView; } bindView(v, mContext, mCursor); return v; } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { final View view = super.newView(context, cursor, parent); final ContactListItemCache cache = new ContactListItemCache(); cache.nameView = (TextView) view.findViewById(R.id.name); cache.labelView = (TextView) view.findViewById(R.id.label); cache.numberView = (TextView) view.findViewById(R.id.number); cache.presenceView = (ImageView) view.findViewById(R.id.presence); cache.photoView = (ImageView) view.findViewById(R.id.photo); view.setTag(cache); return view; } @Override public void bindView(View view, Context context, Cursor cursor) { final ContactListItemCache cache = (ContactListItemCache) view.getTag(); // Set the name cursor.copyStringToBuffer(NAME_COLUMN_INDEX, cache.nameBuffer); int size = cache.nameBuffer.sizeCopied; if (size != 0) { cache.nameView.setText(cache.nameBuffer.data, 0, size); } else { cache.nameView.setText(mUnknownNameText); } // Bail out early if using a specific SEARCH query mode, usually for // matching a specific E-mail or phone number. Any contact details // shown would be identical, and columns might not even be present // in the returned cursor. if (mQueryMode != QUERY_MODE_NONE) { cache.numberView.setVisibility(View.GONE); cache.labelView.setVisibility(View.GONE); cache.presenceView.setVisibility(View.GONE); return; } // Set the phone number TextView numberView = cache.numberView; TextView labelView = cache.labelView; cursor.copyStringToBuffer(NUMBER_COLUMN_INDEX, cache.numberBuffer); size = cache.numberBuffer.sizeCopied; if (size != 0) { numberView.setText(cache.numberBuffer.data, 0, size); numberView.setVisibility(View.VISIBLE); labelView.setVisibility(View.VISIBLE); } else { numberView.setVisibility(View.GONE); labelView.setVisibility(View.GONE); } // Set the label if (!cursor.isNull(TYPE_COLUMN_INDEX)) { int type = cursor.getInt(TYPE_COLUMN_INDEX); if (type != People.Phones.TYPE_CUSTOM) { try { labelView.setText(mLocalizedLabels[type - 1]); } catch (ArrayIndexOutOfBoundsException e) { labelView.setText(mLocalizedLabels[People.Phones.TYPE_HOME - 1]); } } else { cursor.copyStringToBuffer(LABEL_COLUMN_INDEX, cache.labelBuffer); // Don't check size, if it's zero just don't show anything labelView.setText(cache.labelBuffer.data, 0, cache.labelBuffer.sizeCopied); } } else { // There is no label, hide the the view labelView.setVisibility(View.GONE); } // Set the proper icon (star or presence or nothing) ImageView presenceView = cache.presenceView; if ((mMode & MODE_MASK_NO_PRESENCE) == 0) { int serverStatus; if (!cursor.isNull(SERVER_STATUS_COLUMN_INDEX)) { serverStatus = cursor.getInt(SERVER_STATUS_COLUMN_INDEX); presenceView.setImageResource( Presence.getPresenceIconResourceId(serverStatus)); presenceView.setVisibility(View.VISIBLE); } else { presenceView.setVisibility(View.GONE); } } else { presenceView.setVisibility(View.GONE); } // Set the photo, if requested if (mDisplayPhotos) { Bitmap photo = null; // Look for the cached bitmap int pos = cursor.getPosition(); SoftReference<Bitmap> ref = mBitmapCache.get(pos); if (ref != null) { photo = ref.get(); } if (photo == null) { // Bitmap cache miss, decode it from the cursor if (!cursor.isNull(PHOTO_COLUMN_INDEX)) { try { byte[] photoData = cursor.getBlob(PHOTO_COLUMN_INDEX); photo = BitmapFactory.decodeByteArray(photoData, 0, photoData.length); mBitmapCache.put(pos, new SoftReference<Bitmap>(photo)); } catch (OutOfMemoryError e) { // Not enough memory for the photo, use the default one instead photo = null; } } } // Bind the photo, or use the fallback no photo resource if (photo != null) { cache.photoView.setImageBitmap(photo); } else { cache.photoView.setImageResource(R.drawable.ic_contact_list_picture); } } } @Override public void changeCursor(Cursor cursor) { // Get the split between starred and frequent items, if the mode is strequent mFrequentSeparatorPos = ListView.INVALID_POSITION; if (cursor != null && cursor.getCount() > 0 && mMode == MODE_STREQUENT) { cursor.move(-1); for (int i = 0; cursor.moveToNext(); i++) { int starred = cursor.getInt(STARRED_COLUMN_INDEX); if (starred == 0) { if (i > 0) { // Only add the separator when there are starred items present mFrequentSeparatorPos = i; } break; } } } super.changeCursor(cursor); // Update the indexer for the fast scroll widget updateIndexer(cursor); // Clear the photo bitmap cache, if there is one if (mBitmapCache != null) { mBitmapCache.clear(); } } private void updateIndexer(Cursor cursor) { if (mIndexer == null) { mIndexer = getNewIndexer(cursor); } else { if (Locale.getDefault().equals(Locale.JAPAN)) { if (mIndexer instanceof JapaneseContactListIndexer) { ((JapaneseContactListIndexer)mIndexer).setCursor(cursor); } else { mIndexer = getNewIndexer(cursor); } } else { if (mIndexer instanceof AlphabetIndexer) { ((AlphabetIndexer)mIndexer).setCursor(cursor); } else { mIndexer = getNewIndexer(cursor); } } } } /** * Run the query on a helper thread. Beware that this code does not run * on the main UI thread! */ @Override public Cursor runQueryOnBackgroundThread(CharSequence constraint) { return doFilter(constraint.toString()); } public Object [] getSections() { if (mMode == MODE_STREQUENT) { return new String[] { " " }; } else { return mIndexer.getSections(); } } public int getPositionForSection(int sectionIndex) { if (mMode == MODE_STREQUENT) { return 0; } if (mIndexer == null) { Cursor cursor = mAdapter.getCursor(); if (cursor == null) { // No cursor, the section doesn't exist so just return 0 return 0; } mIndexer = getNewIndexer(cursor); } return mIndexer.getPositionForSection(sectionIndex); } public int getSectionForPosition(int position) { // Note: JapaneseContactListIndexer depends on the fact // this method always returns 0. If you change this, // please care it too. return 0; } @Override public boolean areAllItemsEnabled() { return mMode != MODE_STREQUENT; } @Override public boolean isEnabled(int position) { return position != mFrequentSeparatorPos; } @Override public int getCount() { if (mFrequentSeparatorPos != ListView.INVALID_POSITION) { return super.getCount() + 1; } else { return super.getCount(); } } private int getRealPosition(int pos) { if (mFrequentSeparatorPos == ListView.INVALID_POSITION) { // No separator, identity map return pos; } else if (pos <= mFrequentSeparatorPos) { // Before or at the separator, identity map return pos; } else { // After the separator, remove 1 from the pos to get the real underlying pos return pos - 1; } } @Override public Object getItem(int pos) { return super.getItem(getRealPosition(pos)); } @Override public long getItemId(int pos) { return super.getItemId(getRealPosition(pos)); } } }
true
true
protected void onCreate(Bundle icicle) { super.onCreate(icicle); // Resolve the intent final Intent intent = getIntent(); // Allow the title to be set to a custom String using an extra on the intent String title = intent.getStringExtra(Contacts.Intents.UI.TITLE_EXTRA_KEY); if (title != null) { setTitle(title); } final String action = intent.getAction(); mMode = MODE_UNKNOWN; setContentView(R.layout.contacts_list_content); if (UI.LIST_DEFAULT.equals(action)) { mDefaultMode = true; // When mDefaultMode is true the mode is set in onResume(), since the preferneces // activity may change it whenever this activity isn't running } else if (UI.LIST_GROUP_ACTION.equals(action)) { mMode = MODE_GROUP; String groupName = intent.getStringExtra(UI.GROUP_NAME_EXTRA_KEY); if (TextUtils.isEmpty(groupName)) { finish(); return; } buildUserGroupUris(groupName); } else if (UI.LIST_ALL_CONTACTS_ACTION.equals(action)) { mMode = MODE_ALL_CONTACTS; } else if (UI.LIST_STARRED_ACTION.equals(action)) { mMode = MODE_STARRED; } else if (UI.LIST_FREQUENT_ACTION.equals(action)) { mMode = MODE_FREQUENT; } else if (UI.LIST_STREQUENT_ACTION.equals(action)) { mMode = MODE_STREQUENT; } else if (UI.LIST_CONTACTS_WITH_PHONES_ACTION.equals(action)) { mMode = MODE_WITH_PHONES; } else if (Intent.ACTION_PICK.equals(action)) { // XXX These should be showing the data from the URI given in // the Intent. final String type = intent.resolveType(this); if (People.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_CONTACT; } else if (Phones.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (ContactMethods.CONTENT_POSTAL_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } } else if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) { if (intent.getComponent().getClassName().equals("alias.DialShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_CALL; setTitle(R.string.callShortcutActivityTitle); } else if (intent.getComponent().getClassName().equals("alias.MessageShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_SENDTO; setTitle(R.string.messageShortcutActivityTitle); } else { mMode = MODE_PICK_OR_CREATE_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } } else if (Intent.ACTION_GET_CONTENT.equals(action)) { final String type = intent.resolveType(this); if (People.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_OR_CREATE_CONTACT; } else if (Phones.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (ContactMethods.CONTENT_POSTAL_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } } else if (Intent.ACTION_INSERT_OR_EDIT.equals(action)) { mMode = MODE_INSERT_OR_EDIT_CONTACT; } else if (Intent.ACTION_SEARCH.equals(action)) { // See if the suggestion was clicked with a search action key (call button) if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG))) { String query = intent.getStringExtra(SearchManager.QUERY); if (!TextUtils.isEmpty(query)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", query, null)); startActivity(newIntent); } finish(); return; } // See if search request has extras to specify query if (intent.hasExtra(Insert.EMAIL)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_MAILTO; mQueryData = intent.getStringExtra(Insert.EMAIL); } else if (intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_TEL; mQueryData = intent.getStringExtra(Insert.PHONE); } else { // Otherwise handle the more normal search case mMode = MODE_QUERY; } // Since this is the filter activity it receives all intents // dispatched from the SearchManager for security reasons // so we need to re-dispatch from here to the intended target. } else if (Intents.SEARCH_SUGGESTION_CLICKED.equals(action)) { // See if the suggestion was clicked with a search action key (call button) Intent newIntent; if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG))) { newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData()); } else { newIntent = new Intent(Intent.ACTION_VIEW, intent.getData()); } startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED.equals(action)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData()); startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED.equals(action)) { String number = intent.getData().getSchemeSpecificPart(); Intent newIntent = new Intent(Intent.ACTION_INSERT, People.CONTENT_URI); newIntent.putExtra(Intents.Insert.PHONE, number); startActivity(newIntent); finish(); return; } if (mMode == MODE_UNKNOWN) { mMode = DEFAULT_MODE; } // Setup the UI final ListView list = getListView(); list.setFocusable(true); list.setOnCreateContextMenuListener(this); if ((mMode & MODE_MASK_NO_FILTER) != MODE_MASK_NO_FILTER) { list.setTextFilterEnabled(true); list.setGestures(ListView.GESTURES_FILTER); } else { list.setGestures(ListView.GESTURES_NONE); } if ((mMode & MODE_MASK_CREATE_NEW) != 0) { // Add the header for creating a new contact final LayoutInflater inflater = getLayoutInflater(); View header = inflater.inflate(android.R.layout.simple_list_item_1, list, false); TextView text = (TextView) header.findViewById(android.R.id.text1); text.setText(R.string.pickerNewContactHeader); list.addHeaderView(header); } // Set the proper empty string setEmptyText(); mAdapter = new ContactItemListAdapter(this); setListAdapter(mAdapter); // We manually save/restore the listview state list.setSaveEnabled(false); mQueryHandler = new QueryHandler(this); mJustCreated = true; // Check to see if sync is enabled final ContentResolver resolver = getContentResolver(); IContentProvider provider = resolver.acquireProvider(Contacts.CONTENT_URI); if (provider == null) { // No contacts provider, bail. finish(); return; } try { ISyncAdapter sa = provider.getSyncAdapter(); mSyncEnabled = sa != null; } catch (RemoteException e) { mSyncEnabled = false; } finally { resolver.releaseProvider(provider); } }
protected void onCreate(Bundle icicle) { super.onCreate(icicle); // Resolve the intent final Intent intent = getIntent(); // Allow the title to be set to a custom String using an extra on the intent String title = intent.getStringExtra(Contacts.Intents.UI.TITLE_EXTRA_KEY); if (title != null) { setTitle(title); } final String action = intent.getAction(); mMode = MODE_UNKNOWN; setContentView(R.layout.contacts_list_content); if (UI.LIST_DEFAULT.equals(action)) { mDefaultMode = true; // When mDefaultMode is true the mode is set in onResume(), since the preferneces // activity may change it whenever this activity isn't running } else if (UI.LIST_GROUP_ACTION.equals(action)) { mMode = MODE_GROUP; String groupName = intent.getStringExtra(UI.GROUP_NAME_EXTRA_KEY); if (TextUtils.isEmpty(groupName)) { finish(); return; } buildUserGroupUris(groupName); } else if (UI.LIST_ALL_CONTACTS_ACTION.equals(action)) { mMode = MODE_ALL_CONTACTS; } else if (UI.LIST_STARRED_ACTION.equals(action)) { mMode = MODE_STARRED; } else if (UI.LIST_FREQUENT_ACTION.equals(action)) { mMode = MODE_FREQUENT; } else if (UI.LIST_STREQUENT_ACTION.equals(action)) { mMode = MODE_STREQUENT; } else if (UI.LIST_CONTACTS_WITH_PHONES_ACTION.equals(action)) { mMode = MODE_WITH_PHONES; } else if (Intent.ACTION_PICK.equals(action)) { // XXX These should be showing the data from the URI given in // the Intent. final String type = intent.resolveType(this); if (People.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_CONTACT; } else if (Phones.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (ContactMethods.CONTENT_POSTAL_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } } else if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) { if (intent.getComponent().getClassName().equals("alias.DialShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_CALL; setTitle(R.string.callShortcutActivityTitle); } else if (intent.getComponent().getClassName().equals("alias.MessageShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_SENDTO; setTitle(R.string.messageShortcutActivityTitle); } else { mMode = MODE_PICK_OR_CREATE_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } } else if (Intent.ACTION_GET_CONTENT.equals(action)) { final String type = intent.resolveType(this); if (People.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_OR_CREATE_CONTACT; } else if (Phones.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (ContactMethods.CONTENT_POSTAL_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } } else if (Intent.ACTION_INSERT_OR_EDIT.equals(action)) { mMode = MODE_INSERT_OR_EDIT_CONTACT; } else if (Intent.ACTION_SEARCH.equals(action)) { // See if the suggestion was clicked with a search action key (call button) if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG))) { String query = intent.getStringExtra(SearchManager.QUERY); if (!TextUtils.isEmpty(query)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", query, null)); startActivity(newIntent); } finish(); return; } // See if search request has extras to specify query if (intent.hasExtra(Insert.EMAIL)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_MAILTO; mQueryData = intent.getStringExtra(Insert.EMAIL); } else if (intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_TEL; mQueryData = intent.getStringExtra(Insert.PHONE); } else { // Otherwise handle the more normal search case mMode = MODE_QUERY; } // Since this is the filter activity it receives all intents // dispatched from the SearchManager for security reasons // so we need to re-dispatch from here to the intended target. } else if (Intents.SEARCH_SUGGESTION_CLICKED.equals(action)) { // See if the suggestion was clicked with a search action key (call button) Intent newIntent; if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG))) { newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData()); } else { newIntent = new Intent(Intent.ACTION_VIEW, intent.getData()); } startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED.equals(action)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData()); startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED.equals(action)) { String number = intent.getData().getSchemeSpecificPart(); Intent newIntent = new Intent(Intent.ACTION_INSERT, People.CONTENT_URI); newIntent.putExtra(Intents.Insert.PHONE, number); startActivity(newIntent); finish(); return; } if (mMode == MODE_UNKNOWN) { mMode = DEFAULT_MODE; } // Setup the UI final ListView list = getListView(); list.setFocusable(true); list.setOnCreateContextMenuListener(this); if ((mMode & MODE_MASK_NO_FILTER) != MODE_MASK_NO_FILTER) { list.setTextFilterEnabled(true); } if ((mMode & MODE_MASK_CREATE_NEW) != 0) { // Add the header for creating a new contact final LayoutInflater inflater = getLayoutInflater(); View header = inflater.inflate(android.R.layout.simple_list_item_1, list, false); TextView text = (TextView) header.findViewById(android.R.id.text1); text.setText(R.string.pickerNewContactHeader); list.addHeaderView(header); } // Set the proper empty string setEmptyText(); mAdapter = new ContactItemListAdapter(this); setListAdapter(mAdapter); // We manually save/restore the listview state list.setSaveEnabled(false); mQueryHandler = new QueryHandler(this); mJustCreated = true; // Check to see if sync is enabled final ContentResolver resolver = getContentResolver(); IContentProvider provider = resolver.acquireProvider(Contacts.CONTENT_URI); if (provider == null) { // No contacts provider, bail. finish(); return; } try { ISyncAdapter sa = provider.getSyncAdapter(); mSyncEnabled = sa != null; } catch (RemoteException e) { mSyncEnabled = false; } finally { resolver.releaseProvider(provider); } }
diff --git a/host/whiteboard-app/src/main/java/whiteboard/app/SelectPanel.java b/host/whiteboard-app/src/main/java/whiteboard/app/SelectPanel.java index 9e150ea..a2bda0e 100644 --- a/host/whiteboard-app/src/main/java/whiteboard/app/SelectPanel.java +++ b/host/whiteboard-app/src/main/java/whiteboard/app/SelectPanel.java @@ -1,170 +1,170 @@ package whiteboard.app; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.AffineTransform; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.UIManager; import net.miginfocom.swing.MigLayout; import whiteboard.SerialController; import whiteboard.WhiteboardPanel; import whiteboard.WhiteboardParser; import whiteboard.svgreader.SvgReader; public class SelectPanel extends JPanel { private final JFormattedTextField reelSpacingField = new JFormattedTextField(500.0); private final JFormattedTextField reelRadiusField = new JFormattedTextField(25.0); private final JFormattedTextField pulsesPerRotationField = new JFormattedTextField(282.0); private final JFormattedTextField pulleyRadiusField = new JFormattedTextField(0.0); private final JFormattedTextField startXField = new JFormattedTextField(250.0); private final JFormattedTextField startYField = new JFormattedTextField(220.0); private final JTextField portField = new JTextField("/dev/ttyUSB0"); private final JTextField filenameField = new JTextField(); private final JButton chooseFileButton = new JButton(new AbstractAction("Choose file") { @Override public void actionPerformed(ActionEvent ev) { JFileChooser chooser = new JFileChooser(); int ret = chooser.showOpenDialog(SelectPanel.this); if (ret == JFileChooser.APPROVE_OPTION) filenameField.setText(chooser.getSelectedFile().getPath()); } }); private final JButton previewButton = new JButton(new AbstractAction("Preview") { @Override public void actionPerformed(ActionEvent ev) { try { String uri = new File(filenameField.getText()).toURI().toASCIIString(); PreviewPanel preview = new PreviewPanel(new SvgReader(uri)); JDialog d = new JDialog(SwingUtilities.getWindowAncestor(SelectPanel.this)); d.setContentPane(preview); d.pack(); d.setVisible(true); } catch (IOException e) { e.printStackTrace(); // todo: show a dialog } } }); private final JButton simulateButton = new JButton(new AbstractAction("Simulate") { @Override public void actionPerformed(ActionEvent ev) { try { byte[] data = createOutput(); WhiteboardPanel p = new WhiteboardPanel( (Double) reelRadiusField.getValue(), (Double) reelSpacingField.getValue(), 1024 ); JDialog d = new JDialog(SwingUtilities.getWindowAncestor(SelectPanel.this)); d.setContentPane(p); d.setSize(600, 600); d.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); d.setVisible(true); new WhiteboardParser(p, data).start(); } catch (IOException e) { e.printStackTrace(); // todo: show a dialog } } }); private final JButton runButton = new JButton(new AbstractAction("Go!") { @Override public void actionPerformed(ActionEvent ev) { try { final byte[] data = createOutput(); SerialController controller = new SerialController(portField.getText()); final RunPanel p = new RunPanel(controller); JDialog d = new JDialog(SwingUtilities.getWindowAncestor(SelectPanel.this)); d.setContentPane(p); d.pack(); d.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); d.setVisible(true); p.getStartButton().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { new WhiteboardParser(p, data).start(); } }); } catch (IOException e) { e.printStackTrace(); // todo: show a dialog } } }); public SelectPanel() { super(new MigLayout("", "[right]rel[300lp,grow,fill]")); add(new JLabel("Filename")); add(filenameField, "grow, span"); add(chooseFileButton, "skip 1, wrap, grow 0"); add(new JLabel("Reel radius")); add(reelRadiusField, "wrap"); - add(new JLabel("Radians per pulse")); + add(new JLabel("Pulses per rotation")); add(pulsesPerRotationField, "wrap"); add(new JLabel("Pulley radius")); add(pulleyRadiusField, "wrap"); add(new JLabel("Reel spacing")); add(reelSpacingField, "wrap"); add(new JLabel("Start position left")); add(startXField, "wrap"); add(new JLabel("Start position down")); add(startYField, "wrap"); add(new JLabel("Port")); add(portField, "wrap"); add(previewButton, "span, split 2"); add(runButton, "wrap"); } private byte[] createOutput() throws IOException { Converter c = new Converter(); c.setReelRadius((Double) reelRadiusField.getValue()); c.setReelSpacing((Double) reelSpacingField.getValue()); c.setPulsesPerRotation((Double) pulsesPerRotationField.getValue()); c.setStartX((Double) startXField.getValue()); c.setStartY((Double) startYField.getValue()); String uri = new File(filenameField.getText()).toURI().toASCIIString(); SvgReader reader = new SvgReader(uri); double scale = c.getReelSpacing() / reader.getSize().getWidth(); AffineTransform t = AffineTransform.getScaleInstance(scale, scale); ByteArrayOutputStream out = new ByteArrayOutputStream(); c.convert(reader.getPathIterator(t), out); return out.toByteArray(); } public static void main(String[] args) { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) {} JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.setContentPane(new SelectPanel()); f.pack(); f.setVisible(true); } }
true
true
public SelectPanel() { super(new MigLayout("", "[right]rel[300lp,grow,fill]")); add(new JLabel("Filename")); add(filenameField, "grow, span"); add(chooseFileButton, "skip 1, wrap, grow 0"); add(new JLabel("Reel radius")); add(reelRadiusField, "wrap"); add(new JLabel("Radians per pulse")); add(pulsesPerRotationField, "wrap"); add(new JLabel("Pulley radius")); add(pulleyRadiusField, "wrap"); add(new JLabel("Reel spacing")); add(reelSpacingField, "wrap"); add(new JLabel("Start position left")); add(startXField, "wrap"); add(new JLabel("Start position down")); add(startYField, "wrap"); add(new JLabel("Port")); add(portField, "wrap"); add(previewButton, "span, split 2"); add(runButton, "wrap"); }
public SelectPanel() { super(new MigLayout("", "[right]rel[300lp,grow,fill]")); add(new JLabel("Filename")); add(filenameField, "grow, span"); add(chooseFileButton, "skip 1, wrap, grow 0"); add(new JLabel("Reel radius")); add(reelRadiusField, "wrap"); add(new JLabel("Pulses per rotation")); add(pulsesPerRotationField, "wrap"); add(new JLabel("Pulley radius")); add(pulleyRadiusField, "wrap"); add(new JLabel("Reel spacing")); add(reelSpacingField, "wrap"); add(new JLabel("Start position left")); add(startXField, "wrap"); add(new JLabel("Start position down")); add(startYField, "wrap"); add(new JLabel("Port")); add(portField, "wrap"); add(previewButton, "span, split 2"); add(runButton, "wrap"); }
diff --git a/src/uk/me/parabola/imgfmt/sys/ImgHeader.java b/src/uk/me/parabola/imgfmt/sys/ImgHeader.java index 11d59d9d..de798351 100644 --- a/src/uk/me/parabola/imgfmt/sys/ImgHeader.java +++ b/src/uk/me/parabola/imgfmt/sys/ImgHeader.java @@ -1,313 +1,313 @@ /* * Copyright (C) 2006 Steve Ratcliffe * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * Author: Steve Ratcliffe * Create date: 26-Nov-2006 */ package uk.me.parabola.imgfmt.sys; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Calendar; import java.util.Date; import uk.me.parabola.imgfmt.FileSystemParam; import uk.me.parabola.imgfmt.Utils; import uk.me.parabola.imgfmt.fs.ImgChannel; import uk.me.parabola.log.Logger; /** * The header at the very beginning of the .img filesystem. It has the * same signature as a DOS partition table, although I don't know * exactly how much the partition concepts are used. * * @author Steve Ratcliffe */ class ImgHeader { private static final Logger log = Logger.getLogger(ImgHeader.class); // Offsets into the header. private static final int OFF_XOR = 0x0; private static final int OFF_UPDATE_MONTH = 0xa; private static final int OFF_UPDATE_YEAR = 0xb; // +1900 for val >= 0x63, +2000 for less private static final int OFF_CHECKSUM = 0xf; private static final int OFF_SIGNATURE = 0x10; private static final int OFF_UNK_1 = 0x17; // If this was a real boot sector these would be the meanings private static final int OFF_SECTORS = 0x18; private static final int OFF_HEADS = 0x1a; private static final int OFF_CYLINDERS = 0x1c; private static final int OFF_CREATION_YEAR = 0x39; // private static final int OFF_CREATION_MONTH = 0x3b; // private static final int OFF_CREATION_DAY = 0x3c; // private static final int OFF_CREATION_HOUR = 0x3d; // private static final int OFF_CREATION_MINUTE = 0x3e; // private static final int OFF_CREATION_SECOND = 0x3f; // The block number where the directory starts. private static final int OFF_DIRECTORY_START_BLOCK = 0x40; private static final int OFF_MAP_FILE_INTENTIFIER = 0x41; private static final int OFF_MAP_DESCRIPTION = 0x49; // 0x20 padded private static final int OFF_HEADS2 = 0x5d; private static final int OFF_SECTORS2 = 0x5f; private static final int OFF_BLOCK_SIZE_EXPONENT1 = 0x61; private static final int OFF_BLOCK_SIZE_EXPONENT2 = 0x62; private static final int OFF_BLOCK_SIZE = 0x63; // private static final int OFF_UKN_3 = 0x63; private static final int OFF_MAP_NAME_CONT = 0x65; // 'Partition table' offsets. private static final int OFF_START_HEAD = 0x1bf; private static final int OFF_START_SECTOR = 0x1c0; private static final int OFF_START_CYLINDER = 0x1c1; private static final int OFF_SYSTEM_TYPE = 0x1c2; private static final int OFF_END_HEAD = 0x1c3; private static final int OFF_END_SECTOR = 0x1c4; private static final int OFF_END_CYLINDER = 0x1c5; private static final int OFF_REL_SECTORS = 0x1c6; private static final int OFF_NUMBER_OF_SECTORS = 0x1ca; private static final int OFF_PARTITION_SIG = 0x1fe; // Lengths of some of the fields private static final int LEN_MAP_NAME_CONT = 30; private static final int LEN_MAP_DESCRIPTION = 20; private FileSystemParam fsParams; private final ByteBuffer header = ByteBuffer.allocate(512); private ImgChannel file; private Date creationTime; // Signatures. private static final byte[] FILE_ID = { 'G', 'A', 'R', 'M', 'I', 'N', '\0'}; private static final byte[] SIGNATURE = { 'D', 'S', 'K', 'I', 'M', 'G', '\0'}; ImgHeader(ImgChannel chan) { this.file = chan; header.order(ByteOrder.LITTLE_ENDIAN); } /** * Create a header from scratch. * @param params File system parameters. */ void createHeader(FileSystemParam params) { this.fsParams = params; header.put(OFF_XOR, (byte) 0); // Set the block size. 2^(E1+E2) where E1 is always 9. int exp = 9; int bs = params.getBlockSize(); for (int i = 0; i < 32; i++) { bs >>>= 1; if (bs == 0) { exp = i; break; } } if (exp < 9) throw new IllegalArgumentException("block size too small"); header.put(OFF_BLOCK_SIZE_EXPONENT1, (byte) 0x9); header.put(OFF_BLOCK_SIZE_EXPONENT2, (byte) (exp - 9)); header.position(OFF_SIGNATURE); header.put(SIGNATURE); header.position(OFF_MAP_FILE_INTENTIFIER); header.put(FILE_ID); header.put(OFF_UNK_1, (byte) 0x2); // Actually this may not be the directory start block, I am guessing - // always assume it is 2 anyway. header.put(OFF_DIRECTORY_START_BLOCK, (byte) fsParams.getDirectoryStartBlock()); // This sectors, head, cylinders stuff appears to be used by mapsource // and they have to be larger than the actual size of the map. It // doesn't appear to have any effect on a garmin device or other software. int sectors = 0x20; // 0x20 appears to be a max header.putShort(OFF_SECTORS, (short) sectors); int heads = 0x20; // 0x20 appears to be max header.putShort(OFF_HEADS, (short) heads); - int cylinders = 0x100; // gives 128M will try more later + int cylinders = 0x400; // gives 512M header.putShort(OFF_CYLINDERS, (short) cylinders); header.putShort(OFF_HEADS2, (short) heads); header.putShort(OFF_SECTORS2, (short) sectors); header.position(OFF_CREATION_YEAR); Utils.setCreationTime(header, creationTime); // Since there are only 2 bytes here but it can easily overflow, if it // does we replace it with 0xffff, it doesn't work to set it to say zero int blocks = heads * sectors * cylinders / (1 << exp - 9); char shortBlocks = blocks > 0xffff ? 0xffff : (char) blocks; header.putChar(OFF_BLOCK_SIZE, shortBlocks); header.put(OFF_PARTITION_SIG, (byte) 0x55); header.put(OFF_PARTITION_SIG+1, (byte) 0xaa); header.put(OFF_START_HEAD, (byte) 0); header.put(OFF_START_SECTOR, (byte) 1); header.put(OFF_START_CYLINDER, (byte) 0); header.put(OFF_SYSTEM_TYPE, (byte) 0); header.put(OFF_END_HEAD, (byte) (heads - 1)); - header.put(OFF_END_SECTOR, (byte) sectors); + header.put(OFF_END_SECTOR, (byte) (sectors + (((cylinders-1) & 0x300) >> 2))); header.put(OFF_END_CYLINDER, (byte) (cylinders - 1)); header.putInt(OFF_REL_SECTORS, 0); header.putInt(OFF_NUMBER_OF_SECTORS, (blocks * (1 << (exp - 9)))); log.info("number of blocks " + blocks); setDirectoryStartBlock(params.getDirectoryStartBlock()); // Set the times. Date date = new Date(); setCreationTime(date); setUpdateTime(date); setDescription(params.getMapDescription()); // Checksum is not checked. int check = 0; header.put(OFF_CHECKSUM, (byte) check); } void setHeader(ByteBuffer buf) { buf.flip(); header.put(buf); byte exp1 = header.get(OFF_BLOCK_SIZE_EXPONENT1); byte exp2 = header.get(OFF_BLOCK_SIZE_EXPONENT2); log.debug("header exponent", exp1, exp2); fsParams = new FileSystemParam(); fsParams.setBlockSize(1 << (exp1 + exp2)); fsParams.setDirectoryStartBlock(header.get(OFF_DIRECTORY_START_BLOCK)); StringBuffer sb = new StringBuffer(); sb.append(Utils.bytesToString(buf, OFF_MAP_DESCRIPTION, LEN_MAP_DESCRIPTION)); sb.append(Utils.bytesToString(buf, OFF_MAP_NAME_CONT, LEN_MAP_NAME_CONT)); fsParams.setMapDescription(sb.toString().trim()); // ... more to do } void setFile(ImgChannel file) { this.file = file; } FileSystemParam getParams() { return fsParams; } /** * Sync the header to disk. * @throws IOException If an error occurs during writing. */ public void sync() throws IOException { setUpdateTime(new Date()); header.rewind(); file.position(0); file.write(header); file.position(fsParams.getDirectoryStartBlock() * 512L); } /** * Set the update time. * @param date The date to use. */ protected void setUpdateTime(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); header.put(OFF_UPDATE_YEAR, toYearCode(cal.get(Calendar.YEAR))); header.put(OFF_UPDATE_MONTH, (byte) (cal.get(Calendar.MONTH)+1)); } /** * Set the description. It is spread across two areas in the header. * @param desc The description. */ protected void setDescription(String desc) { int len = desc.length(); if (len > 50) throw new IllegalArgumentException("Description is too long (max 50)"); String part1, part2; if (len > LEN_MAP_DESCRIPTION) { part1 = desc.substring(0, LEN_MAP_DESCRIPTION); part2 = desc.substring(LEN_MAP_DESCRIPTION, len); } else { part1 = desc.substring(0, len); part2 = ""; } header.position(OFF_MAP_DESCRIPTION); header.put(toByte(part1)); for (int i = len; i < LEN_MAP_DESCRIPTION; i++) header.put((byte) ' '); header.position(OFF_MAP_NAME_CONT); header.put(toByte(part2)); for (int i = Math.max(len - LEN_MAP_DESCRIPTION, 0); i < LEN_MAP_NAME_CONT; i++) header.put((byte) ' '); header.put((byte) 0); // really? } /** * Convert a string to a byte array. * @param s The string * @return A byte array. */ private byte[] toByte(String s) { // NB: what character set should be used? return s.getBytes(); } /** * Convert to the one byte code that is used for the year. * If the year is in the 1900, then subtract 1900 and add the result to 0x63, * else subtract 2000. * Actually looks simpler, just subtract 1900.. * @param y The year in real-world format eg 2006. * @return A one byte code representing the year. */ private byte toYearCode(int y) { return (byte) (y - 1900); } protected void setDirectoryStartBlock(int directoryStartBlock) { header.put(OFF_DIRECTORY_START_BLOCK, (byte) directoryStartBlock); fsParams.setDirectoryStartBlock(directoryStartBlock); } protected void setCreationTime(Date date) { this.creationTime = date; } }
false
true
void createHeader(FileSystemParam params) { this.fsParams = params; header.put(OFF_XOR, (byte) 0); // Set the block size. 2^(E1+E2) where E1 is always 9. int exp = 9; int bs = params.getBlockSize(); for (int i = 0; i < 32; i++) { bs >>>= 1; if (bs == 0) { exp = i; break; } } if (exp < 9) throw new IllegalArgumentException("block size too small"); header.put(OFF_BLOCK_SIZE_EXPONENT1, (byte) 0x9); header.put(OFF_BLOCK_SIZE_EXPONENT2, (byte) (exp - 9)); header.position(OFF_SIGNATURE); header.put(SIGNATURE); header.position(OFF_MAP_FILE_INTENTIFIER); header.put(FILE_ID); header.put(OFF_UNK_1, (byte) 0x2); // Actually this may not be the directory start block, I am guessing - // always assume it is 2 anyway. header.put(OFF_DIRECTORY_START_BLOCK, (byte) fsParams.getDirectoryStartBlock()); // This sectors, head, cylinders stuff appears to be used by mapsource // and they have to be larger than the actual size of the map. It // doesn't appear to have any effect on a garmin device or other software. int sectors = 0x20; // 0x20 appears to be a max header.putShort(OFF_SECTORS, (short) sectors); int heads = 0x20; // 0x20 appears to be max header.putShort(OFF_HEADS, (short) heads); int cylinders = 0x100; // gives 128M will try more later header.putShort(OFF_CYLINDERS, (short) cylinders); header.putShort(OFF_HEADS2, (short) heads); header.putShort(OFF_SECTORS2, (short) sectors); header.position(OFF_CREATION_YEAR); Utils.setCreationTime(header, creationTime); // Since there are only 2 bytes here but it can easily overflow, if it // does we replace it with 0xffff, it doesn't work to set it to say zero int blocks = heads * sectors * cylinders / (1 << exp - 9); char shortBlocks = blocks > 0xffff ? 0xffff : (char) blocks; header.putChar(OFF_BLOCK_SIZE, shortBlocks); header.put(OFF_PARTITION_SIG, (byte) 0x55); header.put(OFF_PARTITION_SIG+1, (byte) 0xaa); header.put(OFF_START_HEAD, (byte) 0); header.put(OFF_START_SECTOR, (byte) 1); header.put(OFF_START_CYLINDER, (byte) 0); header.put(OFF_SYSTEM_TYPE, (byte) 0); header.put(OFF_END_HEAD, (byte) (heads - 1)); header.put(OFF_END_SECTOR, (byte) sectors); header.put(OFF_END_CYLINDER, (byte) (cylinders - 1)); header.putInt(OFF_REL_SECTORS, 0); header.putInt(OFF_NUMBER_OF_SECTORS, (blocks * (1 << (exp - 9)))); log.info("number of blocks " + blocks); setDirectoryStartBlock(params.getDirectoryStartBlock()); // Set the times. Date date = new Date(); setCreationTime(date); setUpdateTime(date); setDescription(params.getMapDescription()); // Checksum is not checked. int check = 0; header.put(OFF_CHECKSUM, (byte) check); }
void createHeader(FileSystemParam params) { this.fsParams = params; header.put(OFF_XOR, (byte) 0); // Set the block size. 2^(E1+E2) where E1 is always 9. int exp = 9; int bs = params.getBlockSize(); for (int i = 0; i < 32; i++) { bs >>>= 1; if (bs == 0) { exp = i; break; } } if (exp < 9) throw new IllegalArgumentException("block size too small"); header.put(OFF_BLOCK_SIZE_EXPONENT1, (byte) 0x9); header.put(OFF_BLOCK_SIZE_EXPONENT2, (byte) (exp - 9)); header.position(OFF_SIGNATURE); header.put(SIGNATURE); header.position(OFF_MAP_FILE_INTENTIFIER); header.put(FILE_ID); header.put(OFF_UNK_1, (byte) 0x2); // Actually this may not be the directory start block, I am guessing - // always assume it is 2 anyway. header.put(OFF_DIRECTORY_START_BLOCK, (byte) fsParams.getDirectoryStartBlock()); // This sectors, head, cylinders stuff appears to be used by mapsource // and they have to be larger than the actual size of the map. It // doesn't appear to have any effect on a garmin device or other software. int sectors = 0x20; // 0x20 appears to be a max header.putShort(OFF_SECTORS, (short) sectors); int heads = 0x20; // 0x20 appears to be max header.putShort(OFF_HEADS, (short) heads); int cylinders = 0x400; // gives 512M header.putShort(OFF_CYLINDERS, (short) cylinders); header.putShort(OFF_HEADS2, (short) heads); header.putShort(OFF_SECTORS2, (short) sectors); header.position(OFF_CREATION_YEAR); Utils.setCreationTime(header, creationTime); // Since there are only 2 bytes here but it can easily overflow, if it // does we replace it with 0xffff, it doesn't work to set it to say zero int blocks = heads * sectors * cylinders / (1 << exp - 9); char shortBlocks = blocks > 0xffff ? 0xffff : (char) blocks; header.putChar(OFF_BLOCK_SIZE, shortBlocks); header.put(OFF_PARTITION_SIG, (byte) 0x55); header.put(OFF_PARTITION_SIG+1, (byte) 0xaa); header.put(OFF_START_HEAD, (byte) 0); header.put(OFF_START_SECTOR, (byte) 1); header.put(OFF_START_CYLINDER, (byte) 0); header.put(OFF_SYSTEM_TYPE, (byte) 0); header.put(OFF_END_HEAD, (byte) (heads - 1)); header.put(OFF_END_SECTOR, (byte) (sectors + (((cylinders-1) & 0x300) >> 2))); header.put(OFF_END_CYLINDER, (byte) (cylinders - 1)); header.putInt(OFF_REL_SECTORS, 0); header.putInt(OFF_NUMBER_OF_SECTORS, (blocks * (1 << (exp - 9)))); log.info("number of blocks " + blocks); setDirectoryStartBlock(params.getDirectoryStartBlock()); // Set the times. Date date = new Date(); setCreationTime(date); setUpdateTime(date); setDescription(params.getMapDescription()); // Checksum is not checked. int check = 0; header.put(OFF_CHECKSUM, (byte) check); }
diff --git a/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/TemplateTag.java b/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/TemplateTag.java index f9388ef8..4a4e1def 100644 --- a/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/TemplateTag.java +++ b/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/TemplateTag.java @@ -1,354 +1,356 @@ /** * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999. * * This program is free software; you can redistribute it and/or modify * it under the terms of the latest version of the GNU Lesser General * Public License as published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program (LICENSE.txt); if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.jamwiki.parser.jflex; import java.util.HashMap; import java.util.Iterator; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.jamwiki.WikiBase; import org.jamwiki.model.Topic; import org.jamwiki.parser.ParserInput; import org.jamwiki.parser.ParserOutput; import org.jamwiki.utils.NamespaceHandler; import org.jamwiki.utils.Utilities; import org.jamwiki.utils.WikiLogger; import org.jamwiki.utils.WikiUtil; /** * <code>TemplateTag</code> parses Mediawiki template syntax, which allows * programmatic structures to be embedded in wiki syntax. */ public class TemplateTag { private static final WikiLogger logger = WikiLogger.getLogger(TemplateTag.class.getName()); protected static final String TEMPLATE_INCLUSION = "template-inclusion"; private static Pattern PARAM_NAME_VALUE_PATTERN = null; private final HashMap parameterValues = new HashMap(); static { try { PARAM_NAME_VALUE_PATTERN = Pattern.compile("[\\s]*([A-Za-z0-9_\\ \\-]+)[\\s]*\\=([\\s\\S]*)"); } catch (Exception e) { logger.severe("Unable to compile pattern", e); } } /** * Once the template call has been parsed and the template values have been * determined, parse the template body and apply those template values. * Parameters may be embedded or have default values, so there is some * voodoo magic that happens here to first parse any embedded values, and * to apply default values when no template value has been set. */ private String applyParameter(ParserInput parserInput, String param) throws Exception { if (this.parameterValues == null) { return param; } String content = param.substring("{{{".length(), param.length() - "}}}".length()); // re-parse in case of embedded templates or params content = this.parseTemplateBody(parserInput, content); String name = this.parseParamName(content); String defaultValue = this.parseParamDefaultValue(parserInput, content); String value = (String)this.parameterValues.get(name); if (value == null && defaultValue == null) { return param; } return (value == null) ? defaultValue : value; } /** * Parse a call to a Mediawiki template of the form "{{template|param1|param2}}" * and return the resulting template output. */ public String parse(ParserInput parserInput, ParserOutput parserOutput, int mode, String raw) { try { parserInput.incrementTemplateDepth(); // validate and extract the template content if (StringUtils.isBlank(raw)) { throw new Exception("Empty template text"); } if (!raw.startsWith("{{") || !raw.endsWith("}}")) { throw new Exception ("Invalid template text: " + raw); } String templateContent = raw.substring("{{".length(), raw.length() - "}}".length()); - // parse for nested templates + // parse for nested templates, signatures, etc. templateContent = JFlexParserUtil.parseFragment(parserInput, templateContent, mode); + // update the raw value to handle cases such as a signature in the template content + raw = "{{" + templateContent + "}}"; // check for magic word or parser function String[] parserFunctionInfo = ParserFunctionUtil.parseParserFunctionInfo(templateContent); if (MagicWordUtil.isMagicWord(templateContent) || parserFunctionInfo != null) { if (mode <= JFlexParser.MODE_MINIMAL) { parserInput.decrementTemplateDepth(); return raw; } parserInput.decrementTemplateDepth(); if (MagicWordUtil.isMagicWord(templateContent)) { return MagicWordUtil.processMagicWord(parserInput, templateContent); } else { return ParserFunctionUtil.processParserFunction(parserInput, parserFunctionInfo[0], parserFunctionInfo[1]); } } // extract the template name String name = this.parseTemplateName(templateContent); boolean inclusion = false; if (name.startsWith(NamespaceHandler.NAMESPACE_SEPARATOR)) { name = name.substring(1); inclusion = true; } // get the parsed template body Topic templateTopic = WikiBase.getDataHandler().lookupTopic(parserInput.getVirtualWiki(), name, false, null); this.processTemplateMetadata(parserInput, parserOutput, templateTopic, raw, name); if (mode <= JFlexParser.MODE_MINIMAL) { parserInput.decrementTemplateDepth(); return raw; } // make sure template was not redirected if (templateTopic != null && templateTopic.getTopicType() == Topic.TYPE_REDIRECT) { templateTopic = WikiUtil.findRedirectedTopic(templateTopic, 0); name = templateTopic.getName(); } if (templateTopic != null && templateTopic.getTopicType() == Topic.TYPE_REDIRECT) { // redirection target does not exist templateTopic = null; } if (inclusion) { String output = this.processTemplateInclusion(parserInput, parserOutput, mode, templateTopic, raw, name); parserInput.decrementTemplateDepth(); return output; } String output = this.processTemplateContent(parserInput, parserOutput, templateTopic, templateContent, name); parserInput.decrementTemplateDepth(); return output; } catch (Throwable t) { logger.info("Unable to parse " + raw, t); return raw; } } /** * Given template parameter content of the form "name" or "name|default", * return the default value if it exists. */ private String parseParamDefaultValue(ParserInput parserInput, String raw) throws Exception { Vector tokens = this.tokenizeParams(raw); if (tokens.size() < 2) { return null; } // table elements mess up default processing, so just return anything after // the first parameter to avoid having to implement special table logic String param1 = (String)tokens.elementAt(0); String value = raw.substring(param1.length() + 1); return JFlexParserUtil.parseFragment(parserInput, value, JFlexParser.MODE_PREPROCESS); } /** * Given template parameter content of the form "name" or "name|default", * return the parameter name. */ private String parseParamName(String raw) throws Exception { int pos = raw.indexOf('|'); String name = null; if (pos != -1) { name = raw.substring(0, pos); } else { name = raw; } name = name.trim(); if (StringUtils.isBlank(name)) { // FIXME - no need for an exception throw new Exception("No parameter name specified"); } return name; } /** * After template parameter values have been set, process the template body * and replace parameters with parameter values or defaults, processing any * embedded parameters or templates. */ private String parseTemplateBody(ParserInput parserInput, String content) throws Exception { StringBuffer output = new StringBuffer(); int pos = 0; while (pos < content.length()) { String substring = content.substring(pos); if (substring.startsWith("{{{")) { // template int endPos = Utilities.findMatchingEndTag(content, pos, "{{{", "}}}"); if (endPos != -1) { String param = content.substring(pos, endPos); output.append(this.applyParameter(parserInput, param)); } pos = endPos; } else { output.append(content.charAt(pos)); pos++; } } return JFlexParserUtil.parseFragment(parserInput, output.toString(), JFlexParser.MODE_PREPROCESS); } /** * Given a template call of the form "{{template|param|param}}", return * the template name. */ private String parseTemplateName(String raw) throws Exception { String name = raw; int pos = raw.indexOf('|'); if (pos != -1) { name = name.substring(0, pos); } name = Utilities.decodeTopicName(name.trim(), true); if (StringUtils.isBlank(name)) { // FIXME - no need for an exception throw new Exception("No template name specified"); } if (name.startsWith(NamespaceHandler.NAMESPACE_SEPARATOR)) { if (name.length() == 1) { // FIXME - no need for an exception throw new Exception("No template name specified"); } } else if (!name.startsWith(NamespaceHandler.NAMESPACE_TEMPLATE + NamespaceHandler.NAMESPACE_SEPARATOR)) { name = NamespaceHandler.NAMESPACE_TEMPLATE + NamespaceHandler.NAMESPACE_SEPARATOR + StringUtils.capitalize(name); } return name; } /** * Given a template call of the form "{{name|param=value|param=value}}" * parse the parameter names and values. */ private void parseTemplateParameterValues(ParserInput parserInput, String templateContent) throws Exception { Vector tokens = this.tokenizeParams(templateContent); if (tokens.isEmpty()) { throw new Exception("No template name found in " + templateContent); } int count = -1; for (Iterator iterator = tokens.iterator(); iterator.hasNext();) { String token = (String)iterator.next(); count++; if (count == 0) { // first token is template name continue; } String[] nameValue = this.tokenizeNameValue(token); String name = nameValue[0]; if (name == null) { name = Integer.toString(count); } String value = (nameValue[1] == null) ? null : nameValue[1].trim(); this.parameterValues.put(name, value); } } /** * Given a template call of the form "{{name|param|param}}" return the * parsed output. */ private String processTemplateContent(ParserInput parserInput, ParserOutput parserOutput, Topic templateTopic, String templateContent, String name) throws Exception { if (templateTopic == null) { return "[[" + name + "]]"; } // set template parameter values this.parseTemplateParameterValues(parserInput, templateContent); return this.parseTemplateBody(parserInput, templateTopic.getTopicContent()); } /** * Given a template call of the form "{{:name}}" parse the template * inclusion. */ private String processTemplateInclusion(ParserInput parserInput, ParserOutput parserOutput, int mode, Topic templateTopic, String raw, String name) throws Exception { if (templateTopic == null) { return "[[" + name + "]]"; } // FIXME - disable section editing parserInput.getTempParams().put(TEMPLATE_INCLUSION, "true"); return (StringUtils.isBlank(templateTopic.getTopicContent())) ? templateTopic.getTopicContent() : JFlexParserUtil.parseFragment(parserInput, templateTopic.getTopicContent(), mode); } /** * Process template values, setting link and other metadata output values. */ private void processTemplateMetadata(ParserInput parserInput, ParserOutput parserOutput, Topic templateTopic, String raw, String name) throws Exception { name = (templateTopic != null) ? templateTopic.getName() : name; parserOutput.addLink(name); parserOutput.addTemplate(name); } /** * */ private String[] tokenizeNameValue(String content) { String[] results = new String[2]; results[0] = null; results[1] = content; Matcher m = PARAM_NAME_VALUE_PATTERN.matcher(content); if (m.matches()) { results[0] = m.group(1); results[1] = m.group(2); } return results; } /** * Parse a template string of the form "param1|param2|param3" into * tokens (param1, param2, and param3 in the example). */ private Vector tokenizeParams(String content) { Vector tokens = new Vector(); int pos = 0; int endPos = -1; String substring = ""; String value = ""; while (pos < content.length()) { substring = content.substring(pos); endPos = -1; if (substring.startsWith("{{{")) { // template parameter endPos = Utilities.findMatchingEndTag(content, pos, "{{{", "}}}"); } else if (substring.startsWith("{{")) { // template endPos = Utilities.findMatchingEndTag(content, pos, "{{", "}}"); } else if (substring.startsWith("[[")) { // link endPos = Utilities.findMatchingEndTag(content, pos, "[[", "]]"); } else if (substring.startsWith("{|")) { // table endPos = Utilities.findMatchingEndTag(content, pos, "{|", "|}"); } else if (content.charAt(pos) == '|') { // new token tokens.add(new String(value)); value = ""; pos++; continue; } if (endPos != -1) { value += content.substring(pos, endPos); pos = endPos; } else { value += content.charAt(pos); pos++; } } // add the last one tokens.add(new String(value)); return tokens; } }
false
true
public String parse(ParserInput parserInput, ParserOutput parserOutput, int mode, String raw) { try { parserInput.incrementTemplateDepth(); // validate and extract the template content if (StringUtils.isBlank(raw)) { throw new Exception("Empty template text"); } if (!raw.startsWith("{{") || !raw.endsWith("}}")) { throw new Exception ("Invalid template text: " + raw); } String templateContent = raw.substring("{{".length(), raw.length() - "}}".length()); // parse for nested templates templateContent = JFlexParserUtil.parseFragment(parserInput, templateContent, mode); // check for magic word or parser function String[] parserFunctionInfo = ParserFunctionUtil.parseParserFunctionInfo(templateContent); if (MagicWordUtil.isMagicWord(templateContent) || parserFunctionInfo != null) { if (mode <= JFlexParser.MODE_MINIMAL) { parserInput.decrementTemplateDepth(); return raw; } parserInput.decrementTemplateDepth(); if (MagicWordUtil.isMagicWord(templateContent)) { return MagicWordUtil.processMagicWord(parserInput, templateContent); } else { return ParserFunctionUtil.processParserFunction(parserInput, parserFunctionInfo[0], parserFunctionInfo[1]); } } // extract the template name String name = this.parseTemplateName(templateContent); boolean inclusion = false; if (name.startsWith(NamespaceHandler.NAMESPACE_SEPARATOR)) { name = name.substring(1); inclusion = true; } // get the parsed template body Topic templateTopic = WikiBase.getDataHandler().lookupTopic(parserInput.getVirtualWiki(), name, false, null); this.processTemplateMetadata(parserInput, parserOutput, templateTopic, raw, name); if (mode <= JFlexParser.MODE_MINIMAL) { parserInput.decrementTemplateDepth(); return raw; } // make sure template was not redirected if (templateTopic != null && templateTopic.getTopicType() == Topic.TYPE_REDIRECT) { templateTopic = WikiUtil.findRedirectedTopic(templateTopic, 0); name = templateTopic.getName(); } if (templateTopic != null && templateTopic.getTopicType() == Topic.TYPE_REDIRECT) { // redirection target does not exist templateTopic = null; } if (inclusion) { String output = this.processTemplateInclusion(parserInput, parserOutput, mode, templateTopic, raw, name); parserInput.decrementTemplateDepth(); return output; } String output = this.processTemplateContent(parserInput, parserOutput, templateTopic, templateContent, name); parserInput.decrementTemplateDepth(); return output; } catch (Throwable t) { logger.info("Unable to parse " + raw, t); return raw; } }
public String parse(ParserInput parserInput, ParserOutput parserOutput, int mode, String raw) { try { parserInput.incrementTemplateDepth(); // validate and extract the template content if (StringUtils.isBlank(raw)) { throw new Exception("Empty template text"); } if (!raw.startsWith("{{") || !raw.endsWith("}}")) { throw new Exception ("Invalid template text: " + raw); } String templateContent = raw.substring("{{".length(), raw.length() - "}}".length()); // parse for nested templates, signatures, etc. templateContent = JFlexParserUtil.parseFragment(parserInput, templateContent, mode); // update the raw value to handle cases such as a signature in the template content raw = "{{" + templateContent + "}}"; // check for magic word or parser function String[] parserFunctionInfo = ParserFunctionUtil.parseParserFunctionInfo(templateContent); if (MagicWordUtil.isMagicWord(templateContent) || parserFunctionInfo != null) { if (mode <= JFlexParser.MODE_MINIMAL) { parserInput.decrementTemplateDepth(); return raw; } parserInput.decrementTemplateDepth(); if (MagicWordUtil.isMagicWord(templateContent)) { return MagicWordUtil.processMagicWord(parserInput, templateContent); } else { return ParserFunctionUtil.processParserFunction(parserInput, parserFunctionInfo[0], parserFunctionInfo[1]); } } // extract the template name String name = this.parseTemplateName(templateContent); boolean inclusion = false; if (name.startsWith(NamespaceHandler.NAMESPACE_SEPARATOR)) { name = name.substring(1); inclusion = true; } // get the parsed template body Topic templateTopic = WikiBase.getDataHandler().lookupTopic(parserInput.getVirtualWiki(), name, false, null); this.processTemplateMetadata(parserInput, parserOutput, templateTopic, raw, name); if (mode <= JFlexParser.MODE_MINIMAL) { parserInput.decrementTemplateDepth(); return raw; } // make sure template was not redirected if (templateTopic != null && templateTopic.getTopicType() == Topic.TYPE_REDIRECT) { templateTopic = WikiUtil.findRedirectedTopic(templateTopic, 0); name = templateTopic.getName(); } if (templateTopic != null && templateTopic.getTopicType() == Topic.TYPE_REDIRECT) { // redirection target does not exist templateTopic = null; } if (inclusion) { String output = this.processTemplateInclusion(parserInput, parserOutput, mode, templateTopic, raw, name); parserInput.decrementTemplateDepth(); return output; } String output = this.processTemplateContent(parserInput, parserOutput, templateTopic, templateContent, name); parserInput.decrementTemplateDepth(); return output; } catch (Throwable t) { logger.info("Unable to parse " + raw, t); return raw; } }
diff --git a/src/cx/mccormick/pddroidparty/PatchSelector.java b/src/cx/mccormick/pddroidparty/PatchSelector.java index e8abd02..863b193 100644 --- a/src/cx/mccormick/pddroidparty/PatchSelector.java +++ b/src/cx/mccormick/pddroidparty/PatchSelector.java @@ -1,123 +1,125 @@ package cx.mccormick.pddroidparty; /* Based on SceneSelection code by Peter Brinkmann (thanks!) */ import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import org.puredata.android.utils.Properties; import org.puredata.core.PdBase; import org.puredata.core.utils.IoUtils; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class PatchSelector extends Activity implements OnItemClickListener { private ListView patchList; private final Map<String, String> patches = new HashMap<String, String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initGui(); } @Override public void onItemClick(AdapterView<?> arg0, View v, int position, long id) { TextView item = (TextView) v; String name = item.getText().toString(); launchDroidParty(patches.get(name)); } private void launchDroidParty(String path) { Log.e("PdDroidParty ************** PATCH", path); Intent intent = new Intent(this, PdDroidParty.class); intent.putExtra(PdDroidParty.PATCH, path); startActivity(intent); } private String unpackBakedPatch() { Resources res = getResources(); //File libDir = getFilesDir(); // if we have a patch zip if (res.getIdentifier("patch", "raw", getPackageName()) != 0) { //IoUtils.extractZipResource(res.openRawResource(R.raw.abstractions), libDir, false); //IoUtils.extractZipResource(res.openRawResource(Properties.hasArmeabiV7a ? R.raw.externals_v7a : R.raw.externals), libDir, false); // where we will be storing the patch on the sdcard String basedir = "/sdcard/" + res.getString(res.getIdentifier("dirname", "string", getPackageName())); // version file for the existing patch File version = new File(basedir + "/patch/VERSION-" + res.getInteger(res.getIdentifier("revno", "integer", getPackageName()))); // if the version file does not exist if (!version.exists()) { try { IoUtils.extractZipResource(getResources().openRawResource(res.getIdentifier("patch", "raw", getPackageName())), new File(basedir), false); } catch (IOException e) { // do nothing return null; } } //PdBase.addToSearchPath(libDir.getAbsolutePath()); PdBase.addToSearchPath(basedir + "/patch"); return basedir + "/patch/droidparty_main.pd"; } return null; } private void initGui() { setContentView(R.layout.patch_selector); patchList = (ListView) findViewById(R.id.patch_selector); final ProgressDialog progress = new ProgressDialog(this); progress.setMessage("Finding patches..."); progress.setCancelable(false); progress.setIndeterminate(true); progress.show(); new Thread() { @Override public void run() { // see if this is an app with a zip to unpack instead String bakedpatch = unpackBakedPatch(); if (bakedpatch != null) { + finish(); launchDroidParty(bakedpatch); + stop(); } else { List<File> list = IoUtils.find(new File("/sdcard"), ".*droidparty_main\\.pd$"); for (File f: list) { String[] parts = f.getParent().split("/"); patches.put(parts[parts.length - 1], f.getAbsolutePath()); } ArrayList<String> keyList = new ArrayList<String>(patches.keySet()); Collections.sort(keyList, new Comparator<String>() { public int compare(String a, String b) { return a.toLowerCase().compareTo(b.toLowerCase()); } }); final ArrayAdapter<String> adapter = new ArrayAdapter<String>(PatchSelector.this, android.R.layout.simple_list_item_1, keyList); patchList.getHandler().post(new Runnable() { @Override public void run() { patchList.setAdapter(adapter); progress.dismiss(); } }); } }; }.start(); patchList.setOnItemClickListener(this); } }
false
true
private void initGui() { setContentView(R.layout.patch_selector); patchList = (ListView) findViewById(R.id.patch_selector); final ProgressDialog progress = new ProgressDialog(this); progress.setMessage("Finding patches..."); progress.setCancelable(false); progress.setIndeterminate(true); progress.show(); new Thread() { @Override public void run() { // see if this is an app with a zip to unpack instead String bakedpatch = unpackBakedPatch(); if (bakedpatch != null) { launchDroidParty(bakedpatch); } else { List<File> list = IoUtils.find(new File("/sdcard"), ".*droidparty_main\\.pd$"); for (File f: list) { String[] parts = f.getParent().split("/"); patches.put(parts[parts.length - 1], f.getAbsolutePath()); } ArrayList<String> keyList = new ArrayList<String>(patches.keySet()); Collections.sort(keyList, new Comparator<String>() { public int compare(String a, String b) { return a.toLowerCase().compareTo(b.toLowerCase()); } }); final ArrayAdapter<String> adapter = new ArrayAdapter<String>(PatchSelector.this, android.R.layout.simple_list_item_1, keyList); patchList.getHandler().post(new Runnable() { @Override public void run() { patchList.setAdapter(adapter); progress.dismiss(); } }); } }; }.start(); patchList.setOnItemClickListener(this); }
private void initGui() { setContentView(R.layout.patch_selector); patchList = (ListView) findViewById(R.id.patch_selector); final ProgressDialog progress = new ProgressDialog(this); progress.setMessage("Finding patches..."); progress.setCancelable(false); progress.setIndeterminate(true); progress.show(); new Thread() { @Override public void run() { // see if this is an app with a zip to unpack instead String bakedpatch = unpackBakedPatch(); if (bakedpatch != null) { finish(); launchDroidParty(bakedpatch); stop(); } else { List<File> list = IoUtils.find(new File("/sdcard"), ".*droidparty_main\\.pd$"); for (File f: list) { String[] parts = f.getParent().split("/"); patches.put(parts[parts.length - 1], f.getAbsolutePath()); } ArrayList<String> keyList = new ArrayList<String>(patches.keySet()); Collections.sort(keyList, new Comparator<String>() { public int compare(String a, String b) { return a.toLowerCase().compareTo(b.toLowerCase()); } }); final ArrayAdapter<String> adapter = new ArrayAdapter<String>(PatchSelector.this, android.R.layout.simple_list_item_1, keyList); patchList.getHandler().post(new Runnable() { @Override public void run() { patchList.setAdapter(adapter); progress.dismiss(); } }); } }; }.start(); patchList.setOnItemClickListener(this); }
diff --git a/omod/src/main/java/org/openmrs/module/emr/fragment/controller/visit/VisitDetailsFragmentController.java b/omod/src/main/java/org/openmrs/module/emr/fragment/controller/visit/VisitDetailsFragmentController.java index 9012948f..c78b4751 100644 --- a/omod/src/main/java/org/openmrs/module/emr/fragment/controller/visit/VisitDetailsFragmentController.java +++ b/omod/src/main/java/org/openmrs/module/emr/fragment/controller/visit/VisitDetailsFragmentController.java @@ -1,109 +1,109 @@ package org.openmrs.module.emr.fragment.controller.visit; import org.apache.commons.lang.time.DateFormatUtils; import org.apache.commons.lang.time.DateUtils; import org.openmrs.*; import org.openmrs.api.AdministrationService; import org.openmrs.api.EncounterService; import org.openmrs.module.emr.EmrConstants; import org.openmrs.module.emr.EmrContext; import org.openmrs.module.emr.EmrProperties; import org.openmrs.module.emr.consult.Diagnosis; import org.openmrs.module.emr.consult.DiagnosisMetadata; import org.openmrs.module.emr.visit.ParserEncounterIntoSimpleObjects; import org.openmrs.ui.framework.SimpleObject; import org.openmrs.ui.framework.UiFrameworkConstants; import org.openmrs.ui.framework.UiUtils; import org.openmrs.ui.framework.annotation.SpringBean; import org.openmrs.ui.framework.fragment.action.FailureResult; import org.openmrs.ui.framework.fragment.action.FragmentActionResult; import org.openmrs.ui.framework.fragment.action.SuccessResult; import org.springframework.web.bind.annotation.RequestParam; import java.text.ParseException; import java.util.*; public class VisitDetailsFragmentController { public SimpleObject getVisitDetails( @SpringBean("adminService") AdministrationService administrationService, @RequestParam("visitId") Visit visit, UiUtils uiUtils, EmrContext emrContext) throws ParseException { SimpleObject simpleObject = SimpleObject.fromObject(visit, uiUtils, "id", "location"); User authenticatedUser = emrContext.getUserContext().getAuthenticatedUser(); boolean canDelete = authenticatedUser.hasPrivilege(EmrConstants.PRIVILEGE_DELETE_ENCOUNTER); Date startDatetime = visit.getStartDatetime(); Date stopDatetime = visit.getStopDatetime(); - simpleObject.put("startDatetime", DateFormatUtils.format(startDatetime, "dd MMM yyyy hh:mm a")); + simpleObject.put("startDatetime", DateFormatUtils.format(startDatetime, "dd MMM yyyy hh:mm a", emrContext.getUserContext().getLocale())); if (stopDatetime!=null){ - simpleObject.put("stopDatetime", DateFormatUtils.format(stopDatetime, "dd MMM yyyy hh:mm a")); + simpleObject.put("stopDatetime", DateFormatUtils.format(stopDatetime, "dd MMM yyyy hh:mm a", emrContext.getUserContext().getLocale())); } else { simpleObject.put("stopDatetime", null); } List<SimpleObject> encounters = new ArrayList<SimpleObject>(); simpleObject.put("encounters", encounters); String[] datePatterns = { administrationService.getGlobalProperty(UiFrameworkConstants.GP_FORMATTER_DATETIME_FORMAT) }; for (Encounter e : visit.getEncounters()) { if (!e.getVoided()) { - SimpleObject simpleEncounter = SimpleObject.fromObject(e, uiUtils, "encounterId", "encounterDatetime", "location", "encounterProviders.provider", "voided", "form"); + SimpleObject simpleEncounter = SimpleObject.fromObject(e, uiUtils, "encounterId", "location", "encounterProviders.provider", "voided", "form"); - Date encounterDatetime = DateUtils.parseDate((String) simpleEncounter.get("encounterDatetime"), datePatterns); - simpleEncounter.put("encounterDate", DateFormatUtils.format(encounterDatetime, "dd MMM yyyy")); - simpleEncounter.put("encounterTime", DateFormatUtils.format(encounterDatetime, "hh:mm a")); + // manually set the dates so we can control how we format them + simpleEncounter.put("encounterDate", DateFormatUtils.format(e.getEncounterDatetime(), "dd MMM yyyy", emrContext.getUserContext().getLocale())); + simpleEncounter.put("encounterTime", DateFormatUtils.format(e.getEncounterDatetime(), "hh:mm a", emrContext.getUserContext().getLocale())); EncounterType encounterType = e.getEncounterType(); simpleEncounter.put("encounterType", SimpleObject.create("uuid", encounterType.getUuid(), "name", uiUtils.format(encounterType))); if(canDelete){ simpleEncounter.put("canDelete", true); } encounters.add(simpleEncounter); } } return simpleObject; } public SimpleObject getEncounterDetails(@RequestParam("encounterId") Encounter encounter, @SpringBean("emrProperties") EmrProperties emrProperties, UiUtils uiUtils){ ParserEncounterIntoSimpleObjects parserEncounter = new ParserEncounterIntoSimpleObjects(encounter, uiUtils, emrProperties); List<SimpleObject> observations = parserEncounter.parseObservations(); List<SimpleObject> diagnoses = parserEncounter.parseDiagnoses(); List<SimpleObject> orders = parserEncounter.parseOrders(); return SimpleObject.create("observations", observations, "orders", orders, "diagnoses", diagnoses); } public FragmentActionResult deleteEncounter(UiUtils ui, @RequestParam("encounterId")Encounter encounter, @SpringBean("encounterService")EncounterService encounterService, EmrContext emrContext){ if(encounter!=null){ User authenticatedUser = emrContext.getUserContext().getAuthenticatedUser(); boolean canDelete = authenticatedUser.hasPrivilege(EmrConstants.PRIVILEGE_DELETE_ENCOUNTER); if(canDelete){ encounterService.voidEncounter(encounter, "delete encounter"); encounterService.saveEncounter(encounter); }else{ return new FailureResult(ui.message("emr.patientDashBoard.deleteEncounter.notAllowed")); } } return new SuccessResult(ui.message("emr.patientDashBoard.deleteEncounter.successMessage")); } }
false
true
public SimpleObject getVisitDetails( @SpringBean("adminService") AdministrationService administrationService, @RequestParam("visitId") Visit visit, UiUtils uiUtils, EmrContext emrContext) throws ParseException { SimpleObject simpleObject = SimpleObject.fromObject(visit, uiUtils, "id", "location"); User authenticatedUser = emrContext.getUserContext().getAuthenticatedUser(); boolean canDelete = authenticatedUser.hasPrivilege(EmrConstants.PRIVILEGE_DELETE_ENCOUNTER); Date startDatetime = visit.getStartDatetime(); Date stopDatetime = visit.getStopDatetime(); simpleObject.put("startDatetime", DateFormatUtils.format(startDatetime, "dd MMM yyyy hh:mm a")); if (stopDatetime!=null){ simpleObject.put("stopDatetime", DateFormatUtils.format(stopDatetime, "dd MMM yyyy hh:mm a")); } else { simpleObject.put("stopDatetime", null); } List<SimpleObject> encounters = new ArrayList<SimpleObject>(); simpleObject.put("encounters", encounters); String[] datePatterns = { administrationService.getGlobalProperty(UiFrameworkConstants.GP_FORMATTER_DATETIME_FORMAT) }; for (Encounter e : visit.getEncounters()) { if (!e.getVoided()) { SimpleObject simpleEncounter = SimpleObject.fromObject(e, uiUtils, "encounterId", "encounterDatetime", "location", "encounterProviders.provider", "voided", "form"); Date encounterDatetime = DateUtils.parseDate((String) simpleEncounter.get("encounterDatetime"), datePatterns); simpleEncounter.put("encounterDate", DateFormatUtils.format(encounterDatetime, "dd MMM yyyy")); simpleEncounter.put("encounterTime", DateFormatUtils.format(encounterDatetime, "hh:mm a")); EncounterType encounterType = e.getEncounterType(); simpleEncounter.put("encounterType", SimpleObject.create("uuid", encounterType.getUuid(), "name", uiUtils.format(encounterType))); if(canDelete){ simpleEncounter.put("canDelete", true); } encounters.add(simpleEncounter); } } return simpleObject; }
public SimpleObject getVisitDetails( @SpringBean("adminService") AdministrationService administrationService, @RequestParam("visitId") Visit visit, UiUtils uiUtils, EmrContext emrContext) throws ParseException { SimpleObject simpleObject = SimpleObject.fromObject(visit, uiUtils, "id", "location"); User authenticatedUser = emrContext.getUserContext().getAuthenticatedUser(); boolean canDelete = authenticatedUser.hasPrivilege(EmrConstants.PRIVILEGE_DELETE_ENCOUNTER); Date startDatetime = visit.getStartDatetime(); Date stopDatetime = visit.getStopDatetime(); simpleObject.put("startDatetime", DateFormatUtils.format(startDatetime, "dd MMM yyyy hh:mm a", emrContext.getUserContext().getLocale())); if (stopDatetime!=null){ simpleObject.put("stopDatetime", DateFormatUtils.format(stopDatetime, "dd MMM yyyy hh:mm a", emrContext.getUserContext().getLocale())); } else { simpleObject.put("stopDatetime", null); } List<SimpleObject> encounters = new ArrayList<SimpleObject>(); simpleObject.put("encounters", encounters); String[] datePatterns = { administrationService.getGlobalProperty(UiFrameworkConstants.GP_FORMATTER_DATETIME_FORMAT) }; for (Encounter e : visit.getEncounters()) { if (!e.getVoided()) { SimpleObject simpleEncounter = SimpleObject.fromObject(e, uiUtils, "encounterId", "location", "encounterProviders.provider", "voided", "form"); // manually set the dates so we can control how we format them simpleEncounter.put("encounterDate", DateFormatUtils.format(e.getEncounterDatetime(), "dd MMM yyyy", emrContext.getUserContext().getLocale())); simpleEncounter.put("encounterTime", DateFormatUtils.format(e.getEncounterDatetime(), "hh:mm a", emrContext.getUserContext().getLocale())); EncounterType encounterType = e.getEncounterType(); simpleEncounter.put("encounterType", SimpleObject.create("uuid", encounterType.getUuid(), "name", uiUtils.format(encounterType))); if(canDelete){ simpleEncounter.put("canDelete", true); } encounters.add(simpleEncounter); } } return simpleObject; }
diff --git a/src/de/ueller/gps/BtReceiverInput.java b/src/de/ueller/gps/BtReceiverInput.java index 5762b5f2..b0ff7d8c 100644 --- a/src/de/ueller/gps/BtReceiverInput.java +++ b/src/de/ueller/gps/BtReceiverInput.java @@ -1,363 +1,365 @@ package de.ueller.gps; /** * This file is part of GpsMid * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * Copyright (c) 2008 Kai Krueger apmonkey at users dot sourceforge dot net * See Copying */ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Timer; import java.util.TimerTask; import javax.microedition.io.Connector; import javax.microedition.io.StreamConnection; import de.ueller.gps.data.Configuration; import de.ueller.gps.nmea.NmeaInput; import de.ueller.midlet.gps.GpsMid; import de.ueller.midlet.gps.LocationMsgProducer; import de.ueller.midlet.gps.LocationMsgReceiver; import de.ueller.midlet.gps.LocationMsgReceiverList; import de.ueller.midlet.gps.Logger; import de.ueller.midlet.gps.Trace; /** * * This class shares the functionality to read from the Bluetooth GPS receiver * and handles common functionality such as dealing with receiver quality and * lost connections * * The protocol specific decoding is handled in the abstract process() function * of subclasses * */ public abstract class BtReceiverInput implements Runnable, LocationMsgProducer { private static final Logger logger = Logger.getInstance(NmeaInput.class, Logger.TRACE); protected InputStream btGpsInputStream; private OutputStream btGpsOutputStream; private StreamConnection conn; protected OutputStream rawDataLogger; protected Thread processorThread; protected LocationMsgReceiverList receiverList; protected boolean closed = false; protected byte connectQuality = 100; protected int bytesReceived = 0; protected int[] connectError = new int[LocationMsgReceiver.SIRF_FAIL_COUNT]; protected String message; protected int msgsReceived = 1; public BtReceiverInput() { this.receiverList = new LocationMsgReceiverList(); } protected class KeepAliveTimer extends TimerTask { public void run() { if (btGpsOutputStream != null) { try { logger.debug("Writing bogus keep-alive"); btGpsOutputStream.write(0); } catch (IOException e) { logger.info("Closing keep alive timer"); this.cancel(); } catch (IllegalArgumentException iae) { logger.silentexception("KeepAliveTimer went wrong", iae); } } } } public boolean init(LocationMsgReceiver receiver) { if (receiver != null) this.receiverList.addReceiver(receiver); //#debug info logger.info("Connect to "+Configuration.getBtUrl()); if (! openBtConnection(Configuration.getBtUrl())){ this.receiverList.locationDecoderEnd(); return false; } this.receiverList.receiveMessage("BT Connected"); processorThread = new Thread(this, "Bluetooth Receiver Decoder"); processorThread.setPriority(Thread.MAX_PRIORITY); processorThread.start(); /** * There is at least one, perhaps more Bt GPS receivers, that seem to * kill the Bluetooth connection if we don't send it something for some * reason. Perhaps due to poor power management? We don't have anything * to send, so send an arbitrary 0. */ if (Configuration.getBtKeepAlive()) { TimerTask tt = new KeepAliveTimer(); logger.info("Setting keep alive timer: " + tt); Timer t = new Timer(); t.schedule(tt, 1000, 1000); } return true; } abstract protected void process() throws IOException; public void run() { receiverList.receiveMessage("Start Bt GPS receiver"); // Eat the buffer content try { try { byte[] buf = new byte[512]; while (btGpsInputStream.available() > 0) { int received = btGpsInputStream.read(buf); bytesReceived += received; if (rawDataLogger != null) { rawDataLogger.write(buf, 0, received); rawDataLogger.flush(); } } // #debug debug logger.debug("Erased " + bytesReceived + " bytes"); bytesReceived = 100; } catch (IOException e1) { receiverList.receiveMessage("Closing: " + e1.getMessage()); close("Closing: " + e1.getMessage()); } byte timeCounter = 41; while (!closed) { //#debug debug logger.debug("Bt receiver thread looped"); try { timeCounter++; if (timeCounter > 40) { timeCounter = 0; if (connectQuality > 100) { connectQuality = 100; } if (connectQuality < 0) { connectQuality = 0; } receiverList.receiveStatistics(connectError, connectQuality); // watchdog if no bytes received in 10 sec then exit // thread if (bytesReceived == 0) { throw new IOException("No Data from GPS"); } else { bytesReceived = 0; } } process(); } catch (IOException e) { /** * The bluetooth connection seems to have died, try and * reconnect. If the reconnect was successful the reconnect * function will call the init function, which will create a * new thread. In that case we simply exit this old thread. * If the reconnect was unsuccessful then we close the * connection and give an error message. */ logger.info("Failed to read from GPS trying to reconnect: " + e.getMessage()); receiverList.receiveSolution("~~"); if (!autoReconnectBtConnection()) { logger.info("GPS bluethooth could not reconnect"); receiverList.receiveMessage("Closing: " + e.getMessage()); close("Closed: " + e.getMessage()); } else { logger.info("GPS bluetooth reconnect was successful"); return; } } if (!closed) try { synchronized (this) { connectError[LocationMsgReceiver.SIRF_FAIL_MSG_INTERUPTED]++; wait(250); } } catch (InterruptedException e) { // Nothing to do in this case } } } catch (OutOfMemoryError oome) { - logger.fatal("GpsInput thread crashed as out of memory: " + closed = true; + logger.fatal("BtReceiverInput thread ran out of memory: " + oome.getMessage()); oome.printStackTrace(); } catch (Exception e) { - logger.fatal("GpsInput thread crashed unexpectedly: " + closed = true; + logger.fatal("BtReceiverInput thread crashed unexpectedly: " + e.getMessage()); e.printStackTrace(); } finally { if (closed) { logger.info("Finished LocationProducer thread, closing bluetooth"); closeBtConnection(); if (message == null) { receiverList.locationDecoderEnd(); } else { receiverList.locationDecoderEnd(message); } } else { /** * Don't need to do anything here. * This is the case when we are auto-reconnecting * and starting up a new bluetooth processing thread */ } } } /* * (non-Javadoc) * * @see de.ueller.gps.nmea.LocationMsgProducer#close() */ public void close() { logger.info("Location producer closing"); closed = true; if (processorThread != null) processorThread.interrupt(); } public void close(String message) { this.message = message; close(); } public void enableRawLogging(OutputStream os) { rawDataLogger = os; } public void disableRawLogging() { if (rawDataLogger != null) { try { rawDataLogger.close(); } catch (IOException e) { logger.exception("Couldn't close raw GPS logger", e); } rawDataLogger = null; } } public void addLocationMsgReceiver(LocationMsgReceiver receiver) { receiverList.addReceiver(receiver); } public boolean removeLocationMsgReceiver(LocationMsgReceiver receiver) { return receiverList.removeReceiver(receiver); } private synchronized boolean openBtConnection(String url){ if (btGpsInputStream != null){ return true; } if (url == null) return false; try { logger.info("Connector.open()"); conn = (StreamConnection) Connector.open(url); logger.info("conn.openInputStream()"); btGpsInputStream = conn.openInputStream(); /** * There is at least one, perhaps more BT gps receivers, that * seem to kill the bluetooth connection if we don't send it * something for some reason. Perhaps due to poor powermanagment? * We don't have anything to send, so send an arbitrary 0. */ if (Configuration.getBtKeepAlive()) { btGpsOutputStream = conn.openOutputStream(); } } catch (SecurityException se) { /** * The application was not permitted to connect to bluetooth */ receiverList.receiveMessage("Connecting to BT not permitted"); return false; } catch (IOException e) { receiverList.receiveMessage("err BT:"+e.getMessage()); return false; } return true; } private synchronized void closeBtConnection() { disableRawLogging(); if (btGpsInputStream != null){ try { btGpsInputStream.close(); } catch (IOException e) { } btGpsInputStream=null; } if (btGpsOutputStream != null){ try { btGpsOutputStream.close(); } catch (IOException e) { } btGpsOutputStream=null; } if (conn != null){ try { conn.close(); } catch (IOException e) { } conn=null; } } /** * This function tries to reconnect to the bluetooth * it retries for up to 40 seconds and blocks in the * mean time, so this function has to be called from * within a separate thread. If successful, it will * reinitialise the location producer with the new * streams. * * @return whether the reconnect was successful */ private boolean autoReconnectBtConnection() { if (!Configuration.getBtAutoRecon()) { logger.info("Not trying to reconnect"); return false; } if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_DISCONNECT)) { GpsMid.mNoiseMaker.playSound("DISCONNECT"); } /** * If there are still parts of the old connection * left over, close these cleanly. */ closeBtConnection(); int reconnectFailures = 0; logger.info("Trying to reconnect to bluetooth"); while (!closed && (reconnectFailures < 4) && (! openBtConnection(Configuration.getBtUrl()))){ reconnectFailures++; logger.info("Failed to reconnect for the " + reconnectFailures + " time"); try { Thread.sleep(10000); } catch (InterruptedException e) { logger.silentexception("INTERRUPTED!", e); return false; } } if (reconnectFailures < 4 && !closed) { if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_CONNECT)) { GpsMid.mNoiseMaker.playSound("CONNECT"); } init(null); return true; } if (!closed) logger.error("Lost connection to GPS and failed to reconnect"); return false; } }
false
true
public void run() { receiverList.receiveMessage("Start Bt GPS receiver"); // Eat the buffer content try { try { byte[] buf = new byte[512]; while (btGpsInputStream.available() > 0) { int received = btGpsInputStream.read(buf); bytesReceived += received; if (rawDataLogger != null) { rawDataLogger.write(buf, 0, received); rawDataLogger.flush(); } } // #debug debug logger.debug("Erased " + bytesReceived + " bytes"); bytesReceived = 100; } catch (IOException e1) { receiverList.receiveMessage("Closing: " + e1.getMessage()); close("Closing: " + e1.getMessage()); } byte timeCounter = 41; while (!closed) { //#debug debug logger.debug("Bt receiver thread looped"); try { timeCounter++; if (timeCounter > 40) { timeCounter = 0; if (connectQuality > 100) { connectQuality = 100; } if (connectQuality < 0) { connectQuality = 0; } receiverList.receiveStatistics(connectError, connectQuality); // watchdog if no bytes received in 10 sec then exit // thread if (bytesReceived == 0) { throw new IOException("No Data from GPS"); } else { bytesReceived = 0; } } process(); } catch (IOException e) { /** * The bluetooth connection seems to have died, try and * reconnect. If the reconnect was successful the reconnect * function will call the init function, which will create a * new thread. In that case we simply exit this old thread. * If the reconnect was unsuccessful then we close the * connection and give an error message. */ logger.info("Failed to read from GPS trying to reconnect: " + e.getMessage()); receiverList.receiveSolution("~~"); if (!autoReconnectBtConnection()) { logger.info("GPS bluethooth could not reconnect"); receiverList.receiveMessage("Closing: " + e.getMessage()); close("Closed: " + e.getMessage()); } else { logger.info("GPS bluetooth reconnect was successful"); return; } } if (!closed) try { synchronized (this) { connectError[LocationMsgReceiver.SIRF_FAIL_MSG_INTERUPTED]++; wait(250); } } catch (InterruptedException e) { // Nothing to do in this case } } } catch (OutOfMemoryError oome) { logger.fatal("GpsInput thread crashed as out of memory: " + oome.getMessage()); oome.printStackTrace(); } catch (Exception e) { logger.fatal("GpsInput thread crashed unexpectedly: " + e.getMessage()); e.printStackTrace(); } finally { if (closed) { logger.info("Finished LocationProducer thread, closing bluetooth"); closeBtConnection(); if (message == null) { receiverList.locationDecoderEnd(); } else { receiverList.locationDecoderEnd(message); } } else { /** * Don't need to do anything here. * This is the case when we are auto-reconnecting * and starting up a new bluetooth processing thread */ } } }
public void run() { receiverList.receiveMessage("Start Bt GPS receiver"); // Eat the buffer content try { try { byte[] buf = new byte[512]; while (btGpsInputStream.available() > 0) { int received = btGpsInputStream.read(buf); bytesReceived += received; if (rawDataLogger != null) { rawDataLogger.write(buf, 0, received); rawDataLogger.flush(); } } // #debug debug logger.debug("Erased " + bytesReceived + " bytes"); bytesReceived = 100; } catch (IOException e1) { receiverList.receiveMessage("Closing: " + e1.getMessage()); close("Closing: " + e1.getMessage()); } byte timeCounter = 41; while (!closed) { //#debug debug logger.debug("Bt receiver thread looped"); try { timeCounter++; if (timeCounter > 40) { timeCounter = 0; if (connectQuality > 100) { connectQuality = 100; } if (connectQuality < 0) { connectQuality = 0; } receiverList.receiveStatistics(connectError, connectQuality); // watchdog if no bytes received in 10 sec then exit // thread if (bytesReceived == 0) { throw new IOException("No Data from GPS"); } else { bytesReceived = 0; } } process(); } catch (IOException e) { /** * The bluetooth connection seems to have died, try and * reconnect. If the reconnect was successful the reconnect * function will call the init function, which will create a * new thread. In that case we simply exit this old thread. * If the reconnect was unsuccessful then we close the * connection and give an error message. */ logger.info("Failed to read from GPS trying to reconnect: " + e.getMessage()); receiverList.receiveSolution("~~"); if (!autoReconnectBtConnection()) { logger.info("GPS bluethooth could not reconnect"); receiverList.receiveMessage("Closing: " + e.getMessage()); close("Closed: " + e.getMessage()); } else { logger.info("GPS bluetooth reconnect was successful"); return; } } if (!closed) try { synchronized (this) { connectError[LocationMsgReceiver.SIRF_FAIL_MSG_INTERUPTED]++; wait(250); } } catch (InterruptedException e) { // Nothing to do in this case } } } catch (OutOfMemoryError oome) { closed = true; logger.fatal("BtReceiverInput thread ran out of memory: " + oome.getMessage()); oome.printStackTrace(); } catch (Exception e) { closed = true; logger.fatal("BtReceiverInput thread crashed unexpectedly: " + e.getMessage()); e.printStackTrace(); } finally { if (closed) { logger.info("Finished LocationProducer thread, closing bluetooth"); closeBtConnection(); if (message == null) { receiverList.locationDecoderEnd(); } else { receiverList.locationDecoderEnd(message); } } else { /** * Don't need to do anything here. * This is the case when we are auto-reconnecting * and starting up a new bluetooth processing thread */ } } }
diff --git a/src/cz/zcu/kiv/eeg/mobile/base/ui/experiment/ElectrodeLocationAddActivity.java b/src/cz/zcu/kiv/eeg/mobile/base/ui/experiment/ElectrodeLocationAddActivity.java index 9836fff..0a8ad0b 100644 --- a/src/cz/zcu/kiv/eeg/mobile/base/ui/experiment/ElectrodeLocationAddActivity.java +++ b/src/cz/zcu/kiv/eeg/mobile/base/ui/experiment/ElectrodeLocationAddActivity.java @@ -1,235 +1,237 @@ package cz.zcu.kiv.eeg.mobile.base.ui.experiment; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Spinner; import android.widget.TextView; import cz.zcu.kiv.eeg.mobile.base.R; import cz.zcu.kiv.eeg.mobile.base.archetypes.SaveDiscardActivity; import cz.zcu.kiv.eeg.mobile.base.data.Values; import cz.zcu.kiv.eeg.mobile.base.data.adapter.ElectrodeFixAdapter; import cz.zcu.kiv.eeg.mobile.base.data.adapter.ElectrodeTypeAdapter; import cz.zcu.kiv.eeg.mobile.base.data.container.xml.ElectrodeFix; import cz.zcu.kiv.eeg.mobile.base.data.container.xml.ElectrodeLocation; import cz.zcu.kiv.eeg.mobile.base.data.container.xml.ElectrodeType; import cz.zcu.kiv.eeg.mobile.base.utils.ConnectionUtils; import cz.zcu.kiv.eeg.mobile.base.utils.LimitedTextWatcher; import cz.zcu.kiv.eeg.mobile.base.utils.ValidationUtils; import cz.zcu.kiv.eeg.mobile.base.ws.asynctask.CreateElectrodeLocation; import cz.zcu.kiv.eeg.mobile.base.ws.asynctask.FetchElectrodeFixes; import cz.zcu.kiv.eeg.mobile.base.ws.asynctask.FetchElectrodeTypes; import java.util.ArrayList; /** * Activity for creating new electrode location record. * * @author Petr Miko */ public class ElectrodeLocationAddActivity extends SaveDiscardActivity { private static ElectrodeFixAdapter electrodeFixAdapter; private static ElectrodeTypeAdapter electrodeTypeAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.base_electrode_add); initView(); updateData(); } /** * Initializes spinners and character counter for description field. */ private void initView() { Spinner fixes = (Spinner) findViewById(R.id.electrode_add_fix); Spinner types = (Spinner) findViewById(R.id.electrode_add_type); fixes.setAdapter(getElectrodeFixAdapter()); types.setAdapter(getElectrodeTypeAdapter()); TextView description = (TextView) findViewById(R.id.electrode_add_description); TextView descriptionCount = (TextView) findViewById(R.id.electrode_add_description_count); description.addTextChangedListener(new LimitedTextWatcher(getResources().getInteger(R.integer.limit_description_chars), descriptionCount)); ImageButton addFix = (ImageButton) findViewById(R.id.electrode_add_fix_new); addFix.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.electrode_add_fix_new: Intent intent = new Intent(); intent.setClass(this, ElectrodeFixAddActivity.class); startActivityForResult(intent, Values.ADD_ELECTRODE_FIX); break; default: super.onClick(v); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_refresh: if (!isWorking()) { updateElectrodeFixes(); updateElectrodeTypes(); } return true; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == Values.ADD_ELECTRODE_FIX && resultCode == Activity.RESULT_OK) { ElectrodeFix fix = (ElectrodeFix) data.getExtras().get(Values.ADD_ELECTRODE_FIX_KEY); electrodeFixAdapter.add(fix); } super.onActivityResult(requestCode, resultCode, data); } /** * Fetches data from server, if not already loaded or currently fetching. */ private void updateData() { if (!isWorking()) { if (getElectrodeFixAdapter().isEmpty()) updateElectrodeFixes(); if (getElectrodeTypeAdapter().isEmpty()) updateElectrodeTypes(); } } /** * Reads data from fields, if valid proceeds with creating new record on server. */ @Override protected void save() { ElectrodeLocation record; if ((record = getValidRecord()) != null) { if (ConnectionUtils.isOnline(this)) { new CreateElectrodeLocation(this).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, record); } else showAlert(getString(R.string.error_offline)); } } /** * {@inheritDoc} */ @Override protected void discard() { finish(); } /** * Method for fetching electrode fixes from server. * If not online, shows error dialog. */ private void updateElectrodeFixes() { if (ConnectionUtils.isOnline(this)) new FetchElectrodeFixes(this, getElectrodeFixAdapter()).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR); else showAlert(getString(R.string.error_offline)); } /** * Method for fetching electrode types from server. * If not online, shows error dialog. */ private void updateElectrodeTypes() { if (ConnectionUtils.isOnline(this)) new FetchElectrodeTypes(this, getElectrodeTypeAdapter()).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR); else showAlert(getString(R.string.error_offline)); } /** * Getter of electrode fix adapter. If null, creates new. * * @return electrode fix adapter */ private ElectrodeFixAdapter getElectrodeFixAdapter() { if (electrodeFixAdapter == null) electrodeFixAdapter = new ElectrodeFixAdapter(this, R.layout.base_electrode_simple_row, new ArrayList<ElectrodeFix>()); return electrodeFixAdapter; } /** * Getter of electrode type adapter. If null, creates new. * * @return electrode type adapter */ private ElectrodeTypeAdapter getElectrodeTypeAdapter() { if (electrodeTypeAdapter == null) electrodeTypeAdapter = new ElectrodeTypeAdapter(this, R.layout.base_electrode_simple_row, new ArrayList<ElectrodeType>()); return electrodeTypeAdapter; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.exp_add_menu, menu); return true; } /** * Returns valid record or null, if input values are not valid. * * @return valid record */ private ElectrodeLocation getValidRecord() { EditText title = (EditText) findViewById(R.id.electrode_add_title); EditText abbr = (EditText) findViewById(R.id.electrode_add_abbr); EditText description = (EditText) findViewById(R.id.electrode_add_description); Spinner type = (Spinner) findViewById(R.id.electrode_add_type); Spinner fix = (Spinner) findViewById(R.id.electrode_add_fix); StringBuilder error = new StringBuilder(); ElectrodeFix fixData = (ElectrodeFix) fix.getSelectedItem(); ElectrodeType typeData = (ElectrodeType) type.getSelectedItem(); //validations if (ValidationUtils.isEmpty(title.getText().toString())) error.append(getString(R.string.error_empty_field)).append(" (").append(getString(R.string.dialog_title)).append(")").append('\n'); + if (ValidationUtils.isEmpty(description.getText().toString())) + error.append(getString(R.string.error_empty_field)).append(" (").append(getString(R.string.dialog_description)).append(")").append('\n'); if (ValidationUtils.isEmpty(abbr.getText().toString())) error.append(getString(R.string.error_empty_field)).append(" (").append(getString(R.string.dialog_abbr)).append(")").append('\n'); if (fixData == null) error.append(getString(R.string.error_no_fix_selected)).append('\n'); if (typeData == null) error.append(getString(R.string.error_no_type_selected)).append('\n'); //if no error, run service if (error.toString().isEmpty()) { ElectrodeLocation record = new ElectrodeLocation(); record.setTitle(title.getText().toString()); record.setAbbr(abbr.getText().toString()); record.setDescription(description.getText().toString()); record.setElectrodeFix(fixData); record.setElectrodeType(typeData); return record; } else { showAlert(error.toString()); } return null; } }
true
true
private ElectrodeLocation getValidRecord() { EditText title = (EditText) findViewById(R.id.electrode_add_title); EditText abbr = (EditText) findViewById(R.id.electrode_add_abbr); EditText description = (EditText) findViewById(R.id.electrode_add_description); Spinner type = (Spinner) findViewById(R.id.electrode_add_type); Spinner fix = (Spinner) findViewById(R.id.electrode_add_fix); StringBuilder error = new StringBuilder(); ElectrodeFix fixData = (ElectrodeFix) fix.getSelectedItem(); ElectrodeType typeData = (ElectrodeType) type.getSelectedItem(); //validations if (ValidationUtils.isEmpty(title.getText().toString())) error.append(getString(R.string.error_empty_field)).append(" (").append(getString(R.string.dialog_title)).append(")").append('\n'); if (ValidationUtils.isEmpty(abbr.getText().toString())) error.append(getString(R.string.error_empty_field)).append(" (").append(getString(R.string.dialog_abbr)).append(")").append('\n'); if (fixData == null) error.append(getString(R.string.error_no_fix_selected)).append('\n'); if (typeData == null) error.append(getString(R.string.error_no_type_selected)).append('\n'); //if no error, run service if (error.toString().isEmpty()) { ElectrodeLocation record = new ElectrodeLocation(); record.setTitle(title.getText().toString()); record.setAbbr(abbr.getText().toString()); record.setDescription(description.getText().toString()); record.setElectrodeFix(fixData); record.setElectrodeType(typeData); return record; } else { showAlert(error.toString()); } return null; }
private ElectrodeLocation getValidRecord() { EditText title = (EditText) findViewById(R.id.electrode_add_title); EditText abbr = (EditText) findViewById(R.id.electrode_add_abbr); EditText description = (EditText) findViewById(R.id.electrode_add_description); Spinner type = (Spinner) findViewById(R.id.electrode_add_type); Spinner fix = (Spinner) findViewById(R.id.electrode_add_fix); StringBuilder error = new StringBuilder(); ElectrodeFix fixData = (ElectrodeFix) fix.getSelectedItem(); ElectrodeType typeData = (ElectrodeType) type.getSelectedItem(); //validations if (ValidationUtils.isEmpty(title.getText().toString())) error.append(getString(R.string.error_empty_field)).append(" (").append(getString(R.string.dialog_title)).append(")").append('\n'); if (ValidationUtils.isEmpty(description.getText().toString())) error.append(getString(R.string.error_empty_field)).append(" (").append(getString(R.string.dialog_description)).append(")").append('\n'); if (ValidationUtils.isEmpty(abbr.getText().toString())) error.append(getString(R.string.error_empty_field)).append(" (").append(getString(R.string.dialog_abbr)).append(")").append('\n'); if (fixData == null) error.append(getString(R.string.error_no_fix_selected)).append('\n'); if (typeData == null) error.append(getString(R.string.error_no_type_selected)).append('\n'); //if no error, run service if (error.toString().isEmpty()) { ElectrodeLocation record = new ElectrodeLocation(); record.setTitle(title.getText().toString()); record.setAbbr(abbr.getText().toString()); record.setDescription(description.getText().toString()); record.setElectrodeFix(fixData); record.setElectrodeType(typeData); return record; } else { showAlert(error.toString()); } return null; }
diff --git a/src/main/java/com/treasure_data/bulk_import/BulkImportOptions.java b/src/main/java/com/treasure_data/bulk_import/BulkImportOptions.java index 889a09f..d157964 100644 --- a/src/main/java/com/treasure_data/bulk_import/BulkImportOptions.java +++ b/src/main/java/com/treasure_data/bulk_import/BulkImportOptions.java @@ -1,269 +1,275 @@ // // Treasure Data Bulk-Import Tool in Java // // Copyright (C) 2012 - 2013 Muga Nishizawa // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.treasure_data.bulk_import; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.logging.Logger; import joptsimple.HelpFormatter; import joptsimple.OptionDescriptor; import joptsimple.OptionParser; import joptsimple.OptionSet; public class BulkImportOptions { private static final Logger LOG = Logger.getLogger(BulkImportOptions.class.getName()); private static class SimpleHelpFormatter implements HelpFormatter { private boolean isPrepare(Map<String, ? extends OptionDescriptor> options) { for (OptionDescriptor desc : options.values()) { if (desc.options().contains("parallel")) { return false; } } return true; } public String format(Map<String, ? extends OptionDescriptor> options) { boolean isPrepare = isPrepare(options); System.out.println("command: " + isPrepare); StringBuilder sbuf = new StringBuilder(); // usage sbuf.append("usage:\n"); if (isPrepare) { sbuf.append(Configuration.CMD_PREPARE_USAGE); } else { sbuf.append(Configuration.CMD_UPLOAD_USAGE); } sbuf.append("\n"); // example sbuf.append("example:\n"); if (isPrepare) { sbuf.append(Configuration.CMD_PREPARE_EXAMPLE); } else { sbuf.append(Configuration.CMD_UPLOAD_EXAMPLE); } sbuf.append("\n"); // description sbuf.append("description:\n"); if (isPrepare) { sbuf.append(Configuration.CMD_PREPARE_DESC); } else { sbuf.append(Configuration.CMD_UPLOAD_DESC); } sbuf.append("\n"); // options sbuf.append("options:\n"); if (isPrepare) { sbuf.append(Configuration.CMD_PREPARE_OPTIONS); } else { sbuf.append(Configuration.CMD_UPLOAD_OPTIONS); } sbuf.append("\n"); return sbuf.toString(); } } protected OptionParser op; protected OptionSet options; public BulkImportOptions() { op = new OptionParser(); } public void initPrepareOptionParser(Properties props) { op.formatHelpWith(new SimpleHelpFormatter()); op.acceptsAll(Arrays.asList("h", Configuration.BI_PREPARE_PARTS_HELP), Configuration.BI_PREPARE_PARTS_HELP_DESC); op.acceptsAll(Arrays.asList("f", Configuration.BI_PREPARE_PARTS_FORMAT), Configuration.BI_PREPARE_PARTS_FORMAT_DESC) .withRequiredArg() .describedAs("FORMAT") .ofType(String.class); op.acceptsAll(Arrays.asList("C", Configuration.BI_PREPARE_PARTS_COMPRESSION), Configuration.BI_PREPARE_PARTS_COMPRESSION_DESC) .withRequiredArg() .describedAs("TYPE") .ofType(String.class); op.acceptsAll(Arrays.asList("e", Configuration.BI_PREPARE_PARTS_ENCODING), Configuration.BI_PREPARE_PARTS_ENCODING_DESC) .withRequiredArg() .describedAs("TYPE") .ofType(String.class); op.acceptsAll(Arrays.asList("t", Configuration.BI_PREPARE_PARTS_TIMECOLUMN), Configuration.BI_PREPARE_PARTS_TIMECOLUMN_DESC) .withRequiredArg() .describedAs("NAME") .ofType(String.class); op.acceptsAll(Arrays.asList("T", Configuration.BI_PREPARE_PARTS_TIMEFORMAT), Configuration.BI_PREPARE_PARTS_TIMEFORMAT_DESC) .withRequiredArg() .withValuesSeparatedBy(",") .describedAs("FORMAT") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_TIMEVALUE), Configuration.BI_PREPARE_PARTS_TIMEVALUE_DESC) .withRequiredArg() .describedAs("TIME") .ofType(String.class); op.acceptsAll(Arrays.asList("o", Configuration.BI_PREPARE_PARTS_OUTPUTDIR), Configuration.BI_PREPARE_PARTS_OUTPUTDIR_DESC) .withRequiredArg() .describedAs("DIR") .ofType(String.class); op.acceptsAll(Arrays.asList("s", Configuration.BI_PREPARE_PARTS_SPLIT_SIZE), Configuration.BI_PREPARE_PARTS_SPLIT_SIZE_DESC ) .withRequiredArg() .describedAs("SIZE_IN_KB") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_ERROR_RECORDS_HANDLING), Configuration.BI_PREPARE_PARTS_ERROR_RECORDS_HANDLING_DESC) .withRequiredArg() .describedAs("MODE") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_DELIMITER), Configuration.BI_PREPARE_PARTS_DELIMITER_DESC) .withRequiredArg() .describedAs("CHAR") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_QUOTE), Configuration.BI_PREPARE_PARTS_QUOTE_DESC) .withRequiredArg() .describedAs("CHAR") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_NEWLINE), Configuration.BI_PREPARE_PARTS_NEWLINE_DESC) .withRequiredArg() .describedAs("TYPE") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_COLUMNHEADER), Configuration.BI_PREPARE_PARTS_COLUMNHEADER_DESC); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_COLUMNS), Configuration.BI_PREPARE_PARTS_COLUMNS_DESC) .withRequiredArg() .describedAs("NAME,NAME,...") .ofType(String.class) .withValuesSeparatedBy(","); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_COLUMNTYPES), Configuration.BI_PREPARE_PARTS_COLUMNTYPES_DESC) .withRequiredArg() .describedAs("TYPE,TYPE,...") .ofType(String.class) .withValuesSeparatedBy(","); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_EXCLUDE_COLUMNS), Configuration.BI_PREPARE_PARTS_EXCLUDE_COLUMNS_DESC) .withRequiredArg() .describedAs("NAME,NAME,...") .ofType(String.class) .withValuesSeparatedBy(","); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_ONLY_COLUMNS), Configuration.BI_PREPARE_PARTS_ONLY_COLUMNS_DESC) .withRequiredArg() .describedAs("NAME,NAME,...") .ofType(String.class) .withValuesSeparatedBy(","); + op.acceptsAll(Arrays.asList( + Configuration.BI_PREPARE_PARTS_PARALLEL), + Configuration.BI_PREPARE_PARTS_PARALLEL_DESC) + .withRequiredArg() + .describedAs("NUM") + .ofType(String.class); // mysql op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_JDBC_CONNECTION_URL), Configuration.BI_PREPARE_PARTS_JDBC_CONNECTION_URL_DESC) .withRequiredArg() .describedAs("URL") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_JDBC_USER), Configuration.BI_PREPARE_PARTS_JDBC_USER_DESC) .withRequiredArg() .describedAs("NAME") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_JDBC_PASSWORD), Configuration.BI_PREPARE_PARTS_JDBC_PASSWORD_DESC) .withRequiredArg() .describedAs("NAME") .ofType(String.class); } public void initUploadOptionParser(Properties props) { this.initPrepareOptionParser(props); op.acceptsAll(Arrays.asList( Configuration.BI_UPLOAD_PARTS_AUTO_CREATE), Configuration.BI_UPLOAD_PARTS_AUTO_CREATE_DESC) .withRequiredArg() .describedAs("DATABASE.TABLE") .ofType(String.class) .withValuesSeparatedBy("."); op.acceptsAll(Arrays.asList( Configuration.BI_UPLOAD_PARTS_AUTO_PERFORM), Configuration.BI_UPLOAD_PARTS_AUTO_PERFORM_DESC); op.acceptsAll(Arrays.asList( Configuration.BI_UPLOAD_PARTS_AUTO_COMMIT), Configuration.BI_UPLOAD_PARTS_AUTO_COMMIT_DESC); op.acceptsAll(Arrays.asList( Configuration.BI_UPLOAD_PARTS_PARALLEL), Configuration.BI_UPLOAD_PARTS_PARALLEL_DESC) .withRequiredArg() .describedAs("NUM") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_UPLOAD_PARTS_AUTO_DELETE), Configuration.BI_UPLOAD_PARTS_AUTO_DELETE_DESC); } public void showHelp() throws IOException { // this method should be called after invoking initXXXOptionParser(..) op.printHelpOn(System.out); } public void setOptions(final String[] args) { options = op.parse(args); } public OptionSet getOptions() { return options; } }
true
true
public void initPrepareOptionParser(Properties props) { op.formatHelpWith(new SimpleHelpFormatter()); op.acceptsAll(Arrays.asList("h", Configuration.BI_PREPARE_PARTS_HELP), Configuration.BI_PREPARE_PARTS_HELP_DESC); op.acceptsAll(Arrays.asList("f", Configuration.BI_PREPARE_PARTS_FORMAT), Configuration.BI_PREPARE_PARTS_FORMAT_DESC) .withRequiredArg() .describedAs("FORMAT") .ofType(String.class); op.acceptsAll(Arrays.asList("C", Configuration.BI_PREPARE_PARTS_COMPRESSION), Configuration.BI_PREPARE_PARTS_COMPRESSION_DESC) .withRequiredArg() .describedAs("TYPE") .ofType(String.class); op.acceptsAll(Arrays.asList("e", Configuration.BI_PREPARE_PARTS_ENCODING), Configuration.BI_PREPARE_PARTS_ENCODING_DESC) .withRequiredArg() .describedAs("TYPE") .ofType(String.class); op.acceptsAll(Arrays.asList("t", Configuration.BI_PREPARE_PARTS_TIMECOLUMN), Configuration.BI_PREPARE_PARTS_TIMECOLUMN_DESC) .withRequiredArg() .describedAs("NAME") .ofType(String.class); op.acceptsAll(Arrays.asList("T", Configuration.BI_PREPARE_PARTS_TIMEFORMAT), Configuration.BI_PREPARE_PARTS_TIMEFORMAT_DESC) .withRequiredArg() .withValuesSeparatedBy(",") .describedAs("FORMAT") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_TIMEVALUE), Configuration.BI_PREPARE_PARTS_TIMEVALUE_DESC) .withRequiredArg() .describedAs("TIME") .ofType(String.class); op.acceptsAll(Arrays.asList("o", Configuration.BI_PREPARE_PARTS_OUTPUTDIR), Configuration.BI_PREPARE_PARTS_OUTPUTDIR_DESC) .withRequiredArg() .describedAs("DIR") .ofType(String.class); op.acceptsAll(Arrays.asList("s", Configuration.BI_PREPARE_PARTS_SPLIT_SIZE), Configuration.BI_PREPARE_PARTS_SPLIT_SIZE_DESC ) .withRequiredArg() .describedAs("SIZE_IN_KB") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_ERROR_RECORDS_HANDLING), Configuration.BI_PREPARE_PARTS_ERROR_RECORDS_HANDLING_DESC) .withRequiredArg() .describedAs("MODE") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_DELIMITER), Configuration.BI_PREPARE_PARTS_DELIMITER_DESC) .withRequiredArg() .describedAs("CHAR") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_QUOTE), Configuration.BI_PREPARE_PARTS_QUOTE_DESC) .withRequiredArg() .describedAs("CHAR") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_NEWLINE), Configuration.BI_PREPARE_PARTS_NEWLINE_DESC) .withRequiredArg() .describedAs("TYPE") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_COLUMNHEADER), Configuration.BI_PREPARE_PARTS_COLUMNHEADER_DESC); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_COLUMNS), Configuration.BI_PREPARE_PARTS_COLUMNS_DESC) .withRequiredArg() .describedAs("NAME,NAME,...") .ofType(String.class) .withValuesSeparatedBy(","); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_COLUMNTYPES), Configuration.BI_PREPARE_PARTS_COLUMNTYPES_DESC) .withRequiredArg() .describedAs("TYPE,TYPE,...") .ofType(String.class) .withValuesSeparatedBy(","); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_EXCLUDE_COLUMNS), Configuration.BI_PREPARE_PARTS_EXCLUDE_COLUMNS_DESC) .withRequiredArg() .describedAs("NAME,NAME,...") .ofType(String.class) .withValuesSeparatedBy(","); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_ONLY_COLUMNS), Configuration.BI_PREPARE_PARTS_ONLY_COLUMNS_DESC) .withRequiredArg() .describedAs("NAME,NAME,...") .ofType(String.class) .withValuesSeparatedBy(","); // mysql op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_JDBC_CONNECTION_URL), Configuration.BI_PREPARE_PARTS_JDBC_CONNECTION_URL_DESC) .withRequiredArg() .describedAs("URL") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_JDBC_USER), Configuration.BI_PREPARE_PARTS_JDBC_USER_DESC) .withRequiredArg() .describedAs("NAME") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_JDBC_PASSWORD), Configuration.BI_PREPARE_PARTS_JDBC_PASSWORD_DESC) .withRequiredArg() .describedAs("NAME") .ofType(String.class); }
public void initPrepareOptionParser(Properties props) { op.formatHelpWith(new SimpleHelpFormatter()); op.acceptsAll(Arrays.asList("h", Configuration.BI_PREPARE_PARTS_HELP), Configuration.BI_PREPARE_PARTS_HELP_DESC); op.acceptsAll(Arrays.asList("f", Configuration.BI_PREPARE_PARTS_FORMAT), Configuration.BI_PREPARE_PARTS_FORMAT_DESC) .withRequiredArg() .describedAs("FORMAT") .ofType(String.class); op.acceptsAll(Arrays.asList("C", Configuration.BI_PREPARE_PARTS_COMPRESSION), Configuration.BI_PREPARE_PARTS_COMPRESSION_DESC) .withRequiredArg() .describedAs("TYPE") .ofType(String.class); op.acceptsAll(Arrays.asList("e", Configuration.BI_PREPARE_PARTS_ENCODING), Configuration.BI_PREPARE_PARTS_ENCODING_DESC) .withRequiredArg() .describedAs("TYPE") .ofType(String.class); op.acceptsAll(Arrays.asList("t", Configuration.BI_PREPARE_PARTS_TIMECOLUMN), Configuration.BI_PREPARE_PARTS_TIMECOLUMN_DESC) .withRequiredArg() .describedAs("NAME") .ofType(String.class); op.acceptsAll(Arrays.asList("T", Configuration.BI_PREPARE_PARTS_TIMEFORMAT), Configuration.BI_PREPARE_PARTS_TIMEFORMAT_DESC) .withRequiredArg() .withValuesSeparatedBy(",") .describedAs("FORMAT") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_TIMEVALUE), Configuration.BI_PREPARE_PARTS_TIMEVALUE_DESC) .withRequiredArg() .describedAs("TIME") .ofType(String.class); op.acceptsAll(Arrays.asList("o", Configuration.BI_PREPARE_PARTS_OUTPUTDIR), Configuration.BI_PREPARE_PARTS_OUTPUTDIR_DESC) .withRequiredArg() .describedAs("DIR") .ofType(String.class); op.acceptsAll(Arrays.asList("s", Configuration.BI_PREPARE_PARTS_SPLIT_SIZE), Configuration.BI_PREPARE_PARTS_SPLIT_SIZE_DESC ) .withRequiredArg() .describedAs("SIZE_IN_KB") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_ERROR_RECORDS_HANDLING), Configuration.BI_PREPARE_PARTS_ERROR_RECORDS_HANDLING_DESC) .withRequiredArg() .describedAs("MODE") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_DELIMITER), Configuration.BI_PREPARE_PARTS_DELIMITER_DESC) .withRequiredArg() .describedAs("CHAR") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_QUOTE), Configuration.BI_PREPARE_PARTS_QUOTE_DESC) .withRequiredArg() .describedAs("CHAR") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_NEWLINE), Configuration.BI_PREPARE_PARTS_NEWLINE_DESC) .withRequiredArg() .describedAs("TYPE") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_COLUMNHEADER), Configuration.BI_PREPARE_PARTS_COLUMNHEADER_DESC); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_COLUMNS), Configuration.BI_PREPARE_PARTS_COLUMNS_DESC) .withRequiredArg() .describedAs("NAME,NAME,...") .ofType(String.class) .withValuesSeparatedBy(","); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_COLUMNTYPES), Configuration.BI_PREPARE_PARTS_COLUMNTYPES_DESC) .withRequiredArg() .describedAs("TYPE,TYPE,...") .ofType(String.class) .withValuesSeparatedBy(","); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_EXCLUDE_COLUMNS), Configuration.BI_PREPARE_PARTS_EXCLUDE_COLUMNS_DESC) .withRequiredArg() .describedAs("NAME,NAME,...") .ofType(String.class) .withValuesSeparatedBy(","); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_ONLY_COLUMNS), Configuration.BI_PREPARE_PARTS_ONLY_COLUMNS_DESC) .withRequiredArg() .describedAs("NAME,NAME,...") .ofType(String.class) .withValuesSeparatedBy(","); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_PARALLEL), Configuration.BI_PREPARE_PARTS_PARALLEL_DESC) .withRequiredArg() .describedAs("NUM") .ofType(String.class); // mysql op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_JDBC_CONNECTION_URL), Configuration.BI_PREPARE_PARTS_JDBC_CONNECTION_URL_DESC) .withRequiredArg() .describedAs("URL") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_JDBC_USER), Configuration.BI_PREPARE_PARTS_JDBC_USER_DESC) .withRequiredArg() .describedAs("NAME") .ofType(String.class); op.acceptsAll(Arrays.asList( Configuration.BI_PREPARE_PARTS_JDBC_PASSWORD), Configuration.BI_PREPARE_PARTS_JDBC_PASSWORD_DESC) .withRequiredArg() .describedAs("NAME") .ofType(String.class); }
diff --git a/dbmaintain/src/main/java/org/dbmaintain/dbsupport/impl/MsSqlDbSupport.java b/dbmaintain/src/main/java/org/dbmaintain/dbsupport/impl/MsSqlDbSupport.java index ebe1ab1..a5579ee 100644 --- a/dbmaintain/src/main/java/org/dbmaintain/dbsupport/impl/MsSqlDbSupport.java +++ b/dbmaintain/src/main/java/org/dbmaintain/dbsupport/impl/MsSqlDbSupport.java @@ -1,312 +1,313 @@ /* * Copyright 2006-2007, Unitils.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dbmaintain.dbsupport.impl; import static org.apache.commons.dbutils.DbUtils.closeQuietly; import org.dbmaintain.dbsupport.DbSupport; import org.dbmaintain.dbsupport.SQLHandler; import org.dbmaintain.dbsupport.StoredIdentifierCase; import org.dbmaintain.util.DbMaintainException; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.Set; /** * Implementation of {@link DbSupport} for a MsSQL database. * <p/> * Special thanks to Niki Driessen who donated the initial version of the Derby support code. * * @author Tim Ducheyne * @author Niki Driessen * @author Filip Neven */ public class MsSqlDbSupport extends DbSupport { public MsSqlDbSupport(String databaseName, DataSource dataSource, String defaultSchemaName, Set<String> schemaNames, SQLHandler sqlHandler, String customIdentifierQuoteString, StoredIdentifierCase customStoredIdentifierCase) { super(databaseName, "mssql", dataSource, defaultSchemaName, schemaNames, sqlHandler, customIdentifierQuoteString, customStoredIdentifierCase); } /** * Returns the names of all tables in the database. * * @return The names of all tables in the database */ @Override public Set<String> getTableNames(String schemaName) { return getSQLHandler().getItemsAsStringSet("select t.name from sys.tables t, sys.schemas s where t.schema_id = s.schema_id and s.name = '" + schemaName + "'", getDataSource()); } /** * Gets the names of all columns of the given table. * * @param tableName The table, not null * @return The names of the columns of the table with the given name */ @Override public Set<String> getColumnNames(String schemaName, String tableName) { return getSQLHandler().getItemsAsStringSet("select c.name from sys.columns c, sys.tables t, sys.schemas s where c.object_id = t.object_id and t.name = '" + tableName + "' and t.schema_id = s.schema_id and s.name = '" + schemaName + "'", getDataSource()); } /** * Retrieves the names of all the views in the database schema. * * @return The names of all views in the database */ @Override public Set<String> getViewNames(String schemaName) { return getSQLHandler().getItemsAsStringSet("select v.name from sys.views v, sys.schemas s where v.schema_id = s.schema_id and s.name = '" + schemaName + "'", getDataSource()); } /** * Retrieves the names of all synonyms in the database schema. * * @return The names of all synonyms in the database */ @Override public Set<String> getSynonymNames(String schemaName) { return getSQLHandler().getItemsAsStringSet("select o.name from sys.synonyms o, sys.schemas s where o.schema_id = s.schema_id and s.name = '" + schemaName + "'", getDataSource()); } /** * Retrieves the names of all the triggers in the database schema. * * @return The names of all triggers in the database */ @Override public Set<String> getTriggerNames(String schemaName) { return getSQLHandler().getItemsAsStringSet("select t.name from sys.triggers t, sys.all_objects o, sys.schemas s where t.parent_id = o.object_id and o.schema_id = s.schema_id and s.name = '" + schemaName + "'", getDataSource()); } /** * Retrieves the names of all the types in the database schema. * * @return The names of all types in the database */ @Override public Set<String> getTypeNames(String schemaName) { return getSQLHandler().getItemsAsStringSet("select t.name from sys.types t, sys.schemas s where t.schema_id = s.schema_id and s.name = '" + schemaName + "'", getDataSource()); } /** * Gets the names of all identity columns of the given table. * * @param tableName The table, not null * @return The names of the identity columns of the table with the given name */ @Override public Set<String> getIdentityColumnNames(String schemaName, String tableName) { return getSQLHandler().getItemsAsStringSet("select i.name from sys.identity_columns i, sys.tables t, sys.schemas s where i.object_id = t.object_id and t.name = '" + tableName + "' and t.schema_id = s.schema_id and s.name = '" + schemaName + "'", getDataSource()); } /** * Disables all referential constraints (e.g. foreign keys) on all table in the schema * * @param schemaName The schema name, not null */ @Override public void disableReferentialConstraints(String schemaName) { Set<String> tableNames = getTableNames(schemaName); for (String tableName : tableNames) { disableReferentialConstraints(schemaName, tableName); } } // todo refactor (see oracle) protected void disableReferentialConstraints(String schemaName, String tableName) { SQLHandler sqlHandler = getSQLHandler(); Set<String> constraintNames = sqlHandler.getItemsAsStringSet("select f.name from sys.foreign_keys f, sys.tables t, sys.schemas s where f.parent_object_id = t.object_id and t.name = '" + tableName + "' and t.schema_id = s.schema_id and s.name = '" + schemaName + "'", getDataSource()); for (String constraintName : constraintNames) { sqlHandler.executeUpdate("alter table " + qualified(schemaName, tableName) + " drop constraint " + quoted(constraintName), getDataSource()); } } /** * Disables all value constraints (e.g. not null) on all tables in the schema * * @param schemaName The schema name, not null */ @Override public void disableValueConstraints(String schemaName) { Set<String> tableNames = getTableNames(schemaName); for (String tableName : tableNames) { disableValueConstraints(schemaName, tableName); } } // todo refactor (see oracle) protected void disableValueConstraints(String schemaName, String tableName) { SQLHandler sqlHandler = getSQLHandler(); // disable all unique constraints Set<String> keyConstraintNames = sqlHandler.getItemsAsStringSet("select k.name from sys.key_constraints k, sys.tables t, sys.schemas s where k.type = 'UQ' and k.parent_object_id = t.object_id and t.name = '" + tableName + "' and t.schema_id = s.schema_id and s.name = '" + schemaName + "'", getDataSource()); for (String keyConstraintName : keyConstraintNames) { sqlHandler.executeUpdate("alter table " + qualified(schemaName, tableName) + " drop constraint " + quoted(keyConstraintName), getDataSource()); } // disable all check constraints Set<String> checkConstraintNames = sqlHandler.getItemsAsStringSet("select c.name from sys.check_constraints c, sys.tables t, sys.schemas s where c.parent_object_id = t.object_id and t.name = '" + tableName + "' and t.schema_id = s.schema_id and s.name = '" + schemaName + "'", getDataSource()); for (String checkConstraintName : checkConstraintNames) { sqlHandler.executeUpdate("alter table " + qualified(schemaName, tableName) + " drop constraint " + quoted(checkConstraintName), getDataSource()); } // disable all not null constraints disableNotNullConstraints(schemaName, tableName); } /** * Increments the identity value for the specified identity column on the specified table to the given value. If * there is no identity specified on the given primary key, the method silently finishes without effect. * * @param tableName The table with the identity column, not null * @param identityColumnName The column, not null * @param identityValue The new value */ @Override public void incrementIdentityColumnToValue(String schemaName, String tableName, String identityColumnName, long identityValue) { // there can only be 1 identity column per table getSQLHandler().executeUpdate("DBCC CHECKIDENT ('" + qualified(schemaName, tableName) + "', reseed, " + identityValue + ")", getDataSource()); } /** * Synonyms are supported. * * @return True */ @Override public boolean supportsSynonyms() { return true; } /** * Triggers are supported. * * @return True */ @Override public boolean supportsTriggers() { return true; } /** * Types are supported * * @return true */ @Override public boolean supportsTypes() { return true; } /** * Identity columns are supported. * * @return True */ @Override public boolean supportsIdentityColumns() { return true; } /** * Disables not-null constraints on the given table. * <p/> * For primary keys, row-guid, identity and computed columns not-null constrains cannot be disabled in MS-Sql. * * @param schemaName the schema name, not null * @param tableName The table, not null */ protected void disableNotNullConstraints(String schemaName, String tableName) { SQLHandler sqlHandler = getSQLHandler(); // retrieve the name of the primary key, since we cannot remove the not-null constraint on this column Set<String> primaryKeyColumnNames = sqlHandler.getItemsAsStringSet("select c.name from sys.key_constraints k, sys.index_columns i, sys.columns c, sys.tables t, sys.schemas s " + "where k.type = 'PK' and i.index_id = k.unique_index_id and i.column_id = c.column_id " + " and c.object_id = t.object_id and k.parent_object_id = t.object_id and i.object_id = t.object_id " + " and t.name = '" + tableName + "' and t.schema_id = s.schema_id and s.name = '" + schemaName + "'", getDataSource()); Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = getDataSource().getConnection(); statement = connection.createStatement(); // get all not-null columns but not row-guid, identity and computed columns (these cannot be altered in MS-Sql) - resultSet = statement.executeQuery("select c.name column_name, upper(y.name) data_type, c.max_length, c.precision from sys.types y, sys.columns c, sys.tables t, sys.schemas s " + + resultSet = statement.executeQuery("select c.name column_name, upper(y.name) data_type, c.max_length, c.precision, c.scale from sys.types y, sys.columns c, sys.tables t, sys.schemas s " + "where c.is_nullable = 0 and c.is_rowguidcol = 0 and c.is_identity = 0 and c.is_computed = 0 " + - " and y.user_type_id = c.user_type_id and c.object_id = t.object_id and t.name = '" + tableName + "' and t.schema_id = s.schema_id and s.name = '" + schemaName + "'"); + "and y.user_type_id = c.user_type_id and c.object_id = t.object_id and t.name = '" + tableName + "' and t.schema_id = s.schema_id and s.name = '" + schemaName + "'"); while (resultSet.next()) { String columnName = resultSet.getString("column_name"); if (primaryKeyColumnNames.contains(columnName)) { // skip primary key columns continue; } String dataType = resultSet.getString("data_type"); if ("TIMESTAMP".equals(dataType)) { // timestamp columns cannot be altered in MS-Sql continue; } // handle data types that require a length and precision if ("NUMERIC".equals(dataType) || "DECIMAL".equals(dataType)) { - String maxLength = resultSet.getString("max_length"); String precision = resultSet.getString("precision"); - dataType += "(" + maxLength + ", " + precision + ")"; + /* Patch provided by Jan Ischebeck */ + String scale = resultSet.getString("scale"); + dataType += "(" + precision + ", " + scale + ")"; } else if (dataType.contains("CHAR")) { String maxLength = resultSet.getString("max_length"); /* Patch provided by Thomas Queste */ // NChar or NVarchar always count as the double of their real size in the sys.columns table // that means we should divide this value by two to have a correct size. if (dataType.equals("NCHAR") || dataType.equals("NVARCHAR")) { maxLength = String.valueOf(Integer.parseInt(maxLength) / 2); } dataType += "(" + maxLength + ")"; } // remove the not-null constraint sqlHandler.executeUpdate("alter table " + qualified(schemaName, tableName) + " alter column " + quoted(columnName) + " " + dataType + " null", getDataSource()); } } catch (Exception e) { throw new DbMaintainException("Error while disabling not null constraints. Table name: " + tableName, e); } finally { closeQuietly(connection, statement, resultSet); } } }
false
true
protected void disableNotNullConstraints(String schemaName, String tableName) { SQLHandler sqlHandler = getSQLHandler(); // retrieve the name of the primary key, since we cannot remove the not-null constraint on this column Set<String> primaryKeyColumnNames = sqlHandler.getItemsAsStringSet("select c.name from sys.key_constraints k, sys.index_columns i, sys.columns c, sys.tables t, sys.schemas s " + "where k.type = 'PK' and i.index_id = k.unique_index_id and i.column_id = c.column_id " + " and c.object_id = t.object_id and k.parent_object_id = t.object_id and i.object_id = t.object_id " + " and t.name = '" + tableName + "' and t.schema_id = s.schema_id and s.name = '" + schemaName + "'", getDataSource()); Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = getDataSource().getConnection(); statement = connection.createStatement(); // get all not-null columns but not row-guid, identity and computed columns (these cannot be altered in MS-Sql) resultSet = statement.executeQuery("select c.name column_name, upper(y.name) data_type, c.max_length, c.precision from sys.types y, sys.columns c, sys.tables t, sys.schemas s " + "where c.is_nullable = 0 and c.is_rowguidcol = 0 and c.is_identity = 0 and c.is_computed = 0 " + " and y.user_type_id = c.user_type_id and c.object_id = t.object_id and t.name = '" + tableName + "' and t.schema_id = s.schema_id and s.name = '" + schemaName + "'"); while (resultSet.next()) { String columnName = resultSet.getString("column_name"); if (primaryKeyColumnNames.contains(columnName)) { // skip primary key columns continue; } String dataType = resultSet.getString("data_type"); if ("TIMESTAMP".equals(dataType)) { // timestamp columns cannot be altered in MS-Sql continue; } // handle data types that require a length and precision if ("NUMERIC".equals(dataType) || "DECIMAL".equals(dataType)) { String maxLength = resultSet.getString("max_length"); String precision = resultSet.getString("precision"); dataType += "(" + maxLength + ", " + precision + ")"; } else if (dataType.contains("CHAR")) { String maxLength = resultSet.getString("max_length"); /* Patch provided by Thomas Queste */ // NChar or NVarchar always count as the double of their real size in the sys.columns table // that means we should divide this value by two to have a correct size. if (dataType.equals("NCHAR") || dataType.equals("NVARCHAR")) { maxLength = String.valueOf(Integer.parseInt(maxLength) / 2); } dataType += "(" + maxLength + ")"; } // remove the not-null constraint sqlHandler.executeUpdate("alter table " + qualified(schemaName, tableName) + " alter column " + quoted(columnName) + " " + dataType + " null", getDataSource()); } } catch (Exception e) { throw new DbMaintainException("Error while disabling not null constraints. Table name: " + tableName, e); } finally { closeQuietly(connection, statement, resultSet); } }
protected void disableNotNullConstraints(String schemaName, String tableName) { SQLHandler sqlHandler = getSQLHandler(); // retrieve the name of the primary key, since we cannot remove the not-null constraint on this column Set<String> primaryKeyColumnNames = sqlHandler.getItemsAsStringSet("select c.name from sys.key_constraints k, sys.index_columns i, sys.columns c, sys.tables t, sys.schemas s " + "where k.type = 'PK' and i.index_id = k.unique_index_id and i.column_id = c.column_id " + " and c.object_id = t.object_id and k.parent_object_id = t.object_id and i.object_id = t.object_id " + " and t.name = '" + tableName + "' and t.schema_id = s.schema_id and s.name = '" + schemaName + "'", getDataSource()); Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = getDataSource().getConnection(); statement = connection.createStatement(); // get all not-null columns but not row-guid, identity and computed columns (these cannot be altered in MS-Sql) resultSet = statement.executeQuery("select c.name column_name, upper(y.name) data_type, c.max_length, c.precision, c.scale from sys.types y, sys.columns c, sys.tables t, sys.schemas s " + "where c.is_nullable = 0 and c.is_rowguidcol = 0 and c.is_identity = 0 and c.is_computed = 0 " + "and y.user_type_id = c.user_type_id and c.object_id = t.object_id and t.name = '" + tableName + "' and t.schema_id = s.schema_id and s.name = '" + schemaName + "'"); while (resultSet.next()) { String columnName = resultSet.getString("column_name"); if (primaryKeyColumnNames.contains(columnName)) { // skip primary key columns continue; } String dataType = resultSet.getString("data_type"); if ("TIMESTAMP".equals(dataType)) { // timestamp columns cannot be altered in MS-Sql continue; } // handle data types that require a length and precision if ("NUMERIC".equals(dataType) || "DECIMAL".equals(dataType)) { String precision = resultSet.getString("precision"); /* Patch provided by Jan Ischebeck */ String scale = resultSet.getString("scale"); dataType += "(" + precision + ", " + scale + ")"; } else if (dataType.contains("CHAR")) { String maxLength = resultSet.getString("max_length"); /* Patch provided by Thomas Queste */ // NChar or NVarchar always count as the double of their real size in the sys.columns table // that means we should divide this value by two to have a correct size. if (dataType.equals("NCHAR") || dataType.equals("NVARCHAR")) { maxLength = String.valueOf(Integer.parseInt(maxLength) / 2); } dataType += "(" + maxLength + ")"; } // remove the not-null constraint sqlHandler.executeUpdate("alter table " + qualified(schemaName, tableName) + " alter column " + quoted(columnName) + " " + dataType + " null", getDataSource()); } } catch (Exception e) { throw new DbMaintainException("Error while disabling not null constraints. Table name: " + tableName, e); } finally { closeQuietly(connection, statement, resultSet); } }
diff --git a/src/capstone/daemon/DaemonHandler.java b/src/capstone/daemon/DaemonHandler.java index 921bf6c..39dd6a7 100644 --- a/src/capstone/daemon/DaemonHandler.java +++ b/src/capstone/daemon/DaemonHandler.java @@ -1,135 +1,135 @@ package capstone.daemon; import capstone.wrapper.*; import java.util.HashMap; import java.net.URLDecoder; import io.netty.buffer.*; import io.netty.util.CharsetUtil; import io.netty.channel.*; import io.netty.handler.codec.http.*; import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpHeaders.*; import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpVersion.*; public class DaemonHandler extends ChannelInboundMessageHandlerAdapter<DefaultFullHttpRequest> { /** * Format for the key is: "userId_debuggerId" */ static HashMap<String,Wrapper> wrapperMap = new HashMap<String,Wrapper>(); static HashMap<String,String> sessionKeyMap = new HashMap<String,String>(); @Override public void endMessageReceived(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void messageReceived( ChannelHandlerContext ctx , DefaultFullHttpRequest request) { System.out.println("[Daemon] Connection started"); String body = request.data().toString(CharsetUtil.UTF_8); try { HashMap<String, String> args = parseBody(body); // TODO add session tokens // TODO add specifier of C++ vs Python String userId = args.get("usrid"); String debuggerId = args.get("dbgid"); String wrapperKey = userId + "_" + debuggerId; String commandString = args.get("call"); DebuggerCommand command = DebuggerCommand.fromString(commandString); String data = args.get("data"); if (data == null) { data = ""; } DebuggerRequest debuggerRequest = new DebuggerRequest(command, data); // TODO determine the cases when we want to create a new one Wrapper wrapper = wrapperMap.get(wrapperKey); // FIXME synchronize on the session key if (wrapper == null) { // TODO switch off of language here wrapper = new GdbWrapper(Integer.parseInt(userId), Integer.parseInt(debuggerId)); wrapper.start(); wrapperMap.put(wrapperKey, wrapper); // FIXME data race here } System.out.println("[daemon] Submitting a request..."); if (debuggerRequest.command == DebuggerCommand.GIVEINPUT) { wrapper.provideInput(debuggerRequest.data); debuggerRequest.result = ""; } else { - wrapper.submitRequest(debuggerRequest); System.out.println("[daemon] Waiting on the monitor..."); synchronized (debuggerRequest.monitor) { + wrapper.submitRequest(debuggerRequest); debuggerRequest.monitor.wait(); } System.out.println("[daemon] Woke up!"); } System.out.println("[daemon] Got result: " + debuggerRequest.result); FullHttpResponse response = new DefaultFullHttpResponse( HTTP_1_1, OK, Unpooled.copiedBuffer(debuggerRequest.result , CharsetUtil.UTF_8)); response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); response.headers().set(CONTENT_LENGTH, debuggerRequest.result.length()); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); ctx.nextOutboundMessageBuffer().add(response); ctx.flush().addListener(ChannelFutureListener.CLOSE); } catch(Exception e) { System.out.println("[daemon] Got an exception. Printing the stack trace:"); e.printStackTrace(); } } private HashMap<String, String> parseBody(String body) throws Exception // FIXME change to right exception type { HashMap<String, String> args = new HashMap<String, String>(); if(body.length() > 0) { System.out.println("[daemon] parsing: " + body); String[] tokens = body.split("&"); for(String token : tokens) { String[] kvp = token.split("=",2); args.put(URLDecoder.decode(kvp[0], "UTF-8") ,URLDecoder.decode(kvp[1], "UTF-8")); } } return args; } @Override public void exceptionCaught( ChannelHandlerContext ctx , Throwable cause) { cause.printStackTrace(); ctx.close(); } }
false
true
public void messageReceived( ChannelHandlerContext ctx , DefaultFullHttpRequest request) { System.out.println("[Daemon] Connection started"); String body = request.data().toString(CharsetUtil.UTF_8); try { HashMap<String, String> args = parseBody(body); // TODO add session tokens // TODO add specifier of C++ vs Python String userId = args.get("usrid"); String debuggerId = args.get("dbgid"); String wrapperKey = userId + "_" + debuggerId; String commandString = args.get("call"); DebuggerCommand command = DebuggerCommand.fromString(commandString); String data = args.get("data"); if (data == null) { data = ""; } DebuggerRequest debuggerRequest = new DebuggerRequest(command, data); // TODO determine the cases when we want to create a new one Wrapper wrapper = wrapperMap.get(wrapperKey); // FIXME synchronize on the session key if (wrapper == null) { // TODO switch off of language here wrapper = new GdbWrapper(Integer.parseInt(userId), Integer.parseInt(debuggerId)); wrapper.start(); wrapperMap.put(wrapperKey, wrapper); // FIXME data race here } System.out.println("[daemon] Submitting a request..."); if (debuggerRequest.command == DebuggerCommand.GIVEINPUT) { wrapper.provideInput(debuggerRequest.data); debuggerRequest.result = ""; } else { wrapper.submitRequest(debuggerRequest); System.out.println("[daemon] Waiting on the monitor..."); synchronized (debuggerRequest.monitor) { debuggerRequest.monitor.wait(); } System.out.println("[daemon] Woke up!"); } System.out.println("[daemon] Got result: " + debuggerRequest.result); FullHttpResponse response = new DefaultFullHttpResponse( HTTP_1_1, OK, Unpooled.copiedBuffer(debuggerRequest.result , CharsetUtil.UTF_8)); response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); response.headers().set(CONTENT_LENGTH, debuggerRequest.result.length()); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); ctx.nextOutboundMessageBuffer().add(response); ctx.flush().addListener(ChannelFutureListener.CLOSE); } catch(Exception e) { System.out.println("[daemon] Got an exception. Printing the stack trace:"); e.printStackTrace(); } }
public void messageReceived( ChannelHandlerContext ctx , DefaultFullHttpRequest request) { System.out.println("[Daemon] Connection started"); String body = request.data().toString(CharsetUtil.UTF_8); try { HashMap<String, String> args = parseBody(body); // TODO add session tokens // TODO add specifier of C++ vs Python String userId = args.get("usrid"); String debuggerId = args.get("dbgid"); String wrapperKey = userId + "_" + debuggerId; String commandString = args.get("call"); DebuggerCommand command = DebuggerCommand.fromString(commandString); String data = args.get("data"); if (data == null) { data = ""; } DebuggerRequest debuggerRequest = new DebuggerRequest(command, data); // TODO determine the cases when we want to create a new one Wrapper wrapper = wrapperMap.get(wrapperKey); // FIXME synchronize on the session key if (wrapper == null) { // TODO switch off of language here wrapper = new GdbWrapper(Integer.parseInt(userId), Integer.parseInt(debuggerId)); wrapper.start(); wrapperMap.put(wrapperKey, wrapper); // FIXME data race here } System.out.println("[daemon] Submitting a request..."); if (debuggerRequest.command == DebuggerCommand.GIVEINPUT) { wrapper.provideInput(debuggerRequest.data); debuggerRequest.result = ""; } else { System.out.println("[daemon] Waiting on the monitor..."); synchronized (debuggerRequest.monitor) { wrapper.submitRequest(debuggerRequest); debuggerRequest.monitor.wait(); } System.out.println("[daemon] Woke up!"); } System.out.println("[daemon] Got result: " + debuggerRequest.result); FullHttpResponse response = new DefaultFullHttpResponse( HTTP_1_1, OK, Unpooled.copiedBuffer(debuggerRequest.result , CharsetUtil.UTF_8)); response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); response.headers().set(CONTENT_LENGTH, debuggerRequest.result.length()); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); ctx.nextOutboundMessageBuffer().add(response); ctx.flush().addListener(ChannelFutureListener.CLOSE); } catch(Exception e) { System.out.println("[daemon] Got an exception. Printing the stack trace:"); e.printStackTrace(); } }
diff --git a/src/de/aidger/view/models/TableModel.java b/src/de/aidger/view/models/TableModel.java index 18f5dc68..fea0affa 100644 --- a/src/de/aidger/view/models/TableModel.java +++ b/src/de/aidger/view/models/TableModel.java @@ -1,176 +1,176 @@ package de.aidger.view.models; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Observer; import javax.swing.table.DefaultTableModel; import de.aidger.model.AbstractModel; import de.unistuttgart.iste.se.adohive.exceptions.AdoHiveException; /** * The class represents the abstract table model. * * @author aidGer Team */ @SuppressWarnings("serial") public abstract class TableModel extends DefaultTableModel implements Observer { /** * The static map of models. Each data type has its own list of models. */ @SuppressWarnings("unchecked") protected static Map<String, List<AbstractModel>> mapModels = new HashMap<String, List<AbstractModel>>(); /** * The data type specific models that are displayed on the table. */ @SuppressWarnings("unchecked") protected List<AbstractModel> models; /** * The model before it was edited. */ @SuppressWarnings("unchecked") private AbstractModel modelBeforeEdit; /** * Constructs the table model. */ @SuppressWarnings("unchecked") public TableModel(String[] columnNames) { setColumnIdentifiers(columnNames); String className = this.getClass().getName(); // get all models just once from database if (mapModels.get(className) == null) { models = new ArrayList<AbstractModel>(); mapModels.put(className, models); getAllModels(); } else { // models are already gotten models = mapModels.get(className); } refresh(); } /** * Converts the model to a row. * * @param model * the model that will be converted * @return the row that is converted from the model */ @SuppressWarnings("unchecked") protected abstract Object[] convertModelToRow(AbstractModel model); /** * Gets all models from database and stores them in the table model. */ protected abstract void getAllModels(); /** * Returns the model at the given index. * * @return the model at the given index */ @SuppressWarnings("unchecked") public AbstractModel getModel(int i) { return models.get(i); } /** * Sets the model before it was edited. * * @param m * the model before it was edited */ @SuppressWarnings("unchecked") public void setModelBeforeEdit(AbstractModel m) { modelBeforeEdit = m; } /** * Returns the model before it was edited. * * @return the model before it was edited */ @SuppressWarnings("unchecked") public AbstractModel getModelBeforeEdit() { return modelBeforeEdit; } /** * Refreshes the table. */ @SuppressWarnings("unchecked") private void refresh() { getDataVector().removeAllElements(); fireTableDataChanged(); for (AbstractModel model : models) { // each model is observed by the table model model.addObserver(this); // each model is added as a row to the table addRow(convertModelToRow(model)); } fireTableDataChanged(); } /* * (non-Javadoc) * * @see java.util.Observer#update(java.util.Observable, java.lang.Object) */ @SuppressWarnings("unchecked") @Override public void update(Observable m, Object arg) { AbstractModel model = (AbstractModel) m; Boolean save = (Boolean) arg; try { if (save) { // the model was added - if (models.size() != model.size()) { + if (models.size() < model.size()) { models.add(model); } else { // the model was edited if (!models.contains(model)) { models.remove(modelBeforeEdit); models.add(model); } } } else { // the model was removed models.remove(model); } // refresh only the table refresh(); } catch (AdoHiveException e) { } } /* * (non-Javadoc) * * @see javax.swing.table.DefaultTableModel#isCellEditable(int, int) */ @Override public boolean isCellEditable(int row, int col) { return false; } }
true
true
public void update(Observable m, Object arg) { AbstractModel model = (AbstractModel) m; Boolean save = (Boolean) arg; try { if (save) { // the model was added if (models.size() != model.size()) { models.add(model); } else { // the model was edited if (!models.contains(model)) { models.remove(modelBeforeEdit); models.add(model); } } } else { // the model was removed models.remove(model); } // refresh only the table refresh(); } catch (AdoHiveException e) { } }
public void update(Observable m, Object arg) { AbstractModel model = (AbstractModel) m; Boolean save = (Boolean) arg; try { if (save) { // the model was added if (models.size() < model.size()) { models.add(model); } else { // the model was edited if (!models.contains(model)) { models.remove(modelBeforeEdit); models.add(model); } } } else { // the model was removed models.remove(model); } // refresh only the table refresh(); } catch (AdoHiveException e) { } }
diff --git a/Cojen/src/java/cojen/classfile/CodeDisassembler.java b/Cojen/src/java/cojen/classfile/CodeDisassembler.java index e896917..6d177ba 100644 --- a/Cojen/src/java/cojen/classfile/CodeDisassembler.java +++ b/Cojen/src/java/cojen/classfile/CodeDisassembler.java @@ -1,1622 +1,1623 @@ /* * Copyright 2004 Brian S O'Neill * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cojen.classfile; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import cojen.classfile.attribute.CodeAttr; import cojen.classfile.constant.ConstantClassInfo; import cojen.classfile.constant.ConstantDoubleInfo; import cojen.classfile.constant.ConstantFieldInfo; import cojen.classfile.constant.ConstantFloatInfo; import cojen.classfile.constant.ConstantIntegerInfo; import cojen.classfile.constant.ConstantInterfaceMethodInfo; import cojen.classfile.constant.ConstantLongInfo; import cojen.classfile.constant.ConstantMethodInfo; import cojen.classfile.constant.ConstantNameAndTypeInfo; import cojen.classfile.constant.ConstantStringInfo; /** * Disassembles a method into a CodeAssembler, which acts as a visitor. * * @author Brian S O'Neill */ public class CodeDisassembler { private final MethodInfo mMethod; private final String mEnclosingClassName; private final String mSuperClassName; private final CodeAttr mCode; private final ConstantPool mCp; private final byte[] mByteCodes; private final ExceptionHandler[] mExceptionHandlers; // Current CodeAssembler in use for disassembly. private CodeAssembler mAssembler; // List of all the LocalVariable objects in use. private Vector mLocals; // True if the method being decompiled still has a "this" reference. private boolean mHasThis; private Location mReturnLocation; // Maps Integer address keys to itself, but to Label objects after first // needed. private Map mLabels; // Maps Integer catch locations to Lists of ExceptionHandler objects. private Map mCatchLocations; // Current address being decompiled. private int mAddress; /** * @throws IllegalArgumentException if method has no code */ public CodeDisassembler(MethodInfo method) throws IllegalArgumentException { mMethod = method; mEnclosingClassName = method.getClassFile().getClassName(); mSuperClassName = method.getClassFile().getSuperClassName(); if ((mCode = method.getCodeAttr()) == null) { throw new IllegalArgumentException("Method defines no code"); } mCp = mCode.getConstantPool(); CodeBuffer buffer = mCode.getCodeBuffer(); mByteCodes = buffer.getByteCodes(); mExceptionHandlers = buffer.getExceptionHandlers(); } /** * Disassemble the MethodInfo into the given assembler. * * @see CodeAssemblerPrinter */ public void disassemble(CodeAssembler assembler) { disassemble(assembler, null, null); } /** * Disassemble the MethodInfo into the given assembler. * * @param params if not null, override the local variables which hold parameter values * @param returnLocation if not null, disassemble will branch to this location upon seeing * a return, leaving any arguments on the stack * @see CodeAssemblerPrinter */ public synchronized void disassemble(CodeAssembler assembler, LocalVariable[] params, Location returnLocation) { mAssembler = assembler; mLocals = new Vector(); if (mHasThis = !mMethod.getModifiers().isStatic()) { // Reserve a slot for "this" parameter. mLocals.add(null); } gatherLabels(); // Gather the local variables of the parameters. { TypeDesc[] paramTypes = mMethod.getMethodDescriptor().getParameterTypes(); if (params == null) { params = new LocalVariable[assembler.getParameterCount()]; for (int i=params.length; --i>=0; ) { params[i] = assembler.getParameter(i); } } if (paramTypes.length != params.length) { throw new IllegalArgumentException ("Method parameter count doesn't match given parameter count: " + paramTypes.length + " != " + params.length); } for (int i=0; i<paramTypes.length; i++) { LocalVariable paramVar = params[i]; if (!compatibleType(paramTypes[i], paramVar.getType())) { throw new IllegalArgumentException ("Method parameter type is not compatible with given type: " + paramTypes[i] + " != " + paramVar.getType()); } mLocals.add(paramVar); if (paramVar.getType().isDoubleWord()) { // Reserve slot for least significant word. mLocals.add(null); } } } mReturnLocation = returnLocation; Location currentLoc = new Location() { public int getLocation() { return mAddress; } public int compareTo(Object obj) { if (this == obj) { return 0; } Location other = (Location)obj; int loca = getLocation(); int locb = other.getLocation(); if (loca < locb) { return -1; } else if (loca > locb) { return 1; } else { return 0; } } }; int currentLine = -1; for (mAddress = 0; mAddress < mByteCodes.length; mAddress++) { int nextLine = mCode.getLineNumber(currentLoc); if (nextLine != currentLine) { if ((currentLine = nextLine) >= 0) { mAssembler.mapLineNumber(currentLine); } } // Check if a label needs to be created and/or located. locateLabel(); byte opcode = mByteCodes[mAddress]; int index; Location loc; TypeDesc type; ConstantInfo ci; switch (opcode) { default: error(opcode, "Unknown opcode: " + (opcode & 0xff)); break; // Opcodes with no operands... case Opcode.NOP: assembler.nop(); break; case Opcode.BREAKPOINT: assembler.breakpoint(); break; case Opcode.ACONST_NULL: assembler.loadNull(); break; case Opcode.ICONST_M1: assembler.loadConstant(-1); break; case Opcode.ICONST_0: assembler.loadConstant(0); break; case Opcode.ICONST_1: assembler.loadConstant(1); break; case Opcode.ICONST_2: assembler.loadConstant(2); break; case Opcode.ICONST_3: assembler.loadConstant(3); break; case Opcode.ICONST_4: assembler.loadConstant(4); break; case Opcode.ICONST_5: assembler.loadConstant(5); break; case Opcode.LCONST_0: assembler.loadConstant(0L); break; case Opcode.LCONST_1: assembler.loadConstant(1L); break; case Opcode.FCONST_0: assembler.loadConstant(0f); break; case Opcode.FCONST_1: assembler.loadConstant(1f); break; case Opcode.FCONST_2: assembler.loadConstant(2f); break; case Opcode.DCONST_0: assembler.loadConstant(0d); break; case Opcode.DCONST_1: assembler.loadConstant(1d); break; case Opcode.POP: assembler.pop(); break; case Opcode.POP2: assembler.pop2(); break; case Opcode.DUP: assembler.dup(); break; case Opcode.DUP_X1: assembler.dupX1(); break; case Opcode.DUP_X2: assembler.dupX2(); break; case Opcode.DUP2: assembler.dup2(); break; case Opcode.DUP2_X1: assembler.dup2X2(); break; case Opcode.DUP2_X2: assembler.dup2X2(); break; case Opcode.SWAP: assembler.swap(); break; case Opcode.IADD: case Opcode.LADD: case Opcode.FADD: case Opcode.DADD: case Opcode.ISUB: case Opcode.LSUB: case Opcode.FSUB: case Opcode.DSUB: case Opcode.IMUL: case Opcode.LMUL: case Opcode.FMUL: case Opcode.DMUL: case Opcode.IDIV: case Opcode.LDIV: case Opcode.FDIV: case Opcode.DDIV: case Opcode.IREM: case Opcode.LREM: case Opcode.FREM: case Opcode.DREM: case Opcode.INEG: case Opcode.LNEG: case Opcode.FNEG: case Opcode.DNEG: case Opcode.ISHL: case Opcode.LSHL: case Opcode.ISHR: case Opcode.LSHR: case Opcode.IUSHR: case Opcode.LUSHR: case Opcode.IAND: case Opcode.LAND: case Opcode.IOR: case Opcode.LOR: case Opcode.IXOR: case Opcode.LXOR: case Opcode.FCMPL: case Opcode.DCMPL: case Opcode.FCMPG: case Opcode.DCMPG: case Opcode.LCMP: assembler.math(opcode); break; case Opcode.I2L: assembler.convert(TypeDesc.INT, TypeDesc.LONG); break; case Opcode.I2F: assembler.convert(TypeDesc.INT, TypeDesc.FLOAT); break; case Opcode.I2D: assembler.convert(TypeDesc.INT, TypeDesc.DOUBLE); break; case Opcode.L2I: assembler.convert(TypeDesc.LONG, TypeDesc.INT); break; case Opcode.L2F: assembler.convert(TypeDesc.LONG, TypeDesc.FLOAT); break; case Opcode.L2D: assembler.convert(TypeDesc.LONG, TypeDesc.DOUBLE); break; case Opcode.F2I: assembler.convert(TypeDesc.FLOAT, TypeDesc.INT); break; case Opcode.F2L: assembler.convert(TypeDesc.FLOAT, TypeDesc.LONG); break; case Opcode.F2D: assembler.convert(TypeDesc.FLOAT, TypeDesc.DOUBLE); break; case Opcode.D2I: assembler.convert(TypeDesc.DOUBLE, TypeDesc.INT); break; case Opcode.D2L: assembler.convert(TypeDesc.DOUBLE, TypeDesc.LONG); break; case Opcode.D2F: assembler.convert(TypeDesc.DOUBLE, TypeDesc.FLOAT); break; case Opcode.I2B: assembler.convert(TypeDesc.INT, TypeDesc.BYTE); break; case Opcode.I2C: assembler.convert(TypeDesc.INT, TypeDesc.CHAR); break; case Opcode.I2S: assembler.convert(TypeDesc.INT, TypeDesc.SHORT); break; case Opcode.IRETURN: case Opcode.LRETURN: case Opcode.FRETURN: case Opcode.DRETURN: case Opcode.ARETURN: case Opcode.RETURN: if (mReturnLocation != null) { assembler.branch(mReturnLocation); } else { switch (opcode) { case Opcode.IRETURN: assembler.returnValue(TypeDesc.INT); break; case Opcode.LRETURN: assembler.returnValue(TypeDesc.LONG); break; case Opcode.FRETURN: assembler.returnValue(TypeDesc.FLOAT); break; case Opcode.DRETURN: assembler.returnValue(TypeDesc.DOUBLE); break; case Opcode.ARETURN: assembler.returnValue(TypeDesc.OBJECT); break; case Opcode.RETURN: assembler.returnVoid(); break; } } break; case Opcode.IALOAD: assembler.loadFromArray(TypeDesc.INT); break; case Opcode.LALOAD: assembler.loadFromArray(TypeDesc.LONG); break; case Opcode.FALOAD: assembler.loadFromArray(TypeDesc.FLOAT); break; case Opcode.DALOAD: assembler.loadFromArray(TypeDesc.DOUBLE); break; case Opcode.AALOAD: assembler.loadFromArray(TypeDesc.OBJECT); break; case Opcode.BALOAD: assembler.loadFromArray(TypeDesc.BYTE); break; case Opcode.CALOAD: assembler.loadFromArray(TypeDesc.CHAR); break; case Opcode.SALOAD: assembler.loadFromArray(TypeDesc.SHORT); break; case Opcode.IASTORE: assembler.storeToArray(TypeDesc.INT); break; case Opcode.LASTORE: assembler.storeToArray(TypeDesc.LONG); break; case Opcode.FASTORE: assembler.storeToArray(TypeDesc.FLOAT); break; case Opcode.DASTORE: assembler.storeToArray(TypeDesc.DOUBLE); break; case Opcode.AASTORE: assembler.storeToArray(TypeDesc.OBJECT); break; case Opcode.BASTORE: assembler.storeToArray(TypeDesc.BYTE); break; case Opcode.CASTORE: assembler.storeToArray(TypeDesc.CHAR); break; case Opcode.SASTORE: assembler.storeToArray(TypeDesc.SHORT); break; case Opcode.ARRAYLENGTH: assembler.arrayLength(); break; case Opcode.ATHROW: assembler.throwObject(); break; case Opcode.MONITORENTER: assembler.monitorEnter(); break; case Opcode.MONITOREXIT: assembler.monitorExit(); break; // End opcodes with no operands. // Opcodes that load a constant from the constant pool... case Opcode.LDC: case Opcode.LDC_W: case Opcode.LDC2_W: switch (opcode) { case Opcode.LDC: index = readUnsignedByte(); break; case Opcode.LDC_W: case Opcode.LDC2_W: index = readUnsignedShort(); break; default: index = 0; break; } try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (ci instanceof ConstantStringInfo) { assembler.loadConstant(((ConstantStringInfo)ci).getValue()); } else if (ci instanceof ConstantIntegerInfo) { assembler.loadConstant(((ConstantIntegerInfo)ci).getValue()); } else if (ci instanceof ConstantLongInfo) { assembler.loadConstant(((ConstantLongInfo)ci).getValue()); } else if (ci instanceof ConstantFloatInfo) { assembler.loadConstant(((ConstantFloatInfo)ci).getValue()); } else if (ci instanceof ConstantDoubleInfo) { assembler.loadConstant(((ConstantDoubleInfo)ci).getValue()); } else if (ci instanceof ConstantClassInfo) { assembler.loadConstant(((ConstantClassInfo)ci).getType()); } else { error(opcode, "Invalid constant type for load: " + ci); } break; case Opcode.NEW: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (ci instanceof ConstantClassInfo) { assembler.newObject(((ConstantClassInfo)ci).getType()); } else { error(opcode, "Invalid constant type for new: " + ci); } break; case Opcode.ANEWARRAY: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (ci instanceof ConstantClassInfo) { type = ((ConstantClassInfo)ci).getType().toArrayType(); assembler.newObject(type); } else { error(opcode, "Invalid constant type for new: " + ci); } break; case Opcode.MULTIANEWARRAY: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } int dims = readUnsignedByte(); if (ci instanceof ConstantClassInfo) { type = ((ConstantClassInfo)ci).getType(); assembler.newObject(type, dims); } else { error(opcode, "Invalid constant type for new: " + ci); } break; case Opcode.CHECKCAST: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (ci instanceof ConstantClassInfo) { assembler.checkCast(((ConstantClassInfo)ci).getType()); } else { error(opcode, "Invalid constant type for checkcast: " + ci); } break; case Opcode.INSTANCEOF: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (ci instanceof ConstantClassInfo) { assembler.instanceOf(((ConstantClassInfo)ci).getType()); } else { error(opcode, "Invalid constant type for instanceof: " + ci); } break; case Opcode.GETSTATIC: case Opcode.PUTSTATIC: case Opcode.GETFIELD: case Opcode.PUTFIELD: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (!(ci instanceof ConstantFieldInfo)) { error(opcode, "Invalid constant type for field access: " + ci); break; } ConstantFieldInfo field = (ConstantFieldInfo)ci; String className = field.getParentClass().getType().getRootName(); if (mEnclosingClassName.equals(className)) { className = null; } String fieldName = field.getNameAndType().getName(); Descriptor desc = field.getNameAndType().getType(); if (!(desc instanceof TypeDesc)) { error(opcode, "Invalid descriptor for field access: " + desc); break; } else { type = (TypeDesc)desc; } // Implementation note: Although it may seem convenient if the // CodeAssembler had methods that accepted ConstantFieldInfo // objects as parameters, it would cause problems because // ConstantPools are not portable between ClassFiles. switch (opcode) { case Opcode.GETSTATIC: if (className == null) { assembler.loadStaticField(fieldName, type); } else { assembler.loadStaticField(className, fieldName, type); } break; case Opcode.PUTSTATIC: if (className == null) { assembler.storeStaticField(fieldName, type); } else { assembler.storeStaticField(className, fieldName, type); } break; case Opcode.GETFIELD: if (className == null) { assembler.loadField(fieldName, type); } else { assembler.loadField(className, fieldName, type); } break; case Opcode.PUTFIELD: if (className == null) { assembler.storeField(fieldName, type); } else { assembler.storeField(className, fieldName, type); } break; } break; case Opcode.INVOKEVIRTUAL: case Opcode.INVOKESPECIAL: case Opcode.INVOKESTATIC: case Opcode.INVOKEINTERFACE: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } ConstantNameAndTypeInfo nameAndType; if (opcode == Opcode.INVOKEINTERFACE) { // Read and ignore nargs and padding byte. readShort(); if (!(ci instanceof ConstantInterfaceMethodInfo)) { error(opcode, "Invalid constant type for method invocation: " + ci); break; } ConstantInterfaceMethodInfo method = (ConstantInterfaceMethodInfo)ci; className = method.getParentClass().getType().getRootName(); nameAndType = method.getNameAndType(); } else { if (!(ci instanceof ConstantMethodInfo)) { error(opcode, "Invalid constant type for method invocation: " + ci); break; } ConstantMethodInfo method = (ConstantMethodInfo)ci; className = method.getParentClass().getType().getRootName(); if (mEnclosingClassName.equals(className)) { className = null; } nameAndType = method.getNameAndType(); } String methodName = nameAndType.getName(); desc = nameAndType.getType(); if (!(desc instanceof MethodDesc)) { error(opcode, "Invalid descriptor for method invocation: " + desc); break; } TypeDesc ret = ((MethodDesc)desc).getReturnType(); if (ret == TypeDesc.VOID) { ret = null; } TypeDesc[] paramTypes = ((MethodDesc)desc).getParameterTypes(); if (paramTypes.length == 0) { paramTypes = null; } switch (opcode) { case Opcode.INVOKEVIRTUAL: if (className == null) { assembler.invokeVirtual(methodName, ret, paramTypes); } else { assembler.invokeVirtual(className, methodName, ret, paramTypes); } break; case Opcode.INVOKESPECIAL: if ("<init>".equals(methodName)) { if (className == null) { assembler.invokeConstructor(paramTypes); } else { - if (className.equals(mSuperClassName)) { + if ("<init>".equals(mMethod.getName()) + && className.equals(mSuperClassName)) { assembler.invokeSuperConstructor(paramTypes); } else { assembler.invokeConstructor(className, paramTypes); } } } else { if (className == null) { assembler.invokePrivate(methodName, ret, paramTypes); } else { assembler.invokeSuper(className, methodName, ret, paramTypes); } } break; case Opcode.INVOKESTATIC: if (className == null) { assembler.invokeStatic(methodName, ret, paramTypes); } else { assembler.invokeStatic(className, methodName, ret, paramTypes); } break; case Opcode.INVOKEINTERFACE: assembler.invokeInterface(className, methodName, ret, paramTypes); break; } break; // End opcodes that load a constant from the constant pool. // Opcodes that load or store local variables... case Opcode.ILOAD: case Opcode.ISTORE: case Opcode.LLOAD: case Opcode.LSTORE: case Opcode.FLOAD: case Opcode.FSTORE: case Opcode.DLOAD: case Opcode.DSTORE: case Opcode.ALOAD: case Opcode.ASTORE: case Opcode.ILOAD_0: case Opcode.ISTORE_0: case Opcode.ILOAD_1: case Opcode.ISTORE_1: case Opcode.ILOAD_2: case Opcode.ISTORE_2: case Opcode.ILOAD_3: case Opcode.ISTORE_3: case Opcode.LLOAD_0: case Opcode.LSTORE_0: case Opcode.LLOAD_1: case Opcode.LSTORE_1: case Opcode.LLOAD_2: case Opcode.LSTORE_2: case Opcode.LLOAD_3: case Opcode.LSTORE_3: case Opcode.FLOAD_0: case Opcode.FSTORE_0: case Opcode.FLOAD_1: case Opcode.FSTORE_1: case Opcode.FLOAD_2: case Opcode.FSTORE_2: case Opcode.FLOAD_3: case Opcode.FSTORE_3: case Opcode.DLOAD_0: case Opcode.DSTORE_0: case Opcode.DLOAD_1: case Opcode.DSTORE_1: case Opcode.DLOAD_2: case Opcode.DSTORE_2: case Opcode.DLOAD_3: case Opcode.DSTORE_3: case Opcode.ALOAD_0: case Opcode.ASTORE_0: case Opcode.ALOAD_1: case Opcode.ASTORE_1: case Opcode.ALOAD_2: case Opcode.ASTORE_2: case Opcode.ALOAD_3: case Opcode.ASTORE_3: switch (opcode) { case Opcode.ILOAD: case Opcode.ISTORE: index = readUnsignedByte(); type = TypeDesc.INT; break; case Opcode.LLOAD: case Opcode.LSTORE: index = readUnsignedByte(); type = TypeDesc.LONG; break; case Opcode.FLOAD: case Opcode.FSTORE: index = readUnsignedByte(); type = TypeDesc.FLOAT; break; case Opcode.DLOAD: case Opcode.DSTORE: index = readUnsignedByte(); type = TypeDesc.DOUBLE; break; case Opcode.ALOAD: case Opcode.ASTORE: index = readUnsignedByte(); type = TypeDesc.OBJECT; break; case Opcode.ILOAD_0: case Opcode.ISTORE_0: index = 0; type = TypeDesc.INT; break; case Opcode.ILOAD_1: case Opcode.ISTORE_1: index = 1; type = TypeDesc.INT; break; case Opcode.ILOAD_2: case Opcode.ISTORE_2: index = 2; type = TypeDesc.INT; break; case Opcode.ILOAD_3: case Opcode.ISTORE_3: index = 3; type = TypeDesc.INT; break; case Opcode.LLOAD_0: case Opcode.LSTORE_0: index = 0; type = TypeDesc.LONG; break; case Opcode.LLOAD_1: case Opcode.LSTORE_1: index = 1; type = TypeDesc.LONG; break; case Opcode.LLOAD_2: case Opcode.LSTORE_2: index = 2; type = TypeDesc.LONG; break; case Opcode.LLOAD_3: case Opcode.LSTORE_3: index = 3; type = TypeDesc.LONG; break; case Opcode.FLOAD_0: case Opcode.FSTORE_0: index = 0; type = TypeDesc.FLOAT; break; case Opcode.FLOAD_1: case Opcode.FSTORE_1: index = 1; type = TypeDesc.FLOAT; break; case Opcode.FLOAD_2: case Opcode.FSTORE_2: index = 2; type = TypeDesc.FLOAT; break; case Opcode.FLOAD_3: case Opcode.FSTORE_3: index = 3; type = TypeDesc.FLOAT; break; case Opcode.DLOAD_0: case Opcode.DSTORE_0: index = 0; type = TypeDesc.DOUBLE; break; case Opcode.DLOAD_1: case Opcode.DSTORE_1: index = 1; type = TypeDesc.DOUBLE; break; case Opcode.DLOAD_2: case Opcode.DSTORE_2: index = 2; type = TypeDesc.DOUBLE; break; case Opcode.DLOAD_3: case Opcode.DSTORE_3: index = 3; type = TypeDesc.DOUBLE; break; case Opcode.ALOAD_0: case Opcode.ASTORE_0: index = 0; type = TypeDesc.OBJECT; break; case Opcode.ALOAD_1: case Opcode.ASTORE_1: index = 1; type = TypeDesc.OBJECT; break; case Opcode.ALOAD_2: case Opcode.ASTORE_2: index = 2; type = TypeDesc.OBJECT; break; case Opcode.ALOAD_3: case Opcode.ASTORE_3: index = 3; type = TypeDesc.OBJECT; break; default: index = 0; type = null; break; } switch (opcode) { case Opcode.ILOAD: case Opcode.LLOAD: case Opcode.FLOAD: case Opcode.DLOAD: case Opcode.ALOAD: case Opcode.ILOAD_0: case Opcode.ILOAD_1: case Opcode.ILOAD_2: case Opcode.ILOAD_3: case Opcode.LLOAD_0: case Opcode.LLOAD_1: case Opcode.LLOAD_2: case Opcode.LLOAD_3: case Opcode.FLOAD_0: case Opcode.FLOAD_1: case Opcode.FLOAD_2: case Opcode.FLOAD_3: case Opcode.DLOAD_0: case Opcode.DLOAD_1: case Opcode.DLOAD_2: case Opcode.DLOAD_3: case Opcode.ALOAD_0: case Opcode.ALOAD_1: case Opcode.ALOAD_2: case Opcode.ALOAD_3: if (index == 0 && mHasThis) { assembler.loadThis(); } else { assembler.loadLocal(getLocalVariable(index, type)); } break; case Opcode.ISTORE: case Opcode.LSTORE: case Opcode.FSTORE: case Opcode.DSTORE: case Opcode.ASTORE: case Opcode.ISTORE_0: case Opcode.ISTORE_1: case Opcode.ISTORE_2: case Opcode.ISTORE_3: case Opcode.LSTORE_0: case Opcode.LSTORE_1: case Opcode.LSTORE_2: case Opcode.LSTORE_3: case Opcode.FSTORE_0: case Opcode.FSTORE_1: case Opcode.FSTORE_2: case Opcode.FSTORE_3: case Opcode.DSTORE_0: case Opcode.DSTORE_1: case Opcode.DSTORE_2: case Opcode.DSTORE_3: case Opcode.ASTORE_0: case Opcode.ASTORE_1: case Opcode.ASTORE_2: case Opcode.ASTORE_3: if (index == 0 && mHasThis) { // The "this" reference just got blown away. mHasThis = false; } assembler.storeLocal(getLocalVariable(index, type)); break; } break; case Opcode.RET: LocalVariable local = getLocalVariable (readUnsignedByte(), TypeDesc.OBJECT); assembler.ret(local); break; case Opcode.IINC: local = getLocalVariable(readUnsignedByte(), TypeDesc.INT); assembler.integerIncrement(local, readByte()); break; // End opcodes that load or store local variables. // Opcodes that branch to another address. case Opcode.GOTO: loc = getLabel(mAddress + readShort()); assembler.branch(loc); break; case Opcode.JSR: loc = getLabel(mAddress + readShort()); assembler.jsr(loc); break; case Opcode.GOTO_W: loc = getLabel(mAddress + readInt()); assembler.branch(loc); break; case Opcode.JSR_W: loc = getLabel(mAddress + readInt()); assembler.jsr(loc); break; case Opcode.IFNULL: loc = getLabel(mAddress + readShort()); assembler.ifNullBranch(loc, true); break; case Opcode.IFNONNULL: loc = getLabel(mAddress + readShort()); assembler.ifNullBranch(loc, false); break; case Opcode.IF_ACMPEQ: loc = getLabel(mAddress + readShort()); assembler.ifEqualBranch(loc, true); break; case Opcode.IF_ACMPNE: loc = getLabel(mAddress + readShort()); assembler.ifEqualBranch(loc, false); break; case Opcode.IFEQ: case Opcode.IFNE: case Opcode.IFLT: case Opcode.IFGE: case Opcode.IFGT: case Opcode.IFLE: loc = getLabel(mAddress + readShort()); String choice; switch (opcode) { case Opcode.IFEQ: choice = "=="; break; case Opcode.IFNE: choice = "!="; break; case Opcode.IFLT: choice = "<"; break; case Opcode.IFGE: choice = ">="; break; case Opcode.IFGT: choice = ">"; break; case Opcode.IFLE: choice = "<="; break; default: choice = null; break; } assembler.ifZeroComparisonBranch(loc, choice); break; case Opcode.IF_ICMPEQ: case Opcode.IF_ICMPNE: case Opcode.IF_ICMPLT: case Opcode.IF_ICMPGE: case Opcode.IF_ICMPGT: case Opcode.IF_ICMPLE: loc = getLabel(mAddress + readShort()); switch (opcode) { case Opcode.IF_ICMPEQ: choice = "=="; break; case Opcode.IF_ICMPNE: choice = "!="; break; case Opcode.IF_ICMPLT: choice = "<"; break; case Opcode.IF_ICMPGE: choice = ">="; break; case Opcode.IF_ICMPGT: choice = ">"; break; case Opcode.IF_ICMPLE: choice = "<="; break; default: choice = null; break; } assembler.ifComparisonBranch(loc, choice); break; // End opcodes that branch to another address. // Miscellaneous opcodes... case Opcode.BIPUSH: assembler.loadConstant(readByte()); break; case Opcode.SIPUSH: assembler.loadConstant(readShort()); break; case Opcode.NEWARRAY: int atype = readByte(); type = null; switch (atype) { case 4: // T_BOOLEAN type = TypeDesc.BOOLEAN; break; case 5: // T_CHAR type = TypeDesc.CHAR; break; case 6: // T_FLOAT type = TypeDesc.FLOAT; break; case 7: // T_DOUBLE type = TypeDesc.DOUBLE; break; case 8: // T_BYTE type = TypeDesc.BYTE; break; case 9: // T_SHORT type = TypeDesc.SHORT; break; case 10: // T_INT type = TypeDesc.INT; break; case 11: // T_LONG type = TypeDesc.LONG; break; } if (type == null) { error(opcode, "Unknown primitive type for new array: " + atype); break; } assembler.newObject(type.toArrayType()); break; case Opcode.TABLESWITCH: case Opcode.LOOKUPSWITCH: int opcodeAddress = mAddress; // Read padding until address is 32 bit word aligned. while (((mAddress + 1) & 3) != 0) { ++mAddress; } Location defaultLocation = getLabel(opcodeAddress + readInt()); int[] cases; Location[] locations; if (opcode == Opcode.TABLESWITCH) { int lowValue = readInt(); int highValue = readInt(); int caseCount = highValue - lowValue + 1; try { cases = new int[caseCount]; } catch (NegativeArraySizeException e) { error(opcode, "Negative case count for switch: " + caseCount); break; } locations = new Location[caseCount]; for (int i=0; i<caseCount; i++) { cases[i] = lowValue + i; locations[i] = getLabel(opcodeAddress + readInt()); } } else { int caseCount = readInt(); try { cases = new int[caseCount]; } catch (NegativeArraySizeException e) { error(opcode, "Negative case count for switch: " + caseCount); break; } locations = new Location[caseCount]; for (int i=0; i<caseCount; i++) { cases[i] = readInt(); locations[i] = getLabel(opcodeAddress + readInt()); } } assembler.switchBranch(cases, locations, defaultLocation); break; case Opcode.WIDE: opcode = mByteCodes[++mAddress]; switch (opcode) { default: error(opcode, "Unknown wide instruction"); break; case Opcode.ILOAD: case Opcode.ISTORE: case Opcode.LLOAD: case Opcode.LSTORE: case Opcode.FLOAD: case Opcode.FSTORE: case Opcode.DLOAD: case Opcode.DSTORE: case Opcode.ALOAD: case Opcode.ASTORE: switch (opcode) { case Opcode.ILOAD: case Opcode.ISTORE: type = TypeDesc.INT; break; case Opcode.LLOAD: case Opcode.LSTORE: type = TypeDesc.LONG; break; case Opcode.FLOAD: case Opcode.FSTORE: type = TypeDesc.FLOAT; break; case Opcode.DLOAD: case Opcode.DSTORE: type = TypeDesc.DOUBLE; break; case Opcode.ALOAD: case Opcode.ASTORE: type = TypeDesc.OBJECT; break; default: type = null; break; } index = readUnsignedShort(); switch (opcode) { case Opcode.ILOAD: case Opcode.LLOAD: case Opcode.FLOAD: case Opcode.DLOAD: case Opcode.ALOAD: if (index == 0 && mHasThis) { assembler.loadThis(); } else { assembler.loadLocal(getLocalVariable(index, type)); } break; case Opcode.ISTORE: case Opcode.LSTORE: case Opcode.FSTORE: case Opcode.DSTORE: case Opcode.ASTORE: if (index == 0 && mHasThis) { // The "this" reference just got blown away. mHasThis = false; } assembler.storeLocal(getLocalVariable(index, type)); break; } break; case Opcode.RET: local = getLocalVariable (readUnsignedShort(), TypeDesc.OBJECT); assembler.ret(local); break; case Opcode.IINC: local = getLocalVariable (readUnsignedShort(), TypeDesc.INT); assembler.integerIncrement(local, readShort()); break; } break; } // end huge switch } // end for loop } /** * Invoked on disassembly errors. By default, this method does nothing. */ protected void error(byte opcode, String message) { } private void gatherLabels() { mLabels = new HashMap(); mCatchLocations = new HashMap(mExceptionHandlers.length * 2 + 1); Integer labelKey; // Gather labels for any exception handlers. for (int i = mExceptionHandlers.length - 1; i >= 0; i--) { ExceptionHandler handler = mExceptionHandlers[i]; labelKey = new Integer(handler.getStartLocation().getLocation()); mLabels.put(labelKey, labelKey); labelKey = new Integer(handler.getEndLocation().getLocation()); mLabels.put(labelKey, labelKey); labelKey = new Integer(handler.getCatchLocation().getLocation()); List list = (List)mCatchLocations.get(labelKey); if (list == null) { list = new ArrayList(2); mCatchLocations.put(labelKey, list); } list.add(handler); } // Now gather labels that occur within byte code. for (mAddress = 0; mAddress < mByteCodes.length; mAddress++) { byte opcode = mByteCodes[mAddress]; switch (opcode) { default: error(opcode, "Unknown opcode: " + (opcode & 0xff)); break; // Opcodes that use labels. case Opcode.GOTO: case Opcode.JSR: case Opcode.IFNULL: case Opcode.IFNONNULL: case Opcode.IF_ACMPEQ: case Opcode.IF_ACMPNE: case Opcode.IFEQ: case Opcode.IFNE: case Opcode.IFLT: case Opcode.IFGE: case Opcode.IFGT: case Opcode.IFLE: case Opcode.IF_ICMPEQ: case Opcode.IF_ICMPNE: case Opcode.IF_ICMPLT: case Opcode.IF_ICMPGE: case Opcode.IF_ICMPGT: case Opcode.IF_ICMPLE: labelKey = new Integer(mAddress + readShort()); mLabels.put(labelKey, labelKey); break; case Opcode.GOTO_W: case Opcode.JSR_W: labelKey = new Integer(mAddress + readInt()); mLabels.put(labelKey, labelKey); break; case Opcode.TABLESWITCH: case Opcode.LOOKUPSWITCH: int opcodeAddress = mAddress; // Read padding until address is 32 bit word aligned. while (((mAddress + 1) & 3) != 0) { ++mAddress; } // Read the default location. labelKey = new Integer(opcodeAddress + readInt()); mLabels.put(labelKey, labelKey); if (opcode == Opcode.TABLESWITCH) { int lowValue = readInt(); int highValue = readInt(); int caseCount = highValue - lowValue + 1; for (int i=0; i<caseCount; i++) { // Read the branch location. labelKey = new Integer(opcodeAddress + readInt()); mLabels.put(labelKey, labelKey); } } else { int caseCount = readInt(); for (int i=0; i<caseCount; i++) { // Skip the case value. mAddress += 4; // Read the branch location. labelKey = new Integer(opcodeAddress + readInt()); mLabels.put(labelKey, labelKey); } } break; // All other operations are skipped. The amount to skip // depends on the operand size. // Opcodes with no operands... case Opcode.NOP: case Opcode.BREAKPOINT: case Opcode.ACONST_NULL: case Opcode.ICONST_M1: case Opcode.ICONST_0: case Opcode.ICONST_1: case Opcode.ICONST_2: case Opcode.ICONST_3: case Opcode.ICONST_4: case Opcode.ICONST_5: case Opcode.LCONST_0: case Opcode.LCONST_1: case Opcode.FCONST_0: case Opcode.FCONST_1: case Opcode.FCONST_2: case Opcode.DCONST_0: case Opcode.DCONST_1: case Opcode.POP: case Opcode.POP2: case Opcode.DUP: case Opcode.DUP_X1: case Opcode.DUP_X2: case Opcode.DUP2: case Opcode.DUP2_X1: case Opcode.DUP2_X2: case Opcode.SWAP: case Opcode.IADD: case Opcode.LADD: case Opcode.FADD: case Opcode.DADD: case Opcode.ISUB: case Opcode.LSUB: case Opcode.FSUB: case Opcode.DSUB: case Opcode.IMUL: case Opcode.LMUL: case Opcode.FMUL: case Opcode.DMUL: case Opcode.IDIV: case Opcode.LDIV: case Opcode.FDIV: case Opcode.DDIV: case Opcode.IREM: case Opcode.LREM: case Opcode.FREM: case Opcode.DREM: case Opcode.INEG: case Opcode.LNEG: case Opcode.FNEG: case Opcode.DNEG: case Opcode.ISHL: case Opcode.LSHL: case Opcode.ISHR: case Opcode.LSHR: case Opcode.IUSHR: case Opcode.LUSHR: case Opcode.IAND: case Opcode.LAND: case Opcode.IOR: case Opcode.LOR: case Opcode.IXOR: case Opcode.LXOR: case Opcode.FCMPL: case Opcode.DCMPL: case Opcode.FCMPG: case Opcode.DCMPG: case Opcode.LCMP: case Opcode.I2L: case Opcode.I2F: case Opcode.I2D: case Opcode.L2I: case Opcode.L2F: case Opcode.L2D: case Opcode.F2I: case Opcode.F2L: case Opcode.F2D: case Opcode.D2I: case Opcode.D2L: case Opcode.D2F: case Opcode.I2B: case Opcode.I2C: case Opcode.I2S: case Opcode.IRETURN: case Opcode.LRETURN: case Opcode.FRETURN: case Opcode.DRETURN: case Opcode.ARETURN: case Opcode.RETURN: case Opcode.IALOAD: case Opcode.LALOAD: case Opcode.FALOAD: case Opcode.DALOAD: case Opcode.AALOAD: case Opcode.BALOAD: case Opcode.CALOAD: case Opcode.SALOAD: case Opcode.IASTORE: case Opcode.LASTORE: case Opcode.FASTORE: case Opcode.DASTORE: case Opcode.AASTORE: case Opcode.BASTORE: case Opcode.CASTORE: case Opcode.SASTORE: case Opcode.ARRAYLENGTH: case Opcode.ATHROW: case Opcode.MONITORENTER: case Opcode.MONITOREXIT: case Opcode.ILOAD_0: case Opcode.ISTORE_0: case Opcode.ILOAD_1: case Opcode.ISTORE_1: case Opcode.ILOAD_2: case Opcode.ISTORE_2: case Opcode.ILOAD_3: case Opcode.ISTORE_3: case Opcode.LLOAD_0: case Opcode.LSTORE_0: case Opcode.LLOAD_1: case Opcode.LSTORE_1: case Opcode.LLOAD_2: case Opcode.LSTORE_2: case Opcode.LLOAD_3: case Opcode.LSTORE_3: case Opcode.FLOAD_0: case Opcode.FSTORE_0: case Opcode.FLOAD_1: case Opcode.FSTORE_1: case Opcode.FLOAD_2: case Opcode.FSTORE_2: case Opcode.FLOAD_3: case Opcode.FSTORE_3: case Opcode.DLOAD_0: case Opcode.DSTORE_0: case Opcode.DLOAD_1: case Opcode.DSTORE_1: case Opcode.DLOAD_2: case Opcode.DSTORE_2: case Opcode.DLOAD_3: case Opcode.DSTORE_3: case Opcode.ALOAD_0: case Opcode.ASTORE_0: case Opcode.ALOAD_1: case Opcode.ASTORE_1: case Opcode.ALOAD_2: case Opcode.ASTORE_2: case Opcode.ALOAD_3: case Opcode.ASTORE_3: break; // Opcodes with one operand byte... case Opcode.LDC: case Opcode.ILOAD: case Opcode.ISTORE: case Opcode.LLOAD: case Opcode.LSTORE: case Opcode.FLOAD: case Opcode.FSTORE: case Opcode.DLOAD: case Opcode.DSTORE: case Opcode.ALOAD: case Opcode.ASTORE: case Opcode.RET: case Opcode.BIPUSH: case Opcode.NEWARRAY: mAddress += 1; break; // Opcodes with two operand bytes... case Opcode.LDC_W: case Opcode.LDC2_W: case Opcode.NEW: case Opcode.ANEWARRAY: case Opcode.CHECKCAST: case Opcode.INSTANCEOF: case Opcode.GETSTATIC: case Opcode.PUTSTATIC: case Opcode.GETFIELD: case Opcode.PUTFIELD: case Opcode.INVOKEVIRTUAL: case Opcode.INVOKESPECIAL: case Opcode.INVOKESTATIC: case Opcode.SIPUSH: case Opcode.IINC: mAddress += 2; break; // Opcodes with three operand bytes... case Opcode.MULTIANEWARRAY: mAddress += 3; break; // Opcodes with four operand bytes... case Opcode.INVOKEINTERFACE: mAddress += 4; break; // Wide opcode has a variable sized operand. case Opcode.WIDE: opcode = mByteCodes[++mAddress]; mAddress += 2; if (opcode == Opcode.IINC) { mAddress += 2; } break; } // end huge switch } // end for loop } private int readByte() { return mByteCodes[++mAddress]; } private int readUnsignedByte() { return mByteCodes[++mAddress] & 0xff; } private int readShort() { return (mByteCodes[++mAddress] << 8) | (mByteCodes[++mAddress] & 0xff); } private int readUnsignedShort() { return ((mByteCodes[++mAddress] & 0xff) << 8) | ((mByteCodes[++mAddress] & 0xff) << 0); } private int readInt() { return (mByteCodes[++mAddress] << 24) | ((mByteCodes[++mAddress] & 0xff) << 16) | ((mByteCodes[++mAddress] & 0xff) << 8) | ((mByteCodes[++mAddress] & 0xff) << 0); } private LocalVariable getLocalVariable(final int index, final TypeDesc type) { LocalVariable local; if (index >= mLocals.size()) { mLocals.setSize(index + 1); local = mAssembler.createLocalVariable(null, type); mLocals.set(index, local); return local; } Object obj = mLocals.get(index); if (obj == null) { local = mAssembler.createLocalVariable(null, type); mLocals.set(index, local); return local; } if (obj instanceof LocalVariable) { local = (LocalVariable)obj; if (compatibleType(type, local.getType())) { return local; } // Variable takes on multiple types, so convert entry to a list. List locals = new ArrayList(4); locals.add(local); local = mAssembler.createLocalVariable(null, type); locals.add(local); mLocals.set(index, locals); return local; } List locals = (List)obj; for (int i=locals.size(); --i>=0; ) { local = (LocalVariable)locals.get(i); if (compatibleType(type, local.getType())) { return local; } } local = mAssembler.createLocalVariable(null, type); locals.add(local); return local; } private boolean compatibleType(TypeDesc a, TypeDesc b) { return a == b || (!a.isPrimitive() && !b.isPrimitive()); } private void locateLabel() { Integer labelKey = new Integer(mAddress); Object labelValue = mLabels.get(labelKey); if (labelValue != null) { if (labelValue instanceof Label) { ((Label)labelValue).setLocation(); } else { labelValue = mAssembler.createLabel().setLocation(); mLabels.put(labelKey, labelValue); } } List handlers = (List)mCatchLocations.get(labelKey); if (handlers != null) { for (int i=0; i<handlers.size(); i++) { ExceptionHandler handler = (ExceptionHandler)handlers.get(i); Label start = getLabel(handler.getStartLocation().getLocation()); Label end = getLabel(handler.getEndLocation().getLocation()); String catchClassName; if (handler.getCatchType() == null) { catchClassName = null; } else { catchClassName = handler.getCatchType().getType().getRootName(); } mAssembler.exceptionHandler(start, end, catchClassName); } } } private Label getLabel(int address) { Integer labelKey = new Integer(address); Object labelValue = mLabels.get(labelKey); // labelValue will never be null unless gatherLabels is broken. if (!(labelValue instanceof Label)) { labelValue = mAssembler.createLabel(); mLabels.put(labelKey, labelValue); } return (Label)labelValue; } }
true
true
public synchronized void disassemble(CodeAssembler assembler, LocalVariable[] params, Location returnLocation) { mAssembler = assembler; mLocals = new Vector(); if (mHasThis = !mMethod.getModifiers().isStatic()) { // Reserve a slot for "this" parameter. mLocals.add(null); } gatherLabels(); // Gather the local variables of the parameters. { TypeDesc[] paramTypes = mMethod.getMethodDescriptor().getParameterTypes(); if (params == null) { params = new LocalVariable[assembler.getParameterCount()]; for (int i=params.length; --i>=0; ) { params[i] = assembler.getParameter(i); } } if (paramTypes.length != params.length) { throw new IllegalArgumentException ("Method parameter count doesn't match given parameter count: " + paramTypes.length + " != " + params.length); } for (int i=0; i<paramTypes.length; i++) { LocalVariable paramVar = params[i]; if (!compatibleType(paramTypes[i], paramVar.getType())) { throw new IllegalArgumentException ("Method parameter type is not compatible with given type: " + paramTypes[i] + " != " + paramVar.getType()); } mLocals.add(paramVar); if (paramVar.getType().isDoubleWord()) { // Reserve slot for least significant word. mLocals.add(null); } } } mReturnLocation = returnLocation; Location currentLoc = new Location() { public int getLocation() { return mAddress; } public int compareTo(Object obj) { if (this == obj) { return 0; } Location other = (Location)obj; int loca = getLocation(); int locb = other.getLocation(); if (loca < locb) { return -1; } else if (loca > locb) { return 1; } else { return 0; } } }; int currentLine = -1; for (mAddress = 0; mAddress < mByteCodes.length; mAddress++) { int nextLine = mCode.getLineNumber(currentLoc); if (nextLine != currentLine) { if ((currentLine = nextLine) >= 0) { mAssembler.mapLineNumber(currentLine); } } // Check if a label needs to be created and/or located. locateLabel(); byte opcode = mByteCodes[mAddress]; int index; Location loc; TypeDesc type; ConstantInfo ci; switch (opcode) { default: error(opcode, "Unknown opcode: " + (opcode & 0xff)); break; // Opcodes with no operands... case Opcode.NOP: assembler.nop(); break; case Opcode.BREAKPOINT: assembler.breakpoint(); break; case Opcode.ACONST_NULL: assembler.loadNull(); break; case Opcode.ICONST_M1: assembler.loadConstant(-1); break; case Opcode.ICONST_0: assembler.loadConstant(0); break; case Opcode.ICONST_1: assembler.loadConstant(1); break; case Opcode.ICONST_2: assembler.loadConstant(2); break; case Opcode.ICONST_3: assembler.loadConstant(3); break; case Opcode.ICONST_4: assembler.loadConstant(4); break; case Opcode.ICONST_5: assembler.loadConstant(5); break; case Opcode.LCONST_0: assembler.loadConstant(0L); break; case Opcode.LCONST_1: assembler.loadConstant(1L); break; case Opcode.FCONST_0: assembler.loadConstant(0f); break; case Opcode.FCONST_1: assembler.loadConstant(1f); break; case Opcode.FCONST_2: assembler.loadConstant(2f); break; case Opcode.DCONST_0: assembler.loadConstant(0d); break; case Opcode.DCONST_1: assembler.loadConstant(1d); break; case Opcode.POP: assembler.pop(); break; case Opcode.POP2: assembler.pop2(); break; case Opcode.DUP: assembler.dup(); break; case Opcode.DUP_X1: assembler.dupX1(); break; case Opcode.DUP_X2: assembler.dupX2(); break; case Opcode.DUP2: assembler.dup2(); break; case Opcode.DUP2_X1: assembler.dup2X2(); break; case Opcode.DUP2_X2: assembler.dup2X2(); break; case Opcode.SWAP: assembler.swap(); break; case Opcode.IADD: case Opcode.LADD: case Opcode.FADD: case Opcode.DADD: case Opcode.ISUB: case Opcode.LSUB: case Opcode.FSUB: case Opcode.DSUB: case Opcode.IMUL: case Opcode.LMUL: case Opcode.FMUL: case Opcode.DMUL: case Opcode.IDIV: case Opcode.LDIV: case Opcode.FDIV: case Opcode.DDIV: case Opcode.IREM: case Opcode.LREM: case Opcode.FREM: case Opcode.DREM: case Opcode.INEG: case Opcode.LNEG: case Opcode.FNEG: case Opcode.DNEG: case Opcode.ISHL: case Opcode.LSHL: case Opcode.ISHR: case Opcode.LSHR: case Opcode.IUSHR: case Opcode.LUSHR: case Opcode.IAND: case Opcode.LAND: case Opcode.IOR: case Opcode.LOR: case Opcode.IXOR: case Opcode.LXOR: case Opcode.FCMPL: case Opcode.DCMPL: case Opcode.FCMPG: case Opcode.DCMPG: case Opcode.LCMP: assembler.math(opcode); break; case Opcode.I2L: assembler.convert(TypeDesc.INT, TypeDesc.LONG); break; case Opcode.I2F: assembler.convert(TypeDesc.INT, TypeDesc.FLOAT); break; case Opcode.I2D: assembler.convert(TypeDesc.INT, TypeDesc.DOUBLE); break; case Opcode.L2I: assembler.convert(TypeDesc.LONG, TypeDesc.INT); break; case Opcode.L2F: assembler.convert(TypeDesc.LONG, TypeDesc.FLOAT); break; case Opcode.L2D: assembler.convert(TypeDesc.LONG, TypeDesc.DOUBLE); break; case Opcode.F2I: assembler.convert(TypeDesc.FLOAT, TypeDesc.INT); break; case Opcode.F2L: assembler.convert(TypeDesc.FLOAT, TypeDesc.LONG); break; case Opcode.F2D: assembler.convert(TypeDesc.FLOAT, TypeDesc.DOUBLE); break; case Opcode.D2I: assembler.convert(TypeDesc.DOUBLE, TypeDesc.INT); break; case Opcode.D2L: assembler.convert(TypeDesc.DOUBLE, TypeDesc.LONG); break; case Opcode.D2F: assembler.convert(TypeDesc.DOUBLE, TypeDesc.FLOAT); break; case Opcode.I2B: assembler.convert(TypeDesc.INT, TypeDesc.BYTE); break; case Opcode.I2C: assembler.convert(TypeDesc.INT, TypeDesc.CHAR); break; case Opcode.I2S: assembler.convert(TypeDesc.INT, TypeDesc.SHORT); break; case Opcode.IRETURN: case Opcode.LRETURN: case Opcode.FRETURN: case Opcode.DRETURN: case Opcode.ARETURN: case Opcode.RETURN: if (mReturnLocation != null) { assembler.branch(mReturnLocation); } else { switch (opcode) { case Opcode.IRETURN: assembler.returnValue(TypeDesc.INT); break; case Opcode.LRETURN: assembler.returnValue(TypeDesc.LONG); break; case Opcode.FRETURN: assembler.returnValue(TypeDesc.FLOAT); break; case Opcode.DRETURN: assembler.returnValue(TypeDesc.DOUBLE); break; case Opcode.ARETURN: assembler.returnValue(TypeDesc.OBJECT); break; case Opcode.RETURN: assembler.returnVoid(); break; } } break; case Opcode.IALOAD: assembler.loadFromArray(TypeDesc.INT); break; case Opcode.LALOAD: assembler.loadFromArray(TypeDesc.LONG); break; case Opcode.FALOAD: assembler.loadFromArray(TypeDesc.FLOAT); break; case Opcode.DALOAD: assembler.loadFromArray(TypeDesc.DOUBLE); break; case Opcode.AALOAD: assembler.loadFromArray(TypeDesc.OBJECT); break; case Opcode.BALOAD: assembler.loadFromArray(TypeDesc.BYTE); break; case Opcode.CALOAD: assembler.loadFromArray(TypeDesc.CHAR); break; case Opcode.SALOAD: assembler.loadFromArray(TypeDesc.SHORT); break; case Opcode.IASTORE: assembler.storeToArray(TypeDesc.INT); break; case Opcode.LASTORE: assembler.storeToArray(TypeDesc.LONG); break; case Opcode.FASTORE: assembler.storeToArray(TypeDesc.FLOAT); break; case Opcode.DASTORE: assembler.storeToArray(TypeDesc.DOUBLE); break; case Opcode.AASTORE: assembler.storeToArray(TypeDesc.OBJECT); break; case Opcode.BASTORE: assembler.storeToArray(TypeDesc.BYTE); break; case Opcode.CASTORE: assembler.storeToArray(TypeDesc.CHAR); break; case Opcode.SASTORE: assembler.storeToArray(TypeDesc.SHORT); break; case Opcode.ARRAYLENGTH: assembler.arrayLength(); break; case Opcode.ATHROW: assembler.throwObject(); break; case Opcode.MONITORENTER: assembler.monitorEnter(); break; case Opcode.MONITOREXIT: assembler.monitorExit(); break; // End opcodes with no operands. // Opcodes that load a constant from the constant pool... case Opcode.LDC: case Opcode.LDC_W: case Opcode.LDC2_W: switch (opcode) { case Opcode.LDC: index = readUnsignedByte(); break; case Opcode.LDC_W: case Opcode.LDC2_W: index = readUnsignedShort(); break; default: index = 0; break; } try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (ci instanceof ConstantStringInfo) { assembler.loadConstant(((ConstantStringInfo)ci).getValue()); } else if (ci instanceof ConstantIntegerInfo) { assembler.loadConstant(((ConstantIntegerInfo)ci).getValue()); } else if (ci instanceof ConstantLongInfo) { assembler.loadConstant(((ConstantLongInfo)ci).getValue()); } else if (ci instanceof ConstantFloatInfo) { assembler.loadConstant(((ConstantFloatInfo)ci).getValue()); } else if (ci instanceof ConstantDoubleInfo) { assembler.loadConstant(((ConstantDoubleInfo)ci).getValue()); } else if (ci instanceof ConstantClassInfo) { assembler.loadConstant(((ConstantClassInfo)ci).getType()); } else { error(opcode, "Invalid constant type for load: " + ci); } break; case Opcode.NEW: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (ci instanceof ConstantClassInfo) { assembler.newObject(((ConstantClassInfo)ci).getType()); } else { error(opcode, "Invalid constant type for new: " + ci); } break; case Opcode.ANEWARRAY: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (ci instanceof ConstantClassInfo) { type = ((ConstantClassInfo)ci).getType().toArrayType(); assembler.newObject(type); } else { error(opcode, "Invalid constant type for new: " + ci); } break; case Opcode.MULTIANEWARRAY: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } int dims = readUnsignedByte(); if (ci instanceof ConstantClassInfo) { type = ((ConstantClassInfo)ci).getType(); assembler.newObject(type, dims); } else { error(opcode, "Invalid constant type for new: " + ci); } break; case Opcode.CHECKCAST: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (ci instanceof ConstantClassInfo) { assembler.checkCast(((ConstantClassInfo)ci).getType()); } else { error(opcode, "Invalid constant type for checkcast: " + ci); } break; case Opcode.INSTANCEOF: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (ci instanceof ConstantClassInfo) { assembler.instanceOf(((ConstantClassInfo)ci).getType()); } else { error(opcode, "Invalid constant type for instanceof: " + ci); } break; case Opcode.GETSTATIC: case Opcode.PUTSTATIC: case Opcode.GETFIELD: case Opcode.PUTFIELD: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (!(ci instanceof ConstantFieldInfo)) { error(opcode, "Invalid constant type for field access: " + ci); break; } ConstantFieldInfo field = (ConstantFieldInfo)ci; String className = field.getParentClass().getType().getRootName(); if (mEnclosingClassName.equals(className)) { className = null; } String fieldName = field.getNameAndType().getName(); Descriptor desc = field.getNameAndType().getType(); if (!(desc instanceof TypeDesc)) { error(opcode, "Invalid descriptor for field access: " + desc); break; } else { type = (TypeDesc)desc; } // Implementation note: Although it may seem convenient if the // CodeAssembler had methods that accepted ConstantFieldInfo // objects as parameters, it would cause problems because // ConstantPools are not portable between ClassFiles. switch (opcode) { case Opcode.GETSTATIC: if (className == null) { assembler.loadStaticField(fieldName, type); } else { assembler.loadStaticField(className, fieldName, type); } break; case Opcode.PUTSTATIC: if (className == null) { assembler.storeStaticField(fieldName, type); } else { assembler.storeStaticField(className, fieldName, type); } break; case Opcode.GETFIELD: if (className == null) { assembler.loadField(fieldName, type); } else { assembler.loadField(className, fieldName, type); } break; case Opcode.PUTFIELD: if (className == null) { assembler.storeField(fieldName, type); } else { assembler.storeField(className, fieldName, type); } break; } break; case Opcode.INVOKEVIRTUAL: case Opcode.INVOKESPECIAL: case Opcode.INVOKESTATIC: case Opcode.INVOKEINTERFACE: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } ConstantNameAndTypeInfo nameAndType; if (opcode == Opcode.INVOKEINTERFACE) { // Read and ignore nargs and padding byte. readShort(); if (!(ci instanceof ConstantInterfaceMethodInfo)) { error(opcode, "Invalid constant type for method invocation: " + ci); break; } ConstantInterfaceMethodInfo method = (ConstantInterfaceMethodInfo)ci; className = method.getParentClass().getType().getRootName(); nameAndType = method.getNameAndType(); } else { if (!(ci instanceof ConstantMethodInfo)) { error(opcode, "Invalid constant type for method invocation: " + ci); break; } ConstantMethodInfo method = (ConstantMethodInfo)ci; className = method.getParentClass().getType().getRootName(); if (mEnclosingClassName.equals(className)) { className = null; } nameAndType = method.getNameAndType(); } String methodName = nameAndType.getName(); desc = nameAndType.getType(); if (!(desc instanceof MethodDesc)) { error(opcode, "Invalid descriptor for method invocation: " + desc); break; } TypeDesc ret = ((MethodDesc)desc).getReturnType(); if (ret == TypeDesc.VOID) { ret = null; } TypeDesc[] paramTypes = ((MethodDesc)desc).getParameterTypes(); if (paramTypes.length == 0) { paramTypes = null; } switch (opcode) { case Opcode.INVOKEVIRTUAL: if (className == null) { assembler.invokeVirtual(methodName, ret, paramTypes); } else { assembler.invokeVirtual(className, methodName, ret, paramTypes); } break; case Opcode.INVOKESPECIAL: if ("<init>".equals(methodName)) { if (className == null) { assembler.invokeConstructor(paramTypes); } else { if (className.equals(mSuperClassName)) { assembler.invokeSuperConstructor(paramTypes); } else { assembler.invokeConstructor(className, paramTypes); } } } else { if (className == null) { assembler.invokePrivate(methodName, ret, paramTypes); } else { assembler.invokeSuper(className, methodName, ret, paramTypes); } } break; case Opcode.INVOKESTATIC: if (className == null) { assembler.invokeStatic(methodName, ret, paramTypes); } else { assembler.invokeStatic(className, methodName, ret, paramTypes); } break; case Opcode.INVOKEINTERFACE: assembler.invokeInterface(className, methodName, ret, paramTypes); break; } break; // End opcodes that load a constant from the constant pool. // Opcodes that load or store local variables... case Opcode.ILOAD: case Opcode.ISTORE: case Opcode.LLOAD: case Opcode.LSTORE: case Opcode.FLOAD: case Opcode.FSTORE: case Opcode.DLOAD: case Opcode.DSTORE: case Opcode.ALOAD: case Opcode.ASTORE: case Opcode.ILOAD_0: case Opcode.ISTORE_0: case Opcode.ILOAD_1: case Opcode.ISTORE_1: case Opcode.ILOAD_2: case Opcode.ISTORE_2: case Opcode.ILOAD_3: case Opcode.ISTORE_3: case Opcode.LLOAD_0: case Opcode.LSTORE_0: case Opcode.LLOAD_1: case Opcode.LSTORE_1: case Opcode.LLOAD_2: case Opcode.LSTORE_2: case Opcode.LLOAD_3: case Opcode.LSTORE_3: case Opcode.FLOAD_0: case Opcode.FSTORE_0: case Opcode.FLOAD_1: case Opcode.FSTORE_1: case Opcode.FLOAD_2: case Opcode.FSTORE_2: case Opcode.FLOAD_3: case Opcode.FSTORE_3: case Opcode.DLOAD_0: case Opcode.DSTORE_0: case Opcode.DLOAD_1: case Opcode.DSTORE_1: case Opcode.DLOAD_2: case Opcode.DSTORE_2: case Opcode.DLOAD_3: case Opcode.DSTORE_3: case Opcode.ALOAD_0: case Opcode.ASTORE_0: case Opcode.ALOAD_1: case Opcode.ASTORE_1: case Opcode.ALOAD_2: case Opcode.ASTORE_2: case Opcode.ALOAD_3: case Opcode.ASTORE_3: switch (opcode) { case Opcode.ILOAD: case Opcode.ISTORE: index = readUnsignedByte(); type = TypeDesc.INT; break; case Opcode.LLOAD: case Opcode.LSTORE: index = readUnsignedByte(); type = TypeDesc.LONG; break; case Opcode.FLOAD: case Opcode.FSTORE: index = readUnsignedByte(); type = TypeDesc.FLOAT; break; case Opcode.DLOAD: case Opcode.DSTORE: index = readUnsignedByte(); type = TypeDesc.DOUBLE; break; case Opcode.ALOAD: case Opcode.ASTORE: index = readUnsignedByte(); type = TypeDesc.OBJECT; break; case Opcode.ILOAD_0: case Opcode.ISTORE_0: index = 0; type = TypeDesc.INT; break; case Opcode.ILOAD_1: case Opcode.ISTORE_1: index = 1; type = TypeDesc.INT; break; case Opcode.ILOAD_2: case Opcode.ISTORE_2: index = 2; type = TypeDesc.INT; break; case Opcode.ILOAD_3: case Opcode.ISTORE_3: index = 3; type = TypeDesc.INT; break; case Opcode.LLOAD_0: case Opcode.LSTORE_0: index = 0; type = TypeDesc.LONG; break; case Opcode.LLOAD_1: case Opcode.LSTORE_1: index = 1; type = TypeDesc.LONG; break; case Opcode.LLOAD_2: case Opcode.LSTORE_2: index = 2; type = TypeDesc.LONG; break; case Opcode.LLOAD_3: case Opcode.LSTORE_3: index = 3; type = TypeDesc.LONG; break; case Opcode.FLOAD_0: case Opcode.FSTORE_0: index = 0; type = TypeDesc.FLOAT; break; case Opcode.FLOAD_1: case Opcode.FSTORE_1: index = 1; type = TypeDesc.FLOAT; break; case Opcode.FLOAD_2: case Opcode.FSTORE_2: index = 2; type = TypeDesc.FLOAT; break; case Opcode.FLOAD_3: case Opcode.FSTORE_3: index = 3; type = TypeDesc.FLOAT; break; case Opcode.DLOAD_0: case Opcode.DSTORE_0: index = 0; type = TypeDesc.DOUBLE; break; case Opcode.DLOAD_1: case Opcode.DSTORE_1: index = 1; type = TypeDesc.DOUBLE; break; case Opcode.DLOAD_2: case Opcode.DSTORE_2: index = 2; type = TypeDesc.DOUBLE; break; case Opcode.DLOAD_3: case Opcode.DSTORE_3: index = 3; type = TypeDesc.DOUBLE; break; case Opcode.ALOAD_0: case Opcode.ASTORE_0: index = 0; type = TypeDesc.OBJECT; break; case Opcode.ALOAD_1: case Opcode.ASTORE_1: index = 1; type = TypeDesc.OBJECT; break; case Opcode.ALOAD_2: case Opcode.ASTORE_2: index = 2; type = TypeDesc.OBJECT; break; case Opcode.ALOAD_3: case Opcode.ASTORE_3: index = 3; type = TypeDesc.OBJECT; break; default: index = 0; type = null; break; } switch (opcode) { case Opcode.ILOAD: case Opcode.LLOAD: case Opcode.FLOAD: case Opcode.DLOAD: case Opcode.ALOAD: case Opcode.ILOAD_0: case Opcode.ILOAD_1: case Opcode.ILOAD_2: case Opcode.ILOAD_3: case Opcode.LLOAD_0: case Opcode.LLOAD_1: case Opcode.LLOAD_2: case Opcode.LLOAD_3: case Opcode.FLOAD_0: case Opcode.FLOAD_1: case Opcode.FLOAD_2: case Opcode.FLOAD_3: case Opcode.DLOAD_0: case Opcode.DLOAD_1: case Opcode.DLOAD_2: case Opcode.DLOAD_3: case Opcode.ALOAD_0: case Opcode.ALOAD_1: case Opcode.ALOAD_2: case Opcode.ALOAD_3: if (index == 0 && mHasThis) { assembler.loadThis(); } else { assembler.loadLocal(getLocalVariable(index, type)); } break; case Opcode.ISTORE: case Opcode.LSTORE: case Opcode.FSTORE: case Opcode.DSTORE: case Opcode.ASTORE: case Opcode.ISTORE_0: case Opcode.ISTORE_1: case Opcode.ISTORE_2: case Opcode.ISTORE_3: case Opcode.LSTORE_0: case Opcode.LSTORE_1: case Opcode.LSTORE_2: case Opcode.LSTORE_3: case Opcode.FSTORE_0: case Opcode.FSTORE_1: case Opcode.FSTORE_2: case Opcode.FSTORE_3: case Opcode.DSTORE_0: case Opcode.DSTORE_1: case Opcode.DSTORE_2: case Opcode.DSTORE_3: case Opcode.ASTORE_0: case Opcode.ASTORE_1: case Opcode.ASTORE_2: case Opcode.ASTORE_3: if (index == 0 && mHasThis) { // The "this" reference just got blown away. mHasThis = false; } assembler.storeLocal(getLocalVariable(index, type)); break; } break; case Opcode.RET: LocalVariable local = getLocalVariable (readUnsignedByte(), TypeDesc.OBJECT); assembler.ret(local); break; case Opcode.IINC: local = getLocalVariable(readUnsignedByte(), TypeDesc.INT); assembler.integerIncrement(local, readByte()); break; // End opcodes that load or store local variables. // Opcodes that branch to another address. case Opcode.GOTO: loc = getLabel(mAddress + readShort()); assembler.branch(loc); break; case Opcode.JSR: loc = getLabel(mAddress + readShort()); assembler.jsr(loc); break; case Opcode.GOTO_W: loc = getLabel(mAddress + readInt()); assembler.branch(loc); break; case Opcode.JSR_W: loc = getLabel(mAddress + readInt()); assembler.jsr(loc); break; case Opcode.IFNULL: loc = getLabel(mAddress + readShort()); assembler.ifNullBranch(loc, true); break; case Opcode.IFNONNULL: loc = getLabel(mAddress + readShort()); assembler.ifNullBranch(loc, false); break; case Opcode.IF_ACMPEQ: loc = getLabel(mAddress + readShort()); assembler.ifEqualBranch(loc, true); break; case Opcode.IF_ACMPNE: loc = getLabel(mAddress + readShort()); assembler.ifEqualBranch(loc, false); break; case Opcode.IFEQ: case Opcode.IFNE: case Opcode.IFLT: case Opcode.IFGE: case Opcode.IFGT: case Opcode.IFLE: loc = getLabel(mAddress + readShort()); String choice; switch (opcode) { case Opcode.IFEQ: choice = "=="; break; case Opcode.IFNE: choice = "!="; break; case Opcode.IFLT: choice = "<"; break; case Opcode.IFGE: choice = ">="; break; case Opcode.IFGT: choice = ">"; break; case Opcode.IFLE: choice = "<="; break; default: choice = null; break; } assembler.ifZeroComparisonBranch(loc, choice); break; case Opcode.IF_ICMPEQ: case Opcode.IF_ICMPNE: case Opcode.IF_ICMPLT: case Opcode.IF_ICMPGE: case Opcode.IF_ICMPGT: case Opcode.IF_ICMPLE: loc = getLabel(mAddress + readShort()); switch (opcode) { case Opcode.IF_ICMPEQ: choice = "=="; break; case Opcode.IF_ICMPNE: choice = "!="; break; case Opcode.IF_ICMPLT: choice = "<"; break; case Opcode.IF_ICMPGE: choice = ">="; break; case Opcode.IF_ICMPGT: choice = ">"; break; case Opcode.IF_ICMPLE: choice = "<="; break; default: choice = null; break; } assembler.ifComparisonBranch(loc, choice); break; // End opcodes that branch to another address. // Miscellaneous opcodes... case Opcode.BIPUSH: assembler.loadConstant(readByte()); break; case Opcode.SIPUSH: assembler.loadConstant(readShort()); break; case Opcode.NEWARRAY: int atype = readByte(); type = null; switch (atype) { case 4: // T_BOOLEAN type = TypeDesc.BOOLEAN; break; case 5: // T_CHAR type = TypeDesc.CHAR; break; case 6: // T_FLOAT type = TypeDesc.FLOAT; break; case 7: // T_DOUBLE type = TypeDesc.DOUBLE; break; case 8: // T_BYTE type = TypeDesc.BYTE; break; case 9: // T_SHORT type = TypeDesc.SHORT; break; case 10: // T_INT type = TypeDesc.INT; break; case 11: // T_LONG type = TypeDesc.LONG; break; } if (type == null) { error(opcode, "Unknown primitive type for new array: " + atype); break; } assembler.newObject(type.toArrayType()); break; case Opcode.TABLESWITCH: case Opcode.LOOKUPSWITCH: int opcodeAddress = mAddress; // Read padding until address is 32 bit word aligned. while (((mAddress + 1) & 3) != 0) { ++mAddress; } Location defaultLocation = getLabel(opcodeAddress + readInt()); int[] cases; Location[] locations; if (opcode == Opcode.TABLESWITCH) { int lowValue = readInt(); int highValue = readInt(); int caseCount = highValue - lowValue + 1; try { cases = new int[caseCount]; } catch (NegativeArraySizeException e) { error(opcode, "Negative case count for switch: " + caseCount); break; } locations = new Location[caseCount]; for (int i=0; i<caseCount; i++) { cases[i] = lowValue + i; locations[i] = getLabel(opcodeAddress + readInt()); } } else { int caseCount = readInt(); try { cases = new int[caseCount]; } catch (NegativeArraySizeException e) { error(opcode, "Negative case count for switch: " + caseCount); break; } locations = new Location[caseCount]; for (int i=0; i<caseCount; i++) { cases[i] = readInt(); locations[i] = getLabel(opcodeAddress + readInt()); } } assembler.switchBranch(cases, locations, defaultLocation); break; case Opcode.WIDE: opcode = mByteCodes[++mAddress]; switch (opcode) { default: error(opcode, "Unknown wide instruction"); break; case Opcode.ILOAD: case Opcode.ISTORE: case Opcode.LLOAD: case Opcode.LSTORE: case Opcode.FLOAD: case Opcode.FSTORE: case Opcode.DLOAD: case Opcode.DSTORE: case Opcode.ALOAD: case Opcode.ASTORE: switch (opcode) { case Opcode.ILOAD: case Opcode.ISTORE: type = TypeDesc.INT; break; case Opcode.LLOAD: case Opcode.LSTORE: type = TypeDesc.LONG; break; case Opcode.FLOAD: case Opcode.FSTORE: type = TypeDesc.FLOAT; break; case Opcode.DLOAD: case Opcode.DSTORE: type = TypeDesc.DOUBLE; break; case Opcode.ALOAD: case Opcode.ASTORE: type = TypeDesc.OBJECT; break; default: type = null; break; } index = readUnsignedShort(); switch (opcode) { case Opcode.ILOAD: case Opcode.LLOAD: case Opcode.FLOAD: case Opcode.DLOAD: case Opcode.ALOAD: if (index == 0 && mHasThis) { assembler.loadThis(); } else { assembler.loadLocal(getLocalVariable(index, type)); } break; case Opcode.ISTORE: case Opcode.LSTORE: case Opcode.FSTORE: case Opcode.DSTORE: case Opcode.ASTORE: if (index == 0 && mHasThis) { // The "this" reference just got blown away. mHasThis = false; } assembler.storeLocal(getLocalVariable(index, type)); break; } break; case Opcode.RET: local = getLocalVariable (readUnsignedShort(), TypeDesc.OBJECT); assembler.ret(local); break; case Opcode.IINC: local = getLocalVariable (readUnsignedShort(), TypeDesc.INT); assembler.integerIncrement(local, readShort()); break; } break; } // end huge switch } // end for loop }
public synchronized void disassemble(CodeAssembler assembler, LocalVariable[] params, Location returnLocation) { mAssembler = assembler; mLocals = new Vector(); if (mHasThis = !mMethod.getModifiers().isStatic()) { // Reserve a slot for "this" parameter. mLocals.add(null); } gatherLabels(); // Gather the local variables of the parameters. { TypeDesc[] paramTypes = mMethod.getMethodDescriptor().getParameterTypes(); if (params == null) { params = new LocalVariable[assembler.getParameterCount()]; for (int i=params.length; --i>=0; ) { params[i] = assembler.getParameter(i); } } if (paramTypes.length != params.length) { throw new IllegalArgumentException ("Method parameter count doesn't match given parameter count: " + paramTypes.length + " != " + params.length); } for (int i=0; i<paramTypes.length; i++) { LocalVariable paramVar = params[i]; if (!compatibleType(paramTypes[i], paramVar.getType())) { throw new IllegalArgumentException ("Method parameter type is not compatible with given type: " + paramTypes[i] + " != " + paramVar.getType()); } mLocals.add(paramVar); if (paramVar.getType().isDoubleWord()) { // Reserve slot for least significant word. mLocals.add(null); } } } mReturnLocation = returnLocation; Location currentLoc = new Location() { public int getLocation() { return mAddress; } public int compareTo(Object obj) { if (this == obj) { return 0; } Location other = (Location)obj; int loca = getLocation(); int locb = other.getLocation(); if (loca < locb) { return -1; } else if (loca > locb) { return 1; } else { return 0; } } }; int currentLine = -1; for (mAddress = 0; mAddress < mByteCodes.length; mAddress++) { int nextLine = mCode.getLineNumber(currentLoc); if (nextLine != currentLine) { if ((currentLine = nextLine) >= 0) { mAssembler.mapLineNumber(currentLine); } } // Check if a label needs to be created and/or located. locateLabel(); byte opcode = mByteCodes[mAddress]; int index; Location loc; TypeDesc type; ConstantInfo ci; switch (opcode) { default: error(opcode, "Unknown opcode: " + (opcode & 0xff)); break; // Opcodes with no operands... case Opcode.NOP: assembler.nop(); break; case Opcode.BREAKPOINT: assembler.breakpoint(); break; case Opcode.ACONST_NULL: assembler.loadNull(); break; case Opcode.ICONST_M1: assembler.loadConstant(-1); break; case Opcode.ICONST_0: assembler.loadConstant(0); break; case Opcode.ICONST_1: assembler.loadConstant(1); break; case Opcode.ICONST_2: assembler.loadConstant(2); break; case Opcode.ICONST_3: assembler.loadConstant(3); break; case Opcode.ICONST_4: assembler.loadConstant(4); break; case Opcode.ICONST_5: assembler.loadConstant(5); break; case Opcode.LCONST_0: assembler.loadConstant(0L); break; case Opcode.LCONST_1: assembler.loadConstant(1L); break; case Opcode.FCONST_0: assembler.loadConstant(0f); break; case Opcode.FCONST_1: assembler.loadConstant(1f); break; case Opcode.FCONST_2: assembler.loadConstant(2f); break; case Opcode.DCONST_0: assembler.loadConstant(0d); break; case Opcode.DCONST_1: assembler.loadConstant(1d); break; case Opcode.POP: assembler.pop(); break; case Opcode.POP2: assembler.pop2(); break; case Opcode.DUP: assembler.dup(); break; case Opcode.DUP_X1: assembler.dupX1(); break; case Opcode.DUP_X2: assembler.dupX2(); break; case Opcode.DUP2: assembler.dup2(); break; case Opcode.DUP2_X1: assembler.dup2X2(); break; case Opcode.DUP2_X2: assembler.dup2X2(); break; case Opcode.SWAP: assembler.swap(); break; case Opcode.IADD: case Opcode.LADD: case Opcode.FADD: case Opcode.DADD: case Opcode.ISUB: case Opcode.LSUB: case Opcode.FSUB: case Opcode.DSUB: case Opcode.IMUL: case Opcode.LMUL: case Opcode.FMUL: case Opcode.DMUL: case Opcode.IDIV: case Opcode.LDIV: case Opcode.FDIV: case Opcode.DDIV: case Opcode.IREM: case Opcode.LREM: case Opcode.FREM: case Opcode.DREM: case Opcode.INEG: case Opcode.LNEG: case Opcode.FNEG: case Opcode.DNEG: case Opcode.ISHL: case Opcode.LSHL: case Opcode.ISHR: case Opcode.LSHR: case Opcode.IUSHR: case Opcode.LUSHR: case Opcode.IAND: case Opcode.LAND: case Opcode.IOR: case Opcode.LOR: case Opcode.IXOR: case Opcode.LXOR: case Opcode.FCMPL: case Opcode.DCMPL: case Opcode.FCMPG: case Opcode.DCMPG: case Opcode.LCMP: assembler.math(opcode); break; case Opcode.I2L: assembler.convert(TypeDesc.INT, TypeDesc.LONG); break; case Opcode.I2F: assembler.convert(TypeDesc.INT, TypeDesc.FLOAT); break; case Opcode.I2D: assembler.convert(TypeDesc.INT, TypeDesc.DOUBLE); break; case Opcode.L2I: assembler.convert(TypeDesc.LONG, TypeDesc.INT); break; case Opcode.L2F: assembler.convert(TypeDesc.LONG, TypeDesc.FLOAT); break; case Opcode.L2D: assembler.convert(TypeDesc.LONG, TypeDesc.DOUBLE); break; case Opcode.F2I: assembler.convert(TypeDesc.FLOAT, TypeDesc.INT); break; case Opcode.F2L: assembler.convert(TypeDesc.FLOAT, TypeDesc.LONG); break; case Opcode.F2D: assembler.convert(TypeDesc.FLOAT, TypeDesc.DOUBLE); break; case Opcode.D2I: assembler.convert(TypeDesc.DOUBLE, TypeDesc.INT); break; case Opcode.D2L: assembler.convert(TypeDesc.DOUBLE, TypeDesc.LONG); break; case Opcode.D2F: assembler.convert(TypeDesc.DOUBLE, TypeDesc.FLOAT); break; case Opcode.I2B: assembler.convert(TypeDesc.INT, TypeDesc.BYTE); break; case Opcode.I2C: assembler.convert(TypeDesc.INT, TypeDesc.CHAR); break; case Opcode.I2S: assembler.convert(TypeDesc.INT, TypeDesc.SHORT); break; case Opcode.IRETURN: case Opcode.LRETURN: case Opcode.FRETURN: case Opcode.DRETURN: case Opcode.ARETURN: case Opcode.RETURN: if (mReturnLocation != null) { assembler.branch(mReturnLocation); } else { switch (opcode) { case Opcode.IRETURN: assembler.returnValue(TypeDesc.INT); break; case Opcode.LRETURN: assembler.returnValue(TypeDesc.LONG); break; case Opcode.FRETURN: assembler.returnValue(TypeDesc.FLOAT); break; case Opcode.DRETURN: assembler.returnValue(TypeDesc.DOUBLE); break; case Opcode.ARETURN: assembler.returnValue(TypeDesc.OBJECT); break; case Opcode.RETURN: assembler.returnVoid(); break; } } break; case Opcode.IALOAD: assembler.loadFromArray(TypeDesc.INT); break; case Opcode.LALOAD: assembler.loadFromArray(TypeDesc.LONG); break; case Opcode.FALOAD: assembler.loadFromArray(TypeDesc.FLOAT); break; case Opcode.DALOAD: assembler.loadFromArray(TypeDesc.DOUBLE); break; case Opcode.AALOAD: assembler.loadFromArray(TypeDesc.OBJECT); break; case Opcode.BALOAD: assembler.loadFromArray(TypeDesc.BYTE); break; case Opcode.CALOAD: assembler.loadFromArray(TypeDesc.CHAR); break; case Opcode.SALOAD: assembler.loadFromArray(TypeDesc.SHORT); break; case Opcode.IASTORE: assembler.storeToArray(TypeDesc.INT); break; case Opcode.LASTORE: assembler.storeToArray(TypeDesc.LONG); break; case Opcode.FASTORE: assembler.storeToArray(TypeDesc.FLOAT); break; case Opcode.DASTORE: assembler.storeToArray(TypeDesc.DOUBLE); break; case Opcode.AASTORE: assembler.storeToArray(TypeDesc.OBJECT); break; case Opcode.BASTORE: assembler.storeToArray(TypeDesc.BYTE); break; case Opcode.CASTORE: assembler.storeToArray(TypeDesc.CHAR); break; case Opcode.SASTORE: assembler.storeToArray(TypeDesc.SHORT); break; case Opcode.ARRAYLENGTH: assembler.arrayLength(); break; case Opcode.ATHROW: assembler.throwObject(); break; case Opcode.MONITORENTER: assembler.monitorEnter(); break; case Opcode.MONITOREXIT: assembler.monitorExit(); break; // End opcodes with no operands. // Opcodes that load a constant from the constant pool... case Opcode.LDC: case Opcode.LDC_W: case Opcode.LDC2_W: switch (opcode) { case Opcode.LDC: index = readUnsignedByte(); break; case Opcode.LDC_W: case Opcode.LDC2_W: index = readUnsignedShort(); break; default: index = 0; break; } try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (ci instanceof ConstantStringInfo) { assembler.loadConstant(((ConstantStringInfo)ci).getValue()); } else if (ci instanceof ConstantIntegerInfo) { assembler.loadConstant(((ConstantIntegerInfo)ci).getValue()); } else if (ci instanceof ConstantLongInfo) { assembler.loadConstant(((ConstantLongInfo)ci).getValue()); } else if (ci instanceof ConstantFloatInfo) { assembler.loadConstant(((ConstantFloatInfo)ci).getValue()); } else if (ci instanceof ConstantDoubleInfo) { assembler.loadConstant(((ConstantDoubleInfo)ci).getValue()); } else if (ci instanceof ConstantClassInfo) { assembler.loadConstant(((ConstantClassInfo)ci).getType()); } else { error(opcode, "Invalid constant type for load: " + ci); } break; case Opcode.NEW: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (ci instanceof ConstantClassInfo) { assembler.newObject(((ConstantClassInfo)ci).getType()); } else { error(opcode, "Invalid constant type for new: " + ci); } break; case Opcode.ANEWARRAY: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (ci instanceof ConstantClassInfo) { type = ((ConstantClassInfo)ci).getType().toArrayType(); assembler.newObject(type); } else { error(opcode, "Invalid constant type for new: " + ci); } break; case Opcode.MULTIANEWARRAY: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } int dims = readUnsignedByte(); if (ci instanceof ConstantClassInfo) { type = ((ConstantClassInfo)ci).getType(); assembler.newObject(type, dims); } else { error(opcode, "Invalid constant type for new: " + ci); } break; case Opcode.CHECKCAST: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (ci instanceof ConstantClassInfo) { assembler.checkCast(((ConstantClassInfo)ci).getType()); } else { error(opcode, "Invalid constant type for checkcast: " + ci); } break; case Opcode.INSTANCEOF: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (ci instanceof ConstantClassInfo) { assembler.instanceOf(((ConstantClassInfo)ci).getType()); } else { error(opcode, "Invalid constant type for instanceof: " + ci); } break; case Opcode.GETSTATIC: case Opcode.PUTSTATIC: case Opcode.GETFIELD: case Opcode.PUTFIELD: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } if (!(ci instanceof ConstantFieldInfo)) { error(opcode, "Invalid constant type for field access: " + ci); break; } ConstantFieldInfo field = (ConstantFieldInfo)ci; String className = field.getParentClass().getType().getRootName(); if (mEnclosingClassName.equals(className)) { className = null; } String fieldName = field.getNameAndType().getName(); Descriptor desc = field.getNameAndType().getType(); if (!(desc instanceof TypeDesc)) { error(opcode, "Invalid descriptor for field access: " + desc); break; } else { type = (TypeDesc)desc; } // Implementation note: Although it may seem convenient if the // CodeAssembler had methods that accepted ConstantFieldInfo // objects as parameters, it would cause problems because // ConstantPools are not portable between ClassFiles. switch (opcode) { case Opcode.GETSTATIC: if (className == null) { assembler.loadStaticField(fieldName, type); } else { assembler.loadStaticField(className, fieldName, type); } break; case Opcode.PUTSTATIC: if (className == null) { assembler.storeStaticField(fieldName, type); } else { assembler.storeStaticField(className, fieldName, type); } break; case Opcode.GETFIELD: if (className == null) { assembler.loadField(fieldName, type); } else { assembler.loadField(className, fieldName, type); } break; case Opcode.PUTFIELD: if (className == null) { assembler.storeField(fieldName, type); } else { assembler.storeField(className, fieldName, type); } break; } break; case Opcode.INVOKEVIRTUAL: case Opcode.INVOKESPECIAL: case Opcode.INVOKESTATIC: case Opcode.INVOKEINTERFACE: index = readUnsignedShort(); try { ci = mCp.getConstant(index); } catch (IndexOutOfBoundsException e) { error(opcode, "Undefined constant at index: " + index); break; } ConstantNameAndTypeInfo nameAndType; if (opcode == Opcode.INVOKEINTERFACE) { // Read and ignore nargs and padding byte. readShort(); if (!(ci instanceof ConstantInterfaceMethodInfo)) { error(opcode, "Invalid constant type for method invocation: " + ci); break; } ConstantInterfaceMethodInfo method = (ConstantInterfaceMethodInfo)ci; className = method.getParentClass().getType().getRootName(); nameAndType = method.getNameAndType(); } else { if (!(ci instanceof ConstantMethodInfo)) { error(opcode, "Invalid constant type for method invocation: " + ci); break; } ConstantMethodInfo method = (ConstantMethodInfo)ci; className = method.getParentClass().getType().getRootName(); if (mEnclosingClassName.equals(className)) { className = null; } nameAndType = method.getNameAndType(); } String methodName = nameAndType.getName(); desc = nameAndType.getType(); if (!(desc instanceof MethodDesc)) { error(opcode, "Invalid descriptor for method invocation: " + desc); break; } TypeDesc ret = ((MethodDesc)desc).getReturnType(); if (ret == TypeDesc.VOID) { ret = null; } TypeDesc[] paramTypes = ((MethodDesc)desc).getParameterTypes(); if (paramTypes.length == 0) { paramTypes = null; } switch (opcode) { case Opcode.INVOKEVIRTUAL: if (className == null) { assembler.invokeVirtual(methodName, ret, paramTypes); } else { assembler.invokeVirtual(className, methodName, ret, paramTypes); } break; case Opcode.INVOKESPECIAL: if ("<init>".equals(methodName)) { if (className == null) { assembler.invokeConstructor(paramTypes); } else { if ("<init>".equals(mMethod.getName()) && className.equals(mSuperClassName)) { assembler.invokeSuperConstructor(paramTypes); } else { assembler.invokeConstructor(className, paramTypes); } } } else { if (className == null) { assembler.invokePrivate(methodName, ret, paramTypes); } else { assembler.invokeSuper(className, methodName, ret, paramTypes); } } break; case Opcode.INVOKESTATIC: if (className == null) { assembler.invokeStatic(methodName, ret, paramTypes); } else { assembler.invokeStatic(className, methodName, ret, paramTypes); } break; case Opcode.INVOKEINTERFACE: assembler.invokeInterface(className, methodName, ret, paramTypes); break; } break; // End opcodes that load a constant from the constant pool. // Opcodes that load or store local variables... case Opcode.ILOAD: case Opcode.ISTORE: case Opcode.LLOAD: case Opcode.LSTORE: case Opcode.FLOAD: case Opcode.FSTORE: case Opcode.DLOAD: case Opcode.DSTORE: case Opcode.ALOAD: case Opcode.ASTORE: case Opcode.ILOAD_0: case Opcode.ISTORE_0: case Opcode.ILOAD_1: case Opcode.ISTORE_1: case Opcode.ILOAD_2: case Opcode.ISTORE_2: case Opcode.ILOAD_3: case Opcode.ISTORE_3: case Opcode.LLOAD_0: case Opcode.LSTORE_0: case Opcode.LLOAD_1: case Opcode.LSTORE_1: case Opcode.LLOAD_2: case Opcode.LSTORE_2: case Opcode.LLOAD_3: case Opcode.LSTORE_3: case Opcode.FLOAD_0: case Opcode.FSTORE_0: case Opcode.FLOAD_1: case Opcode.FSTORE_1: case Opcode.FLOAD_2: case Opcode.FSTORE_2: case Opcode.FLOAD_3: case Opcode.FSTORE_3: case Opcode.DLOAD_0: case Opcode.DSTORE_0: case Opcode.DLOAD_1: case Opcode.DSTORE_1: case Opcode.DLOAD_2: case Opcode.DSTORE_2: case Opcode.DLOAD_3: case Opcode.DSTORE_3: case Opcode.ALOAD_0: case Opcode.ASTORE_0: case Opcode.ALOAD_1: case Opcode.ASTORE_1: case Opcode.ALOAD_2: case Opcode.ASTORE_2: case Opcode.ALOAD_3: case Opcode.ASTORE_3: switch (opcode) { case Opcode.ILOAD: case Opcode.ISTORE: index = readUnsignedByte(); type = TypeDesc.INT; break; case Opcode.LLOAD: case Opcode.LSTORE: index = readUnsignedByte(); type = TypeDesc.LONG; break; case Opcode.FLOAD: case Opcode.FSTORE: index = readUnsignedByte(); type = TypeDesc.FLOAT; break; case Opcode.DLOAD: case Opcode.DSTORE: index = readUnsignedByte(); type = TypeDesc.DOUBLE; break; case Opcode.ALOAD: case Opcode.ASTORE: index = readUnsignedByte(); type = TypeDesc.OBJECT; break; case Opcode.ILOAD_0: case Opcode.ISTORE_0: index = 0; type = TypeDesc.INT; break; case Opcode.ILOAD_1: case Opcode.ISTORE_1: index = 1; type = TypeDesc.INT; break; case Opcode.ILOAD_2: case Opcode.ISTORE_2: index = 2; type = TypeDesc.INT; break; case Opcode.ILOAD_3: case Opcode.ISTORE_3: index = 3; type = TypeDesc.INT; break; case Opcode.LLOAD_0: case Opcode.LSTORE_0: index = 0; type = TypeDesc.LONG; break; case Opcode.LLOAD_1: case Opcode.LSTORE_1: index = 1; type = TypeDesc.LONG; break; case Opcode.LLOAD_2: case Opcode.LSTORE_2: index = 2; type = TypeDesc.LONG; break; case Opcode.LLOAD_3: case Opcode.LSTORE_3: index = 3; type = TypeDesc.LONG; break; case Opcode.FLOAD_0: case Opcode.FSTORE_0: index = 0; type = TypeDesc.FLOAT; break; case Opcode.FLOAD_1: case Opcode.FSTORE_1: index = 1; type = TypeDesc.FLOAT; break; case Opcode.FLOAD_2: case Opcode.FSTORE_2: index = 2; type = TypeDesc.FLOAT; break; case Opcode.FLOAD_3: case Opcode.FSTORE_3: index = 3; type = TypeDesc.FLOAT; break; case Opcode.DLOAD_0: case Opcode.DSTORE_0: index = 0; type = TypeDesc.DOUBLE; break; case Opcode.DLOAD_1: case Opcode.DSTORE_1: index = 1; type = TypeDesc.DOUBLE; break; case Opcode.DLOAD_2: case Opcode.DSTORE_2: index = 2; type = TypeDesc.DOUBLE; break; case Opcode.DLOAD_3: case Opcode.DSTORE_3: index = 3; type = TypeDesc.DOUBLE; break; case Opcode.ALOAD_0: case Opcode.ASTORE_0: index = 0; type = TypeDesc.OBJECT; break; case Opcode.ALOAD_1: case Opcode.ASTORE_1: index = 1; type = TypeDesc.OBJECT; break; case Opcode.ALOAD_2: case Opcode.ASTORE_2: index = 2; type = TypeDesc.OBJECT; break; case Opcode.ALOAD_3: case Opcode.ASTORE_3: index = 3; type = TypeDesc.OBJECT; break; default: index = 0; type = null; break; } switch (opcode) { case Opcode.ILOAD: case Opcode.LLOAD: case Opcode.FLOAD: case Opcode.DLOAD: case Opcode.ALOAD: case Opcode.ILOAD_0: case Opcode.ILOAD_1: case Opcode.ILOAD_2: case Opcode.ILOAD_3: case Opcode.LLOAD_0: case Opcode.LLOAD_1: case Opcode.LLOAD_2: case Opcode.LLOAD_3: case Opcode.FLOAD_0: case Opcode.FLOAD_1: case Opcode.FLOAD_2: case Opcode.FLOAD_3: case Opcode.DLOAD_0: case Opcode.DLOAD_1: case Opcode.DLOAD_2: case Opcode.DLOAD_3: case Opcode.ALOAD_0: case Opcode.ALOAD_1: case Opcode.ALOAD_2: case Opcode.ALOAD_3: if (index == 0 && mHasThis) { assembler.loadThis(); } else { assembler.loadLocal(getLocalVariable(index, type)); } break; case Opcode.ISTORE: case Opcode.LSTORE: case Opcode.FSTORE: case Opcode.DSTORE: case Opcode.ASTORE: case Opcode.ISTORE_0: case Opcode.ISTORE_1: case Opcode.ISTORE_2: case Opcode.ISTORE_3: case Opcode.LSTORE_0: case Opcode.LSTORE_1: case Opcode.LSTORE_2: case Opcode.LSTORE_3: case Opcode.FSTORE_0: case Opcode.FSTORE_1: case Opcode.FSTORE_2: case Opcode.FSTORE_3: case Opcode.DSTORE_0: case Opcode.DSTORE_1: case Opcode.DSTORE_2: case Opcode.DSTORE_3: case Opcode.ASTORE_0: case Opcode.ASTORE_1: case Opcode.ASTORE_2: case Opcode.ASTORE_3: if (index == 0 && mHasThis) { // The "this" reference just got blown away. mHasThis = false; } assembler.storeLocal(getLocalVariable(index, type)); break; } break; case Opcode.RET: LocalVariable local = getLocalVariable (readUnsignedByte(), TypeDesc.OBJECT); assembler.ret(local); break; case Opcode.IINC: local = getLocalVariable(readUnsignedByte(), TypeDesc.INT); assembler.integerIncrement(local, readByte()); break; // End opcodes that load or store local variables. // Opcodes that branch to another address. case Opcode.GOTO: loc = getLabel(mAddress + readShort()); assembler.branch(loc); break; case Opcode.JSR: loc = getLabel(mAddress + readShort()); assembler.jsr(loc); break; case Opcode.GOTO_W: loc = getLabel(mAddress + readInt()); assembler.branch(loc); break; case Opcode.JSR_W: loc = getLabel(mAddress + readInt()); assembler.jsr(loc); break; case Opcode.IFNULL: loc = getLabel(mAddress + readShort()); assembler.ifNullBranch(loc, true); break; case Opcode.IFNONNULL: loc = getLabel(mAddress + readShort()); assembler.ifNullBranch(loc, false); break; case Opcode.IF_ACMPEQ: loc = getLabel(mAddress + readShort()); assembler.ifEqualBranch(loc, true); break; case Opcode.IF_ACMPNE: loc = getLabel(mAddress + readShort()); assembler.ifEqualBranch(loc, false); break; case Opcode.IFEQ: case Opcode.IFNE: case Opcode.IFLT: case Opcode.IFGE: case Opcode.IFGT: case Opcode.IFLE: loc = getLabel(mAddress + readShort()); String choice; switch (opcode) { case Opcode.IFEQ: choice = "=="; break; case Opcode.IFNE: choice = "!="; break; case Opcode.IFLT: choice = "<"; break; case Opcode.IFGE: choice = ">="; break; case Opcode.IFGT: choice = ">"; break; case Opcode.IFLE: choice = "<="; break; default: choice = null; break; } assembler.ifZeroComparisonBranch(loc, choice); break; case Opcode.IF_ICMPEQ: case Opcode.IF_ICMPNE: case Opcode.IF_ICMPLT: case Opcode.IF_ICMPGE: case Opcode.IF_ICMPGT: case Opcode.IF_ICMPLE: loc = getLabel(mAddress + readShort()); switch (opcode) { case Opcode.IF_ICMPEQ: choice = "=="; break; case Opcode.IF_ICMPNE: choice = "!="; break; case Opcode.IF_ICMPLT: choice = "<"; break; case Opcode.IF_ICMPGE: choice = ">="; break; case Opcode.IF_ICMPGT: choice = ">"; break; case Opcode.IF_ICMPLE: choice = "<="; break; default: choice = null; break; } assembler.ifComparisonBranch(loc, choice); break; // End opcodes that branch to another address. // Miscellaneous opcodes... case Opcode.BIPUSH: assembler.loadConstant(readByte()); break; case Opcode.SIPUSH: assembler.loadConstant(readShort()); break; case Opcode.NEWARRAY: int atype = readByte(); type = null; switch (atype) { case 4: // T_BOOLEAN type = TypeDesc.BOOLEAN; break; case 5: // T_CHAR type = TypeDesc.CHAR; break; case 6: // T_FLOAT type = TypeDesc.FLOAT; break; case 7: // T_DOUBLE type = TypeDesc.DOUBLE; break; case 8: // T_BYTE type = TypeDesc.BYTE; break; case 9: // T_SHORT type = TypeDesc.SHORT; break; case 10: // T_INT type = TypeDesc.INT; break; case 11: // T_LONG type = TypeDesc.LONG; break; } if (type == null) { error(opcode, "Unknown primitive type for new array: " + atype); break; } assembler.newObject(type.toArrayType()); break; case Opcode.TABLESWITCH: case Opcode.LOOKUPSWITCH: int opcodeAddress = mAddress; // Read padding until address is 32 bit word aligned. while (((mAddress + 1) & 3) != 0) { ++mAddress; } Location defaultLocation = getLabel(opcodeAddress + readInt()); int[] cases; Location[] locations; if (opcode == Opcode.TABLESWITCH) { int lowValue = readInt(); int highValue = readInt(); int caseCount = highValue - lowValue + 1; try { cases = new int[caseCount]; } catch (NegativeArraySizeException e) { error(opcode, "Negative case count for switch: " + caseCount); break; } locations = new Location[caseCount]; for (int i=0; i<caseCount; i++) { cases[i] = lowValue + i; locations[i] = getLabel(opcodeAddress + readInt()); } } else { int caseCount = readInt(); try { cases = new int[caseCount]; } catch (NegativeArraySizeException e) { error(opcode, "Negative case count for switch: " + caseCount); break; } locations = new Location[caseCount]; for (int i=0; i<caseCount; i++) { cases[i] = readInt(); locations[i] = getLabel(opcodeAddress + readInt()); } } assembler.switchBranch(cases, locations, defaultLocation); break; case Opcode.WIDE: opcode = mByteCodes[++mAddress]; switch (opcode) { default: error(opcode, "Unknown wide instruction"); break; case Opcode.ILOAD: case Opcode.ISTORE: case Opcode.LLOAD: case Opcode.LSTORE: case Opcode.FLOAD: case Opcode.FSTORE: case Opcode.DLOAD: case Opcode.DSTORE: case Opcode.ALOAD: case Opcode.ASTORE: switch (opcode) { case Opcode.ILOAD: case Opcode.ISTORE: type = TypeDesc.INT; break; case Opcode.LLOAD: case Opcode.LSTORE: type = TypeDesc.LONG; break; case Opcode.FLOAD: case Opcode.FSTORE: type = TypeDesc.FLOAT; break; case Opcode.DLOAD: case Opcode.DSTORE: type = TypeDesc.DOUBLE; break; case Opcode.ALOAD: case Opcode.ASTORE: type = TypeDesc.OBJECT; break; default: type = null; break; } index = readUnsignedShort(); switch (opcode) { case Opcode.ILOAD: case Opcode.LLOAD: case Opcode.FLOAD: case Opcode.DLOAD: case Opcode.ALOAD: if (index == 0 && mHasThis) { assembler.loadThis(); } else { assembler.loadLocal(getLocalVariable(index, type)); } break; case Opcode.ISTORE: case Opcode.LSTORE: case Opcode.FSTORE: case Opcode.DSTORE: case Opcode.ASTORE: if (index == 0 && mHasThis) { // The "this" reference just got blown away. mHasThis = false; } assembler.storeLocal(getLocalVariable(index, type)); break; } break; case Opcode.RET: local = getLocalVariable (readUnsignedShort(), TypeDesc.OBJECT); assembler.ret(local); break; case Opcode.IINC: local = getLocalVariable (readUnsignedShort(), TypeDesc.INT); assembler.integerIncrement(local, readShort()); break; } break; } // end huge switch } // end for loop }
diff --git a/teams/confusedteam/RobotPlayer.java b/teams/confusedteam/RobotPlayer.java index 3e1e9dc..48cf433 100644 --- a/teams/confusedteam/RobotPlayer.java +++ b/teams/confusedteam/RobotPlayer.java @@ -1,222 +1,227 @@ package confusedteam; import battlecode.common.Direction; import battlecode.common.GameConstants; import battlecode.common.RobotController; import battlecode.common.RobotType; import battlecode.common.*; import java.util.*; /** The example funcs player is a player meant to demonstrate basic usage of the most common commands. * Robots will move around randomly, occasionally mining and writing useless messages. * The HQ will spawn soldiers continuously. */ public class RobotPlayer { public static int arrIndexOf(Object[] objs, Object o){ for(int i = 0; i < objs.length; i++){ if(objs[i].equals(o)) return i; } return -1; } public static void run(RobotController rc) { while (true) { try { if (rc.getType() == RobotType.HQ) { if (rc.isActive()) { if(rc.senseEnemyNukeHalfDone()){ rc.broadcast(1354, 1000); } else{ rc.broadcast(1354, 100); } if((int)rc.getEnergon() < rc.readBroadcast(1257)){ rc.broadcast(1489, 1000); } else{ rc.broadcast(1489, 100); } rc.broadcast(1257, (int)rc.getEnergon()); // Robot[] enemies = rc.senseNearbyGameObjects(Robot.class, 100, rc.getTeam().opponent()); // System.out.println(enemies.length + " enemies found"); // if(enemies.length > 0){ // MapLocation loc = rc.senseRobotInfo(enemies[0]).location; // System.out.println("x: " + loc.x + " y: " + loc.y); // } /*if(rc.checkResearchProgress(Upgrade.PICKAXE) < Upgrade.PICKAXE.numRounds && Math.random() > 0.25){ rc.researchUpgrade(Upgrade.PICKAXE); } else*/ if(rc.getTeamPower() > 25 && Math.random() < 0.4){ // Spawn a soldier Direction dir = rc.getLocation().directionTo(rc.senseEnemyHQLocation()); if(rc.senseMineLocations(rc.getLocation(), 2, rc.getTeam()).length < 8){ for(Direction d : Direction.values()){ if(rc.senseMine(rc.getLocation().add(d))==null){ dir = d; break; } } } - while(!rc.canMove(dir) || (dir.equals(Direction.NONE) || dir.equals(Direction.OMNI))){ + int i = 0; + while(i < 10 && (!rc.canMove(dir) || (dir.equals(Direction.NONE) || dir.equals(Direction.OMNI)))){ dir = Direction.values()[(int)(Math.random()*8)]; + i++; } if (rc.canMove(dir)){ -// System.out.println(rc.getTeamPower()); + System.out.println("spawning soldier"); rc.spawn(dir); } - else + else{ + System.out.println("researching nuke cuz cant spawn"); rc.researchUpgrade(Upgrade.NUKE); + } } else{ + System.out.println("researching nuke"); rc.researchUpgrade(Upgrade.NUKE); } } } else if (rc.getType() == RobotType.SOLDIER) { if (rc.isActive()) { if(rc.senseEncampmentSquare(rc.getLocation()) && rc.getTeamPower() > rc.senseCaptureCost()){ RobotType[] far = {RobotType.GENERATOR, RobotType.SUPPLIER, RobotType.SUPPLIER, RobotType.ARTILLERY}; RobotType[] close = {RobotType.ARTILLERY}; RobotType[] mid = {RobotType.ARTILLERY}; // RobotType[] mid = Arrays.copyOf(close, close.length); MapLocation loc = rc.getLocation(); int hqDist = loc.distanceSquaredTo(rc.senseEnemyHQLocation()); int totalDist = rc.senseHQLocation().distanceSquaredTo(rc.senseEnemyHQLocation()); if(hqDist < totalDist/3 && rc.getTeamPower() > rc.senseCaptureCost()){ rc.captureEncampment(close[(int)(Math.random()*close.length)]); } else if(hqDist < totalDist*2/3 && rc.getTeamPower() > rc.senseCaptureCost()){ rc.captureEncampment(mid[(int)(Math.random()*mid.length)]); } else if(rc.getTeamPower() > rc.senseCaptureCost()){ rc.captureEncampment(far[(int)(Math.random()*far.length)]); } } else { // Choose a random direction, and move that way if possible MapLocation loc = rc.getLocation(); // int hqDist = rc.senseEnemyHQLocation().distanceSquaredTo(loc); MapLocation target; Direction dir; Robot me = (Robot)rc.senseObjectAtLocation(loc); - if(me.getID()%3 == 2 || (rc.getTeamPower() > GameConstants.BROADCAST_READ_COST && rc.readBroadcast(1257) > 500)){ + if(me.getID()%3==0 || (rc.getTeamPower() > GameConstants.BROADCAST_READ_COST && rc.readBroadcast(1354) > 500)){ + target = rc.senseEnemyHQLocation(); + dir = loc.directionTo(target); + } + else if(me.getID()%3 == 2 || (rc.getTeamPower() > GameConstants.BROADCAST_READ_COST && rc.readBroadcast(1257) > 500)){ target = rc.senseHQLocation().add(rc.senseHQLocation().directionTo(rc.senseEnemyHQLocation())); dir = loc.directionTo(target); if (rc.senseMine(rc.getLocation()) == null && Math.random()<0.5) { // Lay a mine // if(rc.senseMine(rc.getLocation())==null) rc.layMine(); continue; } else if(rc.senseMineLocations(rc.senseHQLocation(), 2, rc.getTeam()).length < 8){ for(Direction d : Direction.values()){ if(rc.senseMine(rc.senseHQLocation().add(d))==null){ System.out.println("mine found missing in direction " + dir); dir = loc.directionTo(rc.senseHQLocation().add(d)); break; } } } } - else if(me.getID()%3==0 || (rc.getTeamPower() > GameConstants.BROADCAST_READ_COST && rc.readBroadcast(1354) > 500)){ - target = rc.senseEnemyHQLocation(); - dir = loc.directionTo(target); - } else{ target = rc.senseEnemyHQLocation(); dir = loc.directionTo(target); for(MapLocation camp : rc.senseEncampmentSquares(loc, 14, Team.NEUTRAL)){ if(camp.distanceSquaredTo(loc) < loc.distanceSquaredTo(target)){ dir = loc.directionTo(camp); target = camp; } } } target = rc.getLocation().add(dir); if(!dir.equals(Direction.NONE) && !dir.equals(Direction.OMNI) && rc.canMove(dir)){ if(rc.senseMine(target) == null || rc.senseMine(target).equals(rc.getTeam())) { rc.move(dir); rc.setIndicatorString(0, "Last direction moved: "+dir.toString()); } else if(!rc.senseMine(target).equals(rc.getTeam())){ rc.defuseMine(target); } } else{ do{ dir = Direction.values()[(int)(Math.random()*8)]; } while(!rc.canMove(dir) || (dir.equals(Direction.NONE) || dir.equals(Direction.OMNI))); target = rc.getLocation().add(dir); if(rc.canMove(dir) && (rc.senseMine(target) == null || rc.senseMine(target).equals(rc.getTeam()))) { rc.move(dir); rc.setIndicatorString(0, "Last direction moved: "+dir.toString()); } else if(!rc.senseMine(target).equals(rc.getTeam())){ rc.defuseMine(target); } } } } // if (Math.random()<0.01 && rc.getTeamPower()>5) { // // Write the number 5 to a position on the message board corresponding to the robot's ID // rc.broadcast(rc.getRobot().getID()%GameConstants.BROADCAST_MAX_CHANNELS, 5); // } } else if(rc.getType() == RobotType.ARTILLERY){ if(rc.isActive()){ MapLocation target = rc.getLocation(); MapLocation loc = rc.getLocation(); Robot[] enemies = rc.senseNearbyGameObjects(Robot.class, 63, rc.getTeam().opponent()); // Robot[] friends = rc.senseNearbyGameObjects(Robot.class, 63, rc.getTeam()); MapLocation[] enemyLocs = new MapLocation[enemies.length]; // MapLocation[] friendLocs = new MapLocation[friends.length]; int avg = 0; for(int i = 0; i < enemies.length; i++){ enemyLocs[i] = rc.senseRobotInfo(enemies[i]).location; avg += enemyLocs[i].distanceSquaredTo(loc); } if(enemies.length > 0){ avg /= enemies.length; target = enemyLocs[0]; } if(avg > 0) for(MapLocation aim : enemyLocs){ if(Math.abs(avg - aim.distanceSquaredTo(loc)) < 100){ target = aim; } } MapLocation[] enemyCamps = rc.senseEncampmentSquares(loc, 63, Team.NEUTRAL); for(MapLocation l : enemyCamps){ if(rc.canSenseSquare(l)){ Robot camp = (Robot) rc.senseObjectAtLocation(l); if(camp != null && !camp.getTeam().equals(rc.getTeam()) && arrIndexOf(enemyLocs, l) >= 0){ target = l; } } } if(arrIndexOf(enemyLocs, rc.senseEnemyHQLocation()) >= 0){ target = rc.senseEnemyHQLocation(); } // Direction dir = target.directionTo(rc.senseEnemyHQLocation()); // for(int i = 0; i < 5; i++){ // target = target.add(dir); // dir = target.directionTo(rc.senseEnemyHQLocation()); // } System.out.println("artillery"); if(rc.canAttackSquare(target) && avg > 0) rc.attackSquare(target); } } // End turn rc.yield(); } catch (Exception e) { e.printStackTrace(); } } } }
false
true
public static void run(RobotController rc) { while (true) { try { if (rc.getType() == RobotType.HQ) { if (rc.isActive()) { if(rc.senseEnemyNukeHalfDone()){ rc.broadcast(1354, 1000); } else{ rc.broadcast(1354, 100); } if((int)rc.getEnergon() < rc.readBroadcast(1257)){ rc.broadcast(1489, 1000); } else{ rc.broadcast(1489, 100); } rc.broadcast(1257, (int)rc.getEnergon()); // Robot[] enemies = rc.senseNearbyGameObjects(Robot.class, 100, rc.getTeam().opponent()); // System.out.println(enemies.length + " enemies found"); // if(enemies.length > 0){ // MapLocation loc = rc.senseRobotInfo(enemies[0]).location; // System.out.println("x: " + loc.x + " y: " + loc.y); // } /*if(rc.checkResearchProgress(Upgrade.PICKAXE) < Upgrade.PICKAXE.numRounds && Math.random() > 0.25){ rc.researchUpgrade(Upgrade.PICKAXE); } else*/ if(rc.getTeamPower() > 25 && Math.random() < 0.4){ // Spawn a soldier Direction dir = rc.getLocation().directionTo(rc.senseEnemyHQLocation()); if(rc.senseMineLocations(rc.getLocation(), 2, rc.getTeam()).length < 8){ for(Direction d : Direction.values()){ if(rc.senseMine(rc.getLocation().add(d))==null){ dir = d; break; } } } while(!rc.canMove(dir) || (dir.equals(Direction.NONE) || dir.equals(Direction.OMNI))){ dir = Direction.values()[(int)(Math.random()*8)]; } if (rc.canMove(dir)){ // System.out.println(rc.getTeamPower()); rc.spawn(dir); } else rc.researchUpgrade(Upgrade.NUKE); } else{ rc.researchUpgrade(Upgrade.NUKE); } } } else if (rc.getType() == RobotType.SOLDIER) { if (rc.isActive()) { if(rc.senseEncampmentSquare(rc.getLocation()) && rc.getTeamPower() > rc.senseCaptureCost()){ RobotType[] far = {RobotType.GENERATOR, RobotType.SUPPLIER, RobotType.SUPPLIER, RobotType.ARTILLERY}; RobotType[] close = {RobotType.ARTILLERY}; RobotType[] mid = {RobotType.ARTILLERY}; // RobotType[] mid = Arrays.copyOf(close, close.length); MapLocation loc = rc.getLocation(); int hqDist = loc.distanceSquaredTo(rc.senseEnemyHQLocation()); int totalDist = rc.senseHQLocation().distanceSquaredTo(rc.senseEnemyHQLocation()); if(hqDist < totalDist/3 && rc.getTeamPower() > rc.senseCaptureCost()){ rc.captureEncampment(close[(int)(Math.random()*close.length)]); } else if(hqDist < totalDist*2/3 && rc.getTeamPower() > rc.senseCaptureCost()){ rc.captureEncampment(mid[(int)(Math.random()*mid.length)]); } else if(rc.getTeamPower() > rc.senseCaptureCost()){ rc.captureEncampment(far[(int)(Math.random()*far.length)]); } } else { // Choose a random direction, and move that way if possible MapLocation loc = rc.getLocation(); // int hqDist = rc.senseEnemyHQLocation().distanceSquaredTo(loc); MapLocation target; Direction dir; Robot me = (Robot)rc.senseObjectAtLocation(loc); if(me.getID()%3 == 2 || (rc.getTeamPower() > GameConstants.BROADCAST_READ_COST && rc.readBroadcast(1257) > 500)){ target = rc.senseHQLocation().add(rc.senseHQLocation().directionTo(rc.senseEnemyHQLocation())); dir = loc.directionTo(target); if (rc.senseMine(rc.getLocation()) == null && Math.random()<0.5) { // Lay a mine // if(rc.senseMine(rc.getLocation())==null) rc.layMine(); continue; } else if(rc.senseMineLocations(rc.senseHQLocation(), 2, rc.getTeam()).length < 8){ for(Direction d : Direction.values()){ if(rc.senseMine(rc.senseHQLocation().add(d))==null){ System.out.println("mine found missing in direction " + dir); dir = loc.directionTo(rc.senseHQLocation().add(d)); break; } } } } else if(me.getID()%3==0 || (rc.getTeamPower() > GameConstants.BROADCAST_READ_COST && rc.readBroadcast(1354) > 500)){ target = rc.senseEnemyHQLocation(); dir = loc.directionTo(target); } else{ target = rc.senseEnemyHQLocation(); dir = loc.directionTo(target); for(MapLocation camp : rc.senseEncampmentSquares(loc, 14, Team.NEUTRAL)){ if(camp.distanceSquaredTo(loc) < loc.distanceSquaredTo(target)){ dir = loc.directionTo(camp); target = camp; } } } target = rc.getLocation().add(dir); if(!dir.equals(Direction.NONE) && !dir.equals(Direction.OMNI) && rc.canMove(dir)){ if(rc.senseMine(target) == null || rc.senseMine(target).equals(rc.getTeam())) { rc.move(dir); rc.setIndicatorString(0, "Last direction moved: "+dir.toString()); } else if(!rc.senseMine(target).equals(rc.getTeam())){ rc.defuseMine(target); } } else{ do{ dir = Direction.values()[(int)(Math.random()*8)]; } while(!rc.canMove(dir) || (dir.equals(Direction.NONE) || dir.equals(Direction.OMNI))); target = rc.getLocation().add(dir); if(rc.canMove(dir) && (rc.senseMine(target) == null || rc.senseMine(target).equals(rc.getTeam()))) { rc.move(dir); rc.setIndicatorString(0, "Last direction moved: "+dir.toString()); } else if(!rc.senseMine(target).equals(rc.getTeam())){ rc.defuseMine(target); } } } } // if (Math.random()<0.01 && rc.getTeamPower()>5) { // // Write the number 5 to a position on the message board corresponding to the robot's ID // rc.broadcast(rc.getRobot().getID()%GameConstants.BROADCAST_MAX_CHANNELS, 5); // } } else if(rc.getType() == RobotType.ARTILLERY){ if(rc.isActive()){ MapLocation target = rc.getLocation(); MapLocation loc = rc.getLocation(); Robot[] enemies = rc.senseNearbyGameObjects(Robot.class, 63, rc.getTeam().opponent()); // Robot[] friends = rc.senseNearbyGameObjects(Robot.class, 63, rc.getTeam()); MapLocation[] enemyLocs = new MapLocation[enemies.length]; // MapLocation[] friendLocs = new MapLocation[friends.length]; int avg = 0; for(int i = 0; i < enemies.length; i++){ enemyLocs[i] = rc.senseRobotInfo(enemies[i]).location; avg += enemyLocs[i].distanceSquaredTo(loc); } if(enemies.length > 0){ avg /= enemies.length; target = enemyLocs[0]; } if(avg > 0) for(MapLocation aim : enemyLocs){ if(Math.abs(avg - aim.distanceSquaredTo(loc)) < 100){ target = aim; } } MapLocation[] enemyCamps = rc.senseEncampmentSquares(loc, 63, Team.NEUTRAL); for(MapLocation l : enemyCamps){ if(rc.canSenseSquare(l)){ Robot camp = (Robot) rc.senseObjectAtLocation(l); if(camp != null && !camp.getTeam().equals(rc.getTeam()) && arrIndexOf(enemyLocs, l) >= 0){ target = l; } } } if(arrIndexOf(enemyLocs, rc.senseEnemyHQLocation()) >= 0){ target = rc.senseEnemyHQLocation(); } // Direction dir = target.directionTo(rc.senseEnemyHQLocation()); // for(int i = 0; i < 5; i++){ // target = target.add(dir); // dir = target.directionTo(rc.senseEnemyHQLocation()); // } System.out.println("artillery"); if(rc.canAttackSquare(target) && avg > 0) rc.attackSquare(target); } } // End turn rc.yield(); } catch (Exception e) { e.printStackTrace(); } }
public static void run(RobotController rc) { while (true) { try { if (rc.getType() == RobotType.HQ) { if (rc.isActive()) { if(rc.senseEnemyNukeHalfDone()){ rc.broadcast(1354, 1000); } else{ rc.broadcast(1354, 100); } if((int)rc.getEnergon() < rc.readBroadcast(1257)){ rc.broadcast(1489, 1000); } else{ rc.broadcast(1489, 100); } rc.broadcast(1257, (int)rc.getEnergon()); // Robot[] enemies = rc.senseNearbyGameObjects(Robot.class, 100, rc.getTeam().opponent()); // System.out.println(enemies.length + " enemies found"); // if(enemies.length > 0){ // MapLocation loc = rc.senseRobotInfo(enemies[0]).location; // System.out.println("x: " + loc.x + " y: " + loc.y); // } /*if(rc.checkResearchProgress(Upgrade.PICKAXE) < Upgrade.PICKAXE.numRounds && Math.random() > 0.25){ rc.researchUpgrade(Upgrade.PICKAXE); } else*/ if(rc.getTeamPower() > 25 && Math.random() < 0.4){ // Spawn a soldier Direction dir = rc.getLocation().directionTo(rc.senseEnemyHQLocation()); if(rc.senseMineLocations(rc.getLocation(), 2, rc.getTeam()).length < 8){ for(Direction d : Direction.values()){ if(rc.senseMine(rc.getLocation().add(d))==null){ dir = d; break; } } } int i = 0; while(i < 10 && (!rc.canMove(dir) || (dir.equals(Direction.NONE) || dir.equals(Direction.OMNI)))){ dir = Direction.values()[(int)(Math.random()*8)]; i++; } if (rc.canMove(dir)){ System.out.println("spawning soldier"); rc.spawn(dir); } else{ System.out.println("researching nuke cuz cant spawn"); rc.researchUpgrade(Upgrade.NUKE); } } else{ System.out.println("researching nuke"); rc.researchUpgrade(Upgrade.NUKE); } } } else if (rc.getType() == RobotType.SOLDIER) { if (rc.isActive()) { if(rc.senseEncampmentSquare(rc.getLocation()) && rc.getTeamPower() > rc.senseCaptureCost()){ RobotType[] far = {RobotType.GENERATOR, RobotType.SUPPLIER, RobotType.SUPPLIER, RobotType.ARTILLERY}; RobotType[] close = {RobotType.ARTILLERY}; RobotType[] mid = {RobotType.ARTILLERY}; // RobotType[] mid = Arrays.copyOf(close, close.length); MapLocation loc = rc.getLocation(); int hqDist = loc.distanceSquaredTo(rc.senseEnemyHQLocation()); int totalDist = rc.senseHQLocation().distanceSquaredTo(rc.senseEnemyHQLocation()); if(hqDist < totalDist/3 && rc.getTeamPower() > rc.senseCaptureCost()){ rc.captureEncampment(close[(int)(Math.random()*close.length)]); } else if(hqDist < totalDist*2/3 && rc.getTeamPower() > rc.senseCaptureCost()){ rc.captureEncampment(mid[(int)(Math.random()*mid.length)]); } else if(rc.getTeamPower() > rc.senseCaptureCost()){ rc.captureEncampment(far[(int)(Math.random()*far.length)]); } } else { // Choose a random direction, and move that way if possible MapLocation loc = rc.getLocation(); // int hqDist = rc.senseEnemyHQLocation().distanceSquaredTo(loc); MapLocation target; Direction dir; Robot me = (Robot)rc.senseObjectAtLocation(loc); if(me.getID()%3==0 || (rc.getTeamPower() > GameConstants.BROADCAST_READ_COST && rc.readBroadcast(1354) > 500)){ target = rc.senseEnemyHQLocation(); dir = loc.directionTo(target); } else if(me.getID()%3 == 2 || (rc.getTeamPower() > GameConstants.BROADCAST_READ_COST && rc.readBroadcast(1257) > 500)){ target = rc.senseHQLocation().add(rc.senseHQLocation().directionTo(rc.senseEnemyHQLocation())); dir = loc.directionTo(target); if (rc.senseMine(rc.getLocation()) == null && Math.random()<0.5) { // Lay a mine // if(rc.senseMine(rc.getLocation())==null) rc.layMine(); continue; } else if(rc.senseMineLocations(rc.senseHQLocation(), 2, rc.getTeam()).length < 8){ for(Direction d : Direction.values()){ if(rc.senseMine(rc.senseHQLocation().add(d))==null){ System.out.println("mine found missing in direction " + dir); dir = loc.directionTo(rc.senseHQLocation().add(d)); break; } } } } else{ target = rc.senseEnemyHQLocation(); dir = loc.directionTo(target); for(MapLocation camp : rc.senseEncampmentSquares(loc, 14, Team.NEUTRAL)){ if(camp.distanceSquaredTo(loc) < loc.distanceSquaredTo(target)){ dir = loc.directionTo(camp); target = camp; } } } target = rc.getLocation().add(dir); if(!dir.equals(Direction.NONE) && !dir.equals(Direction.OMNI) && rc.canMove(dir)){ if(rc.senseMine(target) == null || rc.senseMine(target).equals(rc.getTeam())) { rc.move(dir); rc.setIndicatorString(0, "Last direction moved: "+dir.toString()); } else if(!rc.senseMine(target).equals(rc.getTeam())){ rc.defuseMine(target); } } else{ do{ dir = Direction.values()[(int)(Math.random()*8)]; } while(!rc.canMove(dir) || (dir.equals(Direction.NONE) || dir.equals(Direction.OMNI))); target = rc.getLocation().add(dir); if(rc.canMove(dir) && (rc.senseMine(target) == null || rc.senseMine(target).equals(rc.getTeam()))) { rc.move(dir); rc.setIndicatorString(0, "Last direction moved: "+dir.toString()); } else if(!rc.senseMine(target).equals(rc.getTeam())){ rc.defuseMine(target); } } } } // if (Math.random()<0.01 && rc.getTeamPower()>5) { // // Write the number 5 to a position on the message board corresponding to the robot's ID // rc.broadcast(rc.getRobot().getID()%GameConstants.BROADCAST_MAX_CHANNELS, 5); // } } else if(rc.getType() == RobotType.ARTILLERY){ if(rc.isActive()){ MapLocation target = rc.getLocation(); MapLocation loc = rc.getLocation(); Robot[] enemies = rc.senseNearbyGameObjects(Robot.class, 63, rc.getTeam().opponent()); // Robot[] friends = rc.senseNearbyGameObjects(Robot.class, 63, rc.getTeam()); MapLocation[] enemyLocs = new MapLocation[enemies.length]; // MapLocation[] friendLocs = new MapLocation[friends.length]; int avg = 0; for(int i = 0; i < enemies.length; i++){ enemyLocs[i] = rc.senseRobotInfo(enemies[i]).location; avg += enemyLocs[i].distanceSquaredTo(loc); } if(enemies.length > 0){ avg /= enemies.length; target = enemyLocs[0]; } if(avg > 0) for(MapLocation aim : enemyLocs){ if(Math.abs(avg - aim.distanceSquaredTo(loc)) < 100){ target = aim; } } MapLocation[] enemyCamps = rc.senseEncampmentSquares(loc, 63, Team.NEUTRAL); for(MapLocation l : enemyCamps){ if(rc.canSenseSquare(l)){ Robot camp = (Robot) rc.senseObjectAtLocation(l); if(camp != null && !camp.getTeam().equals(rc.getTeam()) && arrIndexOf(enemyLocs, l) >= 0){ target = l; } } } if(arrIndexOf(enemyLocs, rc.senseEnemyHQLocation()) >= 0){ target = rc.senseEnemyHQLocation(); } // Direction dir = target.directionTo(rc.senseEnemyHQLocation()); // for(int i = 0; i < 5; i++){ // target = target.add(dir); // dir = target.directionTo(rc.senseEnemyHQLocation()); // } System.out.println("artillery"); if(rc.canAttackSquare(target) && avg > 0) rc.attackSquare(target); } } // End turn rc.yield(); } catch (Exception e) { e.printStackTrace(); } }
diff --git a/src/flow/netbeans/markdown/options/MarkdownPanel.java b/src/flow/netbeans/markdown/options/MarkdownPanel.java index 130f645..19d495f 100644 --- a/src/flow/netbeans/markdown/options/MarkdownPanel.java +++ b/src/flow/netbeans/markdown/options/MarkdownPanel.java @@ -1,443 +1,443 @@ package flow.netbeans.markdown.options; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.JEditorPane; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.Document; import javax.swing.text.EditorKit; import org.netbeans.api.editor.DialogBinding; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileSystem; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataObject; import org.openide.text.CloneableEditorSupport; import org.openide.util.Exceptions; public final class MarkdownPanel extends javax.swing.JPanel { private final MarkdownOptionsPanelController controller; private static final long serialVersionUID = -2655146103696320933L; MarkdownPanel(MarkdownOptionsPanelController controller) { this.controller = controller; initComponents(); setMimeType(HTML_TEMPLATE, "text/html", "html"); ActionListener actionListener = new ActionHandler(); ABBREVIATIONS.addActionListener(actionListener); AUTOLINKS.addActionListener(actionListener); DEFINITION_LISTS.addActionListener(actionListener); FENCED_CODE_BLOCKS.addActionListener(actionListener); HARDWRAPS.addActionListener(actionListener); HTML_BLOCK_SUPPRESSION.addActionListener(actionListener); INLINE_HTML_SUPPRESSION.addActionListener(actionListener); QUOTES.addActionListener(actionListener); SMARTS.addActionListener(actionListener); TABLES.addActionListener(actionListener); WIKILINKS.addActionListener(actionListener); DocumentListener documentListener = new DocumentHandler(); HTML_TEMPLATE.getDocument().addDocumentListener(documentListener); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { TABS = new javax.swing.JTabbedPane(); EXTENSIONS_PANEL = new javax.swing.JPanel(); EXTENSIONS_PANEL_HEADER = new javax.swing.JLabel(); SMARTS = new javax.swing.JCheckBox(); QUOTES = new javax.swing.JCheckBox(); ABBREVIATIONS = new javax.swing.JCheckBox(); HARDWRAPS = new javax.swing.JCheckBox(); AUTOLINKS = new javax.swing.JCheckBox(); TABLES = new javax.swing.JCheckBox(); DEFINITION_LISTS = new javax.swing.JCheckBox(); FENCED_CODE_BLOCKS = new javax.swing.JCheckBox(); HTML_BLOCK_SUPPRESSION = new javax.swing.JCheckBox(); INLINE_HTML_SUPPRESSION = new javax.swing.JCheckBox(); WIKILINKS = new javax.swing.JCheckBox(); HTML_EXPORT_PANEL = new javax.swing.JPanel(); HTML_PANEL_HEADER = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); HTML_TEMPLATE = new javax.swing.JEditorPane(); MISC_PANEL = new javax.swing.JPanel(); VIEW_HTML_ON_SAVE = new javax.swing.JCheckBox(); SAVE_IN_SOURCE_DIR = new javax.swing.JCheckBox(); TYPING_HOOKS = new javax.swing.JCheckBox(); AUTO_ADDITION_LIST = new javax.swing.JCheckBox(); REMOVE_EMPTY_LIST = new javax.swing.JCheckBox(); REORDER_ORDERED_LIST_NUMBER = new javax.swing.JCheckBox(); REMOVE_ORDERED_LIST_NUMBER = new javax.swing.JCheckBox(); org.openide.awt.Mnemonics.setLocalizedText(EXTENSIONS_PANEL_HEADER, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.EXTENSIONS_PANEL_HEADER.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(SMARTS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.SMARTS.text")); // NOI18N SMARTS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.SMARTS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(QUOTES, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.QUOTES.text")); // NOI18N QUOTES.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.QUOTES.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(ABBREVIATIONS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.ABBREVIATIONS.text")); // NOI18N ABBREVIATIONS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.ABBREVIATIONS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(HARDWRAPS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HARDWRAPS.text")); // NOI18N HARDWRAPS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HARDWRAPS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(AUTOLINKS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.AUTOLINKS.text")); // NOI18N AUTOLINKS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.AUTOLINKS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(TABLES, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.TABLES.text")); // NOI18N TABLES.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.TABLES.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(DEFINITION_LISTS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.DEFINITION_LISTS.text")); // NOI18N DEFINITION_LISTS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.DEFINITION_LISTS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(FENCED_CODE_BLOCKS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.FENCED_CODE_BLOCKS.text")); // NOI18N FENCED_CODE_BLOCKS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.FENCED_CODE_BLOCKS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(HTML_BLOCK_SUPPRESSION, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_BLOCK_SUPPRESSION.text")); // NOI18N HTML_BLOCK_SUPPRESSION.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_BLOCK_SUPPRESSION.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(INLINE_HTML_SUPPRESSION, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.INLINE_HTML_SUPPRESSION.text")); // NOI18N INLINE_HTML_SUPPRESSION.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.INLINE_HTML_SUPPRESSION.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(WIKILINKS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.WIKILINKS.text")); // NOI18N WIKILINKS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.WIKILINKS.toolTipText")); // NOI18N javax.swing.GroupLayout EXTENSIONS_PANELLayout = new javax.swing.GroupLayout(EXTENSIONS_PANEL); EXTENSIONS_PANEL.setLayout(EXTENSIONS_PANELLayout); EXTENSIONS_PANELLayout.setHorizontalGroup( EXTENSIONS_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(EXTENSIONS_PANELLayout.createSequentialGroup() .addContainerGap() .addGroup(EXTENSIONS_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(EXTENSIONS_PANEL_HEADER, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(EXTENSIONS_PANELLayout.createSequentialGroup() .addGroup(EXTENSIONS_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(INLINE_HTML_SUPPRESSION) .addComponent(SMARTS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(QUOTES, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(ABBREVIATIONS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(HARDWRAPS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AUTOLINKS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(TABLES, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(DEFINITION_LISTS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(FENCED_CODE_BLOCKS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(HTML_BLOCK_SUPPRESSION, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(WIKILINKS, javax.swing.GroupLayout.PREFERRED_SIZE, 412, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)))) ); EXTENSIONS_PANELLayout.setVerticalGroup( EXTENSIONS_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, EXTENSIONS_PANELLayout.createSequentialGroup() .addContainerGap() .addComponent(EXTENSIONS_PANEL_HEADER) .addGap(17, 17, 17) .addComponent(SMARTS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(QUOTES) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(ABBREVIATIONS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(HARDWRAPS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(AUTOLINKS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(TABLES) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(DEFINITION_LISTS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(FENCED_CODE_BLOCKS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(HTML_BLOCK_SUPPRESSION) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(INLINE_HTML_SUPPRESSION) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(WIKILINKS) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); TABS.addTab(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.EXTENSIONS_PANEL.TabConstraints.tabTitle"), EXTENSIONS_PANEL); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(HTML_PANEL_HEADER, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_PANEL_HEADER.text")); // NOI18N jScrollPane1.setViewportView(HTML_TEMPLATE); javax.swing.GroupLayout HTML_EXPORT_PANELLayout = new javax.swing.GroupLayout(HTML_EXPORT_PANEL); HTML_EXPORT_PANEL.setLayout(HTML_EXPORT_PANELLayout); HTML_EXPORT_PANELLayout.setHorizontalGroup( HTML_EXPORT_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(HTML_EXPORT_PANELLayout.createSequentialGroup() .addContainerGap() .addGroup(HTML_EXPORT_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(HTML_PANEL_HEADER, javax.swing.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE) .addGroup(HTML_EXPORT_PANELLayout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addContainerGap()))) ); HTML_EXPORT_PANELLayout.setVerticalGroup( HTML_EXPORT_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(HTML_EXPORT_PANELLayout.createSequentialGroup() .addContainerGap() .addComponent(HTML_PANEL_HEADER) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE) .addContainerGap()) ); TABS.addTab(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_EXPORT_PANEL.TabConstraints.tabTitle"), HTML_EXPORT_PANEL); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(VIEW_HTML_ON_SAVE, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.VIEW_HTML_ON_SAVE.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(SAVE_IN_SOURCE_DIR, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.SAVE_IN_SOURCE_DIR.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(TYPING_HOOKS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.TYPING_HOOKS.text_1")); // NOI18N TYPING_HOOKS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TYPING_HOOKSActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(AUTO_ADDITION_LIST, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.AUTO_ADDITION_LIST.text")); // NOI18N AUTO_ADDITION_LIST.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.AUTO_ADDITION_LIST.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(REMOVE_EMPTY_LIST, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REMOVE_EMPTY_LIST.text")); // NOI18N REMOVE_EMPTY_LIST.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REMOVE_EMPTY_LIST.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(REORDER_ORDERED_LIST_NUMBER, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REORDER_ORDERED_LIST_NUMBER.text")); // NOI18N REORDER_ORDERED_LIST_NUMBER.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REORDER_ORDERED_LIST_NUMBER.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(REMOVE_ORDERED_LIST_NUMBER, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REMOVE_ORDERED_LIST_NUMBER.text_1")); // NOI18N REMOVE_ORDERED_LIST_NUMBER.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REMOVE_ORDERED_LIST_NUMBER.toolTipText")); // NOI18N javax.swing.GroupLayout MISC_PANELLayout = new javax.swing.GroupLayout(MISC_PANEL); MISC_PANEL.setLayout(MISC_PANELLayout); MISC_PANELLayout.setHorizontalGroup( MISC_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(MISC_PANELLayout.createSequentialGroup() .addContainerGap() .addGroup(MISC_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(MISC_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(VIEW_HTML_ON_SAVE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(SAVE_IN_SOURCE_DIR, javax.swing.GroupLayout.PREFERRED_SIZE, 255, Short.MAX_VALUE)) .addComponent(TYPING_HOOKS) .addGroup(MISC_PANELLayout.createSequentialGroup() .addGap(12, 12, 12) .addGroup(MISC_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(AUTO_ADDITION_LIST) .addComponent(REMOVE_EMPTY_LIST) .addComponent(REORDER_ORDERED_LIST_NUMBER) .addComponent(REMOVE_ORDERED_LIST_NUMBER)))) - .addContainerGap(137, Short.MAX_VALUE)) + .addContainerGap(135, Short.MAX_VALUE)) ); MISC_PANELLayout.setVerticalGroup( MISC_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(MISC_PANELLayout.createSequentialGroup() .addContainerGap() .addComponent(VIEW_HTML_ON_SAVE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(SAVE_IN_SOURCE_DIR) .addGap(18, 18, 18) .addComponent(TYPING_HOOKS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AUTO_ADDITION_LIST) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(REMOVE_EMPTY_LIST) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(REORDER_ORDERED_LIST_NUMBER) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(REMOVE_ORDERED_LIST_NUMBER) .addContainerGap(214, Short.MAX_VALUE)) ); TABS.addTab(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.MISC_PANEL.TabConstraints.tabTitle"), MISC_PANEL); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(TABS) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(TABS) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void TYPING_HOOKSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TYPING_HOOKSActionPerformed setTypinghooksEnabled(TYPING_HOOKS.isSelected()); }//GEN-LAST:event_TYPING_HOOKSActionPerformed private void setMimeType(JEditorPane editorPane, String mimeType, String extension) { FileSystem fileSystem = FileUtil.createMemoryFileSystem(); try { FileObject file = fileSystem.getRoot().createData("template", extension); DataObject data = DataObject.find(file); if (data != null) { EditorKit kit = CloneableEditorSupport.getEditorKit(mimeType); editorPane.setEditorKit(kit); editorPane.getDocument().putProperty(Document.StreamDescriptionProperty, data); DialogBinding.bindComponentToFile(file, 0, 0, editorPane); editorPane.setText(" "); } } catch (IOException ex) { Exceptions.printStackTrace(ex); } } private class ActionHandler implements ActionListener { @Override public void actionPerformed(ActionEvent e) { controller.changed(); } } private class DocumentHandler implements DocumentListener { @Override public void insertUpdate(DocumentEvent e) { controller.changed(); } @Override public void removeUpdate(DocumentEvent e) { controller.changed(); } @Override public void changedUpdate(DocumentEvent e) { controller.changed(); } } void load() { // TODO read settings and initialize GUI // Example: // someCheckBox.setSelected(Preferences.userNodeForPackage(MarkdownPanel.class).getBoolean("someFlag", false)); // or for org.openide.util with API spec. version >= 7.4: // someCheckBox.setSelected(NbPreferences.forModule(MarkdownPanel.class).getBoolean("someFlag", false)); // or: // someTextField.setText(SomeSystemOption.getDefault().getSomeStringProperty()); MarkdownGlobalOptions options = MarkdownGlobalOptions.getInstance(); ABBREVIATIONS.setSelected(options.isAbbreviations()); AUTOLINKS.setSelected(options.isAutoLinks()); DEFINITION_LISTS.setSelected(options.isDefinitions()); FENCED_CODE_BLOCKS.setSelected(options.isFencedCodeBlocks()); HARDWRAPS.setSelected(options.isHardWraps()); HTML_BLOCK_SUPPRESSION.setSelected(options.isSuppressHTMLBlocks()); INLINE_HTML_SUPPRESSION.setSelected(options.isSuppressInlineHTML()); QUOTES.setSelected(options.isQuotes()); SMARTS.setSelected(options.isSmarts()); TABLES.setSelected(options.isTables()); WIKILINKS.setSelected(options.isWikiLinks()); HTML_TEMPLATE.setText(options.getHtmlTemplate()); VIEW_HTML_ON_SAVE.setSelected(options.isViewHtmlOnSave()); // typing hooks TYPING_HOOKS.setSelected(options.isTypingHooks()); AUTO_ADDITION_LIST.setSelected(options.isAutoAdditionList()); REMOVE_EMPTY_LIST.setSelected(options.isRemoveEmptyList()); REORDER_ORDERED_LIST_NUMBER.setSelected(options.isReorderOrderedListNumber()); REMOVE_ORDERED_LIST_NUMBER.setSelected(options.isRemoveOrderedListNumber()); setTypinghooksEnabled(options.isTypingHooks()); } void store() { // TODO store modified settings // Example: // Preferences.userNodeForPackage(MarkdownPanel.class).putBoolean("someFlag", someCheckBox.isSelected()); // or for org.openide.util with API spec. version >= 7.4: // NbPreferences.forModule(MarkdownPanel.class).putBoolean("someFlag", someCheckBox.isSelected()); // or: // SomeSystemOption.getDefault().setSomeStringProperty(someTextField.getText()); MarkdownGlobalOptions options = MarkdownGlobalOptions.getInstance(); options.setAbbreviations(ABBREVIATIONS.isSelected()); options.setAutoLinks(AUTOLINKS.isSelected()); options.setDefinitions(DEFINITION_LISTS.isSelected()); options.setFencedCodeBlocks(FENCED_CODE_BLOCKS.isSelected()); options.setHardWraps(HARDWRAPS.isSelected()); options.setSuppressHTMLBlocks(HTML_BLOCK_SUPPRESSION.isSelected()); options.setSuppressInlineHTML(INLINE_HTML_SUPPRESSION.isSelected()); options.setQuotes(QUOTES.isSelected()); options.setSmarts(SMARTS.isSelected()); options.setTables(TABLES.isSelected()); options.setWikiLinks(WIKILINKS.isSelected()); options.setHtmlTemplate(HTML_TEMPLATE.getText()); options.setViewHtmlOnSave(VIEW_HTML_ON_SAVE.isSelected()); options.setSaveInSourceDir(SAVE_IN_SOURCE_DIR.isSelected()); // typing hooks options.setTypingHooks(TYPING_HOOKS.isSelected()); options.setAutoAdditionList(AUTO_ADDITION_LIST.isSelected()); options.setRemoveEmptyList(REMOVE_EMPTY_LIST.isSelected()); options.setReorderOrderedListNumber(REORDER_ORDERED_LIST_NUMBER.isSelected()); options.setRemoveOrderedListNumber(REMOVE_ORDERED_LIST_NUMBER.isSelected()); } public static String getDefaultHtmlTemplate() { return "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" + "<title>{%TITLE%}</title>\n" + "<style type=\"text/css\">/*...*/</style>\n" + "</head>\n" + "<body>\n" + "{%CONTENT%}\n" + "</body>\n" + "</html>"; } boolean valid() { return true; } private void setTypinghooksEnabled(boolean isEnabled) { AUTO_ADDITION_LIST.setEnabled(isEnabled); REMOVE_EMPTY_LIST.setEnabled(isEnabled); REORDER_ORDERED_LIST_NUMBER.setEnabled(isEnabled); REMOVE_ORDERED_LIST_NUMBER.setEnabled(isEnabled); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBox ABBREVIATIONS; private javax.swing.JCheckBox AUTOLINKS; private javax.swing.JCheckBox AUTO_ADDITION_LIST; private javax.swing.JCheckBox DEFINITION_LISTS; private javax.swing.JPanel EXTENSIONS_PANEL; private javax.swing.JLabel EXTENSIONS_PANEL_HEADER; private javax.swing.JCheckBox FENCED_CODE_BLOCKS; private javax.swing.JCheckBox HARDWRAPS; private javax.swing.JCheckBox HTML_BLOCK_SUPPRESSION; private javax.swing.JPanel HTML_EXPORT_PANEL; private javax.swing.JLabel HTML_PANEL_HEADER; private javax.swing.JEditorPane HTML_TEMPLATE; private javax.swing.JCheckBox INLINE_HTML_SUPPRESSION; private javax.swing.JPanel MISC_PANEL; private javax.swing.JCheckBox QUOTES; private javax.swing.JCheckBox REMOVE_EMPTY_LIST; private javax.swing.JCheckBox REMOVE_ORDERED_LIST_NUMBER; private javax.swing.JCheckBox REORDER_ORDERED_LIST_NUMBER; private javax.swing.JCheckBox SAVE_IN_SOURCE_DIR; private javax.swing.JCheckBox SMARTS; private javax.swing.JCheckBox TABLES; private javax.swing.JTabbedPane TABS; private javax.swing.JCheckBox TYPING_HOOKS; private javax.swing.JCheckBox VIEW_HTML_ON_SAVE; private javax.swing.JCheckBox WIKILINKS; private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables }
true
true
private void initComponents() { TABS = new javax.swing.JTabbedPane(); EXTENSIONS_PANEL = new javax.swing.JPanel(); EXTENSIONS_PANEL_HEADER = new javax.swing.JLabel(); SMARTS = new javax.swing.JCheckBox(); QUOTES = new javax.swing.JCheckBox(); ABBREVIATIONS = new javax.swing.JCheckBox(); HARDWRAPS = new javax.swing.JCheckBox(); AUTOLINKS = new javax.swing.JCheckBox(); TABLES = new javax.swing.JCheckBox(); DEFINITION_LISTS = new javax.swing.JCheckBox(); FENCED_CODE_BLOCKS = new javax.swing.JCheckBox(); HTML_BLOCK_SUPPRESSION = new javax.swing.JCheckBox(); INLINE_HTML_SUPPRESSION = new javax.swing.JCheckBox(); WIKILINKS = new javax.swing.JCheckBox(); HTML_EXPORT_PANEL = new javax.swing.JPanel(); HTML_PANEL_HEADER = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); HTML_TEMPLATE = new javax.swing.JEditorPane(); MISC_PANEL = new javax.swing.JPanel(); VIEW_HTML_ON_SAVE = new javax.swing.JCheckBox(); SAVE_IN_SOURCE_DIR = new javax.swing.JCheckBox(); TYPING_HOOKS = new javax.swing.JCheckBox(); AUTO_ADDITION_LIST = new javax.swing.JCheckBox(); REMOVE_EMPTY_LIST = new javax.swing.JCheckBox(); REORDER_ORDERED_LIST_NUMBER = new javax.swing.JCheckBox(); REMOVE_ORDERED_LIST_NUMBER = new javax.swing.JCheckBox(); org.openide.awt.Mnemonics.setLocalizedText(EXTENSIONS_PANEL_HEADER, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.EXTENSIONS_PANEL_HEADER.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(SMARTS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.SMARTS.text")); // NOI18N SMARTS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.SMARTS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(QUOTES, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.QUOTES.text")); // NOI18N QUOTES.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.QUOTES.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(ABBREVIATIONS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.ABBREVIATIONS.text")); // NOI18N ABBREVIATIONS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.ABBREVIATIONS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(HARDWRAPS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HARDWRAPS.text")); // NOI18N HARDWRAPS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HARDWRAPS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(AUTOLINKS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.AUTOLINKS.text")); // NOI18N AUTOLINKS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.AUTOLINKS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(TABLES, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.TABLES.text")); // NOI18N TABLES.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.TABLES.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(DEFINITION_LISTS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.DEFINITION_LISTS.text")); // NOI18N DEFINITION_LISTS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.DEFINITION_LISTS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(FENCED_CODE_BLOCKS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.FENCED_CODE_BLOCKS.text")); // NOI18N FENCED_CODE_BLOCKS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.FENCED_CODE_BLOCKS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(HTML_BLOCK_SUPPRESSION, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_BLOCK_SUPPRESSION.text")); // NOI18N HTML_BLOCK_SUPPRESSION.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_BLOCK_SUPPRESSION.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(INLINE_HTML_SUPPRESSION, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.INLINE_HTML_SUPPRESSION.text")); // NOI18N INLINE_HTML_SUPPRESSION.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.INLINE_HTML_SUPPRESSION.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(WIKILINKS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.WIKILINKS.text")); // NOI18N WIKILINKS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.WIKILINKS.toolTipText")); // NOI18N javax.swing.GroupLayout EXTENSIONS_PANELLayout = new javax.swing.GroupLayout(EXTENSIONS_PANEL); EXTENSIONS_PANEL.setLayout(EXTENSIONS_PANELLayout); EXTENSIONS_PANELLayout.setHorizontalGroup( EXTENSIONS_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(EXTENSIONS_PANELLayout.createSequentialGroup() .addContainerGap() .addGroup(EXTENSIONS_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(EXTENSIONS_PANEL_HEADER, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(EXTENSIONS_PANELLayout.createSequentialGroup() .addGroup(EXTENSIONS_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(INLINE_HTML_SUPPRESSION) .addComponent(SMARTS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(QUOTES, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(ABBREVIATIONS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(HARDWRAPS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AUTOLINKS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(TABLES, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(DEFINITION_LISTS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(FENCED_CODE_BLOCKS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(HTML_BLOCK_SUPPRESSION, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(WIKILINKS, javax.swing.GroupLayout.PREFERRED_SIZE, 412, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)))) ); EXTENSIONS_PANELLayout.setVerticalGroup( EXTENSIONS_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, EXTENSIONS_PANELLayout.createSequentialGroup() .addContainerGap() .addComponent(EXTENSIONS_PANEL_HEADER) .addGap(17, 17, 17) .addComponent(SMARTS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(QUOTES) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(ABBREVIATIONS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(HARDWRAPS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(AUTOLINKS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(TABLES) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(DEFINITION_LISTS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(FENCED_CODE_BLOCKS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(HTML_BLOCK_SUPPRESSION) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(INLINE_HTML_SUPPRESSION) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(WIKILINKS) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); TABS.addTab(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.EXTENSIONS_PANEL.TabConstraints.tabTitle"), EXTENSIONS_PANEL); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(HTML_PANEL_HEADER, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_PANEL_HEADER.text")); // NOI18N jScrollPane1.setViewportView(HTML_TEMPLATE); javax.swing.GroupLayout HTML_EXPORT_PANELLayout = new javax.swing.GroupLayout(HTML_EXPORT_PANEL); HTML_EXPORT_PANEL.setLayout(HTML_EXPORT_PANELLayout); HTML_EXPORT_PANELLayout.setHorizontalGroup( HTML_EXPORT_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(HTML_EXPORT_PANELLayout.createSequentialGroup() .addContainerGap() .addGroup(HTML_EXPORT_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(HTML_PANEL_HEADER, javax.swing.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE) .addGroup(HTML_EXPORT_PANELLayout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addContainerGap()))) ); HTML_EXPORT_PANELLayout.setVerticalGroup( HTML_EXPORT_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(HTML_EXPORT_PANELLayout.createSequentialGroup() .addContainerGap() .addComponent(HTML_PANEL_HEADER) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE) .addContainerGap()) ); TABS.addTab(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_EXPORT_PANEL.TabConstraints.tabTitle"), HTML_EXPORT_PANEL); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(VIEW_HTML_ON_SAVE, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.VIEW_HTML_ON_SAVE.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(SAVE_IN_SOURCE_DIR, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.SAVE_IN_SOURCE_DIR.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(TYPING_HOOKS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.TYPING_HOOKS.text_1")); // NOI18N TYPING_HOOKS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TYPING_HOOKSActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(AUTO_ADDITION_LIST, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.AUTO_ADDITION_LIST.text")); // NOI18N AUTO_ADDITION_LIST.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.AUTO_ADDITION_LIST.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(REMOVE_EMPTY_LIST, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REMOVE_EMPTY_LIST.text")); // NOI18N REMOVE_EMPTY_LIST.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REMOVE_EMPTY_LIST.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(REORDER_ORDERED_LIST_NUMBER, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REORDER_ORDERED_LIST_NUMBER.text")); // NOI18N REORDER_ORDERED_LIST_NUMBER.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REORDER_ORDERED_LIST_NUMBER.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(REMOVE_ORDERED_LIST_NUMBER, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REMOVE_ORDERED_LIST_NUMBER.text_1")); // NOI18N REMOVE_ORDERED_LIST_NUMBER.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REMOVE_ORDERED_LIST_NUMBER.toolTipText")); // NOI18N javax.swing.GroupLayout MISC_PANELLayout = new javax.swing.GroupLayout(MISC_PANEL); MISC_PANEL.setLayout(MISC_PANELLayout); MISC_PANELLayout.setHorizontalGroup( MISC_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(MISC_PANELLayout.createSequentialGroup() .addContainerGap() .addGroup(MISC_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(MISC_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(VIEW_HTML_ON_SAVE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(SAVE_IN_SOURCE_DIR, javax.swing.GroupLayout.PREFERRED_SIZE, 255, Short.MAX_VALUE)) .addComponent(TYPING_HOOKS) .addGroup(MISC_PANELLayout.createSequentialGroup() .addGap(12, 12, 12) .addGroup(MISC_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(AUTO_ADDITION_LIST) .addComponent(REMOVE_EMPTY_LIST) .addComponent(REORDER_ORDERED_LIST_NUMBER) .addComponent(REMOVE_ORDERED_LIST_NUMBER)))) .addContainerGap(137, Short.MAX_VALUE)) ); MISC_PANELLayout.setVerticalGroup( MISC_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(MISC_PANELLayout.createSequentialGroup() .addContainerGap() .addComponent(VIEW_HTML_ON_SAVE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(SAVE_IN_SOURCE_DIR) .addGap(18, 18, 18) .addComponent(TYPING_HOOKS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AUTO_ADDITION_LIST) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(REMOVE_EMPTY_LIST) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(REORDER_ORDERED_LIST_NUMBER) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(REMOVE_ORDERED_LIST_NUMBER) .addContainerGap(214, Short.MAX_VALUE)) ); TABS.addTab(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.MISC_PANEL.TabConstraints.tabTitle"), MISC_PANEL); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(TABS) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(TABS) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { TABS = new javax.swing.JTabbedPane(); EXTENSIONS_PANEL = new javax.swing.JPanel(); EXTENSIONS_PANEL_HEADER = new javax.swing.JLabel(); SMARTS = new javax.swing.JCheckBox(); QUOTES = new javax.swing.JCheckBox(); ABBREVIATIONS = new javax.swing.JCheckBox(); HARDWRAPS = new javax.swing.JCheckBox(); AUTOLINKS = new javax.swing.JCheckBox(); TABLES = new javax.swing.JCheckBox(); DEFINITION_LISTS = new javax.swing.JCheckBox(); FENCED_CODE_BLOCKS = new javax.swing.JCheckBox(); HTML_BLOCK_SUPPRESSION = new javax.swing.JCheckBox(); INLINE_HTML_SUPPRESSION = new javax.swing.JCheckBox(); WIKILINKS = new javax.swing.JCheckBox(); HTML_EXPORT_PANEL = new javax.swing.JPanel(); HTML_PANEL_HEADER = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); HTML_TEMPLATE = new javax.swing.JEditorPane(); MISC_PANEL = new javax.swing.JPanel(); VIEW_HTML_ON_SAVE = new javax.swing.JCheckBox(); SAVE_IN_SOURCE_DIR = new javax.swing.JCheckBox(); TYPING_HOOKS = new javax.swing.JCheckBox(); AUTO_ADDITION_LIST = new javax.swing.JCheckBox(); REMOVE_EMPTY_LIST = new javax.swing.JCheckBox(); REORDER_ORDERED_LIST_NUMBER = new javax.swing.JCheckBox(); REMOVE_ORDERED_LIST_NUMBER = new javax.swing.JCheckBox(); org.openide.awt.Mnemonics.setLocalizedText(EXTENSIONS_PANEL_HEADER, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.EXTENSIONS_PANEL_HEADER.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(SMARTS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.SMARTS.text")); // NOI18N SMARTS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.SMARTS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(QUOTES, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.QUOTES.text")); // NOI18N QUOTES.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.QUOTES.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(ABBREVIATIONS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.ABBREVIATIONS.text")); // NOI18N ABBREVIATIONS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.ABBREVIATIONS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(HARDWRAPS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HARDWRAPS.text")); // NOI18N HARDWRAPS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HARDWRAPS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(AUTOLINKS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.AUTOLINKS.text")); // NOI18N AUTOLINKS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.AUTOLINKS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(TABLES, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.TABLES.text")); // NOI18N TABLES.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.TABLES.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(DEFINITION_LISTS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.DEFINITION_LISTS.text")); // NOI18N DEFINITION_LISTS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.DEFINITION_LISTS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(FENCED_CODE_BLOCKS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.FENCED_CODE_BLOCKS.text")); // NOI18N FENCED_CODE_BLOCKS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.FENCED_CODE_BLOCKS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(HTML_BLOCK_SUPPRESSION, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_BLOCK_SUPPRESSION.text")); // NOI18N HTML_BLOCK_SUPPRESSION.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_BLOCK_SUPPRESSION.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(INLINE_HTML_SUPPRESSION, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.INLINE_HTML_SUPPRESSION.text")); // NOI18N INLINE_HTML_SUPPRESSION.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.INLINE_HTML_SUPPRESSION.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(WIKILINKS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.WIKILINKS.text")); // NOI18N WIKILINKS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.WIKILINKS.toolTipText")); // NOI18N javax.swing.GroupLayout EXTENSIONS_PANELLayout = new javax.swing.GroupLayout(EXTENSIONS_PANEL); EXTENSIONS_PANEL.setLayout(EXTENSIONS_PANELLayout); EXTENSIONS_PANELLayout.setHorizontalGroup( EXTENSIONS_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(EXTENSIONS_PANELLayout.createSequentialGroup() .addContainerGap() .addGroup(EXTENSIONS_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(EXTENSIONS_PANEL_HEADER, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(EXTENSIONS_PANELLayout.createSequentialGroup() .addGroup(EXTENSIONS_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(INLINE_HTML_SUPPRESSION) .addComponent(SMARTS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(QUOTES, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(ABBREVIATIONS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(HARDWRAPS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AUTOLINKS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(TABLES, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(DEFINITION_LISTS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(FENCED_CODE_BLOCKS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(HTML_BLOCK_SUPPRESSION, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(WIKILINKS, javax.swing.GroupLayout.PREFERRED_SIZE, 412, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)))) ); EXTENSIONS_PANELLayout.setVerticalGroup( EXTENSIONS_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, EXTENSIONS_PANELLayout.createSequentialGroup() .addContainerGap() .addComponent(EXTENSIONS_PANEL_HEADER) .addGap(17, 17, 17) .addComponent(SMARTS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(QUOTES) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(ABBREVIATIONS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(HARDWRAPS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(AUTOLINKS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(TABLES) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(DEFINITION_LISTS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(FENCED_CODE_BLOCKS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(HTML_BLOCK_SUPPRESSION) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(INLINE_HTML_SUPPRESSION) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(WIKILINKS) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); TABS.addTab(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.EXTENSIONS_PANEL.TabConstraints.tabTitle"), EXTENSIONS_PANEL); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(HTML_PANEL_HEADER, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_PANEL_HEADER.text")); // NOI18N jScrollPane1.setViewportView(HTML_TEMPLATE); javax.swing.GroupLayout HTML_EXPORT_PANELLayout = new javax.swing.GroupLayout(HTML_EXPORT_PANEL); HTML_EXPORT_PANEL.setLayout(HTML_EXPORT_PANELLayout); HTML_EXPORT_PANELLayout.setHorizontalGroup( HTML_EXPORT_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(HTML_EXPORT_PANELLayout.createSequentialGroup() .addContainerGap() .addGroup(HTML_EXPORT_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(HTML_PANEL_HEADER, javax.swing.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE) .addGroup(HTML_EXPORT_PANELLayout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addContainerGap()))) ); HTML_EXPORT_PANELLayout.setVerticalGroup( HTML_EXPORT_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(HTML_EXPORT_PANELLayout.createSequentialGroup() .addContainerGap() .addComponent(HTML_PANEL_HEADER) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE) .addContainerGap()) ); TABS.addTab(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_EXPORT_PANEL.TabConstraints.tabTitle"), HTML_EXPORT_PANEL); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(VIEW_HTML_ON_SAVE, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.VIEW_HTML_ON_SAVE.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(SAVE_IN_SOURCE_DIR, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.SAVE_IN_SOURCE_DIR.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(TYPING_HOOKS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.TYPING_HOOKS.text_1")); // NOI18N TYPING_HOOKS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TYPING_HOOKSActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(AUTO_ADDITION_LIST, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.AUTO_ADDITION_LIST.text")); // NOI18N AUTO_ADDITION_LIST.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.AUTO_ADDITION_LIST.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(REMOVE_EMPTY_LIST, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REMOVE_EMPTY_LIST.text")); // NOI18N REMOVE_EMPTY_LIST.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REMOVE_EMPTY_LIST.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(REORDER_ORDERED_LIST_NUMBER, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REORDER_ORDERED_LIST_NUMBER.text")); // NOI18N REORDER_ORDERED_LIST_NUMBER.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REORDER_ORDERED_LIST_NUMBER.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(REMOVE_ORDERED_LIST_NUMBER, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REMOVE_ORDERED_LIST_NUMBER.text_1")); // NOI18N REMOVE_ORDERED_LIST_NUMBER.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.REMOVE_ORDERED_LIST_NUMBER.toolTipText")); // NOI18N javax.swing.GroupLayout MISC_PANELLayout = new javax.swing.GroupLayout(MISC_PANEL); MISC_PANEL.setLayout(MISC_PANELLayout); MISC_PANELLayout.setHorizontalGroup( MISC_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(MISC_PANELLayout.createSequentialGroup() .addContainerGap() .addGroup(MISC_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(MISC_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(VIEW_HTML_ON_SAVE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(SAVE_IN_SOURCE_DIR, javax.swing.GroupLayout.PREFERRED_SIZE, 255, Short.MAX_VALUE)) .addComponent(TYPING_HOOKS) .addGroup(MISC_PANELLayout.createSequentialGroup() .addGap(12, 12, 12) .addGroup(MISC_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(AUTO_ADDITION_LIST) .addComponent(REMOVE_EMPTY_LIST) .addComponent(REORDER_ORDERED_LIST_NUMBER) .addComponent(REMOVE_ORDERED_LIST_NUMBER)))) .addContainerGap(135, Short.MAX_VALUE)) ); MISC_PANELLayout.setVerticalGroup( MISC_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(MISC_PANELLayout.createSequentialGroup() .addContainerGap() .addComponent(VIEW_HTML_ON_SAVE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(SAVE_IN_SOURCE_DIR) .addGap(18, 18, 18) .addComponent(TYPING_HOOKS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AUTO_ADDITION_LIST) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(REMOVE_EMPTY_LIST) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(REORDER_ORDERED_LIST_NUMBER) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(REMOVE_ORDERED_LIST_NUMBER) .addContainerGap(214, Short.MAX_VALUE)) ); TABS.addTab(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.MISC_PANEL.TabConstraints.tabTitle"), MISC_PANEL); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(TABS) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(TABS) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents
diff --git a/ShareYourSpot_Client/src/de/hska/shareyourspot/android/activites/Friends.java b/ShareYourSpot_Client/src/de/hska/shareyourspot/android/activites/Friends.java index f6f03e5..21d040e 100644 --- a/ShareYourSpot_Client/src/de/hska/shareyourspot/android/activites/Friends.java +++ b/ShareYourSpot_Client/src/de/hska/shareyourspot/android/activites/Friends.java @@ -1,115 +1,115 @@ package de.hska.shareyourspot.android.activites; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import de.hska.shareyourspot.android.R; import de.hska.shareyourspot.android.domain.User; import de.hska.shareyourspot.android.domain.Users; import de.hska.shareyourspot.android.restclient.RestClient; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; public class Friends extends Activity { private RestClient restClient = new RestClient(); final Context context = this; private List<User> friends; private List<User> foundUsers; private User lookFor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.friends); } public void showGroups(View view) { Intent intent = new Intent(this, Groups.class); startActivity(intent); } public void onClickSearch(View view) { // TODO: search for users and get list, add friends this.lookFor = new User(); - EditText username = (EditText) findViewById(R.id.lookForUser); + EditText username = (EditText) findViewById(R.id.editText_enter_name); this.lookFor.setName(username.getText().toString()); Users users = this.restClient.searchUser(this.lookFor); // TODO: add users to listUsers on UI this.foundUsers = new ArrayList<User>(); this.foundUsers.addAll(users.getAllUser()); ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.foundUsers); - ListView listUsers = (ListView)findViewById(R.id.listUsers); + ListView listUsers = (ListView)findViewById(R.id.textView1); listUsers.setAdapter(adapter); Intent intent = new Intent(this, Friends.class); startActivity(intent); } public List<User> getFriends() { return friends; } public void setFriends(List<User> friends) { this.friends = friends; } public User getLookFor() { return lookFor; } public void setLookFor(User lookFor) { this.lookFor = lookFor; } public List<User> getFoundUsers() { return foundUsers; } public void setFoundUsers(List<User> foundUsers) { this.foundUsers = foundUsers; } private class StableArrayAdapter extends ArrayAdapter<String> { HashMap<String, Integer> mIdMap = new HashMap<String, Integer>(); public StableArrayAdapter(Context context, int textViewResourceId, List<String> objects) { super(context, textViewResourceId, objects); for (int i = 0; i < objects.size(); ++i) { mIdMap.put(objects.get(i), i); } } @Override public long getItemId(int position) { String item = getItem(position); return mIdMap.get(item); } @Override public boolean hasStableIds() { return true; } } }
false
true
public void onClickSearch(View view) { // TODO: search for users and get list, add friends this.lookFor = new User(); EditText username = (EditText) findViewById(R.id.lookForUser); this.lookFor.setName(username.getText().toString()); Users users = this.restClient.searchUser(this.lookFor); // TODO: add users to listUsers on UI this.foundUsers = new ArrayList<User>(); this.foundUsers.addAll(users.getAllUser()); ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.foundUsers); ListView listUsers = (ListView)findViewById(R.id.listUsers); listUsers.setAdapter(adapter); Intent intent = new Intent(this, Friends.class); startActivity(intent); }
public void onClickSearch(View view) { // TODO: search for users and get list, add friends this.lookFor = new User(); EditText username = (EditText) findViewById(R.id.editText_enter_name); this.lookFor.setName(username.getText().toString()); Users users = this.restClient.searchUser(this.lookFor); // TODO: add users to listUsers on UI this.foundUsers = new ArrayList<User>(); this.foundUsers.addAll(users.getAllUser()); ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.foundUsers); ListView listUsers = (ListView)findViewById(R.id.textView1); listUsers.setAdapter(adapter); Intent intent = new Intent(this, Friends.class); startActivity(intent); }
diff --git a/src/com/esotericsoftware/kryo/serializers/BeanSerializer.java b/src/com/esotericsoftware/kryo/serializers/BeanSerializer.java index 30f149f..8e9a5e5 100644 --- a/src/com/esotericsoftware/kryo/serializers/BeanSerializer.java +++ b/src/com/esotericsoftware/kryo/serializers/BeanSerializer.java @@ -1,194 +1,196 @@ package com.esotericsoftware.kryo.serializers; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.KryoException; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.reflectasm.MethodAccess; import static com.esotericsoftware.minlog.Log.*; /** Serializes Java beans using bean accessor methods. Only bean properties with both a getter and setter are serialized. This * class is not as fast as {@link FieldSerializer} but is much faster and more efficient than Java serialization. Bytecode * generation is used to invoke the bean propert methods, if possible. * <p> * BeanSerializer does not write header data, only the object data is stored. If the type of a bean property is not final (note * primitives are final) then an extra byte is written for that property. * @see Serializer * @see Kryo#register(Class, Serializer) * @author Nathan Sweet <[email protected]> */ public class BeanSerializer<T> extends Serializer<T> { static final Object[] noArgs = {}; private final Kryo kryo; private CachedProperty[] properties; Object access; public BeanSerializer (Kryo kryo, Class type) { this.kryo = kryo; BeanInfo info; try { info = Introspector.getBeanInfo(type); } catch (IntrospectionException ex) { throw new KryoException("Error getting bean info.", ex); } // Methods are sorted by alpha so the order of the data is known. PropertyDescriptor[] descriptors = info.getPropertyDescriptors(); Arrays.sort(descriptors, new Comparator<PropertyDescriptor>() { public int compare (PropertyDescriptor o1, PropertyDescriptor o2) { return o1.getName().compareTo(o2.getName()); } }); ArrayList<CachedProperty> cachedProperties = new ArrayList(descriptors.length); for (int i = 0, n = descriptors.length; i < n; i++) { PropertyDescriptor property = descriptors[i]; String name = property.getName(); if (name.equals("class")) continue; Method getMethod = property.getReadMethod(); Method setMethod = property.getWriteMethod(); if (getMethod == null || setMethod == null) continue; // Require both a getter and setter. // Always use the same serializer for this property if the properties' class is final. Serializer serializer = null; Class returnType = getMethod.getReturnType(); if (kryo.isFinal(returnType)) serializer = kryo.getRegistration(returnType).getSerializer(); CachedProperty cachedProperty = new CachedProperty(); cachedProperty.name = name; cachedProperty.getMethod = getMethod; cachedProperty.setMethod = setMethod; cachedProperty.serializer = serializer; cachedProperty.setMethodType = setMethod.getParameterTypes()[0]; cachedProperties.add(cachedProperty); } properties = cachedProperties.toArray(new CachedProperty[cachedProperties.size()]); try { access = MethodAccess.get(type); for (int i = 0, n = properties.length; i < n; i++) { CachedProperty property = properties[i]; - property.getterAccessIndex = ((MethodAccess)access).getIndex(property.getMethod.getName()); - property.setterAccessIndex = ((MethodAccess)access).getIndex(property.setMethod.getName()); + property.getterAccessIndex = ((MethodAccess)access).getIndex(property.getMethod.getName(), + property.getMethod.getParameterTypes()); + property.setterAccessIndex = ((MethodAccess)access).getIndex(property.setMethod.getName(), + property.setMethod.getParameterTypes()); } } catch (Throwable ignored) { // ReflectASM is not available on Android. } } public void write (Kryo kryo, Output output, T object) { Class type = object.getClass(); for (int i = 0, n = properties.length; i < n; i++) { CachedProperty property = properties[i]; try { if (TRACE) trace("kryo", "Write property: " + property + " (" + type.getName() + ")"); Object value = property.get(object); Serializer serializer = property.serializer; if (serializer != null) kryo.writeObjectOrNull(output, value, serializer); else kryo.writeClassAndObject(output, value); } catch (IllegalAccessException ex) { throw new KryoException("Error accessing getter method: " + property + " (" + type.getName() + ")", ex); } catch (InvocationTargetException ex) { throw new KryoException("Error invoking getter method: " + property + " (" + type.getName() + ")", ex); } catch (KryoException ex) { ex.addTrace(property + " (" + type.getName() + ")"); throw ex; } catch (RuntimeException runtimeEx) { KryoException ex = new KryoException(runtimeEx); ex.addTrace(property + " (" + type.getName() + ")"); throw ex; } } } public T read (Kryo kryo, Input input, Class<T> type) { T object = kryo.newInstance(type); kryo.reference(object); for (int i = 0, n = properties.length; i < n; i++) { CachedProperty property = properties[i]; try { if (TRACE) trace("kryo", "Read property: " + property + " (" + object.getClass() + ")"); Object value; Serializer serializer = property.serializer; if (serializer != null) value = kryo.readObjectOrNull(input, property.setMethodType, serializer); else value = kryo.readClassAndObject(input); property.set(object, value); } catch (IllegalAccessException ex) { throw new KryoException("Error accessing setter method: " + property + " (" + object.getClass().getName() + ")", ex); } catch (InvocationTargetException ex) { throw new KryoException("Error invoking setter method: " + property + " (" + object.getClass().getName() + ")", ex); } catch (KryoException ex) { ex.addTrace(property + " (" + object.getClass().getName() + ")"); throw ex; } catch (RuntimeException runtimeEx) { KryoException ex = new KryoException(runtimeEx); ex.addTrace(property + " (" + object.getClass().getName() + ")"); throw ex; } } return object; } public T copy (Kryo kryo, T original) { T copy = (T)kryo.newInstance(original.getClass()); for (int i = 0, n = properties.length; i < n; i++) { CachedProperty property = properties[i]; try { Object value = property.get(original); property.set(copy, value); } catch (KryoException ex) { ex.addTrace(property + " (" + copy.getClass().getName() + ")"); throw ex; } catch (RuntimeException runtimeEx) { KryoException ex = new KryoException(runtimeEx); ex.addTrace(property + " (" + copy.getClass().getName() + ")"); throw ex; } catch (Exception ex) { throw new KryoException("Error copying bean property: " + property + " (" + copy.getClass().getName() + ")", ex); } } return copy; } class CachedProperty<X> { String name; Method getMethod, setMethod; Class setMethodType; Serializer serializer; int getterAccessIndex, setterAccessIndex; public String toString () { return name; } Object get (Object object) throws IllegalAccessException, InvocationTargetException { if (access != null) return ((MethodAccess)access).invoke(object, getterAccessIndex); return getMethod.invoke(object, noArgs); } void set (Object object, Object value) throws IllegalAccessException, InvocationTargetException { if (access != null) { ((MethodAccess)access).invoke(object, setterAccessIndex, value); return; } setMethod.invoke(object, new Object[] {value}); } } }
true
true
public BeanSerializer (Kryo kryo, Class type) { this.kryo = kryo; BeanInfo info; try { info = Introspector.getBeanInfo(type); } catch (IntrospectionException ex) { throw new KryoException("Error getting bean info.", ex); } // Methods are sorted by alpha so the order of the data is known. PropertyDescriptor[] descriptors = info.getPropertyDescriptors(); Arrays.sort(descriptors, new Comparator<PropertyDescriptor>() { public int compare (PropertyDescriptor o1, PropertyDescriptor o2) { return o1.getName().compareTo(o2.getName()); } }); ArrayList<CachedProperty> cachedProperties = new ArrayList(descriptors.length); for (int i = 0, n = descriptors.length; i < n; i++) { PropertyDescriptor property = descriptors[i]; String name = property.getName(); if (name.equals("class")) continue; Method getMethod = property.getReadMethod(); Method setMethod = property.getWriteMethod(); if (getMethod == null || setMethod == null) continue; // Require both a getter and setter. // Always use the same serializer for this property if the properties' class is final. Serializer serializer = null; Class returnType = getMethod.getReturnType(); if (kryo.isFinal(returnType)) serializer = kryo.getRegistration(returnType).getSerializer(); CachedProperty cachedProperty = new CachedProperty(); cachedProperty.name = name; cachedProperty.getMethod = getMethod; cachedProperty.setMethod = setMethod; cachedProperty.serializer = serializer; cachedProperty.setMethodType = setMethod.getParameterTypes()[0]; cachedProperties.add(cachedProperty); } properties = cachedProperties.toArray(new CachedProperty[cachedProperties.size()]); try { access = MethodAccess.get(type); for (int i = 0, n = properties.length; i < n; i++) { CachedProperty property = properties[i]; property.getterAccessIndex = ((MethodAccess)access).getIndex(property.getMethod.getName()); property.setterAccessIndex = ((MethodAccess)access).getIndex(property.setMethod.getName()); } } catch (Throwable ignored) { // ReflectASM is not available on Android. } }
public BeanSerializer (Kryo kryo, Class type) { this.kryo = kryo; BeanInfo info; try { info = Introspector.getBeanInfo(type); } catch (IntrospectionException ex) { throw new KryoException("Error getting bean info.", ex); } // Methods are sorted by alpha so the order of the data is known. PropertyDescriptor[] descriptors = info.getPropertyDescriptors(); Arrays.sort(descriptors, new Comparator<PropertyDescriptor>() { public int compare (PropertyDescriptor o1, PropertyDescriptor o2) { return o1.getName().compareTo(o2.getName()); } }); ArrayList<CachedProperty> cachedProperties = new ArrayList(descriptors.length); for (int i = 0, n = descriptors.length; i < n; i++) { PropertyDescriptor property = descriptors[i]; String name = property.getName(); if (name.equals("class")) continue; Method getMethod = property.getReadMethod(); Method setMethod = property.getWriteMethod(); if (getMethod == null || setMethod == null) continue; // Require both a getter and setter. // Always use the same serializer for this property if the properties' class is final. Serializer serializer = null; Class returnType = getMethod.getReturnType(); if (kryo.isFinal(returnType)) serializer = kryo.getRegistration(returnType).getSerializer(); CachedProperty cachedProperty = new CachedProperty(); cachedProperty.name = name; cachedProperty.getMethod = getMethod; cachedProperty.setMethod = setMethod; cachedProperty.serializer = serializer; cachedProperty.setMethodType = setMethod.getParameterTypes()[0]; cachedProperties.add(cachedProperty); } properties = cachedProperties.toArray(new CachedProperty[cachedProperties.size()]); try { access = MethodAccess.get(type); for (int i = 0, n = properties.length; i < n; i++) { CachedProperty property = properties[i]; property.getterAccessIndex = ((MethodAccess)access).getIndex(property.getMethod.getName(), property.getMethod.getParameterTypes()); property.setterAccessIndex = ((MethodAccess)access).getIndex(property.setMethod.getName(), property.setMethod.getParameterTypes()); } } catch (Throwable ignored) { // ReflectASM is not available on Android. } }
diff --git a/gui/src/main/java/org/jboss/as/console/client/shared/general/InterfacePresenter.java b/gui/src/main/java/org/jboss/as/console/client/shared/general/InterfacePresenter.java index 06f047a6..4abc0314 100644 --- a/gui/src/main/java/org/jboss/as/console/client/shared/general/InterfacePresenter.java +++ b/gui/src/main/java/org/jboss/as/console/client/shared/general/InterfacePresenter.java @@ -1,235 +1,236 @@ /* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.console.client.shared.general; import com.google.gwt.event.shared.EventBus; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.inject.Inject; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.proxy.Place; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.Proxy; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.core.NameTokens; import org.jboss.as.console.client.domain.model.SimpleCallback; import org.jboss.as.console.client.shared.BeanFactory; import org.jboss.as.console.client.shared.dispatch.DispatchAsync; import org.jboss.as.console.client.shared.dispatch.impl.DMRAction; import org.jboss.as.console.client.shared.dispatch.impl.DMRResponse; import org.jboss.as.console.client.shared.general.model.Interface; import org.jboss.as.console.client.shared.general.model.LoadInterfacesCmd; import org.jboss.as.console.client.shared.general.validation.CompositeDecision; import org.jboss.as.console.client.shared.general.validation.ValidationResult; import org.jboss.as.console.client.shared.subsys.Baseadress; import org.jboss.as.console.client.shared.subsys.RevealStrategy; import org.jboss.as.console.client.widgets.forms.AddressBinding; import org.jboss.as.console.client.widgets.forms.ApplicationMetaData; import org.jboss.as.console.client.widgets.forms.BeanMetaData; import org.jboss.as.console.client.widgets.forms.EntityAdapter; import org.jboss.ballroom.client.widgets.forms.FormItem; import org.jboss.ballroom.client.widgets.window.DefaultWindow; import org.jboss.ballroom.client.widgets.window.Feedback; import org.jboss.dmr.client.ModelNode; import org.jboss.dmr.client.ModelNodeUtil; import java.util.List; import java.util.Map; import static org.jboss.dmr.client.ModelDescriptionConstants.*; /** * @author Heiko Braun * @date 5/17/11 */ public class InterfacePresenter extends Presenter<InterfacePresenter.MyView, InterfacePresenter.MyProxy> { private final PlaceManager placeManager; private BeanFactory factory; private DispatchAsync dispatcher; private LoadInterfacesCmd loadInterfacesCmd; private RevealStrategy revealStrategy; private DefaultWindow window; private EntityAdapter<Interface> entityAdapter; private BeanMetaData beanMetaData; @ProxyCodeSplit @NameToken(NameTokens.InterfacePresenter) public interface MyProxy extends Proxy<InterfacePresenter>, Place { } public interface MyView extends View { void setPresenter(InterfacePresenter presenter); void setInterfaces(List<Interface> interfaces); } @Inject public InterfacePresenter( EventBus eventBus, MyView view, MyProxy proxy, PlaceManager placeManager, DispatchAsync dispatcher, BeanFactory factory, RevealStrategy revealStrategy, ApplicationMetaData metaData) { super(eventBus, view, proxy); this.placeManager = placeManager; this.factory = factory; this.dispatcher = dispatcher; this.revealStrategy = revealStrategy; ModelNode address = new ModelNode(); address.setEmptyList(); loadInterfacesCmd = new LoadInterfacesCmd(dispatcher, address, metaData); entityAdapter = new EntityAdapter<Interface>(Interface.class, metaData); beanMetaData = metaData.getBeanMetaData(Interface.class); } @Override protected void onBind() { super.onBind(); getView().setPresenter(this); } @Override protected void onReset() { super.onReset(); loadInterfaces(); } private void loadInterfaces() { loadInterfacesCmd.execute(new SimpleCallback<List<Interface>>() { @Override public void onSuccess(List<Interface> result) { getView().setInterfaces(result); } }); } @Override protected void revealInParent() { revealStrategy.revealInParent(this); } public void launchNewInterfaceDialogue() { window = new DefaultWindow("New Interface Declaration"); window.setWidth(480); window.setHeight(360); window.setWidget( new NewInterfaceWizard(this).asWidget() ); window.setGlassEnabled(true); window.center(); } public void createNewInterface(Interface entity) { ModelNode operation = entityAdapter.fromEntity(entity); operation.get(ADDRESS).add("interface", entity.getName()); operation.get(OP).set(ADD); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse dmrResponse) { ModelNode result = ModelNode.fromBase64(dmrResponse.getResponseText()); System.out.println(result); } }); } public void closeDialoge() { window.hide(); } public void onRemoveInterface(Interface entity) { } public void onSaveInterface(final Interface entity, Map<String, Object> changeset) { CompositeDecision decisionTree = new CompositeDecision(); ValidationResult validation = decisionTree.validate(entity, changeset); if(validation.isValid()) { //Console.info(validation.asMessageString()); doPersistChanges(entity, changeset); } else { SafeHtmlBuilder html = new SafeHtmlBuilder(); html.appendHtmlConstant("<h3>"); html.appendEscaped(validation.asMessageString()); html.appendHtmlConstant("</h3>"); for(String detail : decisionTree.getDetailMessages()) html.appendEscaped(detail).appendHtmlConstant("<br/>"); Feedback.alert("Invalid Interface Constraints", html.toSafeHtml()); } } // TODO: https://issues.jboss.org/browse/AS7-2670 private void doPersistChanges(final Interface entity, Map<String,Object> changeset) { // artificial values need to be merged manually String wildcard = entity.getAddressWildcard(); changeset.put("anyAddress", wildcard.equals(Interface.ANY_ADDRESS) ? true : FormItem.VALUE_SEMANTICS.UNDEFINED); changeset.put("anyIP4Address", wildcard.equals(Interface.ANY_IP4) ? true : FormItem.VALUE_SEMANTICS.UNDEFINED); changeset.put("anyIP6Address", wildcard.equals(Interface.ANY_IP6) ? true : FormItem.VALUE_SEMANTICS.UNDEFINED); AddressBinding addressBinding = beanMetaData.getAddress(); ModelNode address = addressBinding.asResource(Baseadress.get(), entity.getName()); ModelNode operation = entityAdapter.fromChangeset(changeset, address); System.out.println(operation); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse dmrResponse) { ModelNode response = ModelNode.fromBase64(dmrResponse.getResponseText()); System.out.println(response); if(ModelNodeUtil.indicatesSuccess(response)) { Console.info("Success: Update interface "+entity.getName()); } else { - Console.error("Error: Failed to update interface " + entity.getName()); + Console.error("Error: Failed to update interface " + entity.getName(), + response.get("failure-description").asString()); } loadInterfaces(); } }); } public static boolean isSet(String value) { return value!=null && !value.isEmpty(); } }
true
true
private void doPersistChanges(final Interface entity, Map<String,Object> changeset) { // artificial values need to be merged manually String wildcard = entity.getAddressWildcard(); changeset.put("anyAddress", wildcard.equals(Interface.ANY_ADDRESS) ? true : FormItem.VALUE_SEMANTICS.UNDEFINED); changeset.put("anyIP4Address", wildcard.equals(Interface.ANY_IP4) ? true : FormItem.VALUE_SEMANTICS.UNDEFINED); changeset.put("anyIP6Address", wildcard.equals(Interface.ANY_IP6) ? true : FormItem.VALUE_SEMANTICS.UNDEFINED); AddressBinding addressBinding = beanMetaData.getAddress(); ModelNode address = addressBinding.asResource(Baseadress.get(), entity.getName()); ModelNode operation = entityAdapter.fromChangeset(changeset, address); System.out.println(operation); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse dmrResponse) { ModelNode response = ModelNode.fromBase64(dmrResponse.getResponseText()); System.out.println(response); if(ModelNodeUtil.indicatesSuccess(response)) { Console.info("Success: Update interface "+entity.getName()); } else { Console.error("Error: Failed to update interface " + entity.getName()); } loadInterfaces(); } }); }
private void doPersistChanges(final Interface entity, Map<String,Object> changeset) { // artificial values need to be merged manually String wildcard = entity.getAddressWildcard(); changeset.put("anyAddress", wildcard.equals(Interface.ANY_ADDRESS) ? true : FormItem.VALUE_SEMANTICS.UNDEFINED); changeset.put("anyIP4Address", wildcard.equals(Interface.ANY_IP4) ? true : FormItem.VALUE_SEMANTICS.UNDEFINED); changeset.put("anyIP6Address", wildcard.equals(Interface.ANY_IP6) ? true : FormItem.VALUE_SEMANTICS.UNDEFINED); AddressBinding addressBinding = beanMetaData.getAddress(); ModelNode address = addressBinding.asResource(Baseadress.get(), entity.getName()); ModelNode operation = entityAdapter.fromChangeset(changeset, address); System.out.println(operation); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse dmrResponse) { ModelNode response = ModelNode.fromBase64(dmrResponse.getResponseText()); System.out.println(response); if(ModelNodeUtil.indicatesSuccess(response)) { Console.info("Success: Update interface "+entity.getName()); } else { Console.error("Error: Failed to update interface " + entity.getName(), response.get("failure-description").asString()); } loadInterfaces(); } }); }
diff --git a/codegen/src/main/java/org/exolab/castor/builder/info/CollectionInfo.java b/codegen/src/main/java/org/exolab/castor/builder/info/CollectionInfo.java index a950b860..8a8f8205 100644 --- a/codegen/src/main/java/org/exolab/castor/builder/info/CollectionInfo.java +++ b/codegen/src/main/java/org/exolab/castor/builder/info/CollectionInfo.java @@ -1,813 +1,820 @@ /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided * that the following conditions are met: * * 1. Redistributions of source code must retain copyright * statements and notices. Redistributions must also contain a * copy of this document. * * 2. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * 3. The name "Exolab" must not be used to endorse or promote * products derived from this Software without prior written * permission of Intalio, Inc. For written permission, * please contact [email protected]. * * 4. Products derived from this Software may not be called "Exolab" * nor may "Exolab" appear in their names without prior written * permission of Intalio, Inc. Exolab is a registered * trademark of Intalio, Inc. * * 5. Due credit should be given to the Exolab Project * (http://www.exolab.org/). * * THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Copyright 1999,2000 (C) Intalio, Inc. All Rights Reserved. * * Contribution(s): * * - Frank Thelen, [email protected] * - Moved creation of access methods into an appropriate * set of separate methods, for extensibility * * $Id$ */ package org.exolab.castor.builder.info; import org.exolab.castor.builder.SGTypes; import org.exolab.castor.builder.SourceGeneratorConstants; import org.exolab.castor.builder.types.XSCollectionFactory; import org.exolab.castor.builder.types.XSListType; import org.exolab.castor.builder.types.XSType; import org.exolab.castor.xml.JavaNaming; import org.exolab.javasource.JArrayType; import org.exolab.javasource.JClass; import org.exolab.javasource.JCollectionType; import org.exolab.javasource.JDocComment; import org.exolab.javasource.JDocDescriptor; import org.exolab.javasource.JMethod; import org.exolab.javasource.JParameter; import org.exolab.javasource.JSourceCode; import org.exolab.javasource.JType; /** * A helper used for generating source that deals with Collections. * @author <a href="mailto:[email protected]">Keith Visco</a> * @version $Revision$ $Date: 2006-02-23 01:08:24 -0700 (Thu, 23 Feb 2006) $ */ public class CollectionInfo extends FieldInfo { /** Default suffix for the setter/getter by reference method names. */ public static final String DEFAULT_REFERENCE_SUFFIX = "AsReference"; /** * The property used to overwrite the reference suffix for extra collection * methods. */ public static final String REFERENCE_SUFFIX_PROPERTY = "org.exolab.castor.builder.collections.reference.suffix"; /** * A flag indicating that "extra" accessor methods should be created for * returning and setting a reference to the underlying collection. */ private boolean _extraMethods; /** The reference suffix to use. */ private String _referenceSuffix = DEFAULT_REFERENCE_SUFFIX; /** Element type name converted to a method suffix. */ private final String _methodSuffix; /** Element type name converted to a parameter prefix. */ private final String _parameterPrefix; /** FieldInfo describing the _content (i.e. the elements) of this collection. */ private final FieldInfo _content; /** The name to be used when referring to the elements of this collection. */ private final String _elementName; /** * Creates a new CollectionInfo. * * @param contentType * the _content type of the collection, ie. the type of objects * that the collection will contain * @param name * the name of the Collection * @param elementName * the element name for each element in collection * @param useJava50 * true if source code is supposed to be generated for Java 5 */ public CollectionInfo(final XSType contentType, final String name, final String elementName, final boolean useJava50) { super(XSCollectionFactory.createCollection(SourceGeneratorConstants.FIELD_INFO_VECTOR, contentType, useJava50), name); if (elementName.charAt(0) == '_') { this._elementName = elementName.substring(1); } else { this._elementName = elementName; } this._methodSuffix = JavaNaming.toJavaClassName(this.getElementName()); this._parameterPrefix = JavaNaming.toJavaMemberName(this.getElementName()); this._content = new FieldInfo(contentType, "v" + this.getMethodSuffix()); } // -- CollectionInfo /** * Generate the various accessor methods. * {@inheritDoc} * * @see org.exolab.castor.builder.info.FieldInfo * #createAccessMethods(org.exolab.javasource.JClass, boolean) */ public final void createAccessMethods(final JClass jClass, final boolean useJava50) { this.createAddAndRemoveMethods(jClass); this.createGetAndSetMethods(jClass, useJava50); this.createGetCountMethod(jClass); this.createCollectionIterationMethods(jClass, useJava50); } // -- createAccessMethods /** * {@inheritDoc} * * @see org.exolab.castor.builder.info.FieldInfo * #generateInitializerCode(org.exolab.javasource.JSourceCode) */ public void generateInitializerCode(final JSourceCode sourceCode) { sourceCode.add("this."); sourceCode.append(this.getName()); sourceCode.append(" = new "); JType jType = this.getXSList().getJType(); sourceCode.append(((JCollectionType) jType).getInstanceName()); sourceCode.append("();"); } // -- generateConstructorCode /** * Return the contents of the collection. * @return the contents of the collection. */ public final FieldInfo getContent() { return this._content; } /** * Returns the variable name for the content of the collection. * @return the variable name for the content of the collection. */ public final String getContentName() { return this.getContent().getName(); } /** * Returns the type of content in this collection. * @return the type of content in this collection. */ public final XSType getContentType() { return this.getContent().getSchemaType(); } /** * Returns the name to be used when referring to the elements of this * collection. * * @return the name to be used when referring to the elements of this * collection. */ public final String getElementName() { return this._elementName; } /** * Returns the schema type represented by this collection. * @return the schema type represented by this collection. */ public final XSListType getXSList() { return (XSListType) this.getSchemaType(); } /** * {@inheritDoc} * * @see org.exolab.castor.builder.info.XMLInfo#isMultivalued() */ public final boolean isMultivalued() { return true; } /** * Sets whether or not to create extra collection methods for accessing the * actual collection. * * @param extraMethods * a boolean that when true indicates that extra collection * accessor methods should be created. False by default. * @see #setReferenceMethodSuffix */ public final void setCreateExtraMethods(final boolean extraMethods) { this._extraMethods = extraMethods; } // -- setCreateExtraMethods /** * Sets the method suffix (ending) to use when creating the extra collection * methods. * * @param suffix * the method suffix to use when creating the extra collection * methods. If null or emtpty the default value, as specified by * DEFAULT_REFERENCE_SUFFIX will used. * @see #setCreateExtraMethods */ public final void setReferenceMethodSuffix(final String suffix) { if (suffix == null || suffix.length() == 0) { this._referenceSuffix = DEFAULT_REFERENCE_SUFFIX; } else { this._referenceSuffix = suffix; } } // -- setReferenceMethodSuffix private void addIndexCheck(final JSourceCode sourceCode, final String methodName) { sourceCode.add("// check bounds for index"); sourceCode.add("if (index < 0 || index >= this."); sourceCode.append(this.getName()); sourceCode.append(".size()) {"); sourceCode.indent(); sourceCode.add("throw new IndexOutOfBoundsException(\""); sourceCode.append(methodName); sourceCode.append(": Index value '\" + index + \"' not in range [0..\" + (this."); sourceCode.append(this.getName()); sourceCode.append(".size() - 1) + \"]\");"); sourceCode.unindent(); sourceCode.add("}"); sourceCode.add(""); } protected final void addMaxSizeCheck(final String methodName, final JSourceCode sourceCode) { if (this.getXSList().getMaximumSize() > 0) { final String size = Integer.toString(getXSList().getMaximumSize()); sourceCode.add("// check for the maximum size"); sourceCode.add("if (this."); sourceCode.append(this.getName()); sourceCode.append(".size() >= "); sourceCode.append(size); sourceCode.append(") {"); sourceCode.indent(); sourceCode.add("throw new IndexOutOfBoundsException(\""); sourceCode.append(methodName); sourceCode.append(" has a maximum of "); sourceCode.append(size); sourceCode.append("\");"); sourceCode.unindent(); sourceCode.add("}"); sourceCode.add(""); } } protected void createAddMethod(final JClass jClass) { JMethod method = new JMethod(this.getWriteMethodName()); method.addException(SGTypes.INDEX_OUT_OF_BOUNDS_EXCEPTION, "if the index given is outside the bounds of the collection"); final JParameter parameter = new JParameter( this.getContentType().getJType(), this.getContentName()); method.addParameter(parameter); JSourceCode sourceCode = method.getSourceCode(); this.addMaxSizeCheck(method.getName(), sourceCode); sourceCode.add("this."); sourceCode.append(this.getName()); sourceCode.append(".addElement("); sourceCode.append(this.getContentType().createToJavaObjectCode(parameter.getName())); sourceCode.append(");"); if (this.isBound()) { this.createBoundPropertyCode(sourceCode); } jClass.addMethod(method); } /** * Creates the necessary source code for notifying PropertyChangeListeners * when the collection has been updated. * * @param sourceCode * the JSourceCode to add the new source code to. */ protected final void createBoundPropertyCode(final JSourceCode sourceCode) { sourceCode.add("notifyPropertyChangeListeners(\""); String fieldName = getName(); if (fieldName.startsWith("_")) { sourceCode.append(fieldName.substring(1)); } else { sourceCode.append(fieldName); } sourceCode.append("\", null, "); sourceCode.append(fieldName); sourceCode.append(");"); } // -- createBoundPropertyCode protected void createEnumerateMethod(final JClass jClass, final boolean useJava50) { JMethod method = new JMethod("enumerate" + this.getMethodSuffix(), SGTypes.createEnumeration(this.getContentType().getJType(), useJava50), "an Enumeration over all " + this.getContentType().getJType() + " elements"); JSourceCode sourceCode = method.getSourceCode(); sourceCode.add("return this."); sourceCode.append(this.getName()); sourceCode.append(".elements();"); jClass.addMethod(method); } /** * Returns true if extra collection methods should be generated. The extra * collection methods are methods which return an actual reference to the * underlying collection as opposed to an enumeration, iterator, or copy. * * @return true if extra collection methods should be generated */ protected final boolean createExtraMethods() { return this._extraMethods; } // -- extraMethods protected final void createGetAsArrayMethod(final JClass jClass, final boolean useJava50) { JType baseType = this.getContentType().getJType(); JType arrayType = new JArrayType(baseType, useJava50); JMethod method = new JMethod(this.getReadMethodName(), arrayType, "this collection as an Array"); JSourceCode sourceCode = method.getSourceCode(); // create Javadoc JDocComment comment = method.getJDocComment(); comment.appendComment("Returns the contents of the collection in an Array. "); if (!(baseType.isPrimitive())) { // For non-primitive types, we use the API method made for this purpose comment.appendComment("<p>"); comment.appendComment("Note: Just in case the collection contents are changing in "); comment.appendComment("another thread, we pass a 0-length Array of the correct type "); comment.appendComment("into the API call. This way we <i>know</i> that the Array "); comment.appendComment("returned is of exactly the correct length."); - sourceCode.add(arrayType.toString() + " array = new " + baseType.toString() + "[0];"); + String baseTypeName = baseType.toString(); + if (baseType.isArray()) { + sourceCode.add(arrayType.toString() + " array = new "); + sourceCode.append(baseTypeName.substring(0, baseTypeName.length() - 2) + "[0][];"); + } else { + sourceCode.add(arrayType.toString() + " array = new "); + sourceCode.append(baseTypeName + "[0];"); + } sourceCode.add("return (" + arrayType.toString() + ") "); sourceCode.append("this." + this.getName() + ".toArray(array);"); } else { // For primitive types, we have to do this the hard way sourceCode.add("int size = this."); sourceCode.append(this.getName()); sourceCode.append(".size();"); sourceCode.add(arrayType.toString()); sourceCode.append(" array = new "); // the first brackets must contain the size... int brackets = arrayType.toString().indexOf("[]"); sourceCode.append(arrayType.toString().substring(0, brackets)); sourceCode.append("[size]"); sourceCode.append(";"); sourceCode.add("java.util.Iterator iter = " + this.getName() + ".iterator();"); String value = "iter.next()"; sourceCode.add("for (int index = 0; index < size; index++) {"); sourceCode.indent(); sourceCode.add("array[index] = "); if (getContentType().getType() == XSType.CLASS) { sourceCode.append("("); sourceCode.append(arrayType.getName()); sourceCode.append(") "); sourceCode.append(value); } else { sourceCode.append(getContentType().createFromJavaObjectCode(value)); } sourceCode.append(";"); sourceCode.unindent(); sourceCode.add("}"); sourceCode.add("return array;"); } jClass.addMethod(method); } protected final void createGetAsReferenceMethod(final JClass jClass) { JMethod method = new JMethod(this.getReadMethodName() + this.getReferenceMethodSuffix(), this.getXSList().getJType(), "a reference to the Vector backing this class"); // create Javadoc JDocComment comment = method.getJDocComment(); comment.appendComment("Returns a reference to '"); comment.appendComment(this.getName()); comment.appendComment("'. No type checking is performed on any "); comment.appendComment("modifications to the Vector."); // create code JSourceCode sourceCode = method.getSourceCode(); sourceCode.add("return this."); sourceCode.append(this.getName()); sourceCode.append(";"); jClass.addMethod(method); } protected void createGetByIndexMethod(final JClass jClass) { XSType contentType = this.getContentType(); JMethod method = new JMethod(this.getReadMethodName(), contentType.getJType(), "the value of the " + contentType.getJType().toString() + " at the given index"); method.addException(SGTypes.INDEX_OUT_OF_BOUNDS_EXCEPTION, "if the index given is outside the bounds of the collection"); method.addParameter(new JParameter(JType.INT, "index")); JSourceCode sourceCode = method.getSourceCode(); this.addIndexCheck(sourceCode, method.getName()); String value = this.getName() + ".get(index)"; sourceCode.add("return "); if (contentType.getType() == XSType.CLASS) { sourceCode.append("("); sourceCode.append(method.getReturnType().toString()); sourceCode.append(") "); sourceCode.append(value); } else { sourceCode.append(contentType.createFromJavaObjectCode(value)); } sourceCode.append(";"); jClass.addMethod(method); } protected final void createAddAndRemoveMethods(final JClass jClass) { // create add methods this.createAddMethod(jClass); this.createAddByIndexMethod(jClass); // create remove methods this.createRemoveObjectMethod(jClass); this.createRemoveByIndexMethod(jClass); this.createRemoveAllMethod(jClass); } /** * @param jClass the JClass to which we add this method * @param useJava50 * true if source code is supposed to be generated for Java 5 */ protected final void createGetAndSetMethods(final JClass jClass, final boolean useJava50) { // create get methods this.createGetByIndexMethod(jClass); this.createGetAsArrayMethod(jClass, useJava50); if (this.createExtraMethods()) { this.createGetAsReferenceMethod(jClass); } // create set methods this.createSetByIndexMethod(jClass); this.createSetAsArrayMethod(jClass, useJava50); if (this.createExtraMethods()) { this.createSetAsCopyMethod(jClass); this.createSetAsReferenceMethod(jClass, useJava50); } } protected final void createGetCountMethod(final JClass jClass) { JMethod method = new JMethod(this.getReadMethodName() + "Count", JType.INT, "the size of this collection"); JSourceCode sourceCode = method.getSourceCode(); sourceCode.add("return this."); sourceCode.append(getName()); sourceCode.append(".size();"); jClass.addMethod(method); } /** * Generate methods for iterating over the objects in the collection. For * Java-1 collections, we only generate an Enumerator. Implementations for * other versions of Java should call this method for backward compatbility * and then add any additional new methods. * * @param jClass the JClass to which we add this method * @param useJava50 * true if source code is supposed to be generated for Java 5 */ protected void createCollectionIterationMethods(final JClass jClass, final boolean useJava50) { this.createEnumerateMethod(jClass, useJava50); } // -- createCollectionAccessMethods protected void createAddByIndexMethod(final JClass jClass) { JMethod method = new JMethod(this.getWriteMethodName()); method.addException(SGTypes.INDEX_OUT_OF_BOUNDS_EXCEPTION, "if the index given is outside the bounds of the collection"); method.addParameter(new JParameter(JType.INT, "index")); final JParameter parameter = new JParameter( this.getContentType().getJType(), this.getContentName()); method.addParameter(parameter); JSourceCode sourceCode = method.getSourceCode(); this.addMaxSizeCheck(method.getName(), sourceCode); sourceCode.add("this."); sourceCode.append(this.getName()); sourceCode.append(".add(index, "); sourceCode.append(this.getContentType().createToJavaObjectCode(parameter.getName())); sourceCode.append(");"); if (this.isBound()) { this.createBoundPropertyCode(sourceCode); } jClass.addMethod(method); } protected final void createIteratorMethod(final JClass jClass, final boolean useJava50) { JMethod method = new JMethod("iterate" + this.getMethodSuffix(), SGTypes.createIterator(this.getContentType().getJType(), useJava50), "an Iterator over all possible elements in this collection"); JSourceCode sourceCode = method.getSourceCode(); sourceCode.add("return this."); sourceCode.append(this.getName()); sourceCode.append(".iterator();"); jClass.addMethod(method); } /** * Creates implementation of removeAll() method. * * @param jClass the JClass to which we add this method */ protected final void createRemoveAllMethod(final JClass jClass) { JMethod method = new JMethod("removeAll" + this.getMethodSuffix()); JSourceCode sourceCode = method.getSourceCode(); sourceCode.add("this."); sourceCode.append(this.getName()); sourceCode.append(".clear();"); if (this.isBound()) { this.createBoundPropertyCode(sourceCode); } jClass.addMethod(method); } /** * Creates implementation of remove(int i) method. * * @param jClass the JClass to which we add this method */ protected void createRemoveByIndexMethod(final JClass jClass) { JMethod method = new JMethod("remove" + this.getMethodSuffix() + "At", this.getContentType().getJType(), "the element removed from the collection"); method.addParameter(new JParameter(JType.INT, "index")); JSourceCode sourceCode = method.getSourceCode(); sourceCode.add("java.lang.Object obj = this."); sourceCode.append(this.getName()); sourceCode.append(".remove(index);"); if (this.isBound()) { this.createBoundPropertyCode(sourceCode); } sourceCode.add("return "); if (getContentType().getType() == XSType.CLASS) { sourceCode.append("("); sourceCode.append(method.getReturnType().getName()); sourceCode.append(") obj;"); } else { sourceCode.append(this.getContentType().createFromJavaObjectCode("obj")); sourceCode.append(";"); } jClass.addMethod(method); } /** * Creates implementation of remove(Object) method. * * @param jClass the JClass to which we add this method */ protected final void createRemoveObjectMethod(final JClass jClass) { JMethod method = new JMethod("remove" + this.getMethodSuffix(), JType.BOOLEAN, "true if the object was removed from the collection."); final JParameter parameter = new JParameter(this.getContentType().getJType(), this.getContentName()); method.addParameter(parameter); JSourceCode sourceCode = method.getSourceCode(); sourceCode.add("boolean removed = "); sourceCode.append(this.getName()); sourceCode.append(".remove("); sourceCode.append(this.getContentType().createToJavaObjectCode(parameter.getName())); sourceCode.append(");"); if (this.isBound()) { this.createBoundPropertyCode(sourceCode); } sourceCode.add("return removed;"); jClass.addMethod(method); } protected final void createSetAsArrayMethod(final JClass jClass, final boolean useJava50) { JMethod method = new JMethod("set" + this.getMethodSuffix()); final JParameter parameter = new JParameter(new JArrayType( this.getContentType().getJType(), useJava50), this.getContentName() + "Array"); method.addParameter(parameter); JSourceCode sourceCode = method.getSourceCode(); String index = "i"; if (parameter.getName().equals(index)) { index = "j"; } sourceCode.add("//-- copy array"); sourceCode.add(this.getName()); sourceCode.append(".clear();"); sourceCode.add(""); sourceCode.add("for (int "); sourceCode.append(index); sourceCode.append(" = 0; "); sourceCode.append(index); sourceCode.append(" < "); sourceCode.append(parameter.getName()); sourceCode.append(".length; "); sourceCode.append(index); sourceCode.append("++) {"); sourceCode.indent(); sourceCode.addIndented("this."); sourceCode.append(this.getName()); sourceCode.append(".add("); sourceCode.append(this.getContentType().createToJavaObjectCode( parameter.getName() + "[" + index + "]")); sourceCode.append(");"); sourceCode.unindent(); sourceCode.add("}"); if (this.isBound()) { this.createBoundPropertyCode(sourceCode); } jClass.addMethod(method); } /** * Creates implementation of collection set method. The method will assign * the field a copy of the given collection.<br> * The fields will be checked for type safety. * * @param jClass */ protected final void createSetAsCopyMethod(final JClass jClass) { JMethod method = new JMethod("set" + this.getMethodSuffix()); JParameter parameter = new JParameter(this.getXSList().getJType(), this.getContentName() + "List"); method.addParameter(parameter); // create Javadoc JDocComment comment = method.getJDocComment(); comment.appendComment("Sets the value of '"); comment.appendComment(this.getName()); comment.appendComment( "' by copying the given Vector. All elements will be checked for type safety."); JDocDescriptor jDesc = comment.getParamDescriptor(parameter.getName()); jDesc.setDescription("the Vector to copy."); // create code JSourceCode sourceCode = method.getSourceCode(); sourceCode.add("// copy vector"); sourceCode.add("this."); sourceCode.append(this.getName()); sourceCode.append(".clear();"); sourceCode.add(""); sourceCode.add("this."); sourceCode.append(getName()); sourceCode.append(".addAll("); sourceCode.append(parameter.getName()); sourceCode.append(");"); if (this.isBound()) { this.createBoundPropertyCode(sourceCode); } jClass.addMethod(method); } /** * Creates implementation of collection reference set method. This method is * a non-type safe method which simply assigns the given collection to the * field. * * @param jClass * @param useJava50 true if source code is supposed to be generated for Java 5 */ protected final void createSetAsReferenceMethod(final JClass jClass, final boolean useJava50) { JMethod method = new JMethod("set" + this.getMethodSuffix() + _referenceSuffix); final JType collectionJType = getSchemaType().getJType(); JParameter parameter = new JParameter( collectionJType, this.getParameterPrefix() + collectionJType.getLocalName()); method.addParameter(parameter); // create Javadoc JDocComment comment = method.getJDocComment(); comment.appendComment("Sets the value of '"); comment.appendComment(this.getName()); comment.appendComment("' by setting it to the given Vector."); comment.appendComment(" No type checking is performed."); comment.appendComment("\n@deprecated"); JDocDescriptor jDesc = comment.getParamDescriptor(parameter.getName()); jDesc.setDescription("the Vector to set."); // create code JSourceCode sourceCode = method.getSourceCode(); sourceCode.add("this."); sourceCode.append(this.getName()); sourceCode.append(" = "); sourceCode.append(parameter.getName()); sourceCode.append(";"); if (this.isBound()) { this.createBoundPropertyCode(sourceCode); } jClass.addMethod(method); } private String getParameterPrefix() { return _parameterPrefix; } protected void createSetByIndexMethod(final JClass jClass) { JMethod method = new JMethod("set" + this.getMethodSuffix()); method.addException(SGTypes.INDEX_OUT_OF_BOUNDS_EXCEPTION, "if the index given is outside the bounds of the collection"); method.addParameter(new JParameter(JType.INT, "index")); method.addParameter(new JParameter(this.getContentType().getJType(), this.getContentName())); JSourceCode sourceCode = method.getSourceCode(); this.addIndexCheck(sourceCode, method.getName()); sourceCode.add("this."); sourceCode.append(this.getName()); sourceCode.append(".set(index, "); sourceCode.append(this.getContentType().createToJavaObjectCode(getContentName())); sourceCode.append(");"); if (this.isBound()) { this.createBoundPropertyCode(sourceCode); } jClass.addMethod(method); } /** * {@inheritDoc} * * @see org.exolab.castor.builder.info.FieldInfo#getMethodSuffix() */ public final String getMethodSuffix() { return this._methodSuffix; } /** * Returns the suffix (ending) that should be used when creating the extra * collection methods. * * @return the suffix for the reference methods */ protected final String getReferenceMethodSuffix() { return this._referenceSuffix; } // -- getReferenceMethodSuffix } // -- CollectionInfo
true
true
protected final void createGetAsArrayMethod(final JClass jClass, final boolean useJava50) { JType baseType = this.getContentType().getJType(); JType arrayType = new JArrayType(baseType, useJava50); JMethod method = new JMethod(this.getReadMethodName(), arrayType, "this collection as an Array"); JSourceCode sourceCode = method.getSourceCode(); // create Javadoc JDocComment comment = method.getJDocComment(); comment.appendComment("Returns the contents of the collection in an Array. "); if (!(baseType.isPrimitive())) { // For non-primitive types, we use the API method made for this purpose comment.appendComment("<p>"); comment.appendComment("Note: Just in case the collection contents are changing in "); comment.appendComment("another thread, we pass a 0-length Array of the correct type "); comment.appendComment("into the API call. This way we <i>know</i> that the Array "); comment.appendComment("returned is of exactly the correct length."); sourceCode.add(arrayType.toString() + " array = new " + baseType.toString() + "[0];"); sourceCode.add("return (" + arrayType.toString() + ") "); sourceCode.append("this." + this.getName() + ".toArray(array);"); } else { // For primitive types, we have to do this the hard way sourceCode.add("int size = this."); sourceCode.append(this.getName()); sourceCode.append(".size();"); sourceCode.add(arrayType.toString()); sourceCode.append(" array = new "); // the first brackets must contain the size... int brackets = arrayType.toString().indexOf("[]"); sourceCode.append(arrayType.toString().substring(0, brackets)); sourceCode.append("[size]"); sourceCode.append(";"); sourceCode.add("java.util.Iterator iter = " + this.getName() + ".iterator();"); String value = "iter.next()"; sourceCode.add("for (int index = 0; index < size; index++) {"); sourceCode.indent(); sourceCode.add("array[index] = "); if (getContentType().getType() == XSType.CLASS) { sourceCode.append("("); sourceCode.append(arrayType.getName()); sourceCode.append(") "); sourceCode.append(value); } else { sourceCode.append(getContentType().createFromJavaObjectCode(value)); } sourceCode.append(";"); sourceCode.unindent(); sourceCode.add("}"); sourceCode.add("return array;"); } jClass.addMethod(method); }
protected final void createGetAsArrayMethod(final JClass jClass, final boolean useJava50) { JType baseType = this.getContentType().getJType(); JType arrayType = new JArrayType(baseType, useJava50); JMethod method = new JMethod(this.getReadMethodName(), arrayType, "this collection as an Array"); JSourceCode sourceCode = method.getSourceCode(); // create Javadoc JDocComment comment = method.getJDocComment(); comment.appendComment("Returns the contents of the collection in an Array. "); if (!(baseType.isPrimitive())) { // For non-primitive types, we use the API method made for this purpose comment.appendComment("<p>"); comment.appendComment("Note: Just in case the collection contents are changing in "); comment.appendComment("another thread, we pass a 0-length Array of the correct type "); comment.appendComment("into the API call. This way we <i>know</i> that the Array "); comment.appendComment("returned is of exactly the correct length."); String baseTypeName = baseType.toString(); if (baseType.isArray()) { sourceCode.add(arrayType.toString() + " array = new "); sourceCode.append(baseTypeName.substring(0, baseTypeName.length() - 2) + "[0][];"); } else { sourceCode.add(arrayType.toString() + " array = new "); sourceCode.append(baseTypeName + "[0];"); } sourceCode.add("return (" + arrayType.toString() + ") "); sourceCode.append("this." + this.getName() + ".toArray(array);"); } else { // For primitive types, we have to do this the hard way sourceCode.add("int size = this."); sourceCode.append(this.getName()); sourceCode.append(".size();"); sourceCode.add(arrayType.toString()); sourceCode.append(" array = new "); // the first brackets must contain the size... int brackets = arrayType.toString().indexOf("[]"); sourceCode.append(arrayType.toString().substring(0, brackets)); sourceCode.append("[size]"); sourceCode.append(";"); sourceCode.add("java.util.Iterator iter = " + this.getName() + ".iterator();"); String value = "iter.next()"; sourceCode.add("for (int index = 0; index < size; index++) {"); sourceCode.indent(); sourceCode.add("array[index] = "); if (getContentType().getType() == XSType.CLASS) { sourceCode.append("("); sourceCode.append(arrayType.getName()); sourceCode.append(") "); sourceCode.append(value); } else { sourceCode.append(getContentType().createFromJavaObjectCode(value)); } sourceCode.append(";"); sourceCode.unindent(); sourceCode.add("}"); sourceCode.add("return array;"); } jClass.addMethod(method); }
diff --git a/src/me/corriekay/pppopp3/warp/WarpHandler.java b/src/me/corriekay/pppopp3/warp/WarpHandler.java index 0615092..4c80315 100644 --- a/src/me/corriekay/pppopp3/warp/WarpHandler.java +++ b/src/me/corriekay/pppopp3/warp/WarpHandler.java @@ -1,559 +1,564 @@ package me.corriekay.pppopp3.warp; import java.util.*; import me.corriekay.pppopp3.Mane; import me.corriekay.pppopp3.events.JoinEvent; import me.corriekay.pppopp3.events.QuitEvent; import me.corriekay.pppopp3.modules.Equestria; import me.corriekay.pppopp3.ponyville.Pony; import me.corriekay.pppopp3.ponyville.Ponyville; import me.corriekay.pppopp3.utils.PSCmdExe; import org.bukkit.*; import org.bukkit.World.Environment; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public class WarpHandler extends PSCmdExe{ private static WarpHandler wh; private HashMap<String,WarpList> warpHandler = new HashMap<String,WarpList>(); private HashMap<String,QueuedWarp> warpQueues = new HashMap<String,QueuedWarp>(); private HashMap<String,String> tpQueues = new HashMap<String,String>(); private HashMap<String,Location> homes = new HashMap<String,Location>(); private HashMap<String,Location> backs = new HashMap<String,Location>(); private final int warpCount; private HashMap<World,Location> spawns = new HashMap<World,Location>(); //private static WarpHandler wh; public WarpHandler() throws Exception{ super("WarpHandler", "gw", "pw", "pwlist", "pwdel", "pwset", "gwset", "gwdel", "pwplayer", "tp", "tpa", "tpd", "tphere", "home", "sethome", "back", "spawn", "setspawn", "top"); wh = this; FileConfiguration config = getNamedConfig("warps.yml"); buildWarpList(config); for(Player player : Bukkit.getOnlinePlayers()) { warpHandler.put(player.getName(), getPlayerWarps(player)); loadHome(player); loadBack(player); } methodMap.put(EntityDamageByEntityEvent.class, this.getClass().getMethod("onDamage", EntityDamageEvent.class)); Bukkit.getScheduler().scheduleSyncRepeatingTask(Mane.getInstance(), new Runnable() { @Override public void run(){ HashSet<String> removeMe = new HashSet<String>(); for(String name : warpQueues.keySet()) { QueuedWarp qw = warpQueues.get(name); if(qw.countdown()) { removeMe.add(name); } } for(String name : removeMe) { warpQueues.remove(name); } } }, 0, 20); warpCount = config.getInt("warpCount", 7); for(World w : Equestria.get().getParentWorlds()) { Location spawn = getLocFromList((ArrayList<String>)config.getStringList("spawns." + w.getName())); if(spawn == null) { spawns.put(w, w.getSpawnLocation()); config.set("spawns." + w.getName(), getListFromLoc(w.getSpawnLocation())); } else { spawns.put(w, spawn); } } saveNamedConfig("warps.yml", config); } private void buildWarpList(FileConfiguration config){ HashMap<String,Warp> globalWarpsMap = new HashMap<String,Warp>(); for(String warpName : config.getConfigurationSection("warps").getKeys(false)) { globalWarpsMap.put(warpName, new Warp(warpName, getLocFromList(config.getStringList("warps." + warpName)))); } WarpList global = new WarpList(globalWarpsMap); warpHandler.put("global", global); } private WarpList getPlayerWarps(Player player){ Pony pony = Ponyville.getPony(player); HashMap<String,Location> warps = pony.getAllNamedWarps(); HashMap<String,Warp> warpsList = new HashMap<String,Warp>(); for(String name : warps.keySet()) { warpsList.put(name, new Warp(name, warps.get(name))); } return new WarpList(warpsList); } private void loadHome(Player player){ Pony pony = Ponyville.getPony(player); Location loc = pony.getHomeWarp(); homes.put(player.getName(), loc); } private void loadBack(Player player){ Pony pony = Ponyville.getPony(player); Location loc = pony.getBackWarp(); homes.put(player.getName(), loc); } private Location getLocFromList(List<String> list){ try { String w; double x, y, z; float p, yaw; w = list.get(0); x = Double.parseDouble(list.get(1)); y = Double.parseDouble(list.get(2)); z = Double.parseDouble(list.get(3)); p = Float.parseFloat(list.get(4)); yaw = Float.parseFloat(list.get(5)); Location l = new Location(Bukkit.getWorld(w), x, y, z); l.setPitch(p); l.setYaw(yaw); return l; } catch(Exception e) { return null; } } private ArrayList<String> getListFromLoc(Location loc){ try { ArrayList<String> list = new ArrayList<String>(); list.add(loc.getWorld().getName()); list.add(loc.getX() + ""); list.add(loc.getY() + ""); list.add(loc.getZ() + ""); list.add(loc.getPitch() + ""); list.add(loc.getYaw() + ""); return list; } catch(Exception e) { return null; } } public boolean handleCommand(CommandSender sender, Command cmd, String label, String[] args){ if(cmd.getName().equals("warpdebug")) { for(String warpCategory : warpHandler.keySet()) { System.out.print(warpCategory + ":"); WarpList wl = warpHandler.get(warpCategory); for(String warp : wl.warps()) { System.out.print(warp); } } } if(cmd.getName().equals("pwlist")) { WarpList global = warpHandler.get("global"); if(global.size() > 0) { String gWarps = ChatColor.RED + "Global Warps: "; for(String warp : global.warps()) { gWarps += ChatColor.RED + warp + ChatColor.WHITE + ", "; } gWarps = gWarps.substring(0, gWarps.length() - 4); sendMessage(sender, "Heres a list of global warps!"); sender.sendMessage(gWarps); } if(sender instanceof Player) { Player player = (Player)sender; WarpList pWarps = warpHandler.get(player.getName()); if(pWarps.size() > 0) { String pWarp = ChatColor.RED + "Private Warps: "; for(String warp : pWarps.warps()) { pWarp += ChatColor.RED + warp + ChatColor.WHITE + ", "; } pWarp = pWarp.substring(0, pWarp.length() - 4); sendMessage(player, "Heres a list of your private warps!"); player.sendMessage(pWarp); } } return true; } Player player; if(sender instanceof Player) { player = (Player)sender; } else { sendMessage(sender, notPlayer); return true; } if(cmd.getName().equals("top")) { Location loc = player.getLocation(); int y = loc.getWorld().getHighestBlockYAt(loc); loc.setY(y); player.teleport(loc); return true; } if(cmd.getName().equals("spawn")) { World w = player.getWorld(); if(args.length > 0) { w = Bukkit.getWorld(args[0]); } w = Equestria.get().getParentWorld(w); + Location l = spawns.get(w); + if(l == null) { + sendMessage(player, "Spawn not found!"); + return true; + } queueWarp(player, spawns.get(w)); return true; } if(cmd.getName().equals("setspawn")) { World w = player.getWorld(); if(w.getEnvironment() != Environment.NORMAL) { sendMessage(player, "The spawn is located in the overworld silly!"); return true; } Location l = player.getLocation(); ArrayList<String> loc = getListFromLoc(l); sendMessage(player, "Spawn set!"); World parent = Equestria.get().getParentWorld(w); spawns.put(parent, l); FileConfiguration config = getNamedConfig("warps.yml"); config.set("spawns." + parent.getName(), loc); saveNamedConfig("warps.yml", config); return true; } if(cmd.getName().equals("tpa")) { String target = tpQueues.get(player.getName()); if(target == null) { sendMessage(player, "Uh oh! no teleport request!"); return true; } Player targetP; targetP = Bukkit.getPlayerExact(target); if(targetP == null) { sendMessage(player, "Uh oh, no teleport request!"); return true; } tpQueues.remove(player.getName()); sendMessage(player, "Teleport request accepted!"); sendMessage(targetP, "Teleport request accepted!"); queueWarp(targetP, player.getLocation()); return true; } if(cmd.getName().equals("tpd")) { String requester = tpQueues.get(player.getName()); if(requester == null) { sendMessage(player, "Uh oh, no teleport request!"); return true; } Player targetP = Bukkit.getPlayerExact(requester); if(targetP != null) { sendMessage(targetP, "Teleport request denied from " + player.getDisplayName() + "!"); } sendMessage(player, "Teleport request denied!"); tpQueues.remove(player.getName()); return true; } if(cmd.getName().equals("home")) { Location home = homes.get(player.getName()); if(home == null) { sendMessage(player, "Uh oh, you have no home set! Try setting a home with /sethome!"); return true; } queueWarp(player, home); return true; } if(cmd.getName().equals("sethome")) { Pony pony = Ponyville.getPony(player); pony.setHomeWarp(player.getLocation()); pony.save(); homes.put(player.getName(), player.getLocation()); sendMessage(player, "Woo hoo! home set! Shall we throw a housewarming party?"); return true; } if(cmd.getName().equals("back")) { Location back = backs.get(player.getName()); if(back != null) { queueWarp(player, back); return true; } else { sendMessage(player, "Hey, silly! You havnt warped anywhere yet!"); return true; } } if(cmd.getName().equals("pwplayer")) { if(args.length < 2) { sendMessage(player, "Heres a list of pwplayer commands!"); sendMessage(player, "/pwplayer <player> list - This lists their warps!"); sendMessage(player, "/pwplayer <player> <warpname> - This teleports to one of their warps!"); sendMessage(player, "/pwplayer <player> offline - This teleports to the location they last logged off at!"); sendMessage(player, "/pwplayer <player> home - This teleports to their home location!"); sendMessage(player, "/pwplayer <player> back - This teleports to their back location!"); return true; } OfflinePlayer target = getOnlineOfflinePlayer(args[0], player); if(target == null) { return true; } Pony pony = Ponyville.getOfflinePony(target.getName()); if(args[1].equals("list")) { ArrayList<String> warps = new ArrayList<String>(); warps.addAll(pony.getAllNamedWarps().keySet()); Collections.sort(warps); if(warps.size() < 1) { sendMessage(player, "That player doesnt have any warps... YET!"); return true; } String warpstring = ""; for(String warp : warps) { warpstring += ChatColor.LIGHT_PURPLE + warp + ChatColor.WHITE + ", "; } warpstring = warpstring.substring(0, warpstring.length() - 4); sendMessage(player, "Heres a list of this players warps!: " + warpstring); return true; } else if(args[1].equals("offline")) { Location loc = pony.getOfflineWarp(); if(loc == null) { sendMessage(player, "Uh oh, that warp isnt set!"); return true; } player.teleport(loc); return true; } else if(args[1].equals("home")) { Location loc = pony.getHomeWarp(); if(loc == null) { sendMessage(player, "Uh oh, that warp isnt set!"); return true; } player.teleport(loc); return true; } else if(args[1].equals("back")) { Location loc = pony.getBackWarp(); if(loc == null) { sendMessage(player, "Uh oh, that warp isnt set!"); return true; } player.teleport(loc); return true; } else { Location loc = pony.getNamedWarp(args[1]); if(loc == null) { sendMessage(player, "Uh oh, that warp isnt set!"); return true; } player.teleport(loc); return true; } } if(args.length < 1) { sendMessage(player, notEnoughArgs); return true; } if(cmd.getName().equals("gw")) { WarpList global = warpHandler.get("global"); Location loc = global.getWarp(args[0]); if(loc == null) { sendMessage(player, "Uh oh, I couldnt find that warp!"); return true; } queueWarp(player, loc); return true; } if(cmd.getName().equals("pw")) { WarpList playerWarps = warpHandler.get(player.getName()); Location loc = playerWarps.getWarp(args[0]); if(loc == null) { sendMessage(player, "Uh oh, I couldnt find that warp!"); return true; } queueWarp(player, loc); return true; } if(cmd.getName().equals("pwdel")) { args[0] = args[0].toLowerCase(); Location w = warpHandler.get(player.getName()).getWarp(args[0]); if(w == null || args[0].equalsIgnoreCase("other")) { sendMessage(player, "Uh oh, I couldnt find that warp!"); return true; } Pony pony = Ponyville.getPony(player); pony.removeNamedWarp(args[0]); pony.save(); sendMessage(player, "Warp deleted!"); warpHandler.put(player.getName(), getPlayerWarps(player)); return true; } if(cmd.getName().equals("pwset")) { args[0] = args[0].toLowerCase(); if(args[0].equals("other")) { sendMessage(player, "Uh oh, sorry! thats a reserved name! please choose another warp name!"); return true; } Pony pony = Ponyville.getPony(player); int count = 1; for(String warp : pony.getAllNamedWarps().keySet()) { if(!warp.equals(args[0])) { count++; } } if(count > warpCount) { sendMessage(player, "You have too many warps! You need to delete one, or overwrite an existing one to set another warp!"); return true; } pony.setNamedWarp(args[0], player.getLocation()); pony.save(); sendMessage(player, "Wormhole opened! Warp " + args[0] + " set!"); warpHandler.put(player.getName(), getPlayerWarps(player)); return true; } if(cmd.getName().equals("gwset")) { String name = args[0].toLowerCase(); FileConfiguration config = getNamedConfig("warps.yml"); config.set("warps." + name, getListFromLoc(player.getLocation())); saveNamedConfig("warps.yml", config); buildWarpList(config); for(Player p : Bukkit.getOnlinePlayers()) { sendMessage(p, "Wormhole opened! New global warp set: " + name + "!"); } return true; } if(cmd.getName().equals("gwdel")) { String name = args[0].toLowerCase(); WarpList global = warpHandler.get("global"); Location loc = global.getWarp(name); if(loc == null) { sendMessage(player, "Uh oh! I couldnt find that warp!"); return true; } FileConfiguration config = getNamedConfig("warps.yml"); config.set("warps." + name, null); saveNamedConfig("warps.yml", config); buildWarpList(config); for(Player p : Bukkit.getOnlinePlayers()) { sendMessage(p, "Wormhole closed! Global warp " + name + " deleted!"); } return true; } if(cmd.getName().equals("tp")) { Player target = getOnlinePlayer(args[0], player); if(target == null) { return true; } if(player.hasPermission("pppopp3.tpbypass")) { player.teleport(target); return true; } sendMessage(target, player.getDisplayName() + ChatColor.LIGHT_PURPLE + " has sent you a teleport request! type /tpa to accept, or type /tpd to deny it!"); sendMessage(player, "Yay! you've sent a teleport request to " + target.getDisplayName()); tpQueues.put(target.getName(), player.getName()); return true; } if(cmd.getName().equals("tphere")) { Player target = getOnlinePlayer(args[0], player); if(target == null) { return true; } target.teleport(player); return true; } return true; } private void queueWarp(Player player, Location loc){ if(player.hasPermission("pppopp3.tpbypass")) { player.teleport(loc); sendMessage(player, "Using the express admin wormhole!"); return; } try { warpQueues.put(player.getName(), new QueuedWarp(player.getName(), loc, 7)); } catch(Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } sendMessage(player, "Okay! setting up the wormhole... This process is delicate..."); } @EventHandler public void onJoin(JoinEvent event){ if(event.isJoining()) { Player player = event.getPlayer(); if(!player.hasPlayedBefore()) { player.teleport(spawns.get(Bukkit.getWorld("world"))); } warpHandler.put(player.getName(), getPlayerWarps(player)); loadBack(player); loadHome(player); } } @EventHandler public void onQuit(QuitEvent event){ Player player = event.getPlayer(); if(event.isQuitting()) { warpHandler.remove(player.getName()); backs.remove(player.getName()); homes.remove(player.getName()); } tpQueues.remove(player.getName()); } @EventHandler (priority = EventPriority.MONITOR) public void onDamage(EntityDamageEvent event){ if(event.getEntity() instanceof Player) { Player player = (Player)event.getEntity(); if(warpQueues.containsKey(player.getName())) { warpQueues.remove(player.getName()); sendMessage(player, "Oh no! Catastrophic failure! Warp aborted to avoid black holes!"); } if(tpQueues.containsKey(player.getName())) { tpQueues.remove(player.getName()); sendMessage(player, "Oh no! Catastrophic failure! Player teleport aborted to avoid black holes!"); } } } @EventHandler public void teleport(PlayerTeleportEvent event){ if(event.getCause() == TeleportCause.PLUGIN) { event.getTo().getChunk().load(); Player player = event.getPlayer(); Pony pony = Ponyville.getPony(player); Location back = event.getFrom(); pony.setBackWarp(back); pony.save(); backs.put(player.getName(), back); } } @EventHandler public void onRespawn(PlayerRespawnEvent event){ Player player = event.getPlayer(); Location loc = homes.get(player.getName()); if(loc == null) { Location spawn = spawns.get(Equestria.get().getParentWorld(player.getLocation().getWorld())); event.setRespawnLocation(spawn); return; } else { World overworld, parentOverworld; overworld = Equestria.get().getParentWorld(loc.getWorld()); parentOverworld = Equestria.get().getParentWorld(player.getLocation().getWorld()); if(overworld != parentOverworld) { event.setRespawnLocation(spawns.get(parentOverworld)); } else { event.setRespawnLocation(loc); } return; } } public static Location getWorldSpawn(){ return wh.spawns.get(Bukkit.getWorld("world")); } @EventHandler public void onDeath(PlayerDeathEvent event){ Player player = event.getEntity(); Location loc = player.getLocation(); sendMessage(player, "Oh gosh! Are you okay? ..Shoot, silly me, of course youre not okay... Well, for future reference, heres your location: x: " + loc.getBlockX() + " y: " + loc.getBlockY() + " z: " + loc.getBlockZ() + "! Dont lose your stuff!!"); } }
true
true
public boolean handleCommand(CommandSender sender, Command cmd, String label, String[] args){ if(cmd.getName().equals("warpdebug")) { for(String warpCategory : warpHandler.keySet()) { System.out.print(warpCategory + ":"); WarpList wl = warpHandler.get(warpCategory); for(String warp : wl.warps()) { System.out.print(warp); } } } if(cmd.getName().equals("pwlist")) { WarpList global = warpHandler.get("global"); if(global.size() > 0) { String gWarps = ChatColor.RED + "Global Warps: "; for(String warp : global.warps()) { gWarps += ChatColor.RED + warp + ChatColor.WHITE + ", "; } gWarps = gWarps.substring(0, gWarps.length() - 4); sendMessage(sender, "Heres a list of global warps!"); sender.sendMessage(gWarps); } if(sender instanceof Player) { Player player = (Player)sender; WarpList pWarps = warpHandler.get(player.getName()); if(pWarps.size() > 0) { String pWarp = ChatColor.RED + "Private Warps: "; for(String warp : pWarps.warps()) { pWarp += ChatColor.RED + warp + ChatColor.WHITE + ", "; } pWarp = pWarp.substring(0, pWarp.length() - 4); sendMessage(player, "Heres a list of your private warps!"); player.sendMessage(pWarp); } } return true; } Player player; if(sender instanceof Player) { player = (Player)sender; } else { sendMessage(sender, notPlayer); return true; } if(cmd.getName().equals("top")) { Location loc = player.getLocation(); int y = loc.getWorld().getHighestBlockYAt(loc); loc.setY(y); player.teleport(loc); return true; } if(cmd.getName().equals("spawn")) { World w = player.getWorld(); if(args.length > 0) { w = Bukkit.getWorld(args[0]); } w = Equestria.get().getParentWorld(w); queueWarp(player, spawns.get(w)); return true; } if(cmd.getName().equals("setspawn")) { World w = player.getWorld(); if(w.getEnvironment() != Environment.NORMAL) { sendMessage(player, "The spawn is located in the overworld silly!"); return true; } Location l = player.getLocation(); ArrayList<String> loc = getListFromLoc(l); sendMessage(player, "Spawn set!"); World parent = Equestria.get().getParentWorld(w); spawns.put(parent, l); FileConfiguration config = getNamedConfig("warps.yml"); config.set("spawns." + parent.getName(), loc); saveNamedConfig("warps.yml", config); return true; } if(cmd.getName().equals("tpa")) { String target = tpQueues.get(player.getName()); if(target == null) { sendMessage(player, "Uh oh! no teleport request!"); return true; } Player targetP; targetP = Bukkit.getPlayerExact(target); if(targetP == null) { sendMessage(player, "Uh oh, no teleport request!"); return true; } tpQueues.remove(player.getName()); sendMessage(player, "Teleport request accepted!"); sendMessage(targetP, "Teleport request accepted!"); queueWarp(targetP, player.getLocation()); return true; } if(cmd.getName().equals("tpd")) { String requester = tpQueues.get(player.getName()); if(requester == null) { sendMessage(player, "Uh oh, no teleport request!"); return true; } Player targetP = Bukkit.getPlayerExact(requester); if(targetP != null) { sendMessage(targetP, "Teleport request denied from " + player.getDisplayName() + "!"); } sendMessage(player, "Teleport request denied!"); tpQueues.remove(player.getName()); return true; } if(cmd.getName().equals("home")) { Location home = homes.get(player.getName()); if(home == null) { sendMessage(player, "Uh oh, you have no home set! Try setting a home with /sethome!"); return true; } queueWarp(player, home); return true; } if(cmd.getName().equals("sethome")) { Pony pony = Ponyville.getPony(player); pony.setHomeWarp(player.getLocation()); pony.save(); homes.put(player.getName(), player.getLocation()); sendMessage(player, "Woo hoo! home set! Shall we throw a housewarming party?"); return true; } if(cmd.getName().equals("back")) { Location back = backs.get(player.getName()); if(back != null) { queueWarp(player, back); return true; } else { sendMessage(player, "Hey, silly! You havnt warped anywhere yet!"); return true; } } if(cmd.getName().equals("pwplayer")) { if(args.length < 2) { sendMessage(player, "Heres a list of pwplayer commands!"); sendMessage(player, "/pwplayer <player> list - This lists their warps!"); sendMessage(player, "/pwplayer <player> <warpname> - This teleports to one of their warps!"); sendMessage(player, "/pwplayer <player> offline - This teleports to the location they last logged off at!"); sendMessage(player, "/pwplayer <player> home - This teleports to their home location!"); sendMessage(player, "/pwplayer <player> back - This teleports to their back location!"); return true; } OfflinePlayer target = getOnlineOfflinePlayer(args[0], player); if(target == null) { return true; } Pony pony = Ponyville.getOfflinePony(target.getName()); if(args[1].equals("list")) { ArrayList<String> warps = new ArrayList<String>(); warps.addAll(pony.getAllNamedWarps().keySet()); Collections.sort(warps); if(warps.size() < 1) { sendMessage(player, "That player doesnt have any warps... YET!"); return true; } String warpstring = ""; for(String warp : warps) { warpstring += ChatColor.LIGHT_PURPLE + warp + ChatColor.WHITE + ", "; } warpstring = warpstring.substring(0, warpstring.length() - 4); sendMessage(player, "Heres a list of this players warps!: " + warpstring); return true; } else if(args[1].equals("offline")) { Location loc = pony.getOfflineWarp(); if(loc == null) { sendMessage(player, "Uh oh, that warp isnt set!"); return true; } player.teleport(loc); return true; } else if(args[1].equals("home")) { Location loc = pony.getHomeWarp(); if(loc == null) { sendMessage(player, "Uh oh, that warp isnt set!"); return true; } player.teleport(loc); return true; } else if(args[1].equals("back")) { Location loc = pony.getBackWarp(); if(loc == null) { sendMessage(player, "Uh oh, that warp isnt set!"); return true; } player.teleport(loc); return true; } else { Location loc = pony.getNamedWarp(args[1]); if(loc == null) { sendMessage(player, "Uh oh, that warp isnt set!"); return true; } player.teleport(loc); return true; } } if(args.length < 1) { sendMessage(player, notEnoughArgs); return true; } if(cmd.getName().equals("gw")) { WarpList global = warpHandler.get("global"); Location loc = global.getWarp(args[0]); if(loc == null) { sendMessage(player, "Uh oh, I couldnt find that warp!"); return true; } queueWarp(player, loc); return true; } if(cmd.getName().equals("pw")) { WarpList playerWarps = warpHandler.get(player.getName()); Location loc = playerWarps.getWarp(args[0]); if(loc == null) { sendMessage(player, "Uh oh, I couldnt find that warp!"); return true; } queueWarp(player, loc); return true; } if(cmd.getName().equals("pwdel")) { args[0] = args[0].toLowerCase(); Location w = warpHandler.get(player.getName()).getWarp(args[0]); if(w == null || args[0].equalsIgnoreCase("other")) { sendMessage(player, "Uh oh, I couldnt find that warp!"); return true; } Pony pony = Ponyville.getPony(player); pony.removeNamedWarp(args[0]); pony.save(); sendMessage(player, "Warp deleted!"); warpHandler.put(player.getName(), getPlayerWarps(player)); return true; } if(cmd.getName().equals("pwset")) { args[0] = args[0].toLowerCase(); if(args[0].equals("other")) { sendMessage(player, "Uh oh, sorry! thats a reserved name! please choose another warp name!"); return true; } Pony pony = Ponyville.getPony(player); int count = 1; for(String warp : pony.getAllNamedWarps().keySet()) { if(!warp.equals(args[0])) { count++; } } if(count > warpCount) { sendMessage(player, "You have too many warps! You need to delete one, or overwrite an existing one to set another warp!"); return true; } pony.setNamedWarp(args[0], player.getLocation()); pony.save(); sendMessage(player, "Wormhole opened! Warp " + args[0] + " set!"); warpHandler.put(player.getName(), getPlayerWarps(player)); return true; } if(cmd.getName().equals("gwset")) { String name = args[0].toLowerCase(); FileConfiguration config = getNamedConfig("warps.yml"); config.set("warps." + name, getListFromLoc(player.getLocation())); saveNamedConfig("warps.yml", config); buildWarpList(config); for(Player p : Bukkit.getOnlinePlayers()) { sendMessage(p, "Wormhole opened! New global warp set: " + name + "!"); } return true; } if(cmd.getName().equals("gwdel")) { String name = args[0].toLowerCase(); WarpList global = warpHandler.get("global"); Location loc = global.getWarp(name); if(loc == null) { sendMessage(player, "Uh oh! I couldnt find that warp!"); return true; } FileConfiguration config = getNamedConfig("warps.yml"); config.set("warps." + name, null); saveNamedConfig("warps.yml", config); buildWarpList(config); for(Player p : Bukkit.getOnlinePlayers()) { sendMessage(p, "Wormhole closed! Global warp " + name + " deleted!"); } return true; } if(cmd.getName().equals("tp")) { Player target = getOnlinePlayer(args[0], player); if(target == null) { return true; } if(player.hasPermission("pppopp3.tpbypass")) { player.teleport(target); return true; } sendMessage(target, player.getDisplayName() + ChatColor.LIGHT_PURPLE + " has sent you a teleport request! type /tpa to accept, or type /tpd to deny it!"); sendMessage(player, "Yay! you've sent a teleport request to " + target.getDisplayName()); tpQueues.put(target.getName(), player.getName()); return true; } if(cmd.getName().equals("tphere")) { Player target = getOnlinePlayer(args[0], player); if(target == null) { return true; } target.teleport(player); return true; } return true; }
public boolean handleCommand(CommandSender sender, Command cmd, String label, String[] args){ if(cmd.getName().equals("warpdebug")) { for(String warpCategory : warpHandler.keySet()) { System.out.print(warpCategory + ":"); WarpList wl = warpHandler.get(warpCategory); for(String warp : wl.warps()) { System.out.print(warp); } } } if(cmd.getName().equals("pwlist")) { WarpList global = warpHandler.get("global"); if(global.size() > 0) { String gWarps = ChatColor.RED + "Global Warps: "; for(String warp : global.warps()) { gWarps += ChatColor.RED + warp + ChatColor.WHITE + ", "; } gWarps = gWarps.substring(0, gWarps.length() - 4); sendMessage(sender, "Heres a list of global warps!"); sender.sendMessage(gWarps); } if(sender instanceof Player) { Player player = (Player)sender; WarpList pWarps = warpHandler.get(player.getName()); if(pWarps.size() > 0) { String pWarp = ChatColor.RED + "Private Warps: "; for(String warp : pWarps.warps()) { pWarp += ChatColor.RED + warp + ChatColor.WHITE + ", "; } pWarp = pWarp.substring(0, pWarp.length() - 4); sendMessage(player, "Heres a list of your private warps!"); player.sendMessage(pWarp); } } return true; } Player player; if(sender instanceof Player) { player = (Player)sender; } else { sendMessage(sender, notPlayer); return true; } if(cmd.getName().equals("top")) { Location loc = player.getLocation(); int y = loc.getWorld().getHighestBlockYAt(loc); loc.setY(y); player.teleport(loc); return true; } if(cmd.getName().equals("spawn")) { World w = player.getWorld(); if(args.length > 0) { w = Bukkit.getWorld(args[0]); } w = Equestria.get().getParentWorld(w); Location l = spawns.get(w); if(l == null) { sendMessage(player, "Spawn not found!"); return true; } queueWarp(player, spawns.get(w)); return true; } if(cmd.getName().equals("setspawn")) { World w = player.getWorld(); if(w.getEnvironment() != Environment.NORMAL) { sendMessage(player, "The spawn is located in the overworld silly!"); return true; } Location l = player.getLocation(); ArrayList<String> loc = getListFromLoc(l); sendMessage(player, "Spawn set!"); World parent = Equestria.get().getParentWorld(w); spawns.put(parent, l); FileConfiguration config = getNamedConfig("warps.yml"); config.set("spawns." + parent.getName(), loc); saveNamedConfig("warps.yml", config); return true; } if(cmd.getName().equals("tpa")) { String target = tpQueues.get(player.getName()); if(target == null) { sendMessage(player, "Uh oh! no teleport request!"); return true; } Player targetP; targetP = Bukkit.getPlayerExact(target); if(targetP == null) { sendMessage(player, "Uh oh, no teleport request!"); return true; } tpQueues.remove(player.getName()); sendMessage(player, "Teleport request accepted!"); sendMessage(targetP, "Teleport request accepted!"); queueWarp(targetP, player.getLocation()); return true; } if(cmd.getName().equals("tpd")) { String requester = tpQueues.get(player.getName()); if(requester == null) { sendMessage(player, "Uh oh, no teleport request!"); return true; } Player targetP = Bukkit.getPlayerExact(requester); if(targetP != null) { sendMessage(targetP, "Teleport request denied from " + player.getDisplayName() + "!"); } sendMessage(player, "Teleport request denied!"); tpQueues.remove(player.getName()); return true; } if(cmd.getName().equals("home")) { Location home = homes.get(player.getName()); if(home == null) { sendMessage(player, "Uh oh, you have no home set! Try setting a home with /sethome!"); return true; } queueWarp(player, home); return true; } if(cmd.getName().equals("sethome")) { Pony pony = Ponyville.getPony(player); pony.setHomeWarp(player.getLocation()); pony.save(); homes.put(player.getName(), player.getLocation()); sendMessage(player, "Woo hoo! home set! Shall we throw a housewarming party?"); return true; } if(cmd.getName().equals("back")) { Location back = backs.get(player.getName()); if(back != null) { queueWarp(player, back); return true; } else { sendMessage(player, "Hey, silly! You havnt warped anywhere yet!"); return true; } } if(cmd.getName().equals("pwplayer")) { if(args.length < 2) { sendMessage(player, "Heres a list of pwplayer commands!"); sendMessage(player, "/pwplayer <player> list - This lists their warps!"); sendMessage(player, "/pwplayer <player> <warpname> - This teleports to one of their warps!"); sendMessage(player, "/pwplayer <player> offline - This teleports to the location they last logged off at!"); sendMessage(player, "/pwplayer <player> home - This teleports to their home location!"); sendMessage(player, "/pwplayer <player> back - This teleports to their back location!"); return true; } OfflinePlayer target = getOnlineOfflinePlayer(args[0], player); if(target == null) { return true; } Pony pony = Ponyville.getOfflinePony(target.getName()); if(args[1].equals("list")) { ArrayList<String> warps = new ArrayList<String>(); warps.addAll(pony.getAllNamedWarps().keySet()); Collections.sort(warps); if(warps.size() < 1) { sendMessage(player, "That player doesnt have any warps... YET!"); return true; } String warpstring = ""; for(String warp : warps) { warpstring += ChatColor.LIGHT_PURPLE + warp + ChatColor.WHITE + ", "; } warpstring = warpstring.substring(0, warpstring.length() - 4); sendMessage(player, "Heres a list of this players warps!: " + warpstring); return true; } else if(args[1].equals("offline")) { Location loc = pony.getOfflineWarp(); if(loc == null) { sendMessage(player, "Uh oh, that warp isnt set!"); return true; } player.teleport(loc); return true; } else if(args[1].equals("home")) { Location loc = pony.getHomeWarp(); if(loc == null) { sendMessage(player, "Uh oh, that warp isnt set!"); return true; } player.teleport(loc); return true; } else if(args[1].equals("back")) { Location loc = pony.getBackWarp(); if(loc == null) { sendMessage(player, "Uh oh, that warp isnt set!"); return true; } player.teleport(loc); return true; } else { Location loc = pony.getNamedWarp(args[1]); if(loc == null) { sendMessage(player, "Uh oh, that warp isnt set!"); return true; } player.teleport(loc); return true; } } if(args.length < 1) { sendMessage(player, notEnoughArgs); return true; } if(cmd.getName().equals("gw")) { WarpList global = warpHandler.get("global"); Location loc = global.getWarp(args[0]); if(loc == null) { sendMessage(player, "Uh oh, I couldnt find that warp!"); return true; } queueWarp(player, loc); return true; } if(cmd.getName().equals("pw")) { WarpList playerWarps = warpHandler.get(player.getName()); Location loc = playerWarps.getWarp(args[0]); if(loc == null) { sendMessage(player, "Uh oh, I couldnt find that warp!"); return true; } queueWarp(player, loc); return true; } if(cmd.getName().equals("pwdel")) { args[0] = args[0].toLowerCase(); Location w = warpHandler.get(player.getName()).getWarp(args[0]); if(w == null || args[0].equalsIgnoreCase("other")) { sendMessage(player, "Uh oh, I couldnt find that warp!"); return true; } Pony pony = Ponyville.getPony(player); pony.removeNamedWarp(args[0]); pony.save(); sendMessage(player, "Warp deleted!"); warpHandler.put(player.getName(), getPlayerWarps(player)); return true; } if(cmd.getName().equals("pwset")) { args[0] = args[0].toLowerCase(); if(args[0].equals("other")) { sendMessage(player, "Uh oh, sorry! thats a reserved name! please choose another warp name!"); return true; } Pony pony = Ponyville.getPony(player); int count = 1; for(String warp : pony.getAllNamedWarps().keySet()) { if(!warp.equals(args[0])) { count++; } } if(count > warpCount) { sendMessage(player, "You have too many warps! You need to delete one, or overwrite an existing one to set another warp!"); return true; } pony.setNamedWarp(args[0], player.getLocation()); pony.save(); sendMessage(player, "Wormhole opened! Warp " + args[0] + " set!"); warpHandler.put(player.getName(), getPlayerWarps(player)); return true; } if(cmd.getName().equals("gwset")) { String name = args[0].toLowerCase(); FileConfiguration config = getNamedConfig("warps.yml"); config.set("warps." + name, getListFromLoc(player.getLocation())); saveNamedConfig("warps.yml", config); buildWarpList(config); for(Player p : Bukkit.getOnlinePlayers()) { sendMessage(p, "Wormhole opened! New global warp set: " + name + "!"); } return true; } if(cmd.getName().equals("gwdel")) { String name = args[0].toLowerCase(); WarpList global = warpHandler.get("global"); Location loc = global.getWarp(name); if(loc == null) { sendMessage(player, "Uh oh! I couldnt find that warp!"); return true; } FileConfiguration config = getNamedConfig("warps.yml"); config.set("warps." + name, null); saveNamedConfig("warps.yml", config); buildWarpList(config); for(Player p : Bukkit.getOnlinePlayers()) { sendMessage(p, "Wormhole closed! Global warp " + name + " deleted!"); } return true; } if(cmd.getName().equals("tp")) { Player target = getOnlinePlayer(args[0], player); if(target == null) { return true; } if(player.hasPermission("pppopp3.tpbypass")) { player.teleport(target); return true; } sendMessage(target, player.getDisplayName() + ChatColor.LIGHT_PURPLE + " has sent you a teleport request! type /tpa to accept, or type /tpd to deny it!"); sendMessage(player, "Yay! you've sent a teleport request to " + target.getDisplayName()); tpQueues.put(target.getName(), player.getName()); return true; } if(cmd.getName().equals("tphere")) { Player target = getOnlinePlayer(args[0], player); if(target == null) { return true; } target.teleport(player); return true; } return true; }
diff --git a/x10.compiler/src/polyglot/types/Types.java b/x10.compiler/src/polyglot/types/Types.java index b0c4ef386..ca13b3121 100644 --- a/x10.compiler/src/polyglot/types/Types.java +++ b/x10.compiler/src/polyglot/types/Types.java @@ -1,1781 +1,1779 @@ package polyglot.types; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Collection; import java.util.HashSet; import polyglot.ast.Binary; import polyglot.ast.Binary.Operator; import polyglot.ast.Cast; import polyglot.ast.Expr; import polyglot.ast.Field; import polyglot.ast.FloatLit; import polyglot.ast.IntLit; import polyglot.ast.Lit; import polyglot.ast.NodeFactory; import polyglot.ast.Receiver; import polyglot.ast.Special; import polyglot.ast.TypeNode; import polyglot.ast.Unary; import polyglot.ast.Unary_c; import polyglot.ast.Variable; import polyglot.frontend.Job; import polyglot.main.Reporter; import polyglot.util.ErrorInfo; import polyglot.util.InternalCompilerError; import polyglot.util.Position; import polyglot.util.Transformation; import polyglot.util.TransformingList; import polyglot.visit.ContextVisitor; import x10.ast.HasZeroTest; import x10.ast.Here; import x10.ast.ParExpr; import x10.ast.SubtypeTest; import x10.constraint.XEQV; import x10.constraint.XFailure; import x10.constraint.XLit; import x10.constraint.XLocal; import x10.constraint.XTerm; import x10.constraint.XTerms; import x10.constraint.XVar; import x10.errors.Errors; import x10.errors.Errors.TypeIsMissingParameters; import x10.types.ConstrainedType; import x10.types.MacroType; import x10.types.MacroType_c; import x10.types.ParameterType; import x10.types.ParameterType.Variance; import x10.types.TypeParamSubst; import x10.types.X10ClassDef; import x10.types.X10ClassDef_c; import x10.types.X10ClassType; import x10.types.X10ConstructorInstance; import x10.types.X10Def; import x10.types.X10FieldDef; import x10.types.X10FieldInstance; import x10.types.MethodInstance; import x10.types.X10LocalDef; import x10.types.X10ParsedClassType; import x10.types.X10ParsedClassType_c; import x10.types.X10ProcedureDef; import x10.types.X10ProcedureInstance; import x10.types.X10ThisVar; import x10.types.XTypeTranslator; import x10.types.constraints.CConstraint; import x10.types.constraints.CTerms; import x10.types.constraints.SubtypeConstraint; import x10.types.constraints.TypeConstraint; import x10.types.constraints.XConstrainedTerm; import x10.types.matcher.Matcher; import x10.types.matcher.Subst; import x10.types.matcher.X10FieldMatcher; import x10.X10CompilerOptions; public class Types { public static <T> T get(Ref<T> ref) { return ref != null ? ref.get() : null; } public static <T> T getCached(Ref<T> ref) { return ref != null ? ref.getCached() : null; } @SuppressWarnings("unchecked") // Special-casing TypeObject public static <T> Ref<T> ref(T v) { if (v instanceof TypeObject) return (Ref<T>) new Ref_c((TypeObject) v); else if (v == null) return null; else { Ref<T> ref = lazyRef(v, new Runnable() { public void run() { } }); ref.update(v); return ref; } } /** Create a lazy reference to a type object, with an initial value. * @param defaultValue initial value * @param resolver goal used to bring the reference up-to-date * * ### resolver should be a map */ public static <T> LazyRef<T> lazyRef(T defaultValue) { return new LazyRef_c<T>(defaultValue); } public static <T> LazyRef<T> lazyRef(T defaultValue, Runnable resolver) { return new LazyRef_c<T>(defaultValue, resolver); } public static Type addBinding(Type t, XTerm t1, XTerm t2) { //assert (! (t instanceof UnknownType)); CConstraint c = Types.xclause(t); c = c == null ? new CConstraint() :c.copy(); c.addBinding(t1, t2); return Types.xclause(Types.baseType(t), c); } public static Type addBinding(Type t, XTerm t1, XConstrainedTerm t2) { assert (! (t instanceof UnknownType)); CConstraint c = new CConstraint(); c.addBinding(t1, t2); return Types.xclause(t, c); } public static Type addSelfBinding(Type t, XTerm t1) { assert (! (t instanceof UnknownType)); CConstraint c = Types.xclause(t); c = c == null ? new CConstraint() :c.copy(); c.addSelfBinding(t1); return Types.xclause(Types.baseType(t), c); } /** * Add t1 != t2 to the type t. * The type returned may be inconsistent. * @param t * @param t1 * @param t2 * @return */ public static Type addDisBinding(Type t, XTerm t1, XTerm t2) { assert (! (t instanceof UnknownType)); CConstraint c = Types.xclause(t); c = c == null ? new CConstraint() :c.copy(); c.addDisBinding(t1, t2); return Types.xclause(Types.baseType(t), c); } /** * Add c to t. Note: The type returned may have an inconsistent * constraint. * @param t * @param t1 * @param t2 * @return */ public static Type addConstraint(Type t, CConstraint xc) { CConstraint c = Types.tryAddingConstraint(t, xc); return Types.xclause(Types.baseType(t), c); } public static Type addTerm(Type t, XTerm term) { try { CConstraint c = Types.xclause(t); c = c == null ? new CConstraint() :c.copy(); c.addTerm(term); return Types.xclause(Types.baseType(t), c); } catch (XFailure f) { throw new InternalCompilerError("Cannot add term " + term + " to " + t + ".", f); } } public static void checkVariance(TypeNode t, ParameterType.Variance variance, Job errs) { checkVariance(t.type(),variance,errs,t.position()); } public static void checkVariance(Type t, ParameterType.Variance variance, Job errs, Position pos) { Type base = null; if (t instanceof ParameterType) { ParameterType pt = (ParameterType) t; ParameterType.Variance var = pt.getVariance(); if (var==variance || var==ParameterType.Variance.INVARIANT) { // ok } else { Errors.issue(errs, new Errors.IllegalVarianceParameter(var, variance, pos)); // todo: t.position() is incorrect (see XTENLANG-1439) } } else if (t instanceof X10ParsedClassType_c) { X10ParsedClassType_c pt = (X10ParsedClassType_c) t; List<Type> args = pt.typeArguments(); if (args == null) args = Collections.<Type>emptyList(); X10ClassDef def = (X10ClassDef) pt.def(); final List<ParameterType.Variance> variances = def.variances(); for (int i=0; i<Math.min(args.size(), variances.size()); i++) { Type arg = args.get(i); ParameterType.Variance var = variances.get(i); checkVariance(arg, variance.mult(var), errs, pos); } } else if (t instanceof ConstrainedType) { ConstrainedType ct = (ConstrainedType) t; base = get(ct.baseType()); } /*else if (t instanceof AnnotatedType_c) { AnnotatedType_c at = (AnnotatedType_c) t; base = at.baseType(); }*/ else if (t instanceof MacroType_c) { MacroType mt = (MacroType) t; base = mt.definedType(); } if (base!=null) checkVariance(base,variance,errs,pos); } public static Type baseType(Type t) { while (true) { if (t instanceof MacroType) { t = ((MacroType) t).definedType(); continue; } if (t instanceof ConstrainedType) { t = get(((ConstrainedType) t).baseType()); continue; } break; } return t; } public static ConstrainedType constrainedType(Type base, CConstraint c) { return new ConstrainedType((TypeSystem) base.typeSystem(), base.position(), ref(base), ref(c)); } public static boolean consistent(Type t) { if (t instanceof MacroType) { MacroType mt = (MacroType) t; return consistent(mt.definedType()); } if (t instanceof ConstrainedType) { ConstrainedType ct = (ConstrainedType) t; return ct.xclause().consistent(); } if (t instanceof X10ParsedClassType) { X10ParsedClassType ct = (X10ParsedClassType) t; return ct.getXClause().consistent(); } return true; // clause is null. } public static boolean eitherIsDependent(Type t1, Type t2) { return Types.isDependentOrDependentPath(t1) || Types.isDependentOrDependentPath(t2); } public static boolean entails(Type t, XTerm t1, XTerm t2) { CConstraint c = Types.realX(t); if (c==null) c = new CConstraint(); return c.entails(t1, t2); } public static boolean disEntails(Type t, XTerm t1, XTerm t2) { CConstraint c = Types.realX(t); if (c==null) c = new CConstraint(); return c.disEntails(t1, t2); } public static boolean disEntailsSelf(Type t, XTerm t2) { CConstraint c = Types.realX(t); if (c==null) c = new CConstraint(); return c.disEntails(c.self(), t2); } public static Type arrayBaseType(Type t) { t = baseType(t); if (t instanceof X10ClassType) { X10ClassType ct = (X10ClassType) t; TypeSystem ts = (TypeSystem) t.typeSystem(); ClassType a = (ClassType) ts.Array(); ClassType da = (ClassType) ts.Array(); if (ct.def() == a.def() || ct.def() == da.def()) return ct.typeArguments().get(0); else arrayBaseType(ct.superClass()); } return null; } public static SemanticException error(Type t) { t = baseType(t); if (t instanceof X10ClassType) { X10ClassType ct = (X10ClassType) t; return ct.error(); } return null; } /** * Returns a new constraint that allows null. * E.g., given "{self.home==here, self!=null}" it returns "{self.home==here}" * @param c a constraint "c" that doesn't allow null * @return a new constraint with all the constraints in "c" except {self!=null} * * TODO: this implementation is wrong, see XTENLANG-1380 */ // public static CConstraint allowNull(CConstraint c) { // final XVar self = c.self(); // CConstraint res = new CConstraint(self); // assert !res.disEntails(self,XTerms.NULL); // for (XTerm term : c.constraints()) { // CConstraint copy = res.copy(); // try { // copy.addTerm(term); // } catch (XFailure xFailure) { // assert false : xFailure; // } // if (!copy.disEntails(self,XTerms.NULL)) // res = copy; // } // return res; // } public static void checkMissingParameters(Receiver receiver) throws SemanticException { Type xt = receiver.type(); checkMissingParameters(xt,receiver.position()); } public static void checkMissingParameters(Type xt, Position pos) throws SemanticException { if (xt == null) return; xt = baseType(xt); if (xt instanceof X10ParsedClassType) { X10ParsedClassType xt1 = (X10ParsedClassType) xt; final X10ClassDef classDef = (X10ClassDef) xt1.def(); if (xt1.isMissingTypeArguments()) { List<ParameterType> expectedArgs = classDef.typeParameters(); throw new Errors.TypeIsMissingParameters(xt, expectedArgs, pos); } else { // todo check the TypeConstraint of the class invariant is satisfied } } } public static Type arrayElementType(Type t) { t = baseType(t); TypeSystem xt = (TypeSystem) t.typeSystem(); if (xt.isX10Array(t) || xt.isX10DistArray(t)) { if (t instanceof X10ParsedClassType) { Type result = ((X10ParsedClassType) t).typeArguments().get(0); return result; } } return null; } public static boolean contextKnowsType(Receiver r) { if (r instanceof Variable) return ((Variable) r).flags().isFinal(); if (r instanceof Field) return contextKnowsType( ((Field) r).target()); if (r instanceof Special || r instanceof Here || r instanceof Lit) return true; if (r instanceof ParExpr) return contextKnowsType(((ParExpr) r).expr()); if (r instanceof Cast) return contextKnowsType(((Cast) r).expr()); return false; } public static boolean areConsistent(Type t1, Type t2) { if ( Types.isConstrained(t1) && Types.isConstrained(t2)) return Types.tryAddingConstraint(t1, Types.xclause(t2)).consistent(); return true; } public static X10ParsedClassType instantiate(Type t, Type... typeArg) { if (t instanceof X10ParsedClassType) { X10ParsedClassType ct = (X10ParsedClassType) t; return ct.typeArguments(Arrays.asList(typeArg)); } else { throw new InternalCompilerError("Cannot instantiate non-class " + t); } } public static X10ParsedClassType instantiate(Type t, Ref<? extends Type> typeArg) { // TODO: should not deref now, since could be called by class loader return instantiate(t, get(typeArg)); } public static X10ClassDef_c getDef(Type t) { if (t==null) return null; // GOLDEN if (t.typeSystem().hasUnknown(t)) { return null; } return (X10ClassDef_c) ((X10ParsedClassType_c)baseType(t)).def(); } public static boolean isConstrained(Type t) { /*if (t instanceof AnnotatedType) { AnnotatedType at = (AnnotatedType) t; return isConstrained(at.baseType()); }*/ if (t instanceof MacroType) { MacroType mt = (MacroType) t; return isConstrained(mt.definedType()); } if (t instanceof ConstrainedType) { return true; } return false; } public static boolean isClass(Type t) { return (t instanceof X10ClassType); } public static Type instantiateSelf(XTerm t, Type type) { //assert (! (t instanceof UnknownType)); CConstraint c = Types.xclause(type); if (! ((c==null) || c.valid())) { CConstraint env = c = c.copy().instantiateSelf(t); if (false && ! c.consistent()) { throw new InternalCompilerError("X10TypeMixin: Instantiating self on " + type + " with " + t + " is inconsistent."); } return Types.xclause(baseType(type), c); } return type; } public static boolean isDependentOrDependentPath(Type t) { return isConstrained(t); } public static Type getParameterType(Type theType, int i) { Type b = baseType(theType); if (b instanceof X10ClassType) { X10ClassType ct = (X10ClassType) b; if (ct.typeArguments() != null && i < ct.typeArguments().size()) { return ct.typeArguments().get(i); } } return null; } /** * Returns the var that is thisvar of all the terms in {t1,t2} that have a thisvar. * If none do, return null. Else throw a SemanticError. * @param t1 * @param t2 * @return * @throws SemanticError */ public static XVar getThisVar(Type t1, Type t2) throws XFailure { XVar thisVar = t1 == null ? null : ((X10ThisVar) t1).thisVar(); if (thisVar == null) return t2==null ? null : ((X10ThisVar) t2).thisVar(); if (t2 != null && ! thisVar.equals(((X10ThisVar) t2).thisVar())) throw new XFailure("Inconsistent this vars " + thisVar + " and " + ((X10ThisVar) t2).thisVar()); return thisVar; } public static XVar getThisVar(CConstraint t1, CConstraint t2) throws XFailure { XVar thisVar = t1 == null ? null : t1.thisVar(); if (thisVar == null) return t2==null ? null : t2.thisVar(); if (t2 != null && ! thisVar.equals( t2.thisVar())) throw new XFailure("Inconsistent this vars " + thisVar + " and " + ((X10ThisVar) t2).thisVar()); return thisVar; } public static XVar getThisVar(List<Type> typeArgs) throws XFailure { XVar thisVar = null; if (typeArgs != null) for (Type type : typeArgs) { if (type instanceof X10ThisVar) { X10ThisVar xtype = (X10ThisVar)type; XVar o = xtype.thisVar(); if (thisVar == null) { thisVar = o; } else { if (o != null && !thisVar.equals(o)) throw new XFailure("Inconsistent thisVars in " + typeArgs + "; cannot instantiate "); } } } return thisVar; } public static XTerm getRegionLowerBound(Type type) { return null; } public static XTerm getRegionUpperBound(Type type) { return null; } public static boolean hasVar(Type t, XVar x) { if (t instanceof ConstrainedType) { ConstrainedType ct = (ConstrainedType) t; Type b = baseType(t); CConstraint c = Types.xclause(t); if ( hasVar(b, x)) return true; for (XTerm term : c.constraints()) { if (term.hasVar(x)) return true; } } if (t instanceof MacroType) { MacroType pt = (MacroType) t; return hasVar(pt.definedType(), x); } return false; } /** * Does t imply {self!=null}? */ public static boolean isNonNull(Type t) { return disEntails(t, Types.self(t), XTerms.NULL); } public static boolean isNoThisAccess(X10ProcedureDef def,TypeSystem ts) { return isDefAnnotated(def,ts,"x10.compiler.NoThisAccess"); } public static boolean isNonEscaping(X10ProcedureDef def,TypeSystem ts) { return isDefAnnotated(def,ts,"x10.compiler.NonEscaping"); } public static boolean isDefAnnotated(X10Def def,TypeSystem ts, String name) { try { Type at = ts.systemResolver().findOne(QName.make(name)); return !def.annotationsMatching(at).isEmpty(); } catch (SemanticException e) { return false; } } // this is an under-approximation (it is always safe to return false, i.e., the user will just get more errors). In the future we will improve the precision so more types will have zero. public static boolean isHaszero(Type t, Context xc) { TypeSystem ts = xc.typeSystem(); XLit zeroLit = null; // see Lit_c.constantValue() in its decendants if (t.isBoolean()) { zeroLit = XTerms.FALSE; } else if (ts.isChar(t)) { zeroLit = XTerms.ZERO_CHAR; } else if (ts.isInt(t) || ts.isByte(t) || ts.isUByte(t) || ts.isShort(t) || ts.isUShort(t)) { zeroLit = XTerms.ZERO_INT; } else if (ts.isUInt(t) || ts.isULong(t) || ts.isLong(t)) { zeroLit = XTerms.ZERO_LONG; } else if (ts.isFloat(t)) { zeroLit = XTerms.ZERO_FLOAT; } else if (ts.isDouble(t)) { zeroLit = XTerms.ZERO_DOUBLE; } else if (ts.isObjectOrInterfaceType(t, xc)) { if (Types.permitsNull(t)) return true; //zeroLit = XTerms.NULL; } else if (ts.isParameterType(t)) { // we have some type "T" which is a type parameter. Does it have a zero value? // So, type bounds (e.g., T<:Int) do not help, because Int{self!=0}<:Int // Similarly, Int<:T doesn't help, because Int<:Any{self!=null} - // However, T==Int does help - if (isConstrained(t)) return false; // if we have constraints on the type parameter, e.g., T{self!=null}, then we give up and return false. + // However, T==Int does help, and so does an explicit T hasZero TypeConstraint typeConst = xc.currentTypeConstraint(); List<SubtypeConstraint> env = typeConst.terms(); for (SubtypeConstraint sc : env) { if (sc.isEqualityConstraint()) { Type other = null; final Type sub = sc.subtype(); final Type sup = sc.supertype(); if (ts.typeEquals(t, sub,xc)) { if (!ts.isParameterType(sub)) other = sub; if (!ts.isParameterType(sup)) other = sup; } if (other!=null && isHaszero(other,xc)) // careful of infinite recursion when calling isHaszero // We cannot have infinite recursion because other is not a ParameterType // (we can have that T==U, U==Int. but then typeEquals(T,Int,xc) should return true) return true; // T is equal to another type that has zero } else if (sc.isSubtypeConstraint()) { // doesn't help } else { assert sc.isHaszero(); if (ts.typeEquals(t,sc.subtype(),xc)) { return true; } } } } else if (Types.isX10Struct(t)) { if (!(t instanceof ContainerType)) return false; ContainerType structType = (ContainerType) t; // user-defined structs (such as Complex) can have zero iff // 1) They do not have a class invariant // 2) all their fields have zero // todo: When ConstrainedType_c.fields() is fixed (it should add the constraint to the fields), then I can remove this "if" if (isConstrained(t)) return false; // currently I don't handle constrained user-defined types, i.e., Complex{re!=3.0} doesn't haszero // far to do: if t is constrained, then a constraint with all fields=zero entails t's constraint // e.g., Complex and Complex{re!=3.0} haszero, // Complex{re!=0.0} and Complex{re==3.0} doesn't haszero final Type base = baseType(t); if (!(base instanceof X10ParsedClassType_c)) return false; X10ParsedClassType_c xlass = (X10ParsedClassType_c) base; final ClassDef def = xlass.def(); if (!(def instanceof X10ClassDef_c)) return false; X10ClassDef_c x10ClassDef = (X10ClassDef_c) def; // do we have an classInvariant? // todo: class invariant are not treated correctly: // X10ClassDecl_c.classInvariant is fine, // but X10ClassDef_c.classInvariant is wrong final Ref<CConstraint> ref = x10ClassDef.classInvariant(); if (ref!=null && ref.get().constraints().size()>0) return false; // the struct has a class invariant (so the zero value might not satisfy it) // We use ts.structHaszero to prevent infinite recursion such as in the case of: // struct U(u:U) {} final Boolean res = ts.structHaszero(x10ClassDef); if (res!=null) return res; // it is true for type-checking: S[S[Int]] // struct S[T] {T haszero} {val t:T = Zero.get[T](); } ts.structHaszero().put(x10ClassDef,Boolean.TRUE); // make sure all the fields and properties haszero for (FieldInstance field : structType.fields()) { if (field.flags().isStatic()) { continue; } if (!isHaszero(field.type(),xc)) { ts.structHaszero().put(x10ClassDef,Boolean.FALSE); return false; } } return true; } - if (zeroLit==null) return false; - if (ts.isParameterType(t)) { + if (ts.isParameterType(t)) { // FIXME: why is this code duplicated? // we have some type "T" which is a type parameter. Does it have a zero value? // So, type bounds (e.g., T<:Int) do not help, because Int{self!=0}<:Int // Similarly, Int<:T doesn't help, because Int<:Any{self!=null} - // However, T==Int does help - if (isConstrained(t)) return false; // if we have constraints on the type parameter, e.g., T{self!=null}, then we give up and return false. + // However, T==Int does help, and so does an explicit T hasZero TypeConstraint typeConst = xc.currentTypeConstraint(); List<SubtypeConstraint> env = typeConst.terms(); for (SubtypeConstraint sc : env) { if (sc.isEqualityConstraint()) { Type other = null; final Type sub = sc.subtype(); final Type sup = sc.supertype(); if (ts.typeEquals(t, sub,xc)) { if (!ts.isParameterType(sub)) other = sub; if (!ts.isParameterType(sup)) other = sup; } if (other!=null) return isHaszero(other,xc); } else if (sc.isSubtypeConstraint()) { // doesn't help } else { assert sc.isHaszero(); if (ts.typeEquals(t,sc.subtype(),xc)) { return true; } } } } + if (zeroLit==null) return false; if (!isConstrained(t)) return true; final CConstraint constraint = Types.xclause(t); final CConstraint zeroCons = new CConstraint(constraint.self()); // make sure the zeroLit is not in the constraint zeroCons.addSelfBinding(zeroLit); return zeroCons.entails(constraint); } public static Expr getZeroVal(TypeNode typeNode, Position p, ContextVisitor tc) { // see X10FieldDecl_c.typeCheck try { Type t = typeNode.type(); TypeSystem ts = tc.typeSystem(); NodeFactory nf = tc.nodeFactory(); Context context = tc.context(); if (!isHaszero(t,context)) return null; Expr e = null; if (t.isBoolean()) { e = nf.BooleanLit(p, false); } else if (ts.isShort(t)) { e = nf.IntLit(p, IntLit.SHORT, 0L); } else if (ts.isUShort(t)) { e = nf.IntLit(p, IntLit.USHORT, 0L); } else if (ts.isByte(t)) { e = nf.IntLit(p, IntLit.BYTE, 0L); } else if (ts.isUByte(t)) { e = nf.IntLit(p, IntLit.UBYTE, 0L); } else if (ts.isChar(t)) { e = nf.CharLit(p, '\0'); } else if (ts.isInt(t)) { e = nf.IntLit(p, IntLit.INT, 0L); } else if (ts.isUInt(t)) { e = nf.IntLit(p, IntLit.UINT, 0L); } else if (ts.isLong(t)) { e = nf.IntLit(p, IntLit.LONG, 0L); } else if (ts.isULong(t)) { e = nf.IntLit(p, IntLit.ULONG, 0L); } else if (ts.isFloat(t)) { e = nf.FloatLit(p, FloatLit.FLOAT, 0.0); } else if (ts.isDouble(t)) { e = nf.FloatLit(p, FloatLit.DOUBLE, 0.0); } else if (ts.isObjectOrInterfaceType(t, context)) { e = nf.NullLit(p); } else if (ts.isParameterType(t) || Types.isX10Struct(t)) { TypeNode receiver = nf.CanonicalTypeNode(p, ts.systemResolver().findOne(QName.make("x10.lang.Zero"))); //receiver = (TypeNode) receiver.del().typeCheck(tc).checkConstants(tc); e = nf.X10Call(p,receiver, nf.Id(p,"get"),Collections.singletonList(typeNode), Collections.<Expr>emptyList()); } if (e != null) { e = (Expr) e.del().typeCheck(tc).checkConstants(tc); if (ts.isSubtype(e.type(), t, context)) { // suppose the field is "var i:Int{self!=0}", then you cannot create an initializer which is 0! return e; } } return null; } catch (Throwable e1) { throw new InternalCompilerError(e1); } } public static List<Type> expandTypes(List<Type> formals, TypeSystem xts) { List<Type> result = new ArrayList<Type>(); for (Type f : formals) { result.add(xts.expandMacros(f)); } return result; } public static <PI extends X10ProcedureInstance<?>> boolean isStatic(PI me) { if (me instanceof ConstructorInstance) return true; if (me instanceof MethodInstance) { MethodInstance mi = (MethodInstance) me; return mi.flags().isStatic(); } if (me instanceof MacroType) { MacroType mt = (MacroType) me; return mt.container()==null || mt.flags().isStatic(); } return false; } public static ProcedureInstance<?> getOrigMI(ProcedureInstance<?> xp) { if (xp instanceof MethodInstance) return ((MethodInstance) xp).origMI(); if (xp instanceof ConstructorInstance) return ((ConstructorInstance) xp).origMI(); return xp; } public static Type instantiateTypeParametersExplicitly(Type t) { /*if (t instanceof AnnotatedType) { AnnotatedType at = (AnnotatedType) t; Type bt = at.baseType(); Type ibt = instantiateTypeParametersExplicitly(bt); if (ibt != bt) return at.baseType(ibt); return at; } else*/ if (t instanceof ConstrainedType) { ConstrainedType ct = (ConstrainedType) t; Type bt = get(ct.baseType()); Type ibt = instantiateTypeParametersExplicitly(bt); if (ibt != bt) ct = ct.baseType(ref(ibt)); return ct; } else if (t instanceof X10ParsedClassType) { X10ParsedClassType pct = (X10ParsedClassType) t; pct = pct.instantiateTypeParametersExplicitly(); List<Type> typeArguments = pct.typeArguments(); List<Type> newTypeArguments = typeArguments; if (typeArguments != null) { List<Type> res = new ArrayList<Type>(); for (Type a : typeArguments) { Type ia = instantiateTypeParametersExplicitly(a); if (ia != a) newTypeArguments = res; res.add(ia); } } pct = pct.typeArguments(newTypeArguments); return pct; } else { return t; } } /** * Return the type Array[type]{self.rail==true,self.size==size}. * @param type * @param pos * @return */ public static Type makeArrayRailOf(Type type, int size, Position pos) { Type t = makeArrayRailOf(type, pos); assert (t.isClass()); TypeSystem ts = type.typeSystem(); CConstraint c = Types.xclause(t); FieldInstance sizeField = t.toClass().fieldNamed(Name.make("size")); if (sizeField == null) throw new InternalCompilerError("Could not find size field of " + t, pos); try { XTerm selfSize = ts.xtypeTranslator().translate(c.self(), sizeField); XLit sizeLiteral = XTypeTranslator.translate(size); c.addBinding(selfSize, sizeLiteral); Type result = Types.xclause(t, c); return result; } catch (InternalCompilerError z) { throw new InternalCompilerError("Could not create Array[T]{self.rail==true,self.size==size}"); } } /** * Return the type Array[type]{self.rank==1,self.rect==true,self.zeroBased==true,self.rail==true}. * @param type * @param pos * @return */ public static Type makeArrayRailOf(Type type, Position pos) { TypeSystem ts = type.typeSystem(); X10ClassType t = ts.Array(type); CConstraint c = new CConstraint(); FieldInstance regionField = t.fieldNamed(Name.make("region")); if (regionField == null) throw new InternalCompilerError("Could not find region field of " + t, pos); FieldInstance rankField = t.fieldNamed(Name.make("rank")); if (rankField == null) throw new InternalCompilerError("Could not find rank field of " + t, pos); FieldInstance rectField = t.fieldNamed(Name.make("rect")); if (rectField == null) throw new InternalCompilerError("Could not find rect field of " + t, pos); FieldInstance zeroBasedField = t.fieldNamed(Name.make("zeroBased")); if (zeroBasedField == null) throw new InternalCompilerError("Could not find zeroBased field of " + t, pos); FieldInstance railField = t.fieldNamed(Name.make("rail")); if (railField == null) throw new InternalCompilerError("Could not find rail field of " + t, pos); XTypeTranslator xt = ts.xtypeTranslator(); XVar self = c.self(); XTerm selfRank = xt.translate(self, rankField); XTerm selfRect = xt.translate(self, rectField); XTerm selfZeroBased = xt.translate(self, zeroBasedField); XTerm selfRail = xt.translate(self, railField); XLit rankLiteral = XTerms.makeLit(1); c.addBinding(selfRank, rankLiteral); c.addBinding(selfRect, XTerms.TRUE); c.addBinding(selfZeroBased, XTerms.TRUE); c.addBinding(selfRail, XTerms.TRUE); return Types.xclause(t, c); } public static TypeConstraint parameterBounds(Type t) { if (t instanceof ParameterType) { } else if (t instanceof ConstrainedType) { ConstrainedType ct = (ConstrainedType) t; TypeConstraint bounds = parameterBounds(get(ct.baseType())); if (bounds == null) assert bounds != null; return bounds; } else if (t instanceof X10ClassType) { X10ClassType ct = (X10ClassType) t; TypeConstraint c = get(ct.x10Def().typeBounds()); if (c != null) return TypeParamSubst.reinstantiateTypeConstraint(ct, c); } else if (t instanceof MacroType) { MacroType mt = (MacroType) t; TypeConstraint c = parameterBounds(mt.definedType()); TypeConstraint w = mt.typeGuard(); if (w != null) { c = (TypeConstraint) c.copy(); c.addIn(w); } return c; } return new TypeConstraint(); } /** * Returns the real constraint for the type t -- the specified constraint * (if any), and the root clause of the base type. * * <p>If t has a constraint clause (is a ConstrainedType) * then the returned constraint will have the same * self var as t's clause. * @param t - the type whose real clause is needed * @return -- always a non-null constraint. May be inconsistent. */ public static CConstraint realX(Type t) { if (t instanceof ParameterType) { return new CConstraint(); } else if (t instanceof ConstrainedType) { return ((ConstrainedType) t).getRealXClause().copy(); } else if (t instanceof X10ClassType) { X10ClassType ct = (X10ClassType) t; CConstraint c = ct.x10Def().getRealClause().copy(); return TypeParamSubst.reinstantiateConstraint(ct, c); } else if (t instanceof MacroType) { MacroType mt = (MacroType) t; CConstraint c = realX(mt.definedType()); CConstraint w = mt.guard(); if (w != null && ! w.valid()) { // c = c.copy(); c.addIn(w); // c may have become inconsistent. } return c; } return new CConstraint(); } /** * Is t an X10 struct? * @param t * @return */ public static boolean isX10Struct(Type t) { t = baseType(t); if (t instanceof X10ClassType) { return ((X10ClassType) t).isX10Struct(); } return false; } /** * If x is a class type, return struct x. Else return x. * @param x * @return */ public static Type makeX10Struct(Type t) { if (t instanceof X10ClassType) return ((X10ClassType) t).makeX10Struct(); return t; } public static Type processFlags(Flags f, Type x) { if (f==null) return x; if (f.isStruct()) { x = makeX10Struct(x); } return x; } public static X10ParsedClassType_c myBaseType(Type t) { Type basetype = baseType(t); // it can be a ParameterType if (basetype instanceof X10ParsedClassType_c) return (X10ParsedClassType_c) basetype; return null; } public static void setInconsistent(Type t) { if (t instanceof MacroType) { MacroType mt = (MacroType) t; setInconsistent(mt.definedType()); } if (t instanceof ConstrainedType) { ConstrainedType ct = (ConstrainedType) t; CConstraint c = get(ct.constraint()); c.setInconsistent(); return; } } public static XVar selfVar(ConstrainedType thisType) { return selfVar(thisType.constraint().get()); } public static XVar selfVar(CConstraint c) { if (c == null) return null; return c.self(); } public static XVar selfVarBinding(Type thisType) { CConstraint c = Types.xclause(thisType); // Should this be realX(thisType) ??? - Bowen return selfVarBinding(c); } public static XVar selfVarBinding(CConstraint c) { if (c == null) return null; return c.bindingForVar(c.self()); } public static XTerm selfBinding(Type thisType) { CConstraint c = realX(thisType); return selfBinding(c); } public static XTerm selfBinding(CConstraint c) { if (c == null) return null; return c.bindingForVar(c.self()); } public static Type setSelfVar(Type t, XVar v) throws SemanticException { CConstraint c = Types.xclause(t); if (c == null) { c = new CConstraint(); } else { c = c.copy(); } c.addSelfBinding(v); return Types.xclause(baseType(t), c); } public static Type setThisVar(Type t, XVar v) throws SemanticException { CConstraint c = Types.xclause(t); if (c == null) { c = new CConstraint(); } else { c = c.copy(); } c.setThisVar(v); return Types.xclause(baseType(t), c); } /** * If the type constrains the given property to * a particular value, then return that value, otherwise * return null * @param name -- the name of the property. * @return null if there is no value associated with the property in the type. */ public static XTerm propVal(Type t, Name name) { CConstraint c = Types.xclause(t); if (c == null) return null; return c.bindingForSelfField(Types.getProperty(t, name).def()); } public static Type promote(Unary.Operator op, JavaPrimitiveType t) throws SemanticException { TypeSystem ts = (TypeSystem) t.typeSystem(); Type pt = ts.promote(t); return Types.xclause(baseType(pt), promoteClause(ts, op, Types.xclause(t))); } public static CConstraint promoteClause(TypeSystem ts, polyglot.ast.Unary.Operator op, CConstraint c) { if (c == null) return null; return ts.xtypeTranslator().unaryOp(op, c); } public static Type promote(Binary.Operator op, JavaPrimitiveType t1, JavaPrimitiveType t2) throws SemanticException { TypeSystem ts = (TypeSystem) t1.typeSystem(); Type pt = ts.promote(t1, t2); return Types.xclause(baseType(pt), promoteClause(ts, op, Types.xclause(t1), Types.xclause(t2))); } public static CConstraint promoteClause(TypeSystem ts, Operator op, CConstraint c1, CConstraint c2) { if (c1 == null || c2 == null) return null; return ts.xtypeTranslator().binaryOp(op, c1, c2); } public static List<FieldInstance> properties(Type t) { t = baseType(t); if (t instanceof X10ClassType) { X10ClassType ct = (X10ClassType) t; return ct.properties(); } return Collections.<FieldInstance>emptyList(); } public static boolean isX10Array(Type t) { TypeSystem ts = (TypeSystem) t.typeSystem(); Type tt = baseType(t); Type at = baseType(ts.Array()); if (tt instanceof ClassType && at instanceof ClassType) { ClassDef tdef = ((ClassType) tt).def(); ClassDef adef = ((ClassType) at).def(); return ts.descendsFrom(tdef, adef); } return false; } public static boolean isX10DistArray(Type t) { TypeSystem ts = (TypeSystem) t.typeSystem(); Type tt = baseType(t); Type at = baseType(ts.DistArray()); if (tt instanceof ClassType && at instanceof ClassType) { ClassDef tdef = ((ClassType) tt).def(); ClassDef adef = ((ClassType) at).def(); return ts.descendsFrom(tdef, adef); } return false; } public static XVar self(Type t) { CConstraint c = realX(t); if (c == null) return null; return selfVar(c); } /** * Are instances of this type accessible from anywhere? * @param t * @return public static boolean isGlobalType(Type t) { if (isX10Struct(t)) return true; return false; } */ /** * We need to ensure that there is a symbolic name for this type. i.e. self is bound to some variable. * So if it is not, please create a new EQV and bind self to it. * * This is done in particular before getting field instances of this type. This ensures * that the field instance can be computed accurately, that is the constraint * self = t.f can be added to it, where t is the selfBinding for the container (i.e. this). * */ /*public static Type ensureSelfBound(Type t) { if (t instanceof ConstrainedType) { ((ConstrainedType) t).ensureSelfBound(); return t; } XVar v = selfVarBinding(t); if (v !=null) return t; try { t = setSelfVar(t,XTerms.makeUQV()); } catch (SemanticException z) { } if (selfVarBinding(t) == null) assert selfVarBinding(t) != null; return t; } */ public static boolean isUninitializedField(X10FieldDef def,TypeSystem ts) { return isDefAnnotated(def,ts,"x10.compiler.Uninitialized"); } public static boolean isSuppressTransientErrorField(X10FieldDef def,TypeSystem ts) { return isDefAnnotated(def,ts,"x10.compiler.SuppressTransientError"); } public static boolean permitsNull(Type t) { if (isX10Struct(t)) return false; if (disEntailsSelf(t, XTerms.NULL)) return false; TypeSystem ts = ((TypeSystem) t.typeSystem()); if (ts.isParameterType(t)) { return false; // a parameter type might be instantiated with a struct that doesn't permit null. } return true; } public static Type meetTypes(TypeSystem xts, Type t1, Type t2, Context context) { if (xts.isSubtype(t1, t2, context)) return t1; if (xts.isSubtype(t2, t1, context)) return t2; return null; } public static boolean moreSpecificImpl(Type ct, ProcedureInstance<?> xp1, ProcedureInstance<?> xp2, Context context) { TypeSystem ts = (TypeSystem) xp1.typeSystem(); Type ct1 = xp2 instanceof MemberInstance<?> ? ((MemberInstance<?>) xp1).container() : null; Type ct2 = xp2 instanceof MemberInstance<?> ? ((MemberInstance<?>) xp2).container() : null; Type t1 = ct1; Type t2 = ct2; if (t1 != null && t2 != null) { t1 = baseType(t1); t2 = baseType(t2); } boolean descends = t1 != null && t2 != null && ts.descendsFrom(ts.classDefOf(t1), ts.classDefOf(t2)); Flags flags1 = xp1 instanceof MemberInstance<?> ? ((MemberInstance<?>) xp1).flags() : Flags.NONE; Flags flags2 = xp2 instanceof MemberInstance<?> ? ((MemberInstance<?>) xp2).flags() : Flags.NONE; // A static method in a subclass is always more specific. // Note: this rule differs from Java but avoids an anomaly with conversion methods. if (descends && ! ts.hasSameClassDef(t1, t2) && flags1.isStatic() && flags2.isStatic()) { return true; } Reporter reporter = ts.extensionInfo().getOptions().reporter; boolean java = javaStyleMoreSpecificMethod(xp1, xp2, (Context) context, ct1, t1, t2,descends); if (reporter.should_report(Reporter.specificity, 1)) { boolean old = oldStyleMoreSpecificMethod(xp1, xp2, (Context) context, ts, ct1, t1, t2, descends); if (java != old) { String msg = Types.MORE_SPECIFIC_WARNING + ((java && ! old) ? "p1 is now more specific than p2; it was not in 2.0.6." : "p1 is now not more specific than p2; it was in 2.0.6.") + "\n\t: p1: " + getOrigMI(xp1) + "\n\t: at " + xp1.position() + "\n\t: p2: " + getOrigMI(xp2) + "\n\t: at " + xp2.position() + "\n\t: t1 is " + t1 + "\n\t: t2 is " + t2; //new Error().printStackTrace(); reporter.report(1, "Warning: "+msg); } } // Change this to return old to re-enable 2.0.6 style computation. return java; } // This is taken from the 2.0.6 implementation. // This contains logic for pre-generic Java. One determines // that a method MI1 is more specific than MI2 if each argument of // MI1 is a subtype of the corresponding argument of MI2. That is, // MI2 is taken as the instance of the method definition for the given // call. Hence no type inference is done. private static boolean oldStyleMoreSpecificMethod( ProcedureInstance<?> xp1, ProcedureInstance<?> xp2, Context context, TypeSystem ts, Type ct1, Type t1, Type t2, boolean descends) { // if the formal params of p1 can be used to call p2, p1 is more specific if (xp1.formalTypes().size() == xp2.formalTypes().size() ) { for (int i = 0; i < xp1.formalTypes().size(); i++) { Type f1 = xp1.formalTypes().get(i); Type f2 = xp2.formalTypes().get(i); // Ignore constraints. This avoids an anomaly with the translation with erased constraints // having inverting the result of the most-specific test. Fixes XTENLANG-455. Type b1 = baseType(f1); Type b2 = baseType(f2); if (! ts.isImplicitCastValid(b1, b2, context)) { return false; } } } // If the formal types are all equal, check the containers; otherwise p1 is more specific. for (int i = 0; i < xp1.formalTypes().size(); i++) { Type f1 = xp1.formalTypes().get(i); Type f2 = xp2.formalTypes().get(i); if (! ts.typeEquals(f1, f2, context)) { return true; } } if (t1 != null && t2 != null) { // If p1 overrides p2 or if p1 is in an inner class of p2, pick p1. if (descends) { return true; } if (t1.isClass() && t2.isClass()) { if (t1.toClass().isEnclosed(t2.toClass())) { return true; } } return false; } return true; } /** * * @param xp1 -- the first procedure instance * @param xp2 -- the second procedure instance * @param context -- the context for the original call * @param ts * @param ct1 * @param t1 -- base type of ct1 * @param t2 -- base type of the container of xp2. * @param descends -- does t1 descend from t2? * @return */ private static boolean javaStyleMoreSpecificMethod( ProcedureInstance<?> xp1, ProcedureInstance<?> xp2, Context context, Type ct1, Type t1, Type t2, boolean descends) { assert xp1 != null; assert xp2 != null; assert context != null; TypeSystem ts = (TypeSystem) context.typeSystem(); try { if (xp2 instanceof MethodInstance) { // Both xp1 and xp2 should be X10MethodInstance's MethodInstance xmi2 = (MethodInstance) xp2; MethodInstance origMI2 = (MethodInstance) xmi2.origMI(); assert origMI2 != null; if (! (xp1 instanceof MethodInstance)) return false; MethodInstance xmi1 = (MethodInstance) xp1; MethodInstance origMI1 = (MethodInstance)xmi1.origMI(); assert origMI1 != null; // Now determine that a call can be made to thisMI2 using the // argument list obtained from thisMI1. If not, return false. List<Type> argTypes = new ArrayList<Type>(origMI1.formalTypes()); if (xp2.formalTypes().size() != argTypes.size()) return false; // For xp1 to be more specific than xp2, it must have the same number of type parameters //if (xmi1.typeParameters().size() != 0 && (xmi2.typeParameters().size() != xmi1.typeParameters().size())) // return false; // TODO: Establish that the current context is aware of the method // guard for xmi1. List<Type> typeArgs = origMI1.typeParameters(); // pass in the type parameters, no need to infer MethodInstance r = null; try { r=Matcher.inferAndCheckAndInstantiate(context, origMI2, ct1, typeArgs, argTypes, xp2.position()); } catch (SemanticException z) { } if (r == null){ r = Matcher.inferAndCheckAndInstantiate(context, origMI2, ct1, Collections.<Type>emptyList(), argTypes, xp2.position()); if (r == null){ return false; } } // fall through, we know that xp1 can be used to make a call to xp2 } else if (xp2 instanceof X10ConstructorInstance) { // Both xp1 and xp2 should be X10ConstructorInstance's X10ConstructorInstance xmi2 = (X10ConstructorInstance) xp2; X10ConstructorInstance origMI2 = (X10ConstructorInstance) xmi2.origMI(); assert origMI2 != null; if (! (xp1 instanceof X10ConstructorInstance)) return false; X10ConstructorInstance xmi1 = (X10ConstructorInstance) xp1; X10ConstructorInstance origMI1 = (X10ConstructorInstance) xmi1.origMI(); assert origMI1 != null; List<Type> argTypes = new ArrayList<Type>(origMI1.formalTypes()); if (xp2.formalTypes().size() != argTypes.size()) return false; // TODO: Figure out how to do type inference. List<Type> typeArgs = xmi2.typeParameters(); X10ConstructorInstance r=null; try { r= Matcher.inferAndCheckAndInstantiate( context, origMI2, ct1, typeArgs, argTypes, xp2.position()); } catch (SemanticException z) { } if (r == null) { r = Matcher.inferAndCheckAndInstantiate(context, origMI2, ct1, Collections.<Type>emptyList(), argTypes, xp2.position()); if (r == null) return false; } // fall through, we know that xp1 can be used to make a call to xp2 } else { // Should not happen. // System.out.println("Diagnostic. Unhandled MoreSpecificMatcher case: " + xp2 + " class " + xp2.getClass()); assert false; } } catch (SemanticException z) { return false; } // I have kept the logic below from 2.0.6 for now. // TODO: Determine whether this should stay or not. // If the formal types are all equal, check the containers; otherwise p1 is more specific. for (int i = 0; i < xp1.formalTypes().size(); i++) { Type f1 = xp1.formalTypes().get(i); Type f2 = xp2.formalTypes().get(i); if (! ts.typeEquals(f1, f2, context)) { return true; } } // the types are all equal, check the containers if (t1 != null && t2 != null) { // If p1 overrides p2 or if p1 is in an inner class of p2, pick p1. if (descends) { return true; } if (t1.isClass() && t2.isClass()) { if (t1.toClass().isEnclosed(t2.toClass())) { return true; } } // p1 may be intfc method, p2 the implementing method return false; } return true; } public static boolean isTypeConstraintExpression(Expr e) { if (e instanceof ParExpr) return isTypeConstraintExpression(((ParExpr) e).expr()); else if (e instanceof Unary_c) return isTypeConstraintExpression(((Unary) e).expr()); else if (e instanceof SubtypeTest) return true; else if (e instanceof HasZeroTest) return true; return false; } /** * Return T if type implements Reducer[T]; * @param type * @return */ public static Type reducerType(Type type) { TypeSystem ts = (TypeSystem) type.typeSystem(); Type base = baseType(type); if (base instanceof X10ClassType) { if (ts.hasSameClassDef(base, ts.Reducible())) { return getParameterType(base, 0); } else { Type sup = ts.superClass(type); if (sup != null) { Type t = reducerType(sup); if (t != null) return t; } for (Type ti : ts.interfaces(type)) { Type t = reducerType(ti); if (t != null) { return t; } } } } return null; } public static Type typeArg(Type t, int i) { if (t instanceof X10ParsedClassType) { X10ParsedClassType ct = (X10ParsedClassType) t; return ct.typeArguments().get(i); } return typeArg(baseType(t), i); } //////////////////////////////////////////////////////////////// // For better error reporting, we remove the constraints if we ran with DYNAMIC_CALLS. public static Type stripConstraintsIfDynamicCalls(Type t) { if (t==null) return null; if (((X10CompilerOptions)t.typeSystem().extensionInfo().getOptions()).x10_config.STATIC_CHECKS) return t; return stripConstraints(t); } public static Collection<Type> stripConstraintsIfDynamicCalls(Collection<Type> t) { if (t==null) return null; if (t.size()==0) return t; if (((X10CompilerOptions)t.iterator().next().typeSystem().extensionInfo().getOptions()).x10_config.STATIC_CHECKS) return t; ArrayList<Type> res = new ArrayList<Type>(t.size()); for (Type tt : t) res.add(stripConstraints(tt)); return res; } public static Type stripConstraints(Type t) { TypeSystem ts = (TypeSystem) t.typeSystem(); t = ts.expandMacros(t); t = baseType(t); if (t instanceof X10ClassType) { X10ClassType ct = (X10ClassType) t; if (ct.typeArguments() == null) return ct; List<Type> types = new ArrayList<Type>(ct.typeArguments().size()); for (Type ti : ct.typeArguments()) { Type ti2 = stripConstraints(ti); types.add(ti2); } return ct.typeArguments(types); } return t; } public static Type superClass(Type t) { t = baseType(t); assert t instanceof ClassType; return ((ClassType) t).superClass(); } public static CConstraint tryAddingConstraint(Type t, CConstraint xc) { CConstraint c = Types.xclause(t); c = c == null ? new CConstraint() :c.copy(); c.addIn(xc); return c; } public static ConstrainedType toConstrainedType(Type t) { ConstrainedType result; if (t instanceof ConstrainedType) { result=(ConstrainedType) t; } else { result = constrainedType(t, new CConstraint()); } return result; } public static XVar thisVar(XVar xthis, Type thisType) { Type base = baseType(thisType); if (base instanceof X10ClassType) { XVar supVar = ((X10ClassType) base).x10Def().thisVar(); return supVar; } return xthis; } /** * Return the constraint c entailed by the assertion v is of type t. * @param v * @param t * @return */ public static CConstraint xclause(XVar v, Type t) { CConstraint c = xclause(t); try { return c.substitute(v, c.self()); } catch (XFailure z) { CConstraint c1 = new CConstraint(); c1.setInconsistent(); return c1; } } /** * Returns a copy of t's constraint, if it has one, null otherwise. * @param t * @return */ public static CConstraint xclause(Type t) { if (t instanceof MacroType) { MacroType mt = (MacroType) t; return xclause(mt.definedType()); } if (t instanceof ConstrainedType) { ConstrainedType ct = (ConstrainedType) t; return ct.xclause(); } if (t instanceof X10ParsedClassType) { X10ParsedClassType ct = (X10ParsedClassType) t; return ct.getXClause().copy(); } return null; } public static Type xclause(Type t, CConstraint c) { if (t == null) return null; if (c == null /*|| c.valid()*/) { return t; } return ConstrainedType.xclause(ref(t), ref(c)); } public static X10FieldInstance getProperty( Type t, Name propName) { TypeSystem xts = t.typeSystem(); try { Context c = xts.emptyContext(); X10FieldInstance fi = xts.findField(t, t, propName, c); if (fi != null && fi.isProperty()) { return fi; } } catch (SemanticException e) { // ignore } return null; } public static MethodInstance getPropertyMethod(Type t, Name propName) { TypeSystem xts = t.typeSystem(); try { Context c = xts.emptyContext(); MethodInstance mi = xts.findMethod(t, xts.MethodMatcher(t, propName, Collections.<Type>emptyList(), c)); if (mi != null && mi.flags().isProperty()) { return mi; } } catch (SemanticException e) { // ignore } return null; } /** * Determine if xp1 is more specific than xp2 given some (unknown) current call c to a method m or a constructor * for a class or interface Q (in the given context). (Note that xp1 and xp2 may not be function definitions since * no method resolution is not necessary for function definitions.) * * <p> We may assume that xp1 and xp2 are instantiations of underlying (possibly generic) procedure definitions, * pd1 and pd2 (respectively) that lie in the applicable and available method call set for c. * * <p> The determination is done as follows. First, if xp1 is an instance of a static method on a class C1, and xp2 * is an instance of a static method on a class C2, and C1 is distinct from C2 but descends from it, * Otherwise we examine pd1 and pd2 -- the underlying possibly generic method definitions. Now pd1 is more * specific than pd2 if a call can be made to pd2 with the information available about pd1's arguments. As usual, * type parameters of pd2 (if any) are permitted to be instantiated during this process. * @param ct -- represents the container on which both xp1 and xp2 are available. Ignored now. TODO: Remove the machinery * introduced to permit ct to be available in this call to moreSpecificImpl. * @param xp1 -- the instantiated procedure definition. * @param xp2 * @param context * @return */ public static String MORE_SPECIFIC_WARNING = "Please check definitions p1 and p2. "; private static Type instantiateThis(X10ParsedClassType_c classType, Type t, Type superType) { try { return X10FieldMatcher.instantiateAccess(t,superType,classType.x10Def().thisVar(),false); } catch (SemanticException e) { throw new InternalCompilerError(e); } } //abstract class A implements Iterable<A> {} //abstract class B extends A implements Iterable<B> {} // ERR in Java, but ok in X10 // There can be multiple Iterable[T] due to type parameter upper bounds: X<:Dist && X<:Iterable[...] public static HashSet<Type> getIterableIndex(Type t, Context context) { HashSet<Type> res = new HashSet<Type>(); final TypeSystem ts = t.typeSystem(); Type base = Types.baseType(t); if (ts.isParameterType(base)) { // Now get the upper bound. List<Type> upperBounds = ts.env(context).upperBounds(t, false); // should return non-parameter types for (Type upper : upperBounds) res.addAll(getIterableIndex(upper, context)); } if (t instanceof ObjectType && base instanceof X10ParsedClassType_c) { X10ParsedClassType_c classType_c = (X10ParsedClassType_c) base; ObjectType ot = (ObjectType) t; final Type superType = ot.superClass(); if (superType!=null) res.addAll(getIterableIndex(instantiateThis(classType_c,t,superType),context)); final List<Type> interfaces = ot.interfaces(); for (Type tt : interfaces) res.addAll(getIterableIndex(instantiateThis(classType_c,t,tt),context)); if (base instanceof X10ParsedClassType) { X10ParsedClassType classType = (X10ParsedClassType) base; final ClassDef iterable = ts.Iterable().def(); if (classType.def()==iterable && classType.typeArguments().size()==1) { Type arg = classType.typeArguments().get(0); CConstraint xclause = Types.xclause(t); final XVar tt = XTerms.makeEQV(); try { xclause = Subst.subst(xclause, tt, xclause.self()); } catch (SemanticException e) { assert false; } res.add(Types.xclause(arg, xclause)); } } } return res; } public static Type removeLocals(Context ctx, Type t, CodeDef thisCode) { t = t.typeSystem().expandMacros(t); if (t instanceof X10ClassType) { X10ClassType ct = (X10ClassType) t; if (ct.typeArguments() == null) return ct; List<Type> types = new ArrayList<Type>(ct.typeArguments().size()); for (Type ti : ct.typeArguments()) { Type ti2 = removeLocals(ctx, ti, thisCode); types.add(ti2); } return ct.typeArguments(types); } Type b = baseType(t); if (b != t) b = removeLocals(ctx, b, thisCode); CConstraint c = xclause(t); if (c == null) return b; c = Types.removeLocals(ctx, c, thisCode); return xclause(b, c); } public static CConstraint removeLocals(Context ctx, CConstraint c, CodeDef thisCode) { if (ctx.currentCode() != thisCode) { return c; } TypeSystem ts = (TypeSystem) ctx.typeSystem(); LI: for (LocalDef li : ctx.locals()) { try { if (thisCode instanceof X10ProcedureDef) { for (LocalDef fi : ((X10ProcedureDef) thisCode).formalNames()) if (li == fi) continue LI; } XLocal l = ts.xtypeTranslator().translate(li.asInstance()); XEQV x = XTerms.makeEQV(); c = c.substitute(x, l); } catch (XFailure e) { } } return removeLocals((Context) ctx.pop(), c, thisCode); } public static XVar[] toVarArray(List<LocalDef> formalNames) { XVar[] oldFNs = new XVar[formalNames.size()]; for (int i = 0; i < oldFNs.length; i++) { X10LocalDef oFN = (X10LocalDef) formalNames.get(i); oldFNs[i] = CTerms.makeLocal(oFN); } return oldFNs; } public static List<LocalDef> toLocalDefList(List<LocalInstance> lis) { return new TransformingList<LocalInstance, LocalDef>(lis, new Transformation<LocalInstance,LocalDef>() { public LocalDef transform(LocalInstance o) { return o.def(); } }); } public static ClassType getClassType(Type t, TypeSystem ts, Context context) { Type baseType = Types.baseType(t); if (baseType instanceof ParameterType) { final List<Type> upperBounds = ts.env(context).upperBounds(baseType, false); baseType = null; for (Type up : upperBounds) { if (!(Types.baseType(up) instanceof ParameterType)) baseType = up; } } return baseType==null ? null : baseType.toClass(); } }
false
true
public static boolean isHaszero(Type t, Context xc) { TypeSystem ts = xc.typeSystem(); XLit zeroLit = null; // see Lit_c.constantValue() in its decendants if (t.isBoolean()) { zeroLit = XTerms.FALSE; } else if (ts.isChar(t)) { zeroLit = XTerms.ZERO_CHAR; } else if (ts.isInt(t) || ts.isByte(t) || ts.isUByte(t) || ts.isShort(t) || ts.isUShort(t)) { zeroLit = XTerms.ZERO_INT; } else if (ts.isUInt(t) || ts.isULong(t) || ts.isLong(t)) { zeroLit = XTerms.ZERO_LONG; } else if (ts.isFloat(t)) { zeroLit = XTerms.ZERO_FLOAT; } else if (ts.isDouble(t)) { zeroLit = XTerms.ZERO_DOUBLE; } else if (ts.isObjectOrInterfaceType(t, xc)) { if (Types.permitsNull(t)) return true; //zeroLit = XTerms.NULL; } else if (ts.isParameterType(t)) { // we have some type "T" which is a type parameter. Does it have a zero value? // So, type bounds (e.g., T<:Int) do not help, because Int{self!=0}<:Int // Similarly, Int<:T doesn't help, because Int<:Any{self!=null} // However, T==Int does help if (isConstrained(t)) return false; // if we have constraints on the type parameter, e.g., T{self!=null}, then we give up and return false. TypeConstraint typeConst = xc.currentTypeConstraint(); List<SubtypeConstraint> env = typeConst.terms(); for (SubtypeConstraint sc : env) { if (sc.isEqualityConstraint()) { Type other = null; final Type sub = sc.subtype(); final Type sup = sc.supertype(); if (ts.typeEquals(t, sub,xc)) { if (!ts.isParameterType(sub)) other = sub; if (!ts.isParameterType(sup)) other = sup; } if (other!=null && isHaszero(other,xc)) // careful of infinite recursion when calling isHaszero // We cannot have infinite recursion because other is not a ParameterType // (we can have that T==U, U==Int. but then typeEquals(T,Int,xc) should return true) return true; // T is equal to another type that has zero } else if (sc.isSubtypeConstraint()) { // doesn't help } else { assert sc.isHaszero(); if (ts.typeEquals(t,sc.subtype(),xc)) { return true; } } } } else if (Types.isX10Struct(t)) { if (!(t instanceof ContainerType)) return false; ContainerType structType = (ContainerType) t; // user-defined structs (such as Complex) can have zero iff // 1) They do not have a class invariant // 2) all their fields have zero // todo: When ConstrainedType_c.fields() is fixed (it should add the constraint to the fields), then I can remove this "if" if (isConstrained(t)) return false; // currently I don't handle constrained user-defined types, i.e., Complex{re!=3.0} doesn't haszero // far to do: if t is constrained, then a constraint with all fields=zero entails t's constraint // e.g., Complex and Complex{re!=3.0} haszero, // Complex{re!=0.0} and Complex{re==3.0} doesn't haszero final Type base = baseType(t); if (!(base instanceof X10ParsedClassType_c)) return false; X10ParsedClassType_c xlass = (X10ParsedClassType_c) base; final ClassDef def = xlass.def(); if (!(def instanceof X10ClassDef_c)) return false; X10ClassDef_c x10ClassDef = (X10ClassDef_c) def; // do we have an classInvariant? // todo: class invariant are not treated correctly: // X10ClassDecl_c.classInvariant is fine, // but X10ClassDef_c.classInvariant is wrong final Ref<CConstraint> ref = x10ClassDef.classInvariant(); if (ref!=null && ref.get().constraints().size()>0) return false; // the struct has a class invariant (so the zero value might not satisfy it) // We use ts.structHaszero to prevent infinite recursion such as in the case of: // struct U(u:U) {} final Boolean res = ts.structHaszero(x10ClassDef); if (res!=null) return res; // it is true for type-checking: S[S[Int]] // struct S[T] {T haszero} {val t:T = Zero.get[T](); } ts.structHaszero().put(x10ClassDef,Boolean.TRUE); // make sure all the fields and properties haszero for (FieldInstance field : structType.fields()) { if (field.flags().isStatic()) { continue; } if (!isHaszero(field.type(),xc)) { ts.structHaszero().put(x10ClassDef,Boolean.FALSE); return false; } } return true; } if (zeroLit==null) return false; if (ts.isParameterType(t)) { // we have some type "T" which is a type parameter. Does it have a zero value? // So, type bounds (e.g., T<:Int) do not help, because Int{self!=0}<:Int // Similarly, Int<:T doesn't help, because Int<:Any{self!=null} // However, T==Int does help if (isConstrained(t)) return false; // if we have constraints on the type parameter, e.g., T{self!=null}, then we give up and return false. TypeConstraint typeConst = xc.currentTypeConstraint(); List<SubtypeConstraint> env = typeConst.terms(); for (SubtypeConstraint sc : env) { if (sc.isEqualityConstraint()) { Type other = null; final Type sub = sc.subtype(); final Type sup = sc.supertype(); if (ts.typeEquals(t, sub,xc)) { if (!ts.isParameterType(sub)) other = sub; if (!ts.isParameterType(sup)) other = sup; } if (other!=null) return isHaszero(other,xc); } else if (sc.isSubtypeConstraint()) { // doesn't help } else { assert sc.isHaszero(); if (ts.typeEquals(t,sc.subtype(),xc)) { return true; } } } } if (!isConstrained(t)) return true; final CConstraint constraint = Types.xclause(t); final CConstraint zeroCons = new CConstraint(constraint.self()); // make sure the zeroLit is not in the constraint zeroCons.addSelfBinding(zeroLit); return zeroCons.entails(constraint); }
public static boolean isHaszero(Type t, Context xc) { TypeSystem ts = xc.typeSystem(); XLit zeroLit = null; // see Lit_c.constantValue() in its decendants if (t.isBoolean()) { zeroLit = XTerms.FALSE; } else if (ts.isChar(t)) { zeroLit = XTerms.ZERO_CHAR; } else if (ts.isInt(t) || ts.isByte(t) || ts.isUByte(t) || ts.isShort(t) || ts.isUShort(t)) { zeroLit = XTerms.ZERO_INT; } else if (ts.isUInt(t) || ts.isULong(t) || ts.isLong(t)) { zeroLit = XTerms.ZERO_LONG; } else if (ts.isFloat(t)) { zeroLit = XTerms.ZERO_FLOAT; } else if (ts.isDouble(t)) { zeroLit = XTerms.ZERO_DOUBLE; } else if (ts.isObjectOrInterfaceType(t, xc)) { if (Types.permitsNull(t)) return true; //zeroLit = XTerms.NULL; } else if (ts.isParameterType(t)) { // we have some type "T" which is a type parameter. Does it have a zero value? // So, type bounds (e.g., T<:Int) do not help, because Int{self!=0}<:Int // Similarly, Int<:T doesn't help, because Int<:Any{self!=null} // However, T==Int does help, and so does an explicit T hasZero TypeConstraint typeConst = xc.currentTypeConstraint(); List<SubtypeConstraint> env = typeConst.terms(); for (SubtypeConstraint sc : env) { if (sc.isEqualityConstraint()) { Type other = null; final Type sub = sc.subtype(); final Type sup = sc.supertype(); if (ts.typeEquals(t, sub,xc)) { if (!ts.isParameterType(sub)) other = sub; if (!ts.isParameterType(sup)) other = sup; } if (other!=null && isHaszero(other,xc)) // careful of infinite recursion when calling isHaszero // We cannot have infinite recursion because other is not a ParameterType // (we can have that T==U, U==Int. but then typeEquals(T,Int,xc) should return true) return true; // T is equal to another type that has zero } else if (sc.isSubtypeConstraint()) { // doesn't help } else { assert sc.isHaszero(); if (ts.typeEquals(t,sc.subtype(),xc)) { return true; } } } } else if (Types.isX10Struct(t)) { if (!(t instanceof ContainerType)) return false; ContainerType structType = (ContainerType) t; // user-defined structs (such as Complex) can have zero iff // 1) They do not have a class invariant // 2) all their fields have zero // todo: When ConstrainedType_c.fields() is fixed (it should add the constraint to the fields), then I can remove this "if" if (isConstrained(t)) return false; // currently I don't handle constrained user-defined types, i.e., Complex{re!=3.0} doesn't haszero // far to do: if t is constrained, then a constraint with all fields=zero entails t's constraint // e.g., Complex and Complex{re!=3.0} haszero, // Complex{re!=0.0} and Complex{re==3.0} doesn't haszero final Type base = baseType(t); if (!(base instanceof X10ParsedClassType_c)) return false; X10ParsedClassType_c xlass = (X10ParsedClassType_c) base; final ClassDef def = xlass.def(); if (!(def instanceof X10ClassDef_c)) return false; X10ClassDef_c x10ClassDef = (X10ClassDef_c) def; // do we have an classInvariant? // todo: class invariant are not treated correctly: // X10ClassDecl_c.classInvariant is fine, // but X10ClassDef_c.classInvariant is wrong final Ref<CConstraint> ref = x10ClassDef.classInvariant(); if (ref!=null && ref.get().constraints().size()>0) return false; // the struct has a class invariant (so the zero value might not satisfy it) // We use ts.structHaszero to prevent infinite recursion such as in the case of: // struct U(u:U) {} final Boolean res = ts.structHaszero(x10ClassDef); if (res!=null) return res; // it is true for type-checking: S[S[Int]] // struct S[T] {T haszero} {val t:T = Zero.get[T](); } ts.structHaszero().put(x10ClassDef,Boolean.TRUE); // make sure all the fields and properties haszero for (FieldInstance field : structType.fields()) { if (field.flags().isStatic()) { continue; } if (!isHaszero(field.type(),xc)) { ts.structHaszero().put(x10ClassDef,Boolean.FALSE); return false; } } return true; } if (ts.isParameterType(t)) { // FIXME: why is this code duplicated? // we have some type "T" which is a type parameter. Does it have a zero value? // So, type bounds (e.g., T<:Int) do not help, because Int{self!=0}<:Int // Similarly, Int<:T doesn't help, because Int<:Any{self!=null} // However, T==Int does help, and so does an explicit T hasZero TypeConstraint typeConst = xc.currentTypeConstraint(); List<SubtypeConstraint> env = typeConst.terms(); for (SubtypeConstraint sc : env) { if (sc.isEqualityConstraint()) { Type other = null; final Type sub = sc.subtype(); final Type sup = sc.supertype(); if (ts.typeEquals(t, sub,xc)) { if (!ts.isParameterType(sub)) other = sub; if (!ts.isParameterType(sup)) other = sup; } if (other!=null) return isHaszero(other,xc); } else if (sc.isSubtypeConstraint()) { // doesn't help } else { assert sc.isHaszero(); if (ts.typeEquals(t,sc.subtype(),xc)) { return true; } } } } if (zeroLit==null) return false; if (!isConstrained(t)) return true; final CConstraint constraint = Types.xclause(t); final CConstraint zeroCons = new CConstraint(constraint.self()); // make sure the zeroLit is not in the constraint zeroCons.addSelfBinding(zeroLit); return zeroCons.entails(constraint); }
diff --git a/src/edu/jhu/thrax/hadoop/jobs/WordLexprobJob.java b/src/edu/jhu/thrax/hadoop/jobs/WordLexprobJob.java index 0e840d2..5643261 100644 --- a/src/edu/jhu/thrax/hadoop/jobs/WordLexprobJob.java +++ b/src/edu/jhu/thrax/hadoop/jobs/WordLexprobJob.java @@ -1,61 +1,61 @@ package edu.jhu.thrax.hadoop.jobs; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.mapreduce.lib.reduce.IntSumReducer; import edu.jhu.thrax.hadoop.datatypes.TextPair; import edu.jhu.thrax.hadoop.features.WordLexicalProbabilityCalculator; public abstract class WordLexprobJob extends ThraxJob { public static final String SOURCE_GIVEN_TARGET = "thrax.__wordlexprob_sgt"; private boolean isSourceGivenTarget; public WordLexprobJob(boolean isSrcGivenTgt) { isSourceGivenTarget = isSrcGivenTgt; } public Set<Class<? extends ThraxJob>> getPrerequisites() { Set<Class<? extends ThraxJob>> result = new HashSet<Class<? extends ThraxJob>>(); result.add(VocabularyJob.class); return result; } public Job getJob(Configuration conf) throws IOException { Configuration theConf = new Configuration(conf); theConf.setBoolean(SOURCE_GIVEN_TARGET, isSourceGivenTarget); - Job job = new Job(theConf, "source-word-lexprob"); + Job job = new Job(theConf, getName()); job.setJarByClass(WordLexicalProbabilityCalculator.class); job.setMapperClass(WordLexicalProbabilityCalculator.Map.class); job.setCombinerClass(IntSumReducer.class); job.setSortComparatorClass(TextPair.SndMarginalComparator.class); job.setPartitionerClass(WordLexicalProbabilityCalculator.Partition.class); job.setReducerClass(WordLexicalProbabilityCalculator.Reduce.class); job.setMapOutputKeyClass(LongWritable.class); job.setMapOutputValueClass(IntWritable.class); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(DoubleWritable.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); FileInputFormat.setInputPaths(job, new Path(conf.get("thrax.input-file"))); int maxSplitSize = conf.getInt("thrax.max-split-size", 0); if (maxSplitSize != 0) { FileInputFormat.setMaxInputSplitSize(job, maxSplitSize); } return job; } }
true
true
public Job getJob(Configuration conf) throws IOException { Configuration theConf = new Configuration(conf); theConf.setBoolean(SOURCE_GIVEN_TARGET, isSourceGivenTarget); Job job = new Job(theConf, "source-word-lexprob"); job.setJarByClass(WordLexicalProbabilityCalculator.class); job.setMapperClass(WordLexicalProbabilityCalculator.Map.class); job.setCombinerClass(IntSumReducer.class); job.setSortComparatorClass(TextPair.SndMarginalComparator.class); job.setPartitionerClass(WordLexicalProbabilityCalculator.Partition.class); job.setReducerClass(WordLexicalProbabilityCalculator.Reduce.class); job.setMapOutputKeyClass(LongWritable.class); job.setMapOutputValueClass(IntWritable.class); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(DoubleWritable.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); FileInputFormat.setInputPaths(job, new Path(conf.get("thrax.input-file"))); int maxSplitSize = conf.getInt("thrax.max-split-size", 0); if (maxSplitSize != 0) { FileInputFormat.setMaxInputSplitSize(job, maxSplitSize); } return job; }
public Job getJob(Configuration conf) throws IOException { Configuration theConf = new Configuration(conf); theConf.setBoolean(SOURCE_GIVEN_TARGET, isSourceGivenTarget); Job job = new Job(theConf, getName()); job.setJarByClass(WordLexicalProbabilityCalculator.class); job.setMapperClass(WordLexicalProbabilityCalculator.Map.class); job.setCombinerClass(IntSumReducer.class); job.setSortComparatorClass(TextPair.SndMarginalComparator.class); job.setPartitionerClass(WordLexicalProbabilityCalculator.Partition.class); job.setReducerClass(WordLexicalProbabilityCalculator.Reduce.class); job.setMapOutputKeyClass(LongWritable.class); job.setMapOutputValueClass(IntWritable.class); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(DoubleWritable.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); FileInputFormat.setInputPaths(job, new Path(conf.get("thrax.input-file"))); int maxSplitSize = conf.getInt("thrax.max-split-size", 0); if (maxSplitSize != 0) { FileInputFormat.setMaxInputSplitSize(job, maxSplitSize); } return job; }
diff --git a/dspace/src/org/dspace/storage/rdbms/TableRow.java b/dspace/src/org/dspace/storage/rdbms/TableRow.java index 35c824733..21233329f 100644 --- a/dspace/src/org/dspace/storage/rdbms/TableRow.java +++ b/dspace/src/org/dspace/storage/rdbms/TableRow.java @@ -1,456 +1,456 @@ /* * TableRow.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.storage.rdbms; import java.sql.*; import java.util.*; /** * Represents a database row. * * @author Peter Breton * @version $Revision$ */ public class TableRow { /** Marker object to indicate NULLs. */ private static final Object NULL_OBJECT = new Object(); /** The name of the database table containing this row */ private String table; /** * A map of column names to column values. * The key of the map is a String, the column name; * the value is an Object, either an Integer, Boolean, Date, or String. * If the value is NULL_OBJECT, then the column was NULL. */ private Map data = new HashMap(); /** * Constructor * * @param table The name of the database table containing this row. * @param columns A list of column names. Each member of the * List is a String. After construction, the list of columns * is fixed; attempting to access a column not in the list * will cause an IllegalArgumentException to be thrown. */ public TableRow(String table, List columns) { this.table = table; nullColumns(columns); } /** * Return the name of the table containing this row, or null if * this row is not associated with a database table. * * @return The name of the table containing this row */ public String getTable() { return table; } /** * Return true if this row contains a column with this name. * * @param column The column name (case-insensitive) * @return True if this row contains a column with this name. */ public boolean hasColumn (String column) { return data.get(canonicalize(column)) != null; } /** * Return true if the column is an SQL NULL. * * @param column The column name (case-insensitive) * @return True if the column is an SQL NULL */ public boolean isColumnNull(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); return data.get(canonicalize(column)) == NULL_OBJECT; } /** * Return the integer value of column. * * If the column's type is not an integer, or the column does not * exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @return The integer value of the column, or -1 if the column * is an SQL null. */ public int getIntColumn(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); String name = canonicalize(column); if (isColumnNull(name)) return -1; Object value = data.get(name); if (value == null) throw new IllegalArgumentException("Column " + column + " not present"); if (!(value instanceof Integer)) - throw new IllegalArgumentException("Value is not an integer"); + throw new IllegalArgumentException("Value for " + column + " is not an integer"); return ((Integer) value).intValue(); } /** * Return the long value of column. * * If the column's type is not an long, or the column does not * exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @return The long value of the column, or -1 if the column * is an SQL null. */ public long getLongColumn(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); String name = canonicalize(column); if (isColumnNull(name)) return -1; Object value = data.get(name); if (value == null) throw new IllegalArgumentException("Column " + column + " not present"); if (!(value instanceof Long)) throw new IllegalArgumentException("Value is not an long"); return ((Long) value).longValue(); } /** * Return the String value of column. * * If the column's type is not a String, or the column does not * exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @return The String value of the column, or null if the column * is an SQL null. */ public String getStringColumn(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); String name = canonicalize(column); if (isColumnNull(name)) return null; Object value = data.get(name); if (value == null) throw new IllegalArgumentException("Column " + column + " not present"); if (!(value instanceof String)) throw new IllegalArgumentException("Value is not an string"); return (String) value; } /** * Return the boolean value of column. * * If the column's type is not a boolean, or the column does not * exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @return The boolean value of the column, or false if the column * is an SQL null. */ public boolean getBooleanColumn(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); String name = canonicalize(column); if (isColumnNull(name)) return false; Object value = data.get(name); if (value == null) throw new IllegalArgumentException("Column " + column + " not present"); if (!(value instanceof Boolean)) throw new IllegalArgumentException("Value is not a boolean"); return ((Boolean) value).booleanValue(); } /** * Return the date value of column. * * If the column's type is not a date, or the column does not * exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @return - The date value of the column, or null if the column * is an SQL null. */ public java.util.Date getDateColumn(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); String name = canonicalize(column); if (isColumnNull(name)) return null; Object value = data.get(name); if (value == null) throw new IllegalArgumentException("Column " + column + " not present"); if (!(value instanceof java.util.Date)) throw new IllegalArgumentException("Value is not a Date"); return (java.util.Date) value; } /** * Set column to an SQL NULL. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) */ public void setColumnNull(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); setColumnNullInternal(canonicalize(column)); } /** * Set column to the boolean b. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @param b The boolean value */ public void setColumn(String column, boolean b) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); data.put(canonicalize(column), b ? Boolean.TRUE : Boolean.FALSE); } /** * Set column to the String s. * If s is null, the column is set to null. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @param s The String value */ public void setColumn(String column, String s) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); data.put(canonicalize(column), s == null ? NULL_OBJECT : s); } /** * Set column to the integer i. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @param i The integer value */ public void setColumn(String column, int i) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); data.put(canonicalize(column), new Integer(i)); } /** * Set column to the long l. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @param l The long value */ public void setColumn(String column, long l) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); data.put(canonicalize(column), new Long(l)); } /** * Set column to the date d. If the date is null, the column is * set to NULL as well. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @param d The date value */ public void setColumn(String column, java.util.Date d) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); if (d == null) { setColumnNull(canonicalize(column)); return; } data.put(canonicalize(column), d); } //////////////////////////////////////// // Utility methods //////////////////////////////////////// /** * Return a String representation of this object. */ public String toString() { final String NEWLINE = System.getProperty("line.separator"); StringBuffer result = new StringBuffer(table).append(NEWLINE); for (Iterator iterator = data.keySet().iterator(); iterator.hasNext(); ) { String column = (String) iterator.next(); result .append("\t") .append(column) .append(" = ") .append(isColumnNull(column) ? "NULL" : data.get(column)) .append(NEWLINE) ; } return result.toString(); } /** * Return a hash code for this object. */ public int hashCode() { return toString().hashCode(); } /** * Return true if this object equals obj, false otherwise. */ public boolean equals(Object obj) { if (! (obj instanceof TableRow)) return false; return data.equals(((TableRow) obj).data); } /** * Return the canonical name for column. * * @param column The name of the column. * @return The canonical name of the column. */ static String canonicalize(String column) { return column.toLowerCase(); } /** * Set columns to null. * * @param columns - A list of the columns to set to null. * Each element of the list is a String. */ private void nullColumns(List columns) { for (Iterator iterator = columns.iterator(); iterator.hasNext(); ) { setColumnNullInternal((String) iterator.next()); } } /** * Internal method to set column to null. * The public method ensures that column actually exists. */ private void setColumnNullInternal(String column) { data.put(canonicalize(column), NULL_OBJECT); } }
true
true
public int getIntColumn(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); String name = canonicalize(column); if (isColumnNull(name)) return -1; Object value = data.get(name); if (value == null) throw new IllegalArgumentException("Column " + column + " not present"); if (!(value instanceof Integer)) throw new IllegalArgumentException("Value is not an integer"); return ((Integer) value).intValue(); }
public int getIntColumn(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); String name = canonicalize(column); if (isColumnNull(name)) return -1; Object value = data.get(name); if (value == null) throw new IllegalArgumentException("Column " + column + " not present"); if (!(value instanceof Integer)) throw new IllegalArgumentException("Value for " + column + " is not an integer"); return ((Integer) value).intValue(); }
diff --git a/source/RMG/jing/chem/ThermoGAGroupLibrary.java b/source/RMG/jing/chem/ThermoGAGroupLibrary.java index 7b35805f..cc324aed 100644 --- a/source/RMG/jing/chem/ThermoGAGroupLibrary.java +++ b/source/RMG/jing/chem/ThermoGAGroupLibrary.java @@ -1,1539 +1,1539 @@ //////////////////////////////////////////////////////////////////////////////// // // RMG - Reaction Mechanism Generator // // Copyright (c) 2002-2011 Prof. William H. Green ([email protected]) and the // RMG Team ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // //////////////////////////////////////////////////////////////////////////////// package jing.chem; import java.io.*; import java.util.*; import jing.chemUtil.*; import jing.chemParser.*; import jing.chemUtil.HierarchyTree; import jing.rxnSys.Logger; //## package jing::chem //---------------------------------------------------------------------------- // jing\chem\ThermoGAGroupLibrary.java //---------------------------------------------------------------------------- /** There are six libraries: (1) group (2) radical (3) ring correction (4) other correction (5) gauche correction (6) 1,5 correction In each library, the key should be functional group (name + adjList), and the value should be ThermoGAValue. for (2), (3), (4), we scan the library to find match between chemgraph and functional group each time. search time O(n), where n is the library size. for (1), we first match chemgraph with a tree structure to find out the proper functional group, and then access the library by the key functional group, so the search tiem is O(1) + O(logN), where N is the tree size. */ //## class ThermoGAGroupLibrary public class ThermoGAGroupLibrary { protected static ThermoGAGroupLibrary INSTANCE = new ThermoGAGroupLibrary(); //## attribute INSTANCE protected HashMap groupDictionary; //## attribute groupDictionary protected HashMap groupLibrary; //## attribute groupLibrary /** Note: this kind of tree is different with the kinetics tree. In kinetics tree, tree nodes are FunctionalGroup or FunctionalGroupCollection. In thermo tree, tree nodes are Nodes with connectivity, */ protected HierarchyTree groupTree; //## attribute groupTree protected HashMap otherDictionary; //## attribute otherDictionary protected HashMap otherLibrary; //## attribute otherLibrary protected HierarchyTree otherTree; //## attribute otherTree protected HashMap radicalDictionary; //## attribute radicalDictionary protected HashMap radicalLibrary; //## attribute radicalLibrary protected HierarchyTree radicalTree; //## attribute radicalTree protected HierarchyTree ringTree; protected HashMap ringDictionary; protected HashMap ringLibrary; //## attribute ringLibrary protected HashMap gaucheDictionary; protected HashMap gaucheLibrary; protected HierarchyTree gaucheTree; protected HashMap oneFiveDictionary; protected HashMap oneFiveLibrary; protected HierarchyTree oneFiveTree; protected HashMap abramDictionary; protected HashMap abramLibrary; protected HierarchyTree abramTree; protected HashMap abramradDictionary; protected HashMap abramradLibrary; protected HierarchyTree abramradTree; protected HashMap unifacDictionary; protected HashMap unifacLibrary; protected HierarchyTree unifacTree; private HierarchyTree polycylicTree; private HashMap polycyclicDictionary; private HashMap polycyclicLibrary; //protected HashMap solventDictionary; //protected HashMap solventLibrary; // Constructors //## operation ThermoGAGroupLibrary() private ThermoGAGroupLibrary() { groupTree = new HierarchyTree(); groupDictionary = new HashMap(); groupLibrary = new HashMap(); radicalTree = new HierarchyTree(); radicalDictionary = new HashMap(); radicalLibrary = new HashMap(); ringLibrary = new HashMap(); ringDictionary = new HashMap(); ringTree = new HierarchyTree(); otherLibrary = new HashMap(); otherDictionary = new HashMap(); otherTree = new HierarchyTree(); gaucheLibrary = new HashMap(); gaucheDictionary = new HashMap(); gaucheTree = new HierarchyTree(); oneFiveLibrary = new HashMap(); oneFiveDictionary = new HashMap(); oneFiveTree = new HierarchyTree(); abramLibrary= new HashMap(); abramDictionary=new HashMap(); abramTree=new HierarchyTree(); abramradLibrary= new HashMap(); abramradDictionary=new HashMap(); abramradTree=new HierarchyTree(); unifacLibrary= new HashMap(); unifacDictionary=new HashMap(); unifacTree=new HierarchyTree(); polycyclicLibrary = new HashMap(); polycyclicDictionary = new HashMap(); polycylicTree = new HierarchyTree(); // solventDictionary=new HashMap(); // solventLibrary=new HashMap(); String directory = System.getProperty("jing.chem.ThermoGAGroupLibrary.pathName"); if (directory == null) { Logger.critical("undefined system property: jing.chem.ThermoGAGroupLibrary.pathName, exit!"); System.exit(0); } String separator = System.getProperty("file.separator"); if (!directory.endsWith(separator)) directory = directory + separator; Logger.info("\nReading thermo database from "+directory); String gDictionary = directory + "Group_Dictionary.txt"; String gTree = directory + "Group_Tree.txt"; String gLibrary = directory + "Group_Library.txt"; String rDictionary = directory + "Radical_Dictionary.txt"; String rTree = directory + "Radical_Tree.txt"; String rLibrary = directory + "Radical_Library.txt"; String ringDictionary = directory + "Ring_Dictionary.txt"; String ringTree = directory + "Ring_Tree.txt"; String ringLibrary = directory + "Ring_Library.txt"; String otherLibrary = directory + "Other_Library.txt"; String otherDictionary = directory + "Other_Dictionary.txt"; String otherTree = directory + "Other_Tree.txt"; String gauDictionary = directory + "Gauche_Dictionary.txt"; String gauTree = directory + "Gauche_Tree.txt"; String gauLibrary = directory + "Gauche_Library.txt"; String one5Dictionary = directory + "15_Dictionary.txt"; String one5Tree = directory + "15_Tree.txt"; String one5Library = directory + "15_Library.txt"; String AbDictionary=directory+"Abraham_Dictionary.txt"; String AbTree=directory+"Abraham_Tree.txt"; String AbLibrary=directory+"Abraham_Library.txt"; //Added by Amrit Jalan on December 13, 2010 String AbradDictionary=directory+"Abraham_Radical_Dictionary.txt"; String AbradTree=directory+"Abraham_Radical_Tree.txt"; String AbradLibrary=directory+"Abraham_Radical_Library.txt"; String UnDictionary=directory+"Unifac_Dictionary.txt"; String UnTree=directory+"Unifac_Tree.txt"; String UnLibrary=directory+"Unifac_Library.txt"; String PolycyclicDictionary=directory+"Polycyclic_Dictionary.txt"; String PolycyclicTree=directory+"Polycyclic_Tree.txt"; String PolycyclicLibrary=directory+"Polycyclic_Library.txt"; //String solventdict=directory+"Solvent_Dictionary.txt"; //String solventlib=directory+"Solvent_Library.txt"; read(gDictionary,gTree,gLibrary,rDictionary,rTree,rLibrary,ringDictionary,ringTree,ringLibrary,otherDictionary,otherLibrary,otherTree,gauDictionary,gauTree,gauLibrary,one5Dictionary,one5Tree,one5Library,AbDictionary,AbTree,AbLibrary,UnDictionary,UnTree,UnLibrary,AbradDictionary,AbradTree,AbradLibrary, PolycyclicDictionary,PolycyclicTree,PolycyclicLibrary); } //## operation findCorrectionInLibrary(ChemGraph,HashMap) private ThermoData findCorrectionInLibrary(ChemGraph p_chemGraph, HashMap p_library) { //#[ operation findCorrectionInLibrary(ChemGraph,HashMap) p_chemGraph.clearCentralNode(); ThermoData result=new ThermoData(); int redundance; Iterator iter = p_library.keySet().iterator(); while (iter.hasNext()) { redundance = 0; FunctionalGroup f = (FunctionalGroup)iter.next(); HashSet gv = p_chemGraph.identifyThermoMatchedSite(f); if (gv != null) { redundance = gv.size(); if (redundance > 0) { ThermoGAValue ga = (ThermoGAValue)p_library.get(f); if (ga != null) { ThermoData temp = new ThermoData(ga); temp.multiply(redundance); result.plus(temp); temp = null; } } } } p_chemGraph.getGraph().resetMatchedGC(); return result; //#] } /** Requires: the central node of p_chemGraph has been set to the thermo center atom. Effects: find a matched thermo functional group in the group tree for the pass-in p_chemGraph, return this functional group's thermo value. If no leaf is found, throw GroupNotFoundException Modifies: */ //## operation findGAGroup(ChemGraph) public ThermoGAValue findGAGroup(ChemGraph p_chemGraph) throws GroupNotFoundException, MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = groupTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC();//2/13/09 gmagoon: resetting the matched GC value...for some reason, thermoLibrary.findGAGroup (within getGAGroup in GATP.java) ended up modifiying the central node so that it was matched; this ended up wreaking havoc with subsequent symmetry number calculations; ideally, I would probably want to fix the code so that it didn't end up modifying the matchedGC from the null value after it is done with it, but I do not immediately see how to due so, and debugging proved extremely difficult; I have also tried to put this elsewhere in this class where it might be appropriate if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)groupLibrary.get(fg); p_chemGraph.appendThermoComments("Group:" + fg.getName()); if (ga != null) //{ //System.out.println("Group found: " + fg.getName()); return ga; //} } return null; //#] } //## operation findOtherCorrection(ChemGraph) public ThermoGAValue findOtherCorrection(ChemGraph p_chemGraph) { //#[ operation findOtherCorrection(ChemGraph) if (p_chemGraph == null) return null; Stack stack = otherTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); FunctionalGroup fg = (FunctionalGroup)node.getElement(); ThermoGAValue ga = (ThermoGAValue)otherLibrary.get(fg); p_chemGraph.appendThermoComments("Other:" + fg.getName()); if (ga != null) return ga; } return null; //#] } //## operation findRadicalGroup(ChemGraph) public ThermoGAValue findRadicalGroup(ChemGraph p_chemGraph) throws InvalidThermoCenterException { //#[ operation findRadicalGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = radicalTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)radicalLibrary.get(fg); p_chemGraph.appendThermoComments("Radical:" + fg.getName()); if (ga != null) return ga; } return null; //#] } //## operation findRingCorrection(ChemGraph) public Map<ThermoGAValue, Integer> findRingCorrections(ChemGraph p_chemGraph) { if (p_chemGraph == null) return null; Set<Node> fusedRingAtoms = p_chemGraph.getGraph().getFusedRingAtoms(); if(fusedRingAtoms != null){ p_chemGraph.appendThermoComments("!Fused Ring System!\n"); p_chemGraph.appendThermoComments("!Additive ring strain corrections might not be accurate!\n"); } List<Set<Node>> ringNodes = p_chemGraph.getGraph().getCycleNodes(); if(ringNodes == null){ Logger.error("Could not find ring nodes in graph."); return null; } else{ Map<Stack, Integer> deepestStackMap = null; deepestStackMap = new HashMap<Stack, Integer>(); for(Set<Node> set : ringNodes){ int deepest = -1; Stack dummy = null; Iterator iterNodes = set.iterator(); while(iterNodes.hasNext()){ //take first atom in this ring: Node node = (Node)iterNodes.next(); Atom atom = (Atom)node.getElement(); // make the current node the central atom p_chemGraph.resetThermoSite(node); // find the match in the thermo tree Stack stack = ringTree.findMatchedPath(p_chemGraph); // check if it's the deepest match if (!stack.empty()) { HierarchyTreeNode htn = (HierarchyTreeNode) stack.peek(); if (htn.getDepth() > deepest) { //we have found a Stack that is deeper than the previous ones, re-initialize Set: dummy = stack; deepest = htn.getDepth(); } } } if(deepestStackMap.containsKey(dummy)){ deepestStackMap.put(dummy, deepestStackMap.get(dummy)+1); } else{ deepestStackMap.put(dummy,1); } } if (deepestStackMap.keySet().isEmpty()) return null; //determine ThermoGAValues: Map<ThermoGAValue, Integer> GAMap = new HashMap<ThermoGAValue, Integer>(); for(Stack element : deepestStackMap.keySet()){ HierarchyTreeNode node = (HierarchyTreeNode)element.pop(); FunctionalGroup fg = (FunctionalGroup)node.getElement(); ThermoGAValue ga = (ThermoGAValue)ringLibrary.get(fg); p_chemGraph.appendThermoComments("!Ring:" + fg.getName()); if (ga != null) { if(GAMap.containsKey(ga)){ GAMap.put(ga, GAMap.get(ga)+1); } else{ GAMap.put(ga,1); } } } p_chemGraph.getGraph().resetMatchedGC(); if(GAMap.isEmpty()){ return null; } else{ return GAMap; } } } //2/5/09 gmagoon: new functions for gauche and 1,5-interactions /** Requires: the central node of p_chemGraph has been set to the thermo center atom. Effects: find a matched thermo functional group in the group tree for the pass-in p_chemGraph, return this functional group's thermo value. If no leaf is found, throw GroupNotFoundException Modifies: */ public ThermoGAValue findGaucheGroup(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = gaucheTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)gaucheLibrary.get(fg); p_chemGraph.appendThermoComments("Gauche:" + fg.getName()); if (ga != null) return ga; } return null; } /** Requires: the central node of p_chemGraph has been set to the thermo center atom. Effects: find a matched thermo functional group in the group tree for the pass-in p_chemGraph, return this functional group's thermo value. If no leaf is found, throw GroupNotFoundException Modifies: */ public ThermoGAValue find15Group(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = oneFiveTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)oneFiveLibrary.get(fg); p_chemGraph.appendThermoComments("1,5:" + fg.getName()); if (ga != null) return ga; } return null; } public AbrahamGAValue findAbrahamGroup(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = abramTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); AbrahamGAValue ga = (AbrahamGAValue)abramLibrary.get(fg); if (ga != null) { //System.out.println("Platts Group found: " + fg.getName()); return ga; } } return null; } //Added by Amrit Jalan on December 13, 2010 public AbrahamGAValue findAbrahamradGroup(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findRadicalGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = abramradTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); AbrahamGAValue ga = (AbrahamGAValue)abramradLibrary.get(fg); if (ga != null) return ga; } return null; } public UnifacGAValue findUnifacGroup(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = unifacTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); UnifacGAValue ga = (UnifacGAValue)unifacLibrary.get(fg); if (ga != null) { //System.out.println("Unifac Group found: " + fg.getName()); return ga; } } return null; } //## operation read(String,String,String,String,String,String,String,String,String) public void read(String p_groupDictionary, String p_groupTree, String p_groupLibrary, String p_radicalDictionary, String p_radicalTree, String p_radicalLibrary, String p_ringDictionary, String p_ringTree, String p_ringLibrary, String p_otherDictionary, String p_otherLibrary, String p_otherTree, String p_gaucheDictionary, String p_gaucheTree, String p_gaucheLibrary, String p_15Dictionary, String p_15Tree, String p_15Library,String p_abramDictionary,String p_abramTree,String p_abramLibrary,String p_unifacDictionary,String p_unifacTree,String p_unifacLibrary,String p_abramradDictionary,String p_abramradTree,String p_abramradLibrary, String polycyclicDictionary,String polycyclicTree,String polycyclicLibrary) { //,String p_solventDictionary,String p_solventLibrary) { // step 1: read in GA Groups Logger.info("Reading thermochemistry groups"); // read thermo functional Group dictionary readGroupDictionary(p_groupDictionary); // read thermo functional Group tree structure readGroupTree(p_groupTree); // read group values readGroupLibrary(p_groupLibrary); // step 2: read in Radical Corrections Logger.info("Reading radical correction groups"); // read radical dictionary readRadicalDictionary(p_radicalDictionary); // read radical tree readRadicalTree(p_radicalTree); // read radical value readRadicalLibrary(p_radicalLibrary); // step 3: read in Ring Correction Logger.info("Reading ring correction groups"); readRingDictionary(p_ringDictionary); readRingTree(p_ringTree); readRingLibrary(p_ringLibrary); // step 4: read in Other Correction Logger.info("Reading other correction groups"); readOtherDictionary(p_otherDictionary); readOtherLibrary(p_otherLibrary); readOtherTree(p_otherTree); // step 5: read in Gauche and 15 Correction libraries Logger.info("Reading gauche and 1/5 correction groups"); readGaucheDictionary(p_gaucheDictionary); readGaucheTree(p_gaucheTree); readGaucheLibrary(p_gaucheLibrary); read15Dictionary(p_15Dictionary); read15Tree(p_15Tree); read15Library(p_15Library); if (Species.useSolvation) { // Definitions of Platts dictionary, library and tree for Abraham Model Implementation Logger.info("Reading Abraham solvation groups"); readAbrahamDictionary(p_abramDictionary); readAbrahamTree(p_abramTree); readAbrahamLibrary(p_abramLibrary); Logger.info("Reading Abraham radical solvation groups"); readAbrahamradDictionary(p_abramradDictionary); readAbrahamradTree(p_abramradTree); readAbrahamradLibrary(p_abramradLibrary); /* We no longer need UNIFAC groups, and loading them reports some errors, so let's not bother. Logger.info("Reading UNIFAC solvation groups"); readUnifacDictionary(p_unifacDictionary); readUnifacTree(p_unifacTree); readUnifacLibrary(p_unifacLibrary); */ } // step 6: read in Polyclic ring libraries Logger.info("Reading polycyclic groups"); readPolycyclicDictionary(polycyclicDictionary); readPolycyclicTree(polycyclicTree); readPolycyclicLibrary(polycyclicLibrary); } private void readPolycyclicTree(String polycyclicTree2) { try { polycylicTree = readStandardTree(polycyclicTree2,polycyclicDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read polycylic tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } private void readPolycyclicLibrary(String polycyclicLibrary2) { try { polycyclicLibrary = readStandardLibrary(polycyclicLibrary2, polycyclicDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read polycylic library!"); System.exit(0); } } private void readPolycyclicDictionary(String polycyclicDictionary2) { try { polycyclicDictionary = readStandardDictionary(polycyclicDictionary2); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read polyclic dictionary!"); System.exit(0); } } //## operation readGroupDictionary(String) public void readGroupDictionary(String p_fileName) { //#[ operation readGroupDictionary(String) try { groupDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read group dictionary!"); System.exit(0); } //#] } //## operation readGroupLibrary(String) public void readGroupLibrary(String p_fileName) { try { groupLibrary = readStandardLibrary(p_fileName, groupDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Group Library!"); System.exit(0); } } //## operation readGroupTree(String) public void readGroupTree(String p_fileName) { try { groupTree = readStandardTree(p_fileName,groupDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read thermo group tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //## operation readOtherDictionary(String) public void readOtherDictionary(String p_fileName) { try { otherDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read other dictionary!"); System.exit(0); } } //## operation readOtherLibrary(String) public void readOtherLibrary(String p_fileName) { try { otherLibrary = readStandardLibrary(p_fileName, otherDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Other Library!"); System.exit(0); } } //## operation readOtherTree(String) public void readOtherTree(String p_fileName) { try { otherTree = readStandardTree(p_fileName,otherDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read thermo Other tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //2/5/09 gmagoon: new functions for gauche and 1,5 correction reading (based on analogs for regular values, e.g. readGroupDictionary) public void readGaucheDictionary(String p_fileName) { try { gaucheDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read gauche dictionary!"); System.exit(0); } } public void readGaucheLibrary(String p_fileName) { try { gaucheLibrary = readStandardLibrary(p_fileName, gaucheDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read gauche library!"); System.exit(0); } } public void readGaucheTree(String p_fileName) { try { gaucheTree = readStandardTree(p_fileName,gaucheDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read gauche tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } public void readAbrahamDictionary(String p_fileName) { try { abramDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read Abraham dictionary!"); System.exit(0); } } //Added by Amrit Jalan on December 13, 2010 public void readAbrahamradDictionary(String p_fileName) { try { abramradDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read Abraham Radical dictionary!"); System.exit(0); } } public void readUnifacDictionary(String p_fileName) { try { unifacDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read Unifac dictionary!"); System.exit(0); } } public void readAbrahamLibrary(String p_fileName) { try { abramLibrary = readAbramLibrary(p_fileName, abramDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Abraham library!"); System.exit(0); } } //Added by Amrit Jalan on December 13, 2010 public void readAbrahamradLibrary(String p_fileName) { try { abramradLibrary = readAbramLibrary(p_fileName, abramradDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Abraham library!"); System.exit(0); } } public void readUnifacLibrary(String p_fileName) { try { unifacLibrary = readUNIFACLibrary(p_fileName, unifacDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Unifac library!"); System.exit(0); } } public void readAbrahamTree(String p_fileName) { try { abramTree = readStandardTree(p_fileName,abramDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Abraham tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //Added by Amrit Jalan on December 13, 2010 public void readAbrahamradTree(String p_fileName) { try { abramradTree = readStandardTree(p_fileName,abramradDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Abraham Radical tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } public void readUnifacTree(String p_fileName) { try { unifacTree = readStandardTree(p_fileName,unifacDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Unifac tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //public void readSolventDictionary(String p_fileName) { //try { // solventDictionary = readStandard/Dictionary(p_fileName); // return; //} //catch (Exception e) { // Logger.logStackTrace(e); // Logger.critical("Error in read Solvent dictionary!"); // System.exit(0); //} //#] //} // public void readSolventLibrary(String p_fileName) { // try { // solventLibrary = readStandardLibrary(p_fileName, solventDictionary); // return; // } // catch (Exception e) { // Logger.logStackTrace(e); // Logger.critical("Can't read solvent library!"); // System.exit(0); // } //#] //} public void read15Dictionary(String p_fileName) { try { oneFiveDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read 1,5 dictionary!"); System.exit(0); } } public void read15Library(String p_fileName) { try { oneFiveLibrary = readStandardLibrary(p_fileName, oneFiveDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read 1,5 library!"); System.exit(0); } } public void read15Tree(String p_fileName) { try { oneFiveTree = readStandardTree(p_fileName,oneFiveDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read 1,5 tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //## operation readRadicalDictionary(String) public void readRadicalDictionary(String p_fileName) { try { radicalDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read radical dictionary!\n" + e.getMessage()); System.exit(0); } } //## operation readRadicalLibrary(String) public void readRadicalLibrary(String p_fileName) { try { radicalLibrary = readStandardLibrary(p_fileName, radicalDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read radical Library!"); System.exit(0); } } //## operation readRadicalTree(String) public void readRadicalTree(String p_fileName) { try { radicalTree = readStandardTree(p_fileName,radicalDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read thermo group tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //## operation readRingLibrary(String) public void readRingDictionary(String p_fileName) { try { ringDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read ring dictionary!\n" + e.getMessage()); System.exit(0); } } //## operation readRingTree(String) public void readRingTree(String p_fileName) { try { ringTree = readStandardTree(p_fileName,ringDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read ring tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } // end pey //## operation readRingLibrary(String) public void readRingLibrary(String p_fileName) { try { ringLibrary = readStandardLibrary(p_fileName, ringDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Ring Correction Library!"); Logger.critical("Error: " + e); System.exit(0); } } //## operation readStandardCorrectionLibrary(String,HashMap) protected void readStandardCorrectionLibrary(String p_fileName, HashMap p_library) throws IOException { try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); String line = ChemParser.readMeaningfulLine(data, true); while (line != null) { // step 1: read in index and name StringTokenizer token = new StringTokenizer(line); int index = Integer.parseInt(token.nextToken()); String name = token.nextToken(); if (p_library == ringLibrary) { String fomula = token.nextToken(); String sigma = token.nextToken(); } // setp 2: read in thermoGAValue String thermo=""; for (int i=0;i<12;i++) { thermo = thermo.concat(token.nextToken()); thermo = thermo.concat(" "); } ThermoGAValue gaValue = ChemParser.parseThermoGAValue(thermo); String comments = ""; while (token.hasMoreTokens()) { comments = comments + " " + token.nextToken(); } ThermoGAValue newGaValue = new ThermoGAValue(name,gaValue,comments); // step3: read in graph of the functional group Graph g = ChemParser.readFGGraph(data); if (g == null) throw new NullGraphException(); FunctionalGroup fg = FunctionalGroup.make(name, g); // step4: put in library Object previous = p_library.put(fg, newGaValue); if (previous != null) { throw new ReplaceThermoGAValueException(); } line = ChemParser.readMeaningfulLine(data, true); } in.close(); return; } catch (IOException e) { throw new IOException(); } } //## operation readStandardDictionary(String) public HashMap readStandardDictionary(String p_fileName) throws FileNotFoundException, IOException { //#[ operation readStandardDictionary(String) try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HashMap dictionary = new HashMap(); HashMap unRead = new HashMap(); String line = ChemParser.readMeaningfulLine(data, true); read: while (line != null) { StringTokenizer st = new StringTokenizer(line); String fgname = st.nextToken(); data.mark(10000); line = ChemParser.readMeaningfulLine(data, true); if (line == null) break read; line = line.trim(); String prefix = line.substring(0,5); if (prefix.compareToIgnoreCase("union") == 0) { HashSet union = ChemParser.readUnion(line); unRead.put(fgname,union); } else { data.reset(); Graph fgGraph = null; try { fgGraph = ChemParser.readFGGraph(data); } catch (Exception e) { Logger.logStackTrace(e); throw new InvalidFunctionalGroupException(fgname + ": " + e.getMessage()); } if (fgGraph == null) throw new InvalidFunctionalGroupException(fgname); FunctionalGroup fg = FunctionalGroup.make(fgname, fgGraph); Object old = dictionary.get(fgname); if (old == null) { dictionary.put(fgname,fg); } else { FunctionalGroup oldFG = (FunctionalGroup)old; if (!oldFG.equals(fg)) throw new ReplaceFunctionalGroupException(fgname); } } //System.out.println(line); line = ChemParser.readMeaningfulLine(data, true); } while (!unRead.isEmpty()) { String fgname = (String)(unRead.keySet().iterator().next()); ChemParser.findUnion(fgname,unRead,dictionary); } in.close(); return dictionary; } catch (FileNotFoundException e) { throw new FileNotFoundException(p_fileName); } catch (IOException e) { throw new IOException(p_fileName + ": " + e.getMessage()); } } //## operation readStandardLibrary(String,HashMap) protected HashMap readStandardLibrary(String p_fileName, HashMap p_dictionary) throws IOException { try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HashMap library = new HashMap(); String line = ChemParser.readMeaningfulLine(data, true); while (line != null) { //System.out.println(line);// // step 1: read in index and name StringTokenizer token = new StringTokenizer(line); String index = token.nextToken(); //1/6/09 gmagoon changed index from integer to string, so that if/when ChemGreen/RMGVE adds a decimal after the entry number (after editing thermo library), RMG will still be able to read it String name = token.nextToken(); // step 2: find this functional group in dictionary by name Matchable fg = (Matchable)p_dictionary.get(name); if (fg == null) { throw new FunctionalGroupNotFoundException(); //System.out.println(name); } // step 3: read in thermoGAValue String thermo = token.nextToken(); // if there is a set of real thermo numbers, read them in and put the thermo data into library try { double H = Double.parseDouble(thermo); thermo = thermo.concat(" "); for (int i=0;i<11;i++) { thermo = thermo.concat(token.nextToken()); thermo = thermo.concat(" "); } ThermoGAValue gaValue = ChemParser.parseThermoGAValue(thermo); String comments = ""; while (token.hasMoreTokens()) { comments = comments + " " + token.nextToken(); } ThermoGAValue newGaValue=new ThermoGAValue(name,gaValue,comments); // step4: put in library Object previous = library.put(fg, newGaValue); if (previous != null) { throw new ReplaceThermoGAValueException(); } } // if there is a referenced name, put the name into library catch (NumberFormatException e) { Object o = p_dictionary.get(thermo); if (o == null) { //throw new FunctionalGroupNotFoundException(thermo); System.out.print(index); System.out.println(": " + thermo); } Object previous = library.put(fg, thermo); if (previous != null) { throw new ReplaceThermoGAValueException(); } } line = ChemParser.readMeaningfulLine(data, true); } // scan the library to give the ones having referenced name the real thermo data Iterator iter = library.keySet().iterator(); while (iter.hasNext()) { Matchable fg = (Matchable)iter.next(); Object gaValue = library.get(fg); String path = ""; if (gaValue instanceof String) { do { String name = (String)gaValue; path = path + "->" + name; gaValue = library.get((Matchable)p_dictionary.get(name)); } while (gaValue instanceof String); if (gaValue == null || !(gaValue instanceof ThermoGAValue)) { throw new InvalidReferenceThermoGAValueException(); } ThermoGAValue newGaValue = new ThermoGAValue(fg.getName(),(ThermoGAValue)gaValue, "Use the value of " + path); library.put(fg,newGaValue); } } in.close(); return library; } catch (IOException e) { throw new IOException(); } } //## operation readAbramLibrary(String,HashMap) protected HashMap readAbramLibrary(String p_fileName, HashMap p_dictionary) throws IOException { //#[ operation readStandardLibrary(String,HashMap) try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HashMap library = new HashMap(); String line = ChemParser.readMeaningfulLine(data, true); while (line != null) { // step 1: read in index and name StringTokenizer token = new StringTokenizer(line); String index = token.nextToken(); //1/6/09 gmagoon changed index from integer to string, so that if/when ChemGreen/RMGVE adds a decimal after the entry number (after editing thermo library), RMG will still be able to read it String name = token.nextToken(); // step 2: find this functional group in dictionary by name Matchable fg = (Matchable)p_dictionary.get(name); if (fg == null) { throw new FunctionalGroupNotFoundException(); //System.out.println(name); } // step 3: read in AbrahamGAValue String thermo = token.nextToken(); // if there is a set of real thermo numbers, read them in and put the thermo data into library try { double H = Double.parseDouble(thermo); thermo = thermo.concat(" "); for (int i=0;i<4;i++) { thermo = thermo.concat(token.nextToken()); thermo = thermo.concat(" "); } AbrahamGAValue gaValue = ChemParser.parseAbrahamGAValue(thermo); String comments = ""; while (token.hasMoreTokens()) { comments = comments + " " + token.nextToken(); } AbrahamGAValue newGaValue=new AbrahamGAValue(gaValue); // step4: put in library Object previous = library.put(fg, newGaValue); if (previous != null) { throw new ReplaceThermoGAValueException(); } } // if there is a referenced name, put the name into library catch (NumberFormatException e) { Object o = p_dictionary.get(thermo); if (o == null) { //throw new FunctionalGroupNotFoundException(thermo); System.out.print(index); System.out.println(": " + thermo); } Object previous = library.put(fg, thermo); if (previous != null) { throw new ReplaceThermoGAValueException(); } } line = ChemParser.readMeaningfulLine(data, true); } // scan the library to give the ones having referenced name the real thermo data Iterator iter = library.keySet().iterator(); while (iter.hasNext()) { Matchable fg = (Matchable)iter.next(); Object gaValue = library.get(fg); String path = ""; if (gaValue instanceof String) { do { String name = (String)gaValue; path = path + "->" + name; gaValue = library.get((Matchable)p_dictionary.get(name)); } while (gaValue instanceof String); if (gaValue == null || !(gaValue instanceof AbrahamGAValue)) { throw new InvalidReferenceThermoGAValueException(); } AbrahamGAValue newGaValue = new AbrahamGAValue((AbrahamGAValue)gaValue); library.put(fg,newGaValue); } } in.close(); return library; } catch (IOException e) { throw new IOException(); } } //## operation readAbramLibrary(String,HashMap) protected HashMap readUNIFACLibrary(String p_fileName, HashMap p_dictionary) throws IOException { try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HashMap library = new HashMap(); String line = ChemParser.readMeaningfulLine(data, true); while (line != null) { // step 1: read in index and name StringTokenizer token = new StringTokenizer(line); String index = token.nextToken(); //1/6/09 gmagoon changed index from integer to string, so that if/when ChemGreen/RMGVE adds a decimal after the entry number (after editing thermo library), RMG will still be able to read it String name = token.nextToken(); // step 2: find this functional group in dictionary by name Matchable fg = (Matchable)p_dictionary.get(name); if (fg == null) { throw new FunctionalGroupNotFoundException(); //System.out.println(name); } // step 3: read in AbrahamGAValue String thermo = token.nextToken(); // if there is a set of real thermo numbers, read them in and put the thermo data into library try { double H = Double.parseDouble(thermo); thermo = thermo.concat(" "); for (int i=0;i<1;i++) { thermo = thermo.concat(token.nextToken()); thermo = thermo.concat(" "); } UnifacGAValue gaValue = ChemParser.parseUnifacGAValue(thermo); String comments = ""; while (token.hasMoreTokens()) { comments = comments + " " + token.nextToken(); } UnifacGAValue newGaValue=new UnifacGAValue(gaValue); // step4: put in library Object previous = library.put(fg, newGaValue); if (previous != null) { throw new ReplaceThermoGAValueException(); } } // if there is a referenced name, put the name into library catch (NumberFormatException e) { Object o = p_dictionary.get(thermo); if (o == null) { //throw new FunctionalGroupNotFoundException(thermo); System.out.print(index); System.out.println(": " + thermo); } Object previous = library.put(fg, thermo); if (previous != null) { throw new ReplaceThermoGAValueException(); } } line = ChemParser.readMeaningfulLine(data, true); } // scan the library to give the ones having referenced name the real thermo data Iterator iter = library.keySet().iterator(); while (iter.hasNext()) { Matchable fg = (Matchable)iter.next(); Object gaValue = library.get(fg); String path = ""; if (gaValue instanceof String) { do { String name = (String)gaValue; path = path + "->" + name; gaValue = library.get((Matchable)p_dictionary.get(name)); } while (gaValue instanceof String); if (gaValue == null || !(gaValue instanceof UnifacGAValue)) { throw new InvalidReferenceThermoGAValueException(); } UnifacGAValue newGaValue = new UnifacGAValue((UnifacGAValue)gaValue); library.put(fg,newGaValue); } } in.close(); return library; } catch (IOException e) { throw new IOException(); } } //## operation readStandardTree(String,HashMap,int) public HierarchyTree readStandardTree(String p_fileName, HashMap p_dictionary, int p_level) throws IOException { //#[ operation readStandardTree(String,HashMap,int) try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HierarchyTree tree = ChemParser.readHierarchyTree(data,p_dictionary,p_level); in.close(); return tree; } catch (IOException e) { throw new IOException(p_fileName); } } protected static ThermoGAGroupLibrary getINSTANCE() { return INSTANCE; } public HashMap getGroupDictionary() { return groupDictionary; } public HashMap getGroupLibrary() { return groupLibrary; } public void setGroupLibrary(HashMap p_groupLibrary) { groupLibrary = p_groupLibrary; } protected HierarchyTree getGroupTree() { return groupTree; } public HashMap getOtherDictionary() { return otherDictionary; } public void setOtherDictionary(HashMap p_otherDictionary) { otherDictionary = p_otherDictionary; } public HashMap getOtherLibrary() { return otherLibrary; } public HierarchyTree getOtherTree() { return otherTree; } public void setOtherTree(HierarchyTree p_otherTree) { otherTree = p_otherTree; } public HashMap getRadicalDictionary() { return radicalDictionary; } public void setRadicalDictionary(HashMap p_radicalDictionary) { radicalDictionary = p_radicalDictionary; } protected HashMap getRadicalLibrary() { return radicalLibrary; } public HierarchyTree getRadicalTree() { return radicalTree; } public void setRadicalTree(HierarchyTree p_radicalTree) { radicalTree = p_radicalTree; } protected HashMap getRingLibrary() { return ringLibrary; } public ThermoGAValue findPolyCyclicRingCorrections( ChemGraph molecule) { int deepest = -1; Stack dummy = null; Iterator iterNodes = molecule.getGraph().getNodeList(); while(iterNodes.hasNext()){ //take first atom in this ring: Node node = (Node)iterNodes.next(); Atom atom = (Atom)node.getElement(); // make the current node the central atom molecule.resetThermoSite(node); // find the match in the thermo tree Stack stack = polycylicTree.findMatchedPath(molecule); // check if it's the deepest match if (!stack.empty()) { HierarchyTreeNode htn = (HierarchyTreeNode) stack.peek(); if (htn.getDepth() > deepest) { //we have found a Stack that is deeper than the previous ones, re-initialize Set: dummy = stack; deepest = htn.getDepth(); } } } if (dummy == null) return null; /* * If deepest node is L0, then none of the L1 nodes could be matched. * We should return null then. */ if(deepest == 0) return null; while (!dummy.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)dummy.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)polycyclicLibrary.get(fg); - molecule.appendThermoComments("Polyclic ring system:" + fg.getName()); + molecule.appendThermoComments("Polycyclic ring system:" + fg.getName()); if (ga != null) return ga; } molecule.getGraph().resetMatchedGC(); return null; } } /********************************************************************* File Path : RMG\RMG\jing\chem\ThermoGAGroupLibrary.java *********************************************************************/
true
true
public ThermoGAValue findGAGroup(ChemGraph p_chemGraph) throws GroupNotFoundException, MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = groupTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC();//2/13/09 gmagoon: resetting the matched GC value...for some reason, thermoLibrary.findGAGroup (within getGAGroup in GATP.java) ended up modifiying the central node so that it was matched; this ended up wreaking havoc with subsequent symmetry number calculations; ideally, I would probably want to fix the code so that it didn't end up modifying the matchedGC from the null value after it is done with it, but I do not immediately see how to due so, and debugging proved extremely difficult; I have also tried to put this elsewhere in this class where it might be appropriate if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)groupLibrary.get(fg); p_chemGraph.appendThermoComments("Group:" + fg.getName()); if (ga != null) //{ //System.out.println("Group found: " + fg.getName()); return ga; //} } return null; //#] } //## operation findOtherCorrection(ChemGraph) public ThermoGAValue findOtherCorrection(ChemGraph p_chemGraph) { //#[ operation findOtherCorrection(ChemGraph) if (p_chemGraph == null) return null; Stack stack = otherTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); FunctionalGroup fg = (FunctionalGroup)node.getElement(); ThermoGAValue ga = (ThermoGAValue)otherLibrary.get(fg); p_chemGraph.appendThermoComments("Other:" + fg.getName()); if (ga != null) return ga; } return null; //#] } //## operation findRadicalGroup(ChemGraph) public ThermoGAValue findRadicalGroup(ChemGraph p_chemGraph) throws InvalidThermoCenterException { //#[ operation findRadicalGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = radicalTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)radicalLibrary.get(fg); p_chemGraph.appendThermoComments("Radical:" + fg.getName()); if (ga != null) return ga; } return null; //#] } //## operation findRingCorrection(ChemGraph) public Map<ThermoGAValue, Integer> findRingCorrections(ChemGraph p_chemGraph) { if (p_chemGraph == null) return null; Set<Node> fusedRingAtoms = p_chemGraph.getGraph().getFusedRingAtoms(); if(fusedRingAtoms != null){ p_chemGraph.appendThermoComments("!Fused Ring System!\n"); p_chemGraph.appendThermoComments("!Additive ring strain corrections might not be accurate!\n"); } List<Set<Node>> ringNodes = p_chemGraph.getGraph().getCycleNodes(); if(ringNodes == null){ Logger.error("Could not find ring nodes in graph."); return null; } else{ Map<Stack, Integer> deepestStackMap = null; deepestStackMap = new HashMap<Stack, Integer>(); for(Set<Node> set : ringNodes){ int deepest = -1; Stack dummy = null; Iterator iterNodes = set.iterator(); while(iterNodes.hasNext()){ //take first atom in this ring: Node node = (Node)iterNodes.next(); Atom atom = (Atom)node.getElement(); // make the current node the central atom p_chemGraph.resetThermoSite(node); // find the match in the thermo tree Stack stack = ringTree.findMatchedPath(p_chemGraph); // check if it's the deepest match if (!stack.empty()) { HierarchyTreeNode htn = (HierarchyTreeNode) stack.peek(); if (htn.getDepth() > deepest) { //we have found a Stack that is deeper than the previous ones, re-initialize Set: dummy = stack; deepest = htn.getDepth(); } } } if(deepestStackMap.containsKey(dummy)){ deepestStackMap.put(dummy, deepestStackMap.get(dummy)+1); } else{ deepestStackMap.put(dummy,1); } } if (deepestStackMap.keySet().isEmpty()) return null; //determine ThermoGAValues: Map<ThermoGAValue, Integer> GAMap = new HashMap<ThermoGAValue, Integer>(); for(Stack element : deepestStackMap.keySet()){ HierarchyTreeNode node = (HierarchyTreeNode)element.pop(); FunctionalGroup fg = (FunctionalGroup)node.getElement(); ThermoGAValue ga = (ThermoGAValue)ringLibrary.get(fg); p_chemGraph.appendThermoComments("!Ring:" + fg.getName()); if (ga != null) { if(GAMap.containsKey(ga)){ GAMap.put(ga, GAMap.get(ga)+1); } else{ GAMap.put(ga,1); } } } p_chemGraph.getGraph().resetMatchedGC(); if(GAMap.isEmpty()){ return null; } else{ return GAMap; } } } //2/5/09 gmagoon: new functions for gauche and 1,5-interactions /** Requires: the central node of p_chemGraph has been set to the thermo center atom. Effects: find a matched thermo functional group in the group tree for the pass-in p_chemGraph, return this functional group's thermo value. If no leaf is found, throw GroupNotFoundException Modifies: */ public ThermoGAValue findGaucheGroup(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = gaucheTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)gaucheLibrary.get(fg); p_chemGraph.appendThermoComments("Gauche:" + fg.getName()); if (ga != null) return ga; } return null; } /** Requires: the central node of p_chemGraph has been set to the thermo center atom. Effects: find a matched thermo functional group in the group tree for the pass-in p_chemGraph, return this functional group's thermo value. If no leaf is found, throw GroupNotFoundException Modifies: */ public ThermoGAValue find15Group(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = oneFiveTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)oneFiveLibrary.get(fg); p_chemGraph.appendThermoComments("1,5:" + fg.getName()); if (ga != null) return ga; } return null; } public AbrahamGAValue findAbrahamGroup(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = abramTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); AbrahamGAValue ga = (AbrahamGAValue)abramLibrary.get(fg); if (ga != null) { //System.out.println("Platts Group found: " + fg.getName()); return ga; } } return null; } //Added by Amrit Jalan on December 13, 2010 public AbrahamGAValue findAbrahamradGroup(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findRadicalGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = abramradTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); AbrahamGAValue ga = (AbrahamGAValue)abramradLibrary.get(fg); if (ga != null) return ga; } return null; } public UnifacGAValue findUnifacGroup(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = unifacTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); UnifacGAValue ga = (UnifacGAValue)unifacLibrary.get(fg); if (ga != null) { //System.out.println("Unifac Group found: " + fg.getName()); return ga; } } return null; } //## operation read(String,String,String,String,String,String,String,String,String) public void read(String p_groupDictionary, String p_groupTree, String p_groupLibrary, String p_radicalDictionary, String p_radicalTree, String p_radicalLibrary, String p_ringDictionary, String p_ringTree, String p_ringLibrary, String p_otherDictionary, String p_otherLibrary, String p_otherTree, String p_gaucheDictionary, String p_gaucheTree, String p_gaucheLibrary, String p_15Dictionary, String p_15Tree, String p_15Library,String p_abramDictionary,String p_abramTree,String p_abramLibrary,String p_unifacDictionary,String p_unifacTree,String p_unifacLibrary,String p_abramradDictionary,String p_abramradTree,String p_abramradLibrary, String polycyclicDictionary,String polycyclicTree,String polycyclicLibrary) { //,String p_solventDictionary,String p_solventLibrary) { // step 1: read in GA Groups Logger.info("Reading thermochemistry groups"); // read thermo functional Group dictionary readGroupDictionary(p_groupDictionary); // read thermo functional Group tree structure readGroupTree(p_groupTree); // read group values readGroupLibrary(p_groupLibrary); // step 2: read in Radical Corrections Logger.info("Reading radical correction groups"); // read radical dictionary readRadicalDictionary(p_radicalDictionary); // read radical tree readRadicalTree(p_radicalTree); // read radical value readRadicalLibrary(p_radicalLibrary); // step 3: read in Ring Correction Logger.info("Reading ring correction groups"); readRingDictionary(p_ringDictionary); readRingTree(p_ringTree); readRingLibrary(p_ringLibrary); // step 4: read in Other Correction Logger.info("Reading other correction groups"); readOtherDictionary(p_otherDictionary); readOtherLibrary(p_otherLibrary); readOtherTree(p_otherTree); // step 5: read in Gauche and 15 Correction libraries Logger.info("Reading gauche and 1/5 correction groups"); readGaucheDictionary(p_gaucheDictionary); readGaucheTree(p_gaucheTree); readGaucheLibrary(p_gaucheLibrary); read15Dictionary(p_15Dictionary); read15Tree(p_15Tree); read15Library(p_15Library); if (Species.useSolvation) { // Definitions of Platts dictionary, library and tree for Abraham Model Implementation Logger.info("Reading Abraham solvation groups"); readAbrahamDictionary(p_abramDictionary); readAbrahamTree(p_abramTree); readAbrahamLibrary(p_abramLibrary); Logger.info("Reading Abraham radical solvation groups"); readAbrahamradDictionary(p_abramradDictionary); readAbrahamradTree(p_abramradTree); readAbrahamradLibrary(p_abramradLibrary); /* We no longer need UNIFAC groups, and loading them reports some errors, so let's not bother. Logger.info("Reading UNIFAC solvation groups"); readUnifacDictionary(p_unifacDictionary); readUnifacTree(p_unifacTree); readUnifacLibrary(p_unifacLibrary); */ } // step 6: read in Polyclic ring libraries Logger.info("Reading polycyclic groups"); readPolycyclicDictionary(polycyclicDictionary); readPolycyclicTree(polycyclicTree); readPolycyclicLibrary(polycyclicLibrary); } private void readPolycyclicTree(String polycyclicTree2) { try { polycylicTree = readStandardTree(polycyclicTree2,polycyclicDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read polycylic tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } private void readPolycyclicLibrary(String polycyclicLibrary2) { try { polycyclicLibrary = readStandardLibrary(polycyclicLibrary2, polycyclicDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read polycylic library!"); System.exit(0); } } private void readPolycyclicDictionary(String polycyclicDictionary2) { try { polycyclicDictionary = readStandardDictionary(polycyclicDictionary2); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read polyclic dictionary!"); System.exit(0); } } //## operation readGroupDictionary(String) public void readGroupDictionary(String p_fileName) { //#[ operation readGroupDictionary(String) try { groupDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read group dictionary!"); System.exit(0); } //#] } //## operation readGroupLibrary(String) public void readGroupLibrary(String p_fileName) { try { groupLibrary = readStandardLibrary(p_fileName, groupDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Group Library!"); System.exit(0); } } //## operation readGroupTree(String) public void readGroupTree(String p_fileName) { try { groupTree = readStandardTree(p_fileName,groupDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read thermo group tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //## operation readOtherDictionary(String) public void readOtherDictionary(String p_fileName) { try { otherDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read other dictionary!"); System.exit(0); } } //## operation readOtherLibrary(String) public void readOtherLibrary(String p_fileName) { try { otherLibrary = readStandardLibrary(p_fileName, otherDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Other Library!"); System.exit(0); } } //## operation readOtherTree(String) public void readOtherTree(String p_fileName) { try { otherTree = readStandardTree(p_fileName,otherDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read thermo Other tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //2/5/09 gmagoon: new functions for gauche and 1,5 correction reading (based on analogs for regular values, e.g. readGroupDictionary) public void readGaucheDictionary(String p_fileName) { try { gaucheDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read gauche dictionary!"); System.exit(0); } } public void readGaucheLibrary(String p_fileName) { try { gaucheLibrary = readStandardLibrary(p_fileName, gaucheDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read gauche library!"); System.exit(0); } } public void readGaucheTree(String p_fileName) { try { gaucheTree = readStandardTree(p_fileName,gaucheDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read gauche tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } public void readAbrahamDictionary(String p_fileName) { try { abramDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read Abraham dictionary!"); System.exit(0); } } //Added by Amrit Jalan on December 13, 2010 public void readAbrahamradDictionary(String p_fileName) { try { abramradDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read Abraham Radical dictionary!"); System.exit(0); } } public void readUnifacDictionary(String p_fileName) { try { unifacDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read Unifac dictionary!"); System.exit(0); } } public void readAbrahamLibrary(String p_fileName) { try { abramLibrary = readAbramLibrary(p_fileName, abramDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Abraham library!"); System.exit(0); } } //Added by Amrit Jalan on December 13, 2010 public void readAbrahamradLibrary(String p_fileName) { try { abramradLibrary = readAbramLibrary(p_fileName, abramradDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Abraham library!"); System.exit(0); } } public void readUnifacLibrary(String p_fileName) { try { unifacLibrary = readUNIFACLibrary(p_fileName, unifacDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Unifac library!"); System.exit(0); } } public void readAbrahamTree(String p_fileName) { try { abramTree = readStandardTree(p_fileName,abramDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Abraham tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //Added by Amrit Jalan on December 13, 2010 public void readAbrahamradTree(String p_fileName) { try { abramradTree = readStandardTree(p_fileName,abramradDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Abraham Radical tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } public void readUnifacTree(String p_fileName) { try { unifacTree = readStandardTree(p_fileName,unifacDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Unifac tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //public void readSolventDictionary(String p_fileName) { //try { // solventDictionary = readStandard/Dictionary(p_fileName); // return; //} //catch (Exception e) { // Logger.logStackTrace(e); // Logger.critical("Error in read Solvent dictionary!"); // System.exit(0); //} //#] //} // public void readSolventLibrary(String p_fileName) { // try { // solventLibrary = readStandardLibrary(p_fileName, solventDictionary); // return; // } // catch (Exception e) { // Logger.logStackTrace(e); // Logger.critical("Can't read solvent library!"); // System.exit(0); // } //#] //} public void read15Dictionary(String p_fileName) { try { oneFiveDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read 1,5 dictionary!"); System.exit(0); } } public void read15Library(String p_fileName) { try { oneFiveLibrary = readStandardLibrary(p_fileName, oneFiveDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read 1,5 library!"); System.exit(0); } } public void read15Tree(String p_fileName) { try { oneFiveTree = readStandardTree(p_fileName,oneFiveDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read 1,5 tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //## operation readRadicalDictionary(String) public void readRadicalDictionary(String p_fileName) { try { radicalDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read radical dictionary!\n" + e.getMessage()); System.exit(0); } } //## operation readRadicalLibrary(String) public void readRadicalLibrary(String p_fileName) { try { radicalLibrary = readStandardLibrary(p_fileName, radicalDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read radical Library!"); System.exit(0); } } //## operation readRadicalTree(String) public void readRadicalTree(String p_fileName) { try { radicalTree = readStandardTree(p_fileName,radicalDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read thermo group tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //## operation readRingLibrary(String) public void readRingDictionary(String p_fileName) { try { ringDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read ring dictionary!\n" + e.getMessage()); System.exit(0); } } //## operation readRingTree(String) public void readRingTree(String p_fileName) { try { ringTree = readStandardTree(p_fileName,ringDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read ring tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } // end pey //## operation readRingLibrary(String) public void readRingLibrary(String p_fileName) { try { ringLibrary = readStandardLibrary(p_fileName, ringDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Ring Correction Library!"); Logger.critical("Error: " + e); System.exit(0); } } //## operation readStandardCorrectionLibrary(String,HashMap) protected void readStandardCorrectionLibrary(String p_fileName, HashMap p_library) throws IOException { try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); String line = ChemParser.readMeaningfulLine(data, true); while (line != null) { // step 1: read in index and name StringTokenizer token = new StringTokenizer(line); int index = Integer.parseInt(token.nextToken()); String name = token.nextToken(); if (p_library == ringLibrary) { String fomula = token.nextToken(); String sigma = token.nextToken(); } // setp 2: read in thermoGAValue String thermo=""; for (int i=0;i<12;i++) { thermo = thermo.concat(token.nextToken()); thermo = thermo.concat(" "); } ThermoGAValue gaValue = ChemParser.parseThermoGAValue(thermo); String comments = ""; while (token.hasMoreTokens()) { comments = comments + " " + token.nextToken(); } ThermoGAValue newGaValue = new ThermoGAValue(name,gaValue,comments); // step3: read in graph of the functional group Graph g = ChemParser.readFGGraph(data); if (g == null) throw new NullGraphException(); FunctionalGroup fg = FunctionalGroup.make(name, g); // step4: put in library Object previous = p_library.put(fg, newGaValue); if (previous != null) { throw new ReplaceThermoGAValueException(); } line = ChemParser.readMeaningfulLine(data, true); } in.close(); return; } catch (IOException e) { throw new IOException(); } } //## operation readStandardDictionary(String) public HashMap readStandardDictionary(String p_fileName) throws FileNotFoundException, IOException { //#[ operation readStandardDictionary(String) try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HashMap dictionary = new HashMap(); HashMap unRead = new HashMap(); String line = ChemParser.readMeaningfulLine(data, true); read: while (line != null) { StringTokenizer st = new StringTokenizer(line); String fgname = st.nextToken(); data.mark(10000); line = ChemParser.readMeaningfulLine(data, true); if (line == null) break read; line = line.trim(); String prefix = line.substring(0,5); if (prefix.compareToIgnoreCase("union") == 0) { HashSet union = ChemParser.readUnion(line); unRead.put(fgname,union); } else { data.reset(); Graph fgGraph = null; try { fgGraph = ChemParser.readFGGraph(data); } catch (Exception e) { Logger.logStackTrace(e); throw new InvalidFunctionalGroupException(fgname + ": " + e.getMessage()); } if (fgGraph == null) throw new InvalidFunctionalGroupException(fgname); FunctionalGroup fg = FunctionalGroup.make(fgname, fgGraph); Object old = dictionary.get(fgname); if (old == null) { dictionary.put(fgname,fg); } else { FunctionalGroup oldFG = (FunctionalGroup)old; if (!oldFG.equals(fg)) throw new ReplaceFunctionalGroupException(fgname); } } //System.out.println(line); line = ChemParser.readMeaningfulLine(data, true); } while (!unRead.isEmpty()) { String fgname = (String)(unRead.keySet().iterator().next()); ChemParser.findUnion(fgname,unRead,dictionary); } in.close(); return dictionary; } catch (FileNotFoundException e) { throw new FileNotFoundException(p_fileName); } catch (IOException e) { throw new IOException(p_fileName + ": " + e.getMessage()); } } //## operation readStandardLibrary(String,HashMap) protected HashMap readStandardLibrary(String p_fileName, HashMap p_dictionary) throws IOException { try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HashMap library = new HashMap(); String line = ChemParser.readMeaningfulLine(data, true); while (line != null) { //System.out.println(line);// // step 1: read in index and name StringTokenizer token = new StringTokenizer(line); String index = token.nextToken(); //1/6/09 gmagoon changed index from integer to string, so that if/when ChemGreen/RMGVE adds a decimal after the entry number (after editing thermo library), RMG will still be able to read it String name = token.nextToken(); // step 2: find this functional group in dictionary by name Matchable fg = (Matchable)p_dictionary.get(name); if (fg == null) { throw new FunctionalGroupNotFoundException(); //System.out.println(name); } // step 3: read in thermoGAValue String thermo = token.nextToken(); // if there is a set of real thermo numbers, read them in and put the thermo data into library try { double H = Double.parseDouble(thermo); thermo = thermo.concat(" "); for (int i=0;i<11;i++) { thermo = thermo.concat(token.nextToken()); thermo = thermo.concat(" "); } ThermoGAValue gaValue = ChemParser.parseThermoGAValue(thermo); String comments = ""; while (token.hasMoreTokens()) { comments = comments + " " + token.nextToken(); } ThermoGAValue newGaValue=new ThermoGAValue(name,gaValue,comments); // step4: put in library Object previous = library.put(fg, newGaValue); if (previous != null) { throw new ReplaceThermoGAValueException(); } } // if there is a referenced name, put the name into library catch (NumberFormatException e) { Object o = p_dictionary.get(thermo); if (o == null) { //throw new FunctionalGroupNotFoundException(thermo); System.out.print(index); System.out.println(": " + thermo); } Object previous = library.put(fg, thermo); if (previous != null) { throw new ReplaceThermoGAValueException(); } } line = ChemParser.readMeaningfulLine(data, true); } // scan the library to give the ones having referenced name the real thermo data Iterator iter = library.keySet().iterator(); while (iter.hasNext()) { Matchable fg = (Matchable)iter.next(); Object gaValue = library.get(fg); String path = ""; if (gaValue instanceof String) { do { String name = (String)gaValue; path = path + "->" + name; gaValue = library.get((Matchable)p_dictionary.get(name)); } while (gaValue instanceof String); if (gaValue == null || !(gaValue instanceof ThermoGAValue)) { throw new InvalidReferenceThermoGAValueException(); } ThermoGAValue newGaValue = new ThermoGAValue(fg.getName(),(ThermoGAValue)gaValue, "Use the value of " + path); library.put(fg,newGaValue); } } in.close(); return library; } catch (IOException e) { throw new IOException(); } } //## operation readAbramLibrary(String,HashMap) protected HashMap readAbramLibrary(String p_fileName, HashMap p_dictionary) throws IOException { //#[ operation readStandardLibrary(String,HashMap) try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HashMap library = new HashMap(); String line = ChemParser.readMeaningfulLine(data, true); while (line != null) { // step 1: read in index and name StringTokenizer token = new StringTokenizer(line); String index = token.nextToken(); //1/6/09 gmagoon changed index from integer to string, so that if/when ChemGreen/RMGVE adds a decimal after the entry number (after editing thermo library), RMG will still be able to read it String name = token.nextToken(); // step 2: find this functional group in dictionary by name Matchable fg = (Matchable)p_dictionary.get(name); if (fg == null) { throw new FunctionalGroupNotFoundException(); //System.out.println(name); } // step 3: read in AbrahamGAValue String thermo = token.nextToken(); // if there is a set of real thermo numbers, read them in and put the thermo data into library try { double H = Double.parseDouble(thermo); thermo = thermo.concat(" "); for (int i=0;i<4;i++) { thermo = thermo.concat(token.nextToken()); thermo = thermo.concat(" "); } AbrahamGAValue gaValue = ChemParser.parseAbrahamGAValue(thermo); String comments = ""; while (token.hasMoreTokens()) { comments = comments + " " + token.nextToken(); } AbrahamGAValue newGaValue=new AbrahamGAValue(gaValue); // step4: put in library Object previous = library.put(fg, newGaValue); if (previous != null) { throw new ReplaceThermoGAValueException(); } } // if there is a referenced name, put the name into library catch (NumberFormatException e) { Object o = p_dictionary.get(thermo); if (o == null) { //throw new FunctionalGroupNotFoundException(thermo); System.out.print(index); System.out.println(": " + thermo); } Object previous = library.put(fg, thermo); if (previous != null) { throw new ReplaceThermoGAValueException(); } } line = ChemParser.readMeaningfulLine(data, true); } // scan the library to give the ones having referenced name the real thermo data Iterator iter = library.keySet().iterator(); while (iter.hasNext()) { Matchable fg = (Matchable)iter.next(); Object gaValue = library.get(fg); String path = ""; if (gaValue instanceof String) { do { String name = (String)gaValue; path = path + "->" + name; gaValue = library.get((Matchable)p_dictionary.get(name)); } while (gaValue instanceof String); if (gaValue == null || !(gaValue instanceof AbrahamGAValue)) { throw new InvalidReferenceThermoGAValueException(); } AbrahamGAValue newGaValue = new AbrahamGAValue((AbrahamGAValue)gaValue); library.put(fg,newGaValue); } } in.close(); return library; } catch (IOException e) { throw new IOException(); } } //## operation readAbramLibrary(String,HashMap) protected HashMap readUNIFACLibrary(String p_fileName, HashMap p_dictionary) throws IOException { try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HashMap library = new HashMap(); String line = ChemParser.readMeaningfulLine(data, true); while (line != null) { // step 1: read in index and name StringTokenizer token = new StringTokenizer(line); String index = token.nextToken(); //1/6/09 gmagoon changed index from integer to string, so that if/when ChemGreen/RMGVE adds a decimal after the entry number (after editing thermo library), RMG will still be able to read it String name = token.nextToken(); // step 2: find this functional group in dictionary by name Matchable fg = (Matchable)p_dictionary.get(name); if (fg == null) { throw new FunctionalGroupNotFoundException(); //System.out.println(name); } // step 3: read in AbrahamGAValue String thermo = token.nextToken(); // if there is a set of real thermo numbers, read them in and put the thermo data into library try { double H = Double.parseDouble(thermo); thermo = thermo.concat(" "); for (int i=0;i<1;i++) { thermo = thermo.concat(token.nextToken()); thermo = thermo.concat(" "); } UnifacGAValue gaValue = ChemParser.parseUnifacGAValue(thermo); String comments = ""; while (token.hasMoreTokens()) { comments = comments + " " + token.nextToken(); } UnifacGAValue newGaValue=new UnifacGAValue(gaValue); // step4: put in library Object previous = library.put(fg, newGaValue); if (previous != null) { throw new ReplaceThermoGAValueException(); } } // if there is a referenced name, put the name into library catch (NumberFormatException e) { Object o = p_dictionary.get(thermo); if (o == null) { //throw new FunctionalGroupNotFoundException(thermo); System.out.print(index); System.out.println(": " + thermo); } Object previous = library.put(fg, thermo); if (previous != null) { throw new ReplaceThermoGAValueException(); } } line = ChemParser.readMeaningfulLine(data, true); } // scan the library to give the ones having referenced name the real thermo data Iterator iter = library.keySet().iterator(); while (iter.hasNext()) { Matchable fg = (Matchable)iter.next(); Object gaValue = library.get(fg); String path = ""; if (gaValue instanceof String) { do { String name = (String)gaValue; path = path + "->" + name; gaValue = library.get((Matchable)p_dictionary.get(name)); } while (gaValue instanceof String); if (gaValue == null || !(gaValue instanceof UnifacGAValue)) { throw new InvalidReferenceThermoGAValueException(); } UnifacGAValue newGaValue = new UnifacGAValue((UnifacGAValue)gaValue); library.put(fg,newGaValue); } } in.close(); return library; } catch (IOException e) { throw new IOException(); } } //## operation readStandardTree(String,HashMap,int) public HierarchyTree readStandardTree(String p_fileName, HashMap p_dictionary, int p_level) throws IOException { //#[ operation readStandardTree(String,HashMap,int) try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HierarchyTree tree = ChemParser.readHierarchyTree(data,p_dictionary,p_level); in.close(); return tree; } catch (IOException e) { throw new IOException(p_fileName); } } protected static ThermoGAGroupLibrary getINSTANCE() { return INSTANCE; } public HashMap getGroupDictionary() { return groupDictionary; } public HashMap getGroupLibrary() { return groupLibrary; } public void setGroupLibrary(HashMap p_groupLibrary) { groupLibrary = p_groupLibrary; } protected HierarchyTree getGroupTree() { return groupTree; } public HashMap getOtherDictionary() { return otherDictionary; } public void setOtherDictionary(HashMap p_otherDictionary) { otherDictionary = p_otherDictionary; } public HashMap getOtherLibrary() { return otherLibrary; } public HierarchyTree getOtherTree() { return otherTree; } public void setOtherTree(HierarchyTree p_otherTree) { otherTree = p_otherTree; } public HashMap getRadicalDictionary() { return radicalDictionary; } public void setRadicalDictionary(HashMap p_radicalDictionary) { radicalDictionary = p_radicalDictionary; } protected HashMap getRadicalLibrary() { return radicalLibrary; } public HierarchyTree getRadicalTree() { return radicalTree; } public void setRadicalTree(HierarchyTree p_radicalTree) { radicalTree = p_radicalTree; } protected HashMap getRingLibrary() { return ringLibrary; } public ThermoGAValue findPolyCyclicRingCorrections( ChemGraph molecule) { int deepest = -1; Stack dummy = null; Iterator iterNodes = molecule.getGraph().getNodeList(); while(iterNodes.hasNext()){ //take first atom in this ring: Node node = (Node)iterNodes.next(); Atom atom = (Atom)node.getElement(); // make the current node the central atom molecule.resetThermoSite(node); // find the match in the thermo tree Stack stack = polycylicTree.findMatchedPath(molecule); // check if it's the deepest match if (!stack.empty()) { HierarchyTreeNode htn = (HierarchyTreeNode) stack.peek(); if (htn.getDepth() > deepest) { //we have found a Stack that is deeper than the previous ones, re-initialize Set: dummy = stack; deepest = htn.getDepth(); } } } if (dummy == null) return null; /* * If deepest node is L0, then none of the L1 nodes could be matched. * We should return null then. */ if(deepest == 0) return null; while (!dummy.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)dummy.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)polycyclicLibrary.get(fg); molecule.appendThermoComments("Polyclic ring system:" + fg.getName()); if (ga != null) return ga; } molecule.getGraph().resetMatchedGC(); return null; } } /********************************************************************* File Path : RMG\RMG\jing\chem\ThermoGAGroupLibrary.java *********************************************************************/
public ThermoGAValue findGAGroup(ChemGraph p_chemGraph) throws GroupNotFoundException, MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = groupTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC();//2/13/09 gmagoon: resetting the matched GC value...for some reason, thermoLibrary.findGAGroup (within getGAGroup in GATP.java) ended up modifiying the central node so that it was matched; this ended up wreaking havoc with subsequent symmetry number calculations; ideally, I would probably want to fix the code so that it didn't end up modifying the matchedGC from the null value after it is done with it, but I do not immediately see how to due so, and debugging proved extremely difficult; I have also tried to put this elsewhere in this class where it might be appropriate if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)groupLibrary.get(fg); p_chemGraph.appendThermoComments("Group:" + fg.getName()); if (ga != null) //{ //System.out.println("Group found: " + fg.getName()); return ga; //} } return null; //#] } //## operation findOtherCorrection(ChemGraph) public ThermoGAValue findOtherCorrection(ChemGraph p_chemGraph) { //#[ operation findOtherCorrection(ChemGraph) if (p_chemGraph == null) return null; Stack stack = otherTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); FunctionalGroup fg = (FunctionalGroup)node.getElement(); ThermoGAValue ga = (ThermoGAValue)otherLibrary.get(fg); p_chemGraph.appendThermoComments("Other:" + fg.getName()); if (ga != null) return ga; } return null; //#] } //## operation findRadicalGroup(ChemGraph) public ThermoGAValue findRadicalGroup(ChemGraph p_chemGraph) throws InvalidThermoCenterException { //#[ operation findRadicalGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = radicalTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)radicalLibrary.get(fg); p_chemGraph.appendThermoComments("Radical:" + fg.getName()); if (ga != null) return ga; } return null; //#] } //## operation findRingCorrection(ChemGraph) public Map<ThermoGAValue, Integer> findRingCorrections(ChemGraph p_chemGraph) { if (p_chemGraph == null) return null; Set<Node> fusedRingAtoms = p_chemGraph.getGraph().getFusedRingAtoms(); if(fusedRingAtoms != null){ p_chemGraph.appendThermoComments("!Fused Ring System!\n"); p_chemGraph.appendThermoComments("!Additive ring strain corrections might not be accurate!\n"); } List<Set<Node>> ringNodes = p_chemGraph.getGraph().getCycleNodes(); if(ringNodes == null){ Logger.error("Could not find ring nodes in graph."); return null; } else{ Map<Stack, Integer> deepestStackMap = null; deepestStackMap = new HashMap<Stack, Integer>(); for(Set<Node> set : ringNodes){ int deepest = -1; Stack dummy = null; Iterator iterNodes = set.iterator(); while(iterNodes.hasNext()){ //take first atom in this ring: Node node = (Node)iterNodes.next(); Atom atom = (Atom)node.getElement(); // make the current node the central atom p_chemGraph.resetThermoSite(node); // find the match in the thermo tree Stack stack = ringTree.findMatchedPath(p_chemGraph); // check if it's the deepest match if (!stack.empty()) { HierarchyTreeNode htn = (HierarchyTreeNode) stack.peek(); if (htn.getDepth() > deepest) { //we have found a Stack that is deeper than the previous ones, re-initialize Set: dummy = stack; deepest = htn.getDepth(); } } } if(deepestStackMap.containsKey(dummy)){ deepestStackMap.put(dummy, deepestStackMap.get(dummy)+1); } else{ deepestStackMap.put(dummy,1); } } if (deepestStackMap.keySet().isEmpty()) return null; //determine ThermoGAValues: Map<ThermoGAValue, Integer> GAMap = new HashMap<ThermoGAValue, Integer>(); for(Stack element : deepestStackMap.keySet()){ HierarchyTreeNode node = (HierarchyTreeNode)element.pop(); FunctionalGroup fg = (FunctionalGroup)node.getElement(); ThermoGAValue ga = (ThermoGAValue)ringLibrary.get(fg); p_chemGraph.appendThermoComments("!Ring:" + fg.getName()); if (ga != null) { if(GAMap.containsKey(ga)){ GAMap.put(ga, GAMap.get(ga)+1); } else{ GAMap.put(ga,1); } } } p_chemGraph.getGraph().resetMatchedGC(); if(GAMap.isEmpty()){ return null; } else{ return GAMap; } } } //2/5/09 gmagoon: new functions for gauche and 1,5-interactions /** Requires: the central node of p_chemGraph has been set to the thermo center atom. Effects: find a matched thermo functional group in the group tree for the pass-in p_chemGraph, return this functional group's thermo value. If no leaf is found, throw GroupNotFoundException Modifies: */ public ThermoGAValue findGaucheGroup(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = gaucheTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)gaucheLibrary.get(fg); p_chemGraph.appendThermoComments("Gauche:" + fg.getName()); if (ga != null) return ga; } return null; } /** Requires: the central node of p_chemGraph has been set to the thermo center atom. Effects: find a matched thermo functional group in the group tree for the pass-in p_chemGraph, return this functional group's thermo value. If no leaf is found, throw GroupNotFoundException Modifies: */ public ThermoGAValue find15Group(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = oneFiveTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)oneFiveLibrary.get(fg); p_chemGraph.appendThermoComments("1,5:" + fg.getName()); if (ga != null) return ga; } return null; } public AbrahamGAValue findAbrahamGroup(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = abramTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); AbrahamGAValue ga = (AbrahamGAValue)abramLibrary.get(fg); if (ga != null) { //System.out.println("Platts Group found: " + fg.getName()); return ga; } } return null; } //Added by Amrit Jalan on December 13, 2010 public AbrahamGAValue findAbrahamradGroup(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findRadicalGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = abramradTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); AbrahamGAValue ga = (AbrahamGAValue)abramradLibrary.get(fg); if (ga != null) return ga; } return null; } public UnifacGAValue findUnifacGroup(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = unifacTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); UnifacGAValue ga = (UnifacGAValue)unifacLibrary.get(fg); if (ga != null) { //System.out.println("Unifac Group found: " + fg.getName()); return ga; } } return null; } //## operation read(String,String,String,String,String,String,String,String,String) public void read(String p_groupDictionary, String p_groupTree, String p_groupLibrary, String p_radicalDictionary, String p_radicalTree, String p_radicalLibrary, String p_ringDictionary, String p_ringTree, String p_ringLibrary, String p_otherDictionary, String p_otherLibrary, String p_otherTree, String p_gaucheDictionary, String p_gaucheTree, String p_gaucheLibrary, String p_15Dictionary, String p_15Tree, String p_15Library,String p_abramDictionary,String p_abramTree,String p_abramLibrary,String p_unifacDictionary,String p_unifacTree,String p_unifacLibrary,String p_abramradDictionary,String p_abramradTree,String p_abramradLibrary, String polycyclicDictionary,String polycyclicTree,String polycyclicLibrary) { //,String p_solventDictionary,String p_solventLibrary) { // step 1: read in GA Groups Logger.info("Reading thermochemistry groups"); // read thermo functional Group dictionary readGroupDictionary(p_groupDictionary); // read thermo functional Group tree structure readGroupTree(p_groupTree); // read group values readGroupLibrary(p_groupLibrary); // step 2: read in Radical Corrections Logger.info("Reading radical correction groups"); // read radical dictionary readRadicalDictionary(p_radicalDictionary); // read radical tree readRadicalTree(p_radicalTree); // read radical value readRadicalLibrary(p_radicalLibrary); // step 3: read in Ring Correction Logger.info("Reading ring correction groups"); readRingDictionary(p_ringDictionary); readRingTree(p_ringTree); readRingLibrary(p_ringLibrary); // step 4: read in Other Correction Logger.info("Reading other correction groups"); readOtherDictionary(p_otherDictionary); readOtherLibrary(p_otherLibrary); readOtherTree(p_otherTree); // step 5: read in Gauche and 15 Correction libraries Logger.info("Reading gauche and 1/5 correction groups"); readGaucheDictionary(p_gaucheDictionary); readGaucheTree(p_gaucheTree); readGaucheLibrary(p_gaucheLibrary); read15Dictionary(p_15Dictionary); read15Tree(p_15Tree); read15Library(p_15Library); if (Species.useSolvation) { // Definitions of Platts dictionary, library and tree for Abraham Model Implementation Logger.info("Reading Abraham solvation groups"); readAbrahamDictionary(p_abramDictionary); readAbrahamTree(p_abramTree); readAbrahamLibrary(p_abramLibrary); Logger.info("Reading Abraham radical solvation groups"); readAbrahamradDictionary(p_abramradDictionary); readAbrahamradTree(p_abramradTree); readAbrahamradLibrary(p_abramradLibrary); /* We no longer need UNIFAC groups, and loading them reports some errors, so let's not bother. Logger.info("Reading UNIFAC solvation groups"); readUnifacDictionary(p_unifacDictionary); readUnifacTree(p_unifacTree); readUnifacLibrary(p_unifacLibrary); */ } // step 6: read in Polyclic ring libraries Logger.info("Reading polycyclic groups"); readPolycyclicDictionary(polycyclicDictionary); readPolycyclicTree(polycyclicTree); readPolycyclicLibrary(polycyclicLibrary); } private void readPolycyclicTree(String polycyclicTree2) { try { polycylicTree = readStandardTree(polycyclicTree2,polycyclicDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read polycylic tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } private void readPolycyclicLibrary(String polycyclicLibrary2) { try { polycyclicLibrary = readStandardLibrary(polycyclicLibrary2, polycyclicDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read polycylic library!"); System.exit(0); } } private void readPolycyclicDictionary(String polycyclicDictionary2) { try { polycyclicDictionary = readStandardDictionary(polycyclicDictionary2); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read polyclic dictionary!"); System.exit(0); } } //## operation readGroupDictionary(String) public void readGroupDictionary(String p_fileName) { //#[ operation readGroupDictionary(String) try { groupDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read group dictionary!"); System.exit(0); } //#] } //## operation readGroupLibrary(String) public void readGroupLibrary(String p_fileName) { try { groupLibrary = readStandardLibrary(p_fileName, groupDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Group Library!"); System.exit(0); } } //## operation readGroupTree(String) public void readGroupTree(String p_fileName) { try { groupTree = readStandardTree(p_fileName,groupDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read thermo group tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //## operation readOtherDictionary(String) public void readOtherDictionary(String p_fileName) { try { otherDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read other dictionary!"); System.exit(0); } } //## operation readOtherLibrary(String) public void readOtherLibrary(String p_fileName) { try { otherLibrary = readStandardLibrary(p_fileName, otherDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Other Library!"); System.exit(0); } } //## operation readOtherTree(String) public void readOtherTree(String p_fileName) { try { otherTree = readStandardTree(p_fileName,otherDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read thermo Other tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //2/5/09 gmagoon: new functions for gauche and 1,5 correction reading (based on analogs for regular values, e.g. readGroupDictionary) public void readGaucheDictionary(String p_fileName) { try { gaucheDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read gauche dictionary!"); System.exit(0); } } public void readGaucheLibrary(String p_fileName) { try { gaucheLibrary = readStandardLibrary(p_fileName, gaucheDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read gauche library!"); System.exit(0); } } public void readGaucheTree(String p_fileName) { try { gaucheTree = readStandardTree(p_fileName,gaucheDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read gauche tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } public void readAbrahamDictionary(String p_fileName) { try { abramDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read Abraham dictionary!"); System.exit(0); } } //Added by Amrit Jalan on December 13, 2010 public void readAbrahamradDictionary(String p_fileName) { try { abramradDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read Abraham Radical dictionary!"); System.exit(0); } } public void readUnifacDictionary(String p_fileName) { try { unifacDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read Unifac dictionary!"); System.exit(0); } } public void readAbrahamLibrary(String p_fileName) { try { abramLibrary = readAbramLibrary(p_fileName, abramDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Abraham library!"); System.exit(0); } } //Added by Amrit Jalan on December 13, 2010 public void readAbrahamradLibrary(String p_fileName) { try { abramradLibrary = readAbramLibrary(p_fileName, abramradDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Abraham library!"); System.exit(0); } } public void readUnifacLibrary(String p_fileName) { try { unifacLibrary = readUNIFACLibrary(p_fileName, unifacDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Unifac library!"); System.exit(0); } } public void readAbrahamTree(String p_fileName) { try { abramTree = readStandardTree(p_fileName,abramDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Abraham tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //Added by Amrit Jalan on December 13, 2010 public void readAbrahamradTree(String p_fileName) { try { abramradTree = readStandardTree(p_fileName,abramradDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Abraham Radical tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } public void readUnifacTree(String p_fileName) { try { unifacTree = readStandardTree(p_fileName,unifacDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Unifac tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //public void readSolventDictionary(String p_fileName) { //try { // solventDictionary = readStandard/Dictionary(p_fileName); // return; //} //catch (Exception e) { // Logger.logStackTrace(e); // Logger.critical("Error in read Solvent dictionary!"); // System.exit(0); //} //#] //} // public void readSolventLibrary(String p_fileName) { // try { // solventLibrary = readStandardLibrary(p_fileName, solventDictionary); // return; // } // catch (Exception e) { // Logger.logStackTrace(e); // Logger.critical("Can't read solvent library!"); // System.exit(0); // } //#] //} public void read15Dictionary(String p_fileName) { try { oneFiveDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read 1,5 dictionary!"); System.exit(0); } } public void read15Library(String p_fileName) { try { oneFiveLibrary = readStandardLibrary(p_fileName, oneFiveDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read 1,5 library!"); System.exit(0); } } public void read15Tree(String p_fileName) { try { oneFiveTree = readStandardTree(p_fileName,oneFiveDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read 1,5 tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //## operation readRadicalDictionary(String) public void readRadicalDictionary(String p_fileName) { try { radicalDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read radical dictionary!\n" + e.getMessage()); System.exit(0); } } //## operation readRadicalLibrary(String) public void readRadicalLibrary(String p_fileName) { try { radicalLibrary = readStandardLibrary(p_fileName, radicalDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read radical Library!"); System.exit(0); } } //## operation readRadicalTree(String) public void readRadicalTree(String p_fileName) { try { radicalTree = readStandardTree(p_fileName,radicalDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read thermo group tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //## operation readRingLibrary(String) public void readRingDictionary(String p_fileName) { try { ringDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read ring dictionary!\n" + e.getMessage()); System.exit(0); } } //## operation readRingTree(String) public void readRingTree(String p_fileName) { try { ringTree = readStandardTree(p_fileName,ringDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read ring tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } // end pey //## operation readRingLibrary(String) public void readRingLibrary(String p_fileName) { try { ringLibrary = readStandardLibrary(p_fileName, ringDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Ring Correction Library!"); Logger.critical("Error: " + e); System.exit(0); } } //## operation readStandardCorrectionLibrary(String,HashMap) protected void readStandardCorrectionLibrary(String p_fileName, HashMap p_library) throws IOException { try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); String line = ChemParser.readMeaningfulLine(data, true); while (line != null) { // step 1: read in index and name StringTokenizer token = new StringTokenizer(line); int index = Integer.parseInt(token.nextToken()); String name = token.nextToken(); if (p_library == ringLibrary) { String fomula = token.nextToken(); String sigma = token.nextToken(); } // setp 2: read in thermoGAValue String thermo=""; for (int i=0;i<12;i++) { thermo = thermo.concat(token.nextToken()); thermo = thermo.concat(" "); } ThermoGAValue gaValue = ChemParser.parseThermoGAValue(thermo); String comments = ""; while (token.hasMoreTokens()) { comments = comments + " " + token.nextToken(); } ThermoGAValue newGaValue = new ThermoGAValue(name,gaValue,comments); // step3: read in graph of the functional group Graph g = ChemParser.readFGGraph(data); if (g == null) throw new NullGraphException(); FunctionalGroup fg = FunctionalGroup.make(name, g); // step4: put in library Object previous = p_library.put(fg, newGaValue); if (previous != null) { throw new ReplaceThermoGAValueException(); } line = ChemParser.readMeaningfulLine(data, true); } in.close(); return; } catch (IOException e) { throw new IOException(); } } //## operation readStandardDictionary(String) public HashMap readStandardDictionary(String p_fileName) throws FileNotFoundException, IOException { //#[ operation readStandardDictionary(String) try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HashMap dictionary = new HashMap(); HashMap unRead = new HashMap(); String line = ChemParser.readMeaningfulLine(data, true); read: while (line != null) { StringTokenizer st = new StringTokenizer(line); String fgname = st.nextToken(); data.mark(10000); line = ChemParser.readMeaningfulLine(data, true); if (line == null) break read; line = line.trim(); String prefix = line.substring(0,5); if (prefix.compareToIgnoreCase("union") == 0) { HashSet union = ChemParser.readUnion(line); unRead.put(fgname,union); } else { data.reset(); Graph fgGraph = null; try { fgGraph = ChemParser.readFGGraph(data); } catch (Exception e) { Logger.logStackTrace(e); throw new InvalidFunctionalGroupException(fgname + ": " + e.getMessage()); } if (fgGraph == null) throw new InvalidFunctionalGroupException(fgname); FunctionalGroup fg = FunctionalGroup.make(fgname, fgGraph); Object old = dictionary.get(fgname); if (old == null) { dictionary.put(fgname,fg); } else { FunctionalGroup oldFG = (FunctionalGroup)old; if (!oldFG.equals(fg)) throw new ReplaceFunctionalGroupException(fgname); } } //System.out.println(line); line = ChemParser.readMeaningfulLine(data, true); } while (!unRead.isEmpty()) { String fgname = (String)(unRead.keySet().iterator().next()); ChemParser.findUnion(fgname,unRead,dictionary); } in.close(); return dictionary; } catch (FileNotFoundException e) { throw new FileNotFoundException(p_fileName); } catch (IOException e) { throw new IOException(p_fileName + ": " + e.getMessage()); } } //## operation readStandardLibrary(String,HashMap) protected HashMap readStandardLibrary(String p_fileName, HashMap p_dictionary) throws IOException { try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HashMap library = new HashMap(); String line = ChemParser.readMeaningfulLine(data, true); while (line != null) { //System.out.println(line);// // step 1: read in index and name StringTokenizer token = new StringTokenizer(line); String index = token.nextToken(); //1/6/09 gmagoon changed index from integer to string, so that if/when ChemGreen/RMGVE adds a decimal after the entry number (after editing thermo library), RMG will still be able to read it String name = token.nextToken(); // step 2: find this functional group in dictionary by name Matchable fg = (Matchable)p_dictionary.get(name); if (fg == null) { throw new FunctionalGroupNotFoundException(); //System.out.println(name); } // step 3: read in thermoGAValue String thermo = token.nextToken(); // if there is a set of real thermo numbers, read them in and put the thermo data into library try { double H = Double.parseDouble(thermo); thermo = thermo.concat(" "); for (int i=0;i<11;i++) { thermo = thermo.concat(token.nextToken()); thermo = thermo.concat(" "); } ThermoGAValue gaValue = ChemParser.parseThermoGAValue(thermo); String comments = ""; while (token.hasMoreTokens()) { comments = comments + " " + token.nextToken(); } ThermoGAValue newGaValue=new ThermoGAValue(name,gaValue,comments); // step4: put in library Object previous = library.put(fg, newGaValue); if (previous != null) { throw new ReplaceThermoGAValueException(); } } // if there is a referenced name, put the name into library catch (NumberFormatException e) { Object o = p_dictionary.get(thermo); if (o == null) { //throw new FunctionalGroupNotFoundException(thermo); System.out.print(index); System.out.println(": " + thermo); } Object previous = library.put(fg, thermo); if (previous != null) { throw new ReplaceThermoGAValueException(); } } line = ChemParser.readMeaningfulLine(data, true); } // scan the library to give the ones having referenced name the real thermo data Iterator iter = library.keySet().iterator(); while (iter.hasNext()) { Matchable fg = (Matchable)iter.next(); Object gaValue = library.get(fg); String path = ""; if (gaValue instanceof String) { do { String name = (String)gaValue; path = path + "->" + name; gaValue = library.get((Matchable)p_dictionary.get(name)); } while (gaValue instanceof String); if (gaValue == null || !(gaValue instanceof ThermoGAValue)) { throw new InvalidReferenceThermoGAValueException(); } ThermoGAValue newGaValue = new ThermoGAValue(fg.getName(),(ThermoGAValue)gaValue, "Use the value of " + path); library.put(fg,newGaValue); } } in.close(); return library; } catch (IOException e) { throw new IOException(); } } //## operation readAbramLibrary(String,HashMap) protected HashMap readAbramLibrary(String p_fileName, HashMap p_dictionary) throws IOException { //#[ operation readStandardLibrary(String,HashMap) try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HashMap library = new HashMap(); String line = ChemParser.readMeaningfulLine(data, true); while (line != null) { // step 1: read in index and name StringTokenizer token = new StringTokenizer(line); String index = token.nextToken(); //1/6/09 gmagoon changed index from integer to string, so that if/when ChemGreen/RMGVE adds a decimal after the entry number (after editing thermo library), RMG will still be able to read it String name = token.nextToken(); // step 2: find this functional group in dictionary by name Matchable fg = (Matchable)p_dictionary.get(name); if (fg == null) { throw new FunctionalGroupNotFoundException(); //System.out.println(name); } // step 3: read in AbrahamGAValue String thermo = token.nextToken(); // if there is a set of real thermo numbers, read them in and put the thermo data into library try { double H = Double.parseDouble(thermo); thermo = thermo.concat(" "); for (int i=0;i<4;i++) { thermo = thermo.concat(token.nextToken()); thermo = thermo.concat(" "); } AbrahamGAValue gaValue = ChemParser.parseAbrahamGAValue(thermo); String comments = ""; while (token.hasMoreTokens()) { comments = comments + " " + token.nextToken(); } AbrahamGAValue newGaValue=new AbrahamGAValue(gaValue); // step4: put in library Object previous = library.put(fg, newGaValue); if (previous != null) { throw new ReplaceThermoGAValueException(); } } // if there is a referenced name, put the name into library catch (NumberFormatException e) { Object o = p_dictionary.get(thermo); if (o == null) { //throw new FunctionalGroupNotFoundException(thermo); System.out.print(index); System.out.println(": " + thermo); } Object previous = library.put(fg, thermo); if (previous != null) { throw new ReplaceThermoGAValueException(); } } line = ChemParser.readMeaningfulLine(data, true); } // scan the library to give the ones having referenced name the real thermo data Iterator iter = library.keySet().iterator(); while (iter.hasNext()) { Matchable fg = (Matchable)iter.next(); Object gaValue = library.get(fg); String path = ""; if (gaValue instanceof String) { do { String name = (String)gaValue; path = path + "->" + name; gaValue = library.get((Matchable)p_dictionary.get(name)); } while (gaValue instanceof String); if (gaValue == null || !(gaValue instanceof AbrahamGAValue)) { throw new InvalidReferenceThermoGAValueException(); } AbrahamGAValue newGaValue = new AbrahamGAValue((AbrahamGAValue)gaValue); library.put(fg,newGaValue); } } in.close(); return library; } catch (IOException e) { throw new IOException(); } } //## operation readAbramLibrary(String,HashMap) protected HashMap readUNIFACLibrary(String p_fileName, HashMap p_dictionary) throws IOException { try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HashMap library = new HashMap(); String line = ChemParser.readMeaningfulLine(data, true); while (line != null) { // step 1: read in index and name StringTokenizer token = new StringTokenizer(line); String index = token.nextToken(); //1/6/09 gmagoon changed index from integer to string, so that if/when ChemGreen/RMGVE adds a decimal after the entry number (after editing thermo library), RMG will still be able to read it String name = token.nextToken(); // step 2: find this functional group in dictionary by name Matchable fg = (Matchable)p_dictionary.get(name); if (fg == null) { throw new FunctionalGroupNotFoundException(); //System.out.println(name); } // step 3: read in AbrahamGAValue String thermo = token.nextToken(); // if there is a set of real thermo numbers, read them in and put the thermo data into library try { double H = Double.parseDouble(thermo); thermo = thermo.concat(" "); for (int i=0;i<1;i++) { thermo = thermo.concat(token.nextToken()); thermo = thermo.concat(" "); } UnifacGAValue gaValue = ChemParser.parseUnifacGAValue(thermo); String comments = ""; while (token.hasMoreTokens()) { comments = comments + " " + token.nextToken(); } UnifacGAValue newGaValue=new UnifacGAValue(gaValue); // step4: put in library Object previous = library.put(fg, newGaValue); if (previous != null) { throw new ReplaceThermoGAValueException(); } } // if there is a referenced name, put the name into library catch (NumberFormatException e) { Object o = p_dictionary.get(thermo); if (o == null) { //throw new FunctionalGroupNotFoundException(thermo); System.out.print(index); System.out.println(": " + thermo); } Object previous = library.put(fg, thermo); if (previous != null) { throw new ReplaceThermoGAValueException(); } } line = ChemParser.readMeaningfulLine(data, true); } // scan the library to give the ones having referenced name the real thermo data Iterator iter = library.keySet().iterator(); while (iter.hasNext()) { Matchable fg = (Matchable)iter.next(); Object gaValue = library.get(fg); String path = ""; if (gaValue instanceof String) { do { String name = (String)gaValue; path = path + "->" + name; gaValue = library.get((Matchable)p_dictionary.get(name)); } while (gaValue instanceof String); if (gaValue == null || !(gaValue instanceof UnifacGAValue)) { throw new InvalidReferenceThermoGAValueException(); } UnifacGAValue newGaValue = new UnifacGAValue((UnifacGAValue)gaValue); library.put(fg,newGaValue); } } in.close(); return library; } catch (IOException e) { throw new IOException(); } } //## operation readStandardTree(String,HashMap,int) public HierarchyTree readStandardTree(String p_fileName, HashMap p_dictionary, int p_level) throws IOException { //#[ operation readStandardTree(String,HashMap,int) try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HierarchyTree tree = ChemParser.readHierarchyTree(data,p_dictionary,p_level); in.close(); return tree; } catch (IOException e) { throw new IOException(p_fileName); } } protected static ThermoGAGroupLibrary getINSTANCE() { return INSTANCE; } public HashMap getGroupDictionary() { return groupDictionary; } public HashMap getGroupLibrary() { return groupLibrary; } public void setGroupLibrary(HashMap p_groupLibrary) { groupLibrary = p_groupLibrary; } protected HierarchyTree getGroupTree() { return groupTree; } public HashMap getOtherDictionary() { return otherDictionary; } public void setOtherDictionary(HashMap p_otherDictionary) { otherDictionary = p_otherDictionary; } public HashMap getOtherLibrary() { return otherLibrary; } public HierarchyTree getOtherTree() { return otherTree; } public void setOtherTree(HierarchyTree p_otherTree) { otherTree = p_otherTree; } public HashMap getRadicalDictionary() { return radicalDictionary; } public void setRadicalDictionary(HashMap p_radicalDictionary) { radicalDictionary = p_radicalDictionary; } protected HashMap getRadicalLibrary() { return radicalLibrary; } public HierarchyTree getRadicalTree() { return radicalTree; } public void setRadicalTree(HierarchyTree p_radicalTree) { radicalTree = p_radicalTree; } protected HashMap getRingLibrary() { return ringLibrary; } public ThermoGAValue findPolyCyclicRingCorrections( ChemGraph molecule) { int deepest = -1; Stack dummy = null; Iterator iterNodes = molecule.getGraph().getNodeList(); while(iterNodes.hasNext()){ //take first atom in this ring: Node node = (Node)iterNodes.next(); Atom atom = (Atom)node.getElement(); // make the current node the central atom molecule.resetThermoSite(node); // find the match in the thermo tree Stack stack = polycylicTree.findMatchedPath(molecule); // check if it's the deepest match if (!stack.empty()) { HierarchyTreeNode htn = (HierarchyTreeNode) stack.peek(); if (htn.getDepth() > deepest) { //we have found a Stack that is deeper than the previous ones, re-initialize Set: dummy = stack; deepest = htn.getDepth(); } } } if (dummy == null) return null; /* * If deepest node is L0, then none of the L1 nodes could be matched. * We should return null then. */ if(deepest == 0) return null; while (!dummy.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)dummy.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)polycyclicLibrary.get(fg); molecule.appendThermoComments("Polycyclic ring system:" + fg.getName()); if (ga != null) return ga; } molecule.getGraph().resetMatchedGC(); return null; } } /********************************************************************* File Path : RMG\RMG\jing\chem\ThermoGAGroupLibrary.java *********************************************************************/
diff --git a/mini2Dx-core/src/main/java/org/mini2Dx/core/audio/CrossFadingMusicLoop.java b/mini2Dx-core/src/main/java/org/mini2Dx/core/audio/CrossFadingMusicLoop.java index 1b7c1da35..cd7445269 100644 --- a/mini2Dx-core/src/main/java/org/mini2Dx/core/audio/CrossFadingMusicLoop.java +++ b/mini2Dx-core/src/main/java/org/mini2Dx/core/audio/CrossFadingMusicLoop.java @@ -1,160 +1,162 @@ /** * Copyright (c) 2013, mini2Dx Project * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the mini2Dx nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.mini2Dx.core.audio; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.math.MathUtils; /** * Implements a loopable music track and crossfades into itself * * @author Thomas Cashman */ public class CrossFadingMusicLoop implements Runnable { private Music currentTrack, nextTrack; private long crossfadeTime, crossfadeDuration; private ScheduledExecutorService scheduledExecutorService; private ScheduledFuture<?> scheduledFuture; private float targetVolume = 1f; /** * Constructor * * @param musicFile * The {@link FileHandle} for the music to be looped * @param crossfadeTime * The time at which the crossfade begins at the end of the track * @param timeUnit * The {@link TimeUnit} for crossfadeTime */ public CrossFadingMusicLoop(FileHandle musicFile, long crossfadeTime, long crossfadeDuration, TimeUnit timeUnit) { this.currentTrack = Gdx.audio.newMusic(musicFile); this.nextTrack = Gdx.audio.newMusic(musicFile); this.crossfadeTime = timeUnit.toMillis(crossfadeTime); this.crossfadeDuration = timeUnit.toMillis(crossfadeDuration); this.scheduledExecutorService = new ScheduledThreadPoolExecutor(1); } @Override public void run() { nextTrack.play(); nextTrack.setVolume(0f); Music tempTrack = currentTrack; currentTrack = nextTrack; nextTrack = tempTrack; scheduleFadeIn(); scheduleFadeOut(); } private void scheduleFadeIn() { for (int i = 0; i < crossfadeDuration; i += 50) { float volume = MathUtils.clamp((i / crossfadeDuration), 0f, targetVolume) ; scheduledExecutorService.schedule(new ScheduleFadeIn(volume), i, TimeUnit.MILLISECONDS); } } private void scheduleFadeOut() { for (int i = 0; i < crossfadeDuration; i += 50) { float volume = MathUtils.clamp(1f - (i / crossfadeDuration), 0f, targetVolume) ; scheduledExecutorService.schedule(new ScheduleFadeOut(volume), i, TimeUnit.MILLISECONDS); } } /** * Starts playing the loop */ public void play() { currentTrack.setVolume(targetVolume); currentTrack.play(); long time = (long) crossfadeTime; scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, time, time, TimeUnit.MILLISECONDS); } /** * Stops playing the loop */ public void stop() { - scheduledFuture.cancel(false); - while (!scheduledFuture.isDone()) { - try { - Thread.sleep(1); - } catch (Exception e) { + if(scheduledFuture != null) { + scheduledFuture.cancel(false); + while (!scheduledFuture.isDone()) { + try { + Thread.sleep(1); + } catch (Exception e) { + } } } currentTrack.stop(); nextTrack.stop(); scheduledFuture = null; } /** * Returns if the loop is playing * * @return True if playing */ public boolean isPlaying() { return scheduledFuture != null; } /** * Cleans up resources. To be called when this instance is no longer needed. */ public void dispose() { if (isPlaying()) { throw new RuntimeException( "Cannot dispose of a music instance that is currently playing"); } currentTrack.dispose(); nextTrack.dispose(); } public void setVolume(float volume) { targetVolume = volume; if(currentTrack.isPlaying()) { currentTrack.setVolume(targetVolume); } } private class ScheduleFadeOut implements Runnable { private float volume; public ScheduleFadeOut(float volume) { this.volume = volume; } public void run() { nextTrack.setVolume(volume); } } private class ScheduleFadeIn implements Runnable { private float volume; public ScheduleFadeIn(float volume) { this.volume = volume; } public void run() { currentTrack.setVolume(volume); } } }
true
true
public void stop() { scheduledFuture.cancel(false); while (!scheduledFuture.isDone()) { try { Thread.sleep(1); } catch (Exception e) { } } currentTrack.stop(); nextTrack.stop(); scheduledFuture = null; }
public void stop() { if(scheduledFuture != null) { scheduledFuture.cancel(false); while (!scheduledFuture.isDone()) { try { Thread.sleep(1); } catch (Exception e) { } } } currentTrack.stop(); nextTrack.stop(); scheduledFuture = null; }
diff --git a/src/web/core/src/main/java/org/geoserver/web/data/layer/NewLayerPageProvider.java b/src/web/core/src/main/java/org/geoserver/web/data/layer/NewLayerPageProvider.java index 1c7ff298d7..c5323f1a5a 100644 --- a/src/web/core/src/main/java/org/geoserver/web/data/layer/NewLayerPageProvider.java +++ b/src/web/core/src/main/java/org/geoserver/web/data/layer/NewLayerPageProvider.java @@ -1,131 +1,132 @@ /* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the GPL 2.0 license, available at the root * application directory. */ package org.geoserver.web.data.layer; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.geoserver.catalog.CatalogBuilder; import org.geoserver.catalog.CoverageInfo; import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.ResourceInfo; import org.geoserver.catalog.StoreInfo; import org.geoserver.web.wicket.GeoServerDataProvider; import org.opengis.feature.type.Name; /** * Provides a list of resources for a specific data store * @author Andrea Aime - OpenGeo * */ @SuppressWarnings("serial") public class NewLayerPageProvider extends GeoServerDataProvider<Resource> { public static final Property<Resource> NAME = new BeanProperty<Resource>("name", "localName"); public static final Property<Resource> PUBLISHED = new BeanProperty<Resource>("published", "published"); public static final List<Property<Resource>> PROPERTIES = Arrays.asList(NAME, PUBLISHED); boolean showPublished; String storeId; @Override protected List<Resource> getItems() { // return an empty list in case we still don't know about the store if(storeId == null) return new ArrayList<Resource>(); // else, grab the resource list try { List<Resource> result; StoreInfo store = getCatalog().getStore(storeId, StoreInfo.class); Map<String, Resource> resources = new HashMap<String, Resource>(); if(store instanceof DataStoreInfo) { DataStoreInfo dstore = (DataStoreInfo) store; // collect all the type names and turn them into resources // for the moment we use local names as datastores are not returning // namespace qualified NameImpl List<Name> names = dstore.getDataStore(null).getNames(); for (Name name : names) { resources.put(name.getLocalPart(), new Resource(name)); } } else { // getting to the coverage name without reading the whole coverage seems to // be hard stuff, let's have the catalog builder to the heavy lifting CatalogBuilder builder = new CatalogBuilder(getCatalog()); builder.setStore(store); CoverageInfo ci = builder.buildCoverage(); Name name = ci.getQualifiedName(); resources.put(name.getLocalPart(), new Resource(name)); } // lookup all configured layers, mark them as published in the resources List<ResourceInfo> configuredTypes = getCatalog().getResourcesByStore(store, ResourceInfo.class); for (ResourceInfo type : configuredTypes) { // compare with native name, which is what the DataStore provides through getNames() // above Resource resource = resources.get(type.getNativeName()); if(resource != null) resource.setPublished(true); } result = new ArrayList<Resource>(resources.values()); // return by natural order Collections.sort(result); return result; } catch(Exception e) { - throw new RuntimeException("Could not list layers for this store, an error occurred retrieving them", e); + throw new RuntimeException("Could not list layers for this store, " + + "an error occurred retrieving them: " + e.getMessage(), e); } } public String getStoreId() { return storeId; } public void setStoreId(String storeId) { this.storeId = storeId; } @Override protected List<Resource> getFilteredItems() { List<Resource> resources = super.getFilteredItems(); if(showPublished) return resources; List<Resource> unconfigured = new ArrayList<Resource>(); for (Resource resource : resources) { if(!resource.isPublished()) unconfigured.add(resource); } return unconfigured; } @Override protected List<Property<Resource>> getProperties() { return PROPERTIES; } public IModel model(Object object) { return new Model((Serializable) object); } public void setShowPublished(boolean showPublished) { this.showPublished = showPublished; } }
true
true
protected List<Resource> getItems() { // return an empty list in case we still don't know about the store if(storeId == null) return new ArrayList<Resource>(); // else, grab the resource list try { List<Resource> result; StoreInfo store = getCatalog().getStore(storeId, StoreInfo.class); Map<String, Resource> resources = new HashMap<String, Resource>(); if(store instanceof DataStoreInfo) { DataStoreInfo dstore = (DataStoreInfo) store; // collect all the type names and turn them into resources // for the moment we use local names as datastores are not returning // namespace qualified NameImpl List<Name> names = dstore.getDataStore(null).getNames(); for (Name name : names) { resources.put(name.getLocalPart(), new Resource(name)); } } else { // getting to the coverage name without reading the whole coverage seems to // be hard stuff, let's have the catalog builder to the heavy lifting CatalogBuilder builder = new CatalogBuilder(getCatalog()); builder.setStore(store); CoverageInfo ci = builder.buildCoverage(); Name name = ci.getQualifiedName(); resources.put(name.getLocalPart(), new Resource(name)); } // lookup all configured layers, mark them as published in the resources List<ResourceInfo> configuredTypes = getCatalog().getResourcesByStore(store, ResourceInfo.class); for (ResourceInfo type : configuredTypes) { // compare with native name, which is what the DataStore provides through getNames() // above Resource resource = resources.get(type.getNativeName()); if(resource != null) resource.setPublished(true); } result = new ArrayList<Resource>(resources.values()); // return by natural order Collections.sort(result); return result; } catch(Exception e) { throw new RuntimeException("Could not list layers for this store, an error occurred retrieving them", e); } }
protected List<Resource> getItems() { // return an empty list in case we still don't know about the store if(storeId == null) return new ArrayList<Resource>(); // else, grab the resource list try { List<Resource> result; StoreInfo store = getCatalog().getStore(storeId, StoreInfo.class); Map<String, Resource> resources = new HashMap<String, Resource>(); if(store instanceof DataStoreInfo) { DataStoreInfo dstore = (DataStoreInfo) store; // collect all the type names and turn them into resources // for the moment we use local names as datastores are not returning // namespace qualified NameImpl List<Name> names = dstore.getDataStore(null).getNames(); for (Name name : names) { resources.put(name.getLocalPart(), new Resource(name)); } } else { // getting to the coverage name without reading the whole coverage seems to // be hard stuff, let's have the catalog builder to the heavy lifting CatalogBuilder builder = new CatalogBuilder(getCatalog()); builder.setStore(store); CoverageInfo ci = builder.buildCoverage(); Name name = ci.getQualifiedName(); resources.put(name.getLocalPart(), new Resource(name)); } // lookup all configured layers, mark them as published in the resources List<ResourceInfo> configuredTypes = getCatalog().getResourcesByStore(store, ResourceInfo.class); for (ResourceInfo type : configuredTypes) { // compare with native name, which is what the DataStore provides through getNames() // above Resource resource = resources.get(type.getNativeName()); if(resource != null) resource.setPublished(true); } result = new ArrayList<Resource>(resources.values()); // return by natural order Collections.sort(result); return result; } catch(Exception e) { throw new RuntimeException("Could not list layers for this store, " + "an error occurred retrieving them: " + e.getMessage(), e); } }
diff --git a/blueprints/blueprints-generator/src/main/java/com/tinkerpop/blueprints/generator/AbstractGenerator.java b/blueprints/blueprints-generator/src/main/java/com/tinkerpop/blueprints/generator/AbstractGenerator.java index e7dca4f59..f7fc99e18 100644 --- a/blueprints/blueprints-generator/src/main/java/com/tinkerpop/blueprints/generator/AbstractGenerator.java +++ b/blueprints/blueprints-generator/src/main/java/com/tinkerpop/blueprints/generator/AbstractGenerator.java @@ -1,111 +1,112 @@ package com.tinkerpop.blueprints.generator; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; import java.util.Map; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Supplier; /** * Base class for all synthetic network generators. * * @author Matthias Broecheler ([email protected]) * @author Stephen Mallette (http://stephen.genoprime.com) */ public abstract class AbstractGenerator { private final String label; private final Optional<Consumer<Edge>> edgeAnnotator; private final Optional<BiConsumer<Vertex,Map<String,Object>>> vertexAnnotator; protected final Supplier<Long> seedSupplier; /** * Constructs a new network generator for edges with the given label and annotator. If a {@code seedGenerator} is * not supplied then the system clock is used to generate a seed. * * @param label Label for the generated edges * @param edgeAnnotator {@link Consumer} to use for annotating newly generated edges. * @param vertexAnnotator {@link Consumer} to use for annotating process vertices. * @param seedGenerator A {@link Supplier} function to provide seeds to {@link java.util.Random} */ public AbstractGenerator(final String label, final Optional<Consumer<Edge>> edgeAnnotator, - final Optional<BiConsumer<Vertex,Map<String,Object>>> vertexAnnotator, final Optional<Supplier<Long>> seedGenerator) { + final Optional<BiConsumer<Vertex,Map<String,Object>>> vertexAnnotator, + final Optional<Supplier<Long>> seedGenerator) { if (label == null || label.isEmpty()) throw new IllegalArgumentException("Label cannot be empty"); if (edgeAnnotator == null) throw new IllegalArgumentException("edgeAnnotator"); if (vertexAnnotator == null) throw new IllegalArgumentException("vertexAnnotator"); if (seedGenerator == null) throw new IllegalArgumentException("seedGenerator"); this.label = label; this.edgeAnnotator = edgeAnnotator; this.vertexAnnotator = vertexAnnotator; this.seedSupplier = seedGenerator.orElse(System::currentTimeMillis); } /** * Constructs a new network generator for edges with the given label and annotator. * * @param label Label for the generated edges * @param edgeAnnotator EdgeAnnotator to use for annotating newly generated edges. * @param vertexAnnotator VertexAnnotator to use for annotating process vertices. */ public AbstractGenerator(final String label, final Optional<Consumer<Edge>> edgeAnnotator, final Optional<BiConsumer<Vertex,Map<String,Object>>> vertexAnnotator) { this(label, edgeAnnotator, vertexAnnotator, Optional.empty()); } /** * Constructs a new network generator for edges with the given label and annotator. * * @param label Label for the generated edges * @param annotator EdgeAnnotator to use for annotating newly generated edges. */ public AbstractGenerator(final String label, final Optional<Consumer<Edge>> annotator) { this(label, annotator, Optional.empty()); } /** * Constructs a new network generator for edges with the given label and an empty annotator. * * @param label Label for the generated edges */ public AbstractGenerator(final String label) { this(label, Optional.empty()); } /** * Returns the label for this generator. */ public final String getLabel() { return label; } /** * Returns the {@link Consumer} for this generator */ @SuppressWarnings("UnusedDeclaration") public final Optional<Consumer<Edge>> getEdgeAnnotator() { return edgeAnnotator; } /** * Returns the {@link BiConsumer} for this generator */ @SuppressWarnings("UnusedDeclaration") public final Optional<BiConsumer<Vertex,Map<String,Object>>> getVertexAnnotator() { return vertexAnnotator; } protected final Edge addEdge(final Vertex out, final Vertex in) { final Edge e = out.addEdge(label, in); edgeAnnotator.ifPresent(c->c.accept(e)); return e; } protected final Vertex processVertex(final Vertex vertex, final Map<String, Object> context) { vertexAnnotator.ifPresent(c->c.accept(vertex, context)); return vertex; } }
true
true
public AbstractGenerator(final String label, final Optional<Consumer<Edge>> edgeAnnotator, final Optional<BiConsumer<Vertex,Map<String,Object>>> vertexAnnotator, final Optional<Supplier<Long>> seedGenerator) { if (label == null || label.isEmpty()) throw new IllegalArgumentException("Label cannot be empty"); if (edgeAnnotator == null) throw new IllegalArgumentException("edgeAnnotator"); if (vertexAnnotator == null) throw new IllegalArgumentException("vertexAnnotator"); if (seedGenerator == null) throw new IllegalArgumentException("seedGenerator"); this.label = label; this.edgeAnnotator = edgeAnnotator; this.vertexAnnotator = vertexAnnotator; this.seedSupplier = seedGenerator.orElse(System::currentTimeMillis); }
public AbstractGenerator(final String label, final Optional<Consumer<Edge>> edgeAnnotator, final Optional<BiConsumer<Vertex,Map<String,Object>>> vertexAnnotator, final Optional<Supplier<Long>> seedGenerator) { if (label == null || label.isEmpty()) throw new IllegalArgumentException("Label cannot be empty"); if (edgeAnnotator == null) throw new IllegalArgumentException("edgeAnnotator"); if (vertexAnnotator == null) throw new IllegalArgumentException("vertexAnnotator"); if (seedGenerator == null) throw new IllegalArgumentException("seedGenerator"); this.label = label; this.edgeAnnotator = edgeAnnotator; this.vertexAnnotator = vertexAnnotator; this.seedSupplier = seedGenerator.orElse(System::currentTimeMillis); }
diff --git a/src/com/angrykings/activities/LobbyActivity.java b/src/com/angrykings/activities/LobbyActivity.java index b3dd048..6d5b3cc 100644 --- a/src/com/angrykings/activities/LobbyActivity.java +++ b/src/com/angrykings/activities/LobbyActivity.java @@ -1,179 +1,186 @@ package com.angrykings.activities; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import com.angrykings.Action; import com.angrykings.ServerConnection; import com.angrykings.ServerConnection.OnMessageHandler; import com.angrykings.utils.ServerJSONBuilder; public class LobbyActivity extends ListActivity { private String username; private List<String> users; private Map<String, String> listItemToName = new HashMap<String, String>(); private void updateLobby(List<String> user) { setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, user)); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle extras = getIntent().getExtras(); users = new ArrayList<String>(); if (extras != null) { this.username = extras.getString("username"); } ServerConnection .getInstance() .getConnection() .sendTextMessage( new ServerJSONBuilder().create( Action.Client.GO_TO_LOBBY).build()); displayLobby(); } private void displayLobby() { updateLobby(users); getListView().setTextFilterEnabled(true); ServerConnection.getInstance().setHandler(new OnMessageHandler() { @Override public void onMessage(String payload) { try { - JSONObject jObj = new JSONObject(payload); + final JSONObject jObj = new JSONObject(payload); if (jObj.getInt("action") == Action.Server.REQUEST) { new AlertDialog.Builder(LobbyActivity.this) .setTitle("Request") .setMessage( jObj.getString("partner") + " requested a match!") .setPositiveButton("Okay", new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { ServerConnection .getInstance() .getConnection() .sendTextMessage( new ServerJSONBuilder() .create(Action.Client.ACCEPT) .build()); Intent intent = new Intent( LobbyActivity.this, OnlineGameActivity.class); intent.putExtra("myTurn", true); intent.putExtra("username", username); + try { + intent.putExtra("partnername", + jObj.getString("partner")); + } catch (JSONException e) { + e.printStackTrace(); + intent.putExtra("partnername","Partner"); + } startActivity(intent); } }) .setNegativeButton("Deny", new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { ServerConnection .getInstance() .getConnection() .sendTextMessage( new ServerJSONBuilder() .create(Action.Client.DENY) .build()); } }).show(); } else if (jObj.getInt("action") == Action.Server.LOBBY_UPDATE) { Log.d("AngryKings", "received lobby update: "+jObj.get("names")); JSONArray userArray = new JSONArray(jObj .getString("names")); users.clear(); for (int i = 0; i < userArray.length(); i++) { String eingabe = userArray.getJSONArray(i) .getString(0) + " Gewonnen: " + userArray.getJSONArray(i).getString(1) + " Verloren: " + userArray.getJSONArray(i).getString(2); users.add(eingabe); listItemToName.put(eingabe, userArray.getJSONArray(i).getString(0)); } updateLobby(users); } } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } } }); } @Override protected void onListItemClick(final ListView l, final View v, final int position, final long id) { super.onListItemClick(l, v, position, id); final String partnerName = listItemToName.get( getListView().getItemAtPosition( position).toString()); final AlertDialog dialog = new AlertDialog.Builder(this) .setTitle("Please Wait").setMessage("Waiting for partner") .show(); ServerConnection.getInstance().setHandler(new OnMessageHandler() { @Override public void onMessage(final String payload) { try { final JSONObject jObj = new JSONObject(payload); if (jObj.getInt("action") == Action.Server.DENIED) { dialog.cancel(); displayLobby(); } else { dialog.dismiss(); Intent intent = new Intent(LobbyActivity.this, OnlineGameActivity.class); intent.putExtra("myTurn", false) .putExtra("username", username) .putExtra("partnername", partnerName) .addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); startActivity(intent); } } catch (final JSONException e) { e.printStackTrace(); } } }); ServerConnection .getInstance() .getConnection() .sendTextMessage( new ServerJSONBuilder() .create(Action.Client.PAIR) .option("partner",partnerName).build()); } }
false
true
private void displayLobby() { updateLobby(users); getListView().setTextFilterEnabled(true); ServerConnection.getInstance().setHandler(new OnMessageHandler() { @Override public void onMessage(String payload) { try { JSONObject jObj = new JSONObject(payload); if (jObj.getInt("action") == Action.Server.REQUEST) { new AlertDialog.Builder(LobbyActivity.this) .setTitle("Request") .setMessage( jObj.getString("partner") + " requested a match!") .setPositiveButton("Okay", new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { ServerConnection .getInstance() .getConnection() .sendTextMessage( new ServerJSONBuilder() .create(Action.Client.ACCEPT) .build()); Intent intent = new Intent( LobbyActivity.this, OnlineGameActivity.class); intent.putExtra("myTurn", true); intent.putExtra("username", username); startActivity(intent); } }) .setNegativeButton("Deny", new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { ServerConnection .getInstance() .getConnection() .sendTextMessage( new ServerJSONBuilder() .create(Action.Client.DENY) .build()); } }).show(); } else if (jObj.getInt("action") == Action.Server.LOBBY_UPDATE) { Log.d("AngryKings", "received lobby update: "+jObj.get("names")); JSONArray userArray = new JSONArray(jObj .getString("names")); users.clear(); for (int i = 0; i < userArray.length(); i++) { String eingabe = userArray.getJSONArray(i) .getString(0) + " Gewonnen: " + userArray.getJSONArray(i).getString(1) + " Verloren: " + userArray.getJSONArray(i).getString(2); users.add(eingabe); listItemToName.put(eingabe, userArray.getJSONArray(i).getString(0)); } updateLobby(users); } } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } } }); }
private void displayLobby() { updateLobby(users); getListView().setTextFilterEnabled(true); ServerConnection.getInstance().setHandler(new OnMessageHandler() { @Override public void onMessage(String payload) { try { final JSONObject jObj = new JSONObject(payload); if (jObj.getInt("action") == Action.Server.REQUEST) { new AlertDialog.Builder(LobbyActivity.this) .setTitle("Request") .setMessage( jObj.getString("partner") + " requested a match!") .setPositiveButton("Okay", new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { ServerConnection .getInstance() .getConnection() .sendTextMessage( new ServerJSONBuilder() .create(Action.Client.ACCEPT) .build()); Intent intent = new Intent( LobbyActivity.this, OnlineGameActivity.class); intent.putExtra("myTurn", true); intent.putExtra("username", username); try { intent.putExtra("partnername", jObj.getString("partner")); } catch (JSONException e) { e.printStackTrace(); intent.putExtra("partnername","Partner"); } startActivity(intent); } }) .setNegativeButton("Deny", new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { ServerConnection .getInstance() .getConnection() .sendTextMessage( new ServerJSONBuilder() .create(Action.Client.DENY) .build()); } }).show(); } else if (jObj.getInt("action") == Action.Server.LOBBY_UPDATE) { Log.d("AngryKings", "received lobby update: "+jObj.get("names")); JSONArray userArray = new JSONArray(jObj .getString("names")); users.clear(); for (int i = 0; i < userArray.length(); i++) { String eingabe = userArray.getJSONArray(i) .getString(0) + " Gewonnen: " + userArray.getJSONArray(i).getString(1) + " Verloren: " + userArray.getJSONArray(i).getString(2); users.add(eingabe); listItemToName.put(eingabe, userArray.getJSONArray(i).getString(0)); } updateLobby(users); } } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } } }); }
diff --git a/src/com/github/unluckyninja/mousekiller/MouseKiller.java b/src/com/github/unluckyninja/mousekiller/MouseKiller.java index fc55b05..ffa5718 100644 --- a/src/com/github/unluckyninja/mousekiller/MouseKiller.java +++ b/src/com/github/unluckyninja/mousekiller/MouseKiller.java @@ -1,61 +1,61 @@ package com.github.unluckyninja.mousekiller; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.github.unluckyninja.mousekiller.model.Killer; import com.github.unluckyninja.mousekiller.model.listener.SimpleInputListener; public class MouseKiller extends Game { public static void main(String[] args) { LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration(); - cfg.title = "Drop"; + cfg.title = "MouseKiller"; cfg.width = width; cfg.height = height; cfg.useGL20 = true; new LwjglApplication(new MouseKiller(), cfg); } SpriteBatch batch; Killer killer; private static int width = 800; private static int height = 600; @Override public void create() { Gdx.input.setCursorCatched(true); batch = new SpriteBatch(); killer = new Killer(Gdx.input.getX(),height-Gdx.input.getY()); this.setScreen(new MainMenu(this, batch)); Gdx.input.setInputProcessor(new SimpleInputListener(killer)); } @Override public void resize(int width, int height) { super.resize(width, height); MouseKiller.width = width; MouseKiller.height = height; } @Override public void render() { super.render(); } @Override public void dispose() { getScreen().dispose(); killer.getTexture().getTexture().dispose(); batch.dispose(); } public static int getWidth() { return width; } public static int getHeight() { return height; } }
true
true
public static void main(String[] args) { LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration(); cfg.title = "Drop"; cfg.width = width; cfg.height = height; cfg.useGL20 = true; new LwjglApplication(new MouseKiller(), cfg); }
public static void main(String[] args) { LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration(); cfg.title = "MouseKiller"; cfg.width = width; cfg.height = height; cfg.useGL20 = true; new LwjglApplication(new MouseKiller(), cfg); }
diff --git a/src/de/ueller/midlet/gps/DiscoverGps.java b/src/de/ueller/midlet/gps/DiscoverGps.java index 326c30d1..602d592b 100644 --- a/src/de/ueller/midlet/gps/DiscoverGps.java +++ b/src/de/ueller/midlet/gps/DiscoverGps.java @@ -1,463 +1,463 @@ package de.ueller.midlet.gps; /* * GpsMid - Copyright (c) 2007 Harald Mueller james22 at users dot sourceforge dot net * Copyright (c) 2008 Kai Krueger apm at users dot sourceforge dot net * See Copying */ import java.io.IOException; import java.util.Vector; //#if polish.api.btapi import javax.bluetooth.BluetoothStateException; import javax.bluetooth.DeviceClass; import javax.bluetooth.DiscoveryAgent; import javax.bluetooth.DiscoveryListener; import javax.bluetooth.LocalDevice; import javax.bluetooth.RemoteDevice; import javax.bluetooth.ServiceRecord; import javax.bluetooth.UUID; //#endif import de.ueller.gps.tools.StringTokenizer; public class DiscoverGps //#if polish.api.btapi implements Runnable, DiscoveryListener //#endif { private final static Logger logger=Logger.getInstance(DiscoverGps.class,Logger.DEBUG); //#if polish.api.btapi /** Shows the engine is ready to work. */ private static final int READY = 0; /** Shows the engine is searching bluetooth devices. */ public static final int DEVICE_SEARCH = 1; /** Shows the engine is ready with searching bluetooth devices. */ public static final int DEVICE_READY = 2; /** Shows the engine is searching bluetooth services. */ public static final int SERVICE_SEARCH = 3; /** the engine is wating for a serviceselection */ public static final int SERVICE_SELECT = 4; /** the engine is wating for a serviceselection */ public static final int NODEVICE = 5; private static final String[] stateText = { "ready", "device search", "device select", "service search","select service","No Device in range"}; private final GuiDiscover parent; /** Process the search/download requests. */ private Thread processorThread; /** Collects the remote devices found during a search. */ private Vector /* RemoteDevice */devices = new Vector(); /** Collects the services found during a search. */ private Vector /* ServiceRecord */records = new Vector(); /** Keeps the device discovery return code. */ private int discType = -1; /** Keeps the services search IDs (just to be able to cancel them). */ private int[] searchIDs; /** Optimization: keeps service search pattern. */ private UUID[] uuidSet; /** Optimization: keeps attributes list to be retrieved. */ private int[] attrSet; /** Keeps the current state of engine. */ private int state = READY; /** Keeps the discovery agent reference. */ private DiscoveryAgent discoveryAgent; private boolean isClosed; private GuiBusy guiBusy; /** Keeps the device index for witch a Service discover is requested */ private int selectedDevice = -1; public static final long UUDI_SERIAL=0x1101; public static final long UUDI_FILE=0x1105; private final long searchType; public DiscoverGps(GuiDiscover parent,long searchType) { this.parent = parent; this.searchType = searchType; // we have to initialize a system in different thread... processorThread = new Thread(this); processorThread.start(); } private synchronized void cancelDeviceSearch(){ if (state == DEVICE_SEARCH) { discoveryAgent.cancelInquiry(this); } } /** Cancel's the devices/services search. */ public void cancelSearch() { cancelDeviceSearch(); cancelServiceSearch(); } private synchronized void cancelServiceSearch(){ if (state == SERVICE_SEARCH) { for (int i = 0; i < searchIDs.length; i++) { discoveryAgent.cancelServiceSearch(searchIDs[i]); } } } /** * Destroy a work with bluetooth - exits the accepting thread and close notifier. */ void destroy() { synchronized (this) { parent.addDevice("shutdown discover"); cancelSearch(); isClosed = true; notify(); // FIXME: implement me } // wait for acceptor thread is done try { processorThread.join(); } catch (InterruptedException e) {} // ignore parent.addDevice("distroyed"); parent.show(); } /** * Invoked by system when a new remote device is found - remember the found device. */ public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) { // same device may found several times during single search parent.addDevice("found "+btDevice.getBluetoothAddress()); if (devices.indexOf(btDevice) == -1) { devices.addElement(btDevice); } } public int getState() { return state; } /** * Invoked by system when device discovery is done. * <p> * Use a trick here - just remember the discType and process its evaluation in another thread. */ public void inquiryCompleted(int discType) { this.discType = discType; // parent.showState("search complete"); parent.addDevice("inquiry Complete"); synchronized (this) { notify(); } } /** Sets the request to search the devices/services. */ void requestSearch() { synchronized (this) { notify(); } } public void run() { try { guiBusy = new GuiBusy(); guiBusy.show(); //Probe Commports: try { String commports = System.getProperty("microedition.commports"); String[] commport = StringTokenizer.getArray(commports, ","); for (int i = 0; i < commport.length; i++) { parent.addDevice("comm:" + commport[i] + ";baudrate=19200", commport[i]); } } catch (RuntimeException re) { - logger.error("Comm ports are not supported on this device: " + re.getMessage()); + logger.silentexception("Comm ports are not supported on this device", re); } catch (Exception e) { - logger.error("Comm ports are not supported on this device: " + e.getMessage()); + logger.silentexception("Comm ports are not supported on this device",e); } // System.out.println("Start Thread Discover Gps"); // initialize bluetooth first parent.addDevice("init BT"); boolean isBTReady = false; try { // create/get a local device and discovery agent LocalDevice localDevice = LocalDevice.getLocalDevice(); discoveryAgent = localDevice.getDiscoveryAgent(); // remember we've reached this point. isBTReady = true; } catch (Exception e) { logger.exception("Can't initialize bluetooth: ", e); parent.addDevice("Can't init bluetooth"); } parent.completeInitialization(isBTReady); // nothing to do if no bluetooth available if (!isBTReady) { parent.addDevice("no Blutooth"); return; } // initialize some optimization variables uuidSet = new UUID[1]; // ok, we are interesting in btspp or File services, // which one at the moment is specified by searchType uuidSet[0] = new UUID(searchType); selectService(); } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } parent.show(); parent.addDevice("Thread end"); parent.btDiscoverReady(); } private void searchDevice() { try { setState(DEVICE_SEARCH); discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this); } catch (BluetoothStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (waitUntilNotify()) { return; } switch (discType) { case INQUIRY_ERROR: parent.addDevice("Device discovering error..."); return; case INQUIRY_TERMINATED: // make sure no garbage in found devices list parent.addDevice("Device search canceled"); // nothing to report - go to next request break; case INQUIRY_COMPLETED: if (devices.size() == 0) { // parent.addDevice("No devices in range"); // parent.addDevice("btspp://000DB5315C50:1;authenticate=false;encrypt=false;master=false","Dummy for emulator"); setState(NODEVICE); } else { setState(DEVICE_READY); break; } break; default: // what kind of system you are?... :( parent.addDevice("unknown Return from Discover"); logger.error("system error:" + " unexpected device discovery code: " + discType); // destroy(); // return; } // if (waitUntilNotify()) // return; } private void searchService() { synchronized (this) { searchIDs = new int[devices.size()]; int i = 0; int retries = 0; while (i < searchIDs.length) { if (retries > 4) { //This device discovery failed. //Set searchIDs[i] to -1 to indicate it has failed, //as serviceSerchComplete uses this to check if all searches //have completed searchIDs[i] = -1; i++; retries = 0; continue; } try { RemoteDevice rd = (RemoteDevice) devices.elementAt(i); searchIDs[i] = discoveryAgent.searchServices(attrSet, uuidSet, rd, this); } catch (BluetoothStateException e) { //This exception is most likely due to the fact //that the device is not able to handle concurrent //searchServices() calls. So wait a while and try again try { Thread.sleep(1000); } catch (InterruptedException e1) { //Nothing to do in that case } retries++; continue; } i++; retries = 0; } parent.addDevice("wait for Discovery end"); } } public synchronized void selectDevice(int idx){ selectedDevice=idx; state=SERVICE_SEARCH; notify(); } private void selectService() { // while (!isClosed) { // suche die devices parent.addDevice("search devices"); searchDevice(); if (devices.size() == 0){ parent.addDevice("no Device found"); return; } // durchsuche alle devices nach services parent.addDevice("search services"); searchService(); if (getState() != SERVICE_SELECT) waitUntilNotify(); // parent.clear(); if (devices.size() == 0){ parent.addDevice("no Service found"); return; } for (int i=0; i<records.size();i++){ ServiceRecord service=(ServiceRecord) records.elementAt(i); parent.addDevice(service.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false)); } // if no Services found, try with the discovered BT devices // this is because RAZER V3i is after firmware update not able // to discover services parent.addDevice("constuct "+devices.size()+" services"); if (records.size()==0 && devices.size() > 0){ for (int dl=0; dl < devices.size(); dl++){ RemoteDevice rd = (RemoteDevice) devices.elementAt(dl); parent.addDevice("btspp://"+rd.getBluetoothAddress()+":1;authenticate=false;encrypt=false;master=false",friendlyName(rd)+ "?"); } } // } } public void servicesDiscovered(int transID, ServiceRecord[] servRecord) { for (int i = 0; i < servRecord.length; i++) { // String connectionURL = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false); // parent.addDevice(connectionURL); records.addElement(servRecord[i]); parent.addDevice( servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false), friendlyName(servRecord[i].getHostDevice())); } } private String friendlyName(RemoteDevice rd){ String address = rd.getBluetoothAddress(); String name = null; try { name = rd.getFriendlyName(false); } catch (IOException ioe) {} // On Nokia 6230 the bluetooth stack is buggy and so it could be // that getFriendlyName() fails. In this case we show at least // the bluetooth address in the device list instead of a friendly name if (name == null || name.trim().length() == 0) { try { name = rd.getFriendlyName(true); } catch (IOException ioe) {} if (name == null || name.trim().length() == 0) { name = address; } } return name; } public void serviceSearchCompleted(int transID, int respCode) { // first, find the service search transaction index int index = -1; for (int i = 0; i < searchIDs.length; i++) { if (searchIDs[i] == transID) { index = i; break; } } // error - unexpected transaction index if (index == -1) { logger.error("Unexpected transaction index: " + transID); // FIXME: process the error case } else { searchIDs[index] = -1; } /* * Actually, we do not care about the response code - if device is not reachable or no records, etc. */ // make sure it was the last transaction // parent.addDevice("look if all descovered"); for (int i = 0; i < searchIDs.length; i++) { if (searchIDs[i] != -1) { return; } } // parent.addDevice("all discovered"); // ok, all of the transactions are completed setState(SERVICE_SELECT); synchronized (this) { notify(); } } private void setState(int state) { this.state = state; parent.showState(stateText[state]); } private boolean waitUntilNotify() { if (isClosed) { return false; } // parent.addDevice("wait for notify"); synchronized (this) { try { wait(); // until devices or service are found } catch (InterruptedException e) { logger.silentexception("Unexpected interruption: ", e); parent.addDevice("interrupted"); return true; } } // parent.addDevice("got notify"); if (isClosed) { return true; } return false; } //#endif }
false
true
public void run() { try { guiBusy = new GuiBusy(); guiBusy.show(); //Probe Commports: try { String commports = System.getProperty("microedition.commports"); String[] commport = StringTokenizer.getArray(commports, ","); for (int i = 0; i < commport.length; i++) { parent.addDevice("comm:" + commport[i] + ";baudrate=19200", commport[i]); } } catch (RuntimeException re) { logger.error("Comm ports are not supported on this device: " + re.getMessage()); } catch (Exception e) { logger.error("Comm ports are not supported on this device: " + e.getMessage()); } // System.out.println("Start Thread Discover Gps"); // initialize bluetooth first parent.addDevice("init BT"); boolean isBTReady = false; try { // create/get a local device and discovery agent LocalDevice localDevice = LocalDevice.getLocalDevice(); discoveryAgent = localDevice.getDiscoveryAgent(); // remember we've reached this point. isBTReady = true; } catch (Exception e) { logger.exception("Can't initialize bluetooth: ", e); parent.addDevice("Can't init bluetooth"); } parent.completeInitialization(isBTReady); // nothing to do if no bluetooth available if (!isBTReady) { parent.addDevice("no Blutooth"); return; } // initialize some optimization variables uuidSet = new UUID[1]; // ok, we are interesting in btspp or File services, // which one at the moment is specified by searchType uuidSet[0] = new UUID(searchType); selectService(); } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } parent.show(); parent.addDevice("Thread end"); parent.btDiscoverReady(); }
public void run() { try { guiBusy = new GuiBusy(); guiBusy.show(); //Probe Commports: try { String commports = System.getProperty("microedition.commports"); String[] commport = StringTokenizer.getArray(commports, ","); for (int i = 0; i < commport.length; i++) { parent.addDevice("comm:" + commport[i] + ";baudrate=19200", commport[i]); } } catch (RuntimeException re) { logger.silentexception("Comm ports are not supported on this device", re); } catch (Exception e) { logger.silentexception("Comm ports are not supported on this device",e); } // System.out.println("Start Thread Discover Gps"); // initialize bluetooth first parent.addDevice("init BT"); boolean isBTReady = false; try { // create/get a local device and discovery agent LocalDevice localDevice = LocalDevice.getLocalDevice(); discoveryAgent = localDevice.getDiscoveryAgent(); // remember we've reached this point. isBTReady = true; } catch (Exception e) { logger.exception("Can't initialize bluetooth: ", e); parent.addDevice("Can't init bluetooth"); } parent.completeInitialization(isBTReady); // nothing to do if no bluetooth available if (!isBTReady) { parent.addDevice("no Blutooth"); return; } // initialize some optimization variables uuidSet = new UUID[1]; // ok, we are interesting in btspp or File services, // which one at the moment is specified by searchType uuidSet[0] = new UUID(searchType); selectService(); } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } parent.show(); parent.addDevice("Thread end"); parent.btDiscoverReady(); }
diff --git a/javafx.navigation/src/org/netbeans/modules/javafx/navigation/ClassMemberPanel.java b/javafx.navigation/src/org/netbeans/modules/javafx/navigation/ClassMemberPanel.java index 50a64171..42b10fc3 100644 --- a/javafx.navigation/src/org/netbeans/modules/javafx/navigation/ClassMemberPanel.java +++ b/javafx.navigation/src/org/netbeans/modules/javafx/navigation/ClassMemberPanel.java @@ -1,106 +1,110 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.javafx.navigation; import javax.swing.JComponent; import org.netbeans.spi.navigator.NavigatorPanel; import org.openide.util.Lookup; import org.openide.util.NbBundle; /** * * @author Tomas Zezula */ public class ClassMemberPanel implements NavigatorPanel { private ClassMemberPanelUI component; private static ClassMemberPanel INSTANCE; //Always accessed in event dispatch thread public ClassMemberPanel() { } public void panelActivated(Lookup context) { assert context != null; INSTANCE = this; - // System.out.println("Panel Activated"); - ClassMemberNavigatorJavaFXSourceFactory.getInstance().setLookup(context, getClassMemberPanelUI()); - getClassMemberPanelUI().showWaitNode(); + final ClassMemberNavigatorJavaFXSourceFactory instance = ClassMemberNavigatorJavaFXSourceFactory.getInstance(); + if (instance != null) { + instance.setLookup(context, getClassMemberPanelUI()); + getClassMemberPanelUI().showWaitNode(); + } else { + System.err.println("Can't instantiate ClassMemberNavigatorJavaFXSourceFactory ! No navigator will be available."); + } } public void panelDeactivated() { getClassMemberPanelUI().showWaitNode(); // To clear the ui ClassMemberNavigatorJavaFXSourceFactory.getInstance().setLookup(Lookup.EMPTY, null); INSTANCE = null; } public Lookup getLookup() { return this.getClassMemberPanelUI().getLookup(); } public String getDisplayName() { return NbBundle.getMessage(ClassMemberPanel.class,"LBL_members"); } public String getDisplayHint() { return NbBundle.getMessage(ClassMemberPanel.class,"HINT_members"); } public JComponent getComponent() { return getClassMemberPanelUI(); } // public void selectElement(ElementHandle<Element> eh) { // getClassMemberPanelUI().selectElementNode(eh); // } private synchronized ClassMemberPanelUI getClassMemberPanelUI() { if (this.component == null) { this.component = new ClassMemberPanelUI(); } return this.component; } public static ClassMemberPanel getInstance() { return INSTANCE; } }
true
true
public void panelActivated(Lookup context) { assert context != null; INSTANCE = this; // System.out.println("Panel Activated"); ClassMemberNavigatorJavaFXSourceFactory.getInstance().setLookup(context, getClassMemberPanelUI()); getClassMemberPanelUI().showWaitNode(); }
public void panelActivated(Lookup context) { assert context != null; INSTANCE = this; final ClassMemberNavigatorJavaFXSourceFactory instance = ClassMemberNavigatorJavaFXSourceFactory.getInstance(); if (instance != null) { instance.setLookup(context, getClassMemberPanelUI()); getClassMemberPanelUI().showWaitNode(); } else { System.err.println("Can't instantiate ClassMemberNavigatorJavaFXSourceFactory ! No navigator will be available."); } }
diff --git a/src/main/java/org/pircbotx/PircBotX.java b/src/main/java/org/pircbotx/PircBotX.java index a33345b..0ab7c5a 100644 --- a/src/main/java/org/pircbotx/PircBotX.java +++ b/src/main/java/org/pircbotx/PircBotX.java @@ -1,2328 +1,2327 @@ /** * Copyright (C) 2010 Leon Blakey <lord.quackstar at gmail.com> * * This file is part of PircBotX. * * PircBotX is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PircBotX is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PircBotX. If not, see <http://www.gnu.org/licenses/>. */ package org.pircbotx; import lombok.Setter; import lombok.Getter; import java.util.concurrent.CountDownLatch; import javax.net.SocketFactory; import org.pircbotx.hooks.events.ActionEvent; import org.pircbotx.hooks.events.ChannelInfoEvent; import org.pircbotx.hooks.events.ConnectEvent; import org.pircbotx.hooks.events.DeVoiceEvent; import org.pircbotx.hooks.events.DeopEvent; import org.pircbotx.hooks.events.FingerEvent; import org.pircbotx.hooks.events.InviteEvent; import org.pircbotx.hooks.events.JoinEvent; import org.pircbotx.hooks.events.KickEvent; import org.pircbotx.hooks.events.MessageEvent; import org.pircbotx.hooks.events.ModeEvent; import org.pircbotx.hooks.events.MotdEvent; import org.pircbotx.hooks.events.NickChangeEvent; import org.pircbotx.hooks.events.NoticeEvent; import org.pircbotx.hooks.events.OpEvent; import org.pircbotx.hooks.events.PartEvent; import org.pircbotx.hooks.events.PingEvent; import org.pircbotx.hooks.events.PrivateMessageEvent; import org.pircbotx.hooks.events.QuitEvent; import org.pircbotx.hooks.events.RemoveChannelBanEvent; import org.pircbotx.hooks.events.RemoveChannelKeyEvent; import org.pircbotx.hooks.events.RemoveChannelLimitEvent; import org.pircbotx.hooks.events.RemoveInviteOnlyEvent; import org.pircbotx.hooks.events.RemoveModeratedEvent; import org.pircbotx.hooks.events.RemoveNoExternalMessagesEvent; import org.pircbotx.hooks.events.RemovePrivateEvent; import org.pircbotx.hooks.events.RemoveSecretEvent; import org.pircbotx.hooks.events.RemoveTopicProtectionEvent; import org.pircbotx.hooks.events.ServerPingEvent; import org.pircbotx.hooks.events.ServerResponseEvent; import org.pircbotx.hooks.events.SetChannelBanEvent; import org.pircbotx.hooks.events.SetChannelKeyEvent; import org.pircbotx.hooks.events.SetChannelLimitEvent; import org.pircbotx.hooks.events.SetInviteOnlyEvent; import org.pircbotx.hooks.events.SetModeratedEvent; import org.pircbotx.hooks.events.SetNoExternalMessagesEvent; import org.pircbotx.hooks.events.SetPrivateEvent; import org.pircbotx.hooks.events.SetSecretEvent; import org.pircbotx.hooks.events.SetTopicProtectionEvent; import org.pircbotx.hooks.events.TimeEvent; import org.pircbotx.hooks.events.TopicEvent; import org.pircbotx.hooks.events.UnknownEvent; import org.pircbotx.hooks.events.UserListEvent; import org.pircbotx.hooks.events.UserModeEvent; import org.pircbotx.hooks.events.VersionEvent; import org.pircbotx.hooks.events.VoiceEvent; import org.pircbotx.hooks.Event; import org.pircbotx.hooks.managers.ListenerManager; import java.util.HashSet; import org.pircbotx.exception.IrcException; import org.pircbotx.exception.NickAlreadyInUseException; import java.util.Set; import java.io.PrintWriter; import java.io.StringWriter; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.Collections; import java.util.StringTokenizer; import lombok.Synchronized; import org.pircbotx.hooks.CoreHooks; import org.pircbotx.hooks.managers.GenericListenerManager; import org.pircbotx.hooks.Listener; import org.pircbotx.hooks.managers.ThreadedListenerManager; import static org.pircbotx.ReplyConstants.*; /** * PircBotX is a Java framework for writing IRC bots quickly and easily. * <p> * It provides an event-driven architecture to handle common IRC * events, flood protection, DCC support, ident support, and more. * The comprehensive logfile format is suitable for use with pisg to generate * channel statistics. * <p> * Methods of the PircBotX class can be called to send events to the IRC server * that it connects to. For example, calling the sendMessage method will * send a message to a channel or user on the IRC server. Multiple servers * can be supported using multiple instances of PircBotX. * <p> * To perform an action when the PircBotX receives a normal message from the IRC * server, you would override the onMessage method defined in the PircBotX * class. All on<i>XYZ</i> methods in the PircBotX class are automatically called * when the event <i>XYZ</i> happens, so you would override these if you wish * to do something when it does happen. * <p> * Some event methods, such as onPing, should only really perform a specific * function (i.e. respond to a PING from the server). For your convenience, such * methods are already correctly implemented in the PircBotX and should not * normally need to be overridden. Please read the full documentation for each * method to see which ones are already implemented by the PircBotX class. * * @author Origionally by: * <a href="http://www.jibble.org/">Paul James Mutton</a> for <a href="http://www.jibble.org/pircbot.php">PircBot</a> * <p>Forked and Maintained by in <a href="http://pircbotx.googlecode.com">PircBotX</a>: * Leon Blakey <lord.quackstar at gmail.com> */ public class PircBotX { /** * The definitive version number of this release of PircBotX. * (Note: Change this before automatically building releases) */ public static final String VERSION = "1.2 Beta 2"; protected Socket _socket; // Connection stuff. protected InputThread _inputThread = null; protected OutputThread _outputThread = null; private String _charset = null; private InetAddress _inetAddress = null; // Details about the last server that we connected to. private String _server = null; private int _port = -1; private String _password = null; private long _messageDelay = 1000; /* * A Many to Many map that links Users to Channels and channels to users. Modified * to remove each channel's and user's internal refrences to each other. */ protected ManyToManyMap<Channel, User> _userChanInfo = new ManyToManyMap<Channel, User>() { @Override public Set<Channel> deleteB(User b) { //Remove the Channels internal reference to the User synchronized (lockObject) { for (Channel curChan : BMap.get(b)) curChan.removeUser(b); } return super.deleteB(b); } @Override public boolean dissociate(Channel a, User b, boolean remove) { //Remove the Channels internal reference to the User a.removeUser(b); return super.dissociate(a, b, remove); } }; // DccManager to process and handle all DCC events. private DccManager _dccManager = new DccManager(this); private int[] _dccPorts = null; private InetAddress _dccInetAddress = null; // Default settings for the PircBotX. private boolean _autoNickChange = false; private boolean _verbose = false; private String _name = "PircBotX"; private String _nick = _name; private String _login = "PircBotX"; private String _version = "PircBotX " + VERSION + ", a fork of PircBot, the Java IRC bot - pircbotx.googlecode.com"; private String _finger = "You ought to be arrested for fingering a bot!"; private String _channelPrefixes = "#&+!"; /** * The logging lock object preventing lines from being printed as other * lines are being printed */ private final Object logLock = new Object(); protected ListenerManager<? extends PircBotX> listenerManager = new ThreadedListenerManager(); /** * The number of milliseconds to wait before the socket times out on read * operations. This does not mean the socket is invalid. By default its 5 * minutes */ private int socketTimeout = 1000 * 60 * 5; private final ServerInfo serverInfo = new ServerInfo(this); protected final ListBuilder<ChannelListEntry> channelListBuilder = new ListBuilder(); private SocketFactory _socketFactory = null; /** * Constructs a PircBotX with the default settings and adding {@link CoreHooks} * to the default ListenerManager, {@link ThreadedListenerManager}. This also * adds a shutdown hook to the current runtime while will properly shutdown * the bot by calling {@link #disconnect() } and {@link #dispose() } */ public PircBotX() { listenerManager.addListener(new CoreHooks()); final PircBotX thisBot = this; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (thisBot.isConnected()) { thisBot.disconnect(); thisBot.dispose(); } } }); } /** * Attempt to connect to the specified IRC server. * The onConnect method is called upon success. * * @param hostname The hostname of the server to connect to. * * @throws IOException if it was not possible to connect to the server. * @throws IrcException if the server would not let us join it. * @throws NickAlreadyInUseException if our nick is already in use on the server. */ public synchronized void connect(String hostname) throws IOException, IrcException, NickAlreadyInUseException { this.connect(hostname, 6667, null, null); } /** * Attempt to connect to the specified IRC server and port number. * The onConnect method is called upon success. * * @param hostname The hostname of the server to connect to. * @param port The port number to connect to on the server. * * @throws IOException if it was not possible to connect to the server. * @throws IrcException if the server would not let us join it. * @throws NickAlreadyInUseException if our nick is already in use on the server. */ public synchronized void connect(String hostname, int port) throws IOException, IrcException, NickAlreadyInUseException { this.connect(hostname, port, null, null); } /** * Attempt to connect to the specified IRC server using the given port * and password. * The onConnect method is called upon success. * * @param hostname The hostname of the server to connect to. * @param port The port number to connect to on the server. * @param password The password to use to join the server. * * @throws IOException if it was not possible to connect to the server. * @throws IrcException if the server would not let us join it. * @throws NickAlreadyInUseException if our nick is already in use on the server. */ public synchronized void connect(String hostname, int port, String password) throws IOException, IrcException, NickAlreadyInUseException { this.connect(hostname, port, password, null); } /** * Attempt to connect to the specified IRC server using the given port number * and socketFactory. * The onConnect method is called upon success. * * @param hostname The hostname of the server to connect to. * @param port The port number to connect to on the server. * @param socketFactory The factory to use for creating sockets, including secure sockets * * @throws IOException if it was not possible to connect to the server. * @throws IrcException if the server would not let us join it. * @throws NickAlreadyInUseException if our nick is already in use on the server. */ public synchronized void connect(String hostname, int port, SocketFactory socketFactory) throws IOException, IrcException, NickAlreadyInUseException { this.connect(hostname, port, null, socketFactory); } /** * Attempt to connect to the specified IRC server using the supplied * port number, password, and socketFactory. * The onConnect method is called upon success. * * @param hostname The hostname of the server to connect to. * @param port The port number to connect to on the server. * @param password The password to use to join the server. * @param socketFactory The factory to use for creating sockets, including secure sockets * * @throws IOException if it was not possible to connect to the server. * @throws IrcException if the server would not let us join it. * @throws NickAlreadyInUseException if our nick is already in use on the server. */ public synchronized void connect(String hostname, int port, String password, SocketFactory socketFactory) throws IOException, IrcException, NickAlreadyInUseException { _server = hostname; _port = port; _password = password; if (isConnected()) throw new IrcException("The PircBotXis already connected to an IRC server. Disconnect first."); // Don't clear the outqueue - there might be something important in it! // Clear everything we may have know about channels. _userChanInfo.clear(); // Connect to the server. if (socketFactory == null) _socket = new Socket(hostname, port); else _socket = socketFactory.createSocket(hostname, port); log("*** Connected to server."); _inetAddress = _socket.getLocalAddress(); InputStreamReader inputStreamReader = null; OutputStreamWriter outputStreamWriter = null; if (getEncoding() != null) { // Assume the specified encoding is valid for this JVM. inputStreamReader = new InputStreamReader(_socket.getInputStream(), getEncoding()); outputStreamWriter = new OutputStreamWriter(_socket.getOutputStream(), getEncoding()); } else { // Otherwise, just use the JVM's default encoding. inputStreamReader = new InputStreamReader(_socket.getInputStream()); outputStreamWriter = new OutputStreamWriter(_socket.getOutputStream()); } BufferedReader breader = new BufferedReader(inputStreamReader); BufferedWriter bwriter = new BufferedWriter(outputStreamWriter); //Construct the output and input threads _inputThread = new InputThread(this, _socket, breader); if (_outputThread == null) _outputThread = new OutputThread(this, bwriter); _outputThread.start(); // Attempt to join the server. if (Utils.isBlank(password)) _outputThread.sendRawLineNow("PASS " + password); String nick = getName(); _outputThread.sendRawLineNow("NICK " + nick); _outputThread.sendRawLineNow("USER " + getLogin() + " 8 * :" + getVersion()); // Read stuff back from the server to see if we connected. String line = null; int tries = 1; while ((line = breader.readLine()) != null) { handleLine(line); int firstSpace = line.indexOf(" "); int secondSpace = line.indexOf(" ", firstSpace + 1); if (secondSpace >= 0) { String code = line.substring(firstSpace + 1, secondSpace); if (code.equals("004")) //EXAMPLE: PircBotX gibson.freenode.net a-ircd-version1.5 allUserModes allChannelModes // We're connected to the server. break; else if (code.equals("433")) //EXAMPLE: AnAlreadyUsedName :Nickname already in use //Nickname in use, rename if (_autoNickChange) { tries++; nick = getName() + tries; _outputThread.sendRawLineNow("NICK " + nick); } else { _socket.close(); _inputThread = null; throw new NickAlreadyInUseException(line); } else if (code.equals("439")) { //EXAMPLE: PircBotX: Target change too fast. Please wait 104 seconds // No action required. } else if (code.startsWith("5") || code.startsWith("4")) { _socket.close(); _inputThread = null; throw new IrcException("Could not log into the IRC server: " + line); } } setNick(nick); } log("*** Logged onto server."); // This makes the socket timeout on read operations after 5 minutes. _socket.setSoTimeout(getSocketTimeout()); //Start input to start accepting lines _inputThread.start(); getListenerManager().dispatchEvent(new ConnectEvent(this)); } /** * Reconnects to the IRC server that we were previously connected to. * If necessary, the appropriate port number and password will be used. * This method will throw an IrcException if we have never connected * to an IRC server previously. * * @since PircBotX 0.9.9 * * @throws IOException if it was not possible to connect to the server. * @throws IrcException if the server would not let us join it. * @throws NickAlreadyInUseException if our nick is already in use on the server. */ public synchronized void reconnect() throws IOException, IrcException, NickAlreadyInUseException { if (getServer() == null) throw new IrcException("Cannot reconnect to an IRC server because we were never connected to one previously!"); connect(getServer(), getPort(), getPassword(), getSocketFactory()); } /** * This method disconnects from the server cleanly by calling the * quitServer() method. Providing the PircBotX was connected to an * IRC server, the onDisconnect() will be called as soon as the * disconnection is made by the server. * * @see #quitServer() quitServer * @see #quitServer(String) quitServer */ public synchronized void disconnect() { quitServer(); } /** * When you connect to a server and your nick is already in use and * this is set to true, a new nick will be automatically chosen. * This is done by adding numbers to the end of the nick until an * available nick is found. * * @param autoNickChange Set to true if you want automatic nick changes * during connection. */ public void setAutoNickChange(boolean autoNickChange) { _autoNickChange = autoNickChange; } /** * Starts an ident server (Identification Protocol Server, RFC 1413). * <p> * Most IRC servers attempt to contact the ident server on connecting * hosts in order to determine the user's identity. A few IRC servers * will not allow you to connect unless this information is provided. * <p> * So when a PircBotX is run on a machine that does not run an ident server, * it may be necessary to call this method to start one up. * <p> * Calling this method starts up an ident server which will respond with * the login provided by calling getLogin() and then shut down immediately. * It will also be shut down if it has not been contacted within 60 seconds * of creation. * <p> * If you require an ident response, then the correct procedure is to start * the ident server and then connect to the IRC server. The IRC server may * then contact the ident server to get the information it needs. * <p> * The ident server will fail to start if there is already an ident server * running on port 113, or if you are running as an unprivileged user who * is unable to create a server socket on that port number. * <p> * If it is essential for you to use an ident server when connecting to an * IRC server, then make sure that port 113 on your machine is visible to * the IRC server so that it may contact the ident server. * * @since PircBotX 0.9c */ public IdentServer startIdentServer() { return new IdentServer(this, getLogin()); } /** * Joins a channel. * * @param channel The name of the channel to join (eg "#cs"). */ public void joinChannel(String channel) { sendRawLineViaQueue("JOIN " + channel); } /** * Joins a channel with a key. * * @param channel The name of the channel to join (eg "#cs"). * @param key The key that will be used to join the channel. */ public void joinChannel(String channel, String key) { joinChannel(channel + " " + key); } /** * Parts a channel. * * @param channel The name of the channel to leave. */ public void partChannel(String channel) { sendRawLine("PART " + channel); } /** * Parts a channel, giving a reason. * * @param channel The name of the channel to leave. * @param reason The reason for parting the channel. */ public void partChannel(String channel, String reason) { sendRawLine("PART " + channel + " :" + reason); } /** * Quits from the IRC server. * Providing we are actually connected to an IRC server, the * onDisconnect() method will be called as soon as the IRC server * disconnects us. */ public void quitServer() { quitServer(""); } /** * Quits from the IRC server with a reason. * Providing we are actually connected to an IRC server, the * onDisconnect() method will be called as soon as the IRC server * disconnects us. * * @param reason The reason for quitting the server. */ public void quitServer(String reason) { sendRawLine("QUIT :" + reason); } /** * Sends a raw line to the IRC server as soon as possible, bypassing the * outgoing message queue. * * @param line The raw line to send to the IRC server. */ public void sendRawLine(String line) { if (isConnected()) _outputThread.sendRawLineNow(line); } /** * Sends a raw line through the outgoing message queue. * * @param line The raw line to send to the IRC server. */ public void sendRawLineViaQueue(String line) { if (line == null) throw new NullPointerException("Cannot send null messages to server"); if (isConnected()) _outputThread.send(line); } /** * Sends a message to a channel or a private message to a user. These * messages are added to the outgoing message queue and sent at the * earliest possible opportunity. * <p> * Some examples: - * <pre> // Send the message "Hello!" to the channel #cs. * sendMessage("#cs", "Hello!"); * * // Send a private message to Paul that says "Hi". * sendMessage("Paul", "Hi");</pre> * * You may optionally apply colours, boldness, underlining, etc to * the message by using the <code>Colors</code> class. * * @param target The name of the channel or user nick to send to. * @param message The message to send. * * @see Colors */ public void sendMessage(String target, String message) { _outputThread.send("PRIVMSG " + target + " :" + message); } public void sendMessage(Event event, String message) { User target = Utils.getSource(event); if (target != null && message != null) sendMessage(target, message); } public void sendMessage(User target, String message) { if (target != null && message != null) sendMessage(target.getNick(), message); } public void sendMessage(Channel target, String message) { if (target != null && message != null) sendMessage(target.getName(), message); } /** * Send a message to the given user in the given channel in this format: * <code>user: message</code>. Very useful for responding directly to a command * @param chan The channel to send the message to * @param user * @param message */ public void sendMessage(Channel chan, User user, String message) { if (chan != null && user != null && message != null) sendMessage(chan.getName(), user.getNick() + ": " + message); } /** * Sends an action to the channel or to a user. * * @param target The name of the channel or user nick to send to. * @param action The action to send. * * @see Colors */ public void sendAction(String target, String action) { sendCTCPCommand(target, "ACTION " + action); } public void sendAction(Event event, String message) { User target = Utils.getSource(event); if (target != null && message != null) sendAction(target, message); } public void sendAction(User target, String message) { if (target != null && message != null) sendAction(target.getNick(), message); } public void sendAction(Channel target, String message) { if (target != null && message != null) sendAction(target.getName(), message); } /** * Sends a notice to the channel or to a user. * * @param target The name of the channel or user nick to send to. * @param notice The notice to send. */ public void sendNotice(String target, String notice) { _outputThread.send("NOTICE " + target + " :" + notice); } public void sendNotice(Event event, String notice) { User target = Utils.getSource(event); if (target != null && notice != null) sendNotice(target, notice); } public void sendNotice(User target, String notice) { if (target != null && notice != null) sendNotice(target.getNick(), notice); } public void sendNotice(Channel target, String notice) { if (target != null && notice != null) sendNotice(target.getName(), notice); } /** * Sends a CTCP command to a channel or user. (Client to client protocol). * Examples of such commands are "PING <number>", "FINGER", "VERSION", etc. * For example, if you wish to request the version of a user called "Dave", * then you would call <code>sendCTCPCommand("Dave", "VERSION");</code>. * The type of response to such commands is largely dependant on the target * client software. * * @since PircBotX 0.9.5 * * @param target The name of the channel or user to send the CTCP message to. * @param command The CTCP command to send. */ public void sendCTCPCommand(String target, String command) { _outputThread.send("PRIVMSG " + target + " :\u0001" + command + "\u0001"); } public void sendCTCPCommand(Event event, String command) { User target = Utils.getSource(event); if (target != null && command != null) sendCTCPCommand(target, command); } public void sendCTCPCommand(User target, String command) { if (target != null && command != null) sendCTCPCommand(target.getNick(), command); } public void sendCTCPResponse(String target, String message) { _outputThread.send("NOTICE " + target + " :\u0001" + message + "\u0001"); } public void sendCTCPResponse(Event event, String message) { User target = Utils.getSource(event); if (target != null && message != null) sendCTCPResponse(target, message); } public void sendCTCPResponse(User target, String message) { if (target != null && message != null) sendCTCPResponse(target.getNick(), message); } /** * Attempt to change the current nick (nickname) of the bot when it * is connected to an IRC server. * After confirmation of a successful nick change, the getNick method * will return the new nick. * * @param newNick The new nick to use. */ public void changeNick(String newNick) { sendRawLine("NICK " + newNick); } /** * Identify the bot with NickServ, supplying the appropriate password. * Some IRC Networks (such as freenode) require users to <i>register</i> and * <i>identify</i> with NickServ before they are able to send private messages * to other users, thus reducing the amount of spam. If you are using * an IRC network where this kind of policy is enforced, you will need * to make your bot <i>identify</i> itself to NickServ before you can send * private messages. Assuming you have already registered your bot's * nick with NickServ, this method can be used to <i>identify</i> with * the supplied password. It usually makes sense to identify with NickServ * immediately after connecting to a server. * <p> * This method issues a raw NICKSERV command to the server, and is therefore * safer than the alternative approach of sending a private message to * NickServ. The latter approach is considered dangerous, as it may cause * you to inadvertently transmit your password to an untrusted party if you * connect to a network which does not run a NickServ service and where the * untrusted party has assumed the nick "NickServ". However, if your IRC * network is only compatible with the private message approach, you may * typically identify like so: * <pre>sendMessage("NickServ", "identify PASSWORD");</pre> * * @param password The password which will be used to identify with NickServ. */ public void identify(String password) { sendRawLine("NICKSERV IDENTIFY " + password); } /** * Set the mode of a channel. * This method attempts to set the mode of a channel. This * may require the bot to have operator status on the channel. * For example, if the bot has operator status, we can grant * operator status to "Dave" on the #cs channel * by calling setMode("#cs", "+o Dave"); * An alternative way of doing this would be to use the op method. * * @param chan The channel on which to perform the mode change. * @param mode The new mode to apply to the channel. This may include * zero or more arguments if necessary. * * @see #op(org.pircbotx.Channel, org.pircbotx.User) */ public void setMode(Channel chan, String mode) { sendRawLine("MODE " + chan.getName() + " " + mode); } /** * Set a mode for a user. See {@link #setMode(org.pircbotx.Channel, java.lang.String) } * @param chan The channel on which to perform the mode change. * @param mode The new mode to apply to the channel. <b>This should not * include arguments!</b> * @param user The user to perform the mode change on * @see #setMode(org.pircbotx.Channel, java.lang.String) */ public void setMode(Channel chan, String mode, User user) { setMode(chan, mode + user.getNick()); } /** * Sends an invitation to join a channel. Some channels can be marked * as "invite-only", so it may be useful to allow a bot to invite people * into it. * * @param nick The nick of the user to invite * @param channel The channel you are inviting the user to join. * */ public void sendInvite(String nick, String channel) { sendRawLine("INVITE " + nick + " :" + channel); } public void sendInvite(Event event, String channel) { User target = Utils.getSource(event); if (target != null && channel != null) sendInvite(target, channel); } public void sendInvite(User target, String channel) { if (target != null && channel != null) sendInvite(target.getNick(), channel); } public void sendInvite(Event event, Channel channel) { User target = Utils.getSource(event); if (target != null && channel != null) sendInvite(target, channel); } public void sendInvite(User target, Channel channel) { if (target != null && channel != null) sendInvite(target.getNick(), channel); } public void sendInvite(Channel target, Channel channel) { if (target != null && channel != null) sendInvite(target.getName(), channel); } public void sendInvite(String nick, Channel channel) { if (nick != null && channel != null) sendInvite(nick, channel.getName()); } /** * Bans a user from a channel. An example of a valid hostmask is * "*!*compu@*.18hp.net". This may be used in conjunction with the * kick method to permanently remove a user from a channel. * Successful use of this method may require the bot to have operator * status itself. * * @param channel The channel to ban the user from. * @param hostmask A hostmask representing the user we're banning. */ public void ban(String channel, String hostmask) { sendRawLine("MODE " + channel + " +b " + hostmask); } /** * Unbans a user from a channel. An example of a valid hostmask is * "*!*compu@*.18hp.net". * Successful use of this method may require the bot to have operator * status itself. * * @param channel The channel to unban the user from. * @param hostmask A hostmask representing the user we're unbanning. */ public void unBan(String channel, String hostmask) { sendRawLine("MODE " + channel + " -b " + hostmask); } /** * Grants operator privilidges to a user on a channel. * Successful use of this method may require the bot to have operator * status itself. * * @param chan The channel we're opping the user on. * @param user The user we are opping. */ public void op(Channel chan, User user) { setMode(chan, "+o " + user.getNick()); } /** * Removes operator privileges from a user on a channel. * Successful use of this method may require the bot to have operator * status itself. * * @param chan The channel we're deopping the user on. * @param user The user we are deopping. */ public void deOp(Channel chan, User user) { setMode(chan, "-o " + user.getNick()); } /** * Grants voice privileges to a user on a channel. * Successful use of this method may require the bot to have operator * status itself. * * @param chan The channel we're voicing the user on. * @param user The user we are voicing. */ public void voice(Channel chan, User user) { setMode(chan, "+v " + user.getNick()); } /** * Removes voice privileges from a user on a channel. * Successful use of this method may require the bot to have operator * status itself. * * @param chan The channel we're devoicing the user on. * @param user The user we are devoicing. */ public void deVoice(Channel chan, User user) { setMode(chan, "-v " + user.getNick()); } /** * Set the topic for a channel. * This method attempts to set the topic of a channel. This * may require the bot to have operator status if the topic * is protected. * * @param chan The channel on which to perform the mode change. * @param topic The new topic for the channel. * */ public void setTopic(Channel chan, String topic) { sendRawLine("TOPIC " + chan.getName() + " :" + topic); } /** * Kicks a user from a channel. * This method attempts to kick a user from a channel and * may require the bot to have operator status in the channel. * * @param chan The channel to kick the user from. * @param user The user to kick. */ public void kick(Channel chan, User user) { kick(chan, user, ""); } /** * Kicks a user from a channel, giving a reason. * This method attempts to kick a user from a channel and * may require the bot to have operator status in the channel. * * @param chan The channel to kick the user from. * @param user The user to kick. * @param reason A description of the reason for kicking a user. */ public void kick(Channel chan, User user, String reason) { sendRawLine("KICK " + chan.getName() + " " + user.getNick() + " :" + reason); } /** * Issues a request for a list of all channels on the IRC server. * When the PircBotX receives information for each channel, it will * call the onChannelInfo method, which you will need to override * if you want it to do anything useful. * <p> * <b>NOTE:</b> This will do nothing if a channel list is already in effect * * @see ChannelInfoEvent */ public void listChannels() { listChannels(null); } /** * Issues a request for a list of all channels on the IRC server. * When the PircBotX receives information for each channel, it will * call the onChannelInfo method, which you will need to override * if you want it to do anything useful. * <p> * Some IRC servers support certain parameters for LIST requests. * One example is a parameter of ">10" to list only those channels * that have more than 10 users in them. Whether these parameters * are supported or not will depend on the IRC server software. * <p> * <b>NOTE:</b> This will do nothing if a channel list is already in effect * @param parameters The parameters to supply when requesting the * list. * * @see ChannelInfoEvent */ public void listChannels(String parameters) { if (!channelListBuilder.isRunning()) if (parameters == null) sendRawLine("LIST"); else sendRawLine("LIST " + parameters); } /** * Sends a file to another user. Resuming is supported. * The other user must be able to connect directly to your bot to be * able to receive the file. * <p> * You may throttle the speed of this file transfer by calling the * setPacketDelay method on the DccFileTransfer that is returned. * <p> * This method may not be overridden. * * @since 0.9c * * @param file The file to send. * @param reciever The user to whom the file is to be sent. * @param timeout The number of milliseconds to wait for the recipient to * acccept the file (we recommend about 120000). * * @return The DccFileTransfer that can be used to monitor this transfer. * * @see DccFileTransfer * */ public DccFileTransfer dccSendFile(File file, User reciever, int timeout) { DccFileTransfer transfer = new DccFileTransfer(this, _dccManager, file, reciever, timeout); transfer.doSend(true); return transfer; } /** * Attempts to establish a DCC CHAT session with a client. This method * issues the connection request to the client and then waits for the * client to respond. If the connection is successfully made, then a * DccChat object is returned by this method. If the connection is not * made within the time limit specified by the timeout value, then null * is returned. * <p> * It is <b>strongly recommended</b> that you call this method within a new * Thread, as it may take a long time to return. * <p> * This method may not be overridden. * * @param sender The user object representing the user we are trying to * establish a chat with. * @param timeout The number of milliseconds to wait for the recipient to * accept the chat connection (we recommend about 120000). * * @return a DccChat object that can be used to send and recieve lines of * text. Returns <b>null</b> if the connection could not be made. * * @see DccChat * @since PircBotX 0.9.8 */ public DccChat dccSendChatRequest(User sender, int timeout) { DccChat chat = null; try { ServerSocket ss = null; int[] ports = getDccPorts(); if (ports == null) // Use any free port. ss = new ServerSocket(0); else { for (int i = 0; i < ports.length; i++) try { ss = new ServerSocket(ports[i]); // Found a port number we could use. break; } catch (Exception e) { // Do nothing; go round and try another port. } if (ss == null) // No ports could be used. throw new IOException("All ports returned by getDccPorts() are in use."); } ss.setSoTimeout(timeout); int port = ss.getLocalPort(); InetAddress inetAddress = getDccInetAddress(); if (inetAddress == null) inetAddress = getInetAddress(); byte[] ip = inetAddress.getAddress(); long ipNum = ipToLong(ip); sendCTCPCommand(sender, "DCC CHAT chat " + ipNum + " " + port); // The client may now connect to us to chat. Socket socket = ss.accept(); // Close the server socket now that we've finished with it. ss.close(); chat = new DccChat(this, sender, socket); } catch (Exception e) { // Do nothing. } return chat; } /** * Adds a line to the log. This log is currently output to the standard * output and is in the correct format for use by tools such as pisg, the * Perl IRC Statistics Generator. You may override this method if you wish * to do something else with log entries. * Each line in the log begins with a number which * represents the logging time (as the number of milliseconds since the * epoch). This timestamp and the following log entry are separated by * a single space character, " ". Outgoing messages are distinguishable * by a log entry that has ">>>" immediately following the space character * after the timestamp. DCC events use "+++" and warnings about unhandled * Exceptions and Errors use "###". * <p> * This implementation of the method will only cause log entries to be * output if the PircBotX has had its verbose mode turned on by calling * setVerbose(true); * * @param line The line to add to the log. */ @Synchronized(value = "logLock") public void log(String line) { if (_verbose) System.out.println(System.currentTimeMillis() + " " + line); } @Synchronized(value = "logLock") public void logException(Throwable t) { if (!_verbose) return; StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); StringTokenizer tokenizer = new StringTokenizer(sw.toString(), "\r\n"); log("### Your implementation of PircBotX is faulty and you have"); log("### allowed an uncaught Exception or Error to propagate in your"); log("### code. It may be possible for PircBotX to continue operating"); log("### normally. Here is the stack trace that was produced: -"); log("### "); while (tokenizer.hasMoreTokens()) log("### " + tokenizer.nextToken()); } /** * This method handles events when any line of text arrives from the server, * then calling the appropriate method in the PircBotX. This method is * protected and only called by the InputThread for this instance. * <p> * This method may not be overridden! * * @param line The raw line of text from the server. */ protected void handleLine(String line) { log("<<<" + line); // Check for server pings. if (line.startsWith("PING ")) { // Respond to the ping and return immediately. getListenerManager().dispatchEvent(new ServerPingEvent(this, line.substring(5))); return; } String sourceNick = ""; String sourceLogin = ""; String sourceHostname = ""; StringTokenizer tokenizer = new StringTokenizer(line); String senderInfo = tokenizer.nextToken(); String command = tokenizer.nextToken(); String target = null; int exclamation = senderInfo.indexOf("!"); int at = senderInfo.indexOf("@"); if (senderInfo.startsWith(":")) if (exclamation > 0 && at > 0 && exclamation < at) { sourceNick = senderInfo.substring(1, exclamation); sourceLogin = senderInfo.substring(exclamation + 1, at); sourceHostname = senderInfo.substring(at + 1); } else if (tokenizer.hasMoreTokens()) { String token = command; int code = -1; try { code = Integer.parseInt(token); } catch (NumberFormatException e) { // Keep the existing value. } if (code != -1) { String errorStr = token; String response = line.substring(line.indexOf(errorStr, senderInfo.length()) + 4, line.length()); processServerResponse(code, response); // Return from the method. return; } else // This is not a server response. // It must be a nick without login and hostname. // (or maybe a NOTICE or suchlike from the server) sourceNick = senderInfo; //WARNING: Changed from origional PircBot. Instead of command as target, use channel/user (setup later) } else { // We don't know what this line means. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); // Return from the method; return; } command = command.toUpperCase(); if (sourceNick.startsWith(":")) sourceNick = sourceNick.substring(1); if (target == null) target = tokenizer.nextToken(); if (target.startsWith(":")) target = target.substring(1); User source = getUser(sourceNick); //If the channel matches a prefix, then its a channel Channel channel = (_channelPrefixes.indexOf(target.charAt(0)) >= 0) ? getChannel(target) : null; // Check for CTCP requests. if (command.equals("PRIVMSG") && line.indexOf(":\u0001") > 0 && line.endsWith("\u0001")) { String request = line.substring(line.indexOf(":\u0001") + 2, line.length() - 1); if (request.equals("VERSION")) // VERSION request getListenerManager().dispatchEvent(new VersionEvent(this, source, channel)); else if (request.startsWith("ACTION ")) // ACTION request getListenerManager().dispatchEvent(new ActionEvent(this, source, channel, request.substring(7))); else if (request.startsWith("PING ")) // PING request getListenerManager().dispatchEvent(new PingEvent(this, source, channel, request.substring(5))); else if (request.equals("TIME")) // TIME request getListenerManager().dispatchEvent(new TimeEvent(this, source, channel)); else if (request.equals("FINGER")) // FINGER request getListenerManager().dispatchEvent(new FingerEvent(this, source, channel)); else if ((tokenizer = new StringTokenizer(request)).countTokens() >= 5 && tokenizer.nextToken().equals("DCC")) { // This is a DCC request. boolean success = _dccManager.processRequest(source, request); if (!success) // The DccManager didn't know what to do with the line. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); } else // An unknown CTCP message - ignore it. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); } else if (command.equals("PRIVMSG") && _channelPrefixes.indexOf(target.charAt(0)) >= 0) // This is a normal message to a channel. getListenerManager().dispatchEvent(new MessageEvent(this, channel, source, line.substring(line.indexOf(" :") + 2))); else if (command.equals("PRIVMSG")) // This is a private message to us. getListenerManager().dispatchEvent(new PrivateMessageEvent(this, source, line.substring(line.indexOf(" :") + 2))); else if (command.equals("JOIN")) { // Someone is joining a channel. if (sourceNick.equalsIgnoreCase(_nick)) { //Its us, do some setup (don't use channel var since channel doesn't exist yet) sendRawLine("WHO " + target); sendRawLine("MODE " + target); } source.setLogin(sourceLogin); source.setHostmask(sourceHostname); _userChanInfo.put(channel, source); getListenerManager().dispatchEvent(new JoinEvent(this, channel, source)); } else if (command.equals("PART")) // Someone is parting from a channel. if (sourceNick.equals(getNick())) //We parted the channel _userChanInfo.deleteA(channel); else { //Just remove the user from memory _userChanInfo.dissociate(channel, getUser(sourceNick)); getListenerManager().dispatchEvent(new PartEvent(this, channel, source)); } else if (command.equals("NICK")) { // Somebody is changing their nick. String newNick = target; getUser(sourceNick).setNick(newNick); if (sourceNick.equals(getNick())) // Update our nick if it was us that changed nick. setNick(newNick); getListenerManager().dispatchEvent(new NickChangeEvent(this, sourceNick, newNick, source)); } else if (command.equals("NOTICE")) // Someone is sending a notice. getListenerManager().dispatchEvent(new NoticeEvent(this, source, channel, line.substring(line.indexOf(" :") + 2))); else if (command.equals("QUIT")) { // Someone has quit from the IRC server. if (sourceNick.equals(getNick())) //We just quit the server _userChanInfo.clear(); else //Someone else _userChanInfo.deleteB(source); getListenerManager().dispatchEvent(new QuitEvent(this, source, line.substring(line.indexOf(" :") + 2))); } else if (command.equals("KICK")) { // Somebody has been kicked from a channel. - String recipient = tokenizer.nextToken(); - User user = getUser(sourceNick); - if (recipient.equals(getNick())) + User recipient = getUser(tokenizer.nextToken()); + if (recipient.getNick().equals(getNick())) //We were just kicked _userChanInfo.deleteA(channel); else //Someone else - _userChanInfo.dissociate(channel, user, true); - getListenerManager().dispatchEvent(new KickEvent(this, channel, source, getUser(recipient), line.substring(line.indexOf(" :") + 2))); + _userChanInfo.dissociate(channel, recipient, true); + getListenerManager().dispatchEvent(new KickEvent(this, channel, source, recipient, line.substring(line.indexOf(" :") + 2))); } else if (command.equals("MODE")) { // Somebody is changing the mode on a channel or user. String mode = line.substring(line.indexOf(target, 2) + target.length() + 1); if (mode.startsWith(":")) mode = mode.substring(1); processMode(target, sourceNick, sourceLogin, sourceHostname, mode); } else if (command.equals("TOPIC")) { // Someone is changing the topic. String topic = line.substring(line.indexOf(" :") + 2); long currentTime = System.currentTimeMillis(); channel.setTopic(topic); channel.setTopicSetter(sourceNick); channel.setTopicTimestamp(currentTime); getListenerManager().dispatchEvent(new TopicEvent(this, channel, topic, source, currentTime, true)); } else if (command.equals("INVITE")) { // Somebody is inviting somebody else into a channel. //Use line method instead of channel since channel is wrong getListenerManager().dispatchEvent(new InviteEvent(this, sourceNick, line.substring(line.indexOf(" :") + 2))); //Delete user if not part of any of our channels if (source.getChannels().isEmpty()) _userChanInfo.deleteB(source); } else // If we reach this point, then we've found something that the PircBotX // Doesn't currently deal with. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); } /** * This method is called by the PircBotX when a numeric response * is received from the IRC server. We use this method to * allow PircBotX to process various responses from the server * before then passing them on to the onServerResponse method. * <p> * Note that this method is private and should not appear in any * of the javadoc generated documenation. * * @param code The three-digit numerical code for the response. * @param response The full response from the IRC server. */ protected void processServerResponse(int code, String response) { //NOTE: Update tests if adding support for a new code String[] parsed = response.split(" "); if (code == RPL_LISTSTART) //EXAMPLE: 321 Channel :Users Name (actual text) //A channel list is about to be sent channelListBuilder.setRunning(true); else if (code == RPL_LIST) { //This is part of a full channel listing as part of /LIST //EXAMPLE: 322 lordquackstar #xomb 12 :xomb exokernel project @ www.xomb.org int firstSpace = response.indexOf(' '); int secondSpace = response.indexOf(' ', firstSpace + 1); int thirdSpace = response.indexOf(' ', secondSpace + 1); int colon = response.indexOf(':'); String channel = response.substring(firstSpace + 1, secondSpace); int userCount = 0; try { userCount = Integer.parseInt(response.substring(secondSpace + 1, thirdSpace)); } catch (NumberFormatException e) { // Stick with the value of zero. } String topic = response.substring(colon + 1); channelListBuilder.add(new ChannelListEntry(channel, userCount, topic)); } else if (code == RPL_LISTEND) { //EXAMPLE: 323 :End of /LIST //End of channel list, dispatch event getListenerManager().dispatchEvent(new ChannelInfoEvent(this, channelListBuilder.finish())); channelListBuilder.setRunning(false); } else if (code == RPL_TOPIC) { //EXAMPLE: 332 PircBotX #aChannel :I'm some random topic //This is topic about a channel we've just joined. From /JOIN or /TOPIC parsed = response.split(" ", 3); String channel = parsed[1]; String topic = parsed[2].substring(1); getChannel(channel).setTopic(topic); } else if (code == RPL_TOPICINFO) { //EXAMPLE: 333 PircBotX #aChannel ISetTopic 1564842512 //This is information on the topic of the channel we've just joined. From /JOIN or /TOPIC String channel = parsed[1]; User setBy = getUser(parsed[2]); long date = 0; try { date = Long.parseLong(parsed[3]) * 1000; } catch (NumberFormatException e) { // Stick with the default value of zero. } Channel chan = getChannel(channel); chan.setTopicTimestamp(date); chan.setTopicSetter(setBy.getNick()); getListenerManager().dispatchEvent(new TopicEvent(this, chan, chan.getTopic(), setBy, date, false)); } else if (code == RPL_NAMREPLY) { //EXAMPLE: 353 PircBotX = #aChannel :PircBotX @SuperOp someoneElse //This is a list of nicks in a channel that we've just joined. SPANS MULTIPLE LINES. From /NAMES and /JOIN parsed = response.split(" ", 4); Channel chan = getChannel(parsed[2]); for (String nick : parsed[3].substring(1).split(" ")) { User curUser = getUser(nick); if (nick.contains("@")) chan.addOp(curUser); if (nick.contains("+")) chan.addVoice(curUser); } } else if (code == RPL_ENDOFNAMES) { //EXAMPLE: 366 PircBotX #aChannel :End of /NAMES list // This is the end of a NAMES list, so we know that we've got // the full list of users in the channel that we just joined. From /NAMES and /JOIN String channelName = response.split(" ", 3)[1]; Channel channel = getChannel(channelName); getListenerManager().dispatchEvent(new UserListEvent(this, channel, getUsers(channel))); } else if (code == RPL_WHOREPLY) { //EXAMPLE: PircBotX #aChannel ~someName 74.56.56.56.my.Hostmask wolfe.freenode.net someNick H :0 Full Name //Part of a WHO reply on information on individual users parsed = response.split(" ", 9); Channel chan = getChannel(parsed[1]); User curUser = getUser(parsed[5]); //Only setup when needed if (Utils.isBlank(curUser.getLogin())) { curUser.setLogin(parsed[2]); curUser.setIdentified(parsed[2].startsWith("~")); curUser.setHostmask(parsed[3]); curUser.setServer(parsed[4]); curUser.setNick(parsed[5]); curUser.parseStatus(chan.getName(), parsed[6]); curUser.setHops(Integer.parseInt(parsed[7].substring(1))); curUser.setRealName(parsed[8]); } } else if (code == RPL_ENDOFWHO) { //EXAMPLE: PircBotX #aChannel :End of /WHO list //End of the WHO reply Channel channel = getChannel(response.split(" ")[1]); getListenerManager().dispatchEvent(new UserListEvent(this, channel, getUsers(channel))); } else if (code == RPL_CHANNELMODEIS) //EXAMPLE: PircBotX #aChannel +cnt //Full channel mode (In response to MODE <channel>) getChannel(parsed[1]).setMode(parsed[2]); else if (code == 329) { //EXAMPLE: 329 lordquackstar #botters 1199140245 //Tells when channel was created. Note mIRC says lordquackstar shouldn't be there while Freenode //displays it. From /JOIN(?) int createDate = -1; String channel = ""; //Freenode version try { createDate = Integer.parseInt(parsed[2]); channel = parsed[1]; } catch (NumberFormatException e) { //mIRC version createDate = Integer.parseInt(parsed[1]); channel = parsed[0]; } //Set in channel getChannel(channel).setCreateTimestamp(createDate); } else if (code == RPL_MOTDSTART) //Example: 375 PircBotX :- wolfe.freenode.net Message of the Day - //Motd is starting, reset the StringBuilder getServerInfo().setMotd(""); else if (code == RPL_MOTD) //Example: PircBotX :- Welcome to wolfe.freenode.net in Manchester, England, Uk! Thanks to //This is part of the MOTD, add a new line getServerInfo().setMotd(getServerInfo().getMotd() + response.split(" ", 3) + "\n"); else if (code == RPL_ENDOFMOTD) //Example: PircBotX :End of /MOTD command. //End of MOTD, dispatch event getListenerManager().dispatchEvent(new MotdEvent(this, (getServerInfo().getMotd()))); //WARNING: Parsed array might be modified, recreate if you're going to use down here getListenerManager().dispatchEvent(new ServerResponseEvent(this, code, response)); } /** * Called when the mode of a channel is set. We process this in * order to call the appropriate onOp, onDeop, etc method before * finally calling the override-able onMode method. * <p> * Note that this method is private and is not intended to appear * in the javadoc generated documentation. * * @param target The channel or nick that the mode operation applies to. * @param sourceNick The nick of the user that set the mode. * @param sourceLogin The login of the user that set the mode. * @param sourceHostname The hostname of the user that set the mode. * @param mode The mode that has been set. */ protected void processMode(String target, String sourceNick, String sourceLogin, String sourceHostname, String mode) { User source = getUser(sourceNick); if (_channelPrefixes.indexOf(target.charAt(0)) >= 0) { // The mode of a channel is being changed. Channel channel = getChannel(target); channel.parseMode(mode); StringTokenizer tok = new StringTokenizer(mode); String[] params = new String[tok.countTokens()]; int t = 0; while (tok.hasMoreTokens()) { params[t] = tok.nextToken(); t++; } char pn = ' '; int p = 1; // All of this is very large and ugly, but it's the only way of providing // what the users want :-/ for (int i = 0; i < params[0].length(); i++) { char atPos = params[0].charAt(i); if (atPos == '+' || atPos == '-') pn = atPos; else if (atPos == 'o') { User reciepeint = getUser(params[p]); if (pn == '+') { channel.addOp(reciepeint); getListenerManager().dispatchEvent(new OpEvent(this, channel, source, reciepeint)); } else { channel.removeOp(reciepeint); getListenerManager().dispatchEvent(new DeopEvent(this, channel, source, reciepeint)); } p++; } else if (atPos == 'v') { User reciepeint = getUser(params[p]); if (pn == '+') { channel.addVoice(reciepeint); getListenerManager().dispatchEvent(new VoiceEvent(this, channel, source, reciepeint)); } else { channel.removeVoice(reciepeint); getListenerManager().dispatchEvent(new DeVoiceEvent(this, channel, source, reciepeint)); } p++; } else if (atPos == 'k') { if (pn == '+') getListenerManager().dispatchEvent(new SetChannelKeyEvent(this, channel, source, params[p])); else getListenerManager().dispatchEvent(new RemoveChannelKeyEvent(this, channel, source, params[p])); p++; } else if (atPos == 'l') if (pn == '+') { getListenerManager().dispatchEvent(new SetChannelLimitEvent(this, channel, source, Integer.parseInt(params[p]))); p++; } else getListenerManager().dispatchEvent(new RemoveChannelLimitEvent(this, channel, source)); else if (atPos == 'b') { if (pn == '+') getListenerManager().dispatchEvent(new SetChannelBanEvent(this, channel, source, params[p])); else getListenerManager().dispatchEvent(new RemoveChannelBanEvent(this, channel, source, params[p])); p++; } else if (atPos == 't') if (pn == '+') getListenerManager().dispatchEvent(new SetTopicProtectionEvent(this, channel, source)); else getListenerManager().dispatchEvent(new RemoveTopicProtectionEvent(this, channel, source)); else if (atPos == 'n') if (pn == '+') getListenerManager().dispatchEvent(new SetNoExternalMessagesEvent(this, channel, source)); else getListenerManager().dispatchEvent(new RemoveNoExternalMessagesEvent(this, channel, source)); else if (atPos == 'i') if (pn == '+') getListenerManager().dispatchEvent(new SetInviteOnlyEvent(this, channel, source)); else getListenerManager().dispatchEvent(new RemoveInviteOnlyEvent(this, channel, source)); else if (atPos == 'm') if (pn == '+') getListenerManager().dispatchEvent(new SetModeratedEvent(this, channel, source)); else getListenerManager().dispatchEvent(new RemoveModeratedEvent(this, channel, source)); else if (atPos == 'p') if (pn == '+') getListenerManager().dispatchEvent(new SetPrivateEvent(this, channel, source)); else getListenerManager().dispatchEvent(new RemovePrivateEvent(this, channel, source)); else if (atPos == 's') if (pn == '+') getListenerManager().dispatchEvent(new SetSecretEvent(this, channel, source)); else getListenerManager().dispatchEvent(new RemoveSecretEvent(this, channel, source)); } getListenerManager().dispatchEvent(new ModeEvent(this, channel, source, mode)); } else { // The mode of a user is being changed. String nick = target; getListenerManager().dispatchEvent(new UserModeEvent(this, getUser(nick), source, mode)); } } /** * Sets the verbose mode. If verbose mode is set to true, then log entries * will be printed to the standard output. The default value is false and * will result in no output. For general development, we strongly recommend * setting the verbose mode to true. * * @param verbose true if verbose mode is to be used. Default is false. */ public void setVerbose(boolean verbose) { _verbose = verbose; } /** * Sets the name of the bot, which will be used as its nick when it * tries to join an IRC server. This should be set before joining * any servers, otherwise the default nick will be used. You would * typically call this method from the constructor of the class that * extends PircBotX. * <p> * The changeNick method should be used if you wish to change your nick * when you are connected to a server. * * @param name The new name of the Bot. */ public void setName(String name) { _name = name; } /** * Sets the internal nick of the bot. This is only to be called by the * PircBotX class in response to notification of nick changes that apply * to us. * * @param nick The new nick. */ protected void setNick(String nick) { _nick = nick; } /** * Sets the internal login of the Bot. This should be set before joining * any servers. * * @param login The new login of the Bot. */ public void setLogin(String login) { _login = login; } /** * Sets the internal version of the Bot. This should be set before joining * any servers. * * @param version The new version of the Bot. */ public void setVersion(String version) { _version = version; } /** * Sets the interal finger message. This should be set before joining * any servers. * * @param finger The new finger message for the Bot. */ public void setFinger(String finger) { _finger = finger; } /** * Gets the name of the PircBotX. This is the name that will be used as * as a nick when we try to join servers. * * @return The name of the PircBotX. */ public String getName() { return _name; } /** * Returns the current nick of the bot. Note that if you have just changed * your nick, this method will still return the old nick until confirmation * of the nick change is received from the server. * <p> * The nick returned by this method is maintained only by the PircBotX * class and is guaranteed to be correct in the context of the IRC server. * * @since PircBotX 1.0.0 * * @return The current nick of the bot. */ public String getNick() { return _nick; } /** * Gets the internal login of the PircBotX. * * @return The login of the PircBotX. */ public String getLogin() { return _login; } /** * Gets the internal version of the PircBotX. * * @return The version of the PircBotX. */ public String getVersion() { return _version; } /** * Gets the internal finger message of the PircBotX. * * @return The finger message of the PircBotX. */ public String getFinger() { return _finger; } /** * Returns whether or not the PircBotX is currently connected to a server. * The result of this method should only act as a rough guide, * as the result may not be valid by the time you act upon it. * * @return True if and only if the PircBotX is currently connected to a server. */ public boolean isConnected() { return _inputThread != null && _inputThread.isConnected(); } /** * Sets the number of milliseconds to delay between consecutive * messages when there are multiple messages waiting in the * outgoing message queue. This has a default value of 1000ms. * It is a good idea to stick to this default value, as it will * prevent your bot from spamming servers and facing the subsequent * wrath! However, if you do need to change this delay value (<b>not * recommended</b>), then this is the method to use. * * @param delay The number of milliseconds between each outgoing message. * */ public void setMessageDelay(long delay) { if (delay < 0) throw new IllegalArgumentException("Cannot have a negative time."); _messageDelay = delay; } /** * Returns the number of milliseconds that will be used to separate * consecutive messages to the server from the outgoing message queue. * * @return Number of milliseconds. */ public long getMessageDelay() { return _messageDelay; } /** * Gets the maximum length of any line that is sent via the IRC protocol. * The IRC RFC specifies that line lengths, including the trailing \r\n * must not exceed 512 bytes. Hence, there is currently no option to * change this value in PircBotX. All lines greater than this length * will be truncated before being sent to the IRC server. * * @return The maximum line length (currently fixed at 512) */ public int getMaxLineLength() { return InputThread.MAX_LINE_LENGTH; } /** * Gets the number of lines currently waiting in the outgoing message Queue. * If this returns 0, then the Queue is empty and any new message is likely * to be sent to the IRC server immediately. * * @since PircBotX 0.9.9 * * @return The number of lines in the outgoing message Queue. */ public int getOutgoingQueueSize() { return _outputThread.getQueueSize(); } /** * Returns the name of the last IRC server the PircBotX tried to connect to. * This does not imply that the connection attempt to the server was * successful (we suggest you look at the onConnect method). * A value of null is returned if the PircBotX has never tried to connect * to a server. * * @return The name of the last machine we tried to connect to. Returns * null if no connection attempts have ever been made. */ public String getServer() { return _server; } /** * Returns the port number of the last IRC server that the PircBotX tried * to connect to. * This does not imply that the connection attempt to the server was * successful (we suggest you look at the onConnect method). * A value of -1 is returned if the PircBotX has never tried to connect * to a server. * * @since PircBotX 0.9.9 * * @return The port number of the last IRC server we connected to. * Returns -1 if no connection attempts have ever been made. */ public int getPort() { return _port; } /** * Returns the last password that we used when connecting to an IRC server. * This does not imply that the connection attempt to the server was * successful (we suggest you look at the onConnect method). * A value of null is returned if the PircBotX has never tried to connect * to a server using a password. * * @since PircBotX 0.9.9 * * @return The last password that we used when connecting to an IRC server. * Returns null if we have not previously connected using a password. */ public String getPassword() { return _password; } /** * A convenient method that accepts an IP address represented as a * long and returns an integer array of size 4 representing the same * IP address. * * @since PircBotX 0.9.4 * * @param address the long value representing the IP address. * * @return An int[] of size 4. */ public int[] longToIp(long address) { int[] ip = new int[4]; for (int i = 3; i >= 0; i--) { ip[i] = (int) (address % 256); address = address / 256; } return ip; } /** * A convenient method that accepts an IP address represented by a byte[] * of size 4 and returns this as a long representation of the same IP * address. * * @since PircBotX 0.9.4 * * @param address the byte[] of size 4 representing the IP address. * * @return a long representation of the IP address. */ public long ipToLong(byte[] address) { if (address.length != 4) throw new IllegalArgumentException("byte array must be of length 4"); long ipNum = 0; long multiplier = 1; for (int i = 3; i >= 0; i--) { int byteVal = (address[i] + 256) % 256; ipNum += byteVal * multiplier; multiplier *= 256; } return ipNum; } /** * Sets the encoding charset to be used when sending or receiving lines * from the IRC server. If set to null, then the platform's default * charset is used. You should only use this method if you are * trying to send text to an IRC server in a different charset, e.g. * "GB2312" for Chinese encoding. If a PircBotX is currently connected * to a server, then it must reconnect before this change takes effect. * * @since PircBotX 1.0.4 * * @param charset The new encoding charset to be used by PircBotX. * * @throws UnsupportedEncodingException If the named charset is not * supported. */ public void setEncoding(String charset) throws UnsupportedEncodingException { // Just try to see if the charset is supported first... "".getBytes(charset); _charset = charset; } /** * Returns the encoding used to send and receive lines from * the IRC server, or null if not set. Use the setEncoding * method to change the encoding charset. * * @since PircBotX 1.0.4 * * @return The encoding used to send outgoing messages, or * null if not set. */ public String getEncoding() { return _charset; } /** * Returns the InetAddress used by the PircBotX. * This can be used to find the I.P. address from which the PircBotX is * connected to a server. * * @since PircBotX 1.4.4 * * @return The current local InetAddress, or null if never connected. */ public InetAddress getInetAddress() { return _inetAddress; } /** * Sets the InetAddress to be used when sending DCC chat or file transfers. * This can be very useful when you are running a bot on a machine which * is behind a firewall and you need to tell receiving clients to connect * to a NAT/router, which then forwards the connection. * * @since PircBotX 1.4.4 * * @param dccInetAddress The new InetAddress, or null to use the default. */ public void setDccInetAddress(InetAddress dccInetAddress) { _dccInetAddress = dccInetAddress; } /** * Returns the InetAddress used when sending DCC chat or file transfers. * If this is null, the default InetAddress will be used. * * @since PircBotX 1.4.4 * * @return The current DCC InetAddress, or null if left as default. */ public InetAddress getDccInetAddress() { return _dccInetAddress; } /** * Returns the set of port numbers to be used when sending a DCC chat * or file transfer. This is useful when you are behind a firewall and * need to set up port forwarding. The array of port numbers is traversed * in sequence until a free port is found to listen on. A DCC tranfer will * fail if all ports are already in use. * If set to null, <i>any</i> free port number will be used. * * @since PircBotX 1.4.4 * * @return An array of port numbers that PircBotX can use to send DCC * transfers, or null if any port is allowed. */ public int[] getDccPorts() { if (_dccPorts == null || _dccPorts.length == 0) return null; // Clone the array to prevent external modification. return (int[]) _dccPorts.clone(); } /** * Sets the choice of port numbers that can be used when sending a DCC chat * or file transfer. This is useful when you are behind a firewall and * need to set up port forwarding. The array of port numbers is traversed * in sequence until a free port is found to listen on. A DCC transfer will * fail if all ports are already in use. * If set to null, <i>any</i> free port number will be used. * * @since PircBotX 1.4.4 * * @param ports The set of port numbers that PircBotX may use for DCC * transfers, or null to let it use any free port (default). * */ public void setDccPorts(int[] ports) { if (ports == null || ports.length == 0) _dccPorts = null; else // Clone the array to prevent external modification. _dccPorts = (int[]) ports.clone(); } /** * Returns a String representation of this object. * You may find this useful for debugging purposes, particularly * if you are using more than one PircBotX instance to achieve * multiple server connectivity. The format of * this String may change between different versions of PircBotX * but is currently something of the form * <code> * Version{PircBotX x.y.z Java IRC Bot - www.jibble.org} * Connected{true} * Server{irc.dal.net} * Port{6667} * Password{} * </code> * * @since PircBotX 0.9.10 * * @return a String representation of this object. */ @Override public String toString() { return "Version{" + _version + "}" + " Connected{" + isConnected() + "}" + " Server{" + _server + "}" + " Port{" + _port + "}" + " Password{" + _password + "}"; } /** * Disposes of all thread resources used by this PircBotX. This may be * useful when writing bots or clients that use multiple servers (and * therefore multiple PircBotX instances) or when integrating a PircBotX * with an existing program. * <p> * Each PircBotX runs its own threads for dispatching messages from its * outgoing message queue and receiving messages from the server. * Calling dispose() ensures that these threads are * stopped, thus freeing up system resources and allowing the PircBotX * object to be garbage collected if there are no other references to * it. * <p> * Once a PircBotX object has been disposed, it should not be used again. * Attempting to use a PircBotX that has been disposed may result in * unpredictable behaviour. * * @since 1.2.2 */ public synchronized void dispose() { log("disposing..."); //Close the socket from here and let the threads die try { _socket.close(); } catch (Exception e) { //Something went wrong, interrupt to make sure they are closed _outputThread.interrupt(); _inputThread.interrupt(); } } /** * The number of milliseconds to wait before the socket times out on read * operations. This does not mean the socket is invalid. By default its 5 * minutes * @return the socketTimeout */ public int getSocketTimeout() { return socketTimeout; } /** * The number of milliseconds to wait before the socket times out on read * operations. This does not mean the socket is invalid. By default its 5 * minutes * @param socketTimeout the socketTimeout to set */ public void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; } /** * Returns an array of all channels that we are in. Note that if you * call this method immediately after joining a new channel, the new * channel may not appear in this array as it is not possible to tell * if the join was successful until a response is received from the * IRC server. * * @since PircBotX 1.0.0 * * @return An <i>unmodifiable</i> Set of all channels were connected to */ public Set<Channel> getChannels() { return _userChanInfo.getAValues(); } /** * Get all channels that the given user is connected to * @param user The user to lookup * @return An <i>unmodifiable</i> Set of user's in the channel */ public Set<Channel> getChannels(User user) { if (user == null) throw new NullPointerException("Can't get a null user"); return _userChanInfo.getAValues(user); } /** * Gets a channel or creates a <u>new</u> one. Never returns null * @param name The name of the channel * @return The channel object requested, never null */ public Channel getChannel(String name) { if (name == null) throw new NullPointerException("Can't get a null channel"); for (Channel curChan : _userChanInfo.getAValues()) if (curChan.getName().equals(name)) return curChan; //Channel does not exist, create one Channel chan = new Channel(this, name); _userChanInfo.putB(chan); return chan; } /** * Gets all the name's of all the channels that we are connected to * @return An <i>Unmodifiable</i> set of Channel names */ public Set<String> getChannelsNames() { return Collections.unmodifiableSet(new HashSet<String>() { { for (Channel curChan : _userChanInfo.getAValues()) add(curChan.getName()); } }); } /** * Check if we are still connected to given channel by string. * @param channel A channel name as a string * @return True if we are still connected to the channel, false if not */ public boolean channelExists(String channel) { for (Channel curChan : _userChanInfo.getAValues()) if (curChan.getName().equals(channel)) return true; return false; } /** * Get all user's in the channel. * * There are some important things to note about this method:- * <ul> * <li>This method may not return a full list of users if you call it * before the complete nick list has arrived from the IRC server. * </li> * <li>If you wish to find out which users are in a channel as soon * as you join it, then you should listen for a {@link UserListEvent} * instead of calling this method, as the {@link UserListEvent} is only * dispatched as soon as the full user list has been received. * </li> * <li>This method will return immediately, as it does not require any * interaction with the IRC server. * </li> * <li>The bot must be in a channel to be able to know which users are * in it. * </li> * </ul> * * @since PircBotX 1.0.0 * * @param chan The channel object to search in * @return A Set of all user's in the channel * * @see UserListEvent */ public Set<User> getUsers(Channel chan) { if (chan == null) throw new NullPointerException("Can't get a null channel"); return _userChanInfo.getBValues(chan); } /** * Gets an existing user or creates a new one. * @param nick * @return The requested User. Never is null */ public User getUser(String nick) { if (nick == null) throw new NullPointerException("Can't get a null user"); for (User curUser : _userChanInfo.getBValues()) if (curUser.getNick().equals(nick)) return curUser; //User does not exist, create one User user = new User(this, nick); _userChanInfo.putA(user); return user; } /** * Check if a user exists * @param nick The nick of the user to lookup * @return True if they exist, false if not */ public boolean userExists(String nick) { for (User curUser : _userChanInfo.getBValues()) if (curUser.getNick().equals(nick)) return true; return false; } /** * @return the serverInfo */ public ServerInfo getServerInfo() { return serverInfo; } /** * Returns the current ListenerManager in use by this bot. * @return Current ListenerManager */ public ListenerManager getListenerManager() { return listenerManager; } /** * Sets a new ListenerManager. <b>NOTE:</b> The {@link CoreHooks} are added * when this method is called. If you do not want this, remove CoreHooks with * {@link ListenerManager#removeListener(org.pircbotx.hooks.Listener) } * @param listenerManager The listener manager */ public void setListenerManager(ListenerManager<? extends PircBotX> listenerManager) { this.listenerManager = listenerManager; //Check if corehooks already exist for (Listener curListener : listenerManager.getListeners()) if (curListener instanceof CoreHooks) return; listenerManager.addListener(new CoreHooks()); } /** * Returns the last SocketFactory that we used to connect to an IRC server. * This does not imply that the connection attempt to the server was * successful (we suggest you look at the onConnect method). * A value of null is returned if the PircBot has never tried to connect * to a server using a SocketFactory. * * @return The last SocketFactory that we used when connecting to an IRC server. * Returns null if we have not previously connected using a SocketFactory. */ public SocketFactory getSocketFactory() { return _socketFactory; } /** * Get current verbose mode * @return True if verbose is turned on, false if not */ public boolean isVerbose() { return _verbose; } /** * Get current auto nick change mode * @return True if auto nick change is turned on, false otherwise */ public boolean isAutoNickChange() { return _autoNickChange; } /** * Reset bot, clearing all internal fields */ void reset() { //Clear the user-channel map _userChanInfo.clear(); //Clear any existing channel list channelListBuilder.finish(); //Clear any information that might be provided in another connect() method _server = null; _port = -1; _password = null; _inetAddress = null; _socket = null; } /** * Using the specified eventClass, block until the Event occurs. Eg wait for * a response from a user, capturing the MessageEvent or PrivateMessageEvent. * <p> * <b>Warning:</b> The listener manager in use <i>must</i> support multithreading. * If not, the entire bot will freeze since its waiting in the same thread * that's reading input from the server. This means you <i>can't</i> use * {@link GenericListenerManager}. * @param eventClass The class representing the Event to capture * @return The requested event * @throws InterruptedException If the thread is interrupted, this exception * is thrown */ public <E extends Event> E waitFor(Class<? extends E> eventClass) throws InterruptedException { //Create a WaitListener for getting the event WaitListener waitListener = new WaitListener(); listenerManager.addListener(waitListener); //Call waitFor which blocks until the desired event is captured Event finalEvent = waitListener.waitFor(eventClass); //Remove listener since its no longer needed listenerManager.removeListener(waitListener); //Return requested listener return (E) finalEvent; } /** * A listener that waits for the specified event before returning. Used in * {@link PircBotX#waitFor(java.lang.Class) } */ protected class WaitListener implements Listener { protected CountDownLatch signal = new CountDownLatch(1); protected Class<? extends Event> eventClass; protected Event endEvent; public void onEvent(Event event) throws Exception { if (eventClass.isInstance(event)) { endEvent = event; //Unblock waitFor now that we have an event signal.countDown(); } } /** * Block until the Event represented by the given class is passed * @param event A class representing the event to wait for * @return The specified event * @throws InterruptedException If the thread is interrupted, this exception * is thrown */ public Event waitFor(Class<? extends Event> event) throws InterruptedException { eventClass = event; signal.await(); return endEvent; } } protected class ListBuilder<A> { @Getter @Setter private boolean running = false; private Set<A> channels = new HashSet(); public Set<A> finish() { running = false; Set<A> copy = new HashSet(channels); channels.clear(); return copy; } public void add(A entry) { running = true; channels.add(entry); } } }
false
true
protected void handleLine(String line) { log("<<<" + line); // Check for server pings. if (line.startsWith("PING ")) { // Respond to the ping and return immediately. getListenerManager().dispatchEvent(new ServerPingEvent(this, line.substring(5))); return; } String sourceNick = ""; String sourceLogin = ""; String sourceHostname = ""; StringTokenizer tokenizer = new StringTokenizer(line); String senderInfo = tokenizer.nextToken(); String command = tokenizer.nextToken(); String target = null; int exclamation = senderInfo.indexOf("!"); int at = senderInfo.indexOf("@"); if (senderInfo.startsWith(":")) if (exclamation > 0 && at > 0 && exclamation < at) { sourceNick = senderInfo.substring(1, exclamation); sourceLogin = senderInfo.substring(exclamation + 1, at); sourceHostname = senderInfo.substring(at + 1); } else if (tokenizer.hasMoreTokens()) { String token = command; int code = -1; try { code = Integer.parseInt(token); } catch (NumberFormatException e) { // Keep the existing value. } if (code != -1) { String errorStr = token; String response = line.substring(line.indexOf(errorStr, senderInfo.length()) + 4, line.length()); processServerResponse(code, response); // Return from the method. return; } else // This is not a server response. // It must be a nick without login and hostname. // (or maybe a NOTICE or suchlike from the server) sourceNick = senderInfo; //WARNING: Changed from origional PircBot. Instead of command as target, use channel/user (setup later) } else { // We don't know what this line means. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); // Return from the method; return; } command = command.toUpperCase(); if (sourceNick.startsWith(":")) sourceNick = sourceNick.substring(1); if (target == null) target = tokenizer.nextToken(); if (target.startsWith(":")) target = target.substring(1); User source = getUser(sourceNick); //If the channel matches a prefix, then its a channel Channel channel = (_channelPrefixes.indexOf(target.charAt(0)) >= 0) ? getChannel(target) : null; // Check for CTCP requests. if (command.equals("PRIVMSG") && line.indexOf(":\u0001") > 0 && line.endsWith("\u0001")) { String request = line.substring(line.indexOf(":\u0001") + 2, line.length() - 1); if (request.equals("VERSION")) // VERSION request getListenerManager().dispatchEvent(new VersionEvent(this, source, channel)); else if (request.startsWith("ACTION ")) // ACTION request getListenerManager().dispatchEvent(new ActionEvent(this, source, channel, request.substring(7))); else if (request.startsWith("PING ")) // PING request getListenerManager().dispatchEvent(new PingEvent(this, source, channel, request.substring(5))); else if (request.equals("TIME")) // TIME request getListenerManager().dispatchEvent(new TimeEvent(this, source, channel)); else if (request.equals("FINGER")) // FINGER request getListenerManager().dispatchEvent(new FingerEvent(this, source, channel)); else if ((tokenizer = new StringTokenizer(request)).countTokens() >= 5 && tokenizer.nextToken().equals("DCC")) { // This is a DCC request. boolean success = _dccManager.processRequest(source, request); if (!success) // The DccManager didn't know what to do with the line. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); } else // An unknown CTCP message - ignore it. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); } else if (command.equals("PRIVMSG") && _channelPrefixes.indexOf(target.charAt(0)) >= 0) // This is a normal message to a channel. getListenerManager().dispatchEvent(new MessageEvent(this, channel, source, line.substring(line.indexOf(" :") + 2))); else if (command.equals("PRIVMSG")) // This is a private message to us. getListenerManager().dispatchEvent(new PrivateMessageEvent(this, source, line.substring(line.indexOf(" :") + 2))); else if (command.equals("JOIN")) { // Someone is joining a channel. if (sourceNick.equalsIgnoreCase(_nick)) { //Its us, do some setup (don't use channel var since channel doesn't exist yet) sendRawLine("WHO " + target); sendRawLine("MODE " + target); } source.setLogin(sourceLogin); source.setHostmask(sourceHostname); _userChanInfo.put(channel, source); getListenerManager().dispatchEvent(new JoinEvent(this, channel, source)); } else if (command.equals("PART")) // Someone is parting from a channel. if (sourceNick.equals(getNick())) //We parted the channel _userChanInfo.deleteA(channel); else { //Just remove the user from memory _userChanInfo.dissociate(channel, getUser(sourceNick)); getListenerManager().dispatchEvent(new PartEvent(this, channel, source)); } else if (command.equals("NICK")) { // Somebody is changing their nick. String newNick = target; getUser(sourceNick).setNick(newNick); if (sourceNick.equals(getNick())) // Update our nick if it was us that changed nick. setNick(newNick); getListenerManager().dispatchEvent(new NickChangeEvent(this, sourceNick, newNick, source)); } else if (command.equals("NOTICE")) // Someone is sending a notice. getListenerManager().dispatchEvent(new NoticeEvent(this, source, channel, line.substring(line.indexOf(" :") + 2))); else if (command.equals("QUIT")) { // Someone has quit from the IRC server. if (sourceNick.equals(getNick())) //We just quit the server _userChanInfo.clear(); else //Someone else _userChanInfo.deleteB(source); getListenerManager().dispatchEvent(new QuitEvent(this, source, line.substring(line.indexOf(" :") + 2))); } else if (command.equals("KICK")) { // Somebody has been kicked from a channel. String recipient = tokenizer.nextToken(); User user = getUser(sourceNick); if (recipient.equals(getNick())) //We were just kicked _userChanInfo.deleteA(channel); else //Someone else _userChanInfo.dissociate(channel, user, true); getListenerManager().dispatchEvent(new KickEvent(this, channel, source, getUser(recipient), line.substring(line.indexOf(" :") + 2))); } else if (command.equals("MODE")) { // Somebody is changing the mode on a channel or user. String mode = line.substring(line.indexOf(target, 2) + target.length() + 1); if (mode.startsWith(":")) mode = mode.substring(1); processMode(target, sourceNick, sourceLogin, sourceHostname, mode); } else if (command.equals("TOPIC")) { // Someone is changing the topic. String topic = line.substring(line.indexOf(" :") + 2); long currentTime = System.currentTimeMillis(); channel.setTopic(topic); channel.setTopicSetter(sourceNick); channel.setTopicTimestamp(currentTime); getListenerManager().dispatchEvent(new TopicEvent(this, channel, topic, source, currentTime, true)); } else if (command.equals("INVITE")) { // Somebody is inviting somebody else into a channel. //Use line method instead of channel since channel is wrong getListenerManager().dispatchEvent(new InviteEvent(this, sourceNick, line.substring(line.indexOf(" :") + 2))); //Delete user if not part of any of our channels if (source.getChannels().isEmpty()) _userChanInfo.deleteB(source); } else // If we reach this point, then we've found something that the PircBotX // Doesn't currently deal with. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); }
protected void handleLine(String line) { log("<<<" + line); // Check for server pings. if (line.startsWith("PING ")) { // Respond to the ping and return immediately. getListenerManager().dispatchEvent(new ServerPingEvent(this, line.substring(5))); return; } String sourceNick = ""; String sourceLogin = ""; String sourceHostname = ""; StringTokenizer tokenizer = new StringTokenizer(line); String senderInfo = tokenizer.nextToken(); String command = tokenizer.nextToken(); String target = null; int exclamation = senderInfo.indexOf("!"); int at = senderInfo.indexOf("@"); if (senderInfo.startsWith(":")) if (exclamation > 0 && at > 0 && exclamation < at) { sourceNick = senderInfo.substring(1, exclamation); sourceLogin = senderInfo.substring(exclamation + 1, at); sourceHostname = senderInfo.substring(at + 1); } else if (tokenizer.hasMoreTokens()) { String token = command; int code = -1; try { code = Integer.parseInt(token); } catch (NumberFormatException e) { // Keep the existing value. } if (code != -1) { String errorStr = token; String response = line.substring(line.indexOf(errorStr, senderInfo.length()) + 4, line.length()); processServerResponse(code, response); // Return from the method. return; } else // This is not a server response. // It must be a nick without login and hostname. // (or maybe a NOTICE or suchlike from the server) sourceNick = senderInfo; //WARNING: Changed from origional PircBot. Instead of command as target, use channel/user (setup later) } else { // We don't know what this line means. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); // Return from the method; return; } command = command.toUpperCase(); if (sourceNick.startsWith(":")) sourceNick = sourceNick.substring(1); if (target == null) target = tokenizer.nextToken(); if (target.startsWith(":")) target = target.substring(1); User source = getUser(sourceNick); //If the channel matches a prefix, then its a channel Channel channel = (_channelPrefixes.indexOf(target.charAt(0)) >= 0) ? getChannel(target) : null; // Check for CTCP requests. if (command.equals("PRIVMSG") && line.indexOf(":\u0001") > 0 && line.endsWith("\u0001")) { String request = line.substring(line.indexOf(":\u0001") + 2, line.length() - 1); if (request.equals("VERSION")) // VERSION request getListenerManager().dispatchEvent(new VersionEvent(this, source, channel)); else if (request.startsWith("ACTION ")) // ACTION request getListenerManager().dispatchEvent(new ActionEvent(this, source, channel, request.substring(7))); else if (request.startsWith("PING ")) // PING request getListenerManager().dispatchEvent(new PingEvent(this, source, channel, request.substring(5))); else if (request.equals("TIME")) // TIME request getListenerManager().dispatchEvent(new TimeEvent(this, source, channel)); else if (request.equals("FINGER")) // FINGER request getListenerManager().dispatchEvent(new FingerEvent(this, source, channel)); else if ((tokenizer = new StringTokenizer(request)).countTokens() >= 5 && tokenizer.nextToken().equals("DCC")) { // This is a DCC request. boolean success = _dccManager.processRequest(source, request); if (!success) // The DccManager didn't know what to do with the line. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); } else // An unknown CTCP message - ignore it. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); } else if (command.equals("PRIVMSG") && _channelPrefixes.indexOf(target.charAt(0)) >= 0) // This is a normal message to a channel. getListenerManager().dispatchEvent(new MessageEvent(this, channel, source, line.substring(line.indexOf(" :") + 2))); else if (command.equals("PRIVMSG")) // This is a private message to us. getListenerManager().dispatchEvent(new PrivateMessageEvent(this, source, line.substring(line.indexOf(" :") + 2))); else if (command.equals("JOIN")) { // Someone is joining a channel. if (sourceNick.equalsIgnoreCase(_nick)) { //Its us, do some setup (don't use channel var since channel doesn't exist yet) sendRawLine("WHO " + target); sendRawLine("MODE " + target); } source.setLogin(sourceLogin); source.setHostmask(sourceHostname); _userChanInfo.put(channel, source); getListenerManager().dispatchEvent(new JoinEvent(this, channel, source)); } else if (command.equals("PART")) // Someone is parting from a channel. if (sourceNick.equals(getNick())) //We parted the channel _userChanInfo.deleteA(channel); else { //Just remove the user from memory _userChanInfo.dissociate(channel, getUser(sourceNick)); getListenerManager().dispatchEvent(new PartEvent(this, channel, source)); } else if (command.equals("NICK")) { // Somebody is changing their nick. String newNick = target; getUser(sourceNick).setNick(newNick); if (sourceNick.equals(getNick())) // Update our nick if it was us that changed nick. setNick(newNick); getListenerManager().dispatchEvent(new NickChangeEvent(this, sourceNick, newNick, source)); } else if (command.equals("NOTICE")) // Someone is sending a notice. getListenerManager().dispatchEvent(new NoticeEvent(this, source, channel, line.substring(line.indexOf(" :") + 2))); else if (command.equals("QUIT")) { // Someone has quit from the IRC server. if (sourceNick.equals(getNick())) //We just quit the server _userChanInfo.clear(); else //Someone else _userChanInfo.deleteB(source); getListenerManager().dispatchEvent(new QuitEvent(this, source, line.substring(line.indexOf(" :") + 2))); } else if (command.equals("KICK")) { // Somebody has been kicked from a channel. User recipient = getUser(tokenizer.nextToken()); if (recipient.getNick().equals(getNick())) //We were just kicked _userChanInfo.deleteA(channel); else //Someone else _userChanInfo.dissociate(channel, recipient, true); getListenerManager().dispatchEvent(new KickEvent(this, channel, source, recipient, line.substring(line.indexOf(" :") + 2))); } else if (command.equals("MODE")) { // Somebody is changing the mode on a channel or user. String mode = line.substring(line.indexOf(target, 2) + target.length() + 1); if (mode.startsWith(":")) mode = mode.substring(1); processMode(target, sourceNick, sourceLogin, sourceHostname, mode); } else if (command.equals("TOPIC")) { // Someone is changing the topic. String topic = line.substring(line.indexOf(" :") + 2); long currentTime = System.currentTimeMillis(); channel.setTopic(topic); channel.setTopicSetter(sourceNick); channel.setTopicTimestamp(currentTime); getListenerManager().dispatchEvent(new TopicEvent(this, channel, topic, source, currentTime, true)); } else if (command.equals("INVITE")) { // Somebody is inviting somebody else into a channel. //Use line method instead of channel since channel is wrong getListenerManager().dispatchEvent(new InviteEvent(this, sourceNick, line.substring(line.indexOf(" :") + 2))); //Delete user if not part of any of our channels if (source.getChannels().isEmpty()) _userChanInfo.deleteB(source); } else // If we reach this point, then we've found something that the PircBotX // Doesn't currently deal with. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); }
diff --git a/net.sf.rcer.jcoimport/src/net/sf/rcer/jcoimport/JCoImportWizard.java b/net.sf.rcer.jcoimport/src/net/sf/rcer/jcoimport/JCoImportWizard.java index f508d3d..8808fed 100644 --- a/net.sf.rcer.jcoimport/src/net/sf/rcer/jcoimport/JCoImportWizard.java +++ b/net.sf.rcer.jcoimport/src/net/sf/rcer/jcoimport/JCoImportWizard.java @@ -1,106 +1,106 @@ /** * Copyright (c) 2008 The RCER Development Team. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. If redistributing this code, * this entire header must remain intact. * * $Id$ */ package net.sf.rcer.jcoimport; import java.io.File; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.ui.IImportWizard; import org.eclipse.ui.IWorkbench; /** * A wizard to import the SAP Java Connector archives and create the necessary plug-ins. * @author vwegert * */ public class JCoImportWizard extends Wizard implements IImportWizard { private ProjectGeneratorSettings generatorSettings; private DataBindingContext context; private DownloadPage downloadPage; private ArchiveFilesPage archiveFilesPage; private SummaryPage summaryPage; /** * Default constructor. */ public JCoImportWizard() { super(); } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection) */ public void init(IWorkbench workbench, IStructuredSelection selection) { setWindowTitle(Messages.JCoImportWizard_WindowTitle); setNeedsProgressMonitor(true); generatorSettings = new ProjectGeneratorSettings(); if (Platform.getInstallLocation() != null) { generatorSettings.setBundleExportSelected(true); // TODO use some API to locate the dropins folder - generatorSettings.setExportPath(Platform.getInstallLocation().getURL().getFile() + "dropins" + File.pathSeparator + "sapjco"); //$NON-NLS-1$ $NON-NLS-2$ + generatorSettings.setExportPath(Platform.getInstallLocation().getURL().getFile() + "dropins" + File.separator + "sapjco"); //$NON-NLS-1$ $NON-NLS-2$ } context = new DataBindingContext(); downloadPage = new DownloadPage(); archiveFilesPage = new ArchiveFilesPage(context, generatorSettings); summaryPage = new SummaryPage(context, generatorSettings); } /* (non-Javadoc) * @see org.eclipse.jface.wizard.IWizard#addPages() */ @Override public void addPages() { super.addPages(); addPage(downloadPage); addPage(archiveFilesPage); addPage(summaryPage); } /* (non-Javadoc) * @see org.eclipse.jface.wizard.Wizard#canFinish() */ @Override public boolean canFinish() { return super.canFinish() && getContainer().getCurrentPage() == summaryPage; } /* (non-Javadoc) * @see org.eclipse.jface.wizard.Wizard#performFinish() */ @Override public boolean performFinish() { context.updateModels(); try { getContainer().run(true, true, new ProjectGenerator(generatorSettings)); return true; } catch (InvocationTargetException e) { ErrorDialog.openError(getShell(), Messages.JCoImportWizard_DialogTitle, e.getLocalizedMessage(), new Status(IStatus.ERROR, "net.sf.rcer.jcoimport", Messages.JCoImportWizard_ErrorMessage, e)); //$NON-NLS-1$ return false; } catch (InterruptedException e) { MessageDialog.openWarning(getShell(), Messages.JCoImportWizard_DialogTitle, Messages.JCoImportWizard_ImportCancelledMessage); return false; } } }
true
true
public void init(IWorkbench workbench, IStructuredSelection selection) { setWindowTitle(Messages.JCoImportWizard_WindowTitle); setNeedsProgressMonitor(true); generatorSettings = new ProjectGeneratorSettings(); if (Platform.getInstallLocation() != null) { generatorSettings.setBundleExportSelected(true); // TODO use some API to locate the dropins folder generatorSettings.setExportPath(Platform.getInstallLocation().getURL().getFile() + "dropins" + File.pathSeparator + "sapjco"); //$NON-NLS-1$ $NON-NLS-2$ } context = new DataBindingContext(); downloadPage = new DownloadPage(); archiveFilesPage = new ArchiveFilesPage(context, generatorSettings); summaryPage = new SummaryPage(context, generatorSettings); }
public void init(IWorkbench workbench, IStructuredSelection selection) { setWindowTitle(Messages.JCoImportWizard_WindowTitle); setNeedsProgressMonitor(true); generatorSettings = new ProjectGeneratorSettings(); if (Platform.getInstallLocation() != null) { generatorSettings.setBundleExportSelected(true); // TODO use some API to locate the dropins folder generatorSettings.setExportPath(Platform.getInstallLocation().getURL().getFile() + "dropins" + File.separator + "sapjco"); //$NON-NLS-1$ $NON-NLS-2$ } context = new DataBindingContext(); downloadPage = new DownloadPage(); archiveFilesPage = new ArchiveFilesPage(context, generatorSettings); summaryPage = new SummaryPage(context, generatorSettings); }
diff --git a/src/com/undeadscythes/udsplugin/eventhandlers/PlayerInteractEntity.java b/src/com/undeadscythes/udsplugin/eventhandlers/PlayerInteractEntity.java index 13995e4..2652e56 100644 --- a/src/com/undeadscythes/udsplugin/eventhandlers/PlayerInteractEntity.java +++ b/src/com/undeadscythes/udsplugin/eventhandlers/PlayerInteractEntity.java @@ -1,41 +1,35 @@ package com.undeadscythes.udsplugin.eventhandlers; import com.undeadscythes.udsplugin.*; import org.bukkit.entity.*; import org.bukkit.event.*; import org.bukkit.event.player.*; /** * When a player interacts with an entity. * @author UndeadScythes */ public class PlayerInteractEntity extends ListenerWrapper implements Listener { @EventHandler - public void onEvent(final PlayerInteractEntityEvent event) { + public final void onEvent(final PlayerInteractEntityEvent event) { if(event.getRightClicked() instanceof Tameable) { - final Tameable pet = (Tameable) event.getRightClicked(); + final Tameable pet = (Tameable)event.getRightClicked(); if(pet.isTamed()) { - String ownerName = ""; - if(pet instanceof Wolf) { - ownerName = ((Wolf)pet).getOwner().getName(); - } - if(pet instanceof Ocelot) { - ownerName = ((Ocelot)pet).getOwner().getName(); - } - if(ownerName.equals(event.getPlayer().getName())) { + final String ownerName = pet.getOwner().getName(); + if(ownerName.equals(event.getPlayer().getName()) && event.getPlayer().isSneaking()) { UDSPlugin.getPlayers().get(event.getPlayer().getName()).selectPet(event.getRightClicked().getUniqueId()); event.getPlayer().sendMessage(Color.MESSAGE + "Pet selected."); event.setCancelled(true); - } else if(event.getPlayer().isSneaking()){ + } else { event.getPlayer().sendMessage(Color.MESSAGE + "This animal belongs to " + UDSPlugin.getPlayers().get(ownerName).getNick()); } } } else if(event.getRightClicked() instanceof ItemFrame) { final SaveablePlayer player = UDSPlugin.getPlayers().get(event.getPlayer().getName()); if(!(player.canBuildHere(event.getRightClicked().getLocation()))) { event.setCancelled(true); player.sendMessage(Message.CANT_BUILD_HERE); } } } }
false
true
public void onEvent(final PlayerInteractEntityEvent event) { if(event.getRightClicked() instanceof Tameable) { final Tameable pet = (Tameable) event.getRightClicked(); if(pet.isTamed()) { String ownerName = ""; if(pet instanceof Wolf) { ownerName = ((Wolf)pet).getOwner().getName(); } if(pet instanceof Ocelot) { ownerName = ((Ocelot)pet).getOwner().getName(); } if(ownerName.equals(event.getPlayer().getName())) { UDSPlugin.getPlayers().get(event.getPlayer().getName()).selectPet(event.getRightClicked().getUniqueId()); event.getPlayer().sendMessage(Color.MESSAGE + "Pet selected."); event.setCancelled(true); } else if(event.getPlayer().isSneaking()){ event.getPlayer().sendMessage(Color.MESSAGE + "This animal belongs to " + UDSPlugin.getPlayers().get(ownerName).getNick()); } } } else if(event.getRightClicked() instanceof ItemFrame) { final SaveablePlayer player = UDSPlugin.getPlayers().get(event.getPlayer().getName()); if(!(player.canBuildHere(event.getRightClicked().getLocation()))) { event.setCancelled(true); player.sendMessage(Message.CANT_BUILD_HERE); } } }
public final void onEvent(final PlayerInteractEntityEvent event) { if(event.getRightClicked() instanceof Tameable) { final Tameable pet = (Tameable)event.getRightClicked(); if(pet.isTamed()) { final String ownerName = pet.getOwner().getName(); if(ownerName.equals(event.getPlayer().getName()) && event.getPlayer().isSneaking()) { UDSPlugin.getPlayers().get(event.getPlayer().getName()).selectPet(event.getRightClicked().getUniqueId()); event.getPlayer().sendMessage(Color.MESSAGE + "Pet selected."); event.setCancelled(true); } else { event.getPlayer().sendMessage(Color.MESSAGE + "This animal belongs to " + UDSPlugin.getPlayers().get(ownerName).getNick()); } } } else if(event.getRightClicked() instanceof ItemFrame) { final SaveablePlayer player = UDSPlugin.getPlayers().get(event.getPlayer().getName()); if(!(player.canBuildHere(event.getRightClicked().getLocation()))) { event.setCancelled(true); player.sendMessage(Message.CANT_BUILD_HERE); } } }
diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJDeclarationsConverter.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJDeclarationsConverter.java index ad841845..fc696c90 100644 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJDeclarationsConverter.java +++ b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJDeclarationsConverter.java @@ -1,769 +1,770 @@ /* Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved This file is part of JNAerator (http://jnaerator.googlecode.com/). JNAerator is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JNAerator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JNAerator. If not, see <http://www.gnu.org/licenses/>. */ package com.ochafik.lang.jnaerator; import org.bridj.ann.Name; import org.bridj.BridJ; import org.bridj.FlagSet; import org.bridj.IntValuedEnum; import org.bridj.StructObject; import org.bridj.cpp.CPPObject; import org.bridj.cpp.com.IUnknown; import com.ochafik.lang.jnaerator.BridJTypeConversion.NL4JConversion; import com.ochafik.lang.jnaerator.TypeConversion.ConvType; //import org.bridj.structs.StructIO; //import org.bridj.structs.Array; import java.io.IOException; import java.util.*; import com.ochafik.lang.jnaerator.parser.*; import com.ochafik.lang.jnaerator.parser.Enum; import com.ochafik.lang.jnaerator.parser.Statement.Block; import com.ochafik.lang.jnaerator.parser.StoredDeclarations.*; import com.ochafik.lang.jnaerator.parser.Struct.MemberVisibility; import com.ochafik.lang.jnaerator.parser.TypeRef.*; import com.ochafik.lang.jnaerator.parser.Expression.*; import com.ochafik.lang.jnaerator.parser.Function.Type; import com.ochafik.lang.jnaerator.parser.DeclarationsHolder.ListWrapper; import com.ochafik.lang.jnaerator.parser.Declarator.*; import com.ochafik.util.listenable.Pair; import com.ochafik.util.string.StringUtils; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; import com.ochafik.lang.jnaerator.parser.Function.SignatureType; import com.sun.jna.win32.StdCallLibrary; import org.bridj.*; import org.bridj.ann.Convention; import org.bridj.objc.NSObject; public class BridJDeclarationsConverter extends DeclarationsConverter { public BridJDeclarationsConverter(Result result) { super(result); } public void annotateActualName(ModifiableElement e, Identifier name) { e.addAnnotation(new Annotation(Name.class, expr(name.toString()))); } @Override public Struct convertCallback(FunctionSignature functionSignature, Signatures signatures, Identifier callerLibraryName) { Struct decl = super.convertCallback(functionSignature, signatures, callerLibraryName); if (decl != null) { decl.setParents(Arrays.asList((SimpleTypeRef)( FunctionSignature.Type.ObjCBlock.equals(functionSignature.getType()) ? result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.ObjCBlock) : (SimpleTypeRef)typeRef(ident(result.config.runtime.callbackClass, expr(typeRef(decl.getTag().clone())))) ))); //addCallingConventionAnnotation(functionSignature.getFunction(), decl); } return decl; } @Override public void convertEnum(Enum e, Signatures signatures, DeclarationsHolder out, Identifier libraryClassName) { if (e.isForwardDeclaration()) return; Identifier rawEnumName = getActualTaggedTypeName(e); List<EnumItemResult> results = getEnumValuesAndCommentsByName(e, signatures, libraryClassName); boolean hasEnumClass = false; if (rawEnumName != null && rawEnumName.resolveLastSimpleIdentifier().getName() != null) { hasEnumClass = true; Identifier enumName = result.typeConverter.getValidJavaIdentifier(rawEnumName); if (!signatures.addClass(enumName)) return; signatures = new Signatures(); Enum en = new Enum(); if (!result.config.noComments) en.importComments(e, "enum values", getFileCommentContent(e)); if (!rawEnumName.equals(enumName)) annotateActualName(en, rawEnumName); en.setType(Enum.Type.Java); en.setTag(enumName.clone()); en.addModifiers(ModifierType.Public); out.addDeclaration(new TaggedTypeRefDeclaration(en)); Struct body = new Struct(); en.setBody(body); boolean hasValidItem = false; for (EnumItemResult er : results) { if (er.errorElement != null) { out.addDeclaration(er.errorElement); continue; } String itemName = result.typeConverter.getValidJavaIdentifierString(ident(er.originalItem.getName())); Enum.EnumItem item = new Enum.EnumItem(itemName, er.convertedValue); en.addItem(item); hasValidItem = true; if (!result.config.noComments) if (item != null) {// && hasEnumClass) { item.importComments(er.originalItem); } } if (hasValidItem) { en.addInterface(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))); String valueArgName = "value"; body.addDeclaration(new Function(Type.JavaMethod, enumName.clone(), null, new Arg(valueArgName, typeRef(Long.TYPE))).setBody(block( stat(expr(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName), AssignmentOperator.Equal, varRef(valueArgName))) ))); body.addDeclaration(new VariablesDeclaration(typeRef(Long.TYPE), new DirectDeclarator(valueArgName)).addModifiers(ModifierType.Public, ModifierType.Final)); body.addDeclaration(new Function(Type.JavaMethod, ident(valueArgName), typeRef(Long.TYPE)).setBody(block( new Statement.Return(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName)) )).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("iterator"), typeRef(ident(Iterator.class, expr(typeRef(enumName.clone()))))).setBody(block( new Statement.Return( methodCall( methodCall( expr(typeRef(Collections.class)), MemberRefStyle.Dot, "singleton", thisRef() ), MemberRefStyle.Dot, "iterator" ) ) )).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("fromValue"), typeRef(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))), new Arg(valueArgName, typeRef(Integer.TYPE))).setBody(block( new Statement.Return( methodCall( expr(typeRef(FlagSet.class)), MemberRefStyle.Dot, "fromValue", varRef(valueArgName), methodCall( "values" ) ) ) )).addModifiers(ModifierType.Public, ModifierType.Static)); } } else { outputEnumItemsAsConstants(results, out, signatures, libraryClassName, hasEnumClass); } } void addCallingConventionAnnotation(Function originalFunction, ModifiableElement target) { Convention.Style cc = null; if (originalFunction.hasModifier(ModifierType.__stdcall)) cc = Convention.Style.StdCall; else if (originalFunction.hasModifier(ModifierType.__fastcall)) cc = Convention.Style.FastCall; else if (originalFunction.hasModifier(ModifierType.__thiscall)) cc = Convention.Style.ThisCall; else if (originalFunction.hasModifier(ModifierType.__pascal)) cc = Convention.Style.Pascal; if (cc != null) { target.addAnnotation(new Annotation(typeRef(Convention.class), enumRef(cc))); } } @Override public void convertFunction(Function function, Signatures signatures, boolean isCallback, DeclarationsHolder out, Identifier libraryClassName, String sig, Identifier functionName, String library, int iConstructor) throws UnsupportedConversionException { Element parent = function.getParentElement(); MemberVisibility visibility = function.getVisibility(); boolean isPublic = visibility == MemberVisibility.Public || function.hasModifier(ModifierType.Public); boolean isPrivate = visibility == MemberVisibility.Private || function.hasModifier(ModifierType.Private); boolean isProtected = visibility == MemberVisibility.Protected || function.hasModifier(ModifierType.Protected); boolean isInStruct = parent instanceof Struct; if (isInStruct && result.config.skipPrivateMembers && (isPrivate || !isPublic && !isProtected)) return; boolean isStatic = function.hasModifier(ModifierType.Static); boolean isConstructor = iConstructor != -1; Function nativeMethod = new Function(Type.JavaMethod, ident(functionName), null); if (result.config.synchronizedMethods && !isCallback) nativeMethod.addModifiers(ModifierType.Synchronized); addCallingConventionAnnotation(function, nativeMethod); if (function.getName() != null && !functionName.toString().equals(function.getName().toString()) && !isCallback) { TypeRef mgc = result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Name); if (mgc != null) { nativeMethod.addAnnotation(new Annotation(mgc, "(\"" + function.getName() + "\")")); } } Function rawMethod = nativeMethod.clone(); //Map<String, NL4JConversion> argTypes = new LinkedHashMap<String, NL4JConversion>(); boolean isObjectiveC = function.getType() == Type.ObjCMethod; int iArg = 1; Set<String> argNames = new TreeSet<String>(); List<Expression> superConstructorArgs = null; if (isConstructor) { superConstructorArgs = new ArrayList<Expression>(); superConstructorArgs.add(cast(typeRef(Void.class), nullExpr())); superConstructorArgs.add(expr(iConstructor)); } Identifier varArgType = null; String varArgName = null; NL4JConversion returnType = null; List<NL4JConversion> paramTypes = new ArrayList<NL4JConversion>(); List<String> paramNames = new ArrayList<String>(); if (!isConstructor) { returnType = ((BridJTypeConversion)result.typeConverter).convertTypeToNL4J(function.getValueType(), libraryClassName, null, null, -1, -1); } for (Arg arg : function.getArgs()) { String paramName; if (arg.isVarArg()) { assert arg.getValueType() == null; paramName = varArgName = chooseJavaArgName("varargs", iArg, argNames); varArgType = ident(isObjectiveC ? NSObject.class : Object.class); } else { paramName = chooseJavaArgName(arg.getName(), iArg, argNames); paramTypes.add(((BridJTypeConversion)result.typeConverter).convertTypeToNL4J(arg.getValueType(), libraryClassName, null, null, -1, -1)); } paramNames.add(paramName); if (isConstructor) { superConstructorArgs.add(varRef(paramName)); } iArg++; } fillIn(signatures, functionName, nativeMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, false); Block convertedBody = null; if (isConstructor) { convertedBody = block(stat(methodCall("super", superConstructorArgs.toArray(new Expression[superConstructorArgs.size()])))); } else if (result.config.convertBodies && function.getBody() != null) { try { Pair<Element, List<Declaration>> bodyAndExtraDeclarations = result.bridjer.convertToJava(function.getBody(), libraryClassName); convertedBody = (Block)bodyAndExtraDeclarations.getFirst(); for (Declaration d : bodyAndExtraDeclarations.getSecond()) out.addDeclaration(d); } catch (Exception ex) { ex.printStackTrace(System.out); nativeMethod.addToCommentBefore("TRANSLATION OF BODY FAILED: " + ex); } } if (!result.config.noComments) nativeMethod.importComments(function, isCallback ? null : getFileCommentContent(function)); out.addDeclaration(nativeMethod); boolean generateStaticMethod = isStatic || !isCallback && !isInStruct; if (convertedBody == null) { boolean forwardedToRaw = false; if (result.config.genRawBindings && !isCallback) { // Function rawMethod = nativeMethod.clone(); rawMethod.setArgs(Collections.EMPTY_LIST); fillIn(signatures, functionName, rawMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, true); rawMethod.addModifiers(ModifierType.Protected, ModifierType.Native); if (generateStaticMethod) rawMethod.addModifiers(ModifierType.Static); if (!nativeMethod.computeSignature(SignatureType.ArgsAndRet).equals(rawMethod.computeSignature(SignatureType.ArgsAndRet))) { out.addDeclaration(rawMethod); List<Expression> followedArgs = new ArrayList<Expression>(); for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); Expression followedArg; switch (paramType.type) { case Pointer: followedArg = methodCall(expr(typeRef(org.bridj.Pointer.class)), "getPeer", varRef(paramName)); break; case Enum: followedArg = cast(typeRef(int.class), methodCall(varRef(paramName), "value")); break; // case NativeSize: // case NativeLong: // followedArg = methodCall(varRef(paramName), "longValue"); // break; default: followedArg = varRef(paramName); break; } followedArgs.add(followedArg); } if (varArgType != null) { followedArgs.add(varRef(varArgName)); } Expression followedCall = methodCall(rawMethod.getName().toString(), followedArgs.toArray(new Expression[followedArgs.size()])); boolean isVoid = "void".equals(String.valueOf(nativeMethod.getValueType())); if (isVoid) nativeMethod.setBody(block(stat(followedCall))); else { switch (returnType.type) { case Pointer: if (returnType.isTypedPointer) followedCall = new New(nativeMethod.getValueType(), followedCall); else { Expression ptrExpr = expr(typeRef(org.bridj.Pointer.class)); - if (returnType.targetTypeConversion == null || returnType.targetTypeConversion.type == ConvType.Void) + Expression targetTypeExpr = result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType())); + if (targetTypeExpr == null || (returnType.targetTypeConversion != null && returnType.targetTypeConversion.type == ConvType.Void)) followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall); else - followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall, result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType()))); + followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall, targetTypeExpr); } break; case Enum: followedCall = methodCall(expr(typeRef(org.bridj.FlagSet.class)), "fromValue", followedCall, result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType()))); break; case NativeLong: case NativeSize: if (!rawMethod.getValueType().toString().equals("long")) { followedCall = new New(nativeMethod.getValueType().clone(), followedCall); } default: break; } nativeMethod.setBody(block(new Statement.Return(followedCall))); } forwardedToRaw = true; } } if (!forwardedToRaw) nativeMethod.addModifiers(isCallback ? ModifierType.Abstract : ModifierType.Native); } else nativeMethod.setBody(convertedBody); nativeMethod.addModifiers( isProtected ? ModifierType.Protected : ModifierType.Public, generateStaticMethod ? ModifierType.Static : null ); } private void fillIn(Signatures signatures, Identifier functionName, Function nativeMethod, NL4JConversion returnType, List<NL4JConversion> paramTypes, List<String> paramNames, Identifier varArgType, String varArgName, boolean isCallback, boolean useRawTypes) { for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); nativeMethod.addArg(paramType.annotateTypedType(new Arg(paramName, paramType.getTypeRef(useRawTypes)), useRawTypes));//.getTypedTypeRef()))); } if (varArgType != null) nativeMethod.addArg(new Arg(varArgName, typeRef(varArgType.clone()))).setVarArg(true); if (returnType != null) { returnType.annotateTypedType(nativeMethod, useRawTypes); nativeMethod.setValueType(returnType.getTypeRef(useRawTypes)); } String natSig = nativeMethod.computeSignature(SignatureType.JavaStyle); Identifier javaMethodName = signatures == null ? functionName : signatures.findNextMethodName(natSig, functionName); if (!javaMethodName.equals(functionName)) { nativeMethod.setName(javaMethodName); } if (!isCallback && !javaMethodName.equals(functionName)) annotateActualName(nativeMethod, functionName); } @Override public Struct convertStruct(Struct struct, Signatures signatures, Identifier callerLibraryClass, String callerLibrary, boolean onlyFields) throws IOException { Identifier structName = getActualTaggedTypeName(struct); if (structName == null) return null; //if (structName.toString().contains("MonoObject")) // structName.toString(); if (struct.isForwardDeclaration())// && !result.structsByName.get(structName).isForwardDeclaration()) return null; if (!signatures.addClass(structName)) return null; boolean isUnion = struct.getType() == Struct.Type.CUnion; boolean inheritsFromStruct = false; Identifier baseClass = null; int parentFieldsCount = 0; List<String> preComments = new ArrayList<String>(); for (SimpleTypeRef parentName : struct.getParents()) { Struct parent = result.structsByName.get(parentName.getName()); if (parent == null) { // TODO report error continue; } try { parentFieldsCount += countFieldsInStruct(parent); } catch (UnsupportedConversionException ex) { preComments.add("Error: " + ex); } baseClass = result.typeConverter.getTaggedTypeIdentifierInJava(parent); if (baseClass != null) { inheritsFromStruct = true; break; // TODO handle multiple and virtual inheritage } } boolean hasMemberFunctions = false; for (Declaration d : struct.getDeclarations()) { if (d instanceof Function) { hasMemberFunctions = true; break; } } Constant uuid = (Constant)struct.getModifierValue(ModifierType.UUID); if (baseClass == null) { switch (struct.getType()) { case CStruct: case CUnion: if (!hasMemberFunctions) { baseClass = ident(StructObject.class); break; } case CPPClass: baseClass = ident(uuid == null ? CPPObject.class : IUnknown.class); result.hasCPlusPlus = true; break; default: throw new UnsupportedOperationException(); } } Struct structJavaClass = publicStaticClass(structName, baseClass, Struct.Type.JavaClass, struct); //if (result.config.microsoftCOM) { if (uuid != null) { structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.IID), uuid)); } structJavaClass.addToCommentBefore(preComments); //System.out.println("parentFieldsCount(structName = " + structName + ") = " + parentFieldsCount); final int iChild[] = new int[] { parentFieldsCount }; //cl.addDeclaration(new EmptyDeclaration()) Signatures childSignatures = new Signatures(); /*if (isVirtual(struct) && !onlyFields) { String vptrName = DEFAULT_VPTR_NAME; VariablesDeclaration vptr = new VariablesDeclaration(typeRef(VirtualTablePointer.class), new Declarator.DirectDeclarator(vptrName)); vptr.addModifiers(ModifierType.Public); structJavaClass.addDeclaration(vptr); childSignatures.variablesSignatures.add(vptrName); // TODO add vptr grabber to constructor ! }*/ // private static StructIO<MyStruct> io = StructIO.getInstance(MyStruct.class); Function defaultConstructor = new Function(Type.JavaMethod, ident(structName), null).setBody(block(stat(methodCall("super")))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(defaultConstructor)) structJavaClass.addDeclaration(defaultConstructor); if (isUnion) structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Union))); int iVirtual = 0, iConstructor = 0; //List<Declaration> children = new ArrayList<Declaration>(); for (Declaration d : struct.getDeclarations()) { //if (isUnion) // iChild[0] = 0; if (d instanceof VariablesDeclaration) { convertVariablesDeclaration((VariablesDeclaration)d, childSignatures, structJavaClass, iChild, false, structName, callerLibraryClass, callerLibrary); } else if (!onlyFields) { if (d instanceof TaggedTypeRefDeclaration) { TaggedTypeRef tr = ((TaggedTypeRefDeclaration) d).getTaggedTypeRef(); if (tr instanceof Struct) { outputConvertedStruct((Struct)tr, childSignatures, structJavaClass, callerLibraryClass, callerLibrary, false); } else if (tr instanceof Enum) { convertEnum((Enum)tr, childSignatures, structJavaClass, callerLibraryClass); } } else if (d instanceof TypeDef) { TypeDef td = (TypeDef)d; TypeRef tr = td.getValueType(); if (tr instanceof Struct) { outputConvertedStruct((Struct)tr, childSignatures, structJavaClass, callerLibraryClass, callerLibrary, false); } else if (tr instanceof FunctionSignature) { convertCallback((FunctionSignature)tr, childSignatures, structJavaClass, callerLibraryClass); } } else if (result.config.genCPlusPlus && d instanceof Function) { Function f = (Function) d; boolean isVirtual = f.hasModifier(ModifierType.Virtual); boolean isConstructor = f.getName().equals(structName) && (f.getValueType() == null || f.getValueType().toString().equals("void")); if (isConstructor && f.getArgs().isEmpty()) continue; // default constructor was already generated String library = result.getLibrary(struct); if (library == null) continue; List<Declaration> decls = new ArrayList<Declaration>(); convertFunction(f, childSignatures, false, new ListWrapper(decls), callerLibraryClass, isConstructor ? iConstructor : -1); for (Declaration md : decls) { if (!(md instanceof Function)) continue; Function method = (Function) md; boolean commentOut = false; if (isVirtual) method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Virtual), expr(iVirtual))); else if (method.getValueType() == null) { method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Constructor), expr(iConstructor))); isConstructor = true; } if (method.getName().toString().equals("operator")) commentOut = true; if (commentOut) structJavaClass.addDeclaration(new EmptyDeclaration(method.toString())); else structJavaClass.addDeclaration(method); } if (isVirtual) iVirtual++; if (isConstructor) iConstructor++; } } } String ptrName = "pointer"; Function castConstructor = new Function(Type.JavaMethod, ident(structName), null, new Arg(ptrName, typeRef(result.config.runtime.pointerClass))).setBody(block(stat(methodCall("super", varRef(ptrName))))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(castConstructor)) structJavaClass.addDeclaration(castConstructor); return structJavaClass; } Map<Identifier, Boolean> structsVirtuality = new HashMap<Identifier, Boolean>(); public boolean isVirtual(Struct struct) { Identifier name = getActualTaggedTypeName(struct); Boolean bVirtual = structsVirtuality.get(name); if (bVirtual == null) { boolean hasVirtualParent = false, hasVirtualMembers = false; for (SimpleTypeRef parentName : struct.getParents()) { Struct parentStruct = result.structsByName.get(parentName.getName()); if (parentStruct == null) { if (result.config.verbose) System.out.println("Failed to resolve parent '" + parentName + "' for struct '" + name + "'"); continue; } if (isVirtual(parentStruct)) { hasVirtualParent = true; break; } } for (Declaration mb : struct.getDeclarations()) { if (mb.hasModifier(ModifierType.Virtual)) { hasVirtualMembers = true; break; } } bVirtual = hasVirtualMembers && !hasVirtualParent; structsVirtuality.put(name, bVirtual); } return bVirtual; } protected String ioVarName = "io", ioStaticVarName = "IO"; public List<Declaration> convertVariablesDeclarationToBridJ(String name, TypeRef mutatedType, int[] iChild, int bits, boolean isGlobal, Identifier holderName, Identifier callerLibraryName, String callerLibrary, Element... toImportDetailsFrom) throws UnsupportedConversionException { name = result.typeConverter.getValidJavaArgumentName(ident(name)).toString(); //convertVariablesDeclaration(name, mutatedType, out, iChild, callerLibraryName); final boolean useRawTypes = false; //Expression initVal = null; int fieldIndex = iChild[0]; //convertTypeToNL4J(TypeRef valueType, Identifier libraryClassName, Expression structPeerExpr, Expression structIOExpr, Expression valueExpr, int fieldIndex, int bits) throws UnsupportedConversionException { NL4JConversion conv = ((BridJTypeConversion)result.typeConverter).convertTypeToNL4J( mutatedType, callerLibraryName, thisField("io"), varRef(name), fieldIndex, bits ); if (conv == null) { throw new UnsupportedConversionException(mutatedType, "failed to convert type to Java"); } else if ("void".equals(String.valueOf(conv.getTypeRef(useRawTypes)))) { throw new UnsupportedConversionException(mutatedType, "void type !"); //out.add(new EmptyDeclaration("SKIPPED:", v.formatComments("", true, true, false), v.toString())); } Function convDecl = new Function(); conv.annotateTypedType(convDecl, useRawTypes); convDecl.setType(Type.JavaMethod); convDecl.addModifiers(ModifierType.Public); if (conv.arrayLengths != null) convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Length), "({" + StringUtils.implode(conv.arrayLengths, ", ") + "})")); if (conv.bits != null) convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Bits), conv.bits)); if (conv.byValue) convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.ByValue))); for (Element e : toImportDetailsFrom) convDecl.importDetails(e, false); convDecl.importDetails(mutatedType, true); //convDecl.importDetails(javaType, true); // convDecl.importDetails(v, false); // convDecl.importDetails(vs, false); // convDecl.importDetails(valueType, false); // valueType.stripDetails(); convDecl.moveAllCommentsBefore(); convDecl.setName(ident(name)); if (!isGlobal) convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Field), expr(fieldIndex))); convDecl.setValueType(conv.getTypeRef(useRawTypes)); TypeRef javaType = convDecl.getValueType(); String pointerGetSetMethodSuffix = StringUtils.capitalize(javaType.toString()); Expression getGlobalPointerExpr = null; if (isGlobal) { getGlobalPointerExpr = methodCall(methodCall(methodCall(expr(typeRef(BridJ.class)), "getNativeLibrary", expr(callerLibrary)), "getSymbolPointer", expr(name)), "as", result.typeConverter.typeLiteral(javaType.clone())); } List<Declaration> out = new ArrayList<Declaration>(); if (conv.getExpr != null) { Function getter = convDecl.clone(); if (isGlobal) { getter.setBody(block( tryRethrow(new Statement.Return(cast(javaType.clone(), methodCall(getGlobalPointerExpr, "get")))) )); } else { getter.setBody(block( new Statement.Return(conv.getExpr) )); } out.add(getter); } if (!conv.readOnly && conv.setExpr != null) { Function setter = convDecl.clone(); setter.setValueType(typeRef(holderName.clone()));//Void.TYPE)); setter.addArg(new Arg(name, javaType)); //setter.addModifiers(ModifierType.Native); if (isGlobal) { setter.setBody(block( tryRethrow(block( stat(methodCall(getGlobalPointerExpr, "set", varRef(name))), new Statement.Return(thisRef()) )) )); } else { setter.setBody(block( stat(conv.setExpr), new Statement.Return(thisRef()) )); } out.add(setter); if (result.config.scalaStructSetters) { setter = new Function(); setter.setType(Type.JavaMethod); setter.setName(ident(name + "_$eq")); setter.setValueType(javaType.clone()); setter.addArg(new Arg(name, javaType.clone())); setter.addModifiers(ModifierType.Public, ModifierType.Final); setter.setBody(block( stat(methodCall(name, varRef(name))), new Statement.Return(varRef(name)) )); out.add(setter); } } return out; } @Override public void convertVariablesDeclaration(VariablesDeclaration v, Signatures signatures, DeclarationsHolder out, int[] iChild, boolean isGlobal, Identifier holderName, Identifier callerLibraryClass, String callerLibrary) { try { TypeRef valueType = v.getValueType(); for (Declarator vs : v.getDeclarators()) { if (vs.getDefaultValue() != null) continue; String name = vs.resolveName(); if (name == null || name.length() == 0) { name = "anonymous" + (nextAnonymousFieldId++); } TypeRef mutatedType = valueType; if (!(vs instanceof DirectDeclarator)) { mutatedType = (TypeRef)vs.mutateTypeKeepingParent(valueType); vs = new DirectDeclarator(vs.resolveName()); } //Declarator d = v.getDeclarators().get(0); List<Declaration> vds = convertVariablesDeclarationToBridJ(name, mutatedType, iChild, vs.getBits(), isGlobal, holderName, callerLibraryClass, callerLibrary, v, vs); if (vs.getBits() > 0) for (Declaration vd : vds) vd.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Bits), expr(vs.getBits()))); for (Declaration vd : vds) { if (vd instanceof Function) { if (!signatures.addMethod((Function)vd)) continue; } vd.importDetails(mutatedType, true); vd.moveAllCommentsBefore(); if (!(mutatedType instanceof Primitive) && !result.config.noComments) vd.addToCommentBefore("C type : " + mutatedType); out.addDeclaration(vd); } //} iChild[0]++; } } catch (Throwable e) { if (!(e instanceof UnsupportedConversionException)) e.printStackTrace(); if (!result.config.limitComments) out.addDeclaration(new EmptyDeclaration(e.toString())); } } int nextAnonymousFieldId; @Override protected void configureCallbackStruct(Struct callbackStruct) { callbackStruct.setType(Struct.Type.JavaClass); callbackStruct.addModifiers(ModifierType.Public, ModifierType.Static, ModifierType.Abstract); } @Override protected Struct createFakePointerClass(Identifier fakePointer) { Struct ptClass = result.declarationsConverter.publicStaticClass(fakePointer, ident(TypedPointer.class), Struct.Type.JavaClass, null); String addressVarName = "address"; ptClass.addDeclaration(new Function(Function.Type.JavaMethod, fakePointer, null, new Arg(addressVarName, typeRef(long.class)) ).addModifiers(ModifierType.Public).setBody( block(stat(methodCall("super", varRef(addressVarName))))) ); ptClass.addDeclaration(new Function(Function.Type.JavaMethod, fakePointer, null, new Arg(addressVarName, typeRef(org.bridj.Pointer.class)) ).addModifiers(ModifierType.Public).setBody( block(stat(methodCall("super", varRef(addressVarName))))) ); return ptClass; } }
false
true
public void convertEnum(Enum e, Signatures signatures, DeclarationsHolder out, Identifier libraryClassName) { if (e.isForwardDeclaration()) return; Identifier rawEnumName = getActualTaggedTypeName(e); List<EnumItemResult> results = getEnumValuesAndCommentsByName(e, signatures, libraryClassName); boolean hasEnumClass = false; if (rawEnumName != null && rawEnumName.resolveLastSimpleIdentifier().getName() != null) { hasEnumClass = true; Identifier enumName = result.typeConverter.getValidJavaIdentifier(rawEnumName); if (!signatures.addClass(enumName)) return; signatures = new Signatures(); Enum en = new Enum(); if (!result.config.noComments) en.importComments(e, "enum values", getFileCommentContent(e)); if (!rawEnumName.equals(enumName)) annotateActualName(en, rawEnumName); en.setType(Enum.Type.Java); en.setTag(enumName.clone()); en.addModifiers(ModifierType.Public); out.addDeclaration(new TaggedTypeRefDeclaration(en)); Struct body = new Struct(); en.setBody(body); boolean hasValidItem = false; for (EnumItemResult er : results) { if (er.errorElement != null) { out.addDeclaration(er.errorElement); continue; } String itemName = result.typeConverter.getValidJavaIdentifierString(ident(er.originalItem.getName())); Enum.EnumItem item = new Enum.EnumItem(itemName, er.convertedValue); en.addItem(item); hasValidItem = true; if (!result.config.noComments) if (item != null) {// && hasEnumClass) { item.importComments(er.originalItem); } } if (hasValidItem) { en.addInterface(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))); String valueArgName = "value"; body.addDeclaration(new Function(Type.JavaMethod, enumName.clone(), null, new Arg(valueArgName, typeRef(Long.TYPE))).setBody(block( stat(expr(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName), AssignmentOperator.Equal, varRef(valueArgName))) ))); body.addDeclaration(new VariablesDeclaration(typeRef(Long.TYPE), new DirectDeclarator(valueArgName)).addModifiers(ModifierType.Public, ModifierType.Final)); body.addDeclaration(new Function(Type.JavaMethod, ident(valueArgName), typeRef(Long.TYPE)).setBody(block( new Statement.Return(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName)) )).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("iterator"), typeRef(ident(Iterator.class, expr(typeRef(enumName.clone()))))).setBody(block( new Statement.Return( methodCall( methodCall( expr(typeRef(Collections.class)), MemberRefStyle.Dot, "singleton", thisRef() ), MemberRefStyle.Dot, "iterator" ) ) )).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("fromValue"), typeRef(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))), new Arg(valueArgName, typeRef(Integer.TYPE))).setBody(block( new Statement.Return( methodCall( expr(typeRef(FlagSet.class)), MemberRefStyle.Dot, "fromValue", varRef(valueArgName), methodCall( "values" ) ) ) )).addModifiers(ModifierType.Public, ModifierType.Static)); } } else { outputEnumItemsAsConstants(results, out, signatures, libraryClassName, hasEnumClass); } } void addCallingConventionAnnotation(Function originalFunction, ModifiableElement target) { Convention.Style cc = null; if (originalFunction.hasModifier(ModifierType.__stdcall)) cc = Convention.Style.StdCall; else if (originalFunction.hasModifier(ModifierType.__fastcall)) cc = Convention.Style.FastCall; else if (originalFunction.hasModifier(ModifierType.__thiscall)) cc = Convention.Style.ThisCall; else if (originalFunction.hasModifier(ModifierType.__pascal)) cc = Convention.Style.Pascal; if (cc != null) { target.addAnnotation(new Annotation(typeRef(Convention.class), enumRef(cc))); } } @Override public void convertFunction(Function function, Signatures signatures, boolean isCallback, DeclarationsHolder out, Identifier libraryClassName, String sig, Identifier functionName, String library, int iConstructor) throws UnsupportedConversionException { Element parent = function.getParentElement(); MemberVisibility visibility = function.getVisibility(); boolean isPublic = visibility == MemberVisibility.Public || function.hasModifier(ModifierType.Public); boolean isPrivate = visibility == MemberVisibility.Private || function.hasModifier(ModifierType.Private); boolean isProtected = visibility == MemberVisibility.Protected || function.hasModifier(ModifierType.Protected); boolean isInStruct = parent instanceof Struct; if (isInStruct && result.config.skipPrivateMembers && (isPrivate || !isPublic && !isProtected)) return; boolean isStatic = function.hasModifier(ModifierType.Static); boolean isConstructor = iConstructor != -1; Function nativeMethod = new Function(Type.JavaMethod, ident(functionName), null); if (result.config.synchronizedMethods && !isCallback) nativeMethod.addModifiers(ModifierType.Synchronized); addCallingConventionAnnotation(function, nativeMethod); if (function.getName() != null && !functionName.toString().equals(function.getName().toString()) && !isCallback) { TypeRef mgc = result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Name); if (mgc != null) { nativeMethod.addAnnotation(new Annotation(mgc, "(\"" + function.getName() + "\")")); } } Function rawMethod = nativeMethod.clone(); //Map<String, NL4JConversion> argTypes = new LinkedHashMap<String, NL4JConversion>(); boolean isObjectiveC = function.getType() == Type.ObjCMethod; int iArg = 1; Set<String> argNames = new TreeSet<String>(); List<Expression> superConstructorArgs = null; if (isConstructor) { superConstructorArgs = new ArrayList<Expression>(); superConstructorArgs.add(cast(typeRef(Void.class), nullExpr())); superConstructorArgs.add(expr(iConstructor)); } Identifier varArgType = null; String varArgName = null; NL4JConversion returnType = null; List<NL4JConversion> paramTypes = new ArrayList<NL4JConversion>(); List<String> paramNames = new ArrayList<String>(); if (!isConstructor) { returnType = ((BridJTypeConversion)result.typeConverter).convertTypeToNL4J(function.getValueType(), libraryClassName, null, null, -1, -1); } for (Arg arg : function.getArgs()) { String paramName; if (arg.isVarArg()) { assert arg.getValueType() == null; paramName = varArgName = chooseJavaArgName("varargs", iArg, argNames); varArgType = ident(isObjectiveC ? NSObject.class : Object.class); } else { paramName = chooseJavaArgName(arg.getName(), iArg, argNames); paramTypes.add(((BridJTypeConversion)result.typeConverter).convertTypeToNL4J(arg.getValueType(), libraryClassName, null, null, -1, -1)); } paramNames.add(paramName); if (isConstructor) { superConstructorArgs.add(varRef(paramName)); } iArg++; } fillIn(signatures, functionName, nativeMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, false); Block convertedBody = null; if (isConstructor) { convertedBody = block(stat(methodCall("super", superConstructorArgs.toArray(new Expression[superConstructorArgs.size()])))); } else if (result.config.convertBodies && function.getBody() != null) { try { Pair<Element, List<Declaration>> bodyAndExtraDeclarations = result.bridjer.convertToJava(function.getBody(), libraryClassName); convertedBody = (Block)bodyAndExtraDeclarations.getFirst(); for (Declaration d : bodyAndExtraDeclarations.getSecond()) out.addDeclaration(d); } catch (Exception ex) { ex.printStackTrace(System.out); nativeMethod.addToCommentBefore("TRANSLATION OF BODY FAILED: " + ex); } } if (!result.config.noComments) nativeMethod.importComments(function, isCallback ? null : getFileCommentContent(function)); out.addDeclaration(nativeMethod); boolean generateStaticMethod = isStatic || !isCallback && !isInStruct; if (convertedBody == null) { boolean forwardedToRaw = false; if (result.config.genRawBindings && !isCallback) { // Function rawMethod = nativeMethod.clone(); rawMethod.setArgs(Collections.EMPTY_LIST); fillIn(signatures, functionName, rawMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, true); rawMethod.addModifiers(ModifierType.Protected, ModifierType.Native); if (generateStaticMethod) rawMethod.addModifiers(ModifierType.Static); if (!nativeMethod.computeSignature(SignatureType.ArgsAndRet).equals(rawMethod.computeSignature(SignatureType.ArgsAndRet))) { out.addDeclaration(rawMethod); List<Expression> followedArgs = new ArrayList<Expression>(); for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); Expression followedArg; switch (paramType.type) { case Pointer: followedArg = methodCall(expr(typeRef(org.bridj.Pointer.class)), "getPeer", varRef(paramName)); break; case Enum: followedArg = cast(typeRef(int.class), methodCall(varRef(paramName), "value")); break; // case NativeSize: // case NativeLong: // followedArg = methodCall(varRef(paramName), "longValue"); // break; default: followedArg = varRef(paramName); break; } followedArgs.add(followedArg); } if (varArgType != null) { followedArgs.add(varRef(varArgName)); } Expression followedCall = methodCall(rawMethod.getName().toString(), followedArgs.toArray(new Expression[followedArgs.size()])); boolean isVoid = "void".equals(String.valueOf(nativeMethod.getValueType())); if (isVoid) nativeMethod.setBody(block(stat(followedCall))); else { switch (returnType.type) { case Pointer: if (returnType.isTypedPointer) followedCall = new New(nativeMethod.getValueType(), followedCall); else { Expression ptrExpr = expr(typeRef(org.bridj.Pointer.class)); if (returnType.targetTypeConversion == null || returnType.targetTypeConversion.type == ConvType.Void) followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall); else followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall, result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType()))); } break; case Enum: followedCall = methodCall(expr(typeRef(org.bridj.FlagSet.class)), "fromValue", followedCall, result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType()))); break; case NativeLong: case NativeSize: if (!rawMethod.getValueType().toString().equals("long")) { followedCall = new New(nativeMethod.getValueType().clone(), followedCall); } default: break; } nativeMethod.setBody(block(new Statement.Return(followedCall))); } forwardedToRaw = true; } } if (!forwardedToRaw) nativeMethod.addModifiers(isCallback ? ModifierType.Abstract : ModifierType.Native); } else nativeMethod.setBody(convertedBody); nativeMethod.addModifiers( isProtected ? ModifierType.Protected : ModifierType.Public, generateStaticMethod ? ModifierType.Static : null ); } private void fillIn(Signatures signatures, Identifier functionName, Function nativeMethod, NL4JConversion returnType, List<NL4JConversion> paramTypes, List<String> paramNames, Identifier varArgType, String varArgName, boolean isCallback, boolean useRawTypes) { for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); nativeMethod.addArg(paramType.annotateTypedType(new Arg(paramName, paramType.getTypeRef(useRawTypes)), useRawTypes));//.getTypedTypeRef()))); } if (varArgType != null) nativeMethod.addArg(new Arg(varArgName, typeRef(varArgType.clone()))).setVarArg(true); if (returnType != null) { returnType.annotateTypedType(nativeMethod, useRawTypes); nativeMethod.setValueType(returnType.getTypeRef(useRawTypes)); } String natSig = nativeMethod.computeSignature(SignatureType.JavaStyle); Identifier javaMethodName = signatures == null ? functionName : signatures.findNextMethodName(natSig, functionName); if (!javaMethodName.equals(functionName)) { nativeMethod.setName(javaMethodName); } if (!isCallback && !javaMethodName.equals(functionName)) annotateActualName(nativeMethod, functionName); } @Override public Struct convertStruct(Struct struct, Signatures signatures, Identifier callerLibraryClass, String callerLibrary, boolean onlyFields) throws IOException { Identifier structName = getActualTaggedTypeName(struct); if (structName == null) return null; //if (structName.toString().contains("MonoObject")) // structName.toString(); if (struct.isForwardDeclaration())// && !result.structsByName.get(structName).isForwardDeclaration()) return null; if (!signatures.addClass(structName)) return null; boolean isUnion = struct.getType() == Struct.Type.CUnion; boolean inheritsFromStruct = false; Identifier baseClass = null; int parentFieldsCount = 0; List<String> preComments = new ArrayList<String>(); for (SimpleTypeRef parentName : struct.getParents()) { Struct parent = result.structsByName.get(parentName.getName()); if (parent == null) { // TODO report error continue; } try { parentFieldsCount += countFieldsInStruct(parent); } catch (UnsupportedConversionException ex) { preComments.add("Error: " + ex); } baseClass = result.typeConverter.getTaggedTypeIdentifierInJava(parent); if (baseClass != null) { inheritsFromStruct = true; break; // TODO handle multiple and virtual inheritage } } boolean hasMemberFunctions = false; for (Declaration d : struct.getDeclarations()) { if (d instanceof Function) { hasMemberFunctions = true; break; } } Constant uuid = (Constant)struct.getModifierValue(ModifierType.UUID); if (baseClass == null) { switch (struct.getType()) { case CStruct: case CUnion: if (!hasMemberFunctions) { baseClass = ident(StructObject.class); break; } case CPPClass: baseClass = ident(uuid == null ? CPPObject.class : IUnknown.class); result.hasCPlusPlus = true; break; default: throw new UnsupportedOperationException(); } } Struct structJavaClass = publicStaticClass(structName, baseClass, Struct.Type.JavaClass, struct); //if (result.config.microsoftCOM) { if (uuid != null) { structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.IID), uuid)); } structJavaClass.addToCommentBefore(preComments); //System.out.println("parentFieldsCount(structName = " + structName + ") = " + parentFieldsCount); final int iChild[] = new int[] { parentFieldsCount }; //cl.addDeclaration(new EmptyDeclaration()) Signatures childSignatures = new Signatures(); /*if (isVirtual(struct) && !onlyFields) { String vptrName = DEFAULT_VPTR_NAME; VariablesDeclaration vptr = new VariablesDeclaration(typeRef(VirtualTablePointer.class), new Declarator.DirectDeclarator(vptrName)); vptr.addModifiers(ModifierType.Public); structJavaClass.addDeclaration(vptr); childSignatures.variablesSignatures.add(vptrName); // TODO add vptr grabber to constructor ! }*/ // private static StructIO<MyStruct> io = StructIO.getInstance(MyStruct.class); Function defaultConstructor = new Function(Type.JavaMethod, ident(structName), null).setBody(block(stat(methodCall("super")))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(defaultConstructor)) structJavaClass.addDeclaration(defaultConstructor); if (isUnion) structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Union))); int iVirtual = 0, iConstructor = 0; //List<Declaration> children = new ArrayList<Declaration>(); for (Declaration d : struct.getDeclarations()) { //if (isUnion) // iChild[0] = 0; if (d instanceof VariablesDeclaration) { convertVariablesDeclaration((VariablesDeclaration)d, childSignatures, structJavaClass, iChild, false, structName, callerLibraryClass, callerLibrary); } else if (!onlyFields) { if (d instanceof TaggedTypeRefDeclaration) { TaggedTypeRef tr = ((TaggedTypeRefDeclaration) d).getTaggedTypeRef(); if (tr instanceof Struct) { outputConvertedStruct((Struct)tr, childSignatures, structJavaClass, callerLibraryClass, callerLibrary, false); } else if (tr instanceof Enum) { convertEnum((Enum)tr, childSignatures, structJavaClass, callerLibraryClass); } } else if (d instanceof TypeDef) { TypeDef td = (TypeDef)d; TypeRef tr = td.getValueType(); if (tr instanceof Struct) { outputConvertedStruct((Struct)tr, childSignatures, structJavaClass, callerLibraryClass, callerLibrary, false); } else if (tr instanceof FunctionSignature) { convertCallback((FunctionSignature)tr, childSignatures, structJavaClass, callerLibraryClass); } } else if (result.config.genCPlusPlus && d instanceof Function) { Function f = (Function) d; boolean isVirtual = f.hasModifier(ModifierType.Virtual); boolean isConstructor = f.getName().equals(structName) && (f.getValueType() == null || f.getValueType().toString().equals("void")); if (isConstructor && f.getArgs().isEmpty()) continue; // default constructor was already generated String library = result.getLibrary(struct); if (library == null) continue; List<Declaration> decls = new ArrayList<Declaration>(); convertFunction(f, childSignatures, false, new ListWrapper(decls), callerLibraryClass, isConstructor ? iConstructor : -1); for (Declaration md : decls) { if (!(md instanceof Function)) continue; Function method = (Function) md; boolean commentOut = false; if (isVirtual) method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Virtual), expr(iVirtual))); else if (method.getValueType() == null) { method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Constructor), expr(iConstructor))); isConstructor = true; } if (method.getName().toString().equals("operator")) commentOut = true; if (commentOut) structJavaClass.addDeclaration(new EmptyDeclaration(method.toString())); else structJavaClass.addDeclaration(method); } if (isVirtual) iVirtual++; if (isConstructor) iConstructor++; } } } String ptrName = "pointer"; Function castConstructor = new Function(Type.JavaMethod, ident(structName), null, new Arg(ptrName, typeRef(result.config.runtime.pointerClass))).setBody(block(stat(methodCall("super", varRef(ptrName))))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(castConstructor)) structJavaClass.addDeclaration(castConstructor); return structJavaClass; }
public void convertEnum(Enum e, Signatures signatures, DeclarationsHolder out, Identifier libraryClassName) { if (e.isForwardDeclaration()) return; Identifier rawEnumName = getActualTaggedTypeName(e); List<EnumItemResult> results = getEnumValuesAndCommentsByName(e, signatures, libraryClassName); boolean hasEnumClass = false; if (rawEnumName != null && rawEnumName.resolveLastSimpleIdentifier().getName() != null) { hasEnumClass = true; Identifier enumName = result.typeConverter.getValidJavaIdentifier(rawEnumName); if (!signatures.addClass(enumName)) return; signatures = new Signatures(); Enum en = new Enum(); if (!result.config.noComments) en.importComments(e, "enum values", getFileCommentContent(e)); if (!rawEnumName.equals(enumName)) annotateActualName(en, rawEnumName); en.setType(Enum.Type.Java); en.setTag(enumName.clone()); en.addModifiers(ModifierType.Public); out.addDeclaration(new TaggedTypeRefDeclaration(en)); Struct body = new Struct(); en.setBody(body); boolean hasValidItem = false; for (EnumItemResult er : results) { if (er.errorElement != null) { out.addDeclaration(er.errorElement); continue; } String itemName = result.typeConverter.getValidJavaIdentifierString(ident(er.originalItem.getName())); Enum.EnumItem item = new Enum.EnumItem(itemName, er.convertedValue); en.addItem(item); hasValidItem = true; if (!result.config.noComments) if (item != null) {// && hasEnumClass) { item.importComments(er.originalItem); } } if (hasValidItem) { en.addInterface(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))); String valueArgName = "value"; body.addDeclaration(new Function(Type.JavaMethod, enumName.clone(), null, new Arg(valueArgName, typeRef(Long.TYPE))).setBody(block( stat(expr(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName), AssignmentOperator.Equal, varRef(valueArgName))) ))); body.addDeclaration(new VariablesDeclaration(typeRef(Long.TYPE), new DirectDeclarator(valueArgName)).addModifiers(ModifierType.Public, ModifierType.Final)); body.addDeclaration(new Function(Type.JavaMethod, ident(valueArgName), typeRef(Long.TYPE)).setBody(block( new Statement.Return(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName)) )).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("iterator"), typeRef(ident(Iterator.class, expr(typeRef(enumName.clone()))))).setBody(block( new Statement.Return( methodCall( methodCall( expr(typeRef(Collections.class)), MemberRefStyle.Dot, "singleton", thisRef() ), MemberRefStyle.Dot, "iterator" ) ) )).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("fromValue"), typeRef(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))), new Arg(valueArgName, typeRef(Integer.TYPE))).setBody(block( new Statement.Return( methodCall( expr(typeRef(FlagSet.class)), MemberRefStyle.Dot, "fromValue", varRef(valueArgName), methodCall( "values" ) ) ) )).addModifiers(ModifierType.Public, ModifierType.Static)); } } else { outputEnumItemsAsConstants(results, out, signatures, libraryClassName, hasEnumClass); } } void addCallingConventionAnnotation(Function originalFunction, ModifiableElement target) { Convention.Style cc = null; if (originalFunction.hasModifier(ModifierType.__stdcall)) cc = Convention.Style.StdCall; else if (originalFunction.hasModifier(ModifierType.__fastcall)) cc = Convention.Style.FastCall; else if (originalFunction.hasModifier(ModifierType.__thiscall)) cc = Convention.Style.ThisCall; else if (originalFunction.hasModifier(ModifierType.__pascal)) cc = Convention.Style.Pascal; if (cc != null) { target.addAnnotation(new Annotation(typeRef(Convention.class), enumRef(cc))); } } @Override public void convertFunction(Function function, Signatures signatures, boolean isCallback, DeclarationsHolder out, Identifier libraryClassName, String sig, Identifier functionName, String library, int iConstructor) throws UnsupportedConversionException { Element parent = function.getParentElement(); MemberVisibility visibility = function.getVisibility(); boolean isPublic = visibility == MemberVisibility.Public || function.hasModifier(ModifierType.Public); boolean isPrivate = visibility == MemberVisibility.Private || function.hasModifier(ModifierType.Private); boolean isProtected = visibility == MemberVisibility.Protected || function.hasModifier(ModifierType.Protected); boolean isInStruct = parent instanceof Struct; if (isInStruct && result.config.skipPrivateMembers && (isPrivate || !isPublic && !isProtected)) return; boolean isStatic = function.hasModifier(ModifierType.Static); boolean isConstructor = iConstructor != -1; Function nativeMethod = new Function(Type.JavaMethod, ident(functionName), null); if (result.config.synchronizedMethods && !isCallback) nativeMethod.addModifiers(ModifierType.Synchronized); addCallingConventionAnnotation(function, nativeMethod); if (function.getName() != null && !functionName.toString().equals(function.getName().toString()) && !isCallback) { TypeRef mgc = result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Name); if (mgc != null) { nativeMethod.addAnnotation(new Annotation(mgc, "(\"" + function.getName() + "\")")); } } Function rawMethod = nativeMethod.clone(); //Map<String, NL4JConversion> argTypes = new LinkedHashMap<String, NL4JConversion>(); boolean isObjectiveC = function.getType() == Type.ObjCMethod; int iArg = 1; Set<String> argNames = new TreeSet<String>(); List<Expression> superConstructorArgs = null; if (isConstructor) { superConstructorArgs = new ArrayList<Expression>(); superConstructorArgs.add(cast(typeRef(Void.class), nullExpr())); superConstructorArgs.add(expr(iConstructor)); } Identifier varArgType = null; String varArgName = null; NL4JConversion returnType = null; List<NL4JConversion> paramTypes = new ArrayList<NL4JConversion>(); List<String> paramNames = new ArrayList<String>(); if (!isConstructor) { returnType = ((BridJTypeConversion)result.typeConverter).convertTypeToNL4J(function.getValueType(), libraryClassName, null, null, -1, -1); } for (Arg arg : function.getArgs()) { String paramName; if (arg.isVarArg()) { assert arg.getValueType() == null; paramName = varArgName = chooseJavaArgName("varargs", iArg, argNames); varArgType = ident(isObjectiveC ? NSObject.class : Object.class); } else { paramName = chooseJavaArgName(arg.getName(), iArg, argNames); paramTypes.add(((BridJTypeConversion)result.typeConverter).convertTypeToNL4J(arg.getValueType(), libraryClassName, null, null, -1, -1)); } paramNames.add(paramName); if (isConstructor) { superConstructorArgs.add(varRef(paramName)); } iArg++; } fillIn(signatures, functionName, nativeMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, false); Block convertedBody = null; if (isConstructor) { convertedBody = block(stat(methodCall("super", superConstructorArgs.toArray(new Expression[superConstructorArgs.size()])))); } else if (result.config.convertBodies && function.getBody() != null) { try { Pair<Element, List<Declaration>> bodyAndExtraDeclarations = result.bridjer.convertToJava(function.getBody(), libraryClassName); convertedBody = (Block)bodyAndExtraDeclarations.getFirst(); for (Declaration d : bodyAndExtraDeclarations.getSecond()) out.addDeclaration(d); } catch (Exception ex) { ex.printStackTrace(System.out); nativeMethod.addToCommentBefore("TRANSLATION OF BODY FAILED: " + ex); } } if (!result.config.noComments) nativeMethod.importComments(function, isCallback ? null : getFileCommentContent(function)); out.addDeclaration(nativeMethod); boolean generateStaticMethod = isStatic || !isCallback && !isInStruct; if (convertedBody == null) { boolean forwardedToRaw = false; if (result.config.genRawBindings && !isCallback) { // Function rawMethod = nativeMethod.clone(); rawMethod.setArgs(Collections.EMPTY_LIST); fillIn(signatures, functionName, rawMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, true); rawMethod.addModifiers(ModifierType.Protected, ModifierType.Native); if (generateStaticMethod) rawMethod.addModifiers(ModifierType.Static); if (!nativeMethod.computeSignature(SignatureType.ArgsAndRet).equals(rawMethod.computeSignature(SignatureType.ArgsAndRet))) { out.addDeclaration(rawMethod); List<Expression> followedArgs = new ArrayList<Expression>(); for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); Expression followedArg; switch (paramType.type) { case Pointer: followedArg = methodCall(expr(typeRef(org.bridj.Pointer.class)), "getPeer", varRef(paramName)); break; case Enum: followedArg = cast(typeRef(int.class), methodCall(varRef(paramName), "value")); break; // case NativeSize: // case NativeLong: // followedArg = methodCall(varRef(paramName), "longValue"); // break; default: followedArg = varRef(paramName); break; } followedArgs.add(followedArg); } if (varArgType != null) { followedArgs.add(varRef(varArgName)); } Expression followedCall = methodCall(rawMethod.getName().toString(), followedArgs.toArray(new Expression[followedArgs.size()])); boolean isVoid = "void".equals(String.valueOf(nativeMethod.getValueType())); if (isVoid) nativeMethod.setBody(block(stat(followedCall))); else { switch (returnType.type) { case Pointer: if (returnType.isTypedPointer) followedCall = new New(nativeMethod.getValueType(), followedCall); else { Expression ptrExpr = expr(typeRef(org.bridj.Pointer.class)); Expression targetTypeExpr = result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType())); if (targetTypeExpr == null || (returnType.targetTypeConversion != null && returnType.targetTypeConversion.type == ConvType.Void)) followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall); else followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall, targetTypeExpr); } break; case Enum: followedCall = methodCall(expr(typeRef(org.bridj.FlagSet.class)), "fromValue", followedCall, result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType()))); break; case NativeLong: case NativeSize: if (!rawMethod.getValueType().toString().equals("long")) { followedCall = new New(nativeMethod.getValueType().clone(), followedCall); } default: break; } nativeMethod.setBody(block(new Statement.Return(followedCall))); } forwardedToRaw = true; } } if (!forwardedToRaw) nativeMethod.addModifiers(isCallback ? ModifierType.Abstract : ModifierType.Native); } else nativeMethod.setBody(convertedBody); nativeMethod.addModifiers( isProtected ? ModifierType.Protected : ModifierType.Public, generateStaticMethod ? ModifierType.Static : null ); } private void fillIn(Signatures signatures, Identifier functionName, Function nativeMethod, NL4JConversion returnType, List<NL4JConversion> paramTypes, List<String> paramNames, Identifier varArgType, String varArgName, boolean isCallback, boolean useRawTypes) { for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); nativeMethod.addArg(paramType.annotateTypedType(new Arg(paramName, paramType.getTypeRef(useRawTypes)), useRawTypes));//.getTypedTypeRef()))); } if (varArgType != null) nativeMethod.addArg(new Arg(varArgName, typeRef(varArgType.clone()))).setVarArg(true); if (returnType != null) { returnType.annotateTypedType(nativeMethod, useRawTypes); nativeMethod.setValueType(returnType.getTypeRef(useRawTypes)); } String natSig = nativeMethod.computeSignature(SignatureType.JavaStyle); Identifier javaMethodName = signatures == null ? functionName : signatures.findNextMethodName(natSig, functionName); if (!javaMethodName.equals(functionName)) { nativeMethod.setName(javaMethodName); } if (!isCallback && !javaMethodName.equals(functionName)) annotateActualName(nativeMethod, functionName); } @Override public Struct convertStruct(Struct struct, Signatures signatures, Identifier callerLibraryClass, String callerLibrary, boolean onlyFields) throws IOException { Identifier structName = getActualTaggedTypeName(struct); if (structName == null) return null; //if (structName.toString().contains("MonoObject")) // structName.toString(); if (struct.isForwardDeclaration())// && !result.structsByName.get(structName).isForwardDeclaration()) return null; if (!signatures.addClass(structName)) return null; boolean isUnion = struct.getType() == Struct.Type.CUnion; boolean inheritsFromStruct = false; Identifier baseClass = null; int parentFieldsCount = 0; List<String> preComments = new ArrayList<String>(); for (SimpleTypeRef parentName : struct.getParents()) { Struct parent = result.structsByName.get(parentName.getName()); if (parent == null) { // TODO report error continue; } try { parentFieldsCount += countFieldsInStruct(parent); } catch (UnsupportedConversionException ex) { preComments.add("Error: " + ex); } baseClass = result.typeConverter.getTaggedTypeIdentifierInJava(parent); if (baseClass != null) { inheritsFromStruct = true; break; // TODO handle multiple and virtual inheritage } } boolean hasMemberFunctions = false; for (Declaration d : struct.getDeclarations()) { if (d instanceof Function) { hasMemberFunctions = true; break; } } Constant uuid = (Constant)struct.getModifierValue(ModifierType.UUID); if (baseClass == null) { switch (struct.getType()) { case CStruct: case CUnion: if (!hasMemberFunctions) { baseClass = ident(StructObject.class); break; } case CPPClass: baseClass = ident(uuid == null ? CPPObject.class : IUnknown.class); result.hasCPlusPlus = true; break; default: throw new UnsupportedOperationException(); } } Struct structJavaClass = publicStaticClass(structName, baseClass, Struct.Type.JavaClass, struct); //if (result.config.microsoftCOM) { if (uuid != null) { structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.IID), uuid)); } structJavaClass.addToCommentBefore(preComments); //System.out.println("parentFieldsCount(structName = " + structName + ") = " + parentFieldsCount); final int iChild[] = new int[] { parentFieldsCount }; //cl.addDeclaration(new EmptyDeclaration()) Signatures childSignatures = new Signatures(); /*if (isVirtual(struct) && !onlyFields) { String vptrName = DEFAULT_VPTR_NAME; VariablesDeclaration vptr = new VariablesDeclaration(typeRef(VirtualTablePointer.class), new Declarator.DirectDeclarator(vptrName)); vptr.addModifiers(ModifierType.Public); structJavaClass.addDeclaration(vptr); childSignatures.variablesSignatures.add(vptrName); // TODO add vptr grabber to constructor ! }*/ // private static StructIO<MyStruct> io = StructIO.getInstance(MyStruct.class); Function defaultConstructor = new Function(Type.JavaMethod, ident(structName), null).setBody(block(stat(methodCall("super")))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(defaultConstructor)) structJavaClass.addDeclaration(defaultConstructor); if (isUnion) structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Union))); int iVirtual = 0, iConstructor = 0; //List<Declaration> children = new ArrayList<Declaration>(); for (Declaration d : struct.getDeclarations()) { //if (isUnion) // iChild[0] = 0; if (d instanceof VariablesDeclaration) { convertVariablesDeclaration((VariablesDeclaration)d, childSignatures, structJavaClass, iChild, false, structName, callerLibraryClass, callerLibrary); } else if (!onlyFields) { if (d instanceof TaggedTypeRefDeclaration) { TaggedTypeRef tr = ((TaggedTypeRefDeclaration) d).getTaggedTypeRef(); if (tr instanceof Struct) { outputConvertedStruct((Struct)tr, childSignatures, structJavaClass, callerLibraryClass, callerLibrary, false); } else if (tr instanceof Enum) { convertEnum((Enum)tr, childSignatures, structJavaClass, callerLibraryClass); } } else if (d instanceof TypeDef) { TypeDef td = (TypeDef)d; TypeRef tr = td.getValueType(); if (tr instanceof Struct) { outputConvertedStruct((Struct)tr, childSignatures, structJavaClass, callerLibraryClass, callerLibrary, false); } else if (tr instanceof FunctionSignature) { convertCallback((FunctionSignature)tr, childSignatures, structJavaClass, callerLibraryClass); } } else if (result.config.genCPlusPlus && d instanceof Function) { Function f = (Function) d; boolean isVirtual = f.hasModifier(ModifierType.Virtual); boolean isConstructor = f.getName().equals(structName) && (f.getValueType() == null || f.getValueType().toString().equals("void")); if (isConstructor && f.getArgs().isEmpty()) continue; // default constructor was already generated String library = result.getLibrary(struct); if (library == null) continue; List<Declaration> decls = new ArrayList<Declaration>(); convertFunction(f, childSignatures, false, new ListWrapper(decls), callerLibraryClass, isConstructor ? iConstructor : -1); for (Declaration md : decls) { if (!(md instanceof Function)) continue; Function method = (Function) md; boolean commentOut = false; if (isVirtual) method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Virtual), expr(iVirtual))); else if (method.getValueType() == null) { method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Constructor), expr(iConstructor))); isConstructor = true; } if (method.getName().toString().equals("operator")) commentOut = true; if (commentOut) structJavaClass.addDeclaration(new EmptyDeclaration(method.toString())); else structJavaClass.addDeclaration(method); } if (isVirtual) iVirtual++; if (isConstructor) iConstructor++; } } } String ptrName = "pointer"; Function castConstructor = new Function(Type.JavaMethod, ident(structName), null, new Arg(ptrName, typeRef(result.config.runtime.pointerClass))).setBody(block(stat(methodCall("super", varRef(ptrName))))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(castConstructor)) structJavaClass.addDeclaration(castConstructor); return structJavaClass; }
diff --git a/CubicTestWatirExporter/src/org/cubictest/exporters/watir/converters/TransitionConverter.java b/CubicTestWatirExporter/src/org/cubictest/exporters/watir/converters/TransitionConverter.java index b8d41a68..2fb5d474 100644 --- a/CubicTestWatirExporter/src/org/cubictest/exporters/watir/converters/TransitionConverter.java +++ b/CubicTestWatirExporter/src/org/cubictest/exporters/watir/converters/TransitionConverter.java @@ -1,179 +1,179 @@ /* * Created on Apr 27, 2005 * This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE * Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html * */ package org.cubictest.exporters.watir.converters; import static org.cubictest.model.ActionType.CHECK; import static org.cubictest.model.ActionType.CLEAR_ALL_TEXT; import static org.cubictest.model.ActionType.CLICK; import static org.cubictest.model.ActionType.ENTER_PARAMETER_TEXT; import static org.cubictest.model.ActionType.ENTER_TEXT; import static org.cubictest.model.ActionType.GO_BACK; import static org.cubictest.model.ActionType.GO_FORWARD; import static org.cubictest.model.ActionType.NEXT_WINDOW; import static org.cubictest.model.ActionType.PREVIOUS_WINDOW; import static org.cubictest.model.ActionType.REFRESH; import static org.cubictest.model.ActionType.SELECT; import static org.cubictest.model.ActionType.UNCHECK; import static org.cubictest.model.IdentifierType.LABEL; import java.util.Iterator; import java.util.List; import org.cubictest.export.converters.ITransitionConverter; import org.cubictest.export.exceptions.ExporterException; import org.cubictest.exporters.watir.holders.IStepList; import org.cubictest.exporters.watir.holders.TestStep; import org.cubictest.exporters.watir.utils.WatirUtils; import org.cubictest.model.ActionType; import org.cubictest.model.FormElement; import org.cubictest.model.IdentifierType; import org.cubictest.model.PageElement; import org.cubictest.model.UserInteraction; import org.cubictest.model.UserInteractionsTransition; import org.cubictest.model.WebBrowser; import org.cubictest.model.formElement.Button; import org.cubictest.model.formElement.Option; import org.cubictest.model.formElement.Select; /** * Class to convert transitions between pages to runnable ITestStep objects. * * @author chr_schwarz */ public class TransitionConverter implements ITransitionConverter<IStepList> { /** * Converts a user interactions transition to a list of Watir steps. * * @param userInteractions The transition to convert. */ public void handleUserInteractions(IStepList steps, UserInteractionsTransition userInteractions) { List inputs = userInteractions.getUserInteractions(); Iterator it = inputs.iterator(); while(it.hasNext()) { UserInteraction userInput = (UserInteraction) it.next(); handlePageElementAction(steps, userInput); } } /** * Converts a UserInteraction to a Watir Step. * * @param peAction The FormInput to convert. */ private void handlePageElementAction(IStepList steps, UserInteraction peAction) { Object obj = peAction.getElement(); if (obj == null) { return; } ActionType action = peAction.getActionType(); TestStep step = null; if (obj instanceof PageElement) { String input = peAction.getTextualInput(); PageElement element = (PageElement)peAction.getElement(); String elementType = WatirUtils.getElementType(element); String idType = WatirUtils.getIdType(element); String idText = element.getText(); //If label, inject script to get the ID from the label and modify variables with the injected value: if (element.getIdentifierType().equals(LABEL) && element instanceof FormElement && !(element instanceof Button) && !(element instanceof Option)) { StringBuffer buff = new StringBuffer(); WatirUtils.appendGetLabelTargetId(buff, element, element.getDescription()); idText = "\" + labelTargetId + \""; idType = ":id"; steps.add(new TestStep(buff.toString()).setDescription("Getting label with text = '" + element.getText())); } if(action.equals(CLICK)){ step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").click"); step.setDescription("Clicking on " + elementType + " with " + idType + " = '" + idText + "'"); } - if (action.equals(SELECT) && element instanceof Option) { + else if (action.equals(SELECT) && element instanceof Option) { //Option in SelectList: Select parent = (Select) ((Option) element).getParent(); String parentIdText = parent.getText(); String parentIdType = WatirUtils.getIdType(parent); if (parent.getIdentifierType().equals(IdentifierType.LABEL)) { //If label, inject script to get the ID from the label and modify variables with the injected value: StringBuffer buff = new StringBuffer(); WatirUtils.appendGetLabelTargetId(buff, parent, parent.getDescription()); parentIdText = "\" + labelTargetId + \""; parentIdType = ":id"; steps.add(new TestStep(buff.toString()).setDescription("Getting select list with text = '" + parent.getText())); } String selectList = "ie.select_list(" + parentIdType + ", \"" + parentIdText + "\")"; if (element.getIdentifierType().equals(LABEL)) { step = new TestStep(selectList + ".select(\"" + idText + "\")"); } else { step = new TestStep(selectList + ".option(" + idType + ", \"" + idText + "\").select"); } String ctxMessage = steps.getPrefix().equals(ContextConverter.ROOT_CONTEXT) ? "" : " ( in " + ContextConverter.ROOT_CONTEXT + ")"; step.setDescription("Selecting " + element.getType() + " with " + idType + " = '" + idText + "'" + ctxMessage); } else if(action.equals(CHECK)){ step = new TestStep("ie." + elementType + "(" + idType + " , \"" + idText + "\").set"); step.setDescription("Setting " + element.getType() + " with " + idType + " = '" + idText + "' to checked"); } else if(action.equals(UNCHECK)){ step = new TestStep("ie." + elementType + "(" + idType + " , \"" + idText + "\").clear"); step.setDescription("Setting " + element.getType() + " with " + idType + " = '" + idText + "' to NOT checked"); } else if(action.equals(ENTER_TEXT) || action.equals(ENTER_PARAMETER_TEXT)){ if (element instanceof Select) { step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").option(:value, \"" + input +"\").select"); step.setDescription("Selecting option with value '" + input + "' in " + element.getType() + " with " + idType + " = '" + idText + "'"); } else { step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").set(\"" + input +"\")"); step.setDescription("Inserting value '" + input + "' into " + element.getType() + " with " + idType + " = '" + idText + "'"); } } else if(action.equals(CLEAR_ALL_TEXT)){ step = new TestStep("ie." + elementType + "(" + idType + " , \"" + idText + "\").clear"); step.setDescription("Clearing " + element.getType() + " with " + idType + " = '" + idText + "'"); } else{ //Handle all other events String eventType = WatirUtils.getEventType(action); step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").fireEvent(\"" + eventType + "\")"); step.setDescription("FireEvent '" + eventType + "' on " + element.getType() + " with " + idType + " = '" + idText + "'"); } } else if (obj instanceof WebBrowser) { if (action.equals(GO_BACK)) { step = new TestStep("ie.back()"); step.setDescription("Pressing browser back-button"); } else if (action.equals(GO_FORWARD)) { step = new TestStep("ie.forward()"); step.setDescription("Pressing browser forward-button"); } else if (action.equals(REFRESH)){ step = new TestStep("ie.refresh()"); step.setDescription("Pressing browser refresh button"); } else if (action.equals(NEXT_WINDOW)){ // TODO: should call the IE.attach method in Watir, it requires either an URL or the name of the window. // probably best to just use the name, in order to make it work for more frameworks throw new ExporterException("Previous window not supported by Watir"); } else if (action.equals(PREVIOUS_WINDOW)) { // TODO: should call the IE.attach method in Watir, it requires either an URL or the name of the window. // probably best to just use the name, in order to make it work for more frameworks throw new ExporterException("Previous window not supported by Watir"); } } steps.add(step); } }
true
true
private void handlePageElementAction(IStepList steps, UserInteraction peAction) { Object obj = peAction.getElement(); if (obj == null) { return; } ActionType action = peAction.getActionType(); TestStep step = null; if (obj instanceof PageElement) { String input = peAction.getTextualInput(); PageElement element = (PageElement)peAction.getElement(); String elementType = WatirUtils.getElementType(element); String idType = WatirUtils.getIdType(element); String idText = element.getText(); //If label, inject script to get the ID from the label and modify variables with the injected value: if (element.getIdentifierType().equals(LABEL) && element instanceof FormElement && !(element instanceof Button) && !(element instanceof Option)) { StringBuffer buff = new StringBuffer(); WatirUtils.appendGetLabelTargetId(buff, element, element.getDescription()); idText = "\" + labelTargetId + \""; idType = ":id"; steps.add(new TestStep(buff.toString()).setDescription("Getting label with text = '" + element.getText())); } if(action.equals(CLICK)){ step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").click"); step.setDescription("Clicking on " + elementType + " with " + idType + " = '" + idText + "'"); } if (action.equals(SELECT) && element instanceof Option) { //Option in SelectList: Select parent = (Select) ((Option) element).getParent(); String parentIdText = parent.getText(); String parentIdType = WatirUtils.getIdType(parent); if (parent.getIdentifierType().equals(IdentifierType.LABEL)) { //If label, inject script to get the ID from the label and modify variables with the injected value: StringBuffer buff = new StringBuffer(); WatirUtils.appendGetLabelTargetId(buff, parent, parent.getDescription()); parentIdText = "\" + labelTargetId + \""; parentIdType = ":id"; steps.add(new TestStep(buff.toString()).setDescription("Getting select list with text = '" + parent.getText())); } String selectList = "ie.select_list(" + parentIdType + ", \"" + parentIdText + "\")"; if (element.getIdentifierType().equals(LABEL)) { step = new TestStep(selectList + ".select(\"" + idText + "\")"); } else { step = new TestStep(selectList + ".option(" + idType + ", \"" + idText + "\").select"); } String ctxMessage = steps.getPrefix().equals(ContextConverter.ROOT_CONTEXT) ? "" : " ( in " + ContextConverter.ROOT_CONTEXT + ")"; step.setDescription("Selecting " + element.getType() + " with " + idType + " = '" + idText + "'" + ctxMessage); } else if(action.equals(CHECK)){ step = new TestStep("ie." + elementType + "(" + idType + " , \"" + idText + "\").set"); step.setDescription("Setting " + element.getType() + " with " + idType + " = '" + idText + "' to checked"); } else if(action.equals(UNCHECK)){ step = new TestStep("ie." + elementType + "(" + idType + " , \"" + idText + "\").clear"); step.setDescription("Setting " + element.getType() + " with " + idType + " = '" + idText + "' to NOT checked"); } else if(action.equals(ENTER_TEXT) || action.equals(ENTER_PARAMETER_TEXT)){ if (element instanceof Select) { step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").option(:value, \"" + input +"\").select"); step.setDescription("Selecting option with value '" + input + "' in " + element.getType() + " with " + idType + " = '" + idText + "'"); } else { step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").set(\"" + input +"\")"); step.setDescription("Inserting value '" + input + "' into " + element.getType() + " with " + idType + " = '" + idText + "'"); } } else if(action.equals(CLEAR_ALL_TEXT)){ step = new TestStep("ie." + elementType + "(" + idType + " , \"" + idText + "\").clear"); step.setDescription("Clearing " + element.getType() + " with " + idType + " = '" + idText + "'"); } else{ //Handle all other events String eventType = WatirUtils.getEventType(action); step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").fireEvent(\"" + eventType + "\")"); step.setDescription("FireEvent '" + eventType + "' on " + element.getType() + " with " + idType + " = '" + idText + "'"); } } else if (obj instanceof WebBrowser) { if (action.equals(GO_BACK)) { step = new TestStep("ie.back()"); step.setDescription("Pressing browser back-button"); } else if (action.equals(GO_FORWARD)) { step = new TestStep("ie.forward()"); step.setDescription("Pressing browser forward-button"); } else if (action.equals(REFRESH)){ step = new TestStep("ie.refresh()"); step.setDescription("Pressing browser refresh button"); } else if (action.equals(NEXT_WINDOW)){ // TODO: should call the IE.attach method in Watir, it requires either an URL or the name of the window. // probably best to just use the name, in order to make it work for more frameworks throw new ExporterException("Previous window not supported by Watir"); } else if (action.equals(PREVIOUS_WINDOW)) { // TODO: should call the IE.attach method in Watir, it requires either an URL or the name of the window. // probably best to just use the name, in order to make it work for more frameworks throw new ExporterException("Previous window not supported by Watir"); } } steps.add(step); }
private void handlePageElementAction(IStepList steps, UserInteraction peAction) { Object obj = peAction.getElement(); if (obj == null) { return; } ActionType action = peAction.getActionType(); TestStep step = null; if (obj instanceof PageElement) { String input = peAction.getTextualInput(); PageElement element = (PageElement)peAction.getElement(); String elementType = WatirUtils.getElementType(element); String idType = WatirUtils.getIdType(element); String idText = element.getText(); //If label, inject script to get the ID from the label and modify variables with the injected value: if (element.getIdentifierType().equals(LABEL) && element instanceof FormElement && !(element instanceof Button) && !(element instanceof Option)) { StringBuffer buff = new StringBuffer(); WatirUtils.appendGetLabelTargetId(buff, element, element.getDescription()); idText = "\" + labelTargetId + \""; idType = ":id"; steps.add(new TestStep(buff.toString()).setDescription("Getting label with text = '" + element.getText())); } if(action.equals(CLICK)){ step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").click"); step.setDescription("Clicking on " + elementType + " with " + idType + " = '" + idText + "'"); } else if (action.equals(SELECT) && element instanceof Option) { //Option in SelectList: Select parent = (Select) ((Option) element).getParent(); String parentIdText = parent.getText(); String parentIdType = WatirUtils.getIdType(parent); if (parent.getIdentifierType().equals(IdentifierType.LABEL)) { //If label, inject script to get the ID from the label and modify variables with the injected value: StringBuffer buff = new StringBuffer(); WatirUtils.appendGetLabelTargetId(buff, parent, parent.getDescription()); parentIdText = "\" + labelTargetId + \""; parentIdType = ":id"; steps.add(new TestStep(buff.toString()).setDescription("Getting select list with text = '" + parent.getText())); } String selectList = "ie.select_list(" + parentIdType + ", \"" + parentIdText + "\")"; if (element.getIdentifierType().equals(LABEL)) { step = new TestStep(selectList + ".select(\"" + idText + "\")"); } else { step = new TestStep(selectList + ".option(" + idType + ", \"" + idText + "\").select"); } String ctxMessage = steps.getPrefix().equals(ContextConverter.ROOT_CONTEXT) ? "" : " ( in " + ContextConverter.ROOT_CONTEXT + ")"; step.setDescription("Selecting " + element.getType() + " with " + idType + " = '" + idText + "'" + ctxMessage); } else if(action.equals(CHECK)){ step = new TestStep("ie." + elementType + "(" + idType + " , \"" + idText + "\").set"); step.setDescription("Setting " + element.getType() + " with " + idType + " = '" + idText + "' to checked"); } else if(action.equals(UNCHECK)){ step = new TestStep("ie." + elementType + "(" + idType + " , \"" + idText + "\").clear"); step.setDescription("Setting " + element.getType() + " with " + idType + " = '" + idText + "' to NOT checked"); } else if(action.equals(ENTER_TEXT) || action.equals(ENTER_PARAMETER_TEXT)){ if (element instanceof Select) { step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").option(:value, \"" + input +"\").select"); step.setDescription("Selecting option with value '" + input + "' in " + element.getType() + " with " + idType + " = '" + idText + "'"); } else { step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").set(\"" + input +"\")"); step.setDescription("Inserting value '" + input + "' into " + element.getType() + " with " + idType + " = '" + idText + "'"); } } else if(action.equals(CLEAR_ALL_TEXT)){ step = new TestStep("ie." + elementType + "(" + idType + " , \"" + idText + "\").clear"); step.setDescription("Clearing " + element.getType() + " with " + idType + " = '" + idText + "'"); } else{ //Handle all other events String eventType = WatirUtils.getEventType(action); step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").fireEvent(\"" + eventType + "\")"); step.setDescription("FireEvent '" + eventType + "' on " + element.getType() + " with " + idType + " = '" + idText + "'"); } } else if (obj instanceof WebBrowser) { if (action.equals(GO_BACK)) { step = new TestStep("ie.back()"); step.setDescription("Pressing browser back-button"); } else if (action.equals(GO_FORWARD)) { step = new TestStep("ie.forward()"); step.setDescription("Pressing browser forward-button"); } else if (action.equals(REFRESH)){ step = new TestStep("ie.refresh()"); step.setDescription("Pressing browser refresh button"); } else if (action.equals(NEXT_WINDOW)){ // TODO: should call the IE.attach method in Watir, it requires either an URL or the name of the window. // probably best to just use the name, in order to make it work for more frameworks throw new ExporterException("Previous window not supported by Watir"); } else if (action.equals(PREVIOUS_WINDOW)) { // TODO: should call the IE.attach method in Watir, it requires either an URL or the name of the window. // probably best to just use the name, in order to make it work for more frameworks throw new ExporterException("Previous window not supported by Watir"); } } steps.add(step); }
diff --git a/src/net/java/sip/communicator/impl/media/EncodingConfigurationTableModel.java b/src/net/java/sip/communicator/impl/media/EncodingConfigurationTableModel.java index 617c5dd69..c177f8ff8 100644 --- a/src/net/java/sip/communicator/impl/media/EncodingConfigurationTableModel.java +++ b/src/net/java/sip/communicator/impl/media/EncodingConfigurationTableModel.java @@ -1,186 +1,184 @@ /* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.media; import java.util.*; import javax.swing.table.*; import net.java.sip.communicator.impl.media.codec.*; /** * @author Lubomir Marinov */ public class EncodingConfigurationTableModel extends AbstractTableModel { public static final int AUDIO = DeviceConfigurationComboBoxModel.AUDIO; private static final String[] NO_ENCODINGS = new String[0]; public static final int VIDEO = DeviceConfigurationComboBoxModel.VIDEO; private final EncodingConfiguration encodingConfiguration; private String[] encodings; private final int type; public EncodingConfigurationTableModel( EncodingConfiguration encodingConfiguration, int type) { if (encodingConfiguration == null) throw new IllegalArgumentException("encodingConfiguration"); if ((type != AUDIO) && (type != VIDEO)) throw new IllegalArgumentException("type"); this.encodingConfiguration = encodingConfiguration; this.type = type; } public Class<?> getColumnClass(int columnIndex) { return (columnIndex == 0) ? Boolean.class : super .getColumnClass(columnIndex); } public int getColumnCount() { return 2; } private String[] getEncodings() { if (encodings != null) return encodings; String[] availableEncodings; switch (type) { case AUDIO: availableEncodings = encodingConfiguration.getAvailableAudioEncodings(); break; case VIDEO: availableEncodings = encodingConfiguration.getAvailableVideoEncodings(); break; default: throw new IllegalStateException("type"); } final int encodingCount = availableEncodings.length; if (encodingCount < 1) encodings = NO_ENCODINGS; else { encodings = new String[encodingCount]; System .arraycopy(availableEncodings, 0, encodings, 0, encodingCount); Arrays.sort(encodings, 0, encodingCount, new Comparator<String>() { public int compare(String encoding0, String encoding1) { - if (encodingConfiguration.getPriority(encoding0) > encodingConfiguration - .getPriority(encoding1)) - return -1; - return encoding0.compareTo(encoding1); + return encodingConfiguration.getPriority(encoding1) - + encodingConfiguration.getPriority(encoding0); } }); } return encodings; } private int[] getPriorities() { String[] encodings = getEncodings(); final int count = encodings.length; int[] priorities = new int[count]; for (int i = 0; i < count; i++) { int priority = encodingConfiguration.getPriority(encodings[i]); priorities[i] = (priority > 0) ? (count - i) : 0; } return priorities; } public int getRowCount() { return getEncodings().length; } public Object getValueAt(int rowIndex, int columnIndex) { String encoding = getEncodings()[rowIndex]; switch (columnIndex) { case 0: return (encodingConfiguration.getPriority(encoding) > 0); case 1: return MediaUtils.sdpToJmfEncoding(encoding); default: return null; } } public boolean isCellEditable(int rowIndex, int columnIndex) { return (columnIndex == 0); } public int move(int rowIndex, boolean up) { if (up) { if (rowIndex <= 0) throw new IllegalArgumentException("rowIndex"); return move(rowIndex - 1, false) - 1; } if (rowIndex >= (getRowCount() - 1)) throw new IllegalArgumentException("rowIndex"); int[] priorities = getPriorities(); final int nextRowIndex = rowIndex + 1; if (priorities[rowIndex] > 0) priorities[rowIndex] = priorities.length - nextRowIndex; if (priorities[nextRowIndex] > 0) priorities[nextRowIndex] = priorities.length - rowIndex; setPriorities(priorities); String swap = encodings[rowIndex]; encodings[rowIndex] = encodings[nextRowIndex]; encodings[nextRowIndex] = swap; fireTableRowsUpdated(rowIndex, nextRowIndex); return nextRowIndex; } private void setPriorities(int[] priorities) { final int count = encodings.length; if (priorities.length != count) throw new IllegalArgumentException("priorities"); for (int i = 0; i < count; i++) encodingConfiguration.setPriority(encodings[i], priorities[i]); } public void setValueAt(Object value, int rowIndex, int columnIndex) { if ((columnIndex == 0) && (value instanceof Boolean)) { int[] priorities = getPriorities(); priorities[rowIndex] = ((Boolean) value) ? (priorities.length - rowIndex) : 0; setPriorities(priorities); fireTableCellUpdated(rowIndex, columnIndex); } } }
true
true
private String[] getEncodings() { if (encodings != null) return encodings; String[] availableEncodings; switch (type) { case AUDIO: availableEncodings = encodingConfiguration.getAvailableAudioEncodings(); break; case VIDEO: availableEncodings = encodingConfiguration.getAvailableVideoEncodings(); break; default: throw new IllegalStateException("type"); } final int encodingCount = availableEncodings.length; if (encodingCount < 1) encodings = NO_ENCODINGS; else { encodings = new String[encodingCount]; System .arraycopy(availableEncodings, 0, encodings, 0, encodingCount); Arrays.sort(encodings, 0, encodingCount, new Comparator<String>() { public int compare(String encoding0, String encoding1) { if (encodingConfiguration.getPriority(encoding0) > encodingConfiguration .getPriority(encoding1)) return -1; return encoding0.compareTo(encoding1); } }); } return encodings; }
private String[] getEncodings() { if (encodings != null) return encodings; String[] availableEncodings; switch (type) { case AUDIO: availableEncodings = encodingConfiguration.getAvailableAudioEncodings(); break; case VIDEO: availableEncodings = encodingConfiguration.getAvailableVideoEncodings(); break; default: throw new IllegalStateException("type"); } final int encodingCount = availableEncodings.length; if (encodingCount < 1) encodings = NO_ENCODINGS; else { encodings = new String[encodingCount]; System .arraycopy(availableEncodings, 0, encodings, 0, encodingCount); Arrays.sort(encodings, 0, encodingCount, new Comparator<String>() { public int compare(String encoding0, String encoding1) { return encodingConfiguration.getPriority(encoding1) - encodingConfiguration.getPriority(encoding0); } }); } return encodings; }
diff --git a/plugins/org.eclipse.tm.tcf.debug.ui/src/org/eclipse/tm/internal/tcf/debug/ui/launch/TCFLaunchContext.java b/plugins/org.eclipse.tm.tcf.debug.ui/src/org/eclipse/tm/internal/tcf/debug/ui/launch/TCFLaunchContext.java index c7d71a75f..ab0910489 100644 --- a/plugins/org.eclipse.tm.tcf.debug.ui/src/org/eclipse/tm/internal/tcf/debug/ui/launch/TCFLaunchContext.java +++ b/plugins/org.eclipse.tm.tcf.debug.ui/src/org/eclipse/tm/internal/tcf/debug/ui/launch/TCFLaunchContext.java @@ -1,69 +1,69 @@ /******************************************************************************* * Copyright (c) 2008, 2010 Wind River Systems, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ package org.eclipse.tm.internal.tcf.debug.ui.launch; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtension; import org.eclipse.core.runtime.IExtensionPoint; import org.eclipse.core.runtime.Platform; import org.eclipse.tm.internal.tcf.debug.ui.Activator; import org.osgi.framework.Bundle; /** * TCF clients can implement ITCFLaunchContext to provide information about * workspace projects to TCF Launch Configuration. * * The information includes default values for launch configuration attributes, * list of executable binary files, etc. * * Since each project type can have its own methods to retrieve relevant information, * there should be implementation of this interface for each project type that support TCF. * * Implementation should be able to examine current IDE state (like active editor input source, * project explorer selection, etc.) and figure out an "active project". */ public class TCFLaunchContext { public static ITCFLaunchContext getLaunchContext(Object selection) { try { IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(Activator.PLUGIN_ID, "launch_context"); IExtension[] extensions = point.getExtensions(); for (int i = 0; i < extensions.length; i++) { try { Bundle bundle = Platform.getBundle(extensions[i].getNamespaceIdentifier()); - bundle.start(); + bundle.start(Bundle.START_TRANSIENT); IConfigurationElement[] e = extensions[i].getConfigurationElements(); for (int j = 0; j < e.length; j++) { String nm = e[j].getName(); if (nm.equals("class")) { //$NON-NLS-1$ Class<?> c = bundle.loadClass(e[j].getAttribute("name")); //$NON-NLS-1$ ITCFLaunchContext launch_context = (ITCFLaunchContext)c.newInstance(); if (selection != null) { if (launch_context.isSupportedSelection(selection)) return launch_context; } else { if (launch_context.isActive()) return launch_context; } } } } catch (Throwable x) { Activator.log("Cannot access launch context extension points", x); } } } catch (Exception x) { Activator.log("Cannot access launch context extension points", x); } return null; } }
true
true
public static ITCFLaunchContext getLaunchContext(Object selection) { try { IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(Activator.PLUGIN_ID, "launch_context"); IExtension[] extensions = point.getExtensions(); for (int i = 0; i < extensions.length; i++) { try { Bundle bundle = Platform.getBundle(extensions[i].getNamespaceIdentifier()); bundle.start(); IConfigurationElement[] e = extensions[i].getConfigurationElements(); for (int j = 0; j < e.length; j++) { String nm = e[j].getName(); if (nm.equals("class")) { //$NON-NLS-1$ Class<?> c = bundle.loadClass(e[j].getAttribute("name")); //$NON-NLS-1$ ITCFLaunchContext launch_context = (ITCFLaunchContext)c.newInstance(); if (selection != null) { if (launch_context.isSupportedSelection(selection)) return launch_context; } else { if (launch_context.isActive()) return launch_context; } } } } catch (Throwable x) { Activator.log("Cannot access launch context extension points", x); } } } catch (Exception x) { Activator.log("Cannot access launch context extension points", x); } return null; }
public static ITCFLaunchContext getLaunchContext(Object selection) { try { IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(Activator.PLUGIN_ID, "launch_context"); IExtension[] extensions = point.getExtensions(); for (int i = 0; i < extensions.length; i++) { try { Bundle bundle = Platform.getBundle(extensions[i].getNamespaceIdentifier()); bundle.start(Bundle.START_TRANSIENT); IConfigurationElement[] e = extensions[i].getConfigurationElements(); for (int j = 0; j < e.length; j++) { String nm = e[j].getName(); if (nm.equals("class")) { //$NON-NLS-1$ Class<?> c = bundle.loadClass(e[j].getAttribute("name")); //$NON-NLS-1$ ITCFLaunchContext launch_context = (ITCFLaunchContext)c.newInstance(); if (selection != null) { if (launch_context.isSupportedSelection(selection)) return launch_context; } else { if (launch_context.isActive()) return launch_context; } } } } catch (Throwable x) { Activator.log("Cannot access launch context extension points", x); } } } catch (Exception x) { Activator.log("Cannot access launch context extension points", x); } return null; }
diff --git a/src/org/eclipse/jface/bindings/keys/formatting/NativeKeyFormatter.java b/src/org/eclipse/jface/bindings/keys/formatting/NativeKeyFormatter.java index e388dd24..b8295fe1 100644 --- a/src/org/eclipse/jface/bindings/keys/formatting/NativeKeyFormatter.java +++ b/src/org/eclipse/jface/bindings/keys/formatting/NativeKeyFormatter.java @@ -1,194 +1,194 @@ /******************************************************************************* * Copyright (c) 2004, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jface.bindings.keys.formatting; import java.util.HashMap; import java.util.ResourceBundle; import org.eclipse.jface.bindings.keys.IKeyLookup; import org.eclipse.jface.bindings.keys.KeyLookupFactory; import org.eclipse.jface.bindings.keys.KeySequence; import org.eclipse.jface.bindings.keys.KeyStroke; import org.eclipse.jface.util.Util; import org.eclipse.swt.SWT; /** * <p> * Formats the key sequences and key strokes into the native human-readable * format. This is typically what you would see on the menus for the given * platform and locale. * </p> * * @since 3.1 */ public final class NativeKeyFormatter extends AbstractKeyFormatter { /** * The key into the internationalization resource bundle for the delimiter * to use between keys (on the Carbon platform). */ private final static String CARBON_KEY_DELIMITER_KEY = "CARBON_KEY_DELIMITER"; //$NON-NLS-1$ /** * A look-up table for the string representations of various carbon keys. */ private final static HashMap CARBON_KEY_LOOK_UP = new HashMap(); /** * The resource bundle used by <code>format()</code> to translate formal * string representations by locale. */ private final static ResourceBundle RESOURCE_BUNDLE; /** * The key into the internationalization resource bundle for the delimiter * to use between key strokes (on the Win32 platform). */ private final static String WIN32_KEY_STROKE_DELIMITER_KEY = "WIN32_KEY_STROKE_DELIMITER"; //$NON-NLS-1$ static { RESOURCE_BUNDLE = ResourceBundle.getBundle(NativeKeyFormatter.class .getName()); final String carbonBackspace = "\u232B"; //$NON-NLS-1$ CARBON_KEY_LOOK_UP.put(IKeyLookup.BS_NAME, carbonBackspace); CARBON_KEY_LOOK_UP.put(IKeyLookup.BACKSPACE_NAME, carbonBackspace); CARBON_KEY_LOOK_UP .put(IKeyLookup.CR_NAME, "\u21A9"); //$NON-NLS-1$ final String carbonDelete = "\u2326"; //$NON-NLS-1$ CARBON_KEY_LOOK_UP.put(IKeyLookup.DEL_NAME, carbonDelete); CARBON_KEY_LOOK_UP.put(IKeyLookup.DELETE_NAME, carbonDelete); CARBON_KEY_LOOK_UP.put(IKeyLookup.SPACE_NAME, "\u2423"); //$NON-NLS-1$ CARBON_KEY_LOOK_UP.put(IKeyLookup.ALT_NAME, "\u2325"); //$NON-NLS-1$ CARBON_KEY_LOOK_UP.put(IKeyLookup.COMMAND_NAME, "\u2318"); //$NON-NLS-1$ CARBON_KEY_LOOK_UP.put(IKeyLookup.CTRL_NAME, "\u2303"); //$NON-NLS-1$ CARBON_KEY_LOOK_UP.put(IKeyLookup.SHIFT_NAME, "\u21E7"); //$NON-NLS-1$ CARBON_KEY_LOOK_UP.put(IKeyLookup.ARROW_DOWN_NAME, "\u2193"); //$NON-NLS-1$ CARBON_KEY_LOOK_UP.put(IKeyLookup.ARROW_LEFT_NAME, "\u2190"); //$NON-NLS-1$ CARBON_KEY_LOOK_UP.put(IKeyLookup.ARROW_RIGHT_NAME, "\u2192"); //$NON-NLS-1$ CARBON_KEY_LOOK_UP.put(IKeyLookup.ARROW_UP_NAME, "\u2191"); //$NON-NLS-1$ CARBON_KEY_LOOK_UP.put(IKeyLookup.END_NAME, "\u2198"); //$NON-NLS-1$ CARBON_KEY_LOOK_UP.put(IKeyLookup.NUMPAD_ENTER_NAME, "\u2324"); //$NON-NLS-1$ CARBON_KEY_LOOK_UP.put(IKeyLookup.HOME_NAME, "\u2196"); //$NON-NLS-1$ CARBON_KEY_LOOK_UP.put(IKeyLookup.PAGE_DOWN_NAME, "\u21DF"); //$NON-NLS-1$ CARBON_KEY_LOOK_UP.put(IKeyLookup.PAGE_UP_NAME, "\u21DE"); //$NON-NLS-1$ } /** * Formats an individual key into a human readable format. This uses an * internationalization resource bundle to look up the key. This does the * platform-specific formatting for Carbon. * * @param key * The key to format. * @return The key formatted as a string; should not be <code>null</code>. */ public final String format(final int key) { final IKeyLookup lookup = KeyLookupFactory.getDefault(); final String name = lookup.formalNameLookup(key); // TODO consider platform-specific resource bundles if ("carbon".equals(SWT.getPlatform())) { //$NON-NLS-1$ String formattedName = (String) CARBON_KEY_LOOK_UP.get(name); if (formattedName != null) { return formattedName; } } return super.format(key); } /* * (non-Javadoc) * * @see org.eclipse.jface.bindings.keys.AbstractKeyFormatter#getKeyDelimiter() */ protected String getKeyDelimiter() { // We must do the look up every time, as our locale might change. if ("carbon".equals(SWT.getPlatform())) { //$NON-NLS-1$ return Util.translateString(RESOURCE_BUNDLE, CARBON_KEY_DELIMITER_KEY, Util.ZERO_LENGTH_STRING); } return Util.translateString(RESOURCE_BUNDLE, KEY_DELIMITER_KEY, KeyStroke.KEY_DELIMITER); } /* * (non-Javadoc) * * @see org.eclipse.jface.bindings.keys.AbstractKeyFormatter#getKeyStrokeDelimiter() */ protected String getKeyStrokeDelimiter() { // We must do the look up every time, as our locale might change. if ("win32".equals(SWT.getPlatform())) { //$NON-NLS-1$ return Util.translateString(RESOURCE_BUNDLE, WIN32_KEY_STROKE_DELIMITER_KEY, KeySequence.KEY_STROKE_DELIMITER); } return Util.translateString(RESOURCE_BUNDLE, KEY_STROKE_DELIMITER_KEY, KeySequence.KEY_STROKE_DELIMITER); } /* * (non-Javadoc) * * @see org.eclipse.jface.bindings.keys.AbstractKeyFormatter#sortModifierKeys(int) */ protected int[] sortModifierKeys(final int modifierKeys) { final IKeyLookup lookup = KeyLookupFactory.getDefault(); final String platform = SWT.getPlatform(); final int[] sortedKeys = new int[4]; int index = 0; - if ("win32".equals(platform)) { //$NON-NLS-1$ + if ("win32".equals(platform) || "wpf".equals(platform)) { //$NON-NLS-1$ //$NON-NLS-2$ if ((modifierKeys & lookup.getCtrl()) != 0) { sortedKeys[index++] = lookup.getCtrl(); } if ((modifierKeys & lookup.getAlt()) != 0) { sortedKeys[index++] = lookup.getAlt(); } if ((modifierKeys & lookup.getShift()) != 0) { sortedKeys[index++] = lookup.getShift(); } } else if ("gtk".equals(platform) || "motif".equals(platform)) { //$NON-NLS-1$ //$NON-NLS-2$ if ((modifierKeys & lookup.getShift()) != 0) { sortedKeys[index++] = lookup.getShift(); } if ((modifierKeys & lookup.getCtrl()) != 0) { sortedKeys[index++] = lookup.getCtrl(); } if ((modifierKeys & lookup.getAlt()) != 0) { sortedKeys[index++] = lookup.getAlt(); } } else if ("carbon".equals(platform)) { //$NON-NLS-1$ if ((modifierKeys & lookup.getShift()) != 0) { sortedKeys[index++] = lookup.getShift(); } if ((modifierKeys & lookup.getCtrl()) != 0) { sortedKeys[index++] = lookup.getCtrl(); } if ((modifierKeys & lookup.getAlt()) != 0) { sortedKeys[index++] = lookup.getAlt(); } if ((modifierKeys & lookup.getCommand()) != 0) { sortedKeys[index++] = lookup.getCommand(); } } return sortedKeys; } }
true
true
protected int[] sortModifierKeys(final int modifierKeys) { final IKeyLookup lookup = KeyLookupFactory.getDefault(); final String platform = SWT.getPlatform(); final int[] sortedKeys = new int[4]; int index = 0; if ("win32".equals(platform)) { //$NON-NLS-1$ if ((modifierKeys & lookup.getCtrl()) != 0) { sortedKeys[index++] = lookup.getCtrl(); } if ((modifierKeys & lookup.getAlt()) != 0) { sortedKeys[index++] = lookup.getAlt(); } if ((modifierKeys & lookup.getShift()) != 0) { sortedKeys[index++] = lookup.getShift(); } } else if ("gtk".equals(platform) || "motif".equals(platform)) { //$NON-NLS-1$ //$NON-NLS-2$ if ((modifierKeys & lookup.getShift()) != 0) { sortedKeys[index++] = lookup.getShift(); } if ((modifierKeys & lookup.getCtrl()) != 0) { sortedKeys[index++] = lookup.getCtrl(); } if ((modifierKeys & lookup.getAlt()) != 0) { sortedKeys[index++] = lookup.getAlt(); } } else if ("carbon".equals(platform)) { //$NON-NLS-1$ if ((modifierKeys & lookup.getShift()) != 0) { sortedKeys[index++] = lookup.getShift(); } if ((modifierKeys & lookup.getCtrl()) != 0) { sortedKeys[index++] = lookup.getCtrl(); } if ((modifierKeys & lookup.getAlt()) != 0) { sortedKeys[index++] = lookup.getAlt(); } if ((modifierKeys & lookup.getCommand()) != 0) { sortedKeys[index++] = lookup.getCommand(); } } return sortedKeys; }
protected int[] sortModifierKeys(final int modifierKeys) { final IKeyLookup lookup = KeyLookupFactory.getDefault(); final String platform = SWT.getPlatform(); final int[] sortedKeys = new int[4]; int index = 0; if ("win32".equals(platform) || "wpf".equals(platform)) { //$NON-NLS-1$ //$NON-NLS-2$ if ((modifierKeys & lookup.getCtrl()) != 0) { sortedKeys[index++] = lookup.getCtrl(); } if ((modifierKeys & lookup.getAlt()) != 0) { sortedKeys[index++] = lookup.getAlt(); } if ((modifierKeys & lookup.getShift()) != 0) { sortedKeys[index++] = lookup.getShift(); } } else if ("gtk".equals(platform) || "motif".equals(platform)) { //$NON-NLS-1$ //$NON-NLS-2$ if ((modifierKeys & lookup.getShift()) != 0) { sortedKeys[index++] = lookup.getShift(); } if ((modifierKeys & lookup.getCtrl()) != 0) { sortedKeys[index++] = lookup.getCtrl(); } if ((modifierKeys & lookup.getAlt()) != 0) { sortedKeys[index++] = lookup.getAlt(); } } else if ("carbon".equals(platform)) { //$NON-NLS-1$ if ((modifierKeys & lookup.getShift()) != 0) { sortedKeys[index++] = lookup.getShift(); } if ((modifierKeys & lookup.getCtrl()) != 0) { sortedKeys[index++] = lookup.getCtrl(); } if ((modifierKeys & lookup.getAlt()) != 0) { sortedKeys[index++] = lookup.getAlt(); } if ((modifierKeys & lookup.getCommand()) != 0) { sortedKeys[index++] = lookup.getCommand(); } } return sortedKeys; }
diff --git a/src/org/bombusim/lime/NotificationMgr.java b/src/org/bombusim/lime/NotificationMgr.java index 13065da..690e43e 100644 --- a/src/org/bombusim/lime/NotificationMgr.java +++ b/src/org/bombusim/lime/NotificationMgr.java @@ -1,147 +1,151 @@ /* * Copyright (c) 2005-2011, Eugene Stahov ([email protected]), * http://bombus-im.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.bombusim.lime; import org.bombusim.lime.activity.ChatActivity; import org.bombusim.lime.activity.RosterActivity; import org.bombusim.lime.data.Contact; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.Uri; public class NotificationMgr { private static final int MESSAGE_MAXLEN_NOTIFY = 250; private final static int NOTIFICATION_ONLINE = R.string.app_name; private final static int NOTIFICATION_CHAT = R.string.chatNotify; //TODO: read from configuration private boolean serviceIcon = true; private NotificationManager mNM; private Context context; public NotificationMgr(Context context) { this.context = context; mNM = (NotificationManager)(context.getSystemService(Context.NOTIFICATION_SERVICE)); } public void showChatNotification(Contact visavis, String message, long id) { + //cancelling old notification + mNM.cancel(NOTIFICATION_CHAT); // target ChatActivity - Intent openChat = new Intent(context, ChatActivity.class); + // Every intent should have unique action or uri, + // else we have a mess: same intents with different values. + Intent openChat = new Intent("Msg"+String.valueOf(id), null, context, ChatActivity.class); openChat.putExtra(ChatActivity.MY_JID, visavis.getRosterJid()); openChat.putExtra(ChatActivity.TO_JID, visavis.getJid()); if (message.length()>MESSAGE_MAXLEN_NOTIFY) { message = message.substring(0, MESSAGE_MAXLEN_NOTIFY) + "..."; } int icon = android.R.drawable.stat_notify_chat; String title = visavis.getScreenName(); //TODO: vibration //TODO: play sound // Set the icon, scrolling text and timestamp Notification notification = new Notification(icon, title + ": "+message, System.currentTimeMillis()); // The PendingIntent to launch our activity if the user selects this notification PendingIntent contentIntent = PendingIntent.getActivity(context, 0, openChat, 0); // Set the info for the views that show in the notification panel. notification.setLatestEventInfo(context, title, message, contentIntent); //TODO: optional //TODO: check activity is already visible Preferences p = Lime.getInstance().prefs; String ringtone = p.ringtoneMessage; if (ringtone.length() != 0) { notification.sound = Uri.parse(ringtone); } if (p.vibraNotifyMessage) notification.defaults |= Notification.DEFAULT_VIBRATE; if (p.ledNotifyMessage) { //notification.defaults |= Notification.DEFAULT_LIGHTS; notification.flags |= Notification.FLAG_SHOW_LIGHTS; notification.ledARGB = Color.GREEN; notification.ledOnMS = 300; notification.ledOffMS = 1000; } notification.flags |= Notification.FLAG_AUTO_CANCEL; // Send the notification. synchronized (this) { mNM.notify(NOTIFICATION_CHAT, notification); Lime.getInstance().lastMessageId = id; } } public void cancelChatNotification(long id) { synchronized (this) { if (id == Lime.getInstance().lastMessageId) { mNM.cancel(NOTIFICATION_CHAT); Lime.getInstance().lastMessageId = -1; } } } public void showOnlineNotification(boolean online) { if (!serviceIcon) return; int icon = ((online)? R.drawable.status_online : R.drawable.status_offline); CharSequence title = context.getText(R.string.app_name); CharSequence message = context.getText((online)? R.string.presence_online : R.string.presence_offline); // Set the icon, scrolling text and timestamp Notification notification = new Notification(icon, title, System.currentTimeMillis()); // The PendingIntent to launch our activity if the user selects this notification PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, RosterActivity.class), 0); // Set the info for the views that show in the notification panel. notification.setLatestEventInfo(context, title, message, contentIntent); notification.flags |= Notification.FLAG_NO_CLEAR; notification.flags |= Notification.FLAG_ONGOING_EVENT; // Send the notification. mNM.notify(NOTIFICATION_ONLINE, notification); } public void cancelOnlineNotification() { mNM.cancel(NOTIFICATION_ONLINE); } }
false
true
public void showChatNotification(Contact visavis, String message, long id) { // target ChatActivity Intent openChat = new Intent(context, ChatActivity.class); openChat.putExtra(ChatActivity.MY_JID, visavis.getRosterJid()); openChat.putExtra(ChatActivity.TO_JID, visavis.getJid()); if (message.length()>MESSAGE_MAXLEN_NOTIFY) { message = message.substring(0, MESSAGE_MAXLEN_NOTIFY) + "..."; } int icon = android.R.drawable.stat_notify_chat; String title = visavis.getScreenName(); //TODO: vibration //TODO: play sound // Set the icon, scrolling text and timestamp Notification notification = new Notification(icon, title + ": "+message, System.currentTimeMillis()); // The PendingIntent to launch our activity if the user selects this notification PendingIntent contentIntent = PendingIntent.getActivity(context, 0, openChat, 0); // Set the info for the views that show in the notification panel. notification.setLatestEventInfo(context, title, message, contentIntent); //TODO: optional //TODO: check activity is already visible Preferences p = Lime.getInstance().prefs; String ringtone = p.ringtoneMessage; if (ringtone.length() != 0) { notification.sound = Uri.parse(ringtone); } if (p.vibraNotifyMessage) notification.defaults |= Notification.DEFAULT_VIBRATE; if (p.ledNotifyMessage) { //notification.defaults |= Notification.DEFAULT_LIGHTS; notification.flags |= Notification.FLAG_SHOW_LIGHTS; notification.ledARGB = Color.GREEN; notification.ledOnMS = 300; notification.ledOffMS = 1000; } notification.flags |= Notification.FLAG_AUTO_CANCEL; // Send the notification. synchronized (this) { mNM.notify(NOTIFICATION_CHAT, notification); Lime.getInstance().lastMessageId = id; } }
public void showChatNotification(Contact visavis, String message, long id) { //cancelling old notification mNM.cancel(NOTIFICATION_CHAT); // target ChatActivity // Every intent should have unique action or uri, // else we have a mess: same intents with different values. Intent openChat = new Intent("Msg"+String.valueOf(id), null, context, ChatActivity.class); openChat.putExtra(ChatActivity.MY_JID, visavis.getRosterJid()); openChat.putExtra(ChatActivity.TO_JID, visavis.getJid()); if (message.length()>MESSAGE_MAXLEN_NOTIFY) { message = message.substring(0, MESSAGE_MAXLEN_NOTIFY) + "..."; } int icon = android.R.drawable.stat_notify_chat; String title = visavis.getScreenName(); //TODO: vibration //TODO: play sound // Set the icon, scrolling text and timestamp Notification notification = new Notification(icon, title + ": "+message, System.currentTimeMillis()); // The PendingIntent to launch our activity if the user selects this notification PendingIntent contentIntent = PendingIntent.getActivity(context, 0, openChat, 0); // Set the info for the views that show in the notification panel. notification.setLatestEventInfo(context, title, message, contentIntent); //TODO: optional //TODO: check activity is already visible Preferences p = Lime.getInstance().prefs; String ringtone = p.ringtoneMessage; if (ringtone.length() != 0) { notification.sound = Uri.parse(ringtone); } if (p.vibraNotifyMessage) notification.defaults |= Notification.DEFAULT_VIBRATE; if (p.ledNotifyMessage) { //notification.defaults |= Notification.DEFAULT_LIGHTS; notification.flags |= Notification.FLAG_SHOW_LIGHTS; notification.ledARGB = Color.GREEN; notification.ledOnMS = 300; notification.ledOffMS = 1000; } notification.flags |= Notification.FLAG_AUTO_CANCEL; // Send the notification. synchronized (this) { mNM.notify(NOTIFICATION_CHAT, notification); Lime.getInstance().lastMessageId = id; } }
diff --git a/src/org/newdawn/slick/Color.java b/src/org/newdawn/slick/Color.java index 60235d0..143fb76 100644 --- a/src/org/newdawn/slick/Color.java +++ b/src/org/newdawn/slick/Color.java @@ -1,317 +1,317 @@ package org.newdawn.slick; import java.io.Serializable; import java.nio.FloatBuffer; import org.newdawn.slick.opengl.renderer.Renderer; import org.newdawn.slick.opengl.renderer.SGL; /** * A simple wrapper round the values required for a colour * * @author Kevin Glass */ public class Color implements Serializable { /** The version ID for this calss */ private static final long serialVersionUID = 1393939L; /** The renderer to use for all GL operations */ protected static SGL GL = Renderer.get(); /** The fixed colour white */ public static final Color white = new Color(1.0f,1.0f,1.0f,1.0f); /** The fixed colour yellow */ public static final Color yellow = new Color(1.0f,1.0f,0,1.0f); /** The fixed colour red */ public static final Color red = new Color(1.0f,0,0,1.0f); /** The fixed colour blue */ public static final Color blue = new Color(0,0,1.0f,1.0f); /** The fixed colour green */ public static final Color green = new Color(0,1.0f,0,1.0f); /** The fixed colour black */ public static final Color black = new Color(0,0,0,1.0f); /** The fixed colour gray */ public static final Color gray = new Color(0.5f,0.5f,0.5f,1.0f); /** The fixed colour cyan */ public static final Color cyan = new Color(0,1.0f,1.0f,1.0f); /** The fixed colour dark gray */ public static final Color darkGray = new Color(0.3f,0.3f,0.3f,1.0f); /** The fixed colour light gray */ public static final Color lightGray = new Color(0.7f,0.7f,0.7f,1.0f); /** The fixed colour dark pink */ public final static Color pink = new Color(255, 175, 175); /** The fixed colour dark orange */ public final static Color orange = new Color(255, 200, 0); /** The fixed colour dark magenta */ public final static Color magenta = new Color(255, 0, 255); /** The red component of the colour */ public float r; /** The green component of the colour */ public float g; /** The blue component of the colour */ public float b; /** The alpha component of the colour */ public float a; /** * Copy constructor * * @param color The color to copy into the new instance */ public Color(Color color) { r = color.r; g = color.g; b = color.b; a = color.a; } /** * Create a component based on the first 4 elements of a float buffer * * @param buffer The buffer to read the color from */ public Color(FloatBuffer buffer) { this.r = buffer.get(); this.g = buffer.get(); this.b = buffer.get(); this.a = buffer.get(); } /** * Create a 3 component colour * * @param r The red component of the colour (0.0 -> 1.0) * @param g The green component of the colour (0.0 -> 1.0) * @param b The blue component of the colour (0.0 -> 1.0) */ public Color(float r,float g,float b) { this.r = r; this.g = g; this.b = b; this.a = 1; } /** * Create a 3 component colour * * @param r The red component of the colour (0.0 -> 1.0) * @param g The green component of the colour (0.0 -> 1.0) * @param b The blue component of the colour (0.0 -> 1.0) * @param a The alpha component of the colour (0.0 -> 1.0) */ public Color(float r,float g,float b,float a) { this.r = Math.min(r, 1); this.g = Math.min(g, 1); this.b = Math.min(b, 1); this.a = Math.min(a, 1); } /** * Create a 3 component colour * * @param r The red component of the colour (0 -> 255) * @param g The green component of the colour (0 -> 255) * @param b The blue component of the colour (0 -> 255) */ public Color(int r,int g,int b) { this.r = r / 255.0f; this.g = g / 255.0f; this.b = b / 255.0f; this.a = 1; } /** * Create a 3 component colour * * @param r The red component of the colour (0 -> 255) * @param g The green component of the colour (0 -> 255) * @param b The blue component of the colour (0 -> 255) * @param a The alpha component of the colour (0 -> 255) */ public Color(int r,int g,int b,int a) { this.r = r / 255.0f; this.g = g / 255.0f; this.b = b / 255.0f; this.a = a / 255.0f; } /** * Create a colour from an evil integer packed 0xAARRGGBB * * @param value The value to interpret for the colour */ public Color(int value) { int r = (value & 0x00FF0000) >> 16; int g = (value & 0x0000FF00) >> 8; int b = (value & 0x000000FF); int a = (value & 0xFF000000) >> 24; - if (a == 0) { - a = 255; + if (a < 0) { + a += 255; } this.r = r / 255.0f; this.g = g / 255.0f; this.b = b / 255.0f; this.a = a / 255.0f; } /** * Decode a number in a string and process it as a colour * reference. * * @param nm The number string to decode * @return The color generated from the number read */ public static Color decode(String nm) { return new Color(Integer.decode(nm).intValue()); } /** * Bind this colour to the GL context */ public void bind() { GL.glColor4f(r,g,b,a); } /** * @see java.lang.Object#hashCode() */ public int hashCode() { return ((int) (r+g+b+a)*255); } /** * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object other) { if (other instanceof Color) { Color o = (Color) other; return ((o.r == r) && (o.g == g) && (o.b == b) && (o.a == a)); } return false; } /** * @see java.lang.Object#toString() */ public String toString() { return "Color ("+r+","+g+","+b+","+a+")"; } /** * Make a darker instance of this colour * * @return The darker version of this colour */ public Color darker() { return darker(0.5f); } /** * Make a darker instance of this colour * * @param scale The scale down of RGB (i.e. if you supply 0.03 the colour will be darkened by 3%) * @return The darker version of this colour */ public Color darker(float scale) { scale = 1 - scale; Color temp = new Color(r * scale,g * scale,b * scale,a); return temp; } /** * Make a brighter instance of this colour * * @return The brighter version of this colour */ public Color brighter() { return brighter(0.2f); } /** * Get the red byte component of this colour * * @return The red component (range 0-255) */ public int getRedByte() { return (int) (r * 255); } /** * Get the green byte component of this colour * * @return The green component (range 0-255) */ public int getGreenByte() { return (int) (g * 255); } /** * Get the blue byte component of this colour * * @return The blue component (range 0-255) */ public int getBlueByte() { return (int) (b * 255); } /** * Get the alpha byte component of this colour * * @return The alpha component (range 0-255) */ public int getAlphaByte() { return (int) (a * 255); } /** * Make a brighter instance of this colour * * @param scale The scale up of RGB (i.e. if you supply 0.03 the colour will be brightened by 3%) * @return The brighter version of this colour */ public Color brighter(float scale) { scale += 1; Color temp = new Color(r * scale,g * scale,b * scale,a); return temp; } /** * Multiply this color by another * * @param c the other color * @return product of the two colors */ public Color multiply(Color c) { return new Color(r * c.r, g * c.g, b * c.b, a * c.a); } /** * Add another colour to this one * * @param c The colour to add */ public void add(Color c) { r += c.r; g += c.g; b += c.b; a += c.a; } /** * Scale the components of the colour by the given value * * @param value The value to scale by */ public void scale(float value) { r *= value; g *= value; b *= value; a *= value; } }
true
true
public Color(int value) { int r = (value & 0x00FF0000) >> 16; int g = (value & 0x0000FF00) >> 8; int b = (value & 0x000000FF); int a = (value & 0xFF000000) >> 24; if (a == 0) { a = 255; } this.r = r / 255.0f; this.g = g / 255.0f; this.b = b / 255.0f; this.a = a / 255.0f; }
public Color(int value) { int r = (value & 0x00FF0000) >> 16; int g = (value & 0x0000FF00) >> 8; int b = (value & 0x000000FF); int a = (value & 0xFF000000) >> 24; if (a < 0) { a += 255; } this.r = r / 255.0f; this.g = g / 255.0f; this.b = b / 255.0f; this.a = a / 255.0f; }
diff --git a/src/net/drmods/plugins/irc/Rank.java b/src/net/drmods/plugins/irc/Rank.java index dee3663a..720da383 100644 --- a/src/net/drmods/plugins/irc/Rank.java +++ b/src/net/drmods/plugins/irc/Rank.java @@ -1,230 +1,230 @@ /* * This file is part of DrFTPD, Distributed FTP Daemon. * * DrFTPD is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * DrFTPD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DrFTPD; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package net.drmods.plugins.irc; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Properties; import java.util.StringTokenizer; import net.sf.drftpd.util.ReplacerUtils; import net.sf.drftpd.util.UserComparator; import org.apache.log4j.Logger; import org.drftpd.Bytes; import org.drftpd.GlobalContext; import org.drftpd.commands.TransferStatistics; import org.drftpd.plugins.SiteBot; import org.drftpd.plugins.Trial; import org.drftpd.sitebot.IRCCommand; import org.drftpd.usermanager.User; import org.drftpd.usermanager.UserFileException; import org.tanesha.replacer.ReplacerEnvironment; import f00f.net.irc.martyr.commands.MessageCommand; import f00f.net.irc.martyr.util.FullNick; /** * @author Teflon * @version $Id$ */ public class Rank extends IRCCommand { private static final Logger logger = Logger.getLogger(Rank.class); private String _exemptGroups; public Rank(GlobalContext gctx) { super(gctx); loadConf("conf/drmods.conf"); } public void loadConf(String confFile) { Properties cfg = new Properties(); FileInputStream file = null; try { file = new FileInputStream(confFile); cfg.load(file); _exemptGroups = cfg.getProperty("rank.exempt"); if (_exemptGroups == null) { throw new RuntimeException("Unspecified value 'rank.exempt' in " + confFile); } } catch (FileNotFoundException e) { logger.error("Error reading " + confFile,e); throw new RuntimeException(e.getMessage()); } catch (IOException e) { logger.error("Error reading " + confFile,e); throw new RuntimeException(e.getMessage()); } finally { if (file != null) { try { file.close(); } catch (IOException e) { } } } } public ArrayList<String> doRank(String args, MessageCommand msgc) { ArrayList<String> out = new ArrayList<String>(); ReplacerEnvironment env = new ReplacerEnvironment(SiteBot.GLOBAL_ENV); env.add("ircnick", msgc.getSource().getNick()); FullNick fn = msgc.getSource(); String ident = fn.getNick() + "!" + fn.getUser() + "@" + fn.getHost(); User user; if (args.equals("")) { try { user = getGlobalContext().getUserManager().getUserByIdent(ident); } catch (Exception e) { logger.warn("Could not identify " + ident); out.add(ReplacerUtils.jprintf("ident.noident", env, SiteBot.class)); return out; } } else { try { user = getGlobalContext().getUserManager().getUserByName(args); } catch (Exception e) { - logger.error(args + " is not a vlid username", e); + logger.error(args + " is not a valid username", e); env.add("user", args); out.add(ReplacerUtils.jprintf("rank.error", env, Rank.class)); return out; } } StringTokenizer st = new StringTokenizer(_exemptGroups); while (st.hasMoreTokens()) { if (user.isMemberOf(st.nextToken())) { env.add("eusr", user.getName()); env.add("egrp", user.getGroup()); out.add(ReplacerUtils.jprintf("rank.exempt", env, Rank.class)); return out; } } Collection<User> users; try { users = getGlobalContext().getUserManager().getAllUsers(); } catch (UserFileException e) { out.add("Error processing userfiles"); return out; } String type = "MONTHUP"; boolean allow = false; String exempt[] = _exemptGroups.split(" "); ArrayList<User> filteredusers = new ArrayList<User>(); for (User fuser : users) { allow = true; for (int i = 0; i < exempt.length; i++) { if (fuser.isMemberOf(exempt[i])) allow = false; } if (allow && !fuser.isDeleted()) filteredusers.add(fuser); } Collections.sort(filteredusers, new UserComparator(type)); int pos = filteredusers.indexOf(user); env.add("user", user.getName()); env.add("group", user.getGroup()); env.add("mnup", Bytes.formatBytes(user.getUploadedBytesMonth())); env.add("upfilesmonth", "" + user.getUploadedFilesMonth()); env.add("mnrateup", TransferStatistics.getUpRate(user,Trial.PERIOD_MONTHLY)); if (pos == 0) { out.add(ReplacerUtils.jprintf("rank.ontop", env, Rank.class)); } else { User prevUser = filteredusers.get(pos-1); env.add("pos", ""+(pos+1)); env.add("toup", Bytes.formatBytes( prevUser.getUploadedBytesMonth() - user.getUploadedBytesMonth())); env.add("puser", prevUser.getName()); env.add("pgroup", prevUser.getGroup()); out.add(ReplacerUtils.jprintf("rank.losing", env, Rank.class)); } return out; } public ArrayList<String> doTopRank(String args, MessageCommand msgc) { ArrayList<String> out = new ArrayList<String>(); ReplacerEnvironment env = new ReplacerEnvironment(SiteBot.GLOBAL_ENV); env.add("ircnick", msgc.getSource().getNick()); int count = 10; try { count = Integer.parseInt(args); } catch (NumberFormatException e1) { } Collection<User> users; try { users = getGlobalContext().getUserManager().getAllUsers(); } catch (UserFileException e) { out.add("Error processing userfiles"); return out; } String type = "MONTHUP"; boolean allow = false; String exempt[] = _exemptGroups.split(" "); ArrayList<User> filteredusers = new ArrayList<User>(); for (User fuser : users) { allow = true; for (int i = 0; i < exempt.length; i++) { if (fuser.isMemberOf(exempt[i])) allow = false; } if (allow && !fuser.isDeleted()) filteredusers.add(fuser); } Collections.sort(filteredusers, new UserComparator(type)); for (int pos = 0; pos < filteredusers.size(); pos++) { if (pos >= count) break; User user = filteredusers.get(pos); env.add("user", user.getName()); env.add("group", user.getGroup()); env.add("mnup", Bytes.formatBytes(user.getUploadedBytesMonth())); env.add("upfilesmonth", "" + user.getUploadedFilesMonth()); env.add("mnrateup", TransferStatistics.getUpRate(user,Trial.PERIOD_MONTHLY)); if (pos == 0) { out.add(ReplacerUtils.jprintf("rank.ontop", env, Rank.class)); } else if (pos > 0) { User prevUser = filteredusers.get(pos-1); env.add("pos", ""+(pos+1)); env.add("toup", Bytes.formatBytes( prevUser.getUploadedBytesMonth() - user.getUploadedBytesMonth())); env.add("puser", prevUser.getName()); env.add("pgroup", prevUser.getGroup()); out.add(ReplacerUtils.jprintf("rank.losing", env, Rank.class)); } else { env.add("user", args); out.add(ReplacerUtils.jprintf("rank.error", env, Rank.class)); return out; } } return out; } }
true
true
public ArrayList<String> doRank(String args, MessageCommand msgc) { ArrayList<String> out = new ArrayList<String>(); ReplacerEnvironment env = new ReplacerEnvironment(SiteBot.GLOBAL_ENV); env.add("ircnick", msgc.getSource().getNick()); FullNick fn = msgc.getSource(); String ident = fn.getNick() + "!" + fn.getUser() + "@" + fn.getHost(); User user; if (args.equals("")) { try { user = getGlobalContext().getUserManager().getUserByIdent(ident); } catch (Exception e) { logger.warn("Could not identify " + ident); out.add(ReplacerUtils.jprintf("ident.noident", env, SiteBot.class)); return out; } } else { try { user = getGlobalContext().getUserManager().getUserByName(args); } catch (Exception e) { logger.error(args + " is not a vlid username", e); env.add("user", args); out.add(ReplacerUtils.jprintf("rank.error", env, Rank.class)); return out; } } StringTokenizer st = new StringTokenizer(_exemptGroups); while (st.hasMoreTokens()) { if (user.isMemberOf(st.nextToken())) { env.add("eusr", user.getName()); env.add("egrp", user.getGroup()); out.add(ReplacerUtils.jprintf("rank.exempt", env, Rank.class)); return out; } } Collection<User> users; try { users = getGlobalContext().getUserManager().getAllUsers(); } catch (UserFileException e) { out.add("Error processing userfiles"); return out; } String type = "MONTHUP"; boolean allow = false; String exempt[] = _exemptGroups.split(" "); ArrayList<User> filteredusers = new ArrayList<User>(); for (User fuser : users) { allow = true; for (int i = 0; i < exempt.length; i++) { if (fuser.isMemberOf(exempt[i])) allow = false; } if (allow && !fuser.isDeleted()) filteredusers.add(fuser); } Collections.sort(filteredusers, new UserComparator(type)); int pos = filteredusers.indexOf(user); env.add("user", user.getName()); env.add("group", user.getGroup()); env.add("mnup", Bytes.formatBytes(user.getUploadedBytesMonth())); env.add("upfilesmonth", "" + user.getUploadedFilesMonth()); env.add("mnrateup", TransferStatistics.getUpRate(user,Trial.PERIOD_MONTHLY)); if (pos == 0) { out.add(ReplacerUtils.jprintf("rank.ontop", env, Rank.class)); } else { User prevUser = filteredusers.get(pos-1); env.add("pos", ""+(pos+1)); env.add("toup", Bytes.formatBytes( prevUser.getUploadedBytesMonth() - user.getUploadedBytesMonth())); env.add("puser", prevUser.getName()); env.add("pgroup", prevUser.getGroup()); out.add(ReplacerUtils.jprintf("rank.losing", env, Rank.class)); } return out; }
public ArrayList<String> doRank(String args, MessageCommand msgc) { ArrayList<String> out = new ArrayList<String>(); ReplacerEnvironment env = new ReplacerEnvironment(SiteBot.GLOBAL_ENV); env.add("ircnick", msgc.getSource().getNick()); FullNick fn = msgc.getSource(); String ident = fn.getNick() + "!" + fn.getUser() + "@" + fn.getHost(); User user; if (args.equals("")) { try { user = getGlobalContext().getUserManager().getUserByIdent(ident); } catch (Exception e) { logger.warn("Could not identify " + ident); out.add(ReplacerUtils.jprintf("ident.noident", env, SiteBot.class)); return out; } } else { try { user = getGlobalContext().getUserManager().getUserByName(args); } catch (Exception e) { logger.error(args + " is not a valid username", e); env.add("user", args); out.add(ReplacerUtils.jprintf("rank.error", env, Rank.class)); return out; } } StringTokenizer st = new StringTokenizer(_exemptGroups); while (st.hasMoreTokens()) { if (user.isMemberOf(st.nextToken())) { env.add("eusr", user.getName()); env.add("egrp", user.getGroup()); out.add(ReplacerUtils.jprintf("rank.exempt", env, Rank.class)); return out; } } Collection<User> users; try { users = getGlobalContext().getUserManager().getAllUsers(); } catch (UserFileException e) { out.add("Error processing userfiles"); return out; } String type = "MONTHUP"; boolean allow = false; String exempt[] = _exemptGroups.split(" "); ArrayList<User> filteredusers = new ArrayList<User>(); for (User fuser : users) { allow = true; for (int i = 0; i < exempt.length; i++) { if (fuser.isMemberOf(exempt[i])) allow = false; } if (allow && !fuser.isDeleted()) filteredusers.add(fuser); } Collections.sort(filteredusers, new UserComparator(type)); int pos = filteredusers.indexOf(user); env.add("user", user.getName()); env.add("group", user.getGroup()); env.add("mnup", Bytes.formatBytes(user.getUploadedBytesMonth())); env.add("upfilesmonth", "" + user.getUploadedFilesMonth()); env.add("mnrateup", TransferStatistics.getUpRate(user,Trial.PERIOD_MONTHLY)); if (pos == 0) { out.add(ReplacerUtils.jprintf("rank.ontop", env, Rank.class)); } else { User prevUser = filteredusers.get(pos-1); env.add("pos", ""+(pos+1)); env.add("toup", Bytes.formatBytes( prevUser.getUploadedBytesMonth() - user.getUploadedBytesMonth())); env.add("puser", prevUser.getName()); env.add("pgroup", prevUser.getGroup()); out.add(ReplacerUtils.jprintf("rank.losing", env, Rank.class)); } return out; }
diff --git a/src/main/java/com/alecgorge/minecraft/jsonapi/packets/Packet0x47HttpGetPacket.java b/src/main/java/com/alecgorge/minecraft/jsonapi/packets/Packet0x47HttpGetPacket.java index b7b6d21..1e68d03 100644 --- a/src/main/java/com/alecgorge/minecraft/jsonapi/packets/Packet0x47HttpGetPacket.java +++ b/src/main/java/com/alecgorge/minecraft/jsonapi/packets/Packet0x47HttpGetPacket.java @@ -1,187 +1,187 @@ package com.alecgorge.minecraft.jsonapi.packets; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.InputStream; import java.io.OutputStream; import java.io.SequenceInputStream; import java.net.Socket; import java.util.Properties; import net.minecraft.server.v1_6_R2.Connection; import net.minecraft.server.v1_6_R2.Packet71Weather; import net.minecraft.server.v1_6_R2.PendingConnection; import com.alecgorge.minecraft.jsonapi.JSONAPI; import com.alecgorge.minecraft.jsonapi.JSONServer; import com.alecgorge.minecraft.jsonapi.NanoHTTPD; import com.alecgorge.minecraft.jsonapi.streams.StreamingResponse; public class Packet0x47HttpGetPacket extends Packet71Weather { ByteArrayInputStream payload = null; boolean isHTTP = true; boolean isStream = false; boolean isWebsocket = false; boolean isKeepAlive = false; boolean isGET = true; String streamLine = null; RawPacket rawPacket; boolean shouldDebug = false; void dbug(Object objects) { if(shouldDebug) { System.out.println(objects); } } public void a(DataInput inp) { try { // System.out.println("attempting to read packet"); StringBuilder builder = new StringBuilder(); final byte next = inp.readByte(); dbug("next: " + (char)next); if (next == 'E') { rawPacket = new RawPacket(inp); rawPacket.resetTimeout(); JSONServer jsonServer = JSONAPI.instance.jsonServer; ByteArrayInputStream prefix = new ByteArrayInputStream(new byte[] { 'G', 'E' }); jsonServer.new HTTPSession(new SequenceInputStream(prefix, rawPacket.getInputStream()), rawPacket.getOutputStream(), rawPacket.getAddr(), true); } else if (next == 'S') { isHTTP = false; isStream = true; if (inp.readByte() == 'A') { dbug("Keep Alive!"); isKeepAlive = true; inp.readLine(); return; } dbug("Stream!"); streamLine = inp.readLine(); dbug(streamLine); return; } else { isGET = false; ByteArrayInputStream prefix = new ByteArrayInputStream(new byte[] {'G', next}); super.a(new DataInputStream(new SequenceInputStream(prefix, (DataInputStream)inp))); return; } payload = new ByteArrayInputStream(builder.toString().getBytes()); } catch (Exception e) { e.printStackTrace(); } } public void a(DataOutput out) { if(!isGET) { super.a(out); } } public void handle(Connection net) { - if(!isGET || !isHTTP) { + if(!isGET) { super.handle(net); return; } final PendingConnection loginHandler = (PendingConnection) net; try { loginHandler.getSocket().setTcpNoDelay(true); RawPacket.resetTimeout(loginHandler); if (isKeepAlive) { return; } if (isStream) { final Socket clientSocket = loginHandler.getSocket(); (new Thread(new Runnable() { @Override public void run() { JSONServer jsonServer = JSONAPI.instance.getJSONServer(); String[] split = streamLine.split("\\?", 2); NanoHTTPD.Response r = null; if (split.length < 2) { r = jsonServer.new Response(NanoHTTPD.HTTP_NOTFOUND, NanoHTTPD.MIME_JSON, jsonServer.returnAPIError("", "Incorrect. Socket requests are in the format PAGE?ARGUMENTS. For example, /api/subscribe?source=....").toJSONString()); } else { Properties header = new Properties(); NanoHTTPD.decodeParms(split[1], header); Properties p = new Properties(); p.put("X-REMOTE-ADDR", clientSocket.getInetAddress().getHostAddress()); r = jsonServer.serve(split[0], "GET", p, header); } if (r.data instanceof StreamingResponse) { final StreamingResponse s = (StreamingResponse) r.data; String line = ""; boolean continueSending = true; while ((line = s.nextLine()) != null && continueSending) { RawPacket.sendPacket(new PacketStringResponse(line + "\r\n", false), loginHandler, isHTTP); RawPacket.resetTimeout(loginHandler); continueSending = !clientSocket.isClosed(); } RawPacket.sendPacket(new PacketStringResponse("\r\n", true), loginHandler, isHTTP); try { ((StreamingResponse)r.data).close(); Thread.currentThread().interrupt(); Thread.currentThread().join(); } catch (Exception e) { // TODO Auto-generated catch block // e.printStackTrace(); } } else { InputStream res = r.data; if(res == null) { res = new ByteArrayInputStream(r.bytes); } RawPacket.sendPacket(new PacketStringResponse(res, false), loginHandler, isHTTP); } } })).start(); return; } ByteArrayOutputStream oup = new ByteArrayOutputStream(); JSONAPI.instance.getJSONServer().new HTTPSession(payload, oup, loginHandler.getSocket().getInetAddress(), new Lambda<Void, OutputStream>() { public Void execute(OutputStream x) { try { ByteArrayOutputStream o = (ByteArrayOutputStream) x; ByteArrayInputStream inp = new ByteArrayInputStream(o.toByteArray()); PacketStringResponse packet = new PacketStringResponse(inp, true); RawPacket.sendPacket(packet, loginHandler, isHTTP); } catch (Exception e) { e.printStackTrace(); } return null; } }); } catch (Exception e1) { e1.printStackTrace(); } } public int a() { return 0; } }
true
true
public void handle(Connection net) { if(!isGET || !isHTTP) { super.handle(net); return; } final PendingConnection loginHandler = (PendingConnection) net; try { loginHandler.getSocket().setTcpNoDelay(true); RawPacket.resetTimeout(loginHandler); if (isKeepAlive) { return; } if (isStream) { final Socket clientSocket = loginHandler.getSocket(); (new Thread(new Runnable() { @Override public void run() { JSONServer jsonServer = JSONAPI.instance.getJSONServer(); String[] split = streamLine.split("\\?", 2); NanoHTTPD.Response r = null; if (split.length < 2) { r = jsonServer.new Response(NanoHTTPD.HTTP_NOTFOUND, NanoHTTPD.MIME_JSON, jsonServer.returnAPIError("", "Incorrect. Socket requests are in the format PAGE?ARGUMENTS. For example, /api/subscribe?source=....").toJSONString()); } else { Properties header = new Properties(); NanoHTTPD.decodeParms(split[1], header); Properties p = new Properties(); p.put("X-REMOTE-ADDR", clientSocket.getInetAddress().getHostAddress()); r = jsonServer.serve(split[0], "GET", p, header); } if (r.data instanceof StreamingResponse) { final StreamingResponse s = (StreamingResponse) r.data; String line = ""; boolean continueSending = true; while ((line = s.nextLine()) != null && continueSending) { RawPacket.sendPacket(new PacketStringResponse(line + "\r\n", false), loginHandler, isHTTP); RawPacket.resetTimeout(loginHandler); continueSending = !clientSocket.isClosed(); } RawPacket.sendPacket(new PacketStringResponse("\r\n", true), loginHandler, isHTTP); try { ((StreamingResponse)r.data).close(); Thread.currentThread().interrupt(); Thread.currentThread().join(); } catch (Exception e) { // TODO Auto-generated catch block // e.printStackTrace(); } } else { InputStream res = r.data; if(res == null) { res = new ByteArrayInputStream(r.bytes); } RawPacket.sendPacket(new PacketStringResponse(res, false), loginHandler, isHTTP); } } })).start(); return; } ByteArrayOutputStream oup = new ByteArrayOutputStream(); JSONAPI.instance.getJSONServer().new HTTPSession(payload, oup, loginHandler.getSocket().getInetAddress(), new Lambda<Void, OutputStream>() { public Void execute(OutputStream x) { try { ByteArrayOutputStream o = (ByteArrayOutputStream) x; ByteArrayInputStream inp = new ByteArrayInputStream(o.toByteArray()); PacketStringResponse packet = new PacketStringResponse(inp, true); RawPacket.sendPacket(packet, loginHandler, isHTTP); } catch (Exception e) { e.printStackTrace(); } return null; } }); } catch (Exception e1) { e1.printStackTrace(); } }
public void handle(Connection net) { if(!isGET) { super.handle(net); return; } final PendingConnection loginHandler = (PendingConnection) net; try { loginHandler.getSocket().setTcpNoDelay(true); RawPacket.resetTimeout(loginHandler); if (isKeepAlive) { return; } if (isStream) { final Socket clientSocket = loginHandler.getSocket(); (new Thread(new Runnable() { @Override public void run() { JSONServer jsonServer = JSONAPI.instance.getJSONServer(); String[] split = streamLine.split("\\?", 2); NanoHTTPD.Response r = null; if (split.length < 2) { r = jsonServer.new Response(NanoHTTPD.HTTP_NOTFOUND, NanoHTTPD.MIME_JSON, jsonServer.returnAPIError("", "Incorrect. Socket requests are in the format PAGE?ARGUMENTS. For example, /api/subscribe?source=....").toJSONString()); } else { Properties header = new Properties(); NanoHTTPD.decodeParms(split[1], header); Properties p = new Properties(); p.put("X-REMOTE-ADDR", clientSocket.getInetAddress().getHostAddress()); r = jsonServer.serve(split[0], "GET", p, header); } if (r.data instanceof StreamingResponse) { final StreamingResponse s = (StreamingResponse) r.data; String line = ""; boolean continueSending = true; while ((line = s.nextLine()) != null && continueSending) { RawPacket.sendPacket(new PacketStringResponse(line + "\r\n", false), loginHandler, isHTTP); RawPacket.resetTimeout(loginHandler); continueSending = !clientSocket.isClosed(); } RawPacket.sendPacket(new PacketStringResponse("\r\n", true), loginHandler, isHTTP); try { ((StreamingResponse)r.data).close(); Thread.currentThread().interrupt(); Thread.currentThread().join(); } catch (Exception e) { // TODO Auto-generated catch block // e.printStackTrace(); } } else { InputStream res = r.data; if(res == null) { res = new ByteArrayInputStream(r.bytes); } RawPacket.sendPacket(new PacketStringResponse(res, false), loginHandler, isHTTP); } } })).start(); return; } ByteArrayOutputStream oup = new ByteArrayOutputStream(); JSONAPI.instance.getJSONServer().new HTTPSession(payload, oup, loginHandler.getSocket().getInetAddress(), new Lambda<Void, OutputStream>() { public Void execute(OutputStream x) { try { ByteArrayOutputStream o = (ByteArrayOutputStream) x; ByteArrayInputStream inp = new ByteArrayInputStream(o.toByteArray()); PacketStringResponse packet = new PacketStringResponse(inp, true); RawPacket.sendPacket(packet, loginHandler, isHTTP); } catch (Exception e) { e.printStackTrace(); } return null; } }); } catch (Exception e1) { e1.printStackTrace(); } }
diff --git a/JsTestDriver/src/com/google/jstestdriver/browser/BrowserControl.java b/JsTestDriver/src/com/google/jstestdriver/browser/BrowserControl.java index f0023bbb..99f9d00f 100644 --- a/JsTestDriver/src/com/google/jstestdriver/browser/BrowserControl.java +++ b/JsTestDriver/src/com/google/jstestdriver/browser/BrowserControl.java @@ -1,163 +1,163 @@ /* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.jstestdriver.browser; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import com.google.inject.name.Named; import com.google.jstestdriver.BrowserInfo; import com.google.jstestdriver.JsTestDriverClient; import com.google.jstestdriver.model.JstdTestCase; import com.google.jstestdriver.server.handlers.pages.SlavePageRequest; import com.google.jstestdriver.util.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.concurrent.TimeUnit; /** * Class that handles the * * @author Cory Smith ([email protected]) */ public class BrowserControl { public static interface BrowserControlFactory { public BrowserControl create(BrowserRunner runner, String serverAddress, List<JstdTestCase> testCases); } private final Function<JstdTestCase, String> TESTCASE_TO_ID = new Function<JstdTestCase, String>() { @Override public String apply(JstdTestCase testCase) { return testCase.getId(); } }; private static final String CAPTURE_URL = String.format("%%s/capture/%s/%%s/%s/%%s/%s/%%s/", SlavePageRequest.ID, SlavePageRequest.TIMEOUT, SlavePageRequest.UPLOAD_SIZE); private static final String CAPTURE_URL_WITH_TESTCASE_IDS = String.format("%%s/capture/%s/%%s/%s/%%s/%s/%%s/%s/%%s", SlavePageRequest.ID, SlavePageRequest.TIMEOUT, SlavePageRequest.UPLOAD_SIZE, SlavePageRequest.TESTCASE_ID); private static final Logger logger = LoggerFactory.getLogger(BrowserControl.class); private final BrowserRunner runner; private final String serverAddress; private final StopWatch stopWatch; private final JsTestDriverClient client; private final List<JstdTestCase> testCases; private final long browserTimeout; /** * @param runner * @param serverAddress * @param stopWatch * @param client * @param testCases * @param browserTimeout TODO */ @Inject public BrowserControl( @Assisted BrowserRunner runner, @Assisted String serverAddress, StopWatch stopWatch, JsTestDriverClient client, @Assisted List<JstdTestCase> testCases, @Named("browserTimeout") long browserTimeout) { this.runner = runner; this.serverAddress = serverAddress; this.stopWatch = stopWatch; this.client = client; this.testCases = testCases; this.browserTimeout = browserTimeout; } /** Slaves a new browser window with the provided id. */ public String captureBrowser(String browserId) throws InterruptedException { try { stopWatch.start("browser start %s", browserId); final String url; if (testCases.isEmpty()) { url = String.format(CAPTURE_URL, serverAddress, browserId, Math.max(runner.getHeartbeatTimeout(), browserTimeout), runner.getUploadSize()); } else { url = String.format(CAPTURE_URL_WITH_TESTCASE_IDS, serverAddress, browserId, Math.max(runner.getHeartbeatTimeout(), browserTimeout), runner.getUploadSize(), - Joiner.on(",").join(Lists.transform(testCases, TESTCASE_TO_ID))); + testCases.get(0).getId()); } runner.startBrowser(url); long timeOut = TimeUnit.MILLISECONDS.convert(Math.max(runner.getTimeout(), browserTimeout), TimeUnit.SECONDS); long start = System.currentTimeMillis(); // TODO(corysmith): replace this with a stream from the client on browser // updates. try { stopWatch.start("Capturing browser", browserId); while (!isBrowserCaptured(browserId, client)) { Thread.sleep(50); if (System.currentTimeMillis() - start > timeOut) { throw new RuntimeException("Could not start browser " + runner + " in " + runner.getTimeout()); } } } finally { stopWatch.stop("Capturing browser", browserId); } logger.debug("Browser {} started with id {}", runner, browserId); return browserId; } finally { stopWatch.stop("browser start %s", browserId); } } /** Stop a browser window. */ public void stopBrowser() { stopWatch.start("browser stop %s", runner); runner.stopBrowser(); stopWatch.stop("browser stop %s", runner); } public boolean isBrowserCaptured(String browserId, JsTestDriverClient client) { for (BrowserInfo browserInfo : client.listBrowsers()) { if (browserId.equals(String.valueOf(browserInfo.getId())) && browserInfo.serverReceivedHeartbeat() && browserInfo.browserReady()) { logger.debug("Started {}", browserInfo); return true; } } return false; } }
true
true
public String captureBrowser(String browserId) throws InterruptedException { try { stopWatch.start("browser start %s", browserId); final String url; if (testCases.isEmpty()) { url = String.format(CAPTURE_URL, serverAddress, browserId, Math.max(runner.getHeartbeatTimeout(), browserTimeout), runner.getUploadSize()); } else { url = String.format(CAPTURE_URL_WITH_TESTCASE_IDS, serverAddress, browserId, Math.max(runner.getHeartbeatTimeout(), browserTimeout), runner.getUploadSize(), Joiner.on(",").join(Lists.transform(testCases, TESTCASE_TO_ID))); } runner.startBrowser(url); long timeOut = TimeUnit.MILLISECONDS.convert(Math.max(runner.getTimeout(), browserTimeout), TimeUnit.SECONDS); long start = System.currentTimeMillis(); // TODO(corysmith): replace this with a stream from the client on browser // updates. try { stopWatch.start("Capturing browser", browserId); while (!isBrowserCaptured(browserId, client)) { Thread.sleep(50); if (System.currentTimeMillis() - start > timeOut) { throw new RuntimeException("Could not start browser " + runner + " in " + runner.getTimeout()); } } } finally { stopWatch.stop("Capturing browser", browserId); } logger.debug("Browser {} started with id {}", runner, browserId); return browserId; } finally { stopWatch.stop("browser start %s", browserId); } }
public String captureBrowser(String browserId) throws InterruptedException { try { stopWatch.start("browser start %s", browserId); final String url; if (testCases.isEmpty()) { url = String.format(CAPTURE_URL, serverAddress, browserId, Math.max(runner.getHeartbeatTimeout(), browserTimeout), runner.getUploadSize()); } else { url = String.format(CAPTURE_URL_WITH_TESTCASE_IDS, serverAddress, browserId, Math.max(runner.getHeartbeatTimeout(), browserTimeout), runner.getUploadSize(), testCases.get(0).getId()); } runner.startBrowser(url); long timeOut = TimeUnit.MILLISECONDS.convert(Math.max(runner.getTimeout(), browserTimeout), TimeUnit.SECONDS); long start = System.currentTimeMillis(); // TODO(corysmith): replace this with a stream from the client on browser // updates. try { stopWatch.start("Capturing browser", browserId); while (!isBrowserCaptured(browserId, client)) { Thread.sleep(50); if (System.currentTimeMillis() - start > timeOut) { throw new RuntimeException("Could not start browser " + runner + " in " + runner.getTimeout()); } } } finally { stopWatch.stop("Capturing browser", browserId); } logger.debug("Browser {} started with id {}", runner, browserId); return browserId; } finally { stopWatch.stop("browser start %s", browserId); } }
diff --git a/achartengine/src/org/achartengine/chart/TimeChart.java b/achartengine/src/org/achartengine/chart/TimeChart.java index 2fbf83d..864e5f8 100644 --- a/achartengine/src/org/achartengine/chart/TimeChart.java +++ b/achartengine/src/org/achartengine/chart/TimeChart.java @@ -1,208 +1,211 @@ /** * Copyright (C) 2009 - 2012 SC 4ViewSoft SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.achartengine.chart; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.achartengine.model.XYMultipleSeriesDataset; import org.achartengine.renderer.XYMultipleSeriesRenderer; import android.graphics.Canvas; import android.graphics.Paint; /** * The time chart rendering class. */ public class TimeChart extends LineChart { /** The constant to identify this chart type. */ public static final String TYPE = "Time"; /** The number of milliseconds in a day. */ public static final long DAY = 24 * 60 * 60 * 1000; /** The date format pattern to be used in formatting the X axis labels. */ private String mDateFormat; /** If X axis value selection algorithm to be used. */ private boolean mXAxisSmart = true; /** The starting point for labels. */ private Double mStartPoint; TimeChart() { } /** * Builds a new time chart instance. * * @param dataset the multiple series dataset * @param renderer the multiple series renderer */ public TimeChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer) { super(dataset, renderer); } /** * Returns the date format pattern to be used for formatting the X axis * labels. * * @return the date format pattern for the X axis labels */ public String getDateFormat() { return mDateFormat; } /** * Sets the date format pattern to be used for formatting the X axis labels. * * @param format the date format pattern for the X axis labels. If null, an * appropriate default format will be used. */ public void setDateFormat(String format) { mDateFormat = format; } /** * If X axis smart values to be used. * * @return if smart values to be used */ public boolean isXAxisSmart() { return mXAxisSmart; } /** * Sets if X axis smart values to be used. * * @param smart smart values to be used */ public void setXAxisSmart(boolean smart) { mXAxisSmart = smart; } /** * The graphical representation of the labels on the X axis. * * @param xLabels the X labels values * @param xTextLabelLocations the X text label locations * @param canvas the canvas to paint to * @param paint the paint to be used for drawing * @param left the left value of the labels area * @param top the top value of the labels area * @param bottom the bottom value of the labels area * @param xPixelsPerUnit the amount of pixels per one unit in the chart labels * @param minX the minimum value on the X axis in the chart * @param maxX the maximum value on the X axis in the chart */ @Override protected void drawXLabels(List<Double> xLabels, Double[] xTextLabelLocations, Canvas canvas, Paint paint, int left, int top, int bottom, double xPixelsPerUnit, double minX, double maxX) { int length = xLabels.size(); if (length > 0) { boolean showLabels = mRenderer.isShowLabels(); boolean showGridY = mRenderer.isShowGridY(); DateFormat format = getDateFormat(xLabels.get(0), xLabels.get(length - 1)); for (int i = 0; i < length; i++) { long label = Math.round(xLabels.get(i)); float xLabel = (float) (left + xPixelsPerUnit * (label - minX)); if (showLabels) { paint.setColor(mRenderer.getXLabelsColor()); canvas .drawLine(xLabel, bottom, xLabel, bottom + mRenderer.getLabelsTextSize() / 3, paint); drawText(canvas, format.format(new Date(label)), xLabel, bottom + mRenderer.getLabelsTextSize() * 4 / 3, paint, mRenderer.getXLabelsAngle()); } if (showGridY) { paint.setColor(mRenderer.getGridColor()); canvas.drawLine(xLabel, bottom, xLabel, top, paint); } } } drawXTextLabels(xTextLabelLocations, canvas, paint, true, left, top, bottom, xPixelsPerUnit, minX, maxX); } /** * Returns the date format pattern to be used, based on the date range. * * @param start the start date in milliseconds * @param end the end date in milliseconds * @return the date format */ private DateFormat getDateFormat(double start, double end) { if (mDateFormat != null) { SimpleDateFormat format = null; try { format = new SimpleDateFormat(mDateFormat); return format; } catch (Exception e) { // do nothing here } } DateFormat format = SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM); double diff = end - start; if (diff > DAY && diff < 5 * DAY) { format = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); } else if (diff < DAY) { format = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM); } return format; } /** * Returns the chart type identifier. * * @return the chart type */ public String getChartType() { return TYPE; } protected List<Double> getXLabels(double min, double max, int count) { if (!mXAxisSmart) { return super.getXLabels(min, max, count); } if (mStartPoint == null) { mStartPoint = min - (min % DAY) + DAY + new Date(Math.round(min)).getTimezoneOffset() * 60 * 1000; } if (count > 25) { count = 25; } + final List<Double> result = new ArrayList<Double>(); final double cycleMath = (max - min) / count; + if (cycleMath <= 0) { + return result; + } double cycle = DAY; if (cycleMath <= DAY) { while (cycleMath < cycle / 2) { cycle = cycle / 2; } } else { while (cycleMath > cycle) { cycle = cycle * 2; } } - final List<Double> result = new ArrayList<Double>(); double val = mStartPoint - Math.floor((mStartPoint - min) / cycle) * cycle; int i = 0; while (val < max && i++ <= count) { result.add(val); val += cycle; } return result; } }
false
true
protected List<Double> getXLabels(double min, double max, int count) { if (!mXAxisSmart) { return super.getXLabels(min, max, count); } if (mStartPoint == null) { mStartPoint = min - (min % DAY) + DAY + new Date(Math.round(min)).getTimezoneOffset() * 60 * 1000; } if (count > 25) { count = 25; } final double cycleMath = (max - min) / count; double cycle = DAY; if (cycleMath <= DAY) { while (cycleMath < cycle / 2) { cycle = cycle / 2; } } else { while (cycleMath > cycle) { cycle = cycle * 2; } } final List<Double> result = new ArrayList<Double>(); double val = mStartPoint - Math.floor((mStartPoint - min) / cycle) * cycle; int i = 0; while (val < max && i++ <= count) { result.add(val); val += cycle; } return result; }
protected List<Double> getXLabels(double min, double max, int count) { if (!mXAxisSmart) { return super.getXLabels(min, max, count); } if (mStartPoint == null) { mStartPoint = min - (min % DAY) + DAY + new Date(Math.round(min)).getTimezoneOffset() * 60 * 1000; } if (count > 25) { count = 25; } final List<Double> result = new ArrayList<Double>(); final double cycleMath = (max - min) / count; if (cycleMath <= 0) { return result; } double cycle = DAY; if (cycleMath <= DAY) { while (cycleMath < cycle / 2) { cycle = cycle / 2; } } else { while (cycleMath > cycle) { cycle = cycle * 2; } } double val = mStartPoint - Math.floor((mStartPoint - min) / cycle) * cycle; int i = 0; while (val < max && i++ <= count) { result.add(val); val += cycle; } return result; }
diff --git a/Yamba-8/src/com/marakana/yamba8/YambaWidget.java b/Yamba-8/src/com/marakana/yamba8/YambaWidget.java index 29f45ab..7949cc6 100644 --- a/Yamba-8/src/com/marakana/yamba8/YambaWidget.java +++ b/Yamba-8/src/com/marakana/yamba8/YambaWidget.java @@ -1,60 +1,60 @@ package com.marakana.yamba8; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.text.format.DateUtils; import android.util.Log; import android.widget.RemoteViews; public class YambaWidget extends AppWidgetProvider { // <1> private static final String TAG = YambaWidget.class.getSimpleName(); @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // <2> Cursor c = context.getContentResolver().query(StatusProvider.CONTENT_URI, - null, null, null, null); // <3> + null, null, null, StatusData.C_CREATED_AT + " DESC"); // <3> try { if (c.moveToFirst()) { // <4> CharSequence user = c.getString(c.getColumnIndex(StatusData.C_USER)); // <5> CharSequence createdAt = DateUtils.getRelativeTimeSpanString(context, c .getLong(c.getColumnIndex(StatusData.C_CREATED_AT))); CharSequence message = c.getString(c.getColumnIndex(StatusData.C_TEXT)); // Loop through all instances of this widget for (int appWidgetId : appWidgetIds) { // <6> Log.d(TAG, "Updating widget " + appWidgetId); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.yamba_widget); // <7> views.setTextViewText(R.id.textUser, user); // <8> views.setTextViewText(R.id.textCreatedAt, createdAt); views.setTextViewText(R.id.textText, message); views.setOnClickPendingIntent(R.id.yamba_icon, PendingIntent .getActivity(context, 0, new Intent(context, TimelineActivity.class), 0)); appWidgetManager.updateAppWidget(appWidgetId, views); // <9> } } else { Log.d(TAG, "No data to update"); } } finally { c.close(); // <10> } Log.d(TAG, "onUpdated"); } @Override public void onReceive(Context context, Intent intent) { // <11> super.onReceive(context, intent); if (intent.getAction().equals(UpdaterService.NEW_STATUS_INTENT)) { // <12> Log.d(TAG, "onReceived detected new status update"); AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); // <13> this.onUpdate(context, appWidgetManager, appWidgetManager .getAppWidgetIds(new ComponentName(context, YambaWidget.class))); // <14> } } }
true
true
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // <2> Cursor c = context.getContentResolver().query(StatusProvider.CONTENT_URI, null, null, null, null); // <3> try { if (c.moveToFirst()) { // <4> CharSequence user = c.getString(c.getColumnIndex(StatusData.C_USER)); // <5> CharSequence createdAt = DateUtils.getRelativeTimeSpanString(context, c .getLong(c.getColumnIndex(StatusData.C_CREATED_AT))); CharSequence message = c.getString(c.getColumnIndex(StatusData.C_TEXT)); // Loop through all instances of this widget for (int appWidgetId : appWidgetIds) { // <6> Log.d(TAG, "Updating widget " + appWidgetId); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.yamba_widget); // <7> views.setTextViewText(R.id.textUser, user); // <8> views.setTextViewText(R.id.textCreatedAt, createdAt); views.setTextViewText(R.id.textText, message); views.setOnClickPendingIntent(R.id.yamba_icon, PendingIntent .getActivity(context, 0, new Intent(context, TimelineActivity.class), 0)); appWidgetManager.updateAppWidget(appWidgetId, views); // <9> } } else { Log.d(TAG, "No data to update"); } } finally { c.close(); // <10> } Log.d(TAG, "onUpdated"); }
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // <2> Cursor c = context.getContentResolver().query(StatusProvider.CONTENT_URI, null, null, null, StatusData.C_CREATED_AT + " DESC"); // <3> try { if (c.moveToFirst()) { // <4> CharSequence user = c.getString(c.getColumnIndex(StatusData.C_USER)); // <5> CharSequence createdAt = DateUtils.getRelativeTimeSpanString(context, c .getLong(c.getColumnIndex(StatusData.C_CREATED_AT))); CharSequence message = c.getString(c.getColumnIndex(StatusData.C_TEXT)); // Loop through all instances of this widget for (int appWidgetId : appWidgetIds) { // <6> Log.d(TAG, "Updating widget " + appWidgetId); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.yamba_widget); // <7> views.setTextViewText(R.id.textUser, user); // <8> views.setTextViewText(R.id.textCreatedAt, createdAt); views.setTextViewText(R.id.textText, message); views.setOnClickPendingIntent(R.id.yamba_icon, PendingIntent .getActivity(context, 0, new Intent(context, TimelineActivity.class), 0)); appWidgetManager.updateAppWidget(appWidgetId, views); // <9> } } else { Log.d(TAG, "No data to update"); } } finally { c.close(); // <10> } Log.d(TAG, "onUpdated"); }
diff --git a/ini/trakem2/display/Treeline.java b/ini/trakem2/display/Treeline.java index 39e331b6..a3dc0acc 100644 --- a/ini/trakem2/display/Treeline.java +++ b/ini/trakem2/display/Treeline.java @@ -1,824 +1,824 @@ package ini.trakem2.display; import ij.measure.Calibration; import ij.gui.GenericDialog; import ini.trakem2.Project; import ini.trakem2.utils.IJError; import ini.trakem2.utils.Utils; import ini.trakem2.utils.M; import ini.trakem2.utils.ProjectToolbar; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.awt.Point; import java.awt.Choice; import java.awt.TextField; import java.awt.Color; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.KeyEvent; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; import java.util.ArrayList; import java.util.List; import java.util.Collection; import javax.vecmath.Color3f; import javax.vecmath.Point3f; import javax.vecmath.Tuple3f; import javax.vecmath.Vector3f; import javax.media.j3d.Transform3D; import javax.vecmath.AxisAngle4f; import java.awt.Polygon; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.Point2D; import java.awt.Composite; import java.awt.AlphaComposite; public class Treeline extends Tree<Float> { static protected float last_radius = -1; public Treeline(Project project, String title) { super(project, title); addToDatabase(); } /** Reconstruct from XML. */ public Treeline(final Project project, final long id, final HashMap<String,String> ht_attr, final HashMap<Displayable,String> ht_links) { super(project, id, ht_attr, ht_links); } /** For cloning purposes, does not call addToDatabase() */ public Treeline(final Project project, final long id, final String title, final float width, final float height, final float alpha, final boolean visible, final Color color, final boolean locked, final AffineTransform at) { super(project, id, title, width, height, alpha, visible, color, locked, at); } @Override public Tree<Float> newInstance() { return new Treeline(project, project.getLoader().getNextId(), title, width, height, alpha, visible, color, locked, at); } @Override public Node<Float> newNode(float lx, float ly, Layer la, Node<?> modelNode) { return new RadiusNode(lx, ly, la, null == modelNode ? 0 : ((RadiusNode)modelNode).r); } @Override public Node<Float> newNode(HashMap<String,String> ht_attr) { return new RadiusNode(ht_attr); } @Override public Treeline clone(final Project pr, final boolean copy_id) { final long nid = copy_id ? this.id : pr.getLoader().getNextId(); Treeline tline = new Treeline(pr, nid, title, width, height, alpha, visible, color, locked, at); tline.root = null == this.root ? null : this.root.clone(pr); tline.addToDatabase(); if (null != tline.root) tline.cacheSubtree(tline.root.getSubtreeNodes()); return tline; } @Override public void mousePressed(MouseEvent me, Layer la, int x_p, int y_p, double mag) { if (-1 == last_radius) { last_radius = 10 / (float)mag; } if (me.isShiftDown() && me.isAltDown() && !Utils.isControlDown(me)) { final Layer layer = Display.getFrontLayer(this.project); Node<Float> nd = findNodeNear(x_p, y_p, layer, mag); if (null == nd) { Utils.log("Can't adjust radius: found more than 1 node within visible area!"); return; } // So: only one node within visible area of the canvas: // Adjust the radius by shift+alt+drag float xp = x_p, yp = y_p; if (!this.at.isIdentity()) { final Point2D.Double po = inverseTransformPoint(x_p, y_p); xp = (int)po.x; yp = (int)po.y; } setActive(nd); nd.setData((float)Math.sqrt(Math.pow(xp - nd.x, 2) + Math.pow(yp - nd.y, 2))); repaint(true, la); setLastEdited(nd); return; } super.mousePressed(me, la, x_p, y_p, mag); } protected boolean requireAltDownToEditRadius() { return true; } @Override public void mouseDragged(MouseEvent me, Layer la, int x_p, int y_p, int x_d, int y_d, int x_d_old, int y_d_old) { if (null == getActive()) return; if (requireAltDownToEditRadius() && !me.isAltDown()) { super.mouseDragged(me, la, x_p, y_p, x_d, y_d, x_d_old, y_d_old); return; } if (me.isShiftDown() && !Utils.isControlDown(me)) { // transform to the local coordinates float xd = x_d, yd = y_d; if (!this.at.isIdentity()) { final Point2D.Double po = inverseTransformPoint(x_d, y_d); xd = (float)po.x; yd = (float)po.y; } Node<Float> nd = getActive(); float r = (float)Math.sqrt(Math.pow(xd - nd.x, 2) + Math.pow(yd - nd.y, 2)); nd.setData(r); last_radius = r; repaint(true, la); return; } super.mouseDragged(me, la, x_p, y_p, x_d, y_d, x_d_old, y_d_old); } @Override public void mouseReleased(MouseEvent me, Layer la, int x_p, int y_p, int x_d, int y_d, int x_r, int y_r) { if (null == getActive()) return; if (me.isShiftDown() && me.isAltDown() && !Utils.isControlDown(me)) { updateViewData(getActive()); return; } super.mouseReleased(me, la, x_p, y_p, x_d, y_d, x_r, y_r); } @Override public void mouseWheelMoved(MouseWheelEvent mwe) { final int modifiers = mwe.getModifiers(); if (0 == ( (MouseWheelEvent.SHIFT_MASK | MouseWheelEvent.ALT_MASK) ^ modifiers)) { Object source = mwe.getSource(); if (! (source instanceof DisplayCanvas)) return; DisplayCanvas dc = (DisplayCanvas)source; Layer la = dc.getDisplay().getLayer(); final int rotation = mwe.getWheelRotation(); final float magnification = (float)dc.getMagnification(); final Rectangle srcRect = dc.getSrcRect(); final float x = ((mwe.getX() / magnification) + srcRect.x); final float y = ((mwe.getY() / magnification) + srcRect.y); float inc = (rotation > 0 ? 1 : -1) * (1/magnification); if (null != adjustNodeRadius(inc, x, y, la, magnification)) { Display.repaint(this); mwe.consume(); return; } } super.mouseWheelMoved(mwe); } protected Node<Float> adjustNodeRadius(float inc, float x, float y, Layer layer, double magnification) { Node<Float> nearest = findNodeNear(x, y, layer, magnification); if (null == nearest) { Utils.log("Can't adjust radius: found more than 1 node within visible area!"); return null; } nearest.setData(nearest.getData() + inc); return nearest; } static public class RadiusNode extends Node<Float> { protected float r; public RadiusNode(final float lx, final float ly, final Layer la) { this(lx, ly, la, 0); } public RadiusNode(final float lx, final float ly, final Layer la, final float radius) { super(lx, ly, la); this.r = radius; } /** To reconstruct from XML, without a layer. */ public RadiusNode(final HashMap<String,String> attr) { super(attr); final String sr = (String)attr.get("r"); this.r = null == sr ? 0 : Float.parseFloat(sr); } public Node<Float> newInstance(final float lx, final float ly, final Layer layer) { return new RadiusNode(lx, ly, layer, 0); } /** Set the radius to a positive value. When zero or negative, it's set to zero. */ public final boolean setData(final Float radius) { this.r = radius > 0 ? radius : 0; return true; } public final Float getData() { return this.r; } public final Float getDataCopy() { return this.r; } @Override public boolean isRoughlyInside(final Rectangle localbox) { if (0 == this.r) { if (null == parent) { return localbox.contains((int)this.x, (int)this.y); } else { if (0 == parent.getData()) { // parent.getData() == ((RadiusNode)parent).r return localbox.intersectsLine(parent.x, parent.y, this.x, this.y); } else { return getSegment().intersects(localbox); } } } else { if (null == parent) { return localbox.contains((int)this.x, (int)this.y); } else { return getSegment().intersects(localbox); } } } private final Polygon getSegment() { final RadiusNode parent = (RadiusNode) this.parent; float vx = parent.x - this.x; float vy = parent.y - this.y; float len = (float) Math.sqrt(vx*vx + vy*vy); vx /= len; vy /= len; // perpendicular vector final float vx90 = -vy; final float vy90 = vx; final float vx270 = vy; final float vy270 = -vx; return new Polygon(new int[]{(int)(parent.x + vx90 * parent.r), (int)(parent.x + vx270 * parent.r), (int)(this.x + vx270 * this.r), (int)(this.x + vx90 * this.r)}, new int[]{(int)(parent.y + vy90 * parent.r), (int)(parent.y + vy270 * parent.r), (int)(this.y + vy270 * this.r), (int)(this.y + vy90 * this.r)}, 4); } /** Paint segments. Returns true if the edges have to be painted as well. */ @Override public boolean paintData(final Graphics2D g, final Layer active_layer, final boolean active, final Rectangle srcRect, final double magnification, final Collection<Node<Float>> to_paint, final Tree<Float> tree, final AffineTransform to_screen) { if (null == this.parent) return true; // doing it here for less total cost if (0 == this.r && 0 == parent.getData()) return true; // Two transformations, but it's only 4 points each and it's necessary final Polygon segment = getSegment(); if (!tree.at.createTransformedShape(segment).intersects(srcRect)) return false; final Shape shape = to_screen.createTransformedShape(segment); // Which color? if (active_layer == this.la) { g.setColor(null == this.color ? tree.getColor() : this.color); } else { if (active_layer.getZ() > this.la.getZ()) g.setColor(Color.red); else g.setColor(Color.blue); } final Composite c = g.getComposite(); final float alpha = tree.getAlpha(); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha > 0.4f ? 0.4f : alpha)); g.fill(shape); g.setComposite(c); g.draw(shape); // in Tree's composite mode (such as an alpha) return true; } /** Expects @param a in local coords. */ @Override public boolean intersects(final Area a) { if (0 == r) return a.contains(x, y); return M.intersects(a, new Area(new Ellipse2D.Float(x-r, y-r, r+r, r+r))); // TODO: not the getSegment() ? } @Override public void apply(final mpicbg.models.CoordinateTransform ct, final Area roi) { // store the point float ox = x, oy = y; // transform the point itself super.apply(ct, roi); // transform the radius: assume it's a point to its right if (0 != r) { float[] fp = new float[]{ox + r, oy}; ct.applyInPlace(fp); r = Math.abs(fp[0] - this.x); } } @Override public void apply(final VectorDataTransform vdt) { for (final VectorDataTransform.ROITransform rt : vdt.transforms) { // Apply only the first one that contains the point if (rt.roi.contains(x, y)) { // Store point float ox = x, oy = y; // Transform point float[] fp = new float[]{x, y}; rt.ct.applyInPlace(fp); x = fp[0]; y = fp[1]; // Transform the radius: assume it's a point to the right of the untransformed point if (0 != r) { fp[0] = ox + r; fp[1] = oy; rt.ct.applyInPlace(fp); r = Math.abs(fp[0] - this.x); } break; } } } @Override protected void transformData(final AffineTransform aff) { switch (aff.getType()) { case AffineTransform.TYPE_IDENTITY: case AffineTransform.TYPE_TRANSLATION: // Radius doesn't change return; default: // Scale the radius as appropriate final float[] fp = new float[]{x, y, x + r, y}; aff.transform(fp, 0, fp, 0, 2); r = (float)Math.sqrt(Math.pow(fp[2] - fp[0], 2) + Math.pow(fp[3] - fp[1], 2)); } } } static public void exportDTD(final StringBuilder sb_header, final HashSet<String> hs, final String indent) { Tree.exportDTD(sb_header, hs, indent); final String type = "t2_treeline"; if (hs.contains(type)) return; hs.add(type); sb_header.append(indent).append("<!ELEMENT t2_treeline (t2_node*,").append(Displayable.commonDTDChildren()).append(")>\n"); Displayable.exportDTD(type, sb_header, hs, indent); } /** Export the radius only if it is larger than zero. */ @Override protected boolean exportXMLNodeAttributes(final StringBuilder indent, final StringBuilder sb, final Node<Float> node) { if (node.getData() > 0) sb.append(" r=\"").append(node.getData()).append('\"'); return true; } @Override protected boolean exportXMLNodeData(final StringBuilder indent, final StringBuilder sb, final Node<Float> node) { return false; } /** Testing for performance, 100 iterations: * A: 3307 (current, with clearing of table on the fly) * B: 4613 (without clearing table) * C: 4012 (without point caching) * * Although in short runs (10 iterations) A can get very bad: * (first run of 10) * A: 664 * B: 611 * C: 196 * (second run of 10) * A: 286 * B: 314 * C: 513 <-- gets worse !? * * Differences are not so huge in any case. */ /* static final public void testMeshGenerationPerformance(int n_iterations) { // test 3D mesh generation Layer la = Display.getFrontLayer(); java.util.Random rnd = new java.util.Random(67779); Node root = new RadiusNode(rnd.nextFloat(), rnd.nextFloat(), la); Node parent = root; for (int i=0; i<10000; i++) { Node child = new RadiusNode(rnd.nextFloat(), rnd.nextFloat(), la); parent.add(child, Node.MAX_EDGE_CONFIDENCE); if (0 == i % 100) { // add a branch of 100 nodes Node pa = parent; for (int k = 0; k<100; k++) { Node ch = new RadiusNode(rnd.nextFloat(), rnd.nextFloat(), la); pa.add(ch, Node.MAX_EDGE_CONFIDENCE); pa = ch; } } parent = child; } final AffineTransform at = new AffineTransform(1, 0, 0, 1, 67, 134); final ArrayList list = new ArrayList(); final LinkedList<Node> todo = new LinkedList<Node>(); final float scale = 0.345f; final Calibration cal = la.getParent().getCalibration(); final float pixelWidthScaled = (float) cal.pixelWidth * scale; final float pixelHeightScaled = (float) cal.pixelHeight * scale; final int sign = cal.pixelDepth < 0 ? -1 : 1; final Map<Node,Point3f> points = new HashMap<Node,Point3f>(); // A few performance tests are needed: // 1 - if the map caching of points helps or recomputing every time is cheaper than lookup // 2 - if removing no-longer-needed points from the map helps lookup or overall slows down long t0 = System.currentTimeMillis(); for (int i=0; i<n_iterations; i++) { // A -- current method points.clear(); todo.clear(); todo.add(root); list.clear(); final float[] fps = new float[2]; boolean go = true; while (go) { final Node node = todo.removeFirst(); // Add children to todo list if any if (null != node.children) { for (final Node nd : node.children) todo.add(nd); } go = !todo.isEmpty(); // Get node's 3D coordinate Point3f p = points.get(node); if (null == p) { fps[0] = node.x; fps[1] = node.y; at.transform(fps, 0, fps, 0, 1); p = new Point3f(fps[0] * pixelWidthScaled, fps[1] * pixelHeightScaled, (float)node.la.getZ() * pixelWidthScaled * sign); points.put(node, p); } if (null != node.parent) { // Create a line to the parent list.add(points.get(node.parent)); list.add(p); if (go && node.parent != todo.getFirst().parent) { // node.parent point no longer needed (last child just processed) points.remove(node.parent); } } } } System.out.println("A: " + (System.currentTimeMillis() - t0)); t0 = System.currentTimeMillis(); for (int i=0; i<n_iterations; i++) { points.clear(); todo.clear(); todo.add(root); list.clear(); final float[] fps = new float[2]; // Simpler method, not clearing no-longer-used nodes from map while (!todo.isEmpty()) { final Node node = todo.removeFirst(); // Add children to todo list if any if (null != node.children) { for (final Node nd : node.children) todo.add(nd); } // Get node's 3D coordinate Point3f p = points.get(node); if (null == p) { fps[0] = node.x; fps[1] = node.y; at.transform(fps, 0, fps, 0, 1); p = new Point3f(fps[0] * pixelWidthScaled, fps[1] * pixelHeightScaled, (float)node.la.getZ() * pixelWidthScaled * sign); points.put(node, p); } if (null != node.parent) { // Create a line to the parent list.add(points.get(node.parent)); list.add(p); } } } System.out.println("B: " + (System.currentTimeMillis() - t0)); t0 = System.currentTimeMillis(); for (int i=0; i<n_iterations; i++) { todo.clear(); todo.add(root); list.clear(); // Simplest method: no caching in a map final float[] fp = new float[4]; while (!todo.isEmpty()) { final Node node = todo.removeFirst(); // Add children to todo list if any if (null != node.children) { for (final Node nd : node.children) todo.add(nd); } if (null != node.parent) { // Create a line to the parent fp[0] = node.x; fp[1] = node.y; fp[2] = node.parent.x; fp[3] = node.parent.y; at.transform(fp, 0, fp, 0, 2); list.add(new Point3f(fp[2] * pixelWidthScaled, fp[3] * pixelHeightScaled, (float)node.parent.la.getZ() * pixelWidthScaled * sign)); list.add(new Point3f(fp[0] * pixelWidthScaled, fp[1] * pixelHeightScaled, (float)node.la.getZ() * pixelWidthScaled * sign)); } } } System.out.println("C: " + (System.currentTimeMillis() - t0)); } */ /** Returns a list of two lists: the List<Point3f> and the corresponding List<Color3f>. */ public MeshData generateMesh(double scale_, int parallels) { // Construct a mesh made of straight tubes for each edge, and balls of the same ending diameter on the nodes. // // TODO: // With some cleverness, such meshes could be welded together by merging the nearest vertices on the ball // surfaces, or by cleaving the surface where the diameter of the tube cuts it. // A tougher problem is where tubes cut each other, but perhaps if the resulting mesh is still non-manifold, it's ok. final float scale = (float)scale_; if (parallels < 3) parallels = 3; // Simple ball-and-stick model // first test: just the nodes as icosahedrons with 1 subdivision final Calibration cal = layer_set.getCalibration(); final float pixelWidthScaled = (float)cal.pixelWidth * scale; final float pixelHeightScaled = (float)cal.pixelHeight * scale; final int sign = cal.pixelDepth < 0 ? -1 : 1; final List<Point3f> ico = M.createIcosahedron(1, 1); final List<Point3f> ps = new ArrayList<Point3f>(); // A plane made of as many edges as parallels, with radius 1 // Perpendicular vector of the plane is 0,0,1 final List<Point3f> plane = new ArrayList<Point3f>(); final double inc_rads = (Math.PI * 2) / parallels; double angle = 0; for (int i=0; i<parallels; i++) { plane.add(new Point3f((float)Math.cos(angle), (float)Math.sin(angle), 0)); angle += inc_rads; } final Vector3f vplane = new Vector3f(0, 0, 1); final Transform3D t = new Transform3D(); final AxisAngle4f aa = new AxisAngle4f(); final List<Color3f> colors = new ArrayList<Color3f>(); final Color3f cf = new Color3f(this.color); final HashMap<Color,Color3f> cached_colors = new HashMap<Color,Color3f>(); cached_colors.put(this.color, cf); for (final Set<Node<Float>> nodes : node_layer_map.values()) { for (final Node<Float> nd : nodes) { Point2D.Double po = transformPoint(nd.x, nd.y); final float x = (float)po.x * pixelWidthScaled; final float y = (float)po.y * pixelHeightScaled; final float z = (float)nd.la.getZ() * pixelWidthScaled * sign; final float r = ((RadiusNode)nd).r * pixelWidthScaled; // TODO r is not transformed by the AffineTransform for (final Point3f vert : ico) { Point3f v = new Point3f(vert); v.x = v.x * r + x; v.y = v.y * r + y; v.z = v.z * r + z; ps.add(v); } int n_verts = ico.size(); // Tube from parent to child // Check if a 3D volume representation is necessary for this segment - if (null != nd.parent && 0 != nd.parent.getData() && 0 != nd.getData()) { + if (null != nd.parent && (0 != nd.parent.getData() || 0 != nd.getData())) { po = null; // parent: Point2D.Double pp = transformPoint(nd.parent.x, nd.parent.y); final float parx = (float)pp.x * pixelWidthScaled; final float pary = (float)pp.y * pixelWidthScaled; final float parz = (float)nd.parent.la.getZ() * pixelWidthScaled * sign; final float parr = ((RadiusNode)nd.parent).r * pixelWidthScaled; // TODO r is not transformed by the AffineTransform // the vector perpendicular to the plane is 0,0,1 // the vector from parent to child is: Vector3f vpc = new Vector3f(x - parx, y - pary, z - parz); Vector3f cross = new Vector3f(); cross.cross(vpc, vplane); cross.normalize(); // not needed? aa.set(cross.x, cross.y, cross.z, -vplane.angle(vpc)); t.set(aa); final List<Point3f> parent_verts = transform(t, plane, parx, pary, parz, parr); final List<Point3f> child_verts = transform(t, plane, x, y, z, r); for (int i=1; i<parallels; i++) { addTriangles(ps, parent_verts, child_verts, i-1, i); n_verts += 6; } // faces from last to first: addTriangles(ps, parent_verts, child_verts, parallels -1, 0); n_verts += 6; } // Colors for each segment: Color3f c; if (null == nd.color) { c = cf; } else { c = cached_colors.get(nd.color); if (null == c) { c = new Color3f(nd.color); cached_colors.put(nd.color, c); } } while (n_verts > 0) { n_verts--; colors.add(c); } } } Utils.log2("Treeline MeshData lists of same length: " + (ps.size() == colors.size())); return new MeshData(ps, colors); } static private final void addTriangles(final List<Point3f> ps, final List<Point3f> parent_verts, final List<Point3f> child_verts, final int i0, final int i1) { // one triangle ps.add(new Point3f(parent_verts.get(i0))); ps.add(new Point3f(parent_verts.get(i1))); ps.add(new Point3f(child_verts.get(i0))); // another ps.add(new Point3f(parent_verts.get(i1))); ps.add(new Point3f(child_verts.get(i1))); ps.add(new Point3f(child_verts.get(i0))); } static private final List<Point3f> transform(final Transform3D t, final List<Point3f> plane, final float x, final float y, final float z, final float radius) { final List<Point3f> ps = new ArrayList<Point3f>(plane.size()); for (Point3f p : plane) { p = new Point3f(p); p.x *= radius; p.y *= radius; p.z *= radius; t.transform(p); p.x += x; p.y += y; p.z += z; ps.add(p); } return ps; } @Override public void keyPressed(KeyEvent ke) { if (isTagging()) { super.keyPressed(ke); return; } final int tool = ProjectToolbar.getToolId(); try { if (ProjectToolbar.PEN == tool) { Object origin = ke.getSource(); if (! (origin instanceof DisplayCanvas)) { ke.consume(); return; } DisplayCanvas dc = (DisplayCanvas)origin; Layer layer = dc.getDisplay().getLayer(); final Point p = dc.getCursorLoc(); // as offscreen coords switch (ke.getKeyCode()) { case KeyEvent.VK_O: layer_set.addDataEditStep(this); if (askAdjustRadius(p.x, p.y, layer, dc.getMagnification())) { ke.consume(); layer_set.addDataEditStep(this); // current state } else { layer_set.removeLastUndoStep(); // dialog canceled } break; } } } finally { if (!ke.isConsumed()) { super.keyPressed(ke); } } } private boolean askAdjustRadius(final float x, final float y, final Layer layer, final double magnification) { final Collection<Node<Float>> nodes = node_layer_map.get(layer); if (null == nodes) return false; RadiusNode nd = (RadiusNode) findClosestNodeW(nodes, x, y, magnification); if (null == nd) return false; GenericDialog gd = new GenericDialog("Adjust radius"); final Calibration cal = layer.getParent().getCalibration(); String unit = cal.getUnit(); if (!unit.toLowerCase().startsWith("pixel")) { final String[] units = new String[]{"pixels", unit}; gd.addChoice("Units:", units, units[1]); gd.addNumericField("Radius:", nd.getData() * cal.pixelWidth, 2); final TextField tfr = (TextField) gd.getNumericFields().get(0); ((Choice)gd.getChoices().get(0)).addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { final double val = Double.parseDouble(tfr.getText()); if (Double.isNaN(val)) return; tfr.setText(Double.toString(units[0] == ie.getItem() ? val / cal.pixelWidth : val * cal.pixelWidth)); } }); } else { unit = null; gd.addNumericField("Radius:", nd.getData(), 2, 10, "pixels"); } final String[] choices = {"this node only", "nodes until next branch or end node", "entire subtree"}; gd.addChoice("Apply to:", choices, choices[0]); gd.showDialog(); if (gd.wasCanceled()) return false; double radius = gd.getNextNumber(); if (Double.isNaN(radius) || radius < 0) { Utils.log("Invalid radius: " + radius); return false; } if (null != unit && 1 == gd.getNextChoiceIndex() && 0 != radius) { // convert radius from units to pixels radius = radius / cal.pixelWidth; } final float r = (float)radius; final Node.Operation<Float> op = new Node.Operation<Float>() { @Override public void apply(Node<Float> node) throws Exception { node.setData(r); } }; // Apply to: try { switch (gd.getNextChoiceIndex()) { case 0: // Just the node nd.setData(r); break; case 1: // All the way to the next branch or end point nd.applyToSlab(op); break; case 2: // To the entire subtree of nodes nd.applyToSubtree(op); break; default: return false; } } catch (Exception e) { IJError.print(e); } calculateBoundingBox(layer); Display.repaint(layer_set); return true; } @Override protected Rectangle getBounds(final Collection<Node<Float>> nodes) { Rectangle box = null; for (final RadiusNode nd : (Collection<RadiusNode>)(Collection)nodes) { if (null == nd.parent) { if (null == box) box = new Rectangle((int)nd.x, (int)nd.y, 1, 1); else box.add((int)nd.x, (int)nd.y); continue; } // Get the segment with the parent node if (null == box) box = nd.getSegment().getBounds(); else box.add(nd.getSegment().getBounds()); } return box; } }
true
true
public MeshData generateMesh(double scale_, int parallels) { // Construct a mesh made of straight tubes for each edge, and balls of the same ending diameter on the nodes. // // TODO: // With some cleverness, such meshes could be welded together by merging the nearest vertices on the ball // surfaces, or by cleaving the surface where the diameter of the tube cuts it. // A tougher problem is where tubes cut each other, but perhaps if the resulting mesh is still non-manifold, it's ok. final float scale = (float)scale_; if (parallels < 3) parallels = 3; // Simple ball-and-stick model // first test: just the nodes as icosahedrons with 1 subdivision final Calibration cal = layer_set.getCalibration(); final float pixelWidthScaled = (float)cal.pixelWidth * scale; final float pixelHeightScaled = (float)cal.pixelHeight * scale; final int sign = cal.pixelDepth < 0 ? -1 : 1; final List<Point3f> ico = M.createIcosahedron(1, 1); final List<Point3f> ps = new ArrayList<Point3f>(); // A plane made of as many edges as parallels, with radius 1 // Perpendicular vector of the plane is 0,0,1 final List<Point3f> plane = new ArrayList<Point3f>(); final double inc_rads = (Math.PI * 2) / parallels; double angle = 0; for (int i=0; i<parallels; i++) { plane.add(new Point3f((float)Math.cos(angle), (float)Math.sin(angle), 0)); angle += inc_rads; } final Vector3f vplane = new Vector3f(0, 0, 1); final Transform3D t = new Transform3D(); final AxisAngle4f aa = new AxisAngle4f(); final List<Color3f> colors = new ArrayList<Color3f>(); final Color3f cf = new Color3f(this.color); final HashMap<Color,Color3f> cached_colors = new HashMap<Color,Color3f>(); cached_colors.put(this.color, cf); for (final Set<Node<Float>> nodes : node_layer_map.values()) { for (final Node<Float> nd : nodes) { Point2D.Double po = transformPoint(nd.x, nd.y); final float x = (float)po.x * pixelWidthScaled; final float y = (float)po.y * pixelHeightScaled; final float z = (float)nd.la.getZ() * pixelWidthScaled * sign; final float r = ((RadiusNode)nd).r * pixelWidthScaled; // TODO r is not transformed by the AffineTransform for (final Point3f vert : ico) { Point3f v = new Point3f(vert); v.x = v.x * r + x; v.y = v.y * r + y; v.z = v.z * r + z; ps.add(v); } int n_verts = ico.size(); // Tube from parent to child // Check if a 3D volume representation is necessary for this segment if (null != nd.parent && 0 != nd.parent.getData() && 0 != nd.getData()) { po = null; // parent: Point2D.Double pp = transformPoint(nd.parent.x, nd.parent.y); final float parx = (float)pp.x * pixelWidthScaled; final float pary = (float)pp.y * pixelWidthScaled; final float parz = (float)nd.parent.la.getZ() * pixelWidthScaled * sign; final float parr = ((RadiusNode)nd.parent).r * pixelWidthScaled; // TODO r is not transformed by the AffineTransform // the vector perpendicular to the plane is 0,0,1 // the vector from parent to child is: Vector3f vpc = new Vector3f(x - parx, y - pary, z - parz); Vector3f cross = new Vector3f(); cross.cross(vpc, vplane); cross.normalize(); // not needed? aa.set(cross.x, cross.y, cross.z, -vplane.angle(vpc)); t.set(aa); final List<Point3f> parent_verts = transform(t, plane, parx, pary, parz, parr); final List<Point3f> child_verts = transform(t, plane, x, y, z, r); for (int i=1; i<parallels; i++) { addTriangles(ps, parent_verts, child_verts, i-1, i); n_verts += 6; } // faces from last to first: addTriangles(ps, parent_verts, child_verts, parallels -1, 0); n_verts += 6; } // Colors for each segment: Color3f c; if (null == nd.color) { c = cf; } else { c = cached_colors.get(nd.color); if (null == c) { c = new Color3f(nd.color); cached_colors.put(nd.color, c); } } while (n_verts > 0) { n_verts--; colors.add(c); } } } Utils.log2("Treeline MeshData lists of same length: " + (ps.size() == colors.size())); return new MeshData(ps, colors); }
public MeshData generateMesh(double scale_, int parallels) { // Construct a mesh made of straight tubes for each edge, and balls of the same ending diameter on the nodes. // // TODO: // With some cleverness, such meshes could be welded together by merging the nearest vertices on the ball // surfaces, or by cleaving the surface where the diameter of the tube cuts it. // A tougher problem is where tubes cut each other, but perhaps if the resulting mesh is still non-manifold, it's ok. final float scale = (float)scale_; if (parallels < 3) parallels = 3; // Simple ball-and-stick model // first test: just the nodes as icosahedrons with 1 subdivision final Calibration cal = layer_set.getCalibration(); final float pixelWidthScaled = (float)cal.pixelWidth * scale; final float pixelHeightScaled = (float)cal.pixelHeight * scale; final int sign = cal.pixelDepth < 0 ? -1 : 1; final List<Point3f> ico = M.createIcosahedron(1, 1); final List<Point3f> ps = new ArrayList<Point3f>(); // A plane made of as many edges as parallels, with radius 1 // Perpendicular vector of the plane is 0,0,1 final List<Point3f> plane = new ArrayList<Point3f>(); final double inc_rads = (Math.PI * 2) / parallels; double angle = 0; for (int i=0; i<parallels; i++) { plane.add(new Point3f((float)Math.cos(angle), (float)Math.sin(angle), 0)); angle += inc_rads; } final Vector3f vplane = new Vector3f(0, 0, 1); final Transform3D t = new Transform3D(); final AxisAngle4f aa = new AxisAngle4f(); final List<Color3f> colors = new ArrayList<Color3f>(); final Color3f cf = new Color3f(this.color); final HashMap<Color,Color3f> cached_colors = new HashMap<Color,Color3f>(); cached_colors.put(this.color, cf); for (final Set<Node<Float>> nodes : node_layer_map.values()) { for (final Node<Float> nd : nodes) { Point2D.Double po = transformPoint(nd.x, nd.y); final float x = (float)po.x * pixelWidthScaled; final float y = (float)po.y * pixelHeightScaled; final float z = (float)nd.la.getZ() * pixelWidthScaled * sign; final float r = ((RadiusNode)nd).r * pixelWidthScaled; // TODO r is not transformed by the AffineTransform for (final Point3f vert : ico) { Point3f v = new Point3f(vert); v.x = v.x * r + x; v.y = v.y * r + y; v.z = v.z * r + z; ps.add(v); } int n_verts = ico.size(); // Tube from parent to child // Check if a 3D volume representation is necessary for this segment if (null != nd.parent && (0 != nd.parent.getData() || 0 != nd.getData())) { po = null; // parent: Point2D.Double pp = transformPoint(nd.parent.x, nd.parent.y); final float parx = (float)pp.x * pixelWidthScaled; final float pary = (float)pp.y * pixelWidthScaled; final float parz = (float)nd.parent.la.getZ() * pixelWidthScaled * sign; final float parr = ((RadiusNode)nd.parent).r * pixelWidthScaled; // TODO r is not transformed by the AffineTransform // the vector perpendicular to the plane is 0,0,1 // the vector from parent to child is: Vector3f vpc = new Vector3f(x - parx, y - pary, z - parz); Vector3f cross = new Vector3f(); cross.cross(vpc, vplane); cross.normalize(); // not needed? aa.set(cross.x, cross.y, cross.z, -vplane.angle(vpc)); t.set(aa); final List<Point3f> parent_verts = transform(t, plane, parx, pary, parz, parr); final List<Point3f> child_verts = transform(t, plane, x, y, z, r); for (int i=1; i<parallels; i++) { addTriangles(ps, parent_verts, child_verts, i-1, i); n_verts += 6; } // faces from last to first: addTriangles(ps, parent_verts, child_verts, parallels -1, 0); n_verts += 6; } // Colors for each segment: Color3f c; if (null == nd.color) { c = cf; } else { c = cached_colors.get(nd.color); if (null == c) { c = new Color3f(nd.color); cached_colors.put(nd.color, c); } } while (n_verts > 0) { n_verts--; colors.add(c); } } } Utils.log2("Treeline MeshData lists of same length: " + (ps.size() == colors.size())); return new MeshData(ps, colors); }
diff --git a/src/com/js/interpreter/runtime/exception/PascalIndexOutOfBoundsException.java b/src/com/js/interpreter/runtime/exception/PascalIndexOutOfBoundsException.java index 7c5abfa..50aea5c 100644 --- a/src/com/js/interpreter/runtime/exception/PascalIndexOutOfBoundsException.java +++ b/src/com/js/interpreter/runtime/exception/PascalIndexOutOfBoundsException.java @@ -1,26 +1,28 @@ package com.js.interpreter.runtime.exception; import com.js.interpreter.linenumber.LineInfo; public class PascalIndexOutOfBoundsException extends RuntimePascalException { String message; public PascalIndexOutOfBoundsException(LineInfo line, int index, int min, int max) { super(line); this.message = "Index out of bounds: " + getcause(index, min, max); } @Override public String getMessage() { return message; } private String getcause(int index, int min, int max) { if (index < min) { return index + " is less than the minimum index of " + min; + } else if (max == -1 && min == 0) { + return "variable length array has not been initialized yet"; } else { return index + " is greater than the maximum index of " + max; } } }
true
true
private String getcause(int index, int min, int max) { if (index < min) { return index + " is less than the minimum index of " + min; } else { return index + " is greater than the maximum index of " + max; } }
private String getcause(int index, int min, int max) { if (index < min) { return index + " is less than the minimum index of " + min; } else if (max == -1 && min == 0) { return "variable length array has not been initialized yet"; } else { return index + " is greater than the maximum index of " + max; } }
diff --git a/org/jruby/parser/Parser.java b/org/jruby/parser/Parser.java index 12b515272..2c2c5b90f 100644 --- a/org/jruby/parser/Parser.java +++ b/org/jruby/parser/Parser.java @@ -1,71 +1,79 @@ /* * Copyright (C) 2002 Anders Bengtsson <[email protected]> * * JRuby - http://jruby.sourceforge.net * * This file is part of JRuby * * JRuby is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * JRuby is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with JRuby; if not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ /** * Serves as a simple facade for all the parsing magic. */ package org.jruby.parser; import org.ablaf.ast.INode; import org.ablaf.lexer.*; import org.ablaf.parser.IParser; import org.jruby.Ruby; import org.jruby.common.RubyErrorHandler; import java.util.ArrayList; import java.io.Reader; import java.io.StringReader; public class Parser { private final Ruby ruby; private IParser internalParser = new DefaultRubyParser(); public Parser(Ruby ruby) { this.ruby = ruby; internalParser.setErrorHandler(new RubyErrorHandler(ruby, ruby.isVerbose())); } public INode parse(String file, String content) { return parse(file, new StringReader(content)); } public INode parse(String file, Reader content) { return parse(file, content, new RubyParserConfiguration()); } public INode parse(String file, String content, RubyParserConfiguration config) { return parse(file, new StringReader(content), config); } public INode parse(String file, Reader content, RubyParserConfiguration config) { config.setLocalVariables(ruby.getScope().getLocalNames()); internalParser.init(config); ILexerSource lexerSource = LexerFactory.getInstance().getSource(file, content); IRubyParserResult result = (IRubyParserResult) internalParser.parse(lexerSource); + int newSize = 0; if (result.getLocalVariables() != null) { + newSize = result.getLocalVariables().size(); + } + int oldSize = 0; + if (ruby.getScope().getLocalNames() != null) { + oldSize = ruby.getScope().getLocalNames().size(); + } + if (newSize > oldSize) { ruby.getScope().setLocalNames(new ArrayList(result.getLocalVariables())); } return result.getAST(); } }
false
true
public INode parse(String file, Reader content, RubyParserConfiguration config) { config.setLocalVariables(ruby.getScope().getLocalNames()); internalParser.init(config); ILexerSource lexerSource = LexerFactory.getInstance().getSource(file, content); IRubyParserResult result = (IRubyParserResult) internalParser.parse(lexerSource); if (result.getLocalVariables() != null) { ruby.getScope().setLocalNames(new ArrayList(result.getLocalVariables())); } return result.getAST(); }
public INode parse(String file, Reader content, RubyParserConfiguration config) { config.setLocalVariables(ruby.getScope().getLocalNames()); internalParser.init(config); ILexerSource lexerSource = LexerFactory.getInstance().getSource(file, content); IRubyParserResult result = (IRubyParserResult) internalParser.parse(lexerSource); int newSize = 0; if (result.getLocalVariables() != null) { newSize = result.getLocalVariables().size(); } int oldSize = 0; if (ruby.getScope().getLocalNames() != null) { oldSize = ruby.getScope().getLocalNames().size(); } if (newSize > oldSize) { ruby.getScope().setLocalNames(new ArrayList(result.getLocalVariables())); } return result.getAST(); }
diff --git a/java/src/org/broadinstitute/sting/gatk/walkers/fasta/PickSequenomProbes.java b/java/src/org/broadinstitute/sting/gatk/walkers/fasta/PickSequenomProbes.java index 965ee935c..85cedf520 100755 --- a/java/src/org/broadinstitute/sting/gatk/walkers/fasta/PickSequenomProbes.java +++ b/java/src/org/broadinstitute/sting/gatk/walkers/fasta/PickSequenomProbes.java @@ -1,131 +1,131 @@ package org.broadinstitute.sting.gatk.walkers.fasta; import org.broadinstitute.sting.gatk.GenomeAnalysisEngine; import org.broadinstitute.sting.gatk.contexts.AlignmentContext; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.gatk.refdata.*; import org.broadinstitute.sting.gatk.walkers.*; import org.broadinstitute.sting.utils.*; import org.broadinstitute.sting.utils.cmdLine.Argument; import org.broadinstitute.sting.utils.genotype.Variation; import java.util.*; /** * Generates Sequenom probe information given a single variant track. Emitted is the variant * along with the 200 reference bases on each side of the variant. */ @WalkerName("PickSequenomProbes") @Requires(value={DataSource.REFERENCE}) @Reference(window=@Window(start=-200,stop=200)) public class PickSequenomProbes extends RefWalker<String, String> { @Argument(required=false, shortName="snp_mask", doc="positions to be masked with N's") protected String SNP_MASK = null; @Argument(required=false, shortName="project_id",doc="If specified, all probenames will be prepended with 'project_id|'") String project_id = null; private byte [] maskFlags = new byte[401]; private SeekableRODIterator<TabularROD> snpMaskIterator=null; public void initialize() { if ( SNP_MASK != null ) { logger.info("Loading SNP mask... "); ReferenceOrderedData<TabularROD> snp_mask = new ReferenceOrderedData<TabularROD>("snp_mask", new java.io.File(SNP_MASK), TabularROD.class); snpMaskIterator = snp_mask.iterator(); } } public String map(RefMetaDataTracker rodData, ReferenceContext ref, AlignmentContext context) { logger.debug("Probing " + ref.getLocus() + " " + ref.getWindow()); String refBase = String.valueOf(ref.getBase()); Iterator<ReferenceOrderedDatum> rods = rodData.getAllRods().iterator(); Variation variant = null; while (rods.hasNext()) { ReferenceOrderedDatum rod = rods.next(); // if we have multiple variants at a locus, just take the first one we see if ( rod instanceof Variation ) { variant = (Variation)rod; break; } } if ( variant == null ) return ""; String contig = context.getLocation().getContig(); long offset = context.getLocation().getStart(); long true_offset = offset - 200; // we have variant; let's load all the snps falling into the current window and prepare the mask array: if ( snpMaskIterator != null ) { RODRecordList<TabularROD> snpList = snpMaskIterator.seekForward(GenomeLocParser.createGenomeLoc(contig,offset-200,offset+200)); if ( snpList != null && snpList.size() != 0 ) { Iterator<TabularROD> snpsInWindow = snpList.iterator(); int i = 0; while ( snpsInWindow.hasNext() ) { GenomeLoc snp = snpsInWindow.next().getLocation(); int offsetInWindow = (int)(snp.getStart() - true_offset); for ( ; i < offsetInWindow; i++ ) maskFlags[i] = 0; maskFlags[i++] = 1; } for ( ; i < 401; i++ ) maskFlags[i] = 0; } else { // we got no snps, don't forget to clear the mask for ( int i = 0 ; i < 401; i++ ) maskFlags[i] = 0; } } char[] context_bases = ref.getBases(); for (int i = 0; i < 401; i++) { GenomeLoc loc = GenomeLocParser.parseGenomeLoc(contig + ":" + true_offset + "-" + true_offset); if ( maskFlags[i]==1 ) { context_bases[i] = 'N'; } true_offset += 1; } String leading_bases = new String(Arrays.copyOfRange(context_bases, 0, 200)); String trailing_bases = new String(Arrays.copyOfRange(context_bases, 201, 401)); String assay_sequence; if ( variant.isSNP() ) assay_sequence = leading_bases + "[" + refBase + "/" + variant.getAlternativeBaseForSNP() + "]" + trailing_bases; else if ( variant.isInsertion() ) assay_sequence = leading_bases + refBase + "[-/" + Utils.join("",variant.getAlleleList()) + "]" + trailing_bases; else if ( variant.isDeletion() ) - assay_sequence = leading_bases + refBase + "[" + Utils.join("",variant.getAlleleList()) + "/-]" + trailing_bases.substring(variant.getAlleleList().size()); + assay_sequence = leading_bases + refBase + "[" + Utils.join("",variant.getAlleleList()) + "/-]" + trailing_bases.substring(variant.getAlleleList().get(0).length()); else return ""; StringBuilder assay_id = new StringBuilder(); if ( project_id != null ) { assay_id.append(project_id); assay_id.append('|'); } assay_id.append(context.getLocation().toString().replace(':','_')); assay_id.append('_'); if ( variant.isInsertion() ) assay_id.append("gI_"); else if ( variant.isDeletion()) assay_id.append("gD_"); assay_id.append(ref.getWindow().toString().replace(':', '_')); return assay_id.toString() + "\t" + assay_sequence + "\n"; } public String reduceInit() { return ""; } public String reduce(String data, String sum) { out.print(data); return ""; } public void onTraversalDone(String sum) {} }
true
true
public String map(RefMetaDataTracker rodData, ReferenceContext ref, AlignmentContext context) { logger.debug("Probing " + ref.getLocus() + " " + ref.getWindow()); String refBase = String.valueOf(ref.getBase()); Iterator<ReferenceOrderedDatum> rods = rodData.getAllRods().iterator(); Variation variant = null; while (rods.hasNext()) { ReferenceOrderedDatum rod = rods.next(); // if we have multiple variants at a locus, just take the first one we see if ( rod instanceof Variation ) { variant = (Variation)rod; break; } } if ( variant == null ) return ""; String contig = context.getLocation().getContig(); long offset = context.getLocation().getStart(); long true_offset = offset - 200; // we have variant; let's load all the snps falling into the current window and prepare the mask array: if ( snpMaskIterator != null ) { RODRecordList<TabularROD> snpList = snpMaskIterator.seekForward(GenomeLocParser.createGenomeLoc(contig,offset-200,offset+200)); if ( snpList != null && snpList.size() != 0 ) { Iterator<TabularROD> snpsInWindow = snpList.iterator(); int i = 0; while ( snpsInWindow.hasNext() ) { GenomeLoc snp = snpsInWindow.next().getLocation(); int offsetInWindow = (int)(snp.getStart() - true_offset); for ( ; i < offsetInWindow; i++ ) maskFlags[i] = 0; maskFlags[i++] = 1; } for ( ; i < 401; i++ ) maskFlags[i] = 0; } else { // we got no snps, don't forget to clear the mask for ( int i = 0 ; i < 401; i++ ) maskFlags[i] = 0; } } char[] context_bases = ref.getBases(); for (int i = 0; i < 401; i++) { GenomeLoc loc = GenomeLocParser.parseGenomeLoc(contig + ":" + true_offset + "-" + true_offset); if ( maskFlags[i]==1 ) { context_bases[i] = 'N'; } true_offset += 1; } String leading_bases = new String(Arrays.copyOfRange(context_bases, 0, 200)); String trailing_bases = new String(Arrays.copyOfRange(context_bases, 201, 401)); String assay_sequence; if ( variant.isSNP() ) assay_sequence = leading_bases + "[" + refBase + "/" + variant.getAlternativeBaseForSNP() + "]" + trailing_bases; else if ( variant.isInsertion() ) assay_sequence = leading_bases + refBase + "[-/" + Utils.join("",variant.getAlleleList()) + "]" + trailing_bases; else if ( variant.isDeletion() ) assay_sequence = leading_bases + refBase + "[" + Utils.join("",variant.getAlleleList()) + "/-]" + trailing_bases.substring(variant.getAlleleList().size()); else return ""; StringBuilder assay_id = new StringBuilder(); if ( project_id != null ) { assay_id.append(project_id); assay_id.append('|'); } assay_id.append(context.getLocation().toString().replace(':','_')); assay_id.append('_'); if ( variant.isInsertion() ) assay_id.append("gI_"); else if ( variant.isDeletion()) assay_id.append("gD_"); assay_id.append(ref.getWindow().toString().replace(':', '_')); return assay_id.toString() + "\t" + assay_sequence + "\n"; }
public String map(RefMetaDataTracker rodData, ReferenceContext ref, AlignmentContext context) { logger.debug("Probing " + ref.getLocus() + " " + ref.getWindow()); String refBase = String.valueOf(ref.getBase()); Iterator<ReferenceOrderedDatum> rods = rodData.getAllRods().iterator(); Variation variant = null; while (rods.hasNext()) { ReferenceOrderedDatum rod = rods.next(); // if we have multiple variants at a locus, just take the first one we see if ( rod instanceof Variation ) { variant = (Variation)rod; break; } } if ( variant == null ) return ""; String contig = context.getLocation().getContig(); long offset = context.getLocation().getStart(); long true_offset = offset - 200; // we have variant; let's load all the snps falling into the current window and prepare the mask array: if ( snpMaskIterator != null ) { RODRecordList<TabularROD> snpList = snpMaskIterator.seekForward(GenomeLocParser.createGenomeLoc(contig,offset-200,offset+200)); if ( snpList != null && snpList.size() != 0 ) { Iterator<TabularROD> snpsInWindow = snpList.iterator(); int i = 0; while ( snpsInWindow.hasNext() ) { GenomeLoc snp = snpsInWindow.next().getLocation(); int offsetInWindow = (int)(snp.getStart() - true_offset); for ( ; i < offsetInWindow; i++ ) maskFlags[i] = 0; maskFlags[i++] = 1; } for ( ; i < 401; i++ ) maskFlags[i] = 0; } else { // we got no snps, don't forget to clear the mask for ( int i = 0 ; i < 401; i++ ) maskFlags[i] = 0; } } char[] context_bases = ref.getBases(); for (int i = 0; i < 401; i++) { GenomeLoc loc = GenomeLocParser.parseGenomeLoc(contig + ":" + true_offset + "-" + true_offset); if ( maskFlags[i]==1 ) { context_bases[i] = 'N'; } true_offset += 1; } String leading_bases = new String(Arrays.copyOfRange(context_bases, 0, 200)); String trailing_bases = new String(Arrays.copyOfRange(context_bases, 201, 401)); String assay_sequence; if ( variant.isSNP() ) assay_sequence = leading_bases + "[" + refBase + "/" + variant.getAlternativeBaseForSNP() + "]" + trailing_bases; else if ( variant.isInsertion() ) assay_sequence = leading_bases + refBase + "[-/" + Utils.join("",variant.getAlleleList()) + "]" + trailing_bases; else if ( variant.isDeletion() ) assay_sequence = leading_bases + refBase + "[" + Utils.join("",variant.getAlleleList()) + "/-]" + trailing_bases.substring(variant.getAlleleList().get(0).length()); else return ""; StringBuilder assay_id = new StringBuilder(); if ( project_id != null ) { assay_id.append(project_id); assay_id.append('|'); } assay_id.append(context.getLocation().toString().replace(':','_')); assay_id.append('_'); if ( variant.isInsertion() ) assay_id.append("gI_"); else if ( variant.isDeletion()) assay_id.append("gD_"); assay_id.append(ref.getWindow().toString().replace(':', '_')); return assay_id.toString() + "\t" + assay_sequence + "\n"; }
diff --git a/plugins/org.xwiki.eclipse.ui/src/main/java/org/xwiki/eclipse/ui/adapters/XWikiEclipsePageSummaryAdapter.java b/plugins/org.xwiki.eclipse.ui/src/main/java/org/xwiki/eclipse/ui/adapters/XWikiEclipsePageSummaryAdapter.java index 17b2db5..abd3a18 100644 --- a/plugins/org.xwiki.eclipse.ui/src/main/java/org/xwiki/eclipse/ui/adapters/XWikiEclipsePageSummaryAdapter.java +++ b/plugins/org.xwiki.eclipse.ui/src/main/java/org/xwiki/eclipse/ui/adapters/XWikiEclipsePageSummaryAdapter.java @@ -1,239 +1,244 @@ /* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package org.xwiki.eclipse.ui.adapters; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.model.WorkbenchAdapter; import org.eclipse.ui.progress.IDeferredWorkbenchAdapter; import org.eclipse.ui.progress.IElementCollector; import org.xwiki.eclipse.core.CoreLog; import org.xwiki.eclipse.model.ModelObject; import org.xwiki.eclipse.model.XWikiEclipseAttachment; import org.xwiki.eclipse.model.XWikiEclipseClass; import org.xwiki.eclipse.model.XWikiEclipseComment; import org.xwiki.eclipse.model.XWikiEclipseObjectCollection; import org.xwiki.eclipse.model.XWikiEclipseObjectSummary; import org.xwiki.eclipse.model.XWikiEclipsePageSummary; import org.xwiki.eclipse.model.XWikiEclipseTag; import org.xwiki.eclipse.storage.DataManager; import org.xwiki.eclipse.storage.XWikiEclipseStorageException; import org.xwiki.eclipse.ui.UIConstants; import org.xwiki.eclipse.ui.UIPlugin; import org.xwiki.eclipse.ui.utils.UIUtils; /** * @version $Id$ */ public class XWikiEclipsePageSummaryAdapter extends WorkbenchAdapter implements IDeferredWorkbenchAdapter { @Override public Object[] getChildren(Object object) { if (object instanceof XWikiEclipsePageSummary) { final XWikiEclipsePageSummary pageSummary = (XWikiEclipsePageSummary) object; try { /* fetch objects (including annotations, comments and customized objects), pageClass, tags */ DataManager dataManager = pageSummary.getDataManager(); List<XWikiEclipseObjectSummary> objects = dataManager.getObjectSummaries(pageSummary); List<XWikiEclipseAttachment> attachments = dataManager.getAttachments(pageSummary); XWikiEclipseClass pageClass = dataManager.getClass(pageSummary); List<XWikiEclipseTag> tags = dataManager.getTags(pageSummary); List<XWikiEclipseComment> comments = dataManager.getComments(pageSummary); List<ModelObject> result = new ArrayList<ModelObject>(); String pageId = pageSummary.getId(); /* add pageClass */ result.add(pageClass); /* add attachments */ if (attachments != null && attachments.size() > 0) { XWikiEclipseObjectCollection a = new XWikiEclipseObjectCollection(dataManager); a.setClassName("Attachments"); a.setPageId(pageId); for (XWikiEclipseAttachment attach : attachments) { a.getObjects().add(attach); } if (a.getObjects().size() > 0) { result.add(a); } } /* add tags */ if (tags != null && tags.size() > 0) { XWikiEclipseObjectCollection t = new XWikiEclipseObjectCollection(dataManager); t.setClassName("Tags"); t.setPageId(pageId); for (XWikiEclipseTag tag : tags) { t.getObjects().add(tag); } if (t.getObjects().size() > 0) { result.add(t); } } /* add comments */ if (comments != null && comments.size() > 0) { XWikiEclipseObjectCollection t = new XWikiEclipseObjectCollection(dataManager); t.setClassName("Comments"); t.setPageId(pageId); for (XWikiEclipseComment comment : comments) { t.getObjects().add(comment); } if (t.getObjects().size() > 0) { result.add(t); } } /* * add objects that are not comments or tags, may include all the annotations and all the customized * classes, group them based on the className */ if (objects != null && objects.size() > 0) { - XWikiEclipseObjectCollection collection = new XWikiEclipseObjectCollection(dataManager); - collection.setClassName("Objects"); - collection.setPageId(pageId); + XWikiEclipseObjectCollection collection = null; Map<String, XWikiEclipseObjectCollection> classnameCollectionMap = new HashMap<String, XWikiEclipseObjectCollection>(); for (XWikiEclipseObjectSummary objectSummary : objects) { if (!objectSummary.getClassName().equals("XWiki.TagClass") && !objectSummary.getClassName().equals("XWiki.XWikiComments")) { String classname = objectSummary.getClassName(); if (classnameCollectionMap.containsKey(classname)) { classnameCollectionMap.get(classname).getObjects().add(objectSummary); } else { XWikiEclipseObjectCollection subCollection = new XWikiEclipseObjectCollection(dataManager); subCollection.setPageId(pageId); if (classname.equals("XWiki.XWikiComments")) { subCollection.setClassName("Comments"); } else if (classname.equals("AnnotationCode.AnnotationClass")) { subCollection.setClassName("Annotations"); } else { subCollection.setClassName(classname); } subCollection.getObjects().add(objectSummary); classnameCollectionMap.put(classname, subCollection); + if (collection == null) { + collection = new XWikiEclipseObjectCollection(dataManager); + collection.setClassName("Objects"); + collection.setPageId(pageId); + } collection.getObjects().add(subCollection); } } } - result.add(collection); + if (collection != null) { + result.add(collection); + } } return result.toArray(); } catch (XWikiEclipseStorageException e) { UIUtils .showMessageDialog( Display.getDefault().getActiveShell(), SWT.ICON_ERROR, "Error getting objects.", "There was a communication error while getting objects. XWiki Eclipse is taking the connection offline in order to prevent further errors. Please check your remote XWiki status and then try to reconnect."); pageSummary.getDataManager().disconnect(); CoreLog.logError("Error getting objects.", e); return NO_CHILDREN; } } return super.getChildren(object); } @Override public String getLabel(Object object) { if (object instanceof XWikiEclipsePageSummary) { XWikiEclipsePageSummary pageSummary = (XWikiEclipsePageSummary) object; String title = pageSummary.getTitle(); if (title == null) { title = pageSummary.getId(); } return title; } return super.getLabel(object); } @Override public ImageDescriptor getImageDescriptor(Object object) { if (object instanceof XWikiEclipsePageSummary) { XWikiEclipsePageSummary pageSummary = (XWikiEclipsePageSummary) object; if (pageSummary.getDataManager().isInConflict(pageSummary.getId())) { return UIPlugin.getImageDescriptor(UIConstants.PAGE_CONFLICT_ICON); } if (pageSummary.getDataManager().isLocallyAvailable(pageSummary)) { return UIPlugin.getImageDescriptor(UIConstants.PAGE_LOCALLY_AVAILABLE_ICON); } else { return UIPlugin.getImageDescriptor(UIConstants.PAGE_ICON); } } return null; } public void fetchDeferredChildren(Object object, IElementCollector collector, IProgressMonitor monitor) { collector.add(getChildren(object), monitor); collector.done(); } public ISchedulingRule getRule(Object object) { // TODO Auto-generated method stub return null; } public boolean isContainer() { return true; } }
false
true
public Object[] getChildren(Object object) { if (object instanceof XWikiEclipsePageSummary) { final XWikiEclipsePageSummary pageSummary = (XWikiEclipsePageSummary) object; try { /* fetch objects (including annotations, comments and customized objects), pageClass, tags */ DataManager dataManager = pageSummary.getDataManager(); List<XWikiEclipseObjectSummary> objects = dataManager.getObjectSummaries(pageSummary); List<XWikiEclipseAttachment> attachments = dataManager.getAttachments(pageSummary); XWikiEclipseClass pageClass = dataManager.getClass(pageSummary); List<XWikiEclipseTag> tags = dataManager.getTags(pageSummary); List<XWikiEclipseComment> comments = dataManager.getComments(pageSummary); List<ModelObject> result = new ArrayList<ModelObject>(); String pageId = pageSummary.getId(); /* add pageClass */ result.add(pageClass); /* add attachments */ if (attachments != null && attachments.size() > 0) { XWikiEclipseObjectCollection a = new XWikiEclipseObjectCollection(dataManager); a.setClassName("Attachments"); a.setPageId(pageId); for (XWikiEclipseAttachment attach : attachments) { a.getObjects().add(attach); } if (a.getObjects().size() > 0) { result.add(a); } } /* add tags */ if (tags != null && tags.size() > 0) { XWikiEclipseObjectCollection t = new XWikiEclipseObjectCollection(dataManager); t.setClassName("Tags"); t.setPageId(pageId); for (XWikiEclipseTag tag : tags) { t.getObjects().add(tag); } if (t.getObjects().size() > 0) { result.add(t); } } /* add comments */ if (comments != null && comments.size() > 0) { XWikiEclipseObjectCollection t = new XWikiEclipseObjectCollection(dataManager); t.setClassName("Comments"); t.setPageId(pageId); for (XWikiEclipseComment comment : comments) { t.getObjects().add(comment); } if (t.getObjects().size() > 0) { result.add(t); } } /* * add objects that are not comments or tags, may include all the annotations and all the customized * classes, group them based on the className */ if (objects != null && objects.size() > 0) { XWikiEclipseObjectCollection collection = new XWikiEclipseObjectCollection(dataManager); collection.setClassName("Objects"); collection.setPageId(pageId); Map<String, XWikiEclipseObjectCollection> classnameCollectionMap = new HashMap<String, XWikiEclipseObjectCollection>(); for (XWikiEclipseObjectSummary objectSummary : objects) { if (!objectSummary.getClassName().equals("XWiki.TagClass") && !objectSummary.getClassName().equals("XWiki.XWikiComments")) { String classname = objectSummary.getClassName(); if (classnameCollectionMap.containsKey(classname)) { classnameCollectionMap.get(classname).getObjects().add(objectSummary); } else { XWikiEclipseObjectCollection subCollection = new XWikiEclipseObjectCollection(dataManager); subCollection.setPageId(pageId); if (classname.equals("XWiki.XWikiComments")) { subCollection.setClassName("Comments"); } else if (classname.equals("AnnotationCode.AnnotationClass")) { subCollection.setClassName("Annotations"); } else { subCollection.setClassName(classname); } subCollection.getObjects().add(objectSummary); classnameCollectionMap.put(classname, subCollection); collection.getObjects().add(subCollection); } } } result.add(collection); } return result.toArray(); } catch (XWikiEclipseStorageException e) { UIUtils .showMessageDialog( Display.getDefault().getActiveShell(), SWT.ICON_ERROR, "Error getting objects.", "There was a communication error while getting objects. XWiki Eclipse is taking the connection offline in order to prevent further errors. Please check your remote XWiki status and then try to reconnect."); pageSummary.getDataManager().disconnect(); CoreLog.logError("Error getting objects.", e); return NO_CHILDREN; } } return super.getChildren(object); }
public Object[] getChildren(Object object) { if (object instanceof XWikiEclipsePageSummary) { final XWikiEclipsePageSummary pageSummary = (XWikiEclipsePageSummary) object; try { /* fetch objects (including annotations, comments and customized objects), pageClass, tags */ DataManager dataManager = pageSummary.getDataManager(); List<XWikiEclipseObjectSummary> objects = dataManager.getObjectSummaries(pageSummary); List<XWikiEclipseAttachment> attachments = dataManager.getAttachments(pageSummary); XWikiEclipseClass pageClass = dataManager.getClass(pageSummary); List<XWikiEclipseTag> tags = dataManager.getTags(pageSummary); List<XWikiEclipseComment> comments = dataManager.getComments(pageSummary); List<ModelObject> result = new ArrayList<ModelObject>(); String pageId = pageSummary.getId(); /* add pageClass */ result.add(pageClass); /* add attachments */ if (attachments != null && attachments.size() > 0) { XWikiEclipseObjectCollection a = new XWikiEclipseObjectCollection(dataManager); a.setClassName("Attachments"); a.setPageId(pageId); for (XWikiEclipseAttachment attach : attachments) { a.getObjects().add(attach); } if (a.getObjects().size() > 0) { result.add(a); } } /* add tags */ if (tags != null && tags.size() > 0) { XWikiEclipseObjectCollection t = new XWikiEclipseObjectCollection(dataManager); t.setClassName("Tags"); t.setPageId(pageId); for (XWikiEclipseTag tag : tags) { t.getObjects().add(tag); } if (t.getObjects().size() > 0) { result.add(t); } } /* add comments */ if (comments != null && comments.size() > 0) { XWikiEclipseObjectCollection t = new XWikiEclipseObjectCollection(dataManager); t.setClassName("Comments"); t.setPageId(pageId); for (XWikiEclipseComment comment : comments) { t.getObjects().add(comment); } if (t.getObjects().size() > 0) { result.add(t); } } /* * add objects that are not comments or tags, may include all the annotations and all the customized * classes, group them based on the className */ if (objects != null && objects.size() > 0) { XWikiEclipseObjectCollection collection = null; Map<String, XWikiEclipseObjectCollection> classnameCollectionMap = new HashMap<String, XWikiEclipseObjectCollection>(); for (XWikiEclipseObjectSummary objectSummary : objects) { if (!objectSummary.getClassName().equals("XWiki.TagClass") && !objectSummary.getClassName().equals("XWiki.XWikiComments")) { String classname = objectSummary.getClassName(); if (classnameCollectionMap.containsKey(classname)) { classnameCollectionMap.get(classname).getObjects().add(objectSummary); } else { XWikiEclipseObjectCollection subCollection = new XWikiEclipseObjectCollection(dataManager); subCollection.setPageId(pageId); if (classname.equals("XWiki.XWikiComments")) { subCollection.setClassName("Comments"); } else if (classname.equals("AnnotationCode.AnnotationClass")) { subCollection.setClassName("Annotations"); } else { subCollection.setClassName(classname); } subCollection.getObjects().add(objectSummary); classnameCollectionMap.put(classname, subCollection); if (collection == null) { collection = new XWikiEclipseObjectCollection(dataManager); collection.setClassName("Objects"); collection.setPageId(pageId); } collection.getObjects().add(subCollection); } } } if (collection != null) { result.add(collection); } } return result.toArray(); } catch (XWikiEclipseStorageException e) { UIUtils .showMessageDialog( Display.getDefault().getActiveShell(), SWT.ICON_ERROR, "Error getting objects.", "There was a communication error while getting objects. XWiki Eclipse is taking the connection offline in order to prevent further errors. Please check your remote XWiki status and then try to reconnect."); pageSummary.getDataManager().disconnect(); CoreLog.logError("Error getting objects.", e); return NO_CHILDREN; } } return super.getChildren(object); }
diff --git a/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus779/Nexus779RssFeedFilteringTest.java b/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus779/Nexus779RssFeedFilteringTest.java index 9422f5f86..07c012f98 100644 --- a/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus779/Nexus779RssFeedFilteringTest.java +++ b/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus779/Nexus779RssFeedFilteringTest.java @@ -1,197 +1,198 @@ package org.sonatype.nexus.integrationtests.nexus779; import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import org.junit.Test; import org.sonatype.nexus.integrationtests.AbstractPrivilegeTest; import org.sonatype.nexus.integrationtests.TestContainer; import org.sonatype.nexus.rest.model.PrivilegeTargetResource; import org.sonatype.nexus.rest.model.PrivilegeTargetStatusResource; import org.sonatype.nexus.rest.model.RepositoryTargetResource; import org.sonatype.nexus.rest.model.RoleResource; import org.sonatype.nexus.rest.model.UserResource; import org.sonatype.nexus.test.utils.FeedUtil; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndFeed; import edu.emory.mathcs.backport.java.util.Collections; /** * Test filtering search results based upon security */ public class Nexus779RssFeedFilteringTest extends AbstractPrivilegeTest { public Nexus779RssFeedFilteringTest() { } @SuppressWarnings("unchecked") @Test public void filteredFeeds() throws Exception { TestContainer.getInstance().getTestContext().useAdminForRequests(); // First create the targets RepositoryTargetResource test1Target = createTarget( "filterTarget1", Collections.singletonList( ".*/test1/.*" ) ); RepositoryTargetResource test2Target = createTarget( "filterTarget2", Collections.singletonList( ".*/test2/.*" ) ); // Then create the privileges PrivilegeTargetStatusResource priv1 = createPrivilege( "filterPriv1", test1Target.getId() ); PrivilegeTargetStatusResource priv2 = createPrivilege( "filterPriv2", test2Target.getId() ); // Then create the roles List<String> combined = new ArrayList<String>(); combined.add( priv1.getId() ); combined.add( priv2.getId() ); RoleResource role1 = createRole( "filterRole1", Collections.singletonList( priv1.getId() ) ); RoleResource role2 = createRole( "filterRole2", Collections.singletonList( priv2.getId() ) ); RoleResource role3 = createRole( "filterRole3", combined ); // Now update the test user updateUserRole( TEST_USER_NAME, Collections.singletonList( role3.getId() ) ); TestContainer.getInstance().getTestContext().setUsername( TEST_USER_NAME ); TestContainer.getInstance().getTestContext().setPassword( TEST_USER_PASSWORD ); + Thread.sleep( 200 ); // Should be able to see both test1 & test2 artifacts SyndFeed feed = FeedUtil.getFeed( "recentlyDeployed" ); List<SyndEntry> entries = feed.getEntries(); Assert.assertTrue("Feed should contain entry for nexus779:test1:1.0.0.\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test1", "1.0.0" ) ); Assert.assertTrue("Feed should contain entry for nexus779:test2:1.0.0\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test2", "1.0.0" ) ); // Now update the test user so that the user can only access test1 updateUserRole( TEST_USER_NAME, Collections.singletonList( role1.getId() ) ); TestContainer.getInstance().getTestContext().setUsername( TEST_USER_NAME ); TestContainer.getInstance().getTestContext().setPassword( TEST_USER_PASSWORD ); // Should be able to see only test1 artifacts feed = FeedUtil.getFeed( "recentlyDeployed" ); entries = feed.getEntries(); Assert.assertTrue("Feed should contain entry for nexus779:test1:1.0.0.\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test1", "1.0.0" ) ); Assert.assertFalse( "Feed should not contain entry for nexus779:test2:1.0.0\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test2", "1.0.0" ) ); // Now update the test user so that the user can only access test2 updateUserRole( TEST_USER_NAME, Collections.singletonList( role2.getId() ) ); TestContainer.getInstance().getTestContext().setUsername( TEST_USER_NAME ); TestContainer.getInstance().getTestContext().setPassword( TEST_USER_PASSWORD ); // Should be able to see only test2 artifacts feed = FeedUtil.getFeed( "recentlyDeployed" ); entries = feed.getEntries(); Assert.assertFalse("Feed should not contain entry for nexus779:test1:1.0.0.\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test1", "1.0.0" ) ); Assert.assertTrue( "Feed should contain entry for nexus779:test2:1.0.0\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test2", "1.0.0" ) ); } private String entriesToString(List<SyndEntry> entries) { StringBuffer buffer = new StringBuffer(); for ( SyndEntry syndEntry : entries ) { buffer.append( "\n" ).append( syndEntry.getTitle() ); } return buffer.toString(); } private boolean feedListContainsArtifact( List<SyndEntry> entries, String groupId, String artifactId, String version ) { for ( SyndEntry entry : entries ) { if ( entry.getTitle().contains( groupId ) && entry.getTitle().contains( artifactId ) && entry.getTitle().contains( version ) ) { return true; } } return false; } private RepositoryTargetResource createTarget( String name, List<String> patterns ) throws Exception { RepositoryTargetResource resource = new RepositoryTargetResource(); resource.setContentClass( "maven2" ); resource.setName( name ); resource.setPatterns( patterns ); return this.targetUtil.createTarget( resource ); } private PrivilegeTargetStatusResource createPrivilege( String name, String targetId ) throws Exception { PrivilegeTargetResource resource = new PrivilegeTargetResource(); resource.setName( name ); resource.setDescription( "some description" ); resource.setType( "repositoryTarget" ); resource.setRepositoryTargetId( targetId ); resource.addMethod( "read" ); return ( PrivilegeTargetStatusResource ) privUtil.createPrivileges( resource ).iterator().next(); } private RoleResource createRole( String name, List<String> privilegeIds ) throws Exception { RoleResource role = new RoleResource(); role.setName( name ); role.setDescription( "some description" ); role.setSessionTimeout( 60 ); for ( String privilegeId : privilegeIds ) { role.addPrivilege( privilegeId ); } role.addPrivilege( "1" ); role.addPrivilege( "6" ); role.addPrivilege( "14" ); role.addPrivilege( "17" ); role.addPrivilege( "19" ); role.addPrivilege( "44" ); role.addPrivilege( "54" ); role.addPrivilege( "55" ); role.addPrivilege( "56" ); role.addPrivilege( "57" ); role.addPrivilege( "58" ); role.addPrivilege( "64" ); return this.roleUtil.createRole( role ); } private void updateUserRole( String username, List<String> roleIds ) throws Exception { // change to admin so we can update the roles TestContainer.getInstance().getTestContext().useAdminForRequests(); UserResource resource = userUtil.getUser( username ); resource.setRoles( roleIds ); userUtil.updateUser( resource ); } }
true
true
public void filteredFeeds() throws Exception { TestContainer.getInstance().getTestContext().useAdminForRequests(); // First create the targets RepositoryTargetResource test1Target = createTarget( "filterTarget1", Collections.singletonList( ".*/test1/.*" ) ); RepositoryTargetResource test2Target = createTarget( "filterTarget2", Collections.singletonList( ".*/test2/.*" ) ); // Then create the privileges PrivilegeTargetStatusResource priv1 = createPrivilege( "filterPriv1", test1Target.getId() ); PrivilegeTargetStatusResource priv2 = createPrivilege( "filterPriv2", test2Target.getId() ); // Then create the roles List<String> combined = new ArrayList<String>(); combined.add( priv1.getId() ); combined.add( priv2.getId() ); RoleResource role1 = createRole( "filterRole1", Collections.singletonList( priv1.getId() ) ); RoleResource role2 = createRole( "filterRole2", Collections.singletonList( priv2.getId() ) ); RoleResource role3 = createRole( "filterRole3", combined ); // Now update the test user updateUserRole( TEST_USER_NAME, Collections.singletonList( role3.getId() ) ); TestContainer.getInstance().getTestContext().setUsername( TEST_USER_NAME ); TestContainer.getInstance().getTestContext().setPassword( TEST_USER_PASSWORD ); // Should be able to see both test1 & test2 artifacts SyndFeed feed = FeedUtil.getFeed( "recentlyDeployed" ); List<SyndEntry> entries = feed.getEntries(); Assert.assertTrue("Feed should contain entry for nexus779:test1:1.0.0.\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test1", "1.0.0" ) ); Assert.assertTrue("Feed should contain entry for nexus779:test2:1.0.0\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test2", "1.0.0" ) ); // Now update the test user so that the user can only access test1 updateUserRole( TEST_USER_NAME, Collections.singletonList( role1.getId() ) ); TestContainer.getInstance().getTestContext().setUsername( TEST_USER_NAME ); TestContainer.getInstance().getTestContext().setPassword( TEST_USER_PASSWORD ); // Should be able to see only test1 artifacts feed = FeedUtil.getFeed( "recentlyDeployed" ); entries = feed.getEntries(); Assert.assertTrue("Feed should contain entry for nexus779:test1:1.0.0.\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test1", "1.0.0" ) ); Assert.assertFalse( "Feed should not contain entry for nexus779:test2:1.0.0\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test2", "1.0.0" ) ); // Now update the test user so that the user can only access test2 updateUserRole( TEST_USER_NAME, Collections.singletonList( role2.getId() ) ); TestContainer.getInstance().getTestContext().setUsername( TEST_USER_NAME ); TestContainer.getInstance().getTestContext().setPassword( TEST_USER_PASSWORD ); // Should be able to see only test2 artifacts feed = FeedUtil.getFeed( "recentlyDeployed" ); entries = feed.getEntries(); Assert.assertFalse("Feed should not contain entry for nexus779:test1:1.0.0.\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test1", "1.0.0" ) ); Assert.assertTrue( "Feed should contain entry for nexus779:test2:1.0.0\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test2", "1.0.0" ) ); }
public void filteredFeeds() throws Exception { TestContainer.getInstance().getTestContext().useAdminForRequests(); // First create the targets RepositoryTargetResource test1Target = createTarget( "filterTarget1", Collections.singletonList( ".*/test1/.*" ) ); RepositoryTargetResource test2Target = createTarget( "filterTarget2", Collections.singletonList( ".*/test2/.*" ) ); // Then create the privileges PrivilegeTargetStatusResource priv1 = createPrivilege( "filterPriv1", test1Target.getId() ); PrivilegeTargetStatusResource priv2 = createPrivilege( "filterPriv2", test2Target.getId() ); // Then create the roles List<String> combined = new ArrayList<String>(); combined.add( priv1.getId() ); combined.add( priv2.getId() ); RoleResource role1 = createRole( "filterRole1", Collections.singletonList( priv1.getId() ) ); RoleResource role2 = createRole( "filterRole2", Collections.singletonList( priv2.getId() ) ); RoleResource role3 = createRole( "filterRole3", combined ); // Now update the test user updateUserRole( TEST_USER_NAME, Collections.singletonList( role3.getId() ) ); TestContainer.getInstance().getTestContext().setUsername( TEST_USER_NAME ); TestContainer.getInstance().getTestContext().setPassword( TEST_USER_PASSWORD ); Thread.sleep( 200 ); // Should be able to see both test1 & test2 artifacts SyndFeed feed = FeedUtil.getFeed( "recentlyDeployed" ); List<SyndEntry> entries = feed.getEntries(); Assert.assertTrue("Feed should contain entry for nexus779:test1:1.0.0.\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test1", "1.0.0" ) ); Assert.assertTrue("Feed should contain entry for nexus779:test2:1.0.0\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test2", "1.0.0" ) ); // Now update the test user so that the user can only access test1 updateUserRole( TEST_USER_NAME, Collections.singletonList( role1.getId() ) ); TestContainer.getInstance().getTestContext().setUsername( TEST_USER_NAME ); TestContainer.getInstance().getTestContext().setPassword( TEST_USER_PASSWORD ); // Should be able to see only test1 artifacts feed = FeedUtil.getFeed( "recentlyDeployed" ); entries = feed.getEntries(); Assert.assertTrue("Feed should contain entry for nexus779:test1:1.0.0.\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test1", "1.0.0" ) ); Assert.assertFalse( "Feed should not contain entry for nexus779:test2:1.0.0\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test2", "1.0.0" ) ); // Now update the test user so that the user can only access test2 updateUserRole( TEST_USER_NAME, Collections.singletonList( role2.getId() ) ); TestContainer.getInstance().getTestContext().setUsername( TEST_USER_NAME ); TestContainer.getInstance().getTestContext().setPassword( TEST_USER_PASSWORD ); // Should be able to see only test2 artifacts feed = FeedUtil.getFeed( "recentlyDeployed" ); entries = feed.getEntries(); Assert.assertFalse("Feed should not contain entry for nexus779:test1:1.0.0.\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test1", "1.0.0" ) ); Assert.assertTrue( "Feed should contain entry for nexus779:test2:1.0.0\nEntries: "+ this.entriesToString(entries), feedListContainsArtifact( entries, "nexus779", "test2", "1.0.0" ) ); }
diff --git a/src/org/jets3t/service/impl/rest/httpclient/RestS3Service.java b/src/org/jets3t/service/impl/rest/httpclient/RestS3Service.java index c435b00..c710c68 100644 --- a/src/org/jets3t/service/impl/rest/httpclient/RestS3Service.java +++ b/src/org/jets3t/service/impl/rest/httpclient/RestS3Service.java @@ -1,1734 +1,1734 @@ /* * jets3t : Java Extra-Tasty S3 Toolkit (for Amazon S3 online storage service) * This is a java.net project, see https://jets3t.dev.java.net/ * * Copyright 2006 James Murty * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jets3t.service.impl.rest.httpclient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.HttpMethodRetryHandler; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.ProxyHost; import org.apache.commons.httpclient.URI; import org.apache.commons.httpclient.URIException; import org.apache.commons.httpclient.auth.CredentialsProvider; import org.apache.commons.httpclient.contrib.proxy.PluginProxyUtil; import org.apache.commons.httpclient.methods.DeleteMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.HeadMethod; import org.apache.commons.httpclient.methods.InputStreamRequestEntity; import org.apache.commons.httpclient.methods.PutMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jets3t.service.Constants; import org.jets3t.service.Jets3tProperties; import org.jets3t.service.S3ObjectsChunk; import org.jets3t.service.S3Service; import org.jets3t.service.S3ServiceException; import org.jets3t.service.acl.AccessControlList; import org.jets3t.service.impl.rest.HttpException; import org.jets3t.service.impl.rest.XmlResponsesSaxParser; import org.jets3t.service.impl.rest.XmlResponsesSaxParser.CopyObjectResultHandler; import org.jets3t.service.impl.rest.XmlResponsesSaxParser.ListBucketHandler; import org.jets3t.service.io.UnrecoverableIOException; import org.jets3t.service.model.CreateBucketConfiguration; import org.jets3t.service.model.S3Bucket; import org.jets3t.service.model.S3BucketLoggingStatus; import org.jets3t.service.model.S3Object; import org.jets3t.service.security.AWSCredentials; import org.jets3t.service.utils.Mimetypes; import org.jets3t.service.utils.RestUtils; import org.jets3t.service.utils.ServiceUtils; import org.jets3t.service.utils.signedurl.SignedUrlHandler; /** * REST/HTTP implementation of an S3Service based on the * <a href="http://jakarta.apache.org/commons/httpclient/">HttpClient</a> library. * <p> * This class uses properties obtained through {@link Jets3tProperties}. For more information on * these properties please refer to * <a href="http://jets3t.s3.amazonaws.com/toolkit/configuration.html">JetS3t Configuration</a> * </p> * * @author James Murty */ public class RestS3Service extends S3Service implements SignedUrlHandler { private static final long serialVersionUID = 3515978495790107357L; private final Log log = LogFactory.getLog(RestS3Service.class); private static final String PROTOCOL_SECURE = "https"; private static final String PROTOCOL_INSECURE = "http"; private static final int PORT_SECURE = 443; private static final int PORT_INSECURE = 80; private HttpClient httpClient = null; private MultiThreadedHttpConnectionManager connectionManager = null; /** * Constructs the service and initialises the properties. * * @param awsCredentials * the S3 user credentials to use when communicating with S3, may be null in which case the * communication is done as an anonymous user. * * @throws S3ServiceException */ public RestS3Service(AWSCredentials awsCredentials) throws S3ServiceException { this(awsCredentials, null, null); } /** * Constructs the service and initialises the properties. * * @param awsCredentials * the S3 user credentials to use when communicating with S3, may be null in which case the * communication is done as an anonymous user. * @param invokingApplicationDescription * a short description of the application using the service, suitable for inclusion in a * user agent string for REST/HTTP requests. Ideally this would include the application's * version number, for example: <code>Cockpit/0.6.1</code> or <code>My App Name/1.0</code> * @param credentialsProvider * an implementation of the HttpClient CredentialsProvider interface, to provide a means for * prompting for credentials when necessary. * * @throws S3ServiceException */ public RestS3Service(AWSCredentials awsCredentials, String invokingApplicationDescription, CredentialsProvider credentialsProvider) throws S3ServiceException { this(awsCredentials, invokingApplicationDescription, credentialsProvider, Jets3tProperties.getInstance(Constants.JETS3T_PROPERTIES_FILENAME)); } /** * Constructs the service and initialises the properties. * * @param awsCredentials * the S3 user credentials to use when communicating with S3, may be null in which case the * communication is done as an anonymous user. * @param invokingApplicationDescription * a short description of the application using the service, suitable for inclusion in a * user agent string for REST/HTTP requests. Ideally this would include the application's * version number, for example: <code>Cockpit/0.6.1</code> or <code>My App Name/1.0</code> * @param credentialsProvider * an implementation of the HttpClient CredentialsProvider interface, to provide a means for * prompting for credentials when necessary. * @param jets3tProperties * JetS3t properties that will be applied within this service. * * @throws S3ServiceException */ public RestS3Service(AWSCredentials awsCredentials, String invokingApplicationDescription, CredentialsProvider credentialsProvider, Jets3tProperties jets3tProperties) throws S3ServiceException { this(awsCredentials, invokingApplicationDescription, credentialsProvider, jets3tProperties, new HostConfiguration()); } /** * Constructs the service and initialises the properties. * * @param awsCredentials * the S3 user credentials to use when communicating with S3, may be null in which case the * communication is done as an anonymous user. * @param invokingApplicationDescription * a short description of the application using the service, suitable for inclusion in a * user agent string for REST/HTTP requests. Ideally this would include the application's * version number, for example: <code>Cockpit/0.6.1</code> or <code>My App Name/1.0</code> * @param credentialsProvider * an implementation of the HttpClient CredentialsProvider interface, to provide a means for * prompting for credentials when necessary. * @param jets3tProperties * JetS3t properties that will be applied within this service. * @param hostConfig * Custom HTTP host configuration; e.g to register a custom Protocol Socket Factory * * @throws S3ServiceException */ public RestS3Service(AWSCredentials awsCredentials, String invokingApplicationDescription, CredentialsProvider credentialsProvider, Jets3tProperties jets3tProperties, HostConfiguration hostConfig) throws S3ServiceException { super(awsCredentials, invokingApplicationDescription, jets3tProperties); // Configure HttpClient properties based on Jets3t Properties. HttpConnectionManagerParams connectionParams = new HttpConnectionManagerParams(); connectionParams.setConnectionTimeout(jets3tProperties. getIntProperty("httpclient.connection-timeout-ms", 60000)); connectionParams.setSoTimeout(jets3tProperties. getIntProperty("httpclient.socket-timeout-ms", 60000)); connectionParams.setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, jets3tProperties.getIntProperty("httpclient.max-connections", 4)); connectionParams.setStaleCheckingEnabled(jets3tProperties. getBoolProperty("httpclient.stale-checking-enabled", true)); // Connection properties to take advantage of S3 window scaling. if (jets3tProperties.containsKey("httpclient.socket-receive-buffer")) { connectionParams.setReceiveBufferSize(jets3tProperties. getIntProperty("httpclient.socket-receive-buffer", 0)); } if (jets3tProperties.containsKey("httpclient.socket-send-buffer")) { connectionParams.setSendBufferSize(jets3tProperties. getIntProperty("httpclient.socket-send-buffer", 0)); } connectionParams.setTcpNoDelay(true); connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.setParams(connectionParams); // Set user agent string. HttpClientParams clientParams = new HttpClientParams(); String userAgent = jets3tProperties.getStringProperty("httpclient.useragent", null); if (userAgent == null) { userAgent = ServiceUtils.getUserAgentDescription( getInvokingApplicationDescription()); } log.debug("Setting user agent string: " + userAgent); clientParams.setParameter(HttpMethodParams.USER_AGENT, userAgent); clientParams.setBooleanParameter("http.protocol.expect-continue", true); // Replace default error retry handler. final int retryMaxCount = jets3tProperties.getIntProperty("httpclient.retry-max", 5); clientParams.setParameter(HttpClientParams.RETRY_HANDLER, new HttpMethodRetryHandler() { public boolean retryMethod(HttpMethod httpMethod, IOException ioe, int executionCount) { if (executionCount > retryMaxCount) { log.warn("Retried connection " + executionCount + " times, which exceeds the maximum retry count of " + retryMaxCount); return false; } if (ioe instanceof UnrecoverableIOException) { log.debug("Deliberate interruption, will not retry"); return false; } log.warn("Retrying " + httpMethod.getName() + " request with path '" + httpMethod.getPath() + "' - attempt " + executionCount + " of " + retryMaxCount); // Build the authorization string for the method. try { buildAuthorizationString(httpMethod); } catch (S3ServiceException e) { log.warn("Unable to generate updated authorization string for retried request", e); } return true; } }); httpClient = new HttpClient(clientParams, connectionManager); httpClient.setHostConfiguration(hostConfig); // Retrieve Proxy settings. boolean proxyAutodetect = jets3tProperties.getBoolProperty("httpclient.proxy-autodetect", true); String proxyHostAddress = jets3tProperties.getStringProperty("httpclient.proxy-host", null); int proxyPort = jets3tProperties.getIntProperty("httpclient.proxy-port", -1); // Use explicit proxy settings, if available. if (proxyHostAddress != null && proxyPort != -1) { log.info("Using Proxy: " + proxyHostAddress + ":" + proxyPort); hostConfig.setProxy(proxyHostAddress, proxyPort); } // If no explicit settings are available, try autodetecting proxies (unless autodetect is disabled) else if (proxyAutodetect) { // Try to detect any proxy settings from applet. ProxyHost proxyHost = null; try { proxyHost = PluginProxyUtil.detectProxy(new URL("http://" + Constants.S3_HOSTNAME)); if (proxyHost != null) { log.info("Using Proxy: " + proxyHost.getHostName() + ":" + proxyHost.getPort()); hostConfig.setProxyHost(proxyHost); } } catch (Throwable t) { log.debug("Unable to set proxy configuration", t); } } if (credentialsProvider != null) { log.debug("Using credentials provider class: " + credentialsProvider.getClass().getName()); httpClient.getParams().setParameter(CredentialsProvider.PROVIDER, credentialsProvider); if (jets3tProperties.getBoolProperty("httpclient.authentication-preemptive", false)) { httpClient.getParams().setAuthenticationPreemptive(true); } } } /** * Performs an HTTP/S request by invoking the provided HttpMethod object. If the HTTP * response code doesn't match the expected value, an exception is thrown. * * @param httpMethod * the object containing a request target and all other information necessary to perform the * request * @param expectedResponseCode * the HTTP response code that indicates a successful request. If the response code received * does not match this value an error must have occurred, so an exception is thrown. * @throws S3ServiceException * all exceptions are wrapped in an S3ServiceException. Depending on the kind of error that * occurred, this exception may contain additional error information available from an XML * error response document. */ protected void performRequest(HttpMethodBase httpMethod, int expectedResponseCode) throws S3ServiceException { try { log.debug("Performing " + httpMethod.getName() + " request for '" + httpMethod.getURI().toString() + "', expecting response code " + expectedResponseCode); - // Variables to manage S3 Internal Server 500 errors. + // Variables to manage S3 Internal Server 500 or 503 Service Unavailable errors. boolean completedWithoutRecoverableError = true; int internalErrorCount = 0; int requestTimeoutErrorCount = 0; int redirectCount = 0; boolean wasRecentlyRedirected = false; // Perform the request, sleeping and retrying when S3 Internal Errors are encountered. int responseCode = -1; do { // Build the authorization string for the method (Unless we have just been redirected). if (!wasRecentlyRedirected) { buildAuthorizationString(httpMethod); } else { // Reset redirection flag wasRecentlyRedirected = false; } responseCode = httpClient.executeMethod(httpMethod); if (responseCode == 307) { // Retry on Temporary Redirects, using new URI from location header Header locationHeader = httpMethod.getResponseHeader("location"); httpMethod.setURI(new URI(locationHeader.getValue(), true)); completedWithoutRecoverableError = false; redirectCount++; wasRecentlyRedirected = true; if (redirectCount > 5) { throw new S3ServiceException("Encountered too many 307 Redirects, aborting request."); } - } else if (responseCode == 500) { - // Retry on S3 Internal Server 500 errors. + } else if (responseCode == 500 || responseCode == 503) { + // Retry on S3 Internal Server 500 or 503 Service Unavailable erros. completedWithoutRecoverableError = false; sleepOnInternalError(++internalErrorCount); } else { completedWithoutRecoverableError = true; } String contentType = ""; if (httpMethod.getResponseHeader("Content-Type") != null) { contentType = httpMethod.getResponseHeader("Content-Type").getValue(); } log.debug("Response for '" + httpMethod.getPath() + "'. Content-Type: " + contentType + ", Headers: " + Arrays.asList(httpMethod.getResponseHeaders())); // Check we received the expected result code. if (responseCode != expectedResponseCode) { log.warn("Response '" + httpMethod.getPath() + "' - Unexpected response code " + responseCode + ", expected " + expectedResponseCode); if (Mimetypes.MIMETYPE_XML.equals(contentType) && httpMethod.getResponseBodyAsStream() != null && httpMethod.getResponseContentLength() != 0) { log.warn("Response '" + httpMethod.getPath() + "' - Received error response with XML message"); StringBuffer sb = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader( new HttpMethodReleaseInputStream(httpMethod))); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } finally { if (reader != null) { reader.close(); } } httpMethod.releaseConnection(); // Throw exception containing the XML message document. S3ServiceException exception = new S3ServiceException("S3 " + httpMethod.getName() + " failed for '" + httpMethod.getPath() + "'", sb.toString()); if ("RequestTimeout".equals(exception.getS3ErrorCode())) { int retryMaxCount = jets3tProperties.getIntProperty("httpclient.retry-max", 5); if (requestTimeoutErrorCount < retryMaxCount) { requestTimeoutErrorCount++; log.warn("Response '" + httpMethod.getPath() + "' - Retrying connection that failed with RequestTimeout error" + ", attempt number " + requestTimeoutErrorCount + " of " + retryMaxCount); completedWithoutRecoverableError = false; } else { log.warn("Response '" + httpMethod.getPath() + "' - Exceeded maximum number of retries for RequestTimeout errors: " + retryMaxCount); throw exception; } } else if ("RequestTimeTooSkewed".equals(exception.getS3ErrorCode())) { long timeDifferenceMS = adjustTime(); log.warn("Adjusted time offset in response to RequestTimeTooSkewed error. " + "Local machine and S3 server disagree on the time by approximately " + (timeDifferenceMS / 1000) + " seconds. Retrying connection."); completedWithoutRecoverableError = false; - } else if (responseCode == 500) { - // Retrying after InternalError 500, don't throw exception. + } else if (responseCode == 500 || responseCode == 503) { + // Retrying after 500 or 503 error, don't throw exception. } else if (responseCode == 307) { // Retrying after Temporary Redirect 307, don't throw exception. log.debug("Following Temporary Redirect to: " + httpMethod.getURI().toString()); } else { throw exception; } } else { // Consume response content and release connection. String responseText = null; byte[] responseBody = httpMethod.getResponseBody(); if (responseBody != null && responseBody.length > 0) { responseText = new String(responseBody); } log.debug("Releasing error response without XML content"); httpMethod.releaseConnection(); - if (responseCode == 500) { + if (responseCode == 500 || responseCode == 503) { // Retrying after InternalError 500, don't throw exception. } else { // Throw exception containing the HTTP error fields. HttpException httpException = new HttpException( httpMethod.getStatusCode(), httpMethod.getStatusText()); S3ServiceException exception = new S3ServiceException("S3 " + httpMethod.getName() + " request failed for '" + httpMethod.getPath() + "' - " + "ResponseCode=" + httpMethod.getStatusCode() + ", ResponseMessage=" + httpMethod.getStatusText() + (responseText != null ? "\n" + responseText : ""), httpException); exception.setResponseCode(httpMethod.getStatusCode()); exception.setResponseStatus(httpMethod.getStatusText()); throw exception; } } } } while (!completedWithoutRecoverableError); // Release immediately any connections without response bodies. if ((httpMethod.getResponseBodyAsStream() == null || httpMethod.getResponseBodyAsStream().available() == 0) && httpMethod.getResponseContentLength() == 0) { log.debug("Releasing response without content"); byte[] responseBody = httpMethod.getResponseBody(); if (responseBody != null && responseBody.length > 0) throw new S3ServiceException("Oops, too keen to release connection with a non-empty response body"); httpMethod.releaseConnection(); } } catch (Throwable t) { log.debug("Releasing HttpClient connection after error: " + t.getMessage()); httpMethod.releaseConnection(); if (t instanceof S3ServiceException) { throw (S3ServiceException) t; } else { throw new S3ServiceException("S3 " + httpMethod.getName() + " connection failed for '" + httpMethod.getPath() + "'", t); } } } /** * Adds all the provided request parameters to a URL in GET request format. * * @param urlPath * the target URL * @param requestParameters * the parameters to add to the URL as GET request params. * @return * the target URL including the parameters. * @throws S3ServiceException */ protected String addRequestParametersToUrlPath(String urlPath, Map requestParameters) throws S3ServiceException { if (requestParameters != null) { Iterator reqPropIter = requestParameters.entrySet().iterator(); while (reqPropIter.hasNext()) { Map.Entry entry = (Map.Entry) reqPropIter.next(); Object key = entry.getKey(); Object value = entry.getValue(); urlPath += (urlPath.indexOf("?") < 0? "?" : "&") + RestUtils.encodeUrlString(key.toString()); if (value != null && value.toString().length() > 0) { urlPath += "=" + RestUtils.encodeUrlString(value.toString()); log.debug("Added request parameter: " + key + "=" + value); } else { log.debug("Added request parameter without value: " + key); } } } return urlPath; } /** * Adds the provided request headers to the connection. * * @param httpMethod * the connection object * @param requestHeaders * the request headers to add as name/value pairs. */ protected void addRequestHeadersToConnection( HttpMethodBase httpMethod, Map requestHeaders) { if (requestHeaders != null) { Iterator reqHeaderIter = requestHeaders.entrySet().iterator(); while (reqHeaderIter.hasNext()) { Map.Entry entry = (Map.Entry) reqHeaderIter.next(); String key = entry.getKey().toString(); String value = entry.getValue().toString(); httpMethod.setRequestHeader(key, value); log.debug("Added request header to connection: " + key + "=" + value); } } } /** * Converts an array of Header objects to a map of name/value pairs. * * @param headers * @return */ private Map convertHeadersToMap(Header[] headers) { HashMap map = new HashMap(); for (int i = 0; headers != null && i < headers.length; i++) { map.put(headers[i].getName(), headers[i].getValue()); } return map; } /** * Adds all appropriate metadata to the given HTTP method. * * @param httpMethod * @param metadata */ private void addMetadataToHeaders(HttpMethodBase httpMethod, Map metadata) { Iterator metaDataIter = metadata.entrySet().iterator(); while (metaDataIter.hasNext()) { Map.Entry entry = (Map.Entry) metaDataIter.next(); String key = (String) entry.getKey(); Object value = entry.getValue(); if (key == null || !(value instanceof String)) { // Ignore invalid metadata. continue; } httpMethod.setRequestHeader(key, (String) value); } } /** * Performs an HTTP HEAD request using the {@link #performRequest} method. * * @param bucketName * the bucket's name * @param objectKey * the object's key name, may be null if the operation is on a bucket only. * @param requestParameters * parameters to add to the request URL as GET params * @param requestHeaders * headers to add to the request * @return * the HTTP method object used to perform the request * @throws S3ServiceException */ protected HttpMethodBase performRestHead(String bucketName, String objectKey, Map requestParameters, Map requestHeaders) throws S3ServiceException { HttpMethodBase httpMethod = setupConnection("HEAD", bucketName, objectKey, requestParameters); // Add all request headers. addRequestHeadersToConnection(httpMethod, requestHeaders); performRequest(httpMethod, 200); return httpMethod; } /** * Performs an HTTP GET request using the {@link #performRequest} method. * * @param bucketName * the bucket's name * @param objectKey * the object's key name, may be null if the operation is on a bucket only. * @param requestParameters * parameters to add to the request URL as GET params * @param requestHeaders * headers to add to the request * @return * The HTTP method object used to perform the request. * * @throws S3ServiceException */ protected HttpMethodBase performRestGet(String bucketName, String objectKey, Map requestParameters, Map requestHeaders) throws S3ServiceException { HttpMethodBase httpMethod = setupConnection("GET", bucketName, objectKey, requestParameters); // Add all request headers. addRequestHeadersToConnection(httpMethod, requestHeaders); int expectedStatusCode = 200; if (requestHeaders != null && requestHeaders.containsKey("Range")) { // Partial data responses have a status code of 206. expectedStatusCode = 206; } performRequest(httpMethod, expectedStatusCode); return httpMethod; } /** * Performs an HTTP PUT request using the {@link #performRequest} method. * * @param bucketName * the name of the bucket the object will be stored in. * @param objectKey * the key (name) of the object to be stored. * @param metadata * map of name/value pairs to add as metadata to any S3 objects created. * @param requestParameters * parameters to add to the request URL as GET params * @param requestEntity * an HttpClient object that encapsulates the object and data contents that will be * uploaded. This object supports the resending of object data, when possible. * @param autoRelease * if true, the HTTP Method object will be released after the request has * completed and the connection will be closed. If false, the object will * not be released and the caller must take responsibility for doing this. * @return * a package including the HTTP method object used to perform the request, and the * content length (in bytes) of the object that was PUT to S3. * * @throws S3ServiceException */ protected HttpMethodAndByteCount performRestPut(String bucketName, String objectKey, Map metadata, Map requestParameters, RequestEntity requestEntity, boolean autoRelease) throws S3ServiceException { // Add any request parameters. HttpMethodBase httpMethod = setupConnection("PUT", bucketName, objectKey, requestParameters); Map renamedMetadata = RestUtils.renameMetadataKeys(metadata); addMetadataToHeaders(httpMethod, renamedMetadata); long contentLength = 0; if (requestEntity != null) { ((PutMethod)httpMethod).setRequestEntity(requestEntity); } else { // Need an explicit Content-Length even if no data is being uploaded. httpMethod.setRequestHeader("Content-Length", "0"); } performRequest(httpMethod, 200); if (requestEntity != null) { // Respond with the actual guaranteed content length of the uploaded data. contentLength = ((PutMethod)httpMethod).getRequestEntity().getContentLength(); } if (autoRelease) { httpMethod.releaseConnection(); } return new HttpMethodAndByteCount(httpMethod, contentLength); } /** * Performs an HTTP DELETE request using the {@link #performRequest} method. * * @param bucketName * the bucket's name * @param objectKey * the object's key name, may be null if the operation is on a bucket only. * @return * The HTTP method object used to perform the request. * * @throws S3ServiceException */ protected HttpMethodBase performRestDelete(String bucketName, String objectKey) throws S3ServiceException { HttpMethodBase httpMethod = setupConnection("DELETE", bucketName, objectKey, null); performRequest(httpMethod, 204); // Release connection after DELETE (there's no response content) log.debug("Releasing HttpMethod after delete"); httpMethod.releaseConnection(); return httpMethod; } /** * Creates an {@link HttpMethod} object to handle a particular connection method. * * @param method * the HTTP method/connection-type to use, must be one of: PUT, HEAD, GET, DELETE * @param bucketName * the bucket's name * @param objectKey * the object's key name, may be null if the operation is on a bucket only. * @return * the HTTP method object used to perform the request * * @throws S3ServiceException */ protected HttpMethodBase setupConnection(String method, String bucketName, String objectKey, Map requestParameters) throws S3ServiceException { if (bucketName == null) { throw new S3ServiceException("Cannot connect to S3 Service with a null path"); } String hostname = generateS3HostnameForBucket(bucketName); // Determine the resource string (ie the item's path in S3, including the bucket name) String resourceString = "/"; if (hostname.equals(Constants.S3_HOSTNAME) && bucketName != null && bucketName.length() > 0) { resourceString += bucketName + "/"; } resourceString += (objectKey != null? RestUtils.encodeUrlString(objectKey) : ""); // Construct a URL representing a connection for the S3 resource. String url = null; if (isHttpsOnly()) { url = PROTOCOL_SECURE + "://" + hostname + ":" + PORT_SECURE + resourceString; } else { url = PROTOCOL_INSECURE + "://" + hostname + ":" + PORT_INSECURE + resourceString; } log.debug("S3 URL: " + url); // Add additional request parameters to the URL for special cases (eg ACL operations) url = addRequestParametersToUrlPath(url, requestParameters); HttpMethodBase httpMethod = null; if ("PUT".equals(method)) { httpMethod = new PutMethod(url); } else if ("HEAD".equals(method)) { httpMethod = new HeadMethod(url); } else if ("GET".equals(method)) { httpMethod = new GetMethod(url); } else if ("DELETE".equals(method)) { httpMethod = new DeleteMethod(url); } else { throw new IllegalArgumentException("Unrecognised HTTP method name: " + method); } // Set mandatory Request headers. if (httpMethod.getRequestHeader("Date") == null) { httpMethod.setRequestHeader("Date", ServiceUtils.formatRfc822Date( getCurrentTimeWithOffset())); } if (httpMethod.getRequestHeader("Content-Type") == null) { httpMethod.setRequestHeader("Content-Type", ""); } // Set DevPay request headers. if (getDevPayUserToken() != null || getDevPayProductToken() != null) { // DevPay tokens have been provided, include these with the request. if (getDevPayProductToken() != null) { String securityToken = getDevPayUserToken() + "," + getDevPayProductToken(); httpMethod.setRequestHeader("x-amz-security-token", securityToken); log.debug("Including DevPay user and product tokens in request: " + "x-amz-security-token=" + securityToken); } else { httpMethod.setRequestHeader("x-amz-security-token", getDevPayUserToken()); log.debug("Including DevPay user token in request: x-amz-security-token=" + getDevPayUserToken()); } } return httpMethod; } /** * Authorizes an HTTP request by signing it. The signature is based on the target URL, and the * signed authorization string is added to the {@link HttpMethod} object as an Authorization header. * * @param httpMethod * the request object * @throws S3ServiceException */ protected void buildAuthorizationString(HttpMethod httpMethod) throws S3ServiceException { if (isAuthenticatedConnection()) { log.debug("Adding authorization for AWS Access Key '" + getAWSCredentials().getAccessKey() + "'."); } else { log.debug("Service has no AWS Credential and is un-authenticated, skipping authorization"); return; } String hostname = null; try { hostname = httpMethod.getURI().getHost(); } catch (URIException e) { log.error("Unable to determine hostname target for request", e); } /* * Determine the complete URL for the S3 resource, including any S3-specific parameters. */ String fullUrl = httpMethod.getPath(); // If we are using an alternative hostname, include the hostname/bucketname in the resource path. if (!Constants.S3_HOSTNAME.equals(hostname)) { int subdomainOffset = hostname.indexOf("." + Constants.S3_HOSTNAME); if (subdomainOffset > 0) { // Hostname represents an S3 sub-domain, so the bucket's name is the CNAME portion fullUrl = "/" + hostname.substring(0, subdomainOffset) + httpMethod.getPath(); } else { // Hostname represents a virtual host, so the bucket's name is identical to hostname fullUrl = "/" + hostname + httpMethod.getPath(); } } String queryString = httpMethod.getQueryString(); if (queryString != null && queryString.length() > 0) { fullUrl += "?" + queryString; } // Set/update the date timestamp to the current time // Note that this will be over-ridden if an "x-amz-date" header is present. httpMethod.setRequestHeader("Date", ServiceUtils.formatRfc822Date( getCurrentTimeWithOffset())); // Generate a canonical string representing the operation. String canonicalString = RestUtils.makeCanonicalString( httpMethod.getName(), fullUrl, convertHeadersToMap(httpMethod.getRequestHeaders()), null); log.debug("Canonical string ('|' is a newline): " + canonicalString.replace('\n', '|')); // Sign the canonical string. String signedCanonical = ServiceUtils.signWithHmacSha1( getAWSCredentials().getSecretKey(), canonicalString); // Add encoded authorization to connection as HTTP Authorization header. String authorizationString = "AWS " + getAWSCredentials().getAccessKey() + ":" + signedCanonical; httpMethod.setRequestHeader("Authorization", authorizationString); } //////////////////////////////////////////////////////////////// // Methods below this point implement S3Service abstract methods //////////////////////////////////////////////////////////////// public boolean isBucketAccessible(String bucketName) throws S3ServiceException { log.debug("Checking existence of bucket: " + bucketName); HttpMethodBase httpMethod = null; // This request may return an XML document that we're not interested in. Clean this up. try { // Ensure bucket exists and is accessible by performing a HEAD request httpMethod = performRestHead(bucketName, null, null, null); if (httpMethod.getResponseBodyAsStream() != null) { httpMethod.getResponseBodyAsStream().close(); } } catch (S3ServiceException e) { log.debug("Bucket does not exist: " + bucketName, e); return false; } catch (IOException e) { log.warn("Unable to close response body input stream", e); } finally { log.debug("Releasing un-wanted bucket HEAD response"); if (httpMethod != null) { httpMethod.releaseConnection(); } } // If we get this far, the bucket exists. return true; } public int checkBucketStatus(String bucketName) throws S3ServiceException { log.debug("Checking availability of bucket name: " + bucketName); HttpMethodBase httpMethod = null; // This request may return an XML document that we're not interested in. Clean this up. try { // Test bucket's status by performing a HEAD request against it. HashMap params = new HashMap(); params.put("max-keys", "0"); httpMethod = performRestHead(bucketName, null, params, null); if (httpMethod.getResponseBodyAsStream() != null) { httpMethod.getResponseBodyAsStream().close(); } } catch (S3ServiceException e) { if (e.getResponseCode() == 403) { log.debug("Bucket named '" + bucketName + "' already belongs to another S3 user"); return BUCKET_STATUS__ALREADY_CLAIMED; } else if (e.getResponseCode() == 404) { log.debug("Bucket does not exist: " + bucketName, e); return BUCKET_STATUS__DOES_NOT_EXIST; } else { throw e; } } catch (IOException e) { log.warn("Unable to close response body input stream", e); } finally { log.debug("Releasing un-wanted bucket HEAD response"); if (httpMethod != null) { httpMethod.releaseConnection(); } } // If we get this far, the bucket exists and you own it. return BUCKET_STATUS__MY_BUCKET; } protected S3Bucket[] listAllBucketsImpl() throws S3ServiceException { log.debug("Listing all buckets for AWS user: " + getAWSCredentials().getAccessKey()); String bucketName = ""; // Root path of S3 service lists the user's buckets. HttpMethodBase httpMethod = performRestGet(bucketName, null, null, null); String contentType = httpMethod.getResponseHeader("Content-Type").getValue(); if (!Mimetypes.MIMETYPE_XML.equals(contentType)) { throw new S3ServiceException("Expected XML document response from S3 but received content type " + contentType); } S3Bucket[] buckets = (new XmlResponsesSaxParser()).parseListMyBucketsResponse( new HttpMethodReleaseInputStream(httpMethod)).getBuckets(); return buckets; } protected S3Object[] listObjectsImpl(String bucketName, String prefix, String delimiter, long maxListingLength) throws S3ServiceException { return listObjectsInternal(bucketName, prefix, delimiter, maxListingLength, true, null) .getObjects(); } protected S3ObjectsChunk listObjectsChunkedImpl(String bucketName, String prefix, String delimiter, long maxListingLength, String priorLastKey, boolean completeListing) throws S3ServiceException { return listObjectsInternal(bucketName, prefix, delimiter, maxListingLength, completeListing, priorLastKey); } protected S3ObjectsChunk listObjectsInternal(String bucketName, String prefix, String delimiter, long maxListingLength, boolean automaticallyMergeChunks, String priorLastKey) throws S3ServiceException { HashMap parameters = new HashMap(); if (prefix != null) { parameters.put("prefix", prefix); } if (delimiter != null) { parameters.put("delimiter", delimiter); } if (maxListingLength > 0) { parameters.put("max-keys", String.valueOf(maxListingLength)); } ArrayList objects = new ArrayList(); ArrayList commonPrefixes = new ArrayList(); boolean incompleteListing = true; int ioErrorRetryCount = 0; while (incompleteListing) { if (priorLastKey != null) { parameters.put("marker", priorLastKey); } else { parameters.remove("marker"); } HttpMethodBase httpMethod = performRestGet(bucketName, null, parameters, null); ListBucketHandler listBucketHandler = null; try { listBucketHandler = (new XmlResponsesSaxParser()) .parseListBucketObjectsResponse( new HttpMethodReleaseInputStream(httpMethod)); ioErrorRetryCount = 0; } catch (S3ServiceException e) { if (e.getCause() instanceof IOException && ioErrorRetryCount < 5) { ioErrorRetryCount++; log.warn("Retrying bucket listing failure due to IO error", e); continue; } else { throw e; } } S3Object[] partialObjects = listBucketHandler.getObjects(); log.debug("Found " + partialObjects.length + " objects in one batch"); objects.addAll(Arrays.asList(partialObjects)); String[] partialCommonPrefixes = listBucketHandler.getCommonPrefixes(); log.debug("Found " + partialCommonPrefixes.length + " common prefixes in one batch"); commonPrefixes.addAll(Arrays.asList(partialCommonPrefixes)); incompleteListing = listBucketHandler.isListingTruncated(); if (incompleteListing) { priorLastKey = listBucketHandler.getMarkerForNextListing(); log.debug("Yet to receive complete listing of bucket contents, " + "last key for prior chunk: " + priorLastKey); } else { priorLastKey = null; } if (!automaticallyMergeChunks) break; } if (automaticallyMergeChunks) { log.debug("Found " + objects.size() + " objects in total"); return new S3ObjectsChunk( prefix, delimiter, (S3Object[]) objects.toArray(new S3Object[objects.size()]), (String[]) commonPrefixes.toArray(new String[commonPrefixes.size()]), null); } else { return new S3ObjectsChunk( prefix, delimiter, (S3Object[]) objects.toArray(new S3Object[objects.size()]), (String[]) commonPrefixes.toArray(new String[commonPrefixes.size()]), priorLastKey); } } protected void deleteObjectImpl(String bucketName, String objectKey) throws S3ServiceException { performRestDelete(bucketName, objectKey); } protected AccessControlList getObjectAclImpl(String bucketName, String objectKey) throws S3ServiceException { log.debug("Retrieving Access Control List for bucketName=" + bucketName + ", objectKkey=" + objectKey); HashMap requestParameters = new HashMap(); requestParameters.put("acl",""); HttpMethodBase httpMethod = performRestGet(bucketName, objectKey, requestParameters, null); return (new XmlResponsesSaxParser()).parseAccessControlListResponse( new HttpMethodReleaseInputStream(httpMethod)).getAccessControlList(); } protected AccessControlList getBucketAclImpl(String bucketName) throws S3ServiceException { log.debug("Retrieving Access Control List for Bucket: " + bucketName); HashMap requestParameters = new HashMap(); requestParameters.put("acl",""); HttpMethodBase httpMethod = performRestGet(bucketName, null, requestParameters, null); return (new XmlResponsesSaxParser()).parseAccessControlListResponse( new HttpMethodReleaseInputStream(httpMethod)).getAccessControlList(); } protected void putObjectAclImpl(String bucketName, String objectKey, AccessControlList acl) throws S3ServiceException { putAclImpl(bucketName, objectKey, acl); } protected void putBucketAclImpl(String bucketName, AccessControlList acl) throws S3ServiceException { String fullKey = bucketName; putAclImpl(fullKey, null, acl); } protected void putAclImpl(String bucketName, String objectKey, AccessControlList acl) throws S3ServiceException { log.debug("Setting Access Control List for bucketName=" + bucketName + ", objectKey=" + objectKey); HashMap requestParameters = new HashMap(); requestParameters.put("acl",""); HashMap metadata = new HashMap(); metadata.put("Content-Type", "text/plain"); try { String aclAsXml = acl.toXml(); metadata.put("Content-Length", String.valueOf(aclAsXml.length())); performRestPut(bucketName, objectKey, metadata, requestParameters, new StringRequestEntity(aclAsXml, "text/plain", Constants.DEFAULT_ENCODING), true); } catch (UnsupportedEncodingException e) { throw new S3ServiceException("Unable to encode ACL XML document", e); } } protected S3Bucket createBucketImpl(String bucketName, String location, AccessControlList acl) throws S3ServiceException { log.debug("Creating bucket with name: " + bucketName); HashMap metadata = new HashMap(); RequestEntity requestEntity = null; if (location != null && !"US".equalsIgnoreCase(location)) { metadata.put("Content-Type", "text/xml"); try { CreateBucketConfiguration config = new CreateBucketConfiguration(location); metadata.put("Content-Length", String.valueOf(config.toXml().length())); requestEntity = new StringRequestEntity(config.toXml(), "text/xml", Constants.DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { throw new S3ServiceException("Unable to encode CreateBucketConfiguration XML document", e); } } Map map = createObjectImpl(bucketName, null, null, requestEntity, metadata, acl); S3Bucket bucket = new S3Bucket(bucketName, location); bucket.setAcl(acl); bucket.replaceAllMetadata(map); return bucket; } protected void deleteBucketImpl(String bucketName) throws S3ServiceException { performRestDelete(bucketName, null); } /** * Beware of high memory requirements when creating large S3 objects when the Content-Length * is not set in the object. */ protected S3Object putObjectImpl(String bucketName, S3Object object) throws S3ServiceException { log.debug("Creating Object with key " + object.getKey() + " in bucket " + bucketName); RequestEntity requestEntity = null; if (object.getDataInputStream() != null) { if (object.containsMetadata("Content-Length")) { log.debug("Uploading object data with Content-Length: " + object.getContentLength()); requestEntity = new RepeatableRequestEntity(object.getKey(), object.getDataInputStream(), object.getContentType(), object.getContentLength()); } else { // Use InputStreamRequestEntity for objects with an unknown content length, as the // entity will cache the results and doesn't need to know the data length in advance. log.warn("Content-Length of data stream not set, will automatically determine data length in memory"); requestEntity = new InputStreamRequestEntity( object.getDataInputStream(), InputStreamRequestEntity.CONTENT_LENGTH_AUTO); } } Map map = createObjectImpl(bucketName, object.getKey(), object.getContentType(), requestEntity, object.getMetadataMap(), object.getAcl()); try { object.closeDataInputStream(); } catch (IOException e) { log.warn("Unable to close data input stream for object '" + object.getKey() + "'", e); } // Populate object with result metadata. object.replaceAllMetadata(map); // Confirm that the data was not corrupted in transit by checking S3's calculated // hash value with the locally computed value. This is only necessary if the user // did not provide a Content-MD5 header with the original object. // Note that we can only confirm the data if we used a RepeatableRequestEntity to // upload it, if the user did not provide a content length with the original // object we are SOL. if (object.getMetadata(S3Object.METADATA_HEADER_CONTENT_MD5) == null) { if (requestEntity instanceof RepeatableRequestEntity) { // Obtain locally-calculated MD5 hash from request entity. String hexMD5OfUploadedData = ServiceUtils.toHex( ((RepeatableRequestEntity)requestEntity).getMD5DigestOfData()); // Compare our locally-calculated hash with the ETag returned by S3. if (!object.getETag().equals(hexMD5OfUploadedData)) { throw new S3ServiceException("Mismatch between MD5 hash of uploaded data (" + hexMD5OfUploadedData + ") and ETag returned by S3 (" + object.getETag() + ")"); } } } return object; } protected Map createObjectImpl(String bucketName, String objectKey, String contentType, RequestEntity requestEntity, Map metadata, AccessControlList acl) throws S3ServiceException { if (metadata == null) { metadata = new HashMap(); } else { // Use a new map object in case the one we were provided is immutable. metadata = new HashMap(metadata); } if (contentType != null) { metadata.put("Content-Type", contentType); } else { metadata.put("Content-Type", Mimetypes.MIMETYPE_OCTET_STREAM); } boolean putNonStandardAcl = false; if (acl != null) { if (AccessControlList.REST_CANNED_PRIVATE.equals(acl)) { metadata.put(Constants.REST_HEADER_PREFIX + "acl", "private"); } else if (AccessControlList.REST_CANNED_PUBLIC_READ.equals(acl)) { metadata.put(Constants.REST_HEADER_PREFIX + "acl", "public-read"); } else if (AccessControlList.REST_CANNED_PUBLIC_READ_WRITE.equals(acl)) { metadata.put(Constants.REST_HEADER_PREFIX + "acl", "public-read-write"); } else if (AccessControlList.REST_CANNED_AUTHENTICATED_READ.equals(acl)) { metadata.put(Constants.REST_HEADER_PREFIX + "acl", "authenticated-read"); } else { putNonStandardAcl = true; } } log.debug("Creating object bucketName=" + bucketName + ", objectKey=" + objectKey + "." + " Content-Type=" + metadata.get("Content-Type") + " Including data? " + (requestEntity != null) + " Metadata: " + metadata + " ACL: " + acl ); HttpMethodAndByteCount methodAndByteCount = performRestPut( bucketName, objectKey, metadata, null, requestEntity, true); // Consume response content. HttpMethodBase httpMethod = methodAndByteCount.getHttpMethod(); Map map = new HashMap(); map.putAll(metadata); // Keep existing metadata. map.putAll(convertHeadersToMap(httpMethod.getResponseHeaders())); map.put(S3Object.METADATA_HEADER_CONTENT_LENGTH, String.valueOf(methodAndByteCount.getByteCount())); map = ServiceUtils.cleanRestMetadataMap(map); if (putNonStandardAcl) { log.debug("Creating object with a non-canned ACL using REST, so an extra ACL Put is required"); putAclImpl(bucketName, objectKey, acl); } return map; } protected Map copyObjectImpl(String sourceBucketName, String sourceObjectKey, String destinationBucketName, String destinationObjectKey, AccessControlList acl, Map destinationMetadata) throws S3ServiceException { log.debug("Copying Object from " + sourceBucketName + ":" + sourceObjectKey + " to " + destinationBucketName + ":" + destinationObjectKey); Map metadata = new HashMap(); metadata.put("x-amz-copy-source", RestUtils.encodeUrlString(sourceBucketName + "/" + sourceObjectKey)); if (destinationMetadata != null) { metadata.put("x-amz-metadata-directive", "REPLACE"); // Include any metadata provided with S3 object. metadata.putAll(destinationMetadata); // Set default content type. if (!metadata.containsKey("Content-Type")) { metadata.put("Content-Type", Mimetypes.MIMETYPE_OCTET_STREAM); } } else { metadata.put("x-amz-metadata-directive", "COPY"); } boolean putNonStandardAcl = false; if (acl != null) { if (AccessControlList.REST_CANNED_PRIVATE.equals(acl)) { metadata.put(Constants.REST_HEADER_PREFIX + "acl", "private"); } else if (AccessControlList.REST_CANNED_PUBLIC_READ.equals(acl)) { metadata.put(Constants.REST_HEADER_PREFIX + "acl", "public-read"); } else if (AccessControlList.REST_CANNED_PUBLIC_READ_WRITE.equals(acl)) { metadata.put(Constants.REST_HEADER_PREFIX + "acl", "public-read-write"); } else if (AccessControlList.REST_CANNED_AUTHENTICATED_READ.equals(acl)) { metadata.put(Constants.REST_HEADER_PREFIX + "acl", "authenticated-read"); } else { putNonStandardAcl = true; } } HttpMethodAndByteCount methodAndByteCount = performRestPut( destinationBucketName, destinationObjectKey, metadata, null, null, false); CopyObjectResultHandler handler = (new XmlResponsesSaxParser()).parseCopyObjectResponse( new HttpMethodReleaseInputStream(methodAndByteCount.getHttpMethod())); // Release HTTP connection manually. This should already have been done by the // HttpMethodReleaseInputStream class, but you can never be too sure... methodAndByteCount.getHttpMethod().releaseConnection(); if (handler.isErrorResponse()) { throw new S3ServiceException( "Copy failed: Code=" + handler.getErrorCode() + ", Message=" + handler.getErrorMessage() + ", RequestId=" + handler.getErrorRequestId() + ", HostId=" + handler.getErrorHostId()); } Map map = new HashMap(); // Result fields returned when copy is successful. map.put("Last-Modified", handler.getLastModified()); map.put("ETag", handler.getETag()); // Include response headers in result map. map.putAll(convertHeadersToMap(methodAndByteCount.getHttpMethod().getResponseHeaders())); map = ServiceUtils.cleanRestMetadataMap(map); if (putNonStandardAcl) { log.debug("Creating object with a non-canned ACL using REST, so an extra ACL Put is required"); putAclImpl(destinationBucketName, destinationObjectKey, acl); } return map; } protected S3Object getObjectDetailsImpl(String bucketName, String objectKey, Calendar ifModifiedSince, Calendar ifUnmodifiedSince, String[] ifMatchTags, String[] ifNoneMatchTags) throws S3ServiceException { return getObjectImpl(true, bucketName, objectKey, ifModifiedSince, ifUnmodifiedSince, ifMatchTags, ifNoneMatchTags, null, null); } protected S3Object getObjectImpl(String bucketName, String objectKey, Calendar ifModifiedSince, Calendar ifUnmodifiedSince, String[] ifMatchTags, String[] ifNoneMatchTags, Long byteRangeStart, Long byteRangeEnd) throws S3ServiceException { return getObjectImpl(false, bucketName, objectKey, ifModifiedSince, ifUnmodifiedSince, ifMatchTags, ifNoneMatchTags, byteRangeStart, byteRangeEnd); } private S3Object getObjectImpl(boolean headOnly, String bucketName, String objectKey, Calendar ifModifiedSince, Calendar ifUnmodifiedSince, String[] ifMatchTags, String[] ifNoneMatchTags, Long byteRangeStart, Long byteRangeEnd) throws S3ServiceException { log.debug("Retrieving " + (headOnly? "Head" : "All") + " information for bucket " + bucketName + " and object " + objectKey); HashMap requestHeaders = new HashMap(); if (ifModifiedSince != null) { requestHeaders.put("If-Modified-Since", ServiceUtils.formatRfc822Date(ifModifiedSince.getTime())); log.debug("Only retrieve object if-modified-since:" + ifModifiedSince); } if (ifUnmodifiedSince != null) { requestHeaders.put("If-Unmodified-Since", ServiceUtils.formatRfc822Date(ifUnmodifiedSince.getTime())); log.debug("Only retrieve object if-unmodified-since:" + ifUnmodifiedSince); } if (ifMatchTags != null) { StringBuffer tags = new StringBuffer(); for (int i = 0; i < ifMatchTags.length; i++) { if (i > 0) { tags.append(","); } tags.append(ifMatchTags[i]); } requestHeaders.put("If-Match", tags.toString()); log.debug("Only retrieve object by hash if-match:" + tags.toString()); } if (ifNoneMatchTags != null) { StringBuffer tags = new StringBuffer(); for (int i = 0; i < ifNoneMatchTags.length; i++) { if (i > 0) { tags.append(","); } tags.append(ifNoneMatchTags[i]); } requestHeaders.put("If-None-Match", tags.toString()); log.debug("Only retrieve object by hash if-none-match:" + tags.toString()); } if (byteRangeStart != null || byteRangeEnd != null) { String range = "bytes=" + (byteRangeStart != null? byteRangeStart.toString() : "") + "-" + (byteRangeEnd != null? byteRangeEnd.toString() : ""); requestHeaders.put("Range", range); log.debug("Only retrieve object if it is within range:" + range); } HttpMethodBase httpMethod = null; if (headOnly) { httpMethod = performRestHead(bucketName, objectKey, null, requestHeaders); } else { httpMethod = performRestGet(bucketName, objectKey, null, requestHeaders); } HashMap map = new HashMap(); map.putAll(convertHeadersToMap(httpMethod.getResponseHeaders())); S3Object responseObject = new S3Object(objectKey); responseObject.setBucketName(bucketName); responseObject.replaceAllMetadata(ServiceUtils.cleanRestMetadataMap(map)); responseObject.setMetadataComplete(true); // Flag this object as having the complete metadata set. if (!headOnly) { HttpMethodReleaseInputStream releaseIS = new HttpMethodReleaseInputStream(httpMethod); responseObject.setDataInputStream(releaseIS); } else { // Release connection after HEAD (there's no response content) log.debug("Releasing HttpMethod after HEAD"); httpMethod.releaseConnection(); } return responseObject; } protected String getBucketLocationImpl(String bucketName) throws S3ServiceException { log.debug("Retrieving location of Bucket: " + bucketName); HashMap requestParameters = new HashMap(); requestParameters.put("location",""); HttpMethodBase httpMethod = performRestGet(bucketName, null, requestParameters, null); return (new XmlResponsesSaxParser()).parseBucketLocationResponse( new HttpMethodReleaseInputStream(httpMethod)); } protected S3BucketLoggingStatus getBucketLoggingStatusImpl(String bucketName) throws S3ServiceException { log.debug("Retrieving Logging Status for Bucket: " + bucketName); HashMap requestParameters = new HashMap(); requestParameters.put("logging",""); HttpMethodBase httpMethod = performRestGet(bucketName, null, requestParameters, null); return (new XmlResponsesSaxParser()).parseLoggingStatusResponse( new HttpMethodReleaseInputStream(httpMethod)).getBucketLoggingStatus(); } protected void setBucketLoggingStatusImpl(String bucketName, S3BucketLoggingStatus status) throws S3ServiceException { log.debug("Setting Logging Status for bucket: " + bucketName); HashMap requestParameters = new HashMap(); requestParameters.put("logging",""); HashMap metadata = new HashMap(); metadata.put("Content-Type", "text/plain"); try { String statusAsXml = status.toXml(); metadata.put("Content-Length", String.valueOf(statusAsXml.length())); performRestPut(bucketName, null, metadata, requestParameters, new StringRequestEntity(statusAsXml, "text/plain", Constants.DEFAULT_ENCODING), true); } catch (UnsupportedEncodingException e) { throw new S3ServiceException("Unable to encode LoggingStatus XML document", e); } } /** * Puts an object using a pre-signed PUT URL generated for that object. * This method is an implementation of the interface {@link SignedUrlHandler}. * <p> * This operation does not required any S3 functionality as it merely * uploads the object by performing a standard HTTP PUT using the signed URL. * * @param signedPutUrl * a signed PUT URL generated with * {@link S3Service#createSignedPutUrl(String, String, Map, AWSCredentials, Date)}. * @param object * the object to upload, which must correspond to the object for which the URL was signed. * The object <b>must</b> have the correct content length set, and to apply a non-standard * ACL policy only the REST canned ACLs can be used * (eg {@link AccessControlList#REST_CANNED_PUBLIC_READ_WRITE}). * * @return * the S3Object put to S3. The S3Object returned will represent the object created in S3. * * @throws S3ServiceException */ public S3Object putObjectWithSignedUrl(String signedPutUrl, S3Object object) throws S3ServiceException { PutMethod putMethod = new PutMethod(signedPutUrl); Map renamedMetadata = RestUtils.renameMetadataKeys(object.getMetadataMap()); addMetadataToHeaders(putMethod, renamedMetadata); if (!object.containsMetadata("Content-Length")) { throw new IllegalStateException("Content-Length must be specified for objects put using signed PUT URLs"); } if (object.getDataInputStream() != null) { putMethod.setRequestEntity(new RepeatableRequestEntity(object.getKey(), object.getDataInputStream(), object.getContentType(), object.getContentLength())); } performRequest(putMethod, 200); // Consume response data and release connection. putMethod.releaseConnection(); try { S3Object uploadedObject = ServiceUtils.buildObjectFromUrl(putMethod.getURI().getHost(), putMethod.getPath()); object.setBucketName(uploadedObject.getBucketName()); object.setKey(uploadedObject.getKey()); try { object.setLastModifiedDate(ServiceUtils.parseRfc822Date( putMethod.getResponseHeader("Date").getValue())); } catch (ParseException e1) { log.warn("Unable to interpret date of object PUT in S3", e1); } try { object.closeDataInputStream(); } catch (IOException e) { log.warn("Unable to close data input stream for object '" + object.getKey() + "'", e); } } catch (URIException e) { throw new S3ServiceException("Unable to lookup URI for object created with signed PUT", e); } catch (UnsupportedEncodingException e) { throw new S3ServiceException("Unable to determine name of object created with signed PUT", e); } return object; } /** * Deletes an object using a pre-signed DELETE URL generated for that object. * This method is an implementation of the interface {@link SignedUrlHandler}. * <p> * This operation does not required any S3 functionality as it merely * deletes the object by performing a standard HTTP DELETE using the signed URL. * * @param signedDeleteUrl * a signed DELETE URL generated with {@link S3Service#createSignedDeleteUrl}. * * @throws S3ServiceException */ public void deleteObjectWithSignedUrl(String signedDeleteUrl) throws S3ServiceException { DeleteMethod deleteMethod = new DeleteMethod(signedDeleteUrl); performRequest(deleteMethod, 204); deleteMethod.releaseConnection(); } /** * Gets an object using a pre-signed GET URL generated for that object. * This method is an implementation of the interface {@link SignedUrlHandler}. * <p> * This operation does not required any S3 functionality as it merely * uploads the object by performing a standard HTTP GET using the signed URL. * * @param signedGetUrl * a signed GET URL generated with * {@link S3Service#createSignedGetUrl(String, String, AWSCredentials, Date)}. * * @return * the S3Object in S3 including all metadata and the object's data input stream. * * @throws S3ServiceException */ public S3Object getObjectWithSignedUrl(String signedGetUrl) throws S3ServiceException { return getObjectWithSignedUrlImpl(signedGetUrl, false); } /** * Gets an object's details using a pre-signed HEAD URL generated for that object. * This method is an implementation of the interface {@link SignedUrlHandler}. * <p> * This operation does not required any S3 functionality as it merely * uploads the object by performing a standard HTTP HEAD using the signed URL. * * @param signedHeadUrl * a signed HEAD URL generated with * {@link S3Service#createSignedHeadUrl(String, String, AWSCredentials, Date)}. * * @return * the S3Object in S3 including all metadata, but without the object's data input stream. * * @throws S3ServiceException */ public S3Object getObjectDetailsWithSignedUrl(String signedHeadUrl) throws S3ServiceException { return getObjectWithSignedUrlImpl(signedHeadUrl, true); } /** * Gets an object's ACL details using a pre-signed GET URL generated for that object. * This method is an implementation of the interface {@link SignedUrlHandler}. * * @param signedAclUrl * a signed URL generated with {@link S3Service#createSignedUrl(String, String, String, String, Map, AWSCredentials, long, boolean)}. * * @return * the AccessControlList settings of the object in S3. * * @throws S3ServiceException */ public AccessControlList getObjectAclWithSignedUrl(String signedAclUrl) throws S3ServiceException { HttpMethodBase httpMethod = new GetMethod(signedAclUrl); HashMap requestParameters = new HashMap(); requestParameters.put("acl",""); performRequest(httpMethod, 200); return (new XmlResponsesSaxParser()).parseAccessControlListResponse( new HttpMethodReleaseInputStream(httpMethod)).getAccessControlList(); } /** * Sets an object's ACL details using a pre-signed PUT URL generated for that object. * This method is an implementation of the interface {@link SignedUrlHandler}. * * @param signedAclUrl * a signed URL generated with {@link S3Service#createSignedUrl(String, String, String, String, Map, AWSCredentials, long, boolean)}. * @param acl * the ACL settings to apply to the object represented by the signed URL. * * @throws S3ServiceException */ public void putObjectAclWithSignedUrl(String signedAclUrl, AccessControlList acl) throws S3ServiceException { PutMethod putMethod = new PutMethod(signedAclUrl); if (acl != null) { if (AccessControlList.REST_CANNED_PRIVATE.equals(acl)) { putMethod.addRequestHeader(Constants.REST_HEADER_PREFIX + "acl", "private"); } else if (AccessControlList.REST_CANNED_PUBLIC_READ.equals(acl)) { putMethod.addRequestHeader(Constants.REST_HEADER_PREFIX + "acl", "public-read"); } else if (AccessControlList.REST_CANNED_PUBLIC_READ_WRITE.equals(acl)) { putMethod.addRequestHeader(Constants.REST_HEADER_PREFIX + "acl", "public-read-write"); } else if (AccessControlList.REST_CANNED_AUTHENTICATED_READ.equals(acl)) { putMethod.addRequestHeader(Constants.REST_HEADER_PREFIX + "acl", "authenticated-read"); } else { try { String aclAsXml = acl.toXml(); putMethod.setRequestEntity(new StringRequestEntity( aclAsXml, "text/xml", Constants.DEFAULT_ENCODING)); } catch (UnsupportedEncodingException e) { throw new S3ServiceException("Unable to encode ACL XML document", e); } } } performRequest(putMethod, 200); // Consume response data and release connection. putMethod.releaseConnection(); } private S3Object getObjectWithSignedUrlImpl(String signedGetOrHeadUrl, boolean headOnly) throws S3ServiceException { HttpMethodBase httpMethod = null; if (headOnly) { httpMethod = new HeadMethod(signedGetOrHeadUrl); } else { httpMethod = new GetMethod(signedGetOrHeadUrl); } performRequest(httpMethod, 200); HashMap map = new HashMap(); map.putAll(convertHeadersToMap(httpMethod.getResponseHeaders())); S3Object responseObject = null; try { responseObject = ServiceUtils.buildObjectFromUrl( httpMethod.getURI().getHost(), httpMethod.getPath().substring(1)); } catch (URIException e) { throw new S3ServiceException("Unable to lookup URI for object created with signed PUT", e); } catch (UnsupportedEncodingException e) { throw new S3ServiceException("Unable to determine name of object created with signed PUT", e); } responseObject.replaceAllMetadata(ServiceUtils.cleanRestMetadataMap(map)); responseObject.setMetadataComplete(true); // Flag this object as having the complete metadata set. if (!headOnly) { HttpMethodReleaseInputStream releaseIS = new HttpMethodReleaseInputStream(httpMethod); responseObject.setDataInputStream(releaseIS); } else { // Release connection after HEAD (there's no response content) log.debug("Releasing HttpMethod after HEAD"); httpMethod.releaseConnection(); } return responseObject; } /** * Simple container object to store an HttpMethod object representing a request connection, and a * count of the byte size of the S3 object associated with the request. * <p> * This object is used when S3 objects are created to associate the connection and the actual size * of the object as reported back by S3. * * @author James Murty */ private class HttpMethodAndByteCount { private HttpMethodBase httpMethod = null; private long byteCount = 0; public HttpMethodAndByteCount(HttpMethodBase httpMethod, long byteCount) { this.httpMethod = httpMethod; this.byteCount = byteCount; } public HttpMethodBase getHttpMethod() { return httpMethod; } public long getByteCount() { return byteCount; } } }
false
true
protected void performRequest(HttpMethodBase httpMethod, int expectedResponseCode) throws S3ServiceException { try { log.debug("Performing " + httpMethod.getName() + " request for '" + httpMethod.getURI().toString() + "', expecting response code " + expectedResponseCode); // Variables to manage S3 Internal Server 500 errors. boolean completedWithoutRecoverableError = true; int internalErrorCount = 0; int requestTimeoutErrorCount = 0; int redirectCount = 0; boolean wasRecentlyRedirected = false; // Perform the request, sleeping and retrying when S3 Internal Errors are encountered. int responseCode = -1; do { // Build the authorization string for the method (Unless we have just been redirected). if (!wasRecentlyRedirected) { buildAuthorizationString(httpMethod); } else { // Reset redirection flag wasRecentlyRedirected = false; } responseCode = httpClient.executeMethod(httpMethod); if (responseCode == 307) { // Retry on Temporary Redirects, using new URI from location header Header locationHeader = httpMethod.getResponseHeader("location"); httpMethod.setURI(new URI(locationHeader.getValue(), true)); completedWithoutRecoverableError = false; redirectCount++; wasRecentlyRedirected = true; if (redirectCount > 5) { throw new S3ServiceException("Encountered too many 307 Redirects, aborting request."); } } else if (responseCode == 500) { // Retry on S3 Internal Server 500 errors. completedWithoutRecoverableError = false; sleepOnInternalError(++internalErrorCount); } else { completedWithoutRecoverableError = true; } String contentType = ""; if (httpMethod.getResponseHeader("Content-Type") != null) { contentType = httpMethod.getResponseHeader("Content-Type").getValue(); } log.debug("Response for '" + httpMethod.getPath() + "'. Content-Type: " + contentType + ", Headers: " + Arrays.asList(httpMethod.getResponseHeaders())); // Check we received the expected result code. if (responseCode != expectedResponseCode) { log.warn("Response '" + httpMethod.getPath() + "' - Unexpected response code " + responseCode + ", expected " + expectedResponseCode); if (Mimetypes.MIMETYPE_XML.equals(contentType) && httpMethod.getResponseBodyAsStream() != null && httpMethod.getResponseContentLength() != 0) { log.warn("Response '" + httpMethod.getPath() + "' - Received error response with XML message"); StringBuffer sb = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader( new HttpMethodReleaseInputStream(httpMethod))); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } finally { if (reader != null) { reader.close(); } } httpMethod.releaseConnection(); // Throw exception containing the XML message document. S3ServiceException exception = new S3ServiceException("S3 " + httpMethod.getName() + " failed for '" + httpMethod.getPath() + "'", sb.toString()); if ("RequestTimeout".equals(exception.getS3ErrorCode())) { int retryMaxCount = jets3tProperties.getIntProperty("httpclient.retry-max", 5); if (requestTimeoutErrorCount < retryMaxCount) { requestTimeoutErrorCount++; log.warn("Response '" + httpMethod.getPath() + "' - Retrying connection that failed with RequestTimeout error" + ", attempt number " + requestTimeoutErrorCount + " of " + retryMaxCount); completedWithoutRecoverableError = false; } else { log.warn("Response '" + httpMethod.getPath() + "' - Exceeded maximum number of retries for RequestTimeout errors: " + retryMaxCount); throw exception; } } else if ("RequestTimeTooSkewed".equals(exception.getS3ErrorCode())) { long timeDifferenceMS = adjustTime(); log.warn("Adjusted time offset in response to RequestTimeTooSkewed error. " + "Local machine and S3 server disagree on the time by approximately " + (timeDifferenceMS / 1000) + " seconds. Retrying connection."); completedWithoutRecoverableError = false; } else if (responseCode == 500) { // Retrying after InternalError 500, don't throw exception. } else if (responseCode == 307) { // Retrying after Temporary Redirect 307, don't throw exception. log.debug("Following Temporary Redirect to: " + httpMethod.getURI().toString()); } else { throw exception; } } else { // Consume response content and release connection. String responseText = null; byte[] responseBody = httpMethod.getResponseBody(); if (responseBody != null && responseBody.length > 0) { responseText = new String(responseBody); } log.debug("Releasing error response without XML content"); httpMethod.releaseConnection(); if (responseCode == 500) { // Retrying after InternalError 500, don't throw exception. } else { // Throw exception containing the HTTP error fields. HttpException httpException = new HttpException( httpMethod.getStatusCode(), httpMethod.getStatusText()); S3ServiceException exception = new S3ServiceException("S3 " + httpMethod.getName() + " request failed for '" + httpMethod.getPath() + "' - " + "ResponseCode=" + httpMethod.getStatusCode() + ", ResponseMessage=" + httpMethod.getStatusText() + (responseText != null ? "\n" + responseText : ""), httpException); exception.setResponseCode(httpMethod.getStatusCode()); exception.setResponseStatus(httpMethod.getStatusText()); throw exception; } } } } while (!completedWithoutRecoverableError); // Release immediately any connections without response bodies. if ((httpMethod.getResponseBodyAsStream() == null || httpMethod.getResponseBodyAsStream().available() == 0) && httpMethod.getResponseContentLength() == 0) { log.debug("Releasing response without content"); byte[] responseBody = httpMethod.getResponseBody(); if (responseBody != null && responseBody.length > 0) throw new S3ServiceException("Oops, too keen to release connection with a non-empty response body"); httpMethod.releaseConnection(); } } catch (Throwable t) { log.debug("Releasing HttpClient connection after error: " + t.getMessage()); httpMethod.releaseConnection(); if (t instanceof S3ServiceException) { throw (S3ServiceException) t; } else { throw new S3ServiceException("S3 " + httpMethod.getName() + " connection failed for '" + httpMethod.getPath() + "'", t); } } }
protected void performRequest(HttpMethodBase httpMethod, int expectedResponseCode) throws S3ServiceException { try { log.debug("Performing " + httpMethod.getName() + " request for '" + httpMethod.getURI().toString() + "', expecting response code " + expectedResponseCode); // Variables to manage S3 Internal Server 500 or 503 Service Unavailable errors. boolean completedWithoutRecoverableError = true; int internalErrorCount = 0; int requestTimeoutErrorCount = 0; int redirectCount = 0; boolean wasRecentlyRedirected = false; // Perform the request, sleeping and retrying when S3 Internal Errors are encountered. int responseCode = -1; do { // Build the authorization string for the method (Unless we have just been redirected). if (!wasRecentlyRedirected) { buildAuthorizationString(httpMethod); } else { // Reset redirection flag wasRecentlyRedirected = false; } responseCode = httpClient.executeMethod(httpMethod); if (responseCode == 307) { // Retry on Temporary Redirects, using new URI from location header Header locationHeader = httpMethod.getResponseHeader("location"); httpMethod.setURI(new URI(locationHeader.getValue(), true)); completedWithoutRecoverableError = false; redirectCount++; wasRecentlyRedirected = true; if (redirectCount > 5) { throw new S3ServiceException("Encountered too many 307 Redirects, aborting request."); } } else if (responseCode == 500 || responseCode == 503) { // Retry on S3 Internal Server 500 or 503 Service Unavailable erros. completedWithoutRecoverableError = false; sleepOnInternalError(++internalErrorCount); } else { completedWithoutRecoverableError = true; } String contentType = ""; if (httpMethod.getResponseHeader("Content-Type") != null) { contentType = httpMethod.getResponseHeader("Content-Type").getValue(); } log.debug("Response for '" + httpMethod.getPath() + "'. Content-Type: " + contentType + ", Headers: " + Arrays.asList(httpMethod.getResponseHeaders())); // Check we received the expected result code. if (responseCode != expectedResponseCode) { log.warn("Response '" + httpMethod.getPath() + "' - Unexpected response code " + responseCode + ", expected " + expectedResponseCode); if (Mimetypes.MIMETYPE_XML.equals(contentType) && httpMethod.getResponseBodyAsStream() != null && httpMethod.getResponseContentLength() != 0) { log.warn("Response '" + httpMethod.getPath() + "' - Received error response with XML message"); StringBuffer sb = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader( new HttpMethodReleaseInputStream(httpMethod))); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } finally { if (reader != null) { reader.close(); } } httpMethod.releaseConnection(); // Throw exception containing the XML message document. S3ServiceException exception = new S3ServiceException("S3 " + httpMethod.getName() + " failed for '" + httpMethod.getPath() + "'", sb.toString()); if ("RequestTimeout".equals(exception.getS3ErrorCode())) { int retryMaxCount = jets3tProperties.getIntProperty("httpclient.retry-max", 5); if (requestTimeoutErrorCount < retryMaxCount) { requestTimeoutErrorCount++; log.warn("Response '" + httpMethod.getPath() + "' - Retrying connection that failed with RequestTimeout error" + ", attempt number " + requestTimeoutErrorCount + " of " + retryMaxCount); completedWithoutRecoverableError = false; } else { log.warn("Response '" + httpMethod.getPath() + "' - Exceeded maximum number of retries for RequestTimeout errors: " + retryMaxCount); throw exception; } } else if ("RequestTimeTooSkewed".equals(exception.getS3ErrorCode())) { long timeDifferenceMS = adjustTime(); log.warn("Adjusted time offset in response to RequestTimeTooSkewed error. " + "Local machine and S3 server disagree on the time by approximately " + (timeDifferenceMS / 1000) + " seconds. Retrying connection."); completedWithoutRecoverableError = false; } else if (responseCode == 500 || responseCode == 503) { // Retrying after 500 or 503 error, don't throw exception. } else if (responseCode == 307) { // Retrying after Temporary Redirect 307, don't throw exception. log.debug("Following Temporary Redirect to: " + httpMethod.getURI().toString()); } else { throw exception; } } else { // Consume response content and release connection. String responseText = null; byte[] responseBody = httpMethod.getResponseBody(); if (responseBody != null && responseBody.length > 0) { responseText = new String(responseBody); } log.debug("Releasing error response without XML content"); httpMethod.releaseConnection(); if (responseCode == 500 || responseCode == 503) { // Retrying after InternalError 500, don't throw exception. } else { // Throw exception containing the HTTP error fields. HttpException httpException = new HttpException( httpMethod.getStatusCode(), httpMethod.getStatusText()); S3ServiceException exception = new S3ServiceException("S3 " + httpMethod.getName() + " request failed for '" + httpMethod.getPath() + "' - " + "ResponseCode=" + httpMethod.getStatusCode() + ", ResponseMessage=" + httpMethod.getStatusText() + (responseText != null ? "\n" + responseText : ""), httpException); exception.setResponseCode(httpMethod.getStatusCode()); exception.setResponseStatus(httpMethod.getStatusText()); throw exception; } } } } while (!completedWithoutRecoverableError); // Release immediately any connections without response bodies. if ((httpMethod.getResponseBodyAsStream() == null || httpMethod.getResponseBodyAsStream().available() == 0) && httpMethod.getResponseContentLength() == 0) { log.debug("Releasing response without content"); byte[] responseBody = httpMethod.getResponseBody(); if (responseBody != null && responseBody.length > 0) throw new S3ServiceException("Oops, too keen to release connection with a non-empty response body"); httpMethod.releaseConnection(); } } catch (Throwable t) { log.debug("Releasing HttpClient connection after error: " + t.getMessage()); httpMethod.releaseConnection(); if (t instanceof S3ServiceException) { throw (S3ServiceException) t; } else { throw new S3ServiceException("S3 " + httpMethod.getName() + " connection failed for '" + httpMethod.getPath() + "'", t); } } }
diff --git a/src/general/tracers/OppositeWaveTracer.java b/src/general/tracers/OppositeWaveTracer.java index 2ad3a94..269300e 100644 --- a/src/general/tracers/OppositeWaveTracer.java +++ b/src/general/tracers/OppositeWaveTracer.java @@ -1,99 +1,102 @@ package general.tracers; import general.*; import general.Panel; import java.awt.*; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * Created with IntelliJ IDEA. * User: Vans * Date: 19.05.13 * Time: 23:25 * To change this template use File | Settings | File Templates. */ public class OppositeWaveTracer implements Tracer { private static int[][] field = new int[Scheme.HEIGHT][Scheme.WIDTH]; private int Ni = 0;//wave count private boolean finished = false; ArrayList<Point> points = new ArrayList<Point>(); public int finishX; public int finishY; @Override public Point[] getPath(int x1, int y1, int x2, int y2) { finishX = x2; finishY = y2; /* here we add points, which are already marked with wave * to spread next front of wave from them too*/ //points.add(Panel.tiles[x1][y1]); //points.add(Panel.tiles[x2][y2]); points.add(new Point(x1,y1)); /*Problem is that this loop is infinite - points.size seem to * increase constantly*/ for (int i = 0; i<points.size(); i++) { makeWave(i); /*HashSet hashSet = new HashSet(); hashSet.addAll(points); points.clear(); points.addAll(hashSet); */ } Point[] path = new Point[points.size()]; return points.toArray(path); } private void makeWave (int index) { int x = (int) points.get(index).getX(); int y = (int) points.get(index).getY(); // points.remove(index); int waveFront; if (Scheme.labels[x][y].equals("")) - waveFront=0; + { + waveFront=0; + Scheme.labels[x][y]="0"; + } else waveFront = Integer.parseInt(Scheme.labels[x][y]); if (x+1 == finishX || y+1 == finishY || x-1 == finishX || y-1 == finishY) { finished = true; return; } if (Scheme.tiles[x+1][y] == TileType.EMPTY && x < Scheme.WIDTH && Scheme.labels[x+1][y] == "") { Scheme.labels[x+1][y] = "" +(waveFront+1); points.add(new Point(x+1,y)); } if ( x > 0 && Scheme.tiles[x-1][y] == TileType.EMPTY && Scheme.labels[x-1][y] == "") { Scheme.labels[x-1][y] = "" +(waveFront+1); points.add(new Point(x-1,y)); } if (Scheme.tiles[x][y+1] == TileType.EMPTY && y <Scheme.HEIGHT && Scheme.labels[x][y+1] == "") { Scheme.labels[x][y+1] = "" + (waveFront+1); points.add(new Point(x,y+1)); } if ( y > 0 && Scheme.tiles[x][y-1] == TileType.EMPTY && Scheme.labels[x][y-1] == "") { Scheme.labels[x][y-1] = "" +(waveFront+1); points.add(new Point(x,y-1)); } } }
true
true
private void makeWave (int index) { int x = (int) points.get(index).getX(); int y = (int) points.get(index).getY(); // points.remove(index); int waveFront; if (Scheme.labels[x][y].equals("")) waveFront=0; else waveFront = Integer.parseInt(Scheme.labels[x][y]); if (x+1 == finishX || y+1 == finishY || x-1 == finishX || y-1 == finishY) { finished = true; return; } if (Scheme.tiles[x+1][y] == TileType.EMPTY && x < Scheme.WIDTH && Scheme.labels[x+1][y] == "") { Scheme.labels[x+1][y] = "" +(waveFront+1); points.add(new Point(x+1,y)); } if ( x > 0 && Scheme.tiles[x-1][y] == TileType.EMPTY && Scheme.labels[x-1][y] == "") { Scheme.labels[x-1][y] = "" +(waveFront+1); points.add(new Point(x-1,y)); } if (Scheme.tiles[x][y+1] == TileType.EMPTY && y <Scheme.HEIGHT && Scheme.labels[x][y+1] == "") { Scheme.labels[x][y+1] = "" + (waveFront+1); points.add(new Point(x,y+1)); } if ( y > 0 && Scheme.tiles[x][y-1] == TileType.EMPTY && Scheme.labels[x][y-1] == "") { Scheme.labels[x][y-1] = "" +(waveFront+1); points.add(new Point(x,y-1)); } }
private void makeWave (int index) { int x = (int) points.get(index).getX(); int y = (int) points.get(index).getY(); // points.remove(index); int waveFront; if (Scheme.labels[x][y].equals("")) { waveFront=0; Scheme.labels[x][y]="0"; } else waveFront = Integer.parseInt(Scheme.labels[x][y]); if (x+1 == finishX || y+1 == finishY || x-1 == finishX || y-1 == finishY) { finished = true; return; } if (Scheme.tiles[x+1][y] == TileType.EMPTY && x < Scheme.WIDTH && Scheme.labels[x+1][y] == "") { Scheme.labels[x+1][y] = "" +(waveFront+1); points.add(new Point(x+1,y)); } if ( x > 0 && Scheme.tiles[x-1][y] == TileType.EMPTY && Scheme.labels[x-1][y] == "") { Scheme.labels[x-1][y] = "" +(waveFront+1); points.add(new Point(x-1,y)); } if (Scheme.tiles[x][y+1] == TileType.EMPTY && y <Scheme.HEIGHT && Scheme.labels[x][y+1] == "") { Scheme.labels[x][y+1] = "" + (waveFront+1); points.add(new Point(x,y+1)); } if ( y > 0 && Scheme.tiles[x][y-1] == TileType.EMPTY && Scheme.labels[x][y-1] == "") { Scheme.labels[x][y-1] = "" +(waveFront+1); points.add(new Point(x,y-1)); } }
diff --git a/fits/src/main/uk/ac/starlink/fits/FitsTableSerializer.java b/fits/src/main/uk/ac/starlink/fits/FitsTableSerializer.java index f2c6515b0..210fe949d 100644 --- a/fits/src/main/uk/ac/starlink/fits/FitsTableSerializer.java +++ b/fits/src/main/uk/ac/starlink/fits/FitsTableSerializer.java @@ -1,848 +1,848 @@ package uk.ac.starlink.fits; import java.io.DataOutput; import java.io.IOException; import java.lang.reflect.Array; import java.util.Arrays; import java.util.logging.Logger; import nom.tam.fits.FitsException; import nom.tam.fits.Header; import nom.tam.fits.HeaderCardException; import uk.ac.starlink.table.ColumnInfo; import uk.ac.starlink.table.DescribedValue; import uk.ac.starlink.table.RowSequence; import uk.ac.starlink.table.StarTable; import uk.ac.starlink.table.Tables; /** * Class which knows how to do the various bits of serializing a StarTable * to FITS BINTABLE format. This does the hard work for FitsTableWriter. * * @author Mark Taylor (Starlink) */ public class FitsTableSerializer { private static Logger logger = Logger.getLogger( "uk.ac.starlink.fits" ); private final StarTable table; private final ColumnWriter[] colWriters; private final ColumnInfo[] colInfos; private final long rowCount; /** * Constructs a serializer which will be able to write a given StarTable. * * @param table the table to be written */ public FitsTableSerializer( StarTable table ) throws IOException { this.table = table; /* Get table dimensions (though we may need to calculate the row * count directly later. */ int ncol = table.getColumnCount(); long nrow = table.getRowCount(); /* Store column infos. */ colInfos = Tables.getColumnInfos( table ); /* Work out column shapes, and check if any are unknown (variable * last dimension). */ boolean hasVarShapes = false; boolean hasNullableInts = false; int[][] shapes = new int[ ncol ][]; int[] maxChars = new int[ ncol ]; boolean[] useCols = new boolean[ ncol ]; boolean[] varShapes = new boolean[ ncol ]; boolean[] varChars = new boolean[ ncol ]; boolean[] varElementChars = new boolean[ ncol ]; boolean[] nullableInts = new boolean[ ncol ]; Arrays.fill( useCols, true ); for ( int icol = 0; icol < ncol; icol++ ) { ColumnInfo colinfo = colInfos[ icol ]; Class clazz = colinfo.getContentClass(); if ( clazz.isArray() ) { shapes[ icol ] = (int[]) colinfo.getShape().clone(); int[] shape = shapes[ icol ]; if ( shape[ shape.length - 1 ] < 0 ) { varShapes[ icol ] = true; hasVarShapes = true; } if ( clazz.getComponentType().equals( String.class ) ) { maxChars[ icol ] = colinfo.getElementSize(); if ( maxChars[ icol ] <= 0 ) { varElementChars[ icol ] = true; hasVarShapes = true; } } } else if ( clazz.equals( String.class ) ) { maxChars[ icol ] = colinfo.getElementSize(); if ( maxChars[ icol ] <= 0 ) { varChars[ icol ] = true; hasVarShapes = true; } } else if ( colinfo.isNullable() && ( clazz == Byte.class || clazz == Short.class || clazz == Integer.class || clazz == Long.class ) ) { nullableInts[ icol ] = true; hasNullableInts = true; } } /* If necessary, make a first pass through the table data to * find out the maximum size of variable length fields and the length * of the table. */ boolean[] hasNulls = new boolean[ ncol ]; if ( hasVarShapes || hasNullableInts || nrow < 0 ) { int[] maxElements = new int[ ncol ]; nrow = 0L; /* Get the maximum dimensions. */ RowSequence rseq = table.getRowSequence(); try { while ( rseq.hasNext() ) { rseq.next(); nrow++; for ( int icol = 0; icol < ncol; icol++ ) { if ( useCols[ icol ] && ( varShapes[ icol ] || varChars[ icol ] || varElementChars[ icol ] || ( nullableInts[ icol ] && ! hasNulls[ icol ] ) ) ) { Object cell = rseq.getCell( icol ); if ( cell == null ) { if ( nullableInts[ icol ] ) { hasNulls[ icol ] = true; } } else { if ( varChars[ icol ] ) { int leng = ((String) cell).length(); maxChars[ icol ] = Math.max( maxChars[ icol ], leng ); } else if ( varElementChars[ icol ] ) { String[] svals = (String[]) cell; for ( int i = 0; i < svals.length; i++ ) { maxChars[ icol ] = Math.max( maxChars[ icol ], svals[ i ].length() ); } } if ( varShapes[ icol ] ) { maxElements[ icol ] = Math.max( maxElements[ icol ], Array.getLength( cell ) ); } } } } } } finally { rseq.close(); } /* Work out the actual shapes for columns which have variable ones, * based on the shapes that we encountered in the rows. */ if ( hasVarShapes ) { for ( int icol = 0; icol < ncol; icol++ ) { if ( useCols[ icol ] ) { if ( varShapes[ icol ] ) { int[] shape = shapes[ icol ]; int ndim = shape.length; assert shape[ ndim - 1 ] <= 0; int nel = 1; for ( int i = 0; i < ndim - 1; i++ ) { nel *= shape[ i ]; } shape[ ndim - 1 ] = Math.max( 1, ( maxElements[ icol ] + nel - 1 ) / nel ); } } } } } /* Store the row count, which we must have got by now. */ assert nrow >= 0; rowCount = nrow; /* We now have all the information we need about the table. * Construct and store a custom writer for each column which * knows about the characteristics of the column and how to * write values to the stream. For columns which can't be * written in FITS format store a null in the writers array * and log a message. */ colWriters = new ColumnWriter[ ncol ]; int rbytes = 0; for ( int icol = 0; icol < ncol; icol++ ) { if ( useCols[ icol ] ) { ColumnInfo cinfo = colInfos[ icol ]; ColumnWriter writer = makeColumnWriter( cinfo, shapes[ icol ], maxChars[ icol ], nullableInts[ icol ] && hasNulls[ icol ] ); if ( writer == null ) { logger.warning( "Ignoring column " + cinfo.getName() + " - don't know how to write to FITS" ); } colWriters[ icol ] = writer; } } } /** * Writes the header block for the BINTABLE extension HDU which holds * the table data. * * @param strm destination stream */ public void writeHeader( DataOutput strm ) throws IOException { /* Work out the dimensions in columns and bytes of the table. */ int rowLength = 0; int nUseCol = 0; int ncol = table.getColumnCount(); for ( int icol = 0; icol < ncol; icol++ ) { ColumnWriter writer = colWriters[ icol ]; if ( writer != null ) { nUseCol++; rowLength += writer.getLength(); } } /* Prepare a FITS header block. */ Header hdr = new Header(); try { /* Prepare the overall HDU metadata. */ hdr.addValue( "XTENSION", "BINTABLE", "binary table extension" ); hdr.addValue( "BITPIX", 8, "8-bit bytes" ); hdr.addValue( "NAXIS", 2, "2-dimensional table" ); hdr.addValue( "NAXIS1", rowLength, "width of table in bytes" ); hdr.addValue( "NAXIS2", rowCount, "number of rows in table" ); hdr.addValue( "PCOUNT", 0, "size of special data area" ); hdr.addValue( "GCOUNT", 1, "one data group" ); hdr.addValue( "TFIELDS", nUseCol, "number of columns" ); /* Prepare the per-column HDU metadata. */ int jcol = 0; for ( int icol = 0; icol < ncol; icol++ ) { ColumnWriter colwriter = colWriters[ icol ]; if ( colwriter != null ) { jcol++; String forcol = " for column " + jcol; ColumnInfo colinfo = colInfos[ icol ]; /* Name. */ String name = colinfo.getName(); if ( name != null && name.trim().length() > 0 ) { hdr.addValue( "TTYPE" + jcol, name, "label" + forcol ); } /* Format. */ String form = colwriter.getFormat(); hdr.addValue( "TFORM" + jcol, form, "format" + forcol ); /* Units. */ String unit = colinfo.getUnitString(); if ( unit != null && unit.trim().length() > 0 ) { hdr.addValue( "TUNIT" + jcol, unit, "units" + forcol ); } /* Blank. */ Number bad = colwriter.getBadNumber(); if ( bad != null ) { hdr.addValue( "TNULL" + jcol, bad.toString(), "blank value" + forcol ); } /* Shape. */ int[] dims = colwriter.getDims(); if ( dims != null && dims.length > 1 ) { StringBuffer sbuf = new StringBuffer(); for ( int i = 0; i < dims.length; i++ ) { sbuf.append( i == 0 ? '(' : ',' ); sbuf.append( dims[ i ] ); } sbuf.append( ')' ); hdr.addValue( "TDIM" + jcol, sbuf.toString(), "dimensions" + forcol ); } /* Scaling. */ double zero = colwriter.getZero(); double scale = colwriter.getScale(); if ( zero != 0.0 ) { hdr.addValue( "TZERO" + jcol, zero, "base" + forcol ); } if ( scale != 1.0 ) { hdr.addValue( "TSCALE" + jcol, scale, "factor" + forcol ); } /* Comment (non-standard). */ String comm = colinfo.getDescription(); if ( comm != null && comm.trim().length() > 0 ) { if ( comm.length() > 67 ) { comm = comm.substring( 0, 68 ); } try { hdr.addValue( "TCOMM" + jcol, comm, null ); } catch ( HeaderCardException e ) { logger.warning( "Description " + comm + " too long for FITS header" ); } } } } } catch ( FitsException e ) { throw (IOException) new IOException( e.getMessage() ) .initCause( e ); } /* Write the header block out. */ FitsConstants.writeHeader( strm, hdr ); } /** * Writes the data part of the BINTABLE extension HDU which holds * the table data. * * @param strm destination stream */ public void writeData( DataOutput strm ) throws IOException { /* Work out the length of each row in bytes. */ int rowBytes = 0; int ncol = table.getColumnCount(); for ( int icol = 0; icol < ncol; icol++ ) { ColumnWriter writer = colWriters[ icol ]; if ( writer != null ) { rowBytes += writer.getLength(); } } /* Write the data cells, delegating the item in each column to * the writer that knows how to handle it. */ long nWritten = 0L; RowSequence rseq = table.getRowSequence(); try { while ( rseq.hasNext() ) { rseq.next(); Object[] row = rseq.getRow(); for ( int icol = 0; icol < ncol; icol++ ) { ColumnWriter writer = colWriters[ icol ]; if ( writer != null ) { writer.writeValue( strm, row[ icol ] ); } } nWritten += rowBytes; } } finally { rseq.close(); } /* Write padding. */ int extra = (int) ( nWritten % (long) 2880 ); if ( extra > 0 ) { strm.write( new byte[ 2880 - extra ] ); } } /** * Returns the FITS TFORM letter which describes the type of data * output for a given column. This is as described by the FITS * standard - 'J' for 4-byte integer, 'A' for characters, etc. * If the column is not being output, <tt>(char)0</tt> will be * returned. * * @param icol column to query * @return format letter for data in column <tt>icol</tt>, * or 0 for a column being skipped */ public char getFormatChar( int icol ) { if ( colWriters[ icol ] == null ) { return (char) 0; } else { return colWriters[ icol ].getFormatChar(); } } /** * Returns the dimensions of the items which will be output for a * given column. This will be <tt>null</tt> only if that column * is not being output. Otherwise it will be a zero-element array * for a scalar, 1-element array for a vector, etc. * * @param icol column to query * @return dimensions array for data in column <tt>icol</tt> * or <tt>null</tt> for a column being skipped */ public int[] getDimensions( int icol ) { if ( colWriters[ icol ] == null ) { return null; } else { int[] dims = colWriters[ icol ].getDims(); return dims == null ? new int[ 0 ] : dims; } } /** * Returns a column writer capable of writing a given column to * a stream in FITS format. * * @param cinfo describes the column to write * @param shape shape for array values * @param elementSize element size * @param nullableInt true if we are going to have to store nulls in * an integer column * @return a suitable column writer, or <tt>null</tt> if we don't * know how to write this to FITS */ private static ColumnWriter makeColumnWriter( ColumnInfo cinfo, int[] shape, int eSize, final boolean nullableInt ) { Class clazz = cinfo.getContentClass(); int n1 = 1; if ( shape != null ) { for ( int i = 0; i < shape.length; i++ ) { n1 *= shape[ i ]; } } final int nel = n1; Number blankNum = null; if ( nullableInt ) { DescribedValue blankVal = cinfo.getAuxDatum( Tables.NULL_VALUE_INFO ); if ( blankVal != null ) { Object blankObj = blankVal.getValue(); if ( blankObj instanceof Number ) { blankNum = (Number) blankObj; } } } if ( clazz == Boolean.class ) { return new ColumnWriter( 'L', 1 ) { void writeValue( DataOutput stream, Object value ) throws IOException { - boolean flag = value.equals( Boolean.TRUE ); + boolean flag = Boolean.TRUE.equals( value ); stream.writeByte( flag ? (byte) 'T' : (byte) 'F' ); } }; } else if ( clazz == Byte.class ) { /* Byte is a bit tricky since a FITS byte is unsigned, while * a byte in a StarTable (a java byte) is signed. */ final byte[] buf = new byte[ 1 ]; final byte badVal = blankNum == null ? (byte) 0 : blankNum.byteValue(); return new ColumnWriter( 'B', 1 ) { void writeValue( DataOutput stream, Object value ) throws IOException { byte b = (value != null) ? ((Number) value).byteValue() : badVal; buf[ 0 ] = (byte) ( b ^ (byte) 0x80 ); stream.write( buf ); } double getZero() { return -128.0; } Number getBadNumber() { return nullableInt ? new Byte( badVal ) : null; } }; } else if ( clazz == Short.class ) { final short badVal = blankNum == null ? Short.MIN_VALUE : blankNum.shortValue(); return new ColumnWriter( 'I', 2 ) { void writeValue( DataOutput stream, Object value ) throws IOException { short sval = ( value != null ) ? ((Number) value).shortValue() : badVal; stream.writeShort( sval ); } Number getBadNumber() { return nullableInt ? new Short( badVal ) : null; } }; } else if ( clazz == Integer.class ) { final int badVal = blankNum == null ? Integer.MIN_VALUE : blankNum.intValue(); return new ColumnWriter( 'J', 4 ) { void writeValue( DataOutput stream, Object value ) throws IOException { int ival = ( value != null ) ? ((Number) value).intValue() : badVal; stream.writeInt( ival ); } Number getBadNumber() { return nullableInt ? new Integer( badVal ) : null; } }; } else if ( clazz == Float.class ) { return new ColumnWriter( 'E', 4 ) { void writeValue( DataOutput stream, Object value ) throws IOException { float fval = ( value != null ) ? ((Number) value).floatValue() : Float.NaN; stream.writeFloat( fval ); } }; } else if ( clazz == Double.class ) { return new ColumnWriter( 'D', 8 ) { void writeValue( DataOutput stream, Object value ) throws IOException { double dval = ( value != null ) ? ((Number) value).doubleValue() : Double.NaN; stream.writeDouble( dval ); } }; } else if ( clazz == Character.class ) { return new ColumnWriter( 'A', 1 ) { void writeValue( DataOutput stream, Object value ) throws IOException { char cval = ( value != null ) ? ((Character) value).charValue() : ' '; stream.writeByte( cval ); } }; } else if ( clazz == String.class ) { final int maxChars = eSize; final byte[] buf = new byte[ maxChars ]; final byte[] blankBuf = new byte[ maxChars ]; final byte PAD = (byte) ' '; final int[] charDims = new int[] { maxChars }; Arrays.fill( blankBuf, PAD ); return new ColumnWriter( 'A', maxChars ) { void writeValue( DataOutput stream, Object value ) throws IOException { byte[] bytes; if ( value == null ) { bytes = blankBuf; } else { String sval = (String) value; int i = 0; int leng = Math.min( sval.length(), maxChars ); bytes = buf; for ( ; i < leng; i++ ) { bytes[ i ] = (byte) sval.charAt( i ); } Arrays.fill( bytes, i, maxChars, PAD ); } stream.write( bytes ); } String getFormat() { return Integer.toString( maxChars ) + 'A'; } int[] getDims() { return charDims; } }; } else if ( clazz == boolean[].class ) { final byte[] buf = new byte[ nel ]; final byte PAD = 'F'; return new ColumnWriter( 'L', 1, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { boolean[] bvals = (boolean[]) value; int leng = Math.min( bvals.length, nel ); for ( ; i < leng; i++ ) { buf[ i ] = bvals[ i ] ? (byte) 'T' : (byte) 'F'; } } Arrays.fill( buf, i, nel, PAD ); stream.write( buf ); } }; } else if ( clazz == byte[].class ) { final byte[] buf = new byte[ nel ]; final byte PAD = (byte) 0; return new ColumnWriter( 'B', 1, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { byte[] bvals = (byte[]) value; int leng = Math.min( bvals.length, nel ); for ( ; i < leng; i++ ) { buf[ i ] = bvals[ i ]; } } Arrays.fill( buf, i, nel, PAD ); for ( int j = 0; j < nel; j++ ) { buf[ j ] = (byte) ( buf[ j ] ^ (byte) 0x80 ); } stream.write( buf ); } double getZero() { return -128.0; } }; } else if ( clazz == short[].class ) { final short PAD = (short) 0; return new ColumnWriter( 'I', 2, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { short[] svals = (short[]) value; int leng = Math.min( svals.length, nel ); for ( ; i < leng; i++ ) { stream.writeShort( svals[ i ] ); } } for ( ; i < nel; i++ ) { stream.writeShort( PAD ); } } }; } else if ( clazz == int[].class ) { final int PAD = 0; return new ColumnWriter( 'J', 4, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { int[] ivals = (int[]) value; int leng = Math.min( ivals.length, nel ); for ( ; i < leng; i++ ) { stream.writeInt( ivals[ i ] ); } } for ( ; i < nel; i++ ) { stream.writeInt( PAD ); } } }; } else if ( clazz == float[].class ) { final float PAD = Float.NaN; return new ColumnWriter( 'E', 4, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { float[] fvals = (float[]) value; int leng = Math.min( fvals.length, nel ); for ( ; i < leng; i++ ) { stream.writeFloat( fvals[ i ] ); } } for ( ; i < nel; i++ ) { stream.writeFloat( PAD ); } } }; } else if ( clazz == double[].class ) { final double PAD = Double.NaN; return new ColumnWriter( 'D', 8, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { double[] dvals = (double[]) value; int leng = Math.min( dvals.length, nel ); for ( ; i < leng; i++ ) { stream.writeDouble( dvals[ i ] ); } } for ( ; i < nel; i++ ) { stream.writeDouble( PAD ); } } }; } else if ( clazz == String[].class ) { final byte PAD = (byte) ' '; final int maxChars = eSize; int[] charDims = new int[ shape.length + 1 ]; charDims[ 0 ] = maxChars; System.arraycopy( shape, 0, charDims, 1, shape.length ); final byte[] buf = new byte[ maxChars ]; return new ColumnWriter( 'A', 1, charDims ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { String[] svals = (String[]) value; int leng = Math.min( svals.length, nel ); for ( ; i < leng; i++ ) { String str = svals[ i ]; int j = 0; if ( str != null ) { int sleng = Math.min( str.length(), maxChars ); for ( ; j < sleng; j++ ) { buf[ j ] = (byte) str.charAt( j ); } } Arrays.fill( buf, j, maxChars, PAD ); stream.write( buf ); } } if ( i < nel ) { Arrays.fill( buf, PAD ); for ( ; i < nel; i++ ) { stream.write( buf ); } } } String getFormat() { return Integer.toString( maxChars * nel ) + 'A'; } }; } else { return null; } } /** * Abstract class defining what needs to be done to write an object * to a DataOutput. */ private static abstract class ColumnWriter { final int length; final int[] dims; final char formatChar; String format; /** * Constructs a new writer with a given length and dimension array. * * @param formatChar the basic character denoting this writers * format in a FITS header * @param length number of bytes per element * @param dims array to be imposed on written value */ ColumnWriter( char formatChar, int elength, int[] dims ) { this.formatChar = formatChar; this.dims = dims; int nel = 1; if ( dims != null ) { for ( int i = 0; i < dims.length; i++ ) { nel *= dims[ i ]; } } length = elength * nel; format = ( nel == 1 ) ? "" + formatChar : ( Integer.toString( nel ) + formatChar ); } /** * Constructs a new scalar writer with a given length. * * @param formatChar the basic character denoting this writers * format in a FITS header * @param length number of bytes per value */ ColumnWriter( char formatChar, int length ) { this( formatChar, length, null ); } /** * Writes a value to an output stream. * * @param stream to squirt the value's byte serialization into * @param value the value to write into <tt>stream</tt> */ abstract void writeValue( DataOutput stream, Object value ) throws IOException; /** * Returns the format character appropriate for this writer. * * @return format character */ char getFormatChar() { return formatChar; } /** * Returns the TFORM string appropriate for this writer. * * @return format string */ String getFormat() { return format; } /** * Returns the number of bytes that <tt>writeValue</tt> will write. */ int getLength() { return length; } /** * Returns the dimensionality (in FITS terms) of the values * that this writes. Null for scalars. * * @return dims */ int[] getDims() { return dims; } /** * Returns zero offset to be used for interpreting values this writes. * * @param zero value */ double getZero() { return 0.0; } /** * Returns the scale factor to be used for interpreting values this * writes. * * @param scale factor */ double getScale() { return 1.0; } /** * Returns the number to be used for blank field output (TNULLn). * Only relevant for integer scalar items. * * @return magic bad value */ Number getBadNumber() { return null; } } }
true
true
private static ColumnWriter makeColumnWriter( ColumnInfo cinfo, int[] shape, int eSize, final boolean nullableInt ) { Class clazz = cinfo.getContentClass(); int n1 = 1; if ( shape != null ) { for ( int i = 0; i < shape.length; i++ ) { n1 *= shape[ i ]; } } final int nel = n1; Number blankNum = null; if ( nullableInt ) { DescribedValue blankVal = cinfo.getAuxDatum( Tables.NULL_VALUE_INFO ); if ( blankVal != null ) { Object blankObj = blankVal.getValue(); if ( blankObj instanceof Number ) { blankNum = (Number) blankObj; } } } if ( clazz == Boolean.class ) { return new ColumnWriter( 'L', 1 ) { void writeValue( DataOutput stream, Object value ) throws IOException { boolean flag = value.equals( Boolean.TRUE ); stream.writeByte( flag ? (byte) 'T' : (byte) 'F' ); } }; } else if ( clazz == Byte.class ) { /* Byte is a bit tricky since a FITS byte is unsigned, while * a byte in a StarTable (a java byte) is signed. */ final byte[] buf = new byte[ 1 ]; final byte badVal = blankNum == null ? (byte) 0 : blankNum.byteValue(); return new ColumnWriter( 'B', 1 ) { void writeValue( DataOutput stream, Object value ) throws IOException { byte b = (value != null) ? ((Number) value).byteValue() : badVal; buf[ 0 ] = (byte) ( b ^ (byte) 0x80 ); stream.write( buf ); } double getZero() { return -128.0; } Number getBadNumber() { return nullableInt ? new Byte( badVal ) : null; } }; } else if ( clazz == Short.class ) { final short badVal = blankNum == null ? Short.MIN_VALUE : blankNum.shortValue(); return new ColumnWriter( 'I', 2 ) { void writeValue( DataOutput stream, Object value ) throws IOException { short sval = ( value != null ) ? ((Number) value).shortValue() : badVal; stream.writeShort( sval ); } Number getBadNumber() { return nullableInt ? new Short( badVal ) : null; } }; } else if ( clazz == Integer.class ) { final int badVal = blankNum == null ? Integer.MIN_VALUE : blankNum.intValue(); return new ColumnWriter( 'J', 4 ) { void writeValue( DataOutput stream, Object value ) throws IOException { int ival = ( value != null ) ? ((Number) value).intValue() : badVal; stream.writeInt( ival ); } Number getBadNumber() { return nullableInt ? new Integer( badVal ) : null; } }; } else if ( clazz == Float.class ) { return new ColumnWriter( 'E', 4 ) { void writeValue( DataOutput stream, Object value ) throws IOException { float fval = ( value != null ) ? ((Number) value).floatValue() : Float.NaN; stream.writeFloat( fval ); } }; } else if ( clazz == Double.class ) { return new ColumnWriter( 'D', 8 ) { void writeValue( DataOutput stream, Object value ) throws IOException { double dval = ( value != null ) ? ((Number) value).doubleValue() : Double.NaN; stream.writeDouble( dval ); } }; } else if ( clazz == Character.class ) { return new ColumnWriter( 'A', 1 ) { void writeValue( DataOutput stream, Object value ) throws IOException { char cval = ( value != null ) ? ((Character) value).charValue() : ' '; stream.writeByte( cval ); } }; } else if ( clazz == String.class ) { final int maxChars = eSize; final byte[] buf = new byte[ maxChars ]; final byte[] blankBuf = new byte[ maxChars ]; final byte PAD = (byte) ' '; final int[] charDims = new int[] { maxChars }; Arrays.fill( blankBuf, PAD ); return new ColumnWriter( 'A', maxChars ) { void writeValue( DataOutput stream, Object value ) throws IOException { byte[] bytes; if ( value == null ) { bytes = blankBuf; } else { String sval = (String) value; int i = 0; int leng = Math.min( sval.length(), maxChars ); bytes = buf; for ( ; i < leng; i++ ) { bytes[ i ] = (byte) sval.charAt( i ); } Arrays.fill( bytes, i, maxChars, PAD ); } stream.write( bytes ); } String getFormat() { return Integer.toString( maxChars ) + 'A'; } int[] getDims() { return charDims; } }; } else if ( clazz == boolean[].class ) { final byte[] buf = new byte[ nel ]; final byte PAD = 'F'; return new ColumnWriter( 'L', 1, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { boolean[] bvals = (boolean[]) value; int leng = Math.min( bvals.length, nel ); for ( ; i < leng; i++ ) { buf[ i ] = bvals[ i ] ? (byte) 'T' : (byte) 'F'; } } Arrays.fill( buf, i, nel, PAD ); stream.write( buf ); } }; } else if ( clazz == byte[].class ) { final byte[] buf = new byte[ nel ]; final byte PAD = (byte) 0; return new ColumnWriter( 'B', 1, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { byte[] bvals = (byte[]) value; int leng = Math.min( bvals.length, nel ); for ( ; i < leng; i++ ) { buf[ i ] = bvals[ i ]; } } Arrays.fill( buf, i, nel, PAD ); for ( int j = 0; j < nel; j++ ) { buf[ j ] = (byte) ( buf[ j ] ^ (byte) 0x80 ); } stream.write( buf ); } double getZero() { return -128.0; } }; } else if ( clazz == short[].class ) { final short PAD = (short) 0; return new ColumnWriter( 'I', 2, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { short[] svals = (short[]) value; int leng = Math.min( svals.length, nel ); for ( ; i < leng; i++ ) { stream.writeShort( svals[ i ] ); } } for ( ; i < nel; i++ ) { stream.writeShort( PAD ); } } }; } else if ( clazz == int[].class ) { final int PAD = 0; return new ColumnWriter( 'J', 4, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { int[] ivals = (int[]) value; int leng = Math.min( ivals.length, nel ); for ( ; i < leng; i++ ) { stream.writeInt( ivals[ i ] ); } } for ( ; i < nel; i++ ) { stream.writeInt( PAD ); } } }; } else if ( clazz == float[].class ) { final float PAD = Float.NaN; return new ColumnWriter( 'E', 4, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { float[] fvals = (float[]) value; int leng = Math.min( fvals.length, nel ); for ( ; i < leng; i++ ) { stream.writeFloat( fvals[ i ] ); } } for ( ; i < nel; i++ ) { stream.writeFloat( PAD ); } } }; } else if ( clazz == double[].class ) { final double PAD = Double.NaN; return new ColumnWriter( 'D', 8, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { double[] dvals = (double[]) value; int leng = Math.min( dvals.length, nel ); for ( ; i < leng; i++ ) { stream.writeDouble( dvals[ i ] ); } } for ( ; i < nel; i++ ) { stream.writeDouble( PAD ); } } }; } else if ( clazz == String[].class ) { final byte PAD = (byte) ' '; final int maxChars = eSize; int[] charDims = new int[ shape.length + 1 ]; charDims[ 0 ] = maxChars; System.arraycopy( shape, 0, charDims, 1, shape.length ); final byte[] buf = new byte[ maxChars ]; return new ColumnWriter( 'A', 1, charDims ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { String[] svals = (String[]) value; int leng = Math.min( svals.length, nel ); for ( ; i < leng; i++ ) { String str = svals[ i ]; int j = 0; if ( str != null ) { int sleng = Math.min( str.length(), maxChars ); for ( ; j < sleng; j++ ) { buf[ j ] = (byte) str.charAt( j ); } } Arrays.fill( buf, j, maxChars, PAD ); stream.write( buf ); } } if ( i < nel ) { Arrays.fill( buf, PAD ); for ( ; i < nel; i++ ) { stream.write( buf ); } } } String getFormat() { return Integer.toString( maxChars * nel ) + 'A'; } }; } else { return null; } }
private static ColumnWriter makeColumnWriter( ColumnInfo cinfo, int[] shape, int eSize, final boolean nullableInt ) { Class clazz = cinfo.getContentClass(); int n1 = 1; if ( shape != null ) { for ( int i = 0; i < shape.length; i++ ) { n1 *= shape[ i ]; } } final int nel = n1; Number blankNum = null; if ( nullableInt ) { DescribedValue blankVal = cinfo.getAuxDatum( Tables.NULL_VALUE_INFO ); if ( blankVal != null ) { Object blankObj = blankVal.getValue(); if ( blankObj instanceof Number ) { blankNum = (Number) blankObj; } } } if ( clazz == Boolean.class ) { return new ColumnWriter( 'L', 1 ) { void writeValue( DataOutput stream, Object value ) throws IOException { boolean flag = Boolean.TRUE.equals( value ); stream.writeByte( flag ? (byte) 'T' : (byte) 'F' ); } }; } else if ( clazz == Byte.class ) { /* Byte is a bit tricky since a FITS byte is unsigned, while * a byte in a StarTable (a java byte) is signed. */ final byte[] buf = new byte[ 1 ]; final byte badVal = blankNum == null ? (byte) 0 : blankNum.byteValue(); return new ColumnWriter( 'B', 1 ) { void writeValue( DataOutput stream, Object value ) throws IOException { byte b = (value != null) ? ((Number) value).byteValue() : badVal; buf[ 0 ] = (byte) ( b ^ (byte) 0x80 ); stream.write( buf ); } double getZero() { return -128.0; } Number getBadNumber() { return nullableInt ? new Byte( badVal ) : null; } }; } else if ( clazz == Short.class ) { final short badVal = blankNum == null ? Short.MIN_VALUE : blankNum.shortValue(); return new ColumnWriter( 'I', 2 ) { void writeValue( DataOutput stream, Object value ) throws IOException { short sval = ( value != null ) ? ((Number) value).shortValue() : badVal; stream.writeShort( sval ); } Number getBadNumber() { return nullableInt ? new Short( badVal ) : null; } }; } else if ( clazz == Integer.class ) { final int badVal = blankNum == null ? Integer.MIN_VALUE : blankNum.intValue(); return new ColumnWriter( 'J', 4 ) { void writeValue( DataOutput stream, Object value ) throws IOException { int ival = ( value != null ) ? ((Number) value).intValue() : badVal; stream.writeInt( ival ); } Number getBadNumber() { return nullableInt ? new Integer( badVal ) : null; } }; } else if ( clazz == Float.class ) { return new ColumnWriter( 'E', 4 ) { void writeValue( DataOutput stream, Object value ) throws IOException { float fval = ( value != null ) ? ((Number) value).floatValue() : Float.NaN; stream.writeFloat( fval ); } }; } else if ( clazz == Double.class ) { return new ColumnWriter( 'D', 8 ) { void writeValue( DataOutput stream, Object value ) throws IOException { double dval = ( value != null ) ? ((Number) value).doubleValue() : Double.NaN; stream.writeDouble( dval ); } }; } else if ( clazz == Character.class ) { return new ColumnWriter( 'A', 1 ) { void writeValue( DataOutput stream, Object value ) throws IOException { char cval = ( value != null ) ? ((Character) value).charValue() : ' '; stream.writeByte( cval ); } }; } else if ( clazz == String.class ) { final int maxChars = eSize; final byte[] buf = new byte[ maxChars ]; final byte[] blankBuf = new byte[ maxChars ]; final byte PAD = (byte) ' '; final int[] charDims = new int[] { maxChars }; Arrays.fill( blankBuf, PAD ); return new ColumnWriter( 'A', maxChars ) { void writeValue( DataOutput stream, Object value ) throws IOException { byte[] bytes; if ( value == null ) { bytes = blankBuf; } else { String sval = (String) value; int i = 0; int leng = Math.min( sval.length(), maxChars ); bytes = buf; for ( ; i < leng; i++ ) { bytes[ i ] = (byte) sval.charAt( i ); } Arrays.fill( bytes, i, maxChars, PAD ); } stream.write( bytes ); } String getFormat() { return Integer.toString( maxChars ) + 'A'; } int[] getDims() { return charDims; } }; } else if ( clazz == boolean[].class ) { final byte[] buf = new byte[ nel ]; final byte PAD = 'F'; return new ColumnWriter( 'L', 1, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { boolean[] bvals = (boolean[]) value; int leng = Math.min( bvals.length, nel ); for ( ; i < leng; i++ ) { buf[ i ] = bvals[ i ] ? (byte) 'T' : (byte) 'F'; } } Arrays.fill( buf, i, nel, PAD ); stream.write( buf ); } }; } else if ( clazz == byte[].class ) { final byte[] buf = new byte[ nel ]; final byte PAD = (byte) 0; return new ColumnWriter( 'B', 1, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { byte[] bvals = (byte[]) value; int leng = Math.min( bvals.length, nel ); for ( ; i < leng; i++ ) { buf[ i ] = bvals[ i ]; } } Arrays.fill( buf, i, nel, PAD ); for ( int j = 0; j < nel; j++ ) { buf[ j ] = (byte) ( buf[ j ] ^ (byte) 0x80 ); } stream.write( buf ); } double getZero() { return -128.0; } }; } else if ( clazz == short[].class ) { final short PAD = (short) 0; return new ColumnWriter( 'I', 2, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { short[] svals = (short[]) value; int leng = Math.min( svals.length, nel ); for ( ; i < leng; i++ ) { stream.writeShort( svals[ i ] ); } } for ( ; i < nel; i++ ) { stream.writeShort( PAD ); } } }; } else if ( clazz == int[].class ) { final int PAD = 0; return new ColumnWriter( 'J', 4, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { int[] ivals = (int[]) value; int leng = Math.min( ivals.length, nel ); for ( ; i < leng; i++ ) { stream.writeInt( ivals[ i ] ); } } for ( ; i < nel; i++ ) { stream.writeInt( PAD ); } } }; } else if ( clazz == float[].class ) { final float PAD = Float.NaN; return new ColumnWriter( 'E', 4, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { float[] fvals = (float[]) value; int leng = Math.min( fvals.length, nel ); for ( ; i < leng; i++ ) { stream.writeFloat( fvals[ i ] ); } } for ( ; i < nel; i++ ) { stream.writeFloat( PAD ); } } }; } else if ( clazz == double[].class ) { final double PAD = Double.NaN; return new ColumnWriter( 'D', 8, shape ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { double[] dvals = (double[]) value; int leng = Math.min( dvals.length, nel ); for ( ; i < leng; i++ ) { stream.writeDouble( dvals[ i ] ); } } for ( ; i < nel; i++ ) { stream.writeDouble( PAD ); } } }; } else if ( clazz == String[].class ) { final byte PAD = (byte) ' '; final int maxChars = eSize; int[] charDims = new int[ shape.length + 1 ]; charDims[ 0 ] = maxChars; System.arraycopy( shape, 0, charDims, 1, shape.length ); final byte[] buf = new byte[ maxChars ]; return new ColumnWriter( 'A', 1, charDims ) { void writeValue( DataOutput stream, Object value ) throws IOException { int i = 0; if ( value != null ) { String[] svals = (String[]) value; int leng = Math.min( svals.length, nel ); for ( ; i < leng; i++ ) { String str = svals[ i ]; int j = 0; if ( str != null ) { int sleng = Math.min( str.length(), maxChars ); for ( ; j < sleng; j++ ) { buf[ j ] = (byte) str.charAt( j ); } } Arrays.fill( buf, j, maxChars, PAD ); stream.write( buf ); } } if ( i < nel ) { Arrays.fill( buf, PAD ); for ( ; i < nel; i++ ) { stream.write( buf ); } } } String getFormat() { return Integer.toString( maxChars * nel ) + 'A'; } }; } else { return null; } }
diff --git a/src/test/java/io/prismic/AppTest.java b/src/test/java/io/prismic/AppTest.java index 712ee98..ca91db9 100644 --- a/src/test/java/io/prismic/AppTest.java +++ b/src/test/java/io/prismic/AppTest.java @@ -1,101 +1,103 @@ package io.prismic; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { Api lbc_api; /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); this.lbc_api = Api.get("https://lesbonneschoses.prismic.io/api"); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Tests whether the api object was initialized, and it ready to be used, * and checks whether its master id is available and correct. */ public void testApiIsInitialized() { assertTrue( "Api object is null.", lbc_api != null ); assertEquals( "Api object does not return the right master ref.", lbc_api.getMaster().getRef(), "UkL0hcuvzYUANCrm" ); } /** * Tests whether a simple query (all the products) works. */ public void testApiQueryWorks(){ assertEquals( "SearchForm query does not return the right amount of documents.", lbc_api.getForm("products").ref(lbc_api.getMaster()).submit().size(), 16 ); } /** * Tests whether complex blog posts serialize well into HTML. * This allows to test many fragment types in one shot. */ public void testDocumentSerializationWorks() { String article1_retrieved = lbc_api.getForm("everything") .query("[[:d = at(document.id, \"UkL0gMuvzYUANCps\")]]") .ref(lbc_api.getMaster()) .submit() .get(0) .asHtml(new DocumentLinkResolver() { public String resolve(Fragment.DocumentLink link) { return "/"+link.getId()+"/"+link.getSlug(); } }); - String article1_expected = "<section data-field=\"blog-post.body\"><h1>The end of a chapter the beginning of a new one</h1><p><img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/8181933ff2f5032daff7d732e33a3beb6f57e09f.jpg\" width=\"640\" height=\"960\"></p><p>Jean-Michel Pastranova, the founder of <em>Les Bonnes Choses</em>, and creator of the whole concept of modern fine pastry, has decided to step down as the CEO and the Director of Workshops of <em>Les Bonnes Choses</em>, to focus on other projects, among which his now best-selling pastry cook books, but also to take on a primary role in a culinary television show to be announced later this year.</p><p>\"I believe I've taken the <em>Les Bonnes Choses</em> concept as far as it can go. <em>Les Bonnes Choses</em> is already an entity that is driven by its people, thanks to a strong internal culture, so I don't feel like they need me as much as they used to. I'm sure they are greater ways to come, to innovate in pastry, and I'm sure <em>Les Bonnes Choses</em>'s coming innovation will be even more mind-blowing than if I had stayed longer.\"</p><p>He will remain as a senior advisor to the board, and to the workshop artists, as his daughter Selena, who has been working with him for several years, will fulfill the CEO role from now on.</p><p>\"My father was able not only to create a revolutionary concept, but also a company culture that puts everyone in charge of driving the company's innovation and quality. That gives us years, maybe decades of revolutionary ideas to come, and there's still a long, wonderful path to walk in the fine pastry world.\"</p></section>\n<section data-field=\"blog-post.shortlede\"><p>Jean-Michel Pastranova steps down as the CEO of Les Bonnes Choses.</p></section>\n<section data-field=\"blog-post.date\"><time>2013-09-25T00:00:00.000-07:00</time></section>\n<section data-field=\"blog-post.author\"><span class=\"text\">Jean-Pierre Durand, Head of Communication</span></section>\n<section data-field=\"blog-post.category\"><span class=\"text\">Announcements</span></section>\n<section data-field=\"blog-post.allow_comments\"><span class=\"text\">No</span></section>\n<section data-field=\"blog-post.relatedproduct[0]\"><a href=\"/UkL0gMuvzYUANCpG/pistachio-macaron\">pistachio-macaron</a></section>\n<section data-field=\"blog-post.relatedproduct[1]\"><a href=\"/UkL0gMuvzYUANCpL/-\">-</a></section>\n<section data-field=\"blog-post.relatedpost[0]\"><a href=\"/UkL0gMuvzYUANCpo/our-world-famous-pastry-art-brainstorm-event\">our-world-famous-pastry-art-brainstorm-event</a></section>\n<section data-field=\"blog-post.relatedpost[1]\"><a href=\"/UkL0gMuvzYUANCpp/les-bonnes-chosess-internship-a-testimony\">les-bonnes-chosess-internship-a-testimony</a></section>"; + // In case of mismatch, check <time> at column 1826 + String article1_expected = "<section data-field=\"blog-post.body\"><h1>The end of a chapter the beginning of a new one</h1><p><img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/8181933ff2f5032daff7d732e33a3beb6f57e09f.jpg\" width=\"640\" height=\"960\"></p><p>Jean-Michel Pastranova, the founder of <em>Les Bonnes Choses</em>, and creator of the whole concept of modern fine pastry, has decided to step down as the CEO and the Director of Workshops of <em>Les Bonnes Choses</em>, to focus on other projects, among which his now best-selling pastry cook books, but also to take on a primary role in a culinary television show to be announced later this year.</p><p>\"I believe I've taken the <em>Les Bonnes Choses</em> concept as far as it can go. <em>Les Bonnes Choses</em> is already an entity that is driven by its people, thanks to a strong internal culture, so I don't feel like they need me as much as they used to. I'm sure they are greater ways to come, to innovate in pastry, and I'm sure <em>Les Bonnes Choses</em>'s coming innovation will be even more mind-blowing than if I had stayed longer.\"</p><p>He will remain as a senior advisor to the board, and to the workshop artists, as his daughter Selena, who has been working with him for several years, will fulfill the CEO role from now on.</p><p>\"My father was able not only to create a revolutionary concept, but also a company culture that puts everyone in charge of driving the company's innovation and quality. That gives us years, maybe decades of revolutionary ideas to come, and there's still a long, wonderful path to walk in the fine pastry world.\"</p></section>\n<section data-field=\"blog-post.shortlede\"><p>Jean-Michel Pastranova steps down as the CEO of Les Bonnes Choses.</p></section>\n<section data-field=\"blog-post.date\"><time>2013-09-25T00:00:00.000+02:00</time></section>\n<section data-field=\"blog-post.author\"><span class=\"text\">Jean-Pierre Durand, Head of Communication</span></section>\n<section data-field=\"blog-post.category\"><span class=\"text\">Announcements</span></section>\n<section data-field=\"blog-post.allow_comments\"><span class=\"text\">No</span></section>\n<section data-field=\"blog-post.relatedproduct[0]\"><a href=\"/UkL0gMuvzYUANCpG/pistachio-macaron\">pistachio-macaron</a></section>\n<section data-field=\"blog-post.relatedproduct[1]\"><a href=\"/UkL0gMuvzYUANCpL/-\">-</a></section>\n<section data-field=\"blog-post.relatedpost[0]\"><a href=\"/UkL0gMuvzYUANCpo/our-world-famous-pastry-art-brainstorm-event\">our-world-famous-pastry-art-brainstorm-event</a></section>\n<section data-field=\"blog-post.relatedpost[1]\"><a href=\"/UkL0gMuvzYUANCpp/les-bonnes-chosess-internship-a-testimony\">les-bonnes-chosess-internship-a-testimony</a></section>"; assertEquals( "HTML serialization of article \"The end of a chapter, the beginning of a new one\"", article1_retrieved, article1_expected ); String article2_retrieved = lbc_api.getForm("everything") .query("[[:d = at(document.id, \"UkL0gMuvzYUANCpr\")]]") .ref(lbc_api.getMaster()) .submit() .get(0) .asHtml(new DocumentLinkResolver() { public String resolve(Fragment.DocumentLink link) { return "/"+link.getId()+"/"+link.getSlug(); } }); - String article2_expected = "<section data-field=\"blog-post.body\"><h1>Get the right approach to ganache</h1><p>A lot of people touch base with us to know about one of our key ingredients, and the essential role it plays in our creations: ganache.</p><p>Indeed, ganache is the macaron's softener, or else, macarons would be but tough biscuits; it is the cupcake's wrapper, or else, cupcakes would be but plain old cake. We even sometimes use ganache within our cupcakes, to soften the cake itself, or as a support to our pies' content.</p><h2>How to approach ganache</h2><p><img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/ee7b984b98db4516aba2eabd54ab498293913c6c.jpg\" width=\"640\" height=\"425\"></p><p>Apart from the taste balance, which is always a challenge when it comes to pastry, the tough part about ganache is about thickness. It is even harder to predict through all the phases the ganache gets to meet (how long will it get melted? how long will it remain in the fridge?). Things get a hell of a lot easier to get once you consider that there are two main ways to get the perfect ganache:</p><ul><li><strong>working from the top down</strong>: start with a thick, almost hard material, and soften it by manipulating it, or by mixing it with a more liquid ingredient (like milk)</li><li><strong>working from the bottom up</strong>: start from a liquid-ish state, and harden it by miwing it with thicker ingredients, or by leaving it in the fridge longer.</li></ul><p>We do hope this advice will empower you in your ganache-making skills. Let us know how you did with it!</p><h2>Ganache at <em>Les Bonnes Choses</em></h2><p>We have a saying at Les Bonnes Choses: \"Once you can make ganache, you can make anything.\"</p><p>As you may know, we like to give our workshop artists the ability to master their art to the top; that is why our Preparation Experts always start off as being Ganache Specialists for Les Bonnes Choses. That way, they're given an opportunity to focus on one exercise before moving on. Once they master their ganache, and are able to provide the most optimal delight to our customers, we consider they'll thrive as they work on other kinds of preparations.</p><h2>About the chocolate in our ganache</h2><p>Now, we've also had a lot of questions about how our chocolate gets made. It's true, as you might know, that we make it ourselves, from Columbian cocoa and French cow milk, with a process that much resembles the one in the following Discovery Channel documentary.</p><div data-oembed=\"http://www.youtube.com/watch?v=Ye78F3-CuXY\" data-oembed-type=\"video\" data-oembed-provider=\"youtube\"><iframe width=\"459\" height=\"344\" src=\"http://www.youtube.com/embed/Ye78F3-CuXY?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe></div></section>\n<section data-field=\"blog-post.shortlede\"><p>Ganache is a tricky topic, but here's some guidance.</p></section>\n<section data-field=\"blog-post.date\"><time>2013-07-24T00:00:00.000-07:00</time></section>\n<section data-field=\"blog-post.author\"><span class=\"text\">Steve Adams, Ganache Specialist</span></section>\n<section data-field=\"blog-post.category\"><span class=\"text\">Do it yourself</span></section>\n<section data-field=\"blog-post.allow_comments\"><span class=\"text\">Yes</span></section>\n<section data-field=\"blog-post.relatedproduct[0]\"><a href=\"/UkL0gMuvzYUANCpm/triple-chocolate-cupcake\">triple-chocolate-cupcake</a></section>\n<section data-field=\"blog-post.relatedproduct[1]\"><a href=\"/UkL0gMuvzYUANCpI/dark-chocolate-macaron\">dark-chocolate-macaron</a></section>\n<section data-field=\"blog-post.relatedpost[0]\"><a href=\"/UkL0gMuvzYUANCpn/tips-to-dress-a-pastry\">tips-to-dress-a-pastry</a></section>\n<section data-field=\"blog-post.relatedpost[1]\"><a href=\"/UkL0gMuvzYUANCpp/les-bonnes-chosess-internship-a-testimony\">les-bonnes-chosess-internship-a-testimony</a></section>"; + // In case of mismatch, check <time> at column 2969 + String article2_expected = "<section data-field=\"blog-post.body\"><h1>Get the right approach to ganache</h1><p>A lot of people touch base with us to know about one of our key ingredients, and the essential role it plays in our creations: ganache.</p><p>Indeed, ganache is the macaron's softener, or else, macarons would be but tough biscuits; it is the cupcake's wrapper, or else, cupcakes would be but plain old cake. We even sometimes use ganache within our cupcakes, to soften the cake itself, or as a support to our pies' content.</p><h2>How to approach ganache</h2><p><img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/ee7b984b98db4516aba2eabd54ab498293913c6c.jpg\" width=\"640\" height=\"425\"></p><p>Apart from the taste balance, which is always a challenge when it comes to pastry, the tough part about ganache is about thickness. It is even harder to predict through all the phases the ganache gets to meet (how long will it get melted? how long will it remain in the fridge?). Things get a hell of a lot easier to get once you consider that there are two main ways to get the perfect ganache:</p><ul><li><strong>working from the top down</strong>: start with a thick, almost hard material, and soften it by manipulating it, or by mixing it with a more liquid ingredient (like milk)</li><li><strong>working from the bottom up</strong>: start from a liquid-ish state, and harden it by miwing it with thicker ingredients, or by leaving it in the fridge longer.</li></ul><p>We do hope this advice will empower you in your ganache-making skills. Let us know how you did with it!</p><h2>Ganache at <em>Les Bonnes Choses</em></h2><p>We have a saying at Les Bonnes Choses: \"Once you can make ganache, you can make anything.\"</p><p>As you may know, we like to give our workshop artists the ability to master their art to the top; that is why our Preparation Experts always start off as being Ganache Specialists for Les Bonnes Choses. That way, they're given an opportunity to focus on one exercise before moving on. Once they master their ganache, and are able to provide the most optimal delight to our customers, we consider they'll thrive as they work on other kinds of preparations.</p><h2>About the chocolate in our ganache</h2><p>Now, we've also had a lot of questions about how our chocolate gets made. It's true, as you might know, that we make it ourselves, from Columbian cocoa and French cow milk, with a process that much resembles the one in the following Discovery Channel documentary.</p><div data-oembed=\"http://www.youtube.com/watch?v=Ye78F3-CuXY\" data-oembed-type=\"video\" data-oembed-provider=\"youtube\"><iframe width=\"459\" height=\"344\" src=\"http://www.youtube.com/embed/Ye78F3-CuXY?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe></div></section>\n<section data-field=\"blog-post.shortlede\"><p>Ganache is a tricky topic, but here's some guidance.</p></section>\n<section data-field=\"blog-post.date\"><time>2013-07-24T00:00:00.000+02:00</time></section>\n<section data-field=\"blog-post.author\"><span class=\"text\">Steve Adams, Ganache Specialist</span></section>\n<section data-field=\"blog-post.category\"><span class=\"text\">Do it yourself</span></section>\n<section data-field=\"blog-post.allow_comments\"><span class=\"text\">Yes</span></section>\n<section data-field=\"blog-post.relatedproduct[0]\"><a href=\"/UkL0gMuvzYUANCpm/triple-chocolate-cupcake\">triple-chocolate-cupcake</a></section>\n<section data-field=\"blog-post.relatedproduct[1]\"><a href=\"/UkL0gMuvzYUANCpI/dark-chocolate-macaron\">dark-chocolate-macaron</a></section>\n<section data-field=\"blog-post.relatedpost[0]\"><a href=\"/UkL0gMuvzYUANCpn/tips-to-dress-a-pastry\">tips-to-dress-a-pastry</a></section>\n<section data-field=\"blog-post.relatedpost[1]\"><a href=\"/UkL0gMuvzYUANCpp/les-bonnes-chosess-internship-a-testimony\">les-bonnes-chosess-internship-a-testimony</a></section>"; assertEquals( "HTML serialization of article \"Get the right approach to ganache\"", article2_retrieved, article2_expected ); } }
false
true
public void testDocumentSerializationWorks() { String article1_retrieved = lbc_api.getForm("everything") .query("[[:d = at(document.id, \"UkL0gMuvzYUANCps\")]]") .ref(lbc_api.getMaster()) .submit() .get(0) .asHtml(new DocumentLinkResolver() { public String resolve(Fragment.DocumentLink link) { return "/"+link.getId()+"/"+link.getSlug(); } }); String article1_expected = "<section data-field=\"blog-post.body\"><h1>The end of a chapter the beginning of a new one</h1><p><img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/8181933ff2f5032daff7d732e33a3beb6f57e09f.jpg\" width=\"640\" height=\"960\"></p><p>Jean-Michel Pastranova, the founder of <em>Les Bonnes Choses</em>, and creator of the whole concept of modern fine pastry, has decided to step down as the CEO and the Director of Workshops of <em>Les Bonnes Choses</em>, to focus on other projects, among which his now best-selling pastry cook books, but also to take on a primary role in a culinary television show to be announced later this year.</p><p>\"I believe I've taken the <em>Les Bonnes Choses</em> concept as far as it can go. <em>Les Bonnes Choses</em> is already an entity that is driven by its people, thanks to a strong internal culture, so I don't feel like they need me as much as they used to. I'm sure they are greater ways to come, to innovate in pastry, and I'm sure <em>Les Bonnes Choses</em>'s coming innovation will be even more mind-blowing than if I had stayed longer.\"</p><p>He will remain as a senior advisor to the board, and to the workshop artists, as his daughter Selena, who has been working with him for several years, will fulfill the CEO role from now on.</p><p>\"My father was able not only to create a revolutionary concept, but also a company culture that puts everyone in charge of driving the company's innovation and quality. That gives us years, maybe decades of revolutionary ideas to come, and there's still a long, wonderful path to walk in the fine pastry world.\"</p></section>\n<section data-field=\"blog-post.shortlede\"><p>Jean-Michel Pastranova steps down as the CEO of Les Bonnes Choses.</p></section>\n<section data-field=\"blog-post.date\"><time>2013-09-25T00:00:00.000-07:00</time></section>\n<section data-field=\"blog-post.author\"><span class=\"text\">Jean-Pierre Durand, Head of Communication</span></section>\n<section data-field=\"blog-post.category\"><span class=\"text\">Announcements</span></section>\n<section data-field=\"blog-post.allow_comments\"><span class=\"text\">No</span></section>\n<section data-field=\"blog-post.relatedproduct[0]\"><a href=\"/UkL0gMuvzYUANCpG/pistachio-macaron\">pistachio-macaron</a></section>\n<section data-field=\"blog-post.relatedproduct[1]\"><a href=\"/UkL0gMuvzYUANCpL/-\">-</a></section>\n<section data-field=\"blog-post.relatedpost[0]\"><a href=\"/UkL0gMuvzYUANCpo/our-world-famous-pastry-art-brainstorm-event\">our-world-famous-pastry-art-brainstorm-event</a></section>\n<section data-field=\"blog-post.relatedpost[1]\"><a href=\"/UkL0gMuvzYUANCpp/les-bonnes-chosess-internship-a-testimony\">les-bonnes-chosess-internship-a-testimony</a></section>"; assertEquals( "HTML serialization of article \"The end of a chapter, the beginning of a new one\"", article1_retrieved, article1_expected ); String article2_retrieved = lbc_api.getForm("everything") .query("[[:d = at(document.id, \"UkL0gMuvzYUANCpr\")]]") .ref(lbc_api.getMaster()) .submit() .get(0) .asHtml(new DocumentLinkResolver() { public String resolve(Fragment.DocumentLink link) { return "/"+link.getId()+"/"+link.getSlug(); } }); String article2_expected = "<section data-field=\"blog-post.body\"><h1>Get the right approach to ganache</h1><p>A lot of people touch base with us to know about one of our key ingredients, and the essential role it plays in our creations: ganache.</p><p>Indeed, ganache is the macaron's softener, or else, macarons would be but tough biscuits; it is the cupcake's wrapper, or else, cupcakes would be but plain old cake. We even sometimes use ganache within our cupcakes, to soften the cake itself, or as a support to our pies' content.</p><h2>How to approach ganache</h2><p><img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/ee7b984b98db4516aba2eabd54ab498293913c6c.jpg\" width=\"640\" height=\"425\"></p><p>Apart from the taste balance, which is always a challenge when it comes to pastry, the tough part about ganache is about thickness. It is even harder to predict through all the phases the ganache gets to meet (how long will it get melted? how long will it remain in the fridge?). Things get a hell of a lot easier to get once you consider that there are two main ways to get the perfect ganache:</p><ul><li><strong>working from the top down</strong>: start with a thick, almost hard material, and soften it by manipulating it, or by mixing it with a more liquid ingredient (like milk)</li><li><strong>working from the bottom up</strong>: start from a liquid-ish state, and harden it by miwing it with thicker ingredients, or by leaving it in the fridge longer.</li></ul><p>We do hope this advice will empower you in your ganache-making skills. Let us know how you did with it!</p><h2>Ganache at <em>Les Bonnes Choses</em></h2><p>We have a saying at Les Bonnes Choses: \"Once you can make ganache, you can make anything.\"</p><p>As you may know, we like to give our workshop artists the ability to master their art to the top; that is why our Preparation Experts always start off as being Ganache Specialists for Les Bonnes Choses. That way, they're given an opportunity to focus on one exercise before moving on. Once they master their ganache, and are able to provide the most optimal delight to our customers, we consider they'll thrive as they work on other kinds of preparations.</p><h2>About the chocolate in our ganache</h2><p>Now, we've also had a lot of questions about how our chocolate gets made. It's true, as you might know, that we make it ourselves, from Columbian cocoa and French cow milk, with a process that much resembles the one in the following Discovery Channel documentary.</p><div data-oembed=\"http://www.youtube.com/watch?v=Ye78F3-CuXY\" data-oembed-type=\"video\" data-oembed-provider=\"youtube\"><iframe width=\"459\" height=\"344\" src=\"http://www.youtube.com/embed/Ye78F3-CuXY?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe></div></section>\n<section data-field=\"blog-post.shortlede\"><p>Ganache is a tricky topic, but here's some guidance.</p></section>\n<section data-field=\"blog-post.date\"><time>2013-07-24T00:00:00.000-07:00</time></section>\n<section data-field=\"blog-post.author\"><span class=\"text\">Steve Adams, Ganache Specialist</span></section>\n<section data-field=\"blog-post.category\"><span class=\"text\">Do it yourself</span></section>\n<section data-field=\"blog-post.allow_comments\"><span class=\"text\">Yes</span></section>\n<section data-field=\"blog-post.relatedproduct[0]\"><a href=\"/UkL0gMuvzYUANCpm/triple-chocolate-cupcake\">triple-chocolate-cupcake</a></section>\n<section data-field=\"blog-post.relatedproduct[1]\"><a href=\"/UkL0gMuvzYUANCpI/dark-chocolate-macaron\">dark-chocolate-macaron</a></section>\n<section data-field=\"blog-post.relatedpost[0]\"><a href=\"/UkL0gMuvzYUANCpn/tips-to-dress-a-pastry\">tips-to-dress-a-pastry</a></section>\n<section data-field=\"blog-post.relatedpost[1]\"><a href=\"/UkL0gMuvzYUANCpp/les-bonnes-chosess-internship-a-testimony\">les-bonnes-chosess-internship-a-testimony</a></section>"; assertEquals( "HTML serialization of article \"Get the right approach to ganache\"", article2_retrieved, article2_expected ); }
public void testDocumentSerializationWorks() { String article1_retrieved = lbc_api.getForm("everything") .query("[[:d = at(document.id, \"UkL0gMuvzYUANCps\")]]") .ref(lbc_api.getMaster()) .submit() .get(0) .asHtml(new DocumentLinkResolver() { public String resolve(Fragment.DocumentLink link) { return "/"+link.getId()+"/"+link.getSlug(); } }); // In case of mismatch, check <time> at column 1826 String article1_expected = "<section data-field=\"blog-post.body\"><h1>The end of a chapter the beginning of a new one</h1><p><img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/8181933ff2f5032daff7d732e33a3beb6f57e09f.jpg\" width=\"640\" height=\"960\"></p><p>Jean-Michel Pastranova, the founder of <em>Les Bonnes Choses</em>, and creator of the whole concept of modern fine pastry, has decided to step down as the CEO and the Director of Workshops of <em>Les Bonnes Choses</em>, to focus on other projects, among which his now best-selling pastry cook books, but also to take on a primary role in a culinary television show to be announced later this year.</p><p>\"I believe I've taken the <em>Les Bonnes Choses</em> concept as far as it can go. <em>Les Bonnes Choses</em> is already an entity that is driven by its people, thanks to a strong internal culture, so I don't feel like they need me as much as they used to. I'm sure they are greater ways to come, to innovate in pastry, and I'm sure <em>Les Bonnes Choses</em>'s coming innovation will be even more mind-blowing than if I had stayed longer.\"</p><p>He will remain as a senior advisor to the board, and to the workshop artists, as his daughter Selena, who has been working with him for several years, will fulfill the CEO role from now on.</p><p>\"My father was able not only to create a revolutionary concept, but also a company culture that puts everyone in charge of driving the company's innovation and quality. That gives us years, maybe decades of revolutionary ideas to come, and there's still a long, wonderful path to walk in the fine pastry world.\"</p></section>\n<section data-field=\"blog-post.shortlede\"><p>Jean-Michel Pastranova steps down as the CEO of Les Bonnes Choses.</p></section>\n<section data-field=\"blog-post.date\"><time>2013-09-25T00:00:00.000+02:00</time></section>\n<section data-field=\"blog-post.author\"><span class=\"text\">Jean-Pierre Durand, Head of Communication</span></section>\n<section data-field=\"blog-post.category\"><span class=\"text\">Announcements</span></section>\n<section data-field=\"blog-post.allow_comments\"><span class=\"text\">No</span></section>\n<section data-field=\"blog-post.relatedproduct[0]\"><a href=\"/UkL0gMuvzYUANCpG/pistachio-macaron\">pistachio-macaron</a></section>\n<section data-field=\"blog-post.relatedproduct[1]\"><a href=\"/UkL0gMuvzYUANCpL/-\">-</a></section>\n<section data-field=\"blog-post.relatedpost[0]\"><a href=\"/UkL0gMuvzYUANCpo/our-world-famous-pastry-art-brainstorm-event\">our-world-famous-pastry-art-brainstorm-event</a></section>\n<section data-field=\"blog-post.relatedpost[1]\"><a href=\"/UkL0gMuvzYUANCpp/les-bonnes-chosess-internship-a-testimony\">les-bonnes-chosess-internship-a-testimony</a></section>"; assertEquals( "HTML serialization of article \"The end of a chapter, the beginning of a new one\"", article1_retrieved, article1_expected ); String article2_retrieved = lbc_api.getForm("everything") .query("[[:d = at(document.id, \"UkL0gMuvzYUANCpr\")]]") .ref(lbc_api.getMaster()) .submit() .get(0) .asHtml(new DocumentLinkResolver() { public String resolve(Fragment.DocumentLink link) { return "/"+link.getId()+"/"+link.getSlug(); } }); // In case of mismatch, check <time> at column 2969 String article2_expected = "<section data-field=\"blog-post.body\"><h1>Get the right approach to ganache</h1><p>A lot of people touch base with us to know about one of our key ingredients, and the essential role it plays in our creations: ganache.</p><p>Indeed, ganache is the macaron's softener, or else, macarons would be but tough biscuits; it is the cupcake's wrapper, or else, cupcakes would be but plain old cake. We even sometimes use ganache within our cupcakes, to soften the cake itself, or as a support to our pies' content.</p><h2>How to approach ganache</h2><p><img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/ee7b984b98db4516aba2eabd54ab498293913c6c.jpg\" width=\"640\" height=\"425\"></p><p>Apart from the taste balance, which is always a challenge when it comes to pastry, the tough part about ganache is about thickness. It is even harder to predict through all the phases the ganache gets to meet (how long will it get melted? how long will it remain in the fridge?). Things get a hell of a lot easier to get once you consider that there are two main ways to get the perfect ganache:</p><ul><li><strong>working from the top down</strong>: start with a thick, almost hard material, and soften it by manipulating it, or by mixing it with a more liquid ingredient (like milk)</li><li><strong>working from the bottom up</strong>: start from a liquid-ish state, and harden it by miwing it with thicker ingredients, or by leaving it in the fridge longer.</li></ul><p>We do hope this advice will empower you in your ganache-making skills. Let us know how you did with it!</p><h2>Ganache at <em>Les Bonnes Choses</em></h2><p>We have a saying at Les Bonnes Choses: \"Once you can make ganache, you can make anything.\"</p><p>As you may know, we like to give our workshop artists the ability to master their art to the top; that is why our Preparation Experts always start off as being Ganache Specialists for Les Bonnes Choses. That way, they're given an opportunity to focus on one exercise before moving on. Once they master their ganache, and are able to provide the most optimal delight to our customers, we consider they'll thrive as they work on other kinds of preparations.</p><h2>About the chocolate in our ganache</h2><p>Now, we've also had a lot of questions about how our chocolate gets made. It's true, as you might know, that we make it ourselves, from Columbian cocoa and French cow milk, with a process that much resembles the one in the following Discovery Channel documentary.</p><div data-oembed=\"http://www.youtube.com/watch?v=Ye78F3-CuXY\" data-oembed-type=\"video\" data-oembed-provider=\"youtube\"><iframe width=\"459\" height=\"344\" src=\"http://www.youtube.com/embed/Ye78F3-CuXY?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe></div></section>\n<section data-field=\"blog-post.shortlede\"><p>Ganache is a tricky topic, but here's some guidance.</p></section>\n<section data-field=\"blog-post.date\"><time>2013-07-24T00:00:00.000+02:00</time></section>\n<section data-field=\"blog-post.author\"><span class=\"text\">Steve Adams, Ganache Specialist</span></section>\n<section data-field=\"blog-post.category\"><span class=\"text\">Do it yourself</span></section>\n<section data-field=\"blog-post.allow_comments\"><span class=\"text\">Yes</span></section>\n<section data-field=\"blog-post.relatedproduct[0]\"><a href=\"/UkL0gMuvzYUANCpm/triple-chocolate-cupcake\">triple-chocolate-cupcake</a></section>\n<section data-field=\"blog-post.relatedproduct[1]\"><a href=\"/UkL0gMuvzYUANCpI/dark-chocolate-macaron\">dark-chocolate-macaron</a></section>\n<section data-field=\"blog-post.relatedpost[0]\"><a href=\"/UkL0gMuvzYUANCpn/tips-to-dress-a-pastry\">tips-to-dress-a-pastry</a></section>\n<section data-field=\"blog-post.relatedpost[1]\"><a href=\"/UkL0gMuvzYUANCpp/les-bonnes-chosess-internship-a-testimony\">les-bonnes-chosess-internship-a-testimony</a></section>"; assertEquals( "HTML serialization of article \"Get the right approach to ganache\"", article2_retrieved, article2_expected ); }
diff --git a/bundles/org.eclipse.orion.server.useradmin/src/org/eclipse/orion/server/useradmin/servlets/AdminFilter.java b/bundles/org.eclipse.orion.server.useradmin/src/org/eclipse/orion/server/useradmin/servlets/AdminFilter.java index d920f88..2a9f725 100644 --- a/bundles/org.eclipse.orion.server.useradmin/src/org/eclipse/orion/server/useradmin/servlets/AdminFilter.java +++ b/bundles/org.eclipse.orion.server.useradmin/src/org/eclipse/orion/server/useradmin/servlets/AdminFilter.java @@ -1,75 +1,76 @@ /******************************************************************************* * Copyright (c) 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.orion.server.useradmin.servlets; import org.eclipse.orion.server.useradmin.OrionUserAdminRegistry; import org.eclipse.orion.server.useradmin.UserAdminActivator; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.osgi.service.useradmin.Authorization; import org.osgi.service.useradmin.UserAdmin; public class AdminFilter implements Filter { private static final String ADMIN_ROLE = "admin"; @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if ("POST".equals(httpRequest.getMethod())) { // everyone can create a user chain.doFilter(request, response); return; } - if ("GET".equals(httpRequest.getMethod()) && httpRequest.getPathInfo().startsWith("/create")) { + String path = httpRequest.getPathInfo(); + if ("GET".equals(httpRequest.getMethod()) && path != null && path.startsWith("/create")) { // display add user form to everyone chain.doFilter(request, response); return; } // TODO: We need a better way to get the authentication service that is configured String user = UserAdminActivator.getDefault().getAuthenticationService().authenticateUser(httpRequest, httpResponse, null); UserAdmin userAdmin; userAdmin = OrionUserAdminRegistry.getDefault().getUserStore(); Authorization authorization = userAdmin.getAuthorization(userAdmin.getUser("login", user)); if (authorization.hasRole(ADMIN_ROLE)) { chain.doFilter(request, response); return; } httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN); } @Override public void destroy() { // TODO Auto-generated method stub } }
true
true
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if ("POST".equals(httpRequest.getMethod())) { // everyone can create a user chain.doFilter(request, response); return; } if ("GET".equals(httpRequest.getMethod()) && httpRequest.getPathInfo().startsWith("/create")) { // display add user form to everyone chain.doFilter(request, response); return; } // TODO: We need a better way to get the authentication service that is configured String user = UserAdminActivator.getDefault().getAuthenticationService().authenticateUser(httpRequest, httpResponse, null); UserAdmin userAdmin; userAdmin = OrionUserAdminRegistry.getDefault().getUserStore(); Authorization authorization = userAdmin.getAuthorization(userAdmin.getUser("login", user)); if (authorization.hasRole(ADMIN_ROLE)) { chain.doFilter(request, response); return; } httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if ("POST".equals(httpRequest.getMethod())) { // everyone can create a user chain.doFilter(request, response); return; } String path = httpRequest.getPathInfo(); if ("GET".equals(httpRequest.getMethod()) && path != null && path.startsWith("/create")) { // display add user form to everyone chain.doFilter(request, response); return; } // TODO: We need a better way to get the authentication service that is configured String user = UserAdminActivator.getDefault().getAuthenticationService().authenticateUser(httpRequest, httpResponse, null); UserAdmin userAdmin; userAdmin = OrionUserAdminRegistry.getDefault().getUserStore(); Authorization authorization = userAdmin.getAuthorization(userAdmin.getUser("login", user)); if (authorization.hasRole(ADMIN_ROLE)) { chain.doFilter(request, response); return; } httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN); }
diff --git a/CS5430/src/database/SocialNetworkDatabaseRegions.java b/CS5430/src/database/SocialNetworkDatabaseRegions.java index 1d91156..1f75d7f 100644 --- a/CS5430/src/database/SocialNetworkDatabaseRegions.java +++ b/CS5430/src/database/SocialNetworkDatabaseRegions.java @@ -1,159 +1,162 @@ package database; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class SocialNetworkDatabaseRegions { //private static int numPostsPerBoard = 2; private static String specialStrPostable = "*"; /** * Determine whether the region exists in this board. * ASSUMES THE BOARD EXISTS. */ public static Boolean regionExists(Connection conn, String boardName, String regionName) { String getRegion = "SELECT * FROM " + boardName + ".regions WHERE rname = ?"; PreparedStatement pstmt = null; ResultSet regionResult = null; Boolean regionExists = null; try { pstmt = conn.prepareStatement(getRegion); pstmt.setString(1, regionName); regionResult = pstmt.executeQuery(); regionExists = new Boolean(regionResult.next()); } catch (SQLException e) { e.printStackTrace(); } finally { DBManager.closePreparedStatement(pstmt); DBManager.closeResultSet(regionResult); } return regionExists; } /** * * Creates a region under the given board with the given region name. * ASSUMES that the boardName is valid. */ //TODO (author) ensure the user is an admin for the board. public static String createRegion(Connection conn, String username, String boardName, String regionName) { PreparedStatement regionPstmt = null; String createRegion = "INSERT INTO " + boardName + ".regions VALUES (?)"; boolean success = false; String sqlexmsg = ""; try { regionPstmt = conn.prepareStatement(createRegion); regionPstmt.setString(1, regionName); success = (regionPstmt.executeUpdate() == 1); } catch (SQLException e) { if (e.getErrorCode() == DBManager.DUPLICATE_KEY_CODE) { sqlexmsg = "print A region in this board already exists with that name. Try a different name"; } else { e.printStackTrace(); sqlexmsg = "print Error: Database error while creating the region. Contact the admin."; } } finally { DBManager.closePreparedStatement(regionPstmt); } if (success) { return "print Region \"" + regionName + "\" successfully created."; } else { return sqlexmsg; } } /** * Gets a list of regions that the user has access to. * If the user is an admin, the user can see all regions. * Also returns, with each region, the most recently posted posts. * Assumes boardName is not null and is a valid board. * TODO (author) double check that the user can call this method within this board * */ public static String getRegionListRecentPosts(Connection conn, String username, String boardName){ String regionsAndPosts = "print Regions:;"; PreparedStatement regionPstmt = null; String fetchRegionsMember = "SELECT rname, privileges FROM " + boardName + ".regionprivileges " + "WHERE username = ?"; Statement regionStmt = null; String fetchRegionsAdmin = "SELECT * FROM " + boardName + ".regions"; PreparedStatement recentPostsPstmt = null; - String fetchRecentPost = "SELECT rname, pid, P.postedBy, R.repliedBy, MAX(R.dateReplied)" + - "FROM " + boardName + ".posts AS P INNER JOIN " + + String fetchRecentPost = "SELECT rname, pid, P.postedBy, P.datePosted, R.repliedBy, MAX(R.dateReplied)" + + "FROM " + boardName + ".posts AS P LEFT OUTER JOIN " + boardName + ".replies AS R USING (rname, pid) " + - "WHERE rname = ?"; + "WHERE rname = ? ORDER BY P.datePosted DESC"; ResultSet regionsResults = null; ResultSet recentPostsResults = null; boolean sqlex = false; try { String role = SocialNetworkDatabaseBoards.getUserRole(conn, username); if (role.equals("member")) { regionPstmt = conn.prepareStatement(fetchRegionsMember); regionPstmt.setString(1, username); regionsResults = regionPstmt.executeQuery(); } else if (!role.equals("")) { //user is an admin regionStmt = conn.createStatement(); regionsResults = regionStmt.executeQuery(fetchRegionsAdmin); } else { //error occurred while acquiring role return "print Error: Database Error while querying viewable regions. Contact an admin.;"; } recentPostsPstmt = conn.prepareStatement(fetchRecentPost); while (regionsResults.next()) { /*For each region, fetch the two most recent posts*/ if (role.equals("member")) { regionsAndPosts += "print \t" + (regionsResults.getString("privileges").equals("viewpost") ? specialStrPostable : "") + regionsResults.getString("rname") + ";"; } else { regionsAndPosts += "print \t" + specialStrPostable + regionsResults.getString("rname") + ";"; } recentPostsPstmt.setString(1, regionsResults.getString("rname")); recentPostsResults = recentPostsPstmt.executeQuery(); - if (recentPostsResults.next()) { + if (!recentPostsResults.next()) { regionsAndPosts += "print \t\tNo Posts for this Region;"; } else { regionsAndPosts += "print \t\tMost Recently Updated Post#" + recentPostsResults.getInt("pid") + - "[" + recentPostsResults.getString("P.postedBy") + "];print \t\t" + - "Most Recent Reply: [" + recentPostsResults.getString("R.repliedBy") + "] " + - recentPostsResults.getTimestamp("MAX(R.dateReplied)").toString() + ";"; + "[" + recentPostsResults.getString("P.postedBy") + "];"; + if (recentPostsResults.getTimestamp("MAX(R.dateReplied)") != null) { + regionsAndPosts += "print \t\t " + + "Most Recent Reply: [" + recentPostsResults.getString("R.repliedBy") + "] " + + recentPostsResults.getTimestamp("MAX(R.dateReplied)").toString() + ";"; + } } } } catch (SQLException e) { e.printStackTrace(); sqlex = true; } finally { DBManager.closePreparedStatement(regionPstmt); DBManager.closeStatement(regionStmt); DBManager.closePreparedStatement(recentPostsPstmt); DBManager.closeResultSet(regionsResults); DBManager.closeResultSet(recentPostsResults); } if (regionsAndPosts.equals("print Regions:;") && !sqlex) { //boardName assumed to be valid. return "print No Regions for this Board"; } else if (sqlex) { return "print Error: Database Error while querying viewable regions. Contact an admin.;"; } else return regionsAndPosts; } }
false
true
public static String getRegionListRecentPosts(Connection conn, String username, String boardName){ String regionsAndPosts = "print Regions:;"; PreparedStatement regionPstmt = null; String fetchRegionsMember = "SELECT rname, privileges FROM " + boardName + ".regionprivileges " + "WHERE username = ?"; Statement regionStmt = null; String fetchRegionsAdmin = "SELECT * FROM " + boardName + ".regions"; PreparedStatement recentPostsPstmt = null; String fetchRecentPost = "SELECT rname, pid, P.postedBy, R.repliedBy, MAX(R.dateReplied)" + "FROM " + boardName + ".posts AS P INNER JOIN " + boardName + ".replies AS R USING (rname, pid) " + "WHERE rname = ?"; ResultSet regionsResults = null; ResultSet recentPostsResults = null; boolean sqlex = false; try { String role = SocialNetworkDatabaseBoards.getUserRole(conn, username); if (role.equals("member")) { regionPstmt = conn.prepareStatement(fetchRegionsMember); regionPstmt.setString(1, username); regionsResults = regionPstmt.executeQuery(); } else if (!role.equals("")) { //user is an admin regionStmt = conn.createStatement(); regionsResults = regionStmt.executeQuery(fetchRegionsAdmin); } else { //error occurred while acquiring role return "print Error: Database Error while querying viewable regions. Contact an admin.;"; } recentPostsPstmt = conn.prepareStatement(fetchRecentPost); while (regionsResults.next()) { /*For each region, fetch the two most recent posts*/ if (role.equals("member")) { regionsAndPosts += "print \t" + (regionsResults.getString("privileges").equals("viewpost") ? specialStrPostable : "") + regionsResults.getString("rname") + ";"; } else { regionsAndPosts += "print \t" + specialStrPostable + regionsResults.getString("rname") + ";"; } recentPostsPstmt.setString(1, regionsResults.getString("rname")); recentPostsResults = recentPostsPstmt.executeQuery(); if (recentPostsResults.next()) { regionsAndPosts += "print \t\tNo Posts for this Region;"; } else { regionsAndPosts += "print \t\tMost Recently Updated Post#" + recentPostsResults.getInt("pid") + "[" + recentPostsResults.getString("P.postedBy") + "];print \t\t" + "Most Recent Reply: [" + recentPostsResults.getString("R.repliedBy") + "] " + recentPostsResults.getTimestamp("MAX(R.dateReplied)").toString() + ";"; } } } catch (SQLException e) { e.printStackTrace(); sqlex = true; } finally { DBManager.closePreparedStatement(regionPstmt); DBManager.closeStatement(regionStmt); DBManager.closePreparedStatement(recentPostsPstmt); DBManager.closeResultSet(regionsResults); DBManager.closeResultSet(recentPostsResults); } if (regionsAndPosts.equals("print Regions:;") && !sqlex) { //boardName assumed to be valid. return "print No Regions for this Board"; } else if (sqlex) { return "print Error: Database Error while querying viewable regions. Contact an admin.;"; } else return regionsAndPosts; }
public static String getRegionListRecentPosts(Connection conn, String username, String boardName){ String regionsAndPosts = "print Regions:;"; PreparedStatement regionPstmt = null; String fetchRegionsMember = "SELECT rname, privileges FROM " + boardName + ".regionprivileges " + "WHERE username = ?"; Statement regionStmt = null; String fetchRegionsAdmin = "SELECT * FROM " + boardName + ".regions"; PreparedStatement recentPostsPstmt = null; String fetchRecentPost = "SELECT rname, pid, P.postedBy, P.datePosted, R.repliedBy, MAX(R.dateReplied)" + "FROM " + boardName + ".posts AS P LEFT OUTER JOIN " + boardName + ".replies AS R USING (rname, pid) " + "WHERE rname = ? ORDER BY P.datePosted DESC"; ResultSet regionsResults = null; ResultSet recentPostsResults = null; boolean sqlex = false; try { String role = SocialNetworkDatabaseBoards.getUserRole(conn, username); if (role.equals("member")) { regionPstmt = conn.prepareStatement(fetchRegionsMember); regionPstmt.setString(1, username); regionsResults = regionPstmt.executeQuery(); } else if (!role.equals("")) { //user is an admin regionStmt = conn.createStatement(); regionsResults = regionStmt.executeQuery(fetchRegionsAdmin); } else { //error occurred while acquiring role return "print Error: Database Error while querying viewable regions. Contact an admin.;"; } recentPostsPstmt = conn.prepareStatement(fetchRecentPost); while (regionsResults.next()) { /*For each region, fetch the two most recent posts*/ if (role.equals("member")) { regionsAndPosts += "print \t" + (regionsResults.getString("privileges").equals("viewpost") ? specialStrPostable : "") + regionsResults.getString("rname") + ";"; } else { regionsAndPosts += "print \t" + specialStrPostable + regionsResults.getString("rname") + ";"; } recentPostsPstmt.setString(1, regionsResults.getString("rname")); recentPostsResults = recentPostsPstmt.executeQuery(); if (!recentPostsResults.next()) { regionsAndPosts += "print \t\tNo Posts for this Region;"; } else { regionsAndPosts += "print \t\tMost Recently Updated Post#" + recentPostsResults.getInt("pid") + "[" + recentPostsResults.getString("P.postedBy") + "];"; if (recentPostsResults.getTimestamp("MAX(R.dateReplied)") != null) { regionsAndPosts += "print \t\t " + "Most Recent Reply: [" + recentPostsResults.getString("R.repliedBy") + "] " + recentPostsResults.getTimestamp("MAX(R.dateReplied)").toString() + ";"; } } } } catch (SQLException e) { e.printStackTrace(); sqlex = true; } finally { DBManager.closePreparedStatement(regionPstmt); DBManager.closeStatement(regionStmt); DBManager.closePreparedStatement(recentPostsPstmt); DBManager.closeResultSet(regionsResults); DBManager.closeResultSet(recentPostsResults); } if (regionsAndPosts.equals("print Regions:;") && !sqlex) { //boardName assumed to be valid. return "print No Regions for this Board"; } else if (sqlex) { return "print Error: Database Error while querying viewable regions. Contact an admin.;"; } else return regionsAndPosts; }
diff --git a/src/test/java/com/solidstategroup/radar/test/dao/generic/MedicalResultDaoTest.java b/src/test/java/com/solidstategroup/radar/test/dao/generic/MedicalResultDaoTest.java index 54b0eb0c..b2a097ca 100644 --- a/src/test/java/com/solidstategroup/radar/test/dao/generic/MedicalResultDaoTest.java +++ b/src/test/java/com/solidstategroup/radar/test/dao/generic/MedicalResultDaoTest.java @@ -1,59 +1,66 @@ package com.solidstategroup.radar.test.dao.generic; import com.solidstategroup.radar.dao.generic.DiseaseGroupDao; import com.solidstategroup.radar.dao.generic.MedicalResultDao; import com.solidstategroup.radar.model.generic.DiseaseGroup; import com.solidstategroup.radar.model.generic.MedicalResult; import com.solidstategroup.radar.test.dao.BaseDaoTest; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.Date; public class MedicalResultDaoTest extends BaseDaoTest { @Autowired private MedicalResultDao medicalResultDao; @Autowired DiseaseGroupDao diseaseGroupDao; @Test public void testSave() throws Exception { //save new record Date date = new Date(); MedicalResult medicalResult = new MedicalResult(); + medicalResult.setNhsNo("123456789"); medicalResult.setRadarNo(1L); medicalResult.setSerumCreatanine(10.25); medicalResult.setAntihypertensiveDrugs(MedicalResult.YesNo.YES); + medicalResult.setAntihypertensiveDrugsDate(date); medicalResult.setBloodUrea(12.25); medicalResult.setBloodUreaDate(date); medicalResult.setSerumCreatanine(15.5); medicalResult.setCreatanineDate(date); medicalResult.setBpDiastolic(18); medicalResult.setBpSystolic(19); medicalResult.setHeight(100.5); medicalResult.setHeightDate(date); medicalResult.setWeight(122.0); medicalResult.setWeightDate(date); medicalResult.setBpDate(date); + medicalResult.setPcr(1); + medicalResult.setPcrDate(date); + medicalResult.setAcr(1); + medicalResult.setAcrDate(date); DiseaseGroup diseaseGroup = diseaseGroupDao.getById("1"); medicalResult.setDiseaseGroup(diseaseGroup); medicalResultDao.save(medicalResult); medicalResult = medicalResultDao.getMedicalResult(1L, diseaseGroup.getId()); Assert.assertNotNull("Medical result should not be null", medicalResult); // update record medicalResult.setBloodUrea(15.5); + medicalResult.setNhsNo("123456789"); medicalResultDao.save(medicalResult); medicalResult = medicalResultDao.getMedicalResult(1L, diseaseGroup.getId()); Assert.assertEquals("Blood urea has wrong value", new Double(15.5), medicalResult.getBloodUrea()); } }
false
true
public void testSave() throws Exception { //save new record Date date = new Date(); MedicalResult medicalResult = new MedicalResult(); medicalResult.setRadarNo(1L); medicalResult.setSerumCreatanine(10.25); medicalResult.setAntihypertensiveDrugs(MedicalResult.YesNo.YES); medicalResult.setBloodUrea(12.25); medicalResult.setBloodUreaDate(date); medicalResult.setSerumCreatanine(15.5); medicalResult.setCreatanineDate(date); medicalResult.setBpDiastolic(18); medicalResult.setBpSystolic(19); medicalResult.setHeight(100.5); medicalResult.setHeightDate(date); medicalResult.setWeight(122.0); medicalResult.setWeightDate(date); medicalResult.setBpDate(date); DiseaseGroup diseaseGroup = diseaseGroupDao.getById("1"); medicalResult.setDiseaseGroup(diseaseGroup); medicalResultDao.save(medicalResult); medicalResult = medicalResultDao.getMedicalResult(1L, diseaseGroup.getId()); Assert.assertNotNull("Medical result should not be null", medicalResult); // update record medicalResult.setBloodUrea(15.5); medicalResultDao.save(medicalResult); medicalResult = medicalResultDao.getMedicalResult(1L, diseaseGroup.getId()); Assert.assertEquals("Blood urea has wrong value", new Double(15.5), medicalResult.getBloodUrea()); }
public void testSave() throws Exception { //save new record Date date = new Date(); MedicalResult medicalResult = new MedicalResult(); medicalResult.setNhsNo("123456789"); medicalResult.setRadarNo(1L); medicalResult.setSerumCreatanine(10.25); medicalResult.setAntihypertensiveDrugs(MedicalResult.YesNo.YES); medicalResult.setAntihypertensiveDrugsDate(date); medicalResult.setBloodUrea(12.25); medicalResult.setBloodUreaDate(date); medicalResult.setSerumCreatanine(15.5); medicalResult.setCreatanineDate(date); medicalResult.setBpDiastolic(18); medicalResult.setBpSystolic(19); medicalResult.setHeight(100.5); medicalResult.setHeightDate(date); medicalResult.setWeight(122.0); medicalResult.setWeightDate(date); medicalResult.setBpDate(date); medicalResult.setPcr(1); medicalResult.setPcrDate(date); medicalResult.setAcr(1); medicalResult.setAcrDate(date); DiseaseGroup diseaseGroup = diseaseGroupDao.getById("1"); medicalResult.setDiseaseGroup(diseaseGroup); medicalResultDao.save(medicalResult); medicalResult = medicalResultDao.getMedicalResult(1L, diseaseGroup.getId()); Assert.assertNotNull("Medical result should not be null", medicalResult); // update record medicalResult.setBloodUrea(15.5); medicalResult.setNhsNo("123456789"); medicalResultDao.save(medicalResult); medicalResult = medicalResultDao.getMedicalResult(1L, diseaseGroup.getId()); Assert.assertEquals("Blood urea has wrong value", new Double(15.5), medicalResult.getBloodUrea()); }
diff --git a/src/test/java/kata/holdem/PokerRoundScenariosTest.java b/src/test/java/kata/holdem/PokerRoundScenariosTest.java index 96bda9c..6a8cc5a 100644 --- a/src/test/java/kata/holdem/PokerRoundScenariosTest.java +++ b/src/test/java/kata/holdem/PokerRoundScenariosTest.java @@ -1,128 +1,128 @@ package kata.holdem; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class PokerRoundScenariosTest { @Parameterized.Parameters public static Collection<Object[]> rounds() { return Arrays.asList(new Object[][] { { Round.scenario("player folds", "john 4h 2d", "jane Th 3c").deal("Ks 8d 4d").fold("jane") .expect("john: 4h 2d Ks 8d 4d [Pair 4h 4d Kicker(s) Ks 8d 2d] (Winner)\n" + "jane: Th 3c Ks 8d 4d [folded]") }, { Round.scenario("high card", "john 4d 2d", "jane Ah 3c").deal("Qc Td 5s 6c 9h") .expect("john: 4d 2d Qc Td 5s 6c 9h [High Card Kicker(s) Qc Td 9h 6c 5s]\n" + "jane: Ah 3c Qc Td 5s 6c 9h [High Card Kicker(s) Ah Qc Td 9h 6c] (Winner)") }, { Round.scenario("pair over high card", "john 4d 2d", "jane Ah 3c").deal("Qc Td 4s 6c 9h") .expect("john: 4d 2d Qc Td 4s 6c 9h [Pair 4d 4s Kicker(s) Qc Td 9h] (Winner)\n" + "jane: Ah 3c Qc Td 4s 6c 9h [High Card Kicker(s) Ah Qc Td 9h 6c]") }, { Round.scenario("three-of-a-kind beats high card", "john 2h 2d", "jane Ah 3c").deal("2c Td 4s 6c 9h") .expect("john: 2h 2d 2c Td 4s 6c 9h [Three Of A Kind 2h 2d 2c Kicker(s) Td 9h] (Winner)\n" + "jane: Ah 3c 2c Td 4s 6c 9h [High Card Kicker(s) Ah Td 9h 6c 4s]") }, { Round.scenario("three-of-a-kind beats pair", "john Ah 2c", "jane 2h 2d").deal("Td 4s 6c 9h 2s") .expect("john: Ah 2c Td 4s 6c 9h 2s [Pair 2c 2s Kicker(s) Ah Td 9h]\n" + "jane: 2h 2d Td 4s 6c 9h 2s [Three Of A Kind 2h 2d 2s Kicker(s) Td 9h] (Winner)") }, { Round.scenario("three-of-a-kind beats two-pair", "john 2h 2d", "jane Ah 2c").deal("As Qc Td 4s 2s") .expect("john: 2h 2d As Qc Td 4s 2s [Three Of A Kind 2h 2d 2s Kicker(s) As Qc] (Winner)\n" + "jane: Ah 2c As Qc Td 4s 2s [Two Pair Ah As 2c 2s Kicker(s) Qc]") }, { Round.scenario("highest three-of-a-kind wins", "john 2h 2d", "jane Ah Ac").deal("Qc Td 4s Ad 2s") .expect("john: 2h 2d Qc Td 4s Ad 2s [Three Of A Kind 2h 2d 2s Kicker(s) Ad Qc]\n" + "jane: Ah Ac Qc Td 4s Ad 2s [Three Of A Kind Ah Ac Ad Kicker(s) Qc Td] (Winner)") }, { Round.scenario("straight beats high card", "john 2h 3d", "jane Ah 9c").deal("6c 5d 4s Kc Th") - .expect("john: 2h 3d 6c 5d 4s Kc Th [Straight 2h 3d 4s 5d 6c] (Winner)\n" + + .expect("john: 2h 3d 6c 5d 4s Kc Th [Straight 6c 5d 4s 3d 2h] (Winner)\n" + "jane: Ah 9c 6c 5d 4s Kc Th [High Card Kicker(s) Ah Kc Th 9c 6c]") }, { Round.scenario("straight beats pair", "john Kh 2c", "jane 2h 3d").deal("6c 5d 4s Kc Th") .expect("john: Kh 2c 6c 5d 4s Kc Th [Pair Kh Kc Kicker(s) Th 6c 5d]\n" + - "jane: 2h 3d 6c 5d 4s Kc Th [Straight 2h 3d 4s 5d 6c] (Winner)") }, + "jane: 2h 3d 6c 5d 4s Kc Th [Straight 6c 5d 4s 3d 2h] (Winner)") }, { Round.scenario("straight beats two-pair", "john 2h 3d", "jane 6h 4c").deal("6c 5d 4s Kc Th") - .expect("john: 2h 3d 6c 5d 4s Kc Th [Straight 2h 3d 4s 5d 6c] (Winner)\n" + + .expect("john: 2h 3d 6c 5d 4s Kc Th [Straight 6c 5d 4s 3d 2h] (Winner)\n" + "jane: 6h 4c 6c 5d 4s Kc Th [Two Pair 6h 6c 4c 4s Kicker(s) Kc]") }, { Round.scenario("straight beats three-of-a-kind", "john 2h 3d", "jane 5h 5c").deal("6c 5d 4s Kc Th") - .expect("john: 2h 3d 6c 5d 4s Kc Th [Straight 2h 3d 4s 5d 6c] (Winner)\n" + + .expect("john: 2h 3d 6c 5d 4s Kc Th [Straight 6c 5d 4s 3d 2h] (Winner)\n" + "jane: 5h 5c 6c 5d 4s Kc Th [Three Of A Kind 5h 5c 5d Kicker(s) Kc Th]") }, { Round.scenario("highest straight wins", "john 2h 3d", "jane 8h Ac").deal("6c 5d 4s 7c Th") - .expect("john: 2h 3d 6c 5d 4s 7c Th [Straight 3d 4s 5d 6c 7c]\n" + - "jane: 8h Ac 6c 5d 4s 7c Th [Straight 4s 5d 6c 7c 8h] (Winner)") } + .expect("john: 2h 3d 6c 5d 4s 7c Th [Straight 7c 6c 5d 4s 3d]\n" + + "jane: 8h Ac 6c 5d 4s 7c Th [Straight 8h 7c 6c 5d 4s] (Winner)") } }); } private final Round round; public PokerRoundScenariosTest(Round round) { this.round = round; } @Test public void verify_rounds() { Assert.assertEquals(round.getDescription(), round.getExpectedResult(), round.getRound().toString()); } private static class Round { public static Round scenario(String scenarioDescription, String... playersAndHoleCards) { List<String> players = new ArrayList<String>(); List<String[]> playersHoleCard = new ArrayList<String[]>(); for (String playerAndHoleCards : playersAndHoleCards) { String[] playerAndHoleCardsSplit = playerAndHoleCards.split(" "); playersHoleCard.add(playerAndHoleCardsSplit); players.add(playerAndHoleCardsSplit[0]); } Round round = new Round(scenarioDescription, players.toArray(new String[0])); for (String[] playerAndHoleCards : playersHoleCard) round.getRound().deal(playerAndHoleCards[0], playerAndHoleCards[1], playerAndHoleCards[2]); return round; } private String scenarioDescription; private PokerRound round; private boolean dealtTurn = false; private String expectedResult; private Round(String scenarioDescription, String[] players) { this.scenarioDescription = scenarioDescription; round = new PokerGame(players).newRound(); } public PokerRound getRound() { return round; } public String getDescription() { return scenarioDescription; } public Round deal(String cards) { String[] card = cards.split(" "); if (card.length == 3) round.dealFlop(card[0], card[1], card[2]); else if (card.length == 5) round.dealFlop(card[0], card[1], card[2]).dealTurn(card[3]).dealRiver(card[4]); else if (dealtTurn) round.dealRiver(cards); else { round.dealTurn(cards); dealtTurn = true; } return this; } public Round fold(String player) { round.fold(player); return this; } public Round expect(String result) { expectedResult = result; return this; } public String getExpectedResult() { return expectedResult; } } }
false
true
public static Collection<Object[]> rounds() { return Arrays.asList(new Object[][] { { Round.scenario("player folds", "john 4h 2d", "jane Th 3c").deal("Ks 8d 4d").fold("jane") .expect("john: 4h 2d Ks 8d 4d [Pair 4h 4d Kicker(s) Ks 8d 2d] (Winner)\n" + "jane: Th 3c Ks 8d 4d [folded]") }, { Round.scenario("high card", "john 4d 2d", "jane Ah 3c").deal("Qc Td 5s 6c 9h") .expect("john: 4d 2d Qc Td 5s 6c 9h [High Card Kicker(s) Qc Td 9h 6c 5s]\n" + "jane: Ah 3c Qc Td 5s 6c 9h [High Card Kicker(s) Ah Qc Td 9h 6c] (Winner)") }, { Round.scenario("pair over high card", "john 4d 2d", "jane Ah 3c").deal("Qc Td 4s 6c 9h") .expect("john: 4d 2d Qc Td 4s 6c 9h [Pair 4d 4s Kicker(s) Qc Td 9h] (Winner)\n" + "jane: Ah 3c Qc Td 4s 6c 9h [High Card Kicker(s) Ah Qc Td 9h 6c]") }, { Round.scenario("three-of-a-kind beats high card", "john 2h 2d", "jane Ah 3c").deal("2c Td 4s 6c 9h") .expect("john: 2h 2d 2c Td 4s 6c 9h [Three Of A Kind 2h 2d 2c Kicker(s) Td 9h] (Winner)\n" + "jane: Ah 3c 2c Td 4s 6c 9h [High Card Kicker(s) Ah Td 9h 6c 4s]") }, { Round.scenario("three-of-a-kind beats pair", "john Ah 2c", "jane 2h 2d").deal("Td 4s 6c 9h 2s") .expect("john: Ah 2c Td 4s 6c 9h 2s [Pair 2c 2s Kicker(s) Ah Td 9h]\n" + "jane: 2h 2d Td 4s 6c 9h 2s [Three Of A Kind 2h 2d 2s Kicker(s) Td 9h] (Winner)") }, { Round.scenario("three-of-a-kind beats two-pair", "john 2h 2d", "jane Ah 2c").deal("As Qc Td 4s 2s") .expect("john: 2h 2d As Qc Td 4s 2s [Three Of A Kind 2h 2d 2s Kicker(s) As Qc] (Winner)\n" + "jane: Ah 2c As Qc Td 4s 2s [Two Pair Ah As 2c 2s Kicker(s) Qc]") }, { Round.scenario("highest three-of-a-kind wins", "john 2h 2d", "jane Ah Ac").deal("Qc Td 4s Ad 2s") .expect("john: 2h 2d Qc Td 4s Ad 2s [Three Of A Kind 2h 2d 2s Kicker(s) Ad Qc]\n" + "jane: Ah Ac Qc Td 4s Ad 2s [Three Of A Kind Ah Ac Ad Kicker(s) Qc Td] (Winner)") }, { Round.scenario("straight beats high card", "john 2h 3d", "jane Ah 9c").deal("6c 5d 4s Kc Th") .expect("john: 2h 3d 6c 5d 4s Kc Th [Straight 2h 3d 4s 5d 6c] (Winner)\n" + "jane: Ah 9c 6c 5d 4s Kc Th [High Card Kicker(s) Ah Kc Th 9c 6c]") }, { Round.scenario("straight beats pair", "john Kh 2c", "jane 2h 3d").deal("6c 5d 4s Kc Th") .expect("john: Kh 2c 6c 5d 4s Kc Th [Pair Kh Kc Kicker(s) Th 6c 5d]\n" + "jane: 2h 3d 6c 5d 4s Kc Th [Straight 2h 3d 4s 5d 6c] (Winner)") }, { Round.scenario("straight beats two-pair", "john 2h 3d", "jane 6h 4c").deal("6c 5d 4s Kc Th") .expect("john: 2h 3d 6c 5d 4s Kc Th [Straight 2h 3d 4s 5d 6c] (Winner)\n" + "jane: 6h 4c 6c 5d 4s Kc Th [Two Pair 6h 6c 4c 4s Kicker(s) Kc]") }, { Round.scenario("straight beats three-of-a-kind", "john 2h 3d", "jane 5h 5c").deal("6c 5d 4s Kc Th") .expect("john: 2h 3d 6c 5d 4s Kc Th [Straight 2h 3d 4s 5d 6c] (Winner)\n" + "jane: 5h 5c 6c 5d 4s Kc Th [Three Of A Kind 5h 5c 5d Kicker(s) Kc Th]") }, { Round.scenario("highest straight wins", "john 2h 3d", "jane 8h Ac").deal("6c 5d 4s 7c Th") .expect("john: 2h 3d 6c 5d 4s 7c Th [Straight 3d 4s 5d 6c 7c]\n" + "jane: 8h Ac 6c 5d 4s 7c Th [Straight 4s 5d 6c 7c 8h] (Winner)") } }); }
public static Collection<Object[]> rounds() { return Arrays.asList(new Object[][] { { Round.scenario("player folds", "john 4h 2d", "jane Th 3c").deal("Ks 8d 4d").fold("jane") .expect("john: 4h 2d Ks 8d 4d [Pair 4h 4d Kicker(s) Ks 8d 2d] (Winner)\n" + "jane: Th 3c Ks 8d 4d [folded]") }, { Round.scenario("high card", "john 4d 2d", "jane Ah 3c").deal("Qc Td 5s 6c 9h") .expect("john: 4d 2d Qc Td 5s 6c 9h [High Card Kicker(s) Qc Td 9h 6c 5s]\n" + "jane: Ah 3c Qc Td 5s 6c 9h [High Card Kicker(s) Ah Qc Td 9h 6c] (Winner)") }, { Round.scenario("pair over high card", "john 4d 2d", "jane Ah 3c").deal("Qc Td 4s 6c 9h") .expect("john: 4d 2d Qc Td 4s 6c 9h [Pair 4d 4s Kicker(s) Qc Td 9h] (Winner)\n" + "jane: Ah 3c Qc Td 4s 6c 9h [High Card Kicker(s) Ah Qc Td 9h 6c]") }, { Round.scenario("three-of-a-kind beats high card", "john 2h 2d", "jane Ah 3c").deal("2c Td 4s 6c 9h") .expect("john: 2h 2d 2c Td 4s 6c 9h [Three Of A Kind 2h 2d 2c Kicker(s) Td 9h] (Winner)\n" + "jane: Ah 3c 2c Td 4s 6c 9h [High Card Kicker(s) Ah Td 9h 6c 4s]") }, { Round.scenario("three-of-a-kind beats pair", "john Ah 2c", "jane 2h 2d").deal("Td 4s 6c 9h 2s") .expect("john: Ah 2c Td 4s 6c 9h 2s [Pair 2c 2s Kicker(s) Ah Td 9h]\n" + "jane: 2h 2d Td 4s 6c 9h 2s [Three Of A Kind 2h 2d 2s Kicker(s) Td 9h] (Winner)") }, { Round.scenario("three-of-a-kind beats two-pair", "john 2h 2d", "jane Ah 2c").deal("As Qc Td 4s 2s") .expect("john: 2h 2d As Qc Td 4s 2s [Three Of A Kind 2h 2d 2s Kicker(s) As Qc] (Winner)\n" + "jane: Ah 2c As Qc Td 4s 2s [Two Pair Ah As 2c 2s Kicker(s) Qc]") }, { Round.scenario("highest three-of-a-kind wins", "john 2h 2d", "jane Ah Ac").deal("Qc Td 4s Ad 2s") .expect("john: 2h 2d Qc Td 4s Ad 2s [Three Of A Kind 2h 2d 2s Kicker(s) Ad Qc]\n" + "jane: Ah Ac Qc Td 4s Ad 2s [Three Of A Kind Ah Ac Ad Kicker(s) Qc Td] (Winner)") }, { Round.scenario("straight beats high card", "john 2h 3d", "jane Ah 9c").deal("6c 5d 4s Kc Th") .expect("john: 2h 3d 6c 5d 4s Kc Th [Straight 6c 5d 4s 3d 2h] (Winner)\n" + "jane: Ah 9c 6c 5d 4s Kc Th [High Card Kicker(s) Ah Kc Th 9c 6c]") }, { Round.scenario("straight beats pair", "john Kh 2c", "jane 2h 3d").deal("6c 5d 4s Kc Th") .expect("john: Kh 2c 6c 5d 4s Kc Th [Pair Kh Kc Kicker(s) Th 6c 5d]\n" + "jane: 2h 3d 6c 5d 4s Kc Th [Straight 6c 5d 4s 3d 2h] (Winner)") }, { Round.scenario("straight beats two-pair", "john 2h 3d", "jane 6h 4c").deal("6c 5d 4s Kc Th") .expect("john: 2h 3d 6c 5d 4s Kc Th [Straight 6c 5d 4s 3d 2h] (Winner)\n" + "jane: 6h 4c 6c 5d 4s Kc Th [Two Pair 6h 6c 4c 4s Kicker(s) Kc]") }, { Round.scenario("straight beats three-of-a-kind", "john 2h 3d", "jane 5h 5c").deal("6c 5d 4s Kc Th") .expect("john: 2h 3d 6c 5d 4s Kc Th [Straight 6c 5d 4s 3d 2h] (Winner)\n" + "jane: 5h 5c 6c 5d 4s Kc Th [Three Of A Kind 5h 5c 5d Kicker(s) Kc Th]") }, { Round.scenario("highest straight wins", "john 2h 3d", "jane 8h Ac").deal("6c 5d 4s 7c Th") .expect("john: 2h 3d 6c 5d 4s 7c Th [Straight 7c 6c 5d 4s 3d]\n" + "jane: 8h Ac 6c 5d 4s 7c Th [Straight 8h 7c 6c 5d 4s] (Winner)") } }); }
diff --git a/src/core/de/jroene/vrapper/vim/action/InsertLine.java b/src/core/de/jroene/vrapper/vim/action/InsertLine.java index 4dd97e3a..7d3fe503 100644 --- a/src/core/de/jroene/vrapper/vim/action/InsertLine.java +++ b/src/core/de/jroene/vrapper/vim/action/InsertLine.java @@ -1,72 +1,72 @@ package de.jroene.vrapper.vim.action; import de.jroene.vrapper.vim.InsertMode; import de.jroene.vrapper.vim.LineInformation; import de.jroene.vrapper.vim.Platform; import de.jroene.vrapper.vim.VimConstants; import de.jroene.vrapper.vim.VimEmulator; import de.jroene.vrapper.vim.VimUtils; import de.jroene.vrapper.vim.token.Repeatable; import de.jroene.vrapper.vim.token.Token; import de.jroene.vrapper.vim.token.TokenException; /** * Inserts a new line and switches to insert mode. * * @author Matthias Radig */ public abstract class InsertLine extends TokenAndAction implements Repeatable { private int times = 1; public final void execute(VimEmulator vim) { Platform p = vim.getPlatform(); LineInformation line = p.getLineInformation(); String indent = vim.getVariables().isAutoIndent() ? VimUtils.getIndent(vim, line) : ""; doEdit(p, line, indent); vim.toInsertMode(getParameters(line, times)); } public boolean repeat(VimEmulator vim, int times, Token next) throws TokenException { this.times = times; return true; } abstract InsertMode.Parameters getParameters(LineInformation line, int times); protected abstract void doEdit(Platform p, LineInformation line, String indent); public static class PreCursor extends InsertLine { @Override protected void doEdit(Platform p, LineInformation currentLine, String indent) { p.replace(currentLine.getBeginOffset(), 0, indent+VimConstants.NEWLINE); p.setPosition(currentLine.getBeginOffset()+indent.length()); } @Override InsertMode.Parameters getParameters(LineInformation line, int times) { return new InsertMode.Parameters(true, true, times, line.getBeginOffset()); } } public static class PostCursor extends InsertLine { @Override protected void doEdit(Platform p, LineInformation currentLine, String indent) { int begin = currentLine.getEndOffset(); if (currentLine.getNumber() == p.getNumberOfLines()-1) { begin += 1; } p.replace(begin, 0, VimConstants.NEWLINE+indent); - p.setPosition(begin+indent.length()+1); + p.setPosition(begin+indent.length()+VimConstants.NEWLINE.length()); } @Override InsertMode.Parameters getParameters(LineInformation line, int times) { return new InsertMode.Parameters(true, false, times, line.getEndOffset()+1); } } }
true
true
protected void doEdit(Platform p, LineInformation currentLine, String indent) { int begin = currentLine.getEndOffset(); if (currentLine.getNumber() == p.getNumberOfLines()-1) { begin += 1; } p.replace(begin, 0, VimConstants.NEWLINE+indent); p.setPosition(begin+indent.length()+1); }
protected void doEdit(Platform p, LineInformation currentLine, String indent) { int begin = currentLine.getEndOffset(); if (currentLine.getNumber() == p.getNumberOfLines()-1) { begin += 1; } p.replace(begin, 0, VimConstants.NEWLINE+indent); p.setPosition(begin+indent.length()+VimConstants.NEWLINE.length()); }
diff --git a/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/ompi/OMPIProxyRuntimeClient.java b/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/ompi/OMPIProxyRuntimeClient.java index 57a0f472b..7c3e7b41d 100644 --- a/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/ompi/OMPIProxyRuntimeClient.java +++ b/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/ompi/OMPIProxyRuntimeClient.java @@ -1,226 +1,224 @@ package org.eclipse.ptp.rtsystem.ompi; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.BitSet; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Preferences; import org.eclipse.ptp.core.ControlSystemChoices; import org.eclipse.ptp.core.IModelManager; import org.eclipse.ptp.core.MonitoringSystemChoices; import org.eclipse.ptp.core.PTPCorePlugin; import org.eclipse.ptp.core.PreferenceConstants; import org.eclipse.ptp.core.util.Queue; import org.eclipse.ptp.rtsystem.IRuntimeProxy; import org.eclipse.ptp.rtsystem.proxy.ProxyRuntimeClient; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener; import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeErrorEvent; import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeNewJobEvent; import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeNodeAttributeEvent; import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeNodesEvent; import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeProcessAttributeEvent; import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeProcessesEvent; public class OMPIProxyRuntimeClient extends ProxyRuntimeClient implements IRuntimeProxy, IProxyRuntimeEventListener { protected Queue events = new Queue(); protected BitSet waitEvents = new BitSet(); protected IModelManager modelManager; public OMPIProxyRuntimeClient(IModelManager modelManager) { super(); super.addRuntimeEventListener(this); this.modelManager = modelManager; } public int runJob(String[] args) throws IOException { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_NEWJOB); run(args); IProxyRuntimeEvent event = waitForRuntimeEvent(); return ((ProxyRuntimeNewJobEvent)event).getJobID(); } public int getJobProcesses(int jobID) throws IOException { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_PROCS); getProcesses(jobID); IProxyRuntimeEvent event = waitForRuntimeEvent(); return ((ProxyRuntimeProcessesEvent)event).getNumProcs(); } public String[] getProcessAttributesBlocking(int jobID, int procID, String keys) throws IOException { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_PROCATTR); getProcessAttribute(jobID, procID, keys); IProxyRuntimeEvent event = waitForRuntimeEvent(); return ((ProxyRuntimeProcessAttributeEvent)event).getValues(); } public String[] getAllProcessesAttribuesBlocking(int jobID, String keys) throws IOException { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_PROCATTR); getProcessAttribute(jobID, -1, keys); IProxyRuntimeEvent event = waitForRuntimeEvent(); return ((ProxyRuntimeProcessAttributeEvent)event).getValues(); } public int getNumNodesBlocking(int machineID) throws IOException { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_NODES); getNodes(machineID); IProxyRuntimeEvent event = waitForRuntimeEvent(); return ((ProxyRuntimeNodesEvent)event).getNumNodes(); } public String[] getNodeAttributesBlocking(int machID, int nodeID, String keys) throws IOException { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_NODEATTR); getNodeAttribute(machID, nodeID, keys); IProxyRuntimeEvent event = waitForRuntimeEvent(); return ((ProxyRuntimeNodeAttributeEvent)event).getValues(); } public String[] getAllNodesAttributesBlocking(int machID, String keys) throws IOException { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_NODEATTR); getNodeAttribute(machID, -1, keys); IProxyRuntimeEvent event = waitForRuntimeEvent(); return ((ProxyRuntimeNodeAttributeEvent)event).getValues(); } public boolean startup(final IProgressMonitor monitor) { System.out.println("OMPIProxyRuntimeClient - firing up proxy, waiting for connecting. Please wait! This can take a minute . . ."); Preferences preferences = PTPCorePlugin.getDefault().getPluginPreferences(); String proxyPath = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH); System.out.println("ORTE_SERVER path = '"+proxyPath+"'"); if(proxyPath.equals("")) { String err = "Could not start the ORTE server. Check the "+ "PTP/Open RTE preferences page and be certain that the path and arguments "+ "are correct. Defaulting to Simulation Mode."; System.err.println(err); PTPCorePlugin.errorDialog("ORTE Server Start Failure", err, null); int MSI = MonitoringSystemChoices.SIMULATED; int CSI = ControlSystemChoices.SIMULATED; preferences.setValue(PreferenceConstants.MONITORING_SYSTEM_SELECTION, MSI); preferences.setValue(PreferenceConstants.CONTROL_SYSTEM_SELECTION, CSI); PTPCorePlugin.getDefault().savePluginPreferences(); return false; } final String proxyPath2 = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH); try { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_CONNECTED); sessionCreate(); if (preferences.getBoolean(PreferenceConstants.ORTE_LAUNCH_MANUALLY)) { monitor.subTask("Waiting for manual lauch of orte_server on port "+getSessionPort()+"..."); } else { Thread runThread = new Thread("Proxy Server Thread") { public void run() { String cmd = proxyPath2 + " --port="+getSessionPort(); System.out.println("RUNNING PROXY SERVER COMMAND: '"+cmd+"'"); try { Process process = Runtime.getRuntime ().exec(cmd); InputStreamReader reader = new InputStreamReader (process.getErrorStream()); BufferedReader buf_reader = new BufferedReader (reader); String line = buf_reader.readLine(); if (line != null) { PTPCorePlugin.errorDialog("Running Proxy Server", line, null); - if (monitor != null) { - monitor.setCanceled(true); - } } } catch(IOException e) { PTPCorePlugin.errorDialog("Running Proxy Server", null, e); if (monitor != null) { monitor.setCanceled(true); } } } }; + runThread.setDaemon(true); runThread.start(); } System.out.println("Waiting on accept."); waitForRuntimeEvent(monitor); setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_OK); sendCommand("STARTDAEMON"); waitForRuntimeEvent(); } catch (IOException e) { System.err.println("Exception starting up proxy. :("); try { sessionFinish(); } catch (IOException e1) { PTPCorePlugin.log(e1); } return false; } return true; } public void shutdown() { try { System.out.println("OMPIProxyRuntimeClient shutting down server..."); setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_OK); sessionFinish(); waitForRuntimeEvent(); System.out.println("OMPIProxyRuntimeClient shut down."); } catch (IOException e) { // TODO Auto-generated catch block PTPCorePlugin.log(e); } } private void setWaitEvent(int eventID) { waitEvents.set(eventID); waitEvents.set(IProxyRuntimeEvent.EVENT_RUNTIME_ERROR); // always check for errors } private IProxyRuntimeEvent waitForRuntimeEvent() throws IOException { return waitForRuntimeEvent(null); } private synchronized IProxyRuntimeEvent waitForRuntimeEvent(IProgressMonitor monitor) throws IOException { IProxyRuntimeEvent event = null; System.out.println("OMPIProxyRuntimeClient waiting on " + waitEvents.toString()); while (this.events.isEmpty()) { try { wait(500); } catch (InterruptedException e) { } if (monitor != null && monitor.isCanceled()) { throw new IOException("Cancelled by user"); } } System.out.println("OMPIProxyRuntimeClient awoke!"); try { event = (IProxyRuntimeEvent) this.events.removeItem(); } catch (InterruptedException e) { waitEvents.clear(); throw new IOException(e.getMessage()); } if (event instanceof ProxyRuntimeErrorEvent) { waitEvents.clear(); throw new IOException(((ProxyRuntimeErrorEvent)event).getErrorMessage()); } waitEvents.clear(); return event; } /* * Only handle events we're interested in */ public synchronized void handleEvent(IProxyRuntimeEvent e) { System.out.println("OMPIProxyRuntimeClient got event: " + e.toString()); if (waitEvents.get(e.getEventID())) { System.out.println("OMPIProxyRuntimeClient notifying..."); this.events.addItem(e); notifyAll(); } } }
false
true
public boolean startup(final IProgressMonitor monitor) { System.out.println("OMPIProxyRuntimeClient - firing up proxy, waiting for connecting. Please wait! This can take a minute . . ."); Preferences preferences = PTPCorePlugin.getDefault().getPluginPreferences(); String proxyPath = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH); System.out.println("ORTE_SERVER path = '"+proxyPath+"'"); if(proxyPath.equals("")) { String err = "Could not start the ORTE server. Check the "+ "PTP/Open RTE preferences page and be certain that the path and arguments "+ "are correct. Defaulting to Simulation Mode."; System.err.println(err); PTPCorePlugin.errorDialog("ORTE Server Start Failure", err, null); int MSI = MonitoringSystemChoices.SIMULATED; int CSI = ControlSystemChoices.SIMULATED; preferences.setValue(PreferenceConstants.MONITORING_SYSTEM_SELECTION, MSI); preferences.setValue(PreferenceConstants.CONTROL_SYSTEM_SELECTION, CSI); PTPCorePlugin.getDefault().savePluginPreferences(); return false; } final String proxyPath2 = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH); try { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_CONNECTED); sessionCreate(); if (preferences.getBoolean(PreferenceConstants.ORTE_LAUNCH_MANUALLY)) { monitor.subTask("Waiting for manual lauch of orte_server on port "+getSessionPort()+"..."); } else { Thread runThread = new Thread("Proxy Server Thread") { public void run() { String cmd = proxyPath2 + " --port="+getSessionPort(); System.out.println("RUNNING PROXY SERVER COMMAND: '"+cmd+"'"); try { Process process = Runtime.getRuntime ().exec(cmd); InputStreamReader reader = new InputStreamReader (process.getErrorStream()); BufferedReader buf_reader = new BufferedReader (reader); String line = buf_reader.readLine(); if (line != null) { PTPCorePlugin.errorDialog("Running Proxy Server", line, null); if (monitor != null) { monitor.setCanceled(true); } } } catch(IOException e) { PTPCorePlugin.errorDialog("Running Proxy Server", null, e); if (monitor != null) { monitor.setCanceled(true); } } } }; runThread.start(); } System.out.println("Waiting on accept."); waitForRuntimeEvent(monitor); setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_OK); sendCommand("STARTDAEMON"); waitForRuntimeEvent(); } catch (IOException e) { System.err.println("Exception starting up proxy. :("); try { sessionFinish(); } catch (IOException e1) { PTPCorePlugin.log(e1); } return false; } return true; }
public boolean startup(final IProgressMonitor monitor) { System.out.println("OMPIProxyRuntimeClient - firing up proxy, waiting for connecting. Please wait! This can take a minute . . ."); Preferences preferences = PTPCorePlugin.getDefault().getPluginPreferences(); String proxyPath = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH); System.out.println("ORTE_SERVER path = '"+proxyPath+"'"); if(proxyPath.equals("")) { String err = "Could not start the ORTE server. Check the "+ "PTP/Open RTE preferences page and be certain that the path and arguments "+ "are correct. Defaulting to Simulation Mode."; System.err.println(err); PTPCorePlugin.errorDialog("ORTE Server Start Failure", err, null); int MSI = MonitoringSystemChoices.SIMULATED; int CSI = ControlSystemChoices.SIMULATED; preferences.setValue(PreferenceConstants.MONITORING_SYSTEM_SELECTION, MSI); preferences.setValue(PreferenceConstants.CONTROL_SYSTEM_SELECTION, CSI); PTPCorePlugin.getDefault().savePluginPreferences(); return false; } final String proxyPath2 = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH); try { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_CONNECTED); sessionCreate(); if (preferences.getBoolean(PreferenceConstants.ORTE_LAUNCH_MANUALLY)) { monitor.subTask("Waiting for manual lauch of orte_server on port "+getSessionPort()+"..."); } else { Thread runThread = new Thread("Proxy Server Thread") { public void run() { String cmd = proxyPath2 + " --port="+getSessionPort(); System.out.println("RUNNING PROXY SERVER COMMAND: '"+cmd+"'"); try { Process process = Runtime.getRuntime ().exec(cmd); InputStreamReader reader = new InputStreamReader (process.getErrorStream()); BufferedReader buf_reader = new BufferedReader (reader); String line = buf_reader.readLine(); if (line != null) { PTPCorePlugin.errorDialog("Running Proxy Server", line, null); } } catch(IOException e) { PTPCorePlugin.errorDialog("Running Proxy Server", null, e); if (monitor != null) { monitor.setCanceled(true); } } } }; runThread.setDaemon(true); runThread.start(); } System.out.println("Waiting on accept."); waitForRuntimeEvent(monitor); setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_OK); sendCommand("STARTDAEMON"); waitForRuntimeEvent(); } catch (IOException e) { System.err.println("Exception starting up proxy. :("); try { sessionFinish(); } catch (IOException e1) { PTPCorePlugin.log(e1); } return false; } return true; }
diff --git a/modeling-core/src/main/java/org/inbio/modeling/core/manager/impl/LayerManagerImpl.java b/modeling-core/src/main/java/org/inbio/modeling/core/manager/impl/LayerManagerImpl.java index 2a9b572..d9aa074 100644 --- a/modeling-core/src/main/java/org/inbio/modeling/core/manager/impl/LayerManagerImpl.java +++ b/modeling-core/src/main/java/org/inbio/modeling/core/manager/impl/LayerManagerImpl.java @@ -1,59 +1,59 @@ /* Modeling - Application to model threats. * * Copyright (C) 2010 INBio ( Instituto Nacional de Biodiversidad ) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.inbio.modeling.core.manager.impl; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.inbio.modeling.core.dto.LayerDTO; import org.inbio.modeling.core.manager.FileManager; import org.inbio.modeling.core.manager.LayerManager; public class LayerManagerImpl implements LayerManager { protected final Log logger = LogFactory.getLog(getClass()); private FileManager fileManagerImpl; @Override /** * @see org.inbio.modeling.core.manager.LayerManager#getLayerList() */ public List<LayerDTO> getLayerList() { List<String> layerNames = null; List<LayerDTO> resultList = null; layerNames = this.fileManagerImpl.listLayerHomeFolder(); resultList = new ArrayList<LayerDTO>(); for(String layerName : layerNames) - resultList.add(new LayerDTO(layerName, -1)); + resultList.add(new LayerDTO(layerName, 0)); return resultList; } public FileManager getFileManagerImpl() { return fileManagerImpl; } public void setFileManagerImpl(FileManager fileManagerImpl) { this.fileManagerImpl = fileManagerImpl; } }
true
true
public List<LayerDTO> getLayerList() { List<String> layerNames = null; List<LayerDTO> resultList = null; layerNames = this.fileManagerImpl.listLayerHomeFolder(); resultList = new ArrayList<LayerDTO>(); for(String layerName : layerNames) resultList.add(new LayerDTO(layerName, -1)); return resultList; }
public List<LayerDTO> getLayerList() { List<String> layerNames = null; List<LayerDTO> resultList = null; layerNames = this.fileManagerImpl.listLayerHomeFolder(); resultList = new ArrayList<LayerDTO>(); for(String layerName : layerNames) resultList.add(new LayerDTO(layerName, 0)); return resultList; }
diff --git a/src/codemate/operator/Update.java b/src/codemate/operator/Update.java index 2181691..18d5152 100644 --- a/src/codemate/operator/Update.java +++ b/src/codemate/operator/Update.java @@ -1,64 +1,68 @@ package codemate.operator; import java.io.*; import java.util.*; import java.util.regex.*; import codemate.ui.*; import codemate.utils.*; public class Update { public static void operate() { Pattern hashPattern = Pattern.compile("prev_commit_hash = \\w*"); String urlBase = "https://raw.github.com/dongli/CodeMate/"+ "master/products/installer/payload/"; String dirBase = System.getenv("HOME")+"/.codemate/"; // --------------------------------------------------------------------- // get remote hash UI.notice("codemate", "Fetch information from remote repository."); String hashRemote = null; String content = SystemUtils.downloadAndRead(urlBase+"install.info"); Matcher hashMatcher = hashPattern.matcher(content); if (hashMatcher.find()) hashRemote = hashMatcher.group().split("=")[1]; else UI.error("codemate", "Failed to find remote commit hash!"); // --------------------------------------------------------------------- // get local hash String hashLocal = null; File file = new File(dirBase+"install.info"); if (!file.isFile()) { SystemUtils.download( "https://raw.github.com/dongli/CodeMate/"+ "master/products/installer/codemate.installer", "codemate.installer"); UI.error("codemate", "There is no install.info in ~/.codemate. "+ "New codemate.installer has been downloaded, "+ "reinstall it please!"); } try { content = new Scanner(file).useDelimiter("\\Z").next(); } catch (FileNotFoundException e) { UI.error("codemate", "Failed to find local commit hash!"); } hashMatcher = hashPattern.matcher(content); if (hashMatcher.find()) hashLocal = hashMatcher.group().split("=")[1]; else UI.error("codemate", "Failed to find local commit hash!"); // --------------------------------------------------------------------- // compare if (hashRemote.equals(hashLocal)) { UI.notice("codemate", "CodeMate is already up to date!"); } else { UI.notice("codemate", "Update CodeMate."); String[] fileNames = { "codemate", "codemate.jar", "install.info", "setup.sh" }; for (String fileName : fileNames) { UI.notice("codemate", "Download "+urlBase+fileName+"."); SystemUtils.download(urlBase+fileName, dirBase+fileName); + if (fileName.equals("codemate")) { + File tmp = new File(dirBase+fileName); + tmp.setExecutable(true); + } } } } }
true
true
public static void operate() { Pattern hashPattern = Pattern.compile("prev_commit_hash = \\w*"); String urlBase = "https://raw.github.com/dongli/CodeMate/"+ "master/products/installer/payload/"; String dirBase = System.getenv("HOME")+"/.codemate/"; // --------------------------------------------------------------------- // get remote hash UI.notice("codemate", "Fetch information from remote repository."); String hashRemote = null; String content = SystemUtils.downloadAndRead(urlBase+"install.info"); Matcher hashMatcher = hashPattern.matcher(content); if (hashMatcher.find()) hashRemote = hashMatcher.group().split("=")[1]; else UI.error("codemate", "Failed to find remote commit hash!"); // --------------------------------------------------------------------- // get local hash String hashLocal = null; File file = new File(dirBase+"install.info"); if (!file.isFile()) { SystemUtils.download( "https://raw.github.com/dongli/CodeMate/"+ "master/products/installer/codemate.installer", "codemate.installer"); UI.error("codemate", "There is no install.info in ~/.codemate. "+ "New codemate.installer has been downloaded, "+ "reinstall it please!"); } try { content = new Scanner(file).useDelimiter("\\Z").next(); } catch (FileNotFoundException e) { UI.error("codemate", "Failed to find local commit hash!"); } hashMatcher = hashPattern.matcher(content); if (hashMatcher.find()) hashLocal = hashMatcher.group().split("=")[1]; else UI.error("codemate", "Failed to find local commit hash!"); // --------------------------------------------------------------------- // compare if (hashRemote.equals(hashLocal)) { UI.notice("codemate", "CodeMate is already up to date!"); } else { UI.notice("codemate", "Update CodeMate."); String[] fileNames = { "codemate", "codemate.jar", "install.info", "setup.sh" }; for (String fileName : fileNames) { UI.notice("codemate", "Download "+urlBase+fileName+"."); SystemUtils.download(urlBase+fileName, dirBase+fileName); } } }
public static void operate() { Pattern hashPattern = Pattern.compile("prev_commit_hash = \\w*"); String urlBase = "https://raw.github.com/dongli/CodeMate/"+ "master/products/installer/payload/"; String dirBase = System.getenv("HOME")+"/.codemate/"; // --------------------------------------------------------------------- // get remote hash UI.notice("codemate", "Fetch information from remote repository."); String hashRemote = null; String content = SystemUtils.downloadAndRead(urlBase+"install.info"); Matcher hashMatcher = hashPattern.matcher(content); if (hashMatcher.find()) hashRemote = hashMatcher.group().split("=")[1]; else UI.error("codemate", "Failed to find remote commit hash!"); // --------------------------------------------------------------------- // get local hash String hashLocal = null; File file = new File(dirBase+"install.info"); if (!file.isFile()) { SystemUtils.download( "https://raw.github.com/dongli/CodeMate/"+ "master/products/installer/codemate.installer", "codemate.installer"); UI.error("codemate", "There is no install.info in ~/.codemate. "+ "New codemate.installer has been downloaded, "+ "reinstall it please!"); } try { content = new Scanner(file).useDelimiter("\\Z").next(); } catch (FileNotFoundException e) { UI.error("codemate", "Failed to find local commit hash!"); } hashMatcher = hashPattern.matcher(content); if (hashMatcher.find()) hashLocal = hashMatcher.group().split("=")[1]; else UI.error("codemate", "Failed to find local commit hash!"); // --------------------------------------------------------------------- // compare if (hashRemote.equals(hashLocal)) { UI.notice("codemate", "CodeMate is already up to date!"); } else { UI.notice("codemate", "Update CodeMate."); String[] fileNames = { "codemate", "codemate.jar", "install.info", "setup.sh" }; for (String fileName : fileNames) { UI.notice("codemate", "Download "+urlBase+fileName+"."); SystemUtils.download(urlBase+fileName, dirBase+fileName); if (fileName.equals("codemate")) { File tmp = new File(dirBase+fileName); tmp.setExecutable(true); } } } }
diff --git a/src/core/cascading/flow/FlowPlanner.java b/src/core/cascading/flow/FlowPlanner.java index 261be60d..8afd4e78 100644 --- a/src/core/cascading/flow/FlowPlanner.java +++ b/src/core/cascading/flow/FlowPlanner.java @@ -1,350 +1,350 @@ /* * Copyright (c) 2007-2009 Concurrent, Inc. All Rights Reserved. * * Project and contact information: http://www.cascading.org/ * * This file is part of the Cascading project. * * Cascading is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Cascading is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Cascading. If not, see <http://www.gnu.org/licenses/>. */ package cascading.flow; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import cascading.operation.AssertionLevel; import cascading.operation.DebugLevel; import cascading.pipe.Each; import cascading.pipe.Every; import cascading.pipe.Group; import cascading.pipe.Pipe; import cascading.pipe.SubAssembly; import cascading.tap.Tap; import cascading.util.Util; import org.apache.log4j.Logger; import org.jgrapht.GraphPath; import org.jgrapht.Graphs; /** Class FlowPlanner is the base class for all planner implementations. */ public class FlowPlanner { /** Field LOG */ private static final Logger LOG = Logger.getLogger( FlowPlanner.class ); /** Field properties */ protected final Map<Object, Object> properties; /** Field assertionLevel */ protected AssertionLevel assertionLevel; /** Field debugLevel */ protected DebugLevel debugLevel; FlowPlanner( Map<Object, Object> properties ) { this.properties = properties; this.assertionLevel = FlowConnector.getAssertionLevel( properties ); this.debugLevel = FlowConnector.getDebugLevel( properties ); } /** Must be called to determine if all elements of the base pipe assembly are available */ protected void verifyAssembly( Pipe[] pipes, Map<String, Tap> sources, Map<String, Tap> sinks, Map<String, Tap> traps ) { verifySourceNotSinks( sources, sinks ); verifyTaps( sources, true, true ); verifyTaps( sinks, false, true ); verifyTaps( traps, false, false ); verifyPipeAssemblyEndPoints( sources, sinks, pipes ); verifyTraps( traps, pipes, sources, sinks ); } /** Creates a new ElementGraph instance. */ protected ElementGraph createElementGraph( Pipe[] pipes, Map<String, Tap> sources, Map<String, Tap> sinks, Map<String, Tap> traps ) { return new ElementGraph( pipes, sources, sinks, traps, assertionLevel, debugLevel ); } protected void verifySourceNotSinks( Map<String, Tap> sources, Map<String, Tap> sinks ) { Collection<Tap> sourcesSet = sources.values(); for( Tap tap : sinks.values() ) { if( sourcesSet.contains( tap ) ) throw new PlannerException( "tap may not be used as both source and sink in the same Flow: " + tap ); } } /** * Method verifyTaps ... * * @param taps of type Map<String, Tap> * @param areSources of type boolean * @param mayNotBeEmpty of type boolean */ protected void verifyTaps( Map<String, Tap> taps, boolean areSources, boolean mayNotBeEmpty ) { if( mayNotBeEmpty && taps.isEmpty() ) throw new PlannerException( ( areSources ? "source" : "sink" ) + " taps are required" ); for( String tapName : taps.keySet() ) { if( areSources && !taps.get( tapName ).isSource() ) throw new PlannerException( "tap named: " + tapName + ", cannot be used as a source: " + taps.get( tapName ) ); else if( !areSources && !taps.get( tapName ).isSink() ) throw new PlannerException( "tap named: " + tapName + ", cannot be used as a sink: " + taps.get( tapName ) ); } } /** * Method verifyEndPoints verifies * <p/> * there aren't dupe names in heads or tails. * all the sink and source tap names match up with tail and head pipes * * @param sources of type Map<String, Tap> * @param sinks of type Map<String, Tap> * @param pipes of type Pipe[] */ // todo: force dupe names to throw exceptions protected void verifyPipeAssemblyEndPoints( Map<String, Tap> sources, Map<String, Tap> sinks, Pipe[] pipes ) { Set<String> tapNames = new HashSet<String>(); tapNames.addAll( sources.keySet() ); tapNames.addAll( sinks.keySet() ); // handle tails Set<Pipe> tails = new HashSet<Pipe>(); Set<String> tailNames = new HashSet<String>(); for( Pipe pipe : pipes ) { if( pipe instanceof SubAssembly ) { for( Pipe tail : ( (SubAssembly) pipe ).getTails() ) { String tailName = tail.getName(); if( !tapNames.contains( tailName ) ) throw new PlannerException( pipe, "pipe name not found in either sink or source map: " + tailName ); if( tailNames.contains( tailName ) && !tails.contains( tail ) ) LOG.warn( "duplicate tail name found: " + tailName ); // throw new PlannerException( pipe, "duplicate tail name found: " + tailName ); tailNames.add( tailName ); tails.add( tail ); } } else { String tailName = pipe.getName(); if( !tapNames.contains( tailName ) ) throw new PlannerException( pipe, "pipe name not found in either sink or source map: " + tailName ); if( tailNames.contains( tailName ) && !tails.contains( pipe ) ) LOG.warn( "duplicate tail name found, not an error but tails should have unique names: " + tailName ); // throw new PlannerException( pipe, "duplicate tail name found: " + tailName ); tailNames.add( tailName ); tails.add( pipe ); } } tailNames.removeAll( sinks.keySet() ); Set<String> remainingSinks = new HashSet<String>( sinks.keySet() ); remainingSinks.removeAll( tailNames ); if( tailNames.size() != 0 ) throw new PlannerException( "not all tail pipes bound to sink taps, remaining tail pipe names: [" + Util.join( tailNames, ", " ) + "], remaining sinks: [" + Util.join( remainingSinks, ", " ) + "]" ); // handle heads Set<Pipe> heads = new HashSet<Pipe>(); Set<String> headNames = new HashSet<String>(); for( Pipe pipe : pipes ) { for( Pipe head : pipe.getHeads() ) { String headName = head.getName(); if( !tapNames.contains( headName ) ) throw new PlannerException( head, "pipe name not found in either sink or source map: " + headName ); if( headNames.contains( headName ) && !heads.contains( head ) ) - LOG.warn( "duplicate tail name found, not an error but heads should have unique names: " + headName ); + LOG.warn( "duplicate head name found, not an error but heads should have unique names: " + headName ); // throw new PlannerException( pipe, "duplicate head name found: " + headName ); headNames.add( headName ); heads.add( head ); } } headNames.removeAll( sources.keySet() ); Set<String> remainingSources = new HashSet<String>( sources.keySet() ); remainingSources.removeAll( headNames ); if( headNames.size() != 0 ) throw new PlannerException( "not all head pipes bound to source taps, remaining head pipe names: [" + Util.join( headNames, ", " ) + "], remaining sources: [" + Util.join( remainingSources, ", " ) + "]" ); } protected void verifyTraps( Map<String, Tap> traps, Pipe[] pipes, Map<String, Tap> sources, Map<String, Tap> sinks ) { verifyTrapsNotSourcesSinks( traps, sources, sinks ); Set<String> names = new HashSet<String>(); Collections.addAll( names, Pipe.names( pipes ) ); for( String name : traps.keySet() ) { if( !names.contains( name ) ) throw new PlannerException( "trap name not found in assembly: " + name ); } } private void verifyTrapsNotSourcesSinks( Map<String, Tap> traps, Map<String, Tap> sources, Map<String, Tap> sinks ) { Collection<Tap> sourceTaps = sources.values(); Collection<Tap> sinkTaps = sinks.values(); for( Tap tap : traps.values() ) { if( sourceTaps.contains( tap ) ) throw new PlannerException( "tap may not be used as both a trap and a source in the same Flow: " + tap ); if( sinkTaps.contains( tap ) ) throw new PlannerException( "tap may not be used as both a trap and a sink in the same Flow: " + tap ); } } /** * Verifies that there are not only GroupAssertions following any given Group instance. This will adversely * affect the stream entering any subsquent Tap of Each instances. */ protected void failOnLoneGroupAssertion( ElementGraph elementGraph ) { List<Group> groups = elementGraph.findAllGroups(); // walk Every instances after Group for( Group group : groups ) { for( GraphPath<FlowElement, Scope> path : elementGraph.getAllShortestPathsFrom( group ) ) { List<FlowElement> flowElements = Graphs.getPathVertexList( path ); // last element is tail int everies = 0; int assertions = 0; for( FlowElement flowElement : flowElements ) { if( flowElement instanceof Group ) continue; if( !( flowElement instanceof Every ) ) break; everies++; Every every = (Every) flowElement; if( every.getPlannerLevel() != null ) assertions++; } if( everies != 0 && everies == assertions ) throw new PlannerException( "group assertions must be accompanied by aggregator operations" ); } } } protected void failOnMissingGroup( ElementGraph elementGraph ) { List<Every> everies = elementGraph.findAllEveries(); // walk Every instances after Group for( Every every : everies ) { for( GraphPath<FlowElement, Scope> path : elementGraph.getAllShortestPathsTo( every ) ) { List<FlowElement> flowElements = Graphs.getPathVertexList( path ); // last element is every Collections.reverse( flowElements ); // first element is every for( FlowElement flowElement : flowElements ) { if( flowElement instanceof Each ) throw new PlannerException( (Pipe) flowElement, "Every may only be preceeded by another Every or a Group pipe, found: " + flowElement ); if( flowElement instanceof Every ) continue; if( flowElement instanceof Group ) break; } } } } protected void failOnMisusedBuffer( ElementGraph elementGraph ) { List<Every> everies = elementGraph.findAllEveries(); // walk Every instances after Group for( Every every : everies ) { for( GraphPath<FlowElement, Scope> path : elementGraph.getAllShortestPathsTo( every ) ) { List<FlowElement> flowElements = Graphs.getPathVertexList( path ); // last element is every Collections.reverse( flowElements ); // first element is every Every last = null; boolean foundBuffer = false; int foundEveries = -1; for( FlowElement flowElement : flowElements ) { if( flowElement instanceof Each ) throw new PlannerException( (Pipe) flowElement, "Every may only be preceeded by another Every or a Group pipe, found: " + flowElement ); if( flowElement instanceof Every ) { foundEveries++; boolean isBuffer = ( (Every) flowElement ).isBuffer(); if( foundEveries != 0 && ( isBuffer || foundBuffer ) ) throw new PlannerException( (Pipe) flowElement, "Only one Every Buffer may follow a Group pipe, found: " + flowElement + " before: " + last ); if( !foundBuffer ) foundBuffer = isBuffer; last = (Every) flowElement; } if( flowElement instanceof Group ) break; } } } } }
true
true
protected void verifyPipeAssemblyEndPoints( Map<String, Tap> sources, Map<String, Tap> sinks, Pipe[] pipes ) { Set<String> tapNames = new HashSet<String>(); tapNames.addAll( sources.keySet() ); tapNames.addAll( sinks.keySet() ); // handle tails Set<Pipe> tails = new HashSet<Pipe>(); Set<String> tailNames = new HashSet<String>(); for( Pipe pipe : pipes ) { if( pipe instanceof SubAssembly ) { for( Pipe tail : ( (SubAssembly) pipe ).getTails() ) { String tailName = tail.getName(); if( !tapNames.contains( tailName ) ) throw new PlannerException( pipe, "pipe name not found in either sink or source map: " + tailName ); if( tailNames.contains( tailName ) && !tails.contains( tail ) ) LOG.warn( "duplicate tail name found: " + tailName ); // throw new PlannerException( pipe, "duplicate tail name found: " + tailName ); tailNames.add( tailName ); tails.add( tail ); } } else { String tailName = pipe.getName(); if( !tapNames.contains( tailName ) ) throw new PlannerException( pipe, "pipe name not found in either sink or source map: " + tailName ); if( tailNames.contains( tailName ) && !tails.contains( pipe ) ) LOG.warn( "duplicate tail name found, not an error but tails should have unique names: " + tailName ); // throw new PlannerException( pipe, "duplicate tail name found: " + tailName ); tailNames.add( tailName ); tails.add( pipe ); } } tailNames.removeAll( sinks.keySet() ); Set<String> remainingSinks = new HashSet<String>( sinks.keySet() ); remainingSinks.removeAll( tailNames ); if( tailNames.size() != 0 ) throw new PlannerException( "not all tail pipes bound to sink taps, remaining tail pipe names: [" + Util.join( tailNames, ", " ) + "], remaining sinks: [" + Util.join( remainingSinks, ", " ) + "]" ); // handle heads Set<Pipe> heads = new HashSet<Pipe>(); Set<String> headNames = new HashSet<String>(); for( Pipe pipe : pipes ) { for( Pipe head : pipe.getHeads() ) { String headName = head.getName(); if( !tapNames.contains( headName ) ) throw new PlannerException( head, "pipe name not found in either sink or source map: " + headName ); if( headNames.contains( headName ) && !heads.contains( head ) ) LOG.warn( "duplicate tail name found, not an error but heads should have unique names: " + headName ); // throw new PlannerException( pipe, "duplicate head name found: " + headName ); headNames.add( headName ); heads.add( head ); } } headNames.removeAll( sources.keySet() ); Set<String> remainingSources = new HashSet<String>( sources.keySet() ); remainingSources.removeAll( headNames ); if( headNames.size() != 0 ) throw new PlannerException( "not all head pipes bound to source taps, remaining head pipe names: [" + Util.join( headNames, ", " ) + "], remaining sources: [" + Util.join( remainingSources, ", " ) + "]" ); }
protected void verifyPipeAssemblyEndPoints( Map<String, Tap> sources, Map<String, Tap> sinks, Pipe[] pipes ) { Set<String> tapNames = new HashSet<String>(); tapNames.addAll( sources.keySet() ); tapNames.addAll( sinks.keySet() ); // handle tails Set<Pipe> tails = new HashSet<Pipe>(); Set<String> tailNames = new HashSet<String>(); for( Pipe pipe : pipes ) { if( pipe instanceof SubAssembly ) { for( Pipe tail : ( (SubAssembly) pipe ).getTails() ) { String tailName = tail.getName(); if( !tapNames.contains( tailName ) ) throw new PlannerException( pipe, "pipe name not found in either sink or source map: " + tailName ); if( tailNames.contains( tailName ) && !tails.contains( tail ) ) LOG.warn( "duplicate tail name found: " + tailName ); // throw new PlannerException( pipe, "duplicate tail name found: " + tailName ); tailNames.add( tailName ); tails.add( tail ); } } else { String tailName = pipe.getName(); if( !tapNames.contains( tailName ) ) throw new PlannerException( pipe, "pipe name not found in either sink or source map: " + tailName ); if( tailNames.contains( tailName ) && !tails.contains( pipe ) ) LOG.warn( "duplicate tail name found, not an error but tails should have unique names: " + tailName ); // throw new PlannerException( pipe, "duplicate tail name found: " + tailName ); tailNames.add( tailName ); tails.add( pipe ); } } tailNames.removeAll( sinks.keySet() ); Set<String> remainingSinks = new HashSet<String>( sinks.keySet() ); remainingSinks.removeAll( tailNames ); if( tailNames.size() != 0 ) throw new PlannerException( "not all tail pipes bound to sink taps, remaining tail pipe names: [" + Util.join( tailNames, ", " ) + "], remaining sinks: [" + Util.join( remainingSinks, ", " ) + "]" ); // handle heads Set<Pipe> heads = new HashSet<Pipe>(); Set<String> headNames = new HashSet<String>(); for( Pipe pipe : pipes ) { for( Pipe head : pipe.getHeads() ) { String headName = head.getName(); if( !tapNames.contains( headName ) ) throw new PlannerException( head, "pipe name not found in either sink or source map: " + headName ); if( headNames.contains( headName ) && !heads.contains( head ) ) LOG.warn( "duplicate head name found, not an error but heads should have unique names: " + headName ); // throw new PlannerException( pipe, "duplicate head name found: " + headName ); headNames.add( headName ); heads.add( head ); } } headNames.removeAll( sources.keySet() ); Set<String> remainingSources = new HashSet<String>( sources.keySet() ); remainingSources.removeAll( headNames ); if( headNames.size() != 0 ) throw new PlannerException( "not all head pipes bound to source taps, remaining head pipe names: [" + Util.join( headNames, ", " ) + "], remaining sources: [" + Util.join( remainingSources, ", " ) + "]" ); }
diff --git a/mineguild-admin-plugin/src/com/github/mineguild/MineguildAdmin/MGACommandExecutor.java b/mineguild-admin-plugin/src/com/github/mineguild/MineguildAdmin/MGACommandExecutor.java index bb0a859..c486204 100644 --- a/mineguild-admin-plugin/src/com/github/mineguild/MineguildAdmin/MGACommandExecutor.java +++ b/mineguild-admin-plugin/src/com/github/mineguild/MineguildAdmin/MGACommandExecutor.java @@ -1,288 +1,292 @@ package com.github.mineguild.MineguildAdmin; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class MGACommandExecutor implements CommandExecutor { public MGACommandExecutor(Main plugin) { } @SuppressWarnings({ "unused"}) @Override //Command interpreter public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ //Introducing /mga command if(cmd.getName().equalsIgnoreCase("mga")){ //If the args are length 0 or the args[0] isnt equal "version" it will return false if (args.length == 0 || !args[0].equalsIgnoreCase("version")){ return false; } if (args[0].equalsIgnoreCase("version")) { //Show version to sender and return true if the value of args[0] is equal to "version" sender.sendMessage("MineguildAdmin V0.3"); return true; } } //Introducing /heal command if(cmd.getName().equalsIgnoreCase("heal")){ //If there are no args, simply act with the command sender if(args.length == 0){ //Only do this if the sender is instanceof player if(sender instanceof Player){ Player p = (Player) sender; //set max Health and message p.setHealth(20); p.sendMessage(ChatColor.RED+"You feel restored"); } //If the sender is not instanceof player send message with console use back to the sender else { sender.sendMessage(ChatColor.RED+"Please use /heal <player> on console!"); return true; } } //If the args have the length 1 continue else { Player p = Bukkit.getPlayerExact(args[0]); //If the above defined player isn�t null continue if(p != null){ //set max Health and message String pname = p.getName(); p.setHealth(20); p.sendMessage(ChatColor.RED+"You feel restored"); sender.sendMessage(ChatColor.RED+"You just healed " + pname); return true; } //If output of Bukkit.getPlayerExact(args[0] was null, send error message. else { sender.sendMessage(ChatColor.RED+"Player is not online!"); return true; } } } //Introducing /feed command if(cmd.getName().equalsIgnoreCase("feed")){ //If there are no args, simply act with the command sender if(args.length == 0){ //Only do this if the sender is instanceof player if(sender instanceof Player){ Player p = (Player) sender; //set max hunger level and message p.setFoodLevel(20); p.sendMessage(ChatColor.RED+"You feeded yourself"); } //If the sender is not instanceof player send message with console use back to the sender else { sender.sendMessage(ChatColor.RED+"Please use /feed <player> on console!"); return true; } } //If the args have the length 1 continue else { Player p = Bukkit.getPlayerExact(args[0]); //If the above defined player isn�t null continue if(p != null){ //set max hunger level and message both String pname = p.getName(); p.setFoodLevel(20); p.sendMessage(ChatColor.RED+"You were feeded."); sender.sendMessage(ChatColor.RED+"You just feeded " + pname); return true; } //If output of Bukkit.getPlayerExact(args[0] was null, send error message. else { sender.sendMessage(ChatColor.RED+"Player is not online!"); return true; } } } //Introducing /check command if(cmd.getName().equalsIgnoreCase("check")){ //If there are no args, simply act with the command sender if(args.length == 0){ //Only do this if the sender is instanceof player if(sender instanceof Player){ Player p = (Player) sender; //check health then /2 and print double health = p.getHealth(); health = health / 2.0; double hunger = p.getFoodLevel(); hunger = hunger / 2.0; p.sendMessage(ChatColor.RED+"Your Health is " + health); p.sendMessage(ChatColor.RED+"Your Hunger is " + hunger); return true; } //If the sender is not instanceof player send message with console use back to the sender else { sender.sendMessage(ChatColor.RED+"Please use /check <player> on console!"); return true; } } //If the args have the length 1 continue if(args.length == 1) { Player p = Bukkit.getPlayerExact(args[0]); //If the above defined player isn�t null continue if(p != null){ //set max Health and message double health = p.getHealth(); String string1 = p.getName(); double hunger = p.getFoodLevel(); hunger = hunger / 2.0; health = health / 2.0; sender.sendMessage(ChatColor.RED + string1 +"'s Health is " + health); sender.sendMessage(ChatColor.RED + string1 +"'s Hunger is " + hunger); return true; } //If output of Bukkit.getPlayerExact(args[0] was null, send error message. else { sender.sendMessage(ChatColor.RED+"Player is not online!"); return true; } } } //Introducing /gm command if(cmd.getName().equalsIgnoreCase("gm")){ //If there are no args, simply act with the command sender if(args.length == 0){ //Only do this if the sender is instanceof player if(sender instanceof Player){ Player p = (Player) sender; //If the gamemode is survival it will switch to creative and vice versa //Also returning true, for the correctness if (p.getGameMode().equals(GameMode.SURVIVAL)){ p.setGameMode(GameMode.CREATIVE); p.sendMessage(ChatColor.GOLD + "You are now in creative mode!"); return true; } else if (p.getGameMode().equals(GameMode.CREATIVE)){ p.setGameMode(GameMode.SURVIVAL); p.sendMessage(ChatColor.GOLD + "You are now in survival mode!"); return true; } } //If the sender is not instanceof player send message with console use back to the sender else { sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!"); return true; } } //If the args have the length 1 continue if(args.length == 1) { if(args[0].equalsIgnoreCase("s") || args[0].equalsIgnoreCase("c") || args[0].equals("1") || args[0].equals("0")){ if(sender instanceof Player){ Player p = (Player) sender; if (args[0].equalsIgnoreCase("c") || args[0].equals(1)){ p.setGameMode(GameMode.CREATIVE); sender.sendMessage(ChatColor.GOLD + "You are now in creative mode!"); return true; } if(args[0].equalsIgnoreCase("s") || args[0].equals(0)){ p.setGameMode(GameMode.SURVIVAL); sender.sendMessage(ChatColor.GOLD + "You are now in survival mode!"); return true; } } else{ sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!"); return true; } } else{ if(sender instanceof Player){ Player p = Bukkit.getPlayerExact(args[0]); String pname = p.getDisplayName(); //If the above defined player isn�t null continue if(p != null){ //If the gamemode is survival it will switch to creative and vice versa //Also returning true, for the correctness if (p.getGameMode().equals(GameMode.SURVIVAL)){ p.setGameMode(GameMode.CREATIVE); sender.sendMessage(ChatColor.GOLD + pname + " is now in creative mode!"); p.sendMessage(ChatColor.GOLD + "You are now in creative mode!"); return true; } if (p.getGameMode().equals(GameMode.CREATIVE)){ p.setGameMode(GameMode.SURVIVAL); sender.sendMessage(ChatColor.GOLD + pname + " is now in survival mode!"); p.sendMessage(ChatColor.GOLD + "You are now in survival mode!"); return true; } } //If output of Bukkit.getPlayerExact(args[0] was null, send error message. else{ sender.sendMessage(ChatColor.RED+"Player is not online!"); return true; } } else{ sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!"); return true; } } } else if (args.length == 2) { Player p = Bukkit.getPlayerExact(args[0]); String pname = p.getDisplayName(); if(p != null){ - if (args[1].equalsIgnoreCase("c") || args[1].equals("1")){ + if (args[1].equalsIgnoreCase("c") || args[1].equals("1") && p != null){ p.setGameMode(GameMode.CREATIVE); sender.sendMessage(ChatColor.GOLD + pname + " is now in creative mode!"); return true; } - if(args[1].equalsIgnoreCase("s") || args[1].equals("0")){ + if(args[1].equalsIgnoreCase("s") || args[1].equals("0") && p != null){ p.setGameMode(GameMode.SURVIVAL); sender.sendMessage(ChatColor.GOLD + pname + " is now in survival mode!"); return true; } } + else{ + sender.sendMessage(ChatColor.RED+"Player is not online!"); + return true; + } } } if(cmd.getName().equalsIgnoreCase("spawn")){ if(args.length == 0){ if(sender instanceof Player){ Player p = (Player) sender; Location l = p.getWorld().getSpawnLocation(); p.teleport(l); sender.sendMessage(ChatColor.GREEN + "You were teleported to the spawn!"); return true; } else{ sender.sendMessage(ChatColor.RED + "You cant use this command from console yet!"); return true; } } else{ return false; } } if(cmd.getName().equalsIgnoreCase("setspawn")){ if(sender instanceof Player){ Player p = (Player) sender; int x = p.getLocation().getBlockX(); int y = p.getLocation().getBlockY(); int z = p.getLocation().getBlockZ(); p.getWorld().setSpawnLocation(x, y, z); sender.sendMessage(ChatColor.GREEN + "The spawn point was set to you location"); return true; } else{ sender.sendMessage(ChatColor.RED + "You only can use this command as player!"); return true; } } return false; } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ //Introducing /mga command if(cmd.getName().equalsIgnoreCase("mga")){ //If the args are length 0 or the args[0] isnt equal "version" it will return false if (args.length == 0 || !args[0].equalsIgnoreCase("version")){ return false; } if (args[0].equalsIgnoreCase("version")) { //Show version to sender and return true if the value of args[0] is equal to "version" sender.sendMessage("MineguildAdmin V0.3"); return true; } } //Introducing /heal command if(cmd.getName().equalsIgnoreCase("heal")){ //If there are no args, simply act with the command sender if(args.length == 0){ //Only do this if the sender is instanceof player if(sender instanceof Player){ Player p = (Player) sender; //set max Health and message p.setHealth(20); p.sendMessage(ChatColor.RED+"You feel restored"); } //If the sender is not instanceof player send message with console use back to the sender else { sender.sendMessage(ChatColor.RED+"Please use /heal <player> on console!"); return true; } } //If the args have the length 1 continue else { Player p = Bukkit.getPlayerExact(args[0]); //If the above defined player isn�t null continue if(p != null){ //set max Health and message String pname = p.getName(); p.setHealth(20); p.sendMessage(ChatColor.RED+"You feel restored"); sender.sendMessage(ChatColor.RED+"You just healed " + pname); return true; } //If output of Bukkit.getPlayerExact(args[0] was null, send error message. else { sender.sendMessage(ChatColor.RED+"Player is not online!"); return true; } } } //Introducing /feed command if(cmd.getName().equalsIgnoreCase("feed")){ //If there are no args, simply act with the command sender if(args.length == 0){ //Only do this if the sender is instanceof player if(sender instanceof Player){ Player p = (Player) sender; //set max hunger level and message p.setFoodLevel(20); p.sendMessage(ChatColor.RED+"You feeded yourself"); } //If the sender is not instanceof player send message with console use back to the sender else { sender.sendMessage(ChatColor.RED+"Please use /feed <player> on console!"); return true; } } //If the args have the length 1 continue else { Player p = Bukkit.getPlayerExact(args[0]); //If the above defined player isn�t null continue if(p != null){ //set max hunger level and message both String pname = p.getName(); p.setFoodLevel(20); p.sendMessage(ChatColor.RED+"You were feeded."); sender.sendMessage(ChatColor.RED+"You just feeded " + pname); return true; } //If output of Bukkit.getPlayerExact(args[0] was null, send error message. else { sender.sendMessage(ChatColor.RED+"Player is not online!"); return true; } } } //Introducing /check command if(cmd.getName().equalsIgnoreCase("check")){ //If there are no args, simply act with the command sender if(args.length == 0){ //Only do this if the sender is instanceof player if(sender instanceof Player){ Player p = (Player) sender; //check health then /2 and print double health = p.getHealth(); health = health / 2.0; double hunger = p.getFoodLevel(); hunger = hunger / 2.0; p.sendMessage(ChatColor.RED+"Your Health is " + health); p.sendMessage(ChatColor.RED+"Your Hunger is " + hunger); return true; } //If the sender is not instanceof player send message with console use back to the sender else { sender.sendMessage(ChatColor.RED+"Please use /check <player> on console!"); return true; } } //If the args have the length 1 continue if(args.length == 1) { Player p = Bukkit.getPlayerExact(args[0]); //If the above defined player isn�t null continue if(p != null){ //set max Health and message double health = p.getHealth(); String string1 = p.getName(); double hunger = p.getFoodLevel(); hunger = hunger / 2.0; health = health / 2.0; sender.sendMessage(ChatColor.RED + string1 +"'s Health is " + health); sender.sendMessage(ChatColor.RED + string1 +"'s Hunger is " + hunger); return true; } //If output of Bukkit.getPlayerExact(args[0] was null, send error message. else { sender.sendMessage(ChatColor.RED+"Player is not online!"); return true; } } } //Introducing /gm command if(cmd.getName().equalsIgnoreCase("gm")){ //If there are no args, simply act with the command sender if(args.length == 0){ //Only do this if the sender is instanceof player if(sender instanceof Player){ Player p = (Player) sender; //If the gamemode is survival it will switch to creative and vice versa //Also returning true, for the correctness if (p.getGameMode().equals(GameMode.SURVIVAL)){ p.setGameMode(GameMode.CREATIVE); p.sendMessage(ChatColor.GOLD + "You are now in creative mode!"); return true; } else if (p.getGameMode().equals(GameMode.CREATIVE)){ p.setGameMode(GameMode.SURVIVAL); p.sendMessage(ChatColor.GOLD + "You are now in survival mode!"); return true; } } //If the sender is not instanceof player send message with console use back to the sender else { sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!"); return true; } } //If the args have the length 1 continue if(args.length == 1) { if(args[0].equalsIgnoreCase("s") || args[0].equalsIgnoreCase("c") || args[0].equals("1") || args[0].equals("0")){ if(sender instanceof Player){ Player p = (Player) sender; if (args[0].equalsIgnoreCase("c") || args[0].equals(1)){ p.setGameMode(GameMode.CREATIVE); sender.sendMessage(ChatColor.GOLD + "You are now in creative mode!"); return true; } if(args[0].equalsIgnoreCase("s") || args[0].equals(0)){ p.setGameMode(GameMode.SURVIVAL); sender.sendMessage(ChatColor.GOLD + "You are now in survival mode!"); return true; } } else{ sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!"); return true; } } else{ if(sender instanceof Player){ Player p = Bukkit.getPlayerExact(args[0]); String pname = p.getDisplayName(); //If the above defined player isn�t null continue if(p != null){ //If the gamemode is survival it will switch to creative and vice versa //Also returning true, for the correctness if (p.getGameMode().equals(GameMode.SURVIVAL)){ p.setGameMode(GameMode.CREATIVE); sender.sendMessage(ChatColor.GOLD + pname + " is now in creative mode!"); p.sendMessage(ChatColor.GOLD + "You are now in creative mode!"); return true; } if (p.getGameMode().equals(GameMode.CREATIVE)){ p.setGameMode(GameMode.SURVIVAL); sender.sendMessage(ChatColor.GOLD + pname + " is now in survival mode!"); p.sendMessage(ChatColor.GOLD + "You are now in survival mode!"); return true; } } //If output of Bukkit.getPlayerExact(args[0] was null, send error message. else{ sender.sendMessage(ChatColor.RED+"Player is not online!"); return true; } } else{ sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!"); return true; } } } else if (args.length == 2) { Player p = Bukkit.getPlayerExact(args[0]); String pname = p.getDisplayName(); if(p != null){ if (args[1].equalsIgnoreCase("c") || args[1].equals("1")){ p.setGameMode(GameMode.CREATIVE); sender.sendMessage(ChatColor.GOLD + pname + " is now in creative mode!"); return true; } if(args[1].equalsIgnoreCase("s") || args[1].equals("0")){ p.setGameMode(GameMode.SURVIVAL); sender.sendMessage(ChatColor.GOLD + pname + " is now in survival mode!"); return true; } } } } if(cmd.getName().equalsIgnoreCase("spawn")){ if(args.length == 0){ if(sender instanceof Player){ Player p = (Player) sender; Location l = p.getWorld().getSpawnLocation(); p.teleport(l); sender.sendMessage(ChatColor.GREEN + "You were teleported to the spawn!"); return true; } else{ sender.sendMessage(ChatColor.RED + "You cant use this command from console yet!"); return true; } } else{ return false; } } if(cmd.getName().equalsIgnoreCase("setspawn")){ if(sender instanceof Player){ Player p = (Player) sender; int x = p.getLocation().getBlockX(); int y = p.getLocation().getBlockY(); int z = p.getLocation().getBlockZ(); p.getWorld().setSpawnLocation(x, y, z); sender.sendMessage(ChatColor.GREEN + "The spawn point was set to you location"); return true; } else{ sender.sendMessage(ChatColor.RED + "You only can use this command as player!"); return true; } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ //Introducing /mga command if(cmd.getName().equalsIgnoreCase("mga")){ //If the args are length 0 or the args[0] isnt equal "version" it will return false if (args.length == 0 || !args[0].equalsIgnoreCase("version")){ return false; } if (args[0].equalsIgnoreCase("version")) { //Show version to sender and return true if the value of args[0] is equal to "version" sender.sendMessage("MineguildAdmin V0.3"); return true; } } //Introducing /heal command if(cmd.getName().equalsIgnoreCase("heal")){ //If there are no args, simply act with the command sender if(args.length == 0){ //Only do this if the sender is instanceof player if(sender instanceof Player){ Player p = (Player) sender; //set max Health and message p.setHealth(20); p.sendMessage(ChatColor.RED+"You feel restored"); } //If the sender is not instanceof player send message with console use back to the sender else { sender.sendMessage(ChatColor.RED+"Please use /heal <player> on console!"); return true; } } //If the args have the length 1 continue else { Player p = Bukkit.getPlayerExact(args[0]); //If the above defined player isn�t null continue if(p != null){ //set max Health and message String pname = p.getName(); p.setHealth(20); p.sendMessage(ChatColor.RED+"You feel restored"); sender.sendMessage(ChatColor.RED+"You just healed " + pname); return true; } //If output of Bukkit.getPlayerExact(args[0] was null, send error message. else { sender.sendMessage(ChatColor.RED+"Player is not online!"); return true; } } } //Introducing /feed command if(cmd.getName().equalsIgnoreCase("feed")){ //If there are no args, simply act with the command sender if(args.length == 0){ //Only do this if the sender is instanceof player if(sender instanceof Player){ Player p = (Player) sender; //set max hunger level and message p.setFoodLevel(20); p.sendMessage(ChatColor.RED+"You feeded yourself"); } //If the sender is not instanceof player send message with console use back to the sender else { sender.sendMessage(ChatColor.RED+"Please use /feed <player> on console!"); return true; } } //If the args have the length 1 continue else { Player p = Bukkit.getPlayerExact(args[0]); //If the above defined player isn�t null continue if(p != null){ //set max hunger level and message both String pname = p.getName(); p.setFoodLevel(20); p.sendMessage(ChatColor.RED+"You were feeded."); sender.sendMessage(ChatColor.RED+"You just feeded " + pname); return true; } //If output of Bukkit.getPlayerExact(args[0] was null, send error message. else { sender.sendMessage(ChatColor.RED+"Player is not online!"); return true; } } } //Introducing /check command if(cmd.getName().equalsIgnoreCase("check")){ //If there are no args, simply act with the command sender if(args.length == 0){ //Only do this if the sender is instanceof player if(sender instanceof Player){ Player p = (Player) sender; //check health then /2 and print double health = p.getHealth(); health = health / 2.0; double hunger = p.getFoodLevel(); hunger = hunger / 2.0; p.sendMessage(ChatColor.RED+"Your Health is " + health); p.sendMessage(ChatColor.RED+"Your Hunger is " + hunger); return true; } //If the sender is not instanceof player send message with console use back to the sender else { sender.sendMessage(ChatColor.RED+"Please use /check <player> on console!"); return true; } } //If the args have the length 1 continue if(args.length == 1) { Player p = Bukkit.getPlayerExact(args[0]); //If the above defined player isn�t null continue if(p != null){ //set max Health and message double health = p.getHealth(); String string1 = p.getName(); double hunger = p.getFoodLevel(); hunger = hunger / 2.0; health = health / 2.0; sender.sendMessage(ChatColor.RED + string1 +"'s Health is " + health); sender.sendMessage(ChatColor.RED + string1 +"'s Hunger is " + hunger); return true; } //If output of Bukkit.getPlayerExact(args[0] was null, send error message. else { sender.sendMessage(ChatColor.RED+"Player is not online!"); return true; } } } //Introducing /gm command if(cmd.getName().equalsIgnoreCase("gm")){ //If there are no args, simply act with the command sender if(args.length == 0){ //Only do this if the sender is instanceof player if(sender instanceof Player){ Player p = (Player) sender; //If the gamemode is survival it will switch to creative and vice versa //Also returning true, for the correctness if (p.getGameMode().equals(GameMode.SURVIVAL)){ p.setGameMode(GameMode.CREATIVE); p.sendMessage(ChatColor.GOLD + "You are now in creative mode!"); return true; } else if (p.getGameMode().equals(GameMode.CREATIVE)){ p.setGameMode(GameMode.SURVIVAL); p.sendMessage(ChatColor.GOLD + "You are now in survival mode!"); return true; } } //If the sender is not instanceof player send message with console use back to the sender else { sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!"); return true; } } //If the args have the length 1 continue if(args.length == 1) { if(args[0].equalsIgnoreCase("s") || args[0].equalsIgnoreCase("c") || args[0].equals("1") || args[0].equals("0")){ if(sender instanceof Player){ Player p = (Player) sender; if (args[0].equalsIgnoreCase("c") || args[0].equals(1)){ p.setGameMode(GameMode.CREATIVE); sender.sendMessage(ChatColor.GOLD + "You are now in creative mode!"); return true; } if(args[0].equalsIgnoreCase("s") || args[0].equals(0)){ p.setGameMode(GameMode.SURVIVAL); sender.sendMessage(ChatColor.GOLD + "You are now in survival mode!"); return true; } } else{ sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!"); return true; } } else{ if(sender instanceof Player){ Player p = Bukkit.getPlayerExact(args[0]); String pname = p.getDisplayName(); //If the above defined player isn�t null continue if(p != null){ //If the gamemode is survival it will switch to creative and vice versa //Also returning true, for the correctness if (p.getGameMode().equals(GameMode.SURVIVAL)){ p.setGameMode(GameMode.CREATIVE); sender.sendMessage(ChatColor.GOLD + pname + " is now in creative mode!"); p.sendMessage(ChatColor.GOLD + "You are now in creative mode!"); return true; } if (p.getGameMode().equals(GameMode.CREATIVE)){ p.setGameMode(GameMode.SURVIVAL); sender.sendMessage(ChatColor.GOLD + pname + " is now in survival mode!"); p.sendMessage(ChatColor.GOLD + "You are now in survival mode!"); return true; } } //If output of Bukkit.getPlayerExact(args[0] was null, send error message. else{ sender.sendMessage(ChatColor.RED+"Player is not online!"); return true; } } else{ sender.sendMessage(ChatColor.RED+"Please use /gm <player> <gamemode> on console!"); return true; } } } else if (args.length == 2) { Player p = Bukkit.getPlayerExact(args[0]); String pname = p.getDisplayName(); if(p != null){ if (args[1].equalsIgnoreCase("c") || args[1].equals("1") && p != null){ p.setGameMode(GameMode.CREATIVE); sender.sendMessage(ChatColor.GOLD + pname + " is now in creative mode!"); return true; } if(args[1].equalsIgnoreCase("s") || args[1].equals("0") && p != null){ p.setGameMode(GameMode.SURVIVAL); sender.sendMessage(ChatColor.GOLD + pname + " is now in survival mode!"); return true; } } else{ sender.sendMessage(ChatColor.RED+"Player is not online!"); return true; } } } if(cmd.getName().equalsIgnoreCase("spawn")){ if(args.length == 0){ if(sender instanceof Player){ Player p = (Player) sender; Location l = p.getWorld().getSpawnLocation(); p.teleport(l); sender.sendMessage(ChatColor.GREEN + "You were teleported to the spawn!"); return true; } else{ sender.sendMessage(ChatColor.RED + "You cant use this command from console yet!"); return true; } } else{ return false; } } if(cmd.getName().equalsIgnoreCase("setspawn")){ if(sender instanceof Player){ Player p = (Player) sender; int x = p.getLocation().getBlockX(); int y = p.getLocation().getBlockY(); int z = p.getLocation().getBlockZ(); p.getWorld().setSpawnLocation(x, y, z); sender.sendMessage(ChatColor.GREEN + "The spawn point was set to you location"); return true; } else{ sender.sendMessage(ChatColor.RED + "You only can use this command as player!"); return true; } } return false; }