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/main/java/net/pterodactylus/sone/freenet/wot/WebOfTrustConnector.java b/src/main/java/net/pterodactylus/sone/freenet/wot/WebOfTrustConnector.java index 0a6369f3..7127e8f4 100644 --- a/src/main/java/net/pterodactylus/sone/freenet/wot/WebOfTrustConnector.java +++ b/src/main/java/net/pterodactylus/sone/freenet/wot/WebOfTrustConnector.java @@ -1,487 +1,492 @@ /* * Sone - WebOfTrustConnector.java - Copyright © 2010 David Roden * * 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 net.pterodactylus.sone.freenet.wot; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import net.pterodactylus.util.logging.Logging; import freenet.support.SimpleFieldSet; import freenet.support.api.Bucket; /** * Connector for the Web of Trust plugin. * * @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a> */ public class WebOfTrustConnector implements ConnectorListener { /** The logger. */ private static final Logger logger = Logging.getLogger(WebOfTrustConnector.class); /** The name of the WoT plugin. */ private static final String WOT_PLUGIN_NAME = "plugins.WoT.WoT"; /** A random connection identifier. */ private static final String PLUGIN_CONNECTION_IDENTIFIER = "Sone-WoT-Connector-" + Math.abs(Math.random()); /** The current replies that we wait for. */ private final Map<String, Reply> replies = Collections.synchronizedMap(new HashMap<String, Reply>()); /** The plugin connector. */ private final PluginConnector pluginConnector; /** * Creates a new Web of Trust connector that uses the given plugin * connector. * * @param pluginConnector * The plugin connector */ public WebOfTrustConnector(PluginConnector pluginConnector) { this.pluginConnector = pluginConnector; pluginConnector.addConnectorListener(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, this); } // // ACTIONS // /** * Loads all own identities from the Web of Trust plugin. * * @return All own identity * @throws PluginException * if the own identities can not be loaded */ public Set<OwnIdentity> loadAllOwnIdentities() throws PluginException { Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get(), "OwnIdentities"); SimpleFieldSet fields = reply.getFields(); int ownIdentityCounter = -1; Set<OwnIdentity> ownIdentities = new HashSet<OwnIdentity>(); while (true) { String id = fields.get("Identity" + ++ownIdentityCounter); if (id == null) { break; } String requestUri = fields.get("RequestURI" + ownIdentityCounter); String insertUri = fields.get("InsertURI" + ownIdentityCounter); String nickname = fields.get("Nickname" + ownIdentityCounter); OwnIdentity ownIdentity = new OwnIdentity(id, nickname, requestUri, insertUri); ownIdentity.setContexts(parseContexts("Contexts" + ownIdentityCounter, fields)); ownIdentity.setProperties(parseProperties("Properties" + ownIdentityCounter, fields)); ownIdentities.add(ownIdentity); } return ownIdentities; } /** * Loads all identities that the given identities trusts with a score of * more than 0. * * @param ownIdentity * The own identity * @return All trusted identities * @throws PluginException * if an error occured talking to the Web of Trust plugin */ public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity) throws PluginException { return loadTrustedIdentities(ownIdentity, null); } /** * Loads all identities that the given identities trusts with a score of * more than 0 and the (optional) given context. * * @param ownIdentity * The own identity * @param context * The context to filter, or {@code null} * @return All trusted identities * @throws PluginException * if an error occured talking to the Web of Trust plugin */ public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity, String context) throws PluginException { Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentitiesByScore").put("TreeOwner", ownIdentity.getId()).put("Selection", "+").put("Context", (context == null) ? "" : context).get(), "Identities"); SimpleFieldSet fields = reply.getFields(); Set<Identity> identities = new HashSet<Identity>(); int identityCounter = -1; while (true) { String id = fields.get("Identity" + ++identityCounter); if (id == null) { break; } String nickname = fields.get("Nickname" + identityCounter); String requestUri = fields.get("RequestURI" + identityCounter); Identity identity = new Identity(id, nickname, requestUri); identity.setContexts(parseContexts("Contexts" + identityCounter, fields)); identity.setProperties(parseProperties("Properties" + identityCounter, fields)); identities.add(identity); } return identities; } /** * Adds the given context to the given identity. * * @param ownIdentity * The identity to add the context to * @param context * The context to add * @throws PluginException * if an error occured talking to the Web of Trust plugin */ public void addContext(OwnIdentity ownIdentity, String context) throws PluginException { performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get(), "ContextAdded"); } /** * Removes the given context from the given identity. * * @param ownIdentity * The identity to remove the context from * @param context * The context to remove * @throws PluginException * if an error occured talking to the Web of Trust plugin */ public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException { performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get(), "ContextRemoved"); } /** * Returns the value of the property with the given name. * * @param identity * The identity whose properties to check * @param name * The name of the property to return * @return The value of the property, or {@code null} if there is no value * @throws PluginException * if an error occured talking to the Web of Trust plugin */ public String getProperty(Identity identity, String name) throws PluginException { Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetProperty").put("Identity", identity.getId()).put("Property", name).get(), "PropertyValue"); return reply.getFields().get("Property"); } /** * Sets the property with the given name to the given value. * * @param ownIdentity * The identity to set the property on * @param name * The name of the property to set * @param value * The value to set * @throws PluginException * if an error occured talking to the Web of Trust plugin */ public void setProperty(OwnIdentity ownIdentity, String name, String value) throws PluginException { performRequest(SimpleFieldSetConstructor.create().put("Message", "SetProperty").put("Identity", ownIdentity.getId()).put("Property", name).put("Value", value).get(), "PropertyAdded"); } /** * Removes the property with the given name. * * @param ownIdentity * The identity to remove the property from * @param name * The name of the property to remove * @throws PluginException * if an error occured talking to the Web of Trust plugin */ public void removeProperty(OwnIdentity ownIdentity, String name) throws PluginException { performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveProperty").put("Identity", ownIdentity.getId()).put("Property", name).get(), "PropertyRemoved"); } /** * Pings the Web of Trust plugin. If the plugin can not be reached, a * {@link PluginException} is thrown. * * @throws PluginException * if the plugin is not loaded */ public void ping() throws PluginException { performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get(), "Pong"); } // // PRIVATE ACTIONS // /** * Parses the contexts from the given fields. * * @param prefix * The prefix to use to access the contexts * @param fields * The fields to parse the contexts from * @return The parsed contexts */ private Set<String> parseContexts(String prefix, SimpleFieldSet fields) { Set<String> contexts = new HashSet<String>(); int contextCounter = -1; while (true) { String context = fields.get(prefix + "Context" + ++contextCounter); if (context == null) { break; } contexts.add(context); } return contexts; } /** * Parses the properties from the given fields. * * @param prefix * The prefix to use to access the properties * @param fields * The fields to parse the properties from * @return The parsed properties */ private Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) { Map<String, String> properties = new HashMap<String, String>(); int propertiesCounter = -1; while (true) { String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + "Name"); if (propertyName == null) { break; } String propertyValue = fields.get(prefix + "Property" + propertiesCounter + "Value"); properties.put(propertyName, propertyValue); } return properties; } /** * Sends a request containing the given fields and waits for the target * message. * * @param fields * The fields of the message * @param targetMessages * The messages of the reply to wait for * @return The reply message * @throws PluginException * if the request could not be sent */ private Reply performRequest(SimpleFieldSet fields, String... targetMessages) throws PluginException { return performRequest(fields, null, targetMessages); } /** * Sends a request containing the given fields and waits for the target * message. * * @param fields * The fields of the message * @param data * The payload of the message * @param targetMessages * The messages of the reply to wait for * @return The reply message * @throws PluginException * if the request could not be sent */ private Reply performRequest(SimpleFieldSet fields, Bucket data, String... targetMessages) throws PluginException { @SuppressWarnings("synthetic-access") Reply reply = new Reply(); for (String targetMessage : targetMessages) { replies.put(targetMessage, reply); } replies.put("Error", reply); synchronized (reply) { pluginConnector.sendRequest(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, fields, data); try { - reply.wait(60000); - throw new PluginException("Timeout waiting for " + targetMessages[0] + "!"); + long now = System.currentTimeMillis(); + while ((reply.getFields() == null) && ((System.currentTimeMillis() - now) < 60000)) { + reply.wait(60000 - (System.currentTimeMillis() - now)); + } + if (reply.getFields() == null) { + throw new PluginException("Timeout waiting for " + targetMessages[0] + "!"); + } } catch (InterruptedException ie1) { logger.log(Level.WARNING, "Got interrupted while waiting for reply on " + targetMessages[0] + ".", ie1); } } for (String targetMessage : targetMessages) { replies.remove(targetMessage); } replies.remove("Error"); if ((reply.getFields() != null) && reply.getFields().get("Message").equals("Error")) { throw new PluginException("Could not perform request for " + targetMessages[0]); } return reply; } // // INTERFACE ConnectorListener // /** * {@inheritDoc} */ @Override public void receivedReply(PluginConnector pluginConnector, SimpleFieldSet fields, Bucket data) { String messageName = fields.get("Message"); logger.log(Level.FINEST, "Received Reply from Plugin: " + messageName); Reply reply = replies.remove(messageName); if (reply == null) { logger.log(Level.FINE, "Not waiting for a “%s” message.", messageName); return; } synchronized (reply) { reply.setFields(fields); reply.setData(data); reply.notify(); } } /** * Container for the data of the reply from a plugin. * * @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a> */ private static class Reply { /** The fields of the reply. */ private SimpleFieldSet fields; /** The payload of the reply. */ private Bucket data; /** * Returns the fields of the reply. * * @return The fields of the reply */ public SimpleFieldSet getFields() { return fields; } /** * Sets the fields of the reply. * * @param fields * The fields of the reply */ public void setFields(SimpleFieldSet fields) { this.fields = fields; } /** * Returns the payload of the reply. * * @return The payload of the reply (may be {@code null}) */ @SuppressWarnings("unused") public Bucket getData() { return data; } /** * Sets the payload of the reply. * * @param data * The payload of the reply (may be {@code null}) */ public void setData(Bucket data) { this.data = data; } } /** * Helper method to create {@link SimpleFieldSet}s with terser code. * * @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a> */ private static class SimpleFieldSetConstructor { /** The field set being created. */ private SimpleFieldSet simpleFieldSet; /** * Creates a new simple field set constructor. * * @param shortLived * {@code true} if the resulting simple field set should be * short-lived, {@code false} otherwise */ private SimpleFieldSetConstructor(boolean shortLived) { simpleFieldSet = new SimpleFieldSet(shortLived); } // // ACCESSORS // /** * Returns the created simple field set. * * @return The created simple field set */ public SimpleFieldSet get() { return simpleFieldSet; } /** * Sets the field with the given name to the given value. * * @param name * The name of the fleld * @param value * The value of the field * @return This constructor (for method chaining) */ public SimpleFieldSetConstructor put(String name, String value) { simpleFieldSet.putOverwrite(name, value); return this; } // // ACTIONS // /** * Creates a new simple field set constructor. * * @return The created simple field set constructor */ public static SimpleFieldSetConstructor create() { return create(true); } /** * Creates a new simple field set constructor. * * @param shortLived * {@code true} if the resulting simple field set should be * short-lived, {@code false} otherwise * @return The created simple field set constructor */ public static SimpleFieldSetConstructor create(boolean shortLived) { SimpleFieldSetConstructor simpleFieldSetConstructor = new SimpleFieldSetConstructor(shortLived); return simpleFieldSetConstructor; } } }
true
true
private Reply performRequest(SimpleFieldSet fields, Bucket data, String... targetMessages) throws PluginException { @SuppressWarnings("synthetic-access") Reply reply = new Reply(); for (String targetMessage : targetMessages) { replies.put(targetMessage, reply); } replies.put("Error", reply); synchronized (reply) { pluginConnector.sendRequest(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, fields, data); try { reply.wait(60000); throw new PluginException("Timeout waiting for " + targetMessages[0] + "!"); } catch (InterruptedException ie1) { logger.log(Level.WARNING, "Got interrupted while waiting for reply on " + targetMessages[0] + ".", ie1); } } for (String targetMessage : targetMessages) { replies.remove(targetMessage); } replies.remove("Error"); if ((reply.getFields() != null) && reply.getFields().get("Message").equals("Error")) { throw new PluginException("Could not perform request for " + targetMessages[0]); } return reply; }
private Reply performRequest(SimpleFieldSet fields, Bucket data, String... targetMessages) throws PluginException { @SuppressWarnings("synthetic-access") Reply reply = new Reply(); for (String targetMessage : targetMessages) { replies.put(targetMessage, reply); } replies.put("Error", reply); synchronized (reply) { pluginConnector.sendRequest(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, fields, data); try { long now = System.currentTimeMillis(); while ((reply.getFields() == null) && ((System.currentTimeMillis() - now) < 60000)) { reply.wait(60000 - (System.currentTimeMillis() - now)); } if (reply.getFields() == null) { throw new PluginException("Timeout waiting for " + targetMessages[0] + "!"); } } catch (InterruptedException ie1) { logger.log(Level.WARNING, "Got interrupted while waiting for reply on " + targetMessages[0] + ".", ie1); } } for (String targetMessage : targetMessages) { replies.remove(targetMessage); } replies.remove("Error"); if ((reply.getFields() != null) && reply.getFields().get("Message").equals("Error")) { throw new PluginException("Could not perform request for " + targetMessages[0]); } return reply; }
diff --git a/src/me/aRt3m1s/ls/lsEL.java b/src/me/aRt3m1s/ls/lsEL.java index 9d67354..ba23c12 100644 --- a/src/me/aRt3m1s/ls/lsEL.java +++ b/src/me/aRt3m1s/ls/lsEL.java @@ -1,79 +1,81 @@ package me.aRt3m1s.ls; import org.bukkit.ChatColor; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.entity.*; import java.util.Random; /** * Created by IntelliJ IDEA. * User: Christian * Date: 9/16/11 * Time: 7:48 AM * To change this template use File | Settings | File Templates. */ public class lsEL extends EntityListener{ public static LongShot plugin; public lsEL(LongShot instance) { plugin = instance; } public void onEntityDamage(EntityDamageEvent event){ if(event instanceof EntityDamageByEntityEvent){ EntityDamageByEntityEvent ee = (EntityDamageByEntityEvent)event; if(ee.getDamager() instanceof Projectile){ Projectile projectile =(Projectile) ee.getDamager(); if(projectile.getShooter() instanceof Player){ Player player = (Player) projectile.getShooter(); if(ee.getEntity() instanceof LivingEntity){ LivingEntity damagee = (LivingEntity) ee.getEntity(); double distance = damagee.getLocation().distance(player.getLocation()); int finalDamage = getFinalDamage(distance, ee.getDamage()); ee.setDamage(finalDamage); ee.setCancelled(false); } } } } } public void onEntityDeath(EntityDeathEvent event){ if(event.getEntity() instanceof Player){ Player player = (Player) event.getEntity(); EntityDamageEvent e = player.getLastDamageCause(); if(e!=null){ if(e.getCause().equals(EntityDamageEvent.DamageCause.PROJECTILE)){ if(e instanceof EntityDamageByEntityEvent){ if(((EntityDamageByEntityEvent) e).getDamager() instanceof Player){ if(plugin.config.getInt("LongShot.distance/BLOCKS-damagePlus", 1)<=0){ Player damager = (Player)((EntityDamageByEntityEvent) e).getDamager(); - player.getServer().broadcastMessage(ChatColor.RED+player.getName()+ - " has been sniped by "+damager.getName()); + for(Player allOnlinePlayer: plugin.getServer().getOnlinePlayers()){ + allOnlinePlayer.sendMessage(ChatColor.GOLD+player.getName()+ + " has been sniped by "+damager.getName()); + } } } } } } } } private int getFinalDamage(double distance, int damage) { int dBdP = plugin.config.getInt("LongShot.distance/BLOCKS-damagePlus", 1); boolean dTOF = plugin.config.getBoolean("LongShot.critical-hits.double", true); int range = plugin.config.getInt("LongShot.critical-hits.random-range", 20); if(dBdP>0){ damage += (int)distance/dBdP; return damage; }else{ if(dTOF){ damage *= 2; }else{ Random generator2 = new Random( 19580427 ); int plusDamage = generator2.nextInt(range); damage += plusDamage; } return damage; } } }
true
true
public void onEntityDeath(EntityDeathEvent event){ if(event.getEntity() instanceof Player){ Player player = (Player) event.getEntity(); EntityDamageEvent e = player.getLastDamageCause(); if(e!=null){ if(e.getCause().equals(EntityDamageEvent.DamageCause.PROJECTILE)){ if(e instanceof EntityDamageByEntityEvent){ if(((EntityDamageByEntityEvent) e).getDamager() instanceof Player){ if(plugin.config.getInt("LongShot.distance/BLOCKS-damagePlus", 1)<=0){ Player damager = (Player)((EntityDamageByEntityEvent) e).getDamager(); player.getServer().broadcastMessage(ChatColor.RED+player.getName()+ " has been sniped by "+damager.getName()); } } } } } } }
public void onEntityDeath(EntityDeathEvent event){ if(event.getEntity() instanceof Player){ Player player = (Player) event.getEntity(); EntityDamageEvent e = player.getLastDamageCause(); if(e!=null){ if(e.getCause().equals(EntityDamageEvent.DamageCause.PROJECTILE)){ if(e instanceof EntityDamageByEntityEvent){ if(((EntityDamageByEntityEvent) e).getDamager() instanceof Player){ if(plugin.config.getInt("LongShot.distance/BLOCKS-damagePlus", 1)<=0){ Player damager = (Player)((EntityDamageByEntityEvent) e).getDamager(); for(Player allOnlinePlayer: plugin.getServer().getOnlinePlayers()){ allOnlinePlayer.sendMessage(ChatColor.GOLD+player.getName()+ " has been sniped by "+damager.getName()); } } } } } } } }
diff --git a/core/src/main/java/hudson/PluginManager.java b/core/src/main/java/hudson/PluginManager.java index 484885b51..b0b3a520f 100644 --- a/core/src/main/java/hudson/PluginManager.java +++ b/core/src/main/java/hudson/PluginManager.java @@ -1,622 +1,622 @@ /* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly, Tom Huybrechts * * 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 hudson; import static hudson.init.InitMilestone.PLUGINS_PREPARED; import static hudson.init.InitMilestone.PLUGINS_STARTED; import static hudson.init.InitMilestone.PLUGINS_LISTED; import hudson.PluginWrapper.Dependency; import hudson.init.InitStrategy; import hudson.model.AbstractModelObject; import hudson.model.Failure; import hudson.model.Hudson; import hudson.model.UpdateCenter; import hudson.model.UpdateSite; import hudson.util.CyclicGraphDetector; import hudson.util.CyclicGraphDetector.CycleDetectedException; import hudson.util.Service; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.LogFactory; import org.jvnet.hudson.reactor.Executable; import org.jvnet.hudson.reactor.Reactor; import org.jvnet.hudson.reactor.TaskBuilder; import org.jvnet.hudson.reactor.TaskGraphBuilder; import org.kohsuke.stapler.HttpRedirect; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.HttpResponses; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletContext; import javax.servlet.ServletException; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Set; import java.util.Map; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; /** * Manages {@link PluginWrapper}s. * * @author Kohsuke Kawaguchi */ public abstract class PluginManager extends AbstractModelObject { /** * All discovered plugins. */ protected final List<PluginWrapper> plugins = new ArrayList<PluginWrapper>(); /** * All active plugins. */ protected final List<PluginWrapper> activePlugins = new ArrayList<PluginWrapper>(); protected final List<FailedPlugin> failedPlugins = new ArrayList<FailedPlugin>(); /** * Plug-in root directory. */ public final File rootDir; /** * @deprecated as of 1.355 * {@link PluginManager} can now live longer than {@link Hudson} instance, so * use {@code Hudson.getInstance().servletContext} instead. */ public final ServletContext context; /** * {@link ClassLoader} that can load all the publicly visible classes from plugins * (and including the classloader that loads Hudson itself.) * */ // implementation is minimal --- just enough to run XStream // and load plugin-contributed classes. public final ClassLoader uberClassLoader = new UberClassLoader(); /** * Once plugin is uploaded, this flag becomes true. * This is used to report a message that Hudson needs to be restarted * for new plugins to take effect. */ public volatile boolean pluginUploaded = false; /** * The initialization of {@link PluginManager} splits into two parts; * one is the part about listing them, extracting them, and preparing classloader for them. * The 2nd part is about creating instances. Once the former completes this flags become true, * as the 2nd part can be repeated for each Hudson instance. */ private boolean pluginListed = false; /** * Strategy for creating and initializing plugins */ private final PluginStrategy strategy; public PluginManager(ServletContext context, File rootDir) { this.context = context; this.rootDir = rootDir; if(!rootDir.exists()) rootDir.mkdirs(); strategy = createPluginStrategy(); } /** * Called immediately after the construction. * This is a separate method so that code executed from here will see a valid value in * {@link Hudson#pluginManager}. */ public TaskBuilder initTasks(final InitStrategy initStrategy) { TaskBuilder builder; if (!pluginListed) { builder = new TaskGraphBuilder() { List<File> archives; Collection<String> bundledPlugins; { Handle loadBundledPlugins = add("Loading bundled plugins", new Executable() { public void run(Reactor session) throws Exception { bundledPlugins = loadBundledPlugins(); } }); Handle listUpPlugins = requires(loadBundledPlugins).add("Listing up plugins", new Executable() { public void run(Reactor session) throws Exception { archives = initStrategy.listPluginArchives(PluginManager.this); } }); requires(listUpPlugins).attains(PLUGINS_LISTED).add("Preparing plugins",new Executable() { public void run(Reactor session) throws Exception { // once we've listed plugins, we can fill in the reactor with plugin-specific initialization tasks TaskGraphBuilder g = new TaskGraphBuilder(); final Map<String,File> inspectedShortNames = new HashMap<String,File>(); for( final File arc : archives ) { g.followedBy().notFatal().attains(PLUGINS_LISTED).add("Inspecting plugin " + arc, new Executable() { public void run(Reactor session1) throws Exception { try { PluginWrapper p = strategy.createPluginWrapper(arc); if (isDuplicate(p)) return; p.isBundled = bundledPlugins.contains(arc.getName()); plugins.add(p); if(p.isActive()) activePlugins.add(p); } catch (IOException e) { failedPlugins.add(new FailedPlugin(arc.getName(),e)); throw e; } } /** * Inspects duplication. this happens when you run hpi:run on a bundled plugin, * as well as putting numbered hpi files, like "cobertura-1.0.hpi" and "cobertura-1.1.hpi" */ private boolean isDuplicate(PluginWrapper p) { String shortName = p.getShortName(); if (inspectedShortNames.containsKey(shortName)) { LOGGER.info("Ignoring "+arc+" because "+inspectedShortNames.get(shortName)+" is already loaded"); return true; } inspectedShortNames.put(shortName,arc); return false; } }); } - g.requires(PLUGINS_LISTED).add("Checking cyclic dependencies",new Executable() { + g.requires(PLUGINS_PREPARED).add("Checking cyclic dependencies",new Executable() { /** * Makes sure there's no cycle in dependencies. */ public void run(Reactor reactor) throws Exception { try { new CyclicGraphDetector<PluginWrapper>() { @Override protected List<PluginWrapper> getEdges(PluginWrapper p) { List<PluginWrapper> next = new ArrayList<PluginWrapper>(); addTo(p.getDependencies(),next); addTo(p.getOptionalDependencies(),next); return next; } private void addTo(List<Dependency> dependencies, List<PluginWrapper> r) { for (Dependency d : dependencies) { PluginWrapper p = getPlugin(d.shortName); if (p!=null) r.add(p); } } }.run(getPlugins()); } catch (CycleDetectedException e) { stop(); // disable all plugins since classloading from them can lead to StackOverflow throw e; // let Hudson fail } } }); session.addAll(g.discoverTasks(session)); pluginListed = true; // technically speaking this is still too early, as at this point tasks are merely scheduled, not necessarily executed. } }); } }; } else { builder = TaskBuilder.EMPTY_BUILDER; } // lists up initialization tasks about loading plugins. return TaskBuilder.union(builder,new TaskGraphBuilder() {{ requires(PLUGINS_LISTED).attains(PLUGINS_PREPARED).add("Loading plugins",new Executable() { /** * Once the plugins are listed, schedule their initialization. */ public void run(Reactor session) throws Exception { Hudson.getInstance().lookup.set(PluginInstanceStore.class,new PluginInstanceStore()); TaskGraphBuilder g = new TaskGraphBuilder(); // schedule execution of loading plugins for (final PluginWrapper p : activePlugins.toArray(new PluginWrapper[activePlugins.size()])) { g.followedBy().notFatal().attains(PLUGINS_PREPARED).add("Loading plugin " + p.getShortName(), new Executable() { public void run(Reactor session) throws Exception { try { p.resolvePluginDependencies(); strategy.load(p); } catch (IOException e) { failedPlugins.add(new FailedPlugin(p.getShortName(), e)); activePlugins.remove(p); plugins.remove(p); throw e; } } }); } // schedule execution of initializing plugins for (final PluginWrapper p : activePlugins.toArray(new PluginWrapper[activePlugins.size()])) { g.followedBy().notFatal().attains(PLUGINS_STARTED).add("Initializing plugin " + p.getShortName(), new Executable() { public void run(Reactor session) throws Exception { try { p.getPlugin().postInitialize(); } catch (Exception e) { failedPlugins.add(new FailedPlugin(p.getShortName(), e)); activePlugins.remove(p); plugins.remove(p); throw e; } } }); } // register them all session.addAll(g.discoverTasks(session)); } }); }}); } /** * If the war file has any "/WEB-INF/plugins/*.hpi", extract them into the plugin directory. * * @return * File names of the bundled plugins. Like {"ssh-slaves.hpi","subvesrion.hpi"} * @throws Exception * Any exception will be reported and halt the startup. */ protected abstract Collection<String> loadBundledPlugins() throws Exception; /** * Copies the bundled plugin from the given URL to the destination of the given file name (like 'abc.hpi'), * with a reasonable up-to-date check. A convenience method to be used by the {@link #loadBundledPlugins()}. */ protected void copyBundledPlugin(URL src, String fileName) throws IOException { long lastModified = src.openConnection().getLastModified(); File file = new File(rootDir, fileName); File pinFile = new File(rootDir, fileName+".pinned"); // update file if: // - no file exists today // - bundled version and current version differs (by timestamp), and the file isn't pinned. if (!file.exists() || (file.lastModified() != lastModified && !pinFile.exists())) { FileUtils.copyURLToFile(src, file); file.setLastModified(src.openConnection().getLastModified()); // lastModified is set for two reasons: // - to avoid unpacking as much as possible, but still do it on both upgrade and downgrade // - to make sure the value is not changed after each restart, so we can avoid // unpacking the plugin itself in ClassicPluginStrategy.explode } } /** * Creates a hudson.PluginStrategy, looking at the corresponding system property. */ private PluginStrategy createPluginStrategy() { String strategyName = System.getProperty(PluginStrategy.class.getName()); if (strategyName != null) { try { Class<?> klazz = getClass().getClassLoader().loadClass(strategyName); Object strategy = klazz.getConstructor(PluginManager.class) .newInstance(this); if (strategy instanceof PluginStrategy) { LOGGER.info("Plugin strategy: " + strategyName); return (PluginStrategy) strategy; } else { LOGGER.warning("Plugin strategy (" + strategyName + ") is not an instance of hudson.PluginStrategy"); } } catch (ClassNotFoundException e) { LOGGER.warning("Plugin strategy class not found: " + strategyName); } catch (Exception e) { LOGGER.log(Level.WARNING, "Could not instantiate plugin strategy: " + strategyName + ". Falling back to ClassicPluginStrategy", e); } LOGGER.info("Falling back to ClassicPluginStrategy"); } // default and fallback return new ClassicPluginStrategy(this); } public PluginStrategy getPluginStrategy() { return strategy; } /** * Returns true if any new plugin was added, which means a restart is required * for the change to take effect. */ public boolean isPluginUploaded() { return pluginUploaded; } public List<PluginWrapper> getPlugins() { return plugins; } public List<FailedPlugin> getFailedPlugins() { return failedPlugins; } public PluginWrapper getPlugin(String shortName) { for (PluginWrapper p : plugins) { if(p.getShortName().equals(shortName)) return p; } return null; } /** * Get the plugin instance that implements a specific class, use to find your plugin singleton. * Note: beware the classloader fun. * @param pluginClazz The class that your plugin implements. * @return The plugin singleton or <code>null</code> if for some reason the plugin is not loaded. */ public PluginWrapper getPlugin(Class<? extends Plugin> pluginClazz) { for (PluginWrapper p : plugins) { if(pluginClazz.isInstance(p.getPlugin())) return p; } return null; } /** * Get the plugin instances that extend a specific class, use to find similar plugins. * Note: beware the classloader fun. * @param pluginSuperclass The class that your plugin is derived from. * @return The list of plugins implementing the specified class. */ public List<PluginWrapper> getPlugins(Class<? extends Plugin> pluginSuperclass) { List<PluginWrapper> result = new ArrayList<PluginWrapper>(); for (PluginWrapper p : plugins) { if(pluginSuperclass.isInstance(p.getPlugin())) result.add(p); } return Collections.unmodifiableList(result); } public String getDisplayName() { return Messages.PluginManager_DisplayName(); } public String getSearchUrl() { return "pluginManager"; } /** * Discover all the service provider implementations of the given class, * via <tt>META-INF/services</tt>. */ public <T> Collection<Class<? extends T>> discover( Class<T> spi ) { Set<Class<? extends T>> result = new HashSet<Class<? extends T>>(); for (PluginWrapper p : activePlugins) { Service.load(spi, p.classLoader, result); } return result; } /** * Orderly terminates all the plugins. */ public void stop() { for (PluginWrapper p : activePlugins) { p.stop(); p.releaseClassLoader(); } activePlugins.clear(); // Work around a bug in commons-logging. // See http://www.szegedi.org/articles/memleak.html LogFactory.release(uberClassLoader); } public HttpResponse doUpdateSources(StaplerRequest req) throws IOException { Hudson.getInstance().checkPermission(Hudson.ADMINISTER); if (req.hasParameter("remove")) { UpdateCenter uc = Hudson.getInstance().getUpdateCenter(); BulkChange bc = new BulkChange(uc); try { for (String id : req.getParameterValues("sources")) uc.getSites().remove(uc.getById(id)); } finally { bc.commit(); } } else if (req.hasParameter("add")) return new HttpRedirect("addSite"); return new HttpRedirect("./sites"); } /** * Performs the installation of the plugins. */ public void doInstall(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { Enumeration<String> en = req.getParameterNames(); while (en.hasMoreElements()) { String n = en.nextElement(); if(n.startsWith("plugin.")) { n = n.substring(7); if (n.indexOf(".") > 0) { String[] pluginInfo = n.split("\\."); UpdateSite.Plugin p = Hudson.getInstance().getUpdateCenter().getById(pluginInfo[1]).getPlugin(pluginInfo[0]); if(p==null) throw new Failure("No such plugin: "+n); p.deploy(); } } } rsp.sendRedirect("../updateCenter/"); } public HttpResponse doProxyConfigure( @QueryParameter("proxy.server") String server, @QueryParameter("proxy.port") String port, @QueryParameter("proxy.userName") String userName, @QueryParameter("proxy.password") String password) throws IOException { Hudson hudson = Hudson.getInstance(); hudson.checkPermission(Hudson.ADMINISTER); server = Util.fixEmptyAndTrim(server); if(server==null) { hudson.proxy = null; ProxyConfiguration.getXmlFile().delete(); } else try { hudson.proxy = new ProxyConfiguration(server,Integer.parseInt(Util.fixNull(port)), Util.fixEmptyAndTrim(userName),Util.fixEmptyAndTrim(password)); hudson.proxy.save(); } catch (NumberFormatException nfe) { return HttpResponses.error(StaplerResponse.SC_BAD_REQUEST, new IllegalArgumentException("Invalid proxy port: " + port, nfe)); } return new HttpRedirect("advanced"); } /** * Uploads a plugin. */ public HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, ServletException { try { Hudson.getInstance().checkPermission(Hudson.ADMINISTER); ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); // Parse the request FileItem fileItem = (FileItem) upload.parseRequest(req).get(0); String fileName = Util.getFileName(fileItem.getName()); if(!fileName.endsWith(".hpi")) throw new Failure(hudson.model.Messages.Hudson_NotAPlugin(fileName)); fileItem.write(new File(rootDir, fileName)); fileItem.delete(); pluginUploaded = true; return new HttpRedirect("."); } catch (IOException e) { throw e; } catch (Exception e) {// grrr. fileItem.write throws this throw new ServletException(e); } } /** * {@link ClassLoader} that can see all plugins. */ private final class UberClassLoader extends ClassLoader { public UberClassLoader() { super(PluginManager.class.getClassLoader()); } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { // first, use the context classloader so that plugins that are loading // can use its own classloader first. ClassLoader cl = Thread.currentThread().getContextClassLoader(); if(cl!=null && cl!=this) try { return cl.loadClass(name); } catch(ClassNotFoundException e) { // not found. try next } for (PluginWrapper p : activePlugins) { try { return p.classLoader.loadClass(name); } catch (ClassNotFoundException e) { //not found. try next } } // not found in any of the classloader. delegate. throw new ClassNotFoundException(name); } @Override protected URL findResource(String name) { for (PluginWrapper p : activePlugins) { URL url = p.classLoader.getResource(name); if(url!=null) return url; } return null; } @Override protected Enumeration<URL> findResources(String name) throws IOException { List<URL> resources = new ArrayList<URL>(); for (PluginWrapper p : activePlugins) { resources.addAll(Collections.list(p.classLoader.getResources(name))); } return Collections.enumeration(resources); } } private static final Logger LOGGER = Logger.getLogger(PluginManager.class.getName()); /** * Remembers why a plugin failed to deploy. */ public static final class FailedPlugin { public final String name; public final Exception cause; public FailedPlugin(String name, Exception cause) { this.name = name; this.cause = cause; } public String getExceptionString() { return Functions.printThrowable(cause); } } /** * Stores {@link Plugin} instances. */ /*package*/ static final class PluginInstanceStore { final Map<PluginWrapper,Plugin> store = new Hashtable<PluginWrapper,Plugin>(); } }
true
true
public TaskBuilder initTasks(final InitStrategy initStrategy) { TaskBuilder builder; if (!pluginListed) { builder = new TaskGraphBuilder() { List<File> archives; Collection<String> bundledPlugins; { Handle loadBundledPlugins = add("Loading bundled plugins", new Executable() { public void run(Reactor session) throws Exception { bundledPlugins = loadBundledPlugins(); } }); Handle listUpPlugins = requires(loadBundledPlugins).add("Listing up plugins", new Executable() { public void run(Reactor session) throws Exception { archives = initStrategy.listPluginArchives(PluginManager.this); } }); requires(listUpPlugins).attains(PLUGINS_LISTED).add("Preparing plugins",new Executable() { public void run(Reactor session) throws Exception { // once we've listed plugins, we can fill in the reactor with plugin-specific initialization tasks TaskGraphBuilder g = new TaskGraphBuilder(); final Map<String,File> inspectedShortNames = new HashMap<String,File>(); for( final File arc : archives ) { g.followedBy().notFatal().attains(PLUGINS_LISTED).add("Inspecting plugin " + arc, new Executable() { public void run(Reactor session1) throws Exception { try { PluginWrapper p = strategy.createPluginWrapper(arc); if (isDuplicate(p)) return; p.isBundled = bundledPlugins.contains(arc.getName()); plugins.add(p); if(p.isActive()) activePlugins.add(p); } catch (IOException e) { failedPlugins.add(new FailedPlugin(arc.getName(),e)); throw e; } } /** * Inspects duplication. this happens when you run hpi:run on a bundled plugin, * as well as putting numbered hpi files, like "cobertura-1.0.hpi" and "cobertura-1.1.hpi" */ private boolean isDuplicate(PluginWrapper p) { String shortName = p.getShortName(); if (inspectedShortNames.containsKey(shortName)) { LOGGER.info("Ignoring "+arc+" because "+inspectedShortNames.get(shortName)+" is already loaded"); return true; } inspectedShortNames.put(shortName,arc); return false; } }); } g.requires(PLUGINS_LISTED).add("Checking cyclic dependencies",new Executable() { /** * Makes sure there's no cycle in dependencies. */ public void run(Reactor reactor) throws Exception { try { new CyclicGraphDetector<PluginWrapper>() { @Override protected List<PluginWrapper> getEdges(PluginWrapper p) { List<PluginWrapper> next = new ArrayList<PluginWrapper>(); addTo(p.getDependencies(),next); addTo(p.getOptionalDependencies(),next); return next; } private void addTo(List<Dependency> dependencies, List<PluginWrapper> r) { for (Dependency d : dependencies) { PluginWrapper p = getPlugin(d.shortName); if (p!=null) r.add(p); } } }.run(getPlugins()); } catch (CycleDetectedException e) { stop(); // disable all plugins since classloading from them can lead to StackOverflow throw e; // let Hudson fail } } }); session.addAll(g.discoverTasks(session)); pluginListed = true; // technically speaking this is still too early, as at this point tasks are merely scheduled, not necessarily executed. } }); } }; } else { builder = TaskBuilder.EMPTY_BUILDER; } // lists up initialization tasks about loading plugins. return TaskBuilder.union(builder,new TaskGraphBuilder() {{ requires(PLUGINS_LISTED).attains(PLUGINS_PREPARED).add("Loading plugins",new Executable() { /** * Once the plugins are listed, schedule their initialization. */ public void run(Reactor session) throws Exception { Hudson.getInstance().lookup.set(PluginInstanceStore.class,new PluginInstanceStore()); TaskGraphBuilder g = new TaskGraphBuilder(); // schedule execution of loading plugins for (final PluginWrapper p : activePlugins.toArray(new PluginWrapper[activePlugins.size()])) { g.followedBy().notFatal().attains(PLUGINS_PREPARED).add("Loading plugin " + p.getShortName(), new Executable() { public void run(Reactor session) throws Exception { try { p.resolvePluginDependencies(); strategy.load(p); } catch (IOException e) { failedPlugins.add(new FailedPlugin(p.getShortName(), e)); activePlugins.remove(p); plugins.remove(p); throw e; } } }); } // schedule execution of initializing plugins for (final PluginWrapper p : activePlugins.toArray(new PluginWrapper[activePlugins.size()])) { g.followedBy().notFatal().attains(PLUGINS_STARTED).add("Initializing plugin " + p.getShortName(), new Executable() { public void run(Reactor session) throws Exception { try { p.getPlugin().postInitialize(); } catch (Exception e) { failedPlugins.add(new FailedPlugin(p.getShortName(), e)); activePlugins.remove(p); plugins.remove(p); throw e; } } }); } // register them all session.addAll(g.discoverTasks(session)); } }); }}); }
public TaskBuilder initTasks(final InitStrategy initStrategy) { TaskBuilder builder; if (!pluginListed) { builder = new TaskGraphBuilder() { List<File> archives; Collection<String> bundledPlugins; { Handle loadBundledPlugins = add("Loading bundled plugins", new Executable() { public void run(Reactor session) throws Exception { bundledPlugins = loadBundledPlugins(); } }); Handle listUpPlugins = requires(loadBundledPlugins).add("Listing up plugins", new Executable() { public void run(Reactor session) throws Exception { archives = initStrategy.listPluginArchives(PluginManager.this); } }); requires(listUpPlugins).attains(PLUGINS_LISTED).add("Preparing plugins",new Executable() { public void run(Reactor session) throws Exception { // once we've listed plugins, we can fill in the reactor with plugin-specific initialization tasks TaskGraphBuilder g = new TaskGraphBuilder(); final Map<String,File> inspectedShortNames = new HashMap<String,File>(); for( final File arc : archives ) { g.followedBy().notFatal().attains(PLUGINS_LISTED).add("Inspecting plugin " + arc, new Executable() { public void run(Reactor session1) throws Exception { try { PluginWrapper p = strategy.createPluginWrapper(arc); if (isDuplicate(p)) return; p.isBundled = bundledPlugins.contains(arc.getName()); plugins.add(p); if(p.isActive()) activePlugins.add(p); } catch (IOException e) { failedPlugins.add(new FailedPlugin(arc.getName(),e)); throw e; } } /** * Inspects duplication. this happens when you run hpi:run on a bundled plugin, * as well as putting numbered hpi files, like "cobertura-1.0.hpi" and "cobertura-1.1.hpi" */ private boolean isDuplicate(PluginWrapper p) { String shortName = p.getShortName(); if (inspectedShortNames.containsKey(shortName)) { LOGGER.info("Ignoring "+arc+" because "+inspectedShortNames.get(shortName)+" is already loaded"); return true; } inspectedShortNames.put(shortName,arc); return false; } }); } g.requires(PLUGINS_PREPARED).add("Checking cyclic dependencies",new Executable() { /** * Makes sure there's no cycle in dependencies. */ public void run(Reactor reactor) throws Exception { try { new CyclicGraphDetector<PluginWrapper>() { @Override protected List<PluginWrapper> getEdges(PluginWrapper p) { List<PluginWrapper> next = new ArrayList<PluginWrapper>(); addTo(p.getDependencies(),next); addTo(p.getOptionalDependencies(),next); return next; } private void addTo(List<Dependency> dependencies, List<PluginWrapper> r) { for (Dependency d : dependencies) { PluginWrapper p = getPlugin(d.shortName); if (p!=null) r.add(p); } } }.run(getPlugins()); } catch (CycleDetectedException e) { stop(); // disable all plugins since classloading from them can lead to StackOverflow throw e; // let Hudson fail } } }); session.addAll(g.discoverTasks(session)); pluginListed = true; // technically speaking this is still too early, as at this point tasks are merely scheduled, not necessarily executed. } }); } }; } else { builder = TaskBuilder.EMPTY_BUILDER; } // lists up initialization tasks about loading plugins. return TaskBuilder.union(builder,new TaskGraphBuilder() {{ requires(PLUGINS_LISTED).attains(PLUGINS_PREPARED).add("Loading plugins",new Executable() { /** * Once the plugins are listed, schedule their initialization. */ public void run(Reactor session) throws Exception { Hudson.getInstance().lookup.set(PluginInstanceStore.class,new PluginInstanceStore()); TaskGraphBuilder g = new TaskGraphBuilder(); // schedule execution of loading plugins for (final PluginWrapper p : activePlugins.toArray(new PluginWrapper[activePlugins.size()])) { g.followedBy().notFatal().attains(PLUGINS_PREPARED).add("Loading plugin " + p.getShortName(), new Executable() { public void run(Reactor session) throws Exception { try { p.resolvePluginDependencies(); strategy.load(p); } catch (IOException e) { failedPlugins.add(new FailedPlugin(p.getShortName(), e)); activePlugins.remove(p); plugins.remove(p); throw e; } } }); } // schedule execution of initializing plugins for (final PluginWrapper p : activePlugins.toArray(new PluginWrapper[activePlugins.size()])) { g.followedBy().notFatal().attains(PLUGINS_STARTED).add("Initializing plugin " + p.getShortName(), new Executable() { public void run(Reactor session) throws Exception { try { p.getPlugin().postInitialize(); } catch (Exception e) { failedPlugins.add(new FailedPlugin(p.getShortName(), e)); activePlugins.remove(p); plugins.remove(p); throw e; } } }); } // register them all session.addAll(g.discoverTasks(session)); } }); }}); }
diff --git a/src/frontend/org/voltdb/client/ConnectionUtil.java b/src/frontend/org/voltdb/client/ConnectionUtil.java index 260fe7e31..d6b7369c4 100644 --- a/src/frontend/org/voltdb/client/ConnectionUtil.java +++ b/src/frontend/org/voltdb/client/ConnectionUtil.java @@ -1,419 +1,419 @@ /* This file is part of VoltDB. * Copyright (C) 2008-2011 VoltDB Inc. * * VoltDB 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. * * VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.client; import java.io.EOFException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.Inet4Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Enumeration; import java.util.HashMap; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.voltdb.ClientInterface; import org.voltdb.ClientResponseImpl; import org.voltdb.messaging.FastDeserializer; import org.voltdb.messaging.FastSerializer; import org.voltdb.utils.DBBPool.BBContainer; /** * A utility class for opening a connection to a Volt server and authenticating as well * as sending invocations and receiving responses. It is safe to queue multiple requests * @author aweisberg * */ public class ConnectionUtil { private static class TF implements ThreadFactory { @Override public Thread newThread(Runnable r) { return new Thread(null, r, "Yet another thread", 65536); } } private static final TF m_tf = new TF(); public static class ExecutorPair { public final ExecutorService m_writeExecutor; public final ExecutorService m_readExecutor; public ExecutorPair() { m_writeExecutor = Executors.newSingleThreadExecutor(m_tf); m_readExecutor = Executors.newSingleThreadExecutor(m_tf); } private void shutdown() throws InterruptedException { m_readExecutor.shutdownNow(); m_writeExecutor.shutdownNow(); m_readExecutor.awaitTermination(1, TimeUnit.DAYS); m_writeExecutor.awaitTermination(1, TimeUnit.DAYS); } } private static final HashMap<SocketChannel, ExecutorPair> m_executors = new HashMap<SocketChannel, ExecutorPair>(); private static final AtomicLong m_handle = new AtomicLong(Long.MIN_VALUE); /** * Get a hashed password using SHA-1 in a consistent way. * @param password The password to encode. * @return The bytes of the hashed password. */ public static byte[] getHashedPassword(String password) { if (password == null) return null; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.exit(-1); } byte hashedPassword[] = null; try { hashedPassword = md.digest(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException("JVM doesn't support UTF-8. Please use a supported JVM", e); } return hashedPassword; } /** * Create a connection to a Volt server and authenticate the connection. * @param host * @param username * @param password * @param port * @throws IOException * @returns An array of objects. The first is an * authenticated socket channel, the second. is an array of 4 longs - * Integer hostId, Long connectionId, Long timestamp (part of instanceId), Int leaderAddress (part of instanceId). * The last object is the build string */ public static Object[] getAuthenticatedConnection( String host, String username, byte[] hashedPassword, int port) throws IOException { return getAuthenticatedConnection("database", host, username, hashedPassword, port); } /** * Create a connection to a Volt server for export and authenticate the connection. * @param host * @param username * @param password * @param port * @throws IOException * @returns An array of objects. The first is an * authenticated socket channel, the second. is an array of 4 longs - * Integer hostId, Long connectionId, Long timestamp (part of instanceId), Int leaderAddress (part of instanceId). * The last object is the build string */ public static Object[] getAuthenticatedExportConnection( String host, String username, byte[] hashedPassword, int port) throws IOException { return getAuthenticatedConnection("export", host, username, hashedPassword, port); } public static String getHostnameOrAddress() { try { final InetAddress addr = InetAddress.getLocalHost(); return addr.getHostName(); } catch (UnknownHostException e) { try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); if (interfaces == null) { return ""; } NetworkInterface intf = interfaces.nextElement(); Enumeration<InetAddress> addresses = intf.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (address instanceof Inet4Address) { return address.getHostAddress(); } } interfaces = NetworkInterface.getNetworkInterfaces(); while (addresses.hasMoreElements()) { return addresses.nextElement().getHostAddress(); } return ""; } catch (SocketException e1) { return ""; } } } public static InetAddress getLocalAddress() { try { final InetAddress addr = InetAddress.getLocalHost(); return addr; } catch (UnknownHostException e) { try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); if (interfaces == null) { return null; } NetworkInterface intf = interfaces.nextElement(); Enumeration<InetAddress> addresses = intf.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (address instanceof Inet4Address) { return address; } } interfaces = NetworkInterface.getNetworkInterfaces(); while (addresses.hasMoreElements()) { return addresses.nextElement(); } return null; } catch (SocketException e1) { return null; } } } private static Object[] getAuthenticatedConnection( String service, String host, String username, byte[] hashedPassword, int port) throws IOException { Object returnArray[] = new Object[3]; boolean success = false; InetSocketAddress addr = new InetSocketAddress(host, port); if (addr.isUnresolved()) { throw new java.net.UnknownHostException(host); } SocketChannel aChannel = SocketChannel.open(addr); returnArray[0] = aChannel; assert(aChannel.isConnected()); if (!aChannel.isConnected()) { // TODO Can open() be asynchronous if configureBlocking(true)? throw new IOException("Failed to open host " + host); } final long retvals[] = new long[4]; returnArray[1] = retvals; try { /* * Send login info */ aChannel.configureBlocking(true); aChannel.socket().setTcpNoDelay(true); FastSerializer fs = new FastSerializer(); fs.writeInt(0); // placeholder for length fs.writeByte(0); // version fs.writeString(service); // data service (export|database) fs.writeString(username); fs.write(hashedPassword); final ByteBuffer fsBuffer = fs.getBuffer(); final ByteBuffer b = ByteBuffer.allocate(fsBuffer.remaining()); b.put(fsBuffer); final int size = fsBuffer.limit() - 4; b.flip(); b.putInt(size); b.position(0); boolean successfulWrite = false; IOException writeException = null; try { for (int ii = 0; ii < 4 && b.hasRemaining(); ii++) { aChannel.write(b); } if (!b.hasRemaining()) { successfulWrite = true; } } catch (IOException e) { writeException = e; } int read = 0; ByteBuffer lengthBuffer = ByteBuffer.allocate(4); while (lengthBuffer.hasRemaining()) { read = aChannel.read(lengthBuffer); if (read == -1) { if (writeException != null) { throw writeException; } if (!successfulWrite) { - throw new IOException("Unable to write authentication info to serer"); + throw new IOException("Unable to write authentication info to server"); } throw new IOException("Authentication rejected"); } } lengthBuffer.flip(); int len = lengthBuffer.getInt(); ByteBuffer loginResponse = ByteBuffer.allocate(len);//Read version and length etc. while (loginResponse.hasRemaining()) { read = aChannel.read(loginResponse); if (read == -1) { if (writeException != null) { throw writeException; } if (!successfulWrite) { - throw new IOException("Unable to write authentication info to serer"); + throw new IOException("Unable to write authentication info to server"); } throw new IOException("Authentication rejected"); } } loginResponse.flip(); loginResponse.position(1); byte loginResponseCode = loginResponse.get(); if (loginResponseCode != 0) { aChannel.close(); switch (loginResponseCode) { case ClientInterface.MAX_CONNECTIONS_LIMIT_ERROR: throw new IOException("Server has too many connections"); case ClientInterface.WIRE_PROTOCOL_TIMEOUT_ERROR: throw new IOException("Connection timed out during authentication. " + "The VoltDB server may be overloaded."); case ClientInterface.EXPORT_DISABLED_REJECTION: throw new IOException("Export not enabled for server"); case ClientInterface.WIRE_PROTOCOL_FORMAT_ERROR: throw new IOException("Wire protocol format violation error"); case ClientInterface.AUTHENTICATION_FAILURE_DUE_TO_REJOIN: throw new IOException("Failed to authenticate to rejoining node"); default: throw new IOException("Authentication rejected"); } } retvals[0] = loginResponse.getInt(); retvals[1] = loginResponse.getLong(); retvals[2] = loginResponse.getLong(); retvals[3] = loginResponse.getInt(); int buildStringLength = loginResponse.getInt(); byte buildStringBytes[] = new byte[buildStringLength]; loginResponse.get(buildStringBytes); returnArray[2] = new String(buildStringBytes, "UTF-8"); aChannel.configureBlocking(false); aChannel.socket().setTcpNoDelay(false); aChannel.socket().setKeepAlive(true); success = true; } finally { if (!success) { aChannel.close(); } } return returnArray; } public static void closeConnection(SocketChannel connection) throws InterruptedException, IOException { synchronized (m_executors) { ExecutorPair p = m_executors.remove(connection); assert(p != null); p.shutdown(); } connection.close(); } private static ExecutorPair getExecutorPair(final SocketChannel channel) { synchronized (m_executors) { ExecutorPair p = m_executors.get(channel); if (p == null) { p = new ExecutorPair(); m_executors.put( channel, p); } return p; } } public static Future<Long> sendInvocation(final SocketChannel channel, final String procName,final Object ...parameters) { final ExecutorPair p = getExecutorPair(channel); return sendInvocation(p.m_writeExecutor, channel, procName, parameters); } public static Future<Long> sendInvocation(final ExecutorService executor, final SocketChannel channel, final String procName,final Object ...parameters) { return executor.submit(new Callable<Long>() { @Override public Long call() throws Exception { final long handle = m_handle.getAndIncrement(); final ProcedureInvocation invocation = new ProcedureInvocation(handle, procName, parameters); final FastSerializer fs = new FastSerializer(); final BBContainer c = fs.writeObjectForMessaging(invocation); do { channel.write(c.b); if (c.b.hasRemaining()) { Thread.yield(); } } while(c.b.hasRemaining()); c.discard(); return handle; } }); } public static Future<ClientResponse> readResponse(final SocketChannel channel) { final ExecutorPair p = getExecutorPair(channel); return readResponse(p.m_readExecutor, channel); } public static Future<ClientResponse> readResponse(final ExecutorService executor, final SocketChannel channel) { return executor.submit(new Callable<ClientResponse>() { @Override public ClientResponse call() throws Exception { ByteBuffer lengthBuffer = ByteBuffer.allocate(4); do { final int read = channel.read(lengthBuffer); if (read == -1) { throw new EOFException(); } if (lengthBuffer.hasRemaining()) { Thread.yield(); } } while (lengthBuffer.hasRemaining()); lengthBuffer.flip(); ByteBuffer message = ByteBuffer.allocate(lengthBuffer.getInt()); do { final int read = channel.read(message); if (read == -1) { throw new EOFException(); } if (lengthBuffer.hasRemaining()) { Thread.yield(); } } while (message.hasRemaining()); message.flip(); FastDeserializer fds = new FastDeserializer(message); ClientResponseImpl response = fds.readObject(ClientResponseImpl.class); return response; } }); } }
false
true
private static Object[] getAuthenticatedConnection( String service, String host, String username, byte[] hashedPassword, int port) throws IOException { Object returnArray[] = new Object[3]; boolean success = false; InetSocketAddress addr = new InetSocketAddress(host, port); if (addr.isUnresolved()) { throw new java.net.UnknownHostException(host); } SocketChannel aChannel = SocketChannel.open(addr); returnArray[0] = aChannel; assert(aChannel.isConnected()); if (!aChannel.isConnected()) { // TODO Can open() be asynchronous if configureBlocking(true)? throw new IOException("Failed to open host " + host); } final long retvals[] = new long[4]; returnArray[1] = retvals; try { /* * Send login info */ aChannel.configureBlocking(true); aChannel.socket().setTcpNoDelay(true); FastSerializer fs = new FastSerializer(); fs.writeInt(0); // placeholder for length fs.writeByte(0); // version fs.writeString(service); // data service (export|database) fs.writeString(username); fs.write(hashedPassword); final ByteBuffer fsBuffer = fs.getBuffer(); final ByteBuffer b = ByteBuffer.allocate(fsBuffer.remaining()); b.put(fsBuffer); final int size = fsBuffer.limit() - 4; b.flip(); b.putInt(size); b.position(0); boolean successfulWrite = false; IOException writeException = null; try { for (int ii = 0; ii < 4 && b.hasRemaining(); ii++) { aChannel.write(b); } if (!b.hasRemaining()) { successfulWrite = true; } } catch (IOException e) { writeException = e; } int read = 0; ByteBuffer lengthBuffer = ByteBuffer.allocate(4); while (lengthBuffer.hasRemaining()) { read = aChannel.read(lengthBuffer); if (read == -1) { if (writeException != null) { throw writeException; } if (!successfulWrite) { throw new IOException("Unable to write authentication info to serer"); } throw new IOException("Authentication rejected"); } } lengthBuffer.flip(); int len = lengthBuffer.getInt(); ByteBuffer loginResponse = ByteBuffer.allocate(len);//Read version and length etc. while (loginResponse.hasRemaining()) { read = aChannel.read(loginResponse); if (read == -1) { if (writeException != null) { throw writeException; } if (!successfulWrite) { throw new IOException("Unable to write authentication info to serer"); } throw new IOException("Authentication rejected"); } } loginResponse.flip(); loginResponse.position(1); byte loginResponseCode = loginResponse.get(); if (loginResponseCode != 0) { aChannel.close(); switch (loginResponseCode) { case ClientInterface.MAX_CONNECTIONS_LIMIT_ERROR: throw new IOException("Server has too many connections"); case ClientInterface.WIRE_PROTOCOL_TIMEOUT_ERROR: throw new IOException("Connection timed out during authentication. " + "The VoltDB server may be overloaded."); case ClientInterface.EXPORT_DISABLED_REJECTION: throw new IOException("Export not enabled for server"); case ClientInterface.WIRE_PROTOCOL_FORMAT_ERROR: throw new IOException("Wire protocol format violation error"); case ClientInterface.AUTHENTICATION_FAILURE_DUE_TO_REJOIN: throw new IOException("Failed to authenticate to rejoining node"); default: throw new IOException("Authentication rejected"); } } retvals[0] = loginResponse.getInt(); retvals[1] = loginResponse.getLong(); retvals[2] = loginResponse.getLong(); retvals[3] = loginResponse.getInt(); int buildStringLength = loginResponse.getInt(); byte buildStringBytes[] = new byte[buildStringLength]; loginResponse.get(buildStringBytes); returnArray[2] = new String(buildStringBytes, "UTF-8"); aChannel.configureBlocking(false); aChannel.socket().setTcpNoDelay(false); aChannel.socket().setKeepAlive(true); success = true; } finally { if (!success) { aChannel.close(); } } return returnArray; }
private static Object[] getAuthenticatedConnection( String service, String host, String username, byte[] hashedPassword, int port) throws IOException { Object returnArray[] = new Object[3]; boolean success = false; InetSocketAddress addr = new InetSocketAddress(host, port); if (addr.isUnresolved()) { throw new java.net.UnknownHostException(host); } SocketChannel aChannel = SocketChannel.open(addr); returnArray[0] = aChannel; assert(aChannel.isConnected()); if (!aChannel.isConnected()) { // TODO Can open() be asynchronous if configureBlocking(true)? throw new IOException("Failed to open host " + host); } final long retvals[] = new long[4]; returnArray[1] = retvals; try { /* * Send login info */ aChannel.configureBlocking(true); aChannel.socket().setTcpNoDelay(true); FastSerializer fs = new FastSerializer(); fs.writeInt(0); // placeholder for length fs.writeByte(0); // version fs.writeString(service); // data service (export|database) fs.writeString(username); fs.write(hashedPassword); final ByteBuffer fsBuffer = fs.getBuffer(); final ByteBuffer b = ByteBuffer.allocate(fsBuffer.remaining()); b.put(fsBuffer); final int size = fsBuffer.limit() - 4; b.flip(); b.putInt(size); b.position(0); boolean successfulWrite = false; IOException writeException = null; try { for (int ii = 0; ii < 4 && b.hasRemaining(); ii++) { aChannel.write(b); } if (!b.hasRemaining()) { successfulWrite = true; } } catch (IOException e) { writeException = e; } int read = 0; ByteBuffer lengthBuffer = ByteBuffer.allocate(4); while (lengthBuffer.hasRemaining()) { read = aChannel.read(lengthBuffer); if (read == -1) { if (writeException != null) { throw writeException; } if (!successfulWrite) { throw new IOException("Unable to write authentication info to server"); } throw new IOException("Authentication rejected"); } } lengthBuffer.flip(); int len = lengthBuffer.getInt(); ByteBuffer loginResponse = ByteBuffer.allocate(len);//Read version and length etc. while (loginResponse.hasRemaining()) { read = aChannel.read(loginResponse); if (read == -1) { if (writeException != null) { throw writeException; } if (!successfulWrite) { throw new IOException("Unable to write authentication info to server"); } throw new IOException("Authentication rejected"); } } loginResponse.flip(); loginResponse.position(1); byte loginResponseCode = loginResponse.get(); if (loginResponseCode != 0) { aChannel.close(); switch (loginResponseCode) { case ClientInterface.MAX_CONNECTIONS_LIMIT_ERROR: throw new IOException("Server has too many connections"); case ClientInterface.WIRE_PROTOCOL_TIMEOUT_ERROR: throw new IOException("Connection timed out during authentication. " + "The VoltDB server may be overloaded."); case ClientInterface.EXPORT_DISABLED_REJECTION: throw new IOException("Export not enabled for server"); case ClientInterface.WIRE_PROTOCOL_FORMAT_ERROR: throw new IOException("Wire protocol format violation error"); case ClientInterface.AUTHENTICATION_FAILURE_DUE_TO_REJOIN: throw new IOException("Failed to authenticate to rejoining node"); default: throw new IOException("Authentication rejected"); } } retvals[0] = loginResponse.getInt(); retvals[1] = loginResponse.getLong(); retvals[2] = loginResponse.getLong(); retvals[3] = loginResponse.getInt(); int buildStringLength = loginResponse.getInt(); byte buildStringBytes[] = new byte[buildStringLength]; loginResponse.get(buildStringBytes); returnArray[2] = new String(buildStringBytes, "UTF-8"); aChannel.configureBlocking(false); aChannel.socket().setTcpNoDelay(false); aChannel.socket().setKeepAlive(true); success = true; } finally { if (!success) { aChannel.close(); } } return returnArray; }
diff --git a/src/com/arpia49/Evento.java b/src/com/arpia49/Evento.java index e2db30e..5784ef9 100644 --- a/src/com/arpia49/Evento.java +++ b/src/com/arpia49/Evento.java @@ -1,95 +1,96 @@ package com.arpia49; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.Message; import android.widget.Toast; /** * @author arpia49 */ public class Evento { private static Context contexto = null; private int claveAlarma; private boolean fuerte; /** * @uml.property name="claveSonido" */ private int claveSonido; /** * @uml.property name="handler" */ private static Handler handler=null; private final int NOTIFICATION_ID = 1; public Evento(final int claveAlarma, int claveSonido, final Boolean fuerte, Activity val) { contexto = val.getApplicationContext(); this.claveAlarma = claveAlarma; this.claveSonido = claveSonido; this.fuerte = fuerte; if(handler==null){ handler = new Handler() { @Override public void handleMessage(Message msg) { @SuppressWarnings("unused") + Alarma tmpAlarma = ListaAlarmas.obtenerDesdeClave(msg.what); Notificacion nuevaNotificacion = new Notificacion.Builder( System.currentTimeMillis(), - ListaAlarmas.element(msg.what).getNombre(), - ListaAlarmas.element(msg.what).getUbicacion(), + tmpAlarma.getNombre(), + tmpAlarma.getUbicacion(), msg.what) .build(true); triggerNotification(); Toast.makeText(contexto, "¡Alarma detectada!", Toast.LENGTH_SHORT).show(); } }; } } public int getClave() { return claveAlarma; } public boolean getMuyFuerte() { return fuerte; } /** * @return * @uml.property name="claveSonido" */ public int getClaveSonido() { return claveSonido; } /** * @return * @uml.property name="handler" */ public static Handler getHandler() { return handler; } @SuppressWarnings("static-access") private void triggerNotification() { CharSequence title = "Timbre 2.0"; CharSequence message = "Click para ver las notificaciones de alertas"; NotificationManager notificationManager = (NotificationManager)contexto.getSystemService(contexto.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.icon, "¡Alarma detectada!", System.currentTimeMillis()); notification.defaults |= Notification.DEFAULT_VIBRATE; notification.defaults |= Notification.DEFAULT_LIGHTS; Intent notificationIntent = new Intent(contexto, ActNotificaciones.class); PendingIntent pendingIntent = PendingIntent.getActivity(contexto, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | Notification.FLAG_AUTO_CANCEL); notification.setLatestEventInfo(contexto, title, message, pendingIntent); notificationManager.notify(NOTIFICATION_ID, notification); } }
false
true
public Evento(final int claveAlarma, int claveSonido, final Boolean fuerte, Activity val) { contexto = val.getApplicationContext(); this.claveAlarma = claveAlarma; this.claveSonido = claveSonido; this.fuerte = fuerte; if(handler==null){ handler = new Handler() { @Override public void handleMessage(Message msg) { @SuppressWarnings("unused") Notificacion nuevaNotificacion = new Notificacion.Builder( System.currentTimeMillis(), ListaAlarmas.element(msg.what).getNombre(), ListaAlarmas.element(msg.what).getUbicacion(), msg.what) .build(true); triggerNotification(); Toast.makeText(contexto, "¡Alarma detectada!", Toast.LENGTH_SHORT).show(); } }; } }
public Evento(final int claveAlarma, int claveSonido, final Boolean fuerte, Activity val) { contexto = val.getApplicationContext(); this.claveAlarma = claveAlarma; this.claveSonido = claveSonido; this.fuerte = fuerte; if(handler==null){ handler = new Handler() { @Override public void handleMessage(Message msg) { @SuppressWarnings("unused") Alarma tmpAlarma = ListaAlarmas.obtenerDesdeClave(msg.what); Notificacion nuevaNotificacion = new Notificacion.Builder( System.currentTimeMillis(), tmpAlarma.getNombre(), tmpAlarma.getUbicacion(), msg.what) .build(true); triggerNotification(); Toast.makeText(contexto, "¡Alarma detectada!", Toast.LENGTH_SHORT).show(); } }; } }
diff --git a/src/net/zschech/gwt/comet/server/impl/BlockingAsyncServlet.java b/src/net/zschech/gwt/comet/server/impl/BlockingAsyncServlet.java index b4a51a5..1e1a29e 100644 --- a/src/net/zschech/gwt/comet/server/impl/BlockingAsyncServlet.java +++ b/src/net/zschech/gwt/comet/server/impl/BlockingAsyncServlet.java @@ -1,146 +1,146 @@ /* * Copyright 2009 Richard Zschech. * * 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 net.zschech.gwt.comet.server.impl; import java.io.IOException; import java.io.InterruptedIOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; /** * This AsyncServlet implementation blocks the HTTP request processing thread. * * It does not generate notifications for client disconnection and therefore must wait for a heartbeat send attempt to * detect client disconnection :-( * * @author Richard Zschech */ public class BlockingAsyncServlet extends AsyncServlet { @Override public void init(ServletContext context) throws ServletException { super.init(context); } @Override public Object suspend(CometServletResponseImpl response, CometSessionImpl session, HttpServletRequest request) throws IOException { assert !Thread.holdsLock(response); if (session == null) { try { synchronized (response) { while (!response.isTerminated()) { long heartBeatTime = response.getHeartbeatScheduleTime(); if (heartBeatTime <= 0) { try { response.heartbeat(); } catch (IOException e) { log("Error sending heartbeat", e); return null; } heartBeatTime = response.getHeartbeatScheduleTime(); } response.wait(heartBeatTime); } } } catch (InterruptedException e) { + log("Interrupted waiting for messages", e); response.tryTerminate(); - throw new InterruptedIOException(e.getMessage()); } } else { assert !Thread.holdsLock(session); try { try { synchronized (response) { while (session.isValid() && !response.isTerminated()) { while (response.checkSessionQueue(true)) { long sessionKeepAliveTime = response.getSessionKeepAliveScheduleTime(); if (sessionKeepAliveTime <= 0) { if (access(session.getHttpSession())) { session.setLastAccessedTime(); sessionKeepAliveTime = response.getSessionKeepAliveScheduleTime(); } else { response.tryTerminate(); break; } } long heartBeatTime = response.getHeartbeatScheduleTime(); if (heartBeatTime <= 0) { try { response.heartbeat(); } catch (IOException e) { log("Error sending heartbeat", e); break; } heartBeatTime = response.getHeartbeat(); } response.wait(Math.min(sessionKeepAliveTime, heartBeatTime)); } response.writeSessionQueue(true); } } } catch (InterruptedException e) { + log("Interrupted waiting for messages", e); response.tryTerminate(); - throw new InterruptedIOException(e.getMessage()); } } catch (IOException e) { log("Error writing messages", e); } if (!session.isValid() && !response.isTerminated()) { response.tryTerminate(); } } return null; } @Override public void terminate(CometServletResponseImpl response, final CometSessionImpl session, boolean serverInitiated, Object suspendInfo) { assert Thread.holdsLock(response); response.notifyAll(); } @Override public void invalidate(CometSessionImpl session) { CometServletResponseImpl response = session.getResponse(); if (response != null) { synchronized (response) { response.notifyAll(); } } } @Override public void enqueued(CometSessionImpl session) { CometServletResponseImpl response = session.getResponse(); if (response != null) { synchronized (response) { response.notifyAll(); } } } }
false
true
public Object suspend(CometServletResponseImpl response, CometSessionImpl session, HttpServletRequest request) throws IOException { assert !Thread.holdsLock(response); if (session == null) { try { synchronized (response) { while (!response.isTerminated()) { long heartBeatTime = response.getHeartbeatScheduleTime(); if (heartBeatTime <= 0) { try { response.heartbeat(); } catch (IOException e) { log("Error sending heartbeat", e); return null; } heartBeatTime = response.getHeartbeatScheduleTime(); } response.wait(heartBeatTime); } } } catch (InterruptedException e) { response.tryTerminate(); throw new InterruptedIOException(e.getMessage()); } } else { assert !Thread.holdsLock(session); try { try { synchronized (response) { while (session.isValid() && !response.isTerminated()) { while (response.checkSessionQueue(true)) { long sessionKeepAliveTime = response.getSessionKeepAliveScheduleTime(); if (sessionKeepAliveTime <= 0) { if (access(session.getHttpSession())) { session.setLastAccessedTime(); sessionKeepAliveTime = response.getSessionKeepAliveScheduleTime(); } else { response.tryTerminate(); break; } } long heartBeatTime = response.getHeartbeatScheduleTime(); if (heartBeatTime <= 0) { try { response.heartbeat(); } catch (IOException e) { log("Error sending heartbeat", e); break; } heartBeatTime = response.getHeartbeat(); } response.wait(Math.min(sessionKeepAliveTime, heartBeatTime)); } response.writeSessionQueue(true); } } } catch (InterruptedException e) { response.tryTerminate(); throw new InterruptedIOException(e.getMessage()); } } catch (IOException e) { log("Error writing messages", e); } if (!session.isValid() && !response.isTerminated()) { response.tryTerminate(); } } return null; }
public Object suspend(CometServletResponseImpl response, CometSessionImpl session, HttpServletRequest request) throws IOException { assert !Thread.holdsLock(response); if (session == null) { try { synchronized (response) { while (!response.isTerminated()) { long heartBeatTime = response.getHeartbeatScheduleTime(); if (heartBeatTime <= 0) { try { response.heartbeat(); } catch (IOException e) { log("Error sending heartbeat", e); return null; } heartBeatTime = response.getHeartbeatScheduleTime(); } response.wait(heartBeatTime); } } } catch (InterruptedException e) { log("Interrupted waiting for messages", e); response.tryTerminate(); } } else { assert !Thread.holdsLock(session); try { try { synchronized (response) { while (session.isValid() && !response.isTerminated()) { while (response.checkSessionQueue(true)) { long sessionKeepAliveTime = response.getSessionKeepAliveScheduleTime(); if (sessionKeepAliveTime <= 0) { if (access(session.getHttpSession())) { session.setLastAccessedTime(); sessionKeepAliveTime = response.getSessionKeepAliveScheduleTime(); } else { response.tryTerminate(); break; } } long heartBeatTime = response.getHeartbeatScheduleTime(); if (heartBeatTime <= 0) { try { response.heartbeat(); } catch (IOException e) { log("Error sending heartbeat", e); break; } heartBeatTime = response.getHeartbeat(); } response.wait(Math.min(sessionKeepAliveTime, heartBeatTime)); } response.writeSessionQueue(true); } } } catch (InterruptedException e) { log("Interrupted waiting for messages", e); response.tryTerminate(); } } catch (IOException e) { log("Error writing messages", e); } if (!session.isValid() && !response.isTerminated()) { response.tryTerminate(); } } return null; }
diff --git a/freeplane/src/org/freeplane/core/icon/factory/MindIconFactory.java b/freeplane/src/org/freeplane/core/icon/factory/MindIconFactory.java index c21269381..4ad0eb189 100644 --- a/freeplane/src/org/freeplane/core/icon/factory/MindIconFactory.java +++ b/freeplane/src/org/freeplane/core/icon/factory/MindIconFactory.java @@ -1,48 +1,47 @@ /* * Freeplane - mind map editor * Copyright (C) 2009 Tamas Eppel * * This file author is Tamas Eppel * * 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 program. If not, see <http://www.gnu.org/licenses/>. */ package org.freeplane.core.icon.factory; import org.freeplane.core.icon.MindIcon; import org.freeplane.core.resources.ResourceBundles; /** * * Factory for MindIcons. * * @author Tamas Eppel * */ public class MindIconFactory { private static final String DESC_KEY = "icon_%s"; /** * Constructs a MindIcon with the given name from the property file. * The name of the icon is the file name without the extension. * * @param name of the icon * @return */ public static MindIcon create(String name) { - return new MindIcon(name, - name + ".png", - ResourceBundles.getText(String.format(DESC_KEY, name))); + final String description = name.indexOf('/') > 0 ? "" : ResourceBundles.getText(String.format(DESC_KEY, name)); + return new MindIcon(name, name + ".png", description); } }
true
true
public static MindIcon create(String name) { return new MindIcon(name, name + ".png", ResourceBundles.getText(String.format(DESC_KEY, name))); }
public static MindIcon create(String name) { final String description = name.indexOf('/') > 0 ? "" : ResourceBundles.getText(String.format(DESC_KEY, name)); return new MindIcon(name, name + ".png", description); }
diff --git a/src/main/java/com/philihp/weblabora/model/UsageParam.java b/src/main/java/com/philihp/weblabora/model/UsageParam.java index 5d69518..215761f 100644 --- a/src/main/java/com/philihp/weblabora/model/UsageParam.java +++ b/src/main/java/com/philihp/weblabora/model/UsageParam.java @@ -1,405 +1,405 @@ package com.philihp.weblabora.model; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.philihp.weblabora.model.building.Building; import com.philihp.weblabora.model.building.Erection; public class UsageParam { private List<Coordinate> coordinates = new ArrayList<Coordinate>(); private String param; private int bonusPoints = 0; private int peat = 0; private int penny = 0; private int clay = 0; private int wood = 0; private int grain = 0; private int sheep = 0; private int stone = 0; private int flour = 0; private int grapes = 0; private int nickel = 0; private int hops = 0; private int coal = 0; private int book = 0; private int pottery = 0; private int whiskey = 0; private int straw = 0; private int meat = 0; private int ornament = 0; private int bread = 0; private int wine = 0; private int beer = 0; private int reliquary = 0; private Erection card = null; private boolean withJoker = false; public int differentSingularGoods() { int different = 0; if(peat == 1) different++; if(penny == 1) different++; if(clay == 1) different++; if(wood == 1) different++; if(grain == 1) different++; if(sheep == 1) different++; if(stone == 1) different++; if(flour == 1) different++; if(grapes == 1) different++; if(nickel == 1) different++; if(hops == 1) different++; if(coal == 1) different++; if(book == 1) different++; if(pottery == 1) different++; if(whiskey == 1) different++; if(straw == 1) different++; if(meat == 1) different++; if(ornament == 1) different++; if(bread == 1) different++; if(wine == 1) different++; if(beer == 1) different++; if(reliquary == 1) different++; return different; } public UsageParam(String in) { this.param = in; for(int i = 0; i < in.length()/2; i++) { - String token = in.substring(i,i+2); + String token = in.substring(i*2,i*2+2); if("Wo".equals(token)) wood++; else if("Gn".equals(token)) grain++; else if("Sh".equals(token)) sheep++; else if("Cl".equals(token)) clay++; else if("Pt".equals(token)) peat++; else if("Pn".equals(token)) penny++; else if("Sn".equals(token)) stone++; else if("Fl".equals(token)) flour++; else if("Gp".equals(token)) grapes++; else if("Ni".equals(token)) nickel++; else if("Ho".equals(token)) hops++; else if("Co".equals(token)) coal++; else if("Bo".equals(token)) book++; else if("Po".equals(token)) pottery++; else if("Wh".equals(token)) whiskey++; else if("Sw".equals(token)) straw++; else if("Mt".equals(token)) meat++; else if("Or".equals(token)) ornament++; else if("Br".equals(token)) bread++; else if("Wn".equals(token)) wine++; else if("Rq".equals(token)) reliquary++; else if("Bp".equals(token)) bonusPoints++; else if("Jo".equals(token)) withJoker = true; } } public static UsageParam is() { return new UsageParam(""); } public UsageParam bonusPoint(int quantity) { bonusPoints += quantity; return this; } public UsageParam peat(int quantity) { peat += quantity; return this; } public UsageParam penny(int quantity) { penny += quantity; return this; } public UsageParam clay(int quantity) { clay += quantity; return this; } public UsageParam wood(int quantity) { wood += quantity; return this; } public UsageParam grain(int quantity) { grain += quantity; return this; } public UsageParam sheep(int quantity) { sheep += quantity; return this; } public UsageParam stone(int quantity) { stone += quantity; return this; } public UsageParam flour(int quantity) { flour += quantity; return this; } public UsageParam grapes(int quantity) { grapes += quantity; return this; } public UsageParam nickel(int quantity) { nickel += quantity; return this; } public UsageParam hops(int quantity) { hops += quantity; return this; } public UsageParam coal(int quantity) { coal += quantity; return this; } public UsageParam book(int quantity) { book += quantity; return this; } public UsageParam pottery(int quantity) { pottery += quantity; return this; } public UsageParam whiskey(int quantity) { whiskey += quantity; return this; } public UsageParam straw(int quantity) { straw += quantity; return this; } public UsageParam meat(int quantity) { meat += quantity; return this; } public UsageParam ornament(int quantity) { ornament += quantity; return this; } public UsageParam bread(int quantity) { bread += quantity; return this; } public UsageParam wine(int quantity) { wine += quantity; return this; } public UsageParam beer(int quantity) { beer += quantity; return this; } public UsageParam reliquary(int quantity) { reliquary += quantity; return this; } public UsageParam card(Erection card) { this.card = card; return this; } public int getPeat() { return peat; } public int getPenny() { return penny; } public int getClay() { return clay; } public int getWood() { return wood; } public int getGrain() { return grain; } public int getSheep() { return sheep; } public int getStone() { return stone; } public int getFlour() { return flour; } public int getGrapes() { return grapes; } public int getNickel() { return nickel; } public int getHops() { return hops; } public int getCoal() { return coal; } public int getBook() { return book; } public int getPottery() { return pottery; } public int getWhiskey() { return whiskey; } public int getStraw() { return straw; } public int getMeat() { return meat; } public int getOrnament() { return ornament; } public int getBread() { return bread; } public int getWine() { return wine; } public int getBeer() { return beer; } public int getReliquary() { return reliquary; } public Erection getCard() { return card; } public int getBonusPoints() { return bonusPoints; } public void setWithJoker(boolean withJoker) { this.withJoker = withJoker; } public boolean isWithJoker() { return withJoker; } public boolean isWithGift() { return whiskey != 0 || wine != 0; } public double getEnergy() { return getCoal()*3 + getPeat()*2 + getWood() + getStraw()*0.5; } public double getFood() { return getPenny() + getGrain() + getSheep() * 2 + getFlour() + getGrapes() + getNickel() * 5 + getHops() + getWhiskey() * 2 + getMeat() * 5 + getBread() * 3 + getWine() + getBeer() * 5; } public int getCoins() { return getPenny() + getNickel()*5; } public String getParam() { return this.param; } public Coordinate getCoordinate() { return coordinates.get(0); } public List<Coordinate> getCoordinates() { return Collections.unmodifiableList(coordinates); } public void pushCoordinate(Coordinate coordinate) { coordinates.add(coordinate); } public void pushCoordinate(int x, int y) { pushCoordinate(new Coordinate(x, y)); } public String toString() { StringBuilder builder = new StringBuilder("("+this.param+")"); for(Coordinate coordinate : getCoordinates()) { return "("+coordinate.getX()+","+coordinate.getY()+")"; } return builder.toString(); } public void subtractWine(int wine) { this.wine -= wine; } }
true
true
public UsageParam(String in) { this.param = in; for(int i = 0; i < in.length()/2; i++) { String token = in.substring(i,i+2); if("Wo".equals(token)) wood++; else if("Gn".equals(token)) grain++; else if("Sh".equals(token)) sheep++; else if("Cl".equals(token)) clay++; else if("Pt".equals(token)) peat++; else if("Pn".equals(token)) penny++; else if("Sn".equals(token)) stone++; else if("Fl".equals(token)) flour++; else if("Gp".equals(token)) grapes++; else if("Ni".equals(token)) nickel++; else if("Ho".equals(token)) hops++; else if("Co".equals(token)) coal++; else if("Bo".equals(token)) book++; else if("Po".equals(token)) pottery++; else if("Wh".equals(token)) whiskey++; else if("Sw".equals(token)) straw++; else if("Mt".equals(token)) meat++; else if("Or".equals(token)) ornament++; else if("Br".equals(token)) bread++; else if("Wn".equals(token)) wine++; else if("Rq".equals(token)) reliquary++; else if("Bp".equals(token)) bonusPoints++; else if("Jo".equals(token)) withJoker = true; } }
public UsageParam(String in) { this.param = in; for(int i = 0; i < in.length()/2; i++) { String token = in.substring(i*2,i*2+2); if("Wo".equals(token)) wood++; else if("Gn".equals(token)) grain++; else if("Sh".equals(token)) sheep++; else if("Cl".equals(token)) clay++; else if("Pt".equals(token)) peat++; else if("Pn".equals(token)) penny++; else if("Sn".equals(token)) stone++; else if("Fl".equals(token)) flour++; else if("Gp".equals(token)) grapes++; else if("Ni".equals(token)) nickel++; else if("Ho".equals(token)) hops++; else if("Co".equals(token)) coal++; else if("Bo".equals(token)) book++; else if("Po".equals(token)) pottery++; else if("Wh".equals(token)) whiskey++; else if("Sw".equals(token)) straw++; else if("Mt".equals(token)) meat++; else if("Or".equals(token)) ornament++; else if("Br".equals(token)) bread++; else if("Wn".equals(token)) wine++; else if("Rq".equals(token)) reliquary++; else if("Bp".equals(token)) bonusPoints++; else if("Jo".equals(token)) withJoker = true; } }
diff --git a/src/org/protege/editor/owl/ui/frame/cls/InheritedAnonymousClassesFrameSection.java b/src/org/protege/editor/owl/ui/frame/cls/InheritedAnonymousClassesFrameSection.java index 2a5f4b5f..868363aa 100644 --- a/src/org/protege/editor/owl/ui/frame/cls/InheritedAnonymousClassesFrameSection.java +++ b/src/org/protege/editor/owl/ui/frame/cls/InheritedAnonymousClassesFrameSection.java @@ -1,136 +1,137 @@ package org.protege.editor.owl.ui.frame.cls; import java.util.Comparator; import java.util.HashSet; import java.util.Set; import org.protege.editor.owl.OWLEditorKit; import org.protege.editor.owl.model.inference.ReasonerPreferences.OptionalInferenceTask; import org.protege.editor.owl.ui.editor.OWLObjectEditor; import org.protege.editor.owl.ui.frame.AbstractOWLFrameSection; import org.protege.editor.owl.ui.frame.OWLFrame; import org.protege.editor.owl.ui.frame.OWLFrameSectionRow; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLClassAxiom; import org.semanticweb.owlapi.model.OWLClassExpression; import org.semanticweb.owlapi.model.OWLEquivalentClassesAxiom; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLSubClassOfAxiom; /** * Author: Matthew Horridge<br> * The University Of Manchester<br> * Bio-Health Informatics Group<br> * Date: 23-Feb-2007<br><br> */ public class InheritedAnonymousClassesFrameSection extends AbstractOWLFrameSection<OWLClass, OWLClassAxiom, OWLClassExpression> { private static final String LABEL = "SubClass Of (Anonymous Ancestor)"; private Set<OWLClass> processedClasses = new HashSet<OWLClass>(); public InheritedAnonymousClassesFrameSection(OWLEditorKit editorKit, OWLFrame<? extends OWLClass> frame) { super(editorKit, LABEL, "Anonymous Ancestor Class", frame); } protected OWLSubClassOfAxiom createAxiom(OWLClassExpression object) { return null; // canAdd() = false } public OWLObjectEditor<OWLClassExpression> getObjectEditor() { return null; // canAdd() = false } protected void refill(OWLOntology ontology) { Set<OWLClass> clses = getOWLModelManager().getOWLHierarchyManager().getOWLClassHierarchyProvider().getAncestors(getRootObject()); clses.remove(getRootObject()); for (OWLClass cls : clses) { for (OWLSubClassOfAxiom ax : ontology.getSubClassAxiomsForSubClass(cls)) { if (ax.getSuperClass().isAnonymous()) { addRow(new InheritedAnonymousClassesFrameSectionRow(getOWLEditorKit(), this, ontology, cls, ax)); } } for (OWLEquivalentClassesAxiom ax : ontology.getEquivalentClassesAxioms(cls)) { addRow(new InheritedAnonymousClassesFrameSectionRow(getOWLEditorKit(), this, ontology, cls, ax)); } processedClasses.add(cls); } } protected void refillInferred() { getOWLModelManager().getReasonerPreferences().executeTask(OptionalInferenceTask.SHOW_INFERRED_SUPER_CLASSES, new Runnable() { public void run() { refillInferredDoIt(); } }); } private void refillInferredDoIt() { if (!getOWLModelManager().getReasoner().isConsistent()) { return; } Set<OWLClass> clses = getReasoner().getSuperClasses(getRootObject(), true).getFlattened(); clses.remove(getRootObject()); for (OWLClass cls : clses) { if (!processedClasses.contains(cls)) { for (OWLOntology ontology : getOWLModelManager().getActiveOntology().getImportsClosure()) { for (OWLSubClassOfAxiom ax : ontology.getSubClassAxiomsForSubClass(cls)) { if (ax.getSuperClass().isAnonymous()) { addRow(new InheritedAnonymousClassesFrameSectionRow(getOWLEditorKit(), this, null, cls, ax)); } } for (OWLEquivalentClassesAxiom ax : ontology.getEquivalentClassesAxioms(cls)) { Set<OWLClassExpression> descs = new HashSet<OWLClassExpression>(ax.getClassExpressions()); descs.remove(getRootObject()); - OWLClassExpression superCls = descs.iterator().next(); - if (superCls.isAnonymous()) { - addRow(new InheritedAnonymousClassesFrameSectionRow(getOWLEditorKit(), - this, - null, - cls, - getOWLDataFactory().getOWLSubClassOfAxiom( - getRootObject(), - superCls))); + for (OWLClassExpression superCls : descs) { + if (superCls.isAnonymous()) { + addRow(new InheritedAnonymousClassesFrameSectionRow(getOWLEditorKit(), + this, + null, + cls, + getOWLDataFactory().getOWLSubClassOfAxiom( + getRootObject(), + superCls))); + } } } } } } } public boolean canAdd() { return false; } public void visit(OWLSubClassOfAxiom axiom) { reset(); } public void visit(OWLEquivalentClassesAxiom axiom) { reset(); } protected void clear() { processedClasses.clear(); } public Comparator<OWLFrameSectionRow<OWLClass, OWLClassAxiom, OWLClassExpression>> getRowComparator() { return null; } }
true
true
private void refillInferredDoIt() { if (!getOWLModelManager().getReasoner().isConsistent()) { return; } Set<OWLClass> clses = getReasoner().getSuperClasses(getRootObject(), true).getFlattened(); clses.remove(getRootObject()); for (OWLClass cls : clses) { if (!processedClasses.contains(cls)) { for (OWLOntology ontology : getOWLModelManager().getActiveOntology().getImportsClosure()) { for (OWLSubClassOfAxiom ax : ontology.getSubClassAxiomsForSubClass(cls)) { if (ax.getSuperClass().isAnonymous()) { addRow(new InheritedAnonymousClassesFrameSectionRow(getOWLEditorKit(), this, null, cls, ax)); } } for (OWLEquivalentClassesAxiom ax : ontology.getEquivalentClassesAxioms(cls)) { Set<OWLClassExpression> descs = new HashSet<OWLClassExpression>(ax.getClassExpressions()); descs.remove(getRootObject()); OWLClassExpression superCls = descs.iterator().next(); if (superCls.isAnonymous()) { addRow(new InheritedAnonymousClassesFrameSectionRow(getOWLEditorKit(), this, null, cls, getOWLDataFactory().getOWLSubClassOfAxiom( getRootObject(), superCls))); } } } } } }
private void refillInferredDoIt() { if (!getOWLModelManager().getReasoner().isConsistent()) { return; } Set<OWLClass> clses = getReasoner().getSuperClasses(getRootObject(), true).getFlattened(); clses.remove(getRootObject()); for (OWLClass cls : clses) { if (!processedClasses.contains(cls)) { for (OWLOntology ontology : getOWLModelManager().getActiveOntology().getImportsClosure()) { for (OWLSubClassOfAxiom ax : ontology.getSubClassAxiomsForSubClass(cls)) { if (ax.getSuperClass().isAnonymous()) { addRow(new InheritedAnonymousClassesFrameSectionRow(getOWLEditorKit(), this, null, cls, ax)); } } for (OWLEquivalentClassesAxiom ax : ontology.getEquivalentClassesAxioms(cls)) { Set<OWLClassExpression> descs = new HashSet<OWLClassExpression>(ax.getClassExpressions()); descs.remove(getRootObject()); for (OWLClassExpression superCls : descs) { if (superCls.isAnonymous()) { addRow(new InheritedAnonymousClassesFrameSectionRow(getOWLEditorKit(), this, null, cls, getOWLDataFactory().getOWLSubClassOfAxiom( getRootObject(), superCls))); } } } } } } }
diff --git a/CyberPrime2/src/cyberprime/servlets/Login.java b/CyberPrime2/src/cyberprime/servlets/Login.java index cfc2be8..45b8a95 100644 --- a/CyberPrime2/src/cyberprime/servlets/Login.java +++ b/CyberPrime2/src/cyberprime/servlets/Login.java @@ -1,162 +1,166 @@ package cyberprime.servlets; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.Iterator; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import cyberprime.entities.Clients; import cyberprime.entities.Sessions; import cyberprime.entities.dao.ClientsDAO; import cyberprime.util.FileMethods; /** * Servlet implementation class Login */ @WebServlet("/Login") public class Login extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Login() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); Clients client = (Clients) session.getAttribute("client"); if(client==null){ Object obj = new Object(); obj = "<p style='color:red'>*Your session has timed out</p>"; request.setAttribute("loginResult", obj); request.getRequestDispatcher("templateLogin.jsp").forward(request, response); return; } String image = (String)session.getAttribute("image"); String pattern = (String)request.getParameter("pattern"); Clients c = ClientsDAO.retrieveClient(client); if(c.getActivation()==null){ Object obj = new Object(); obj = "<p style='color:red'>*There is no user registered with the image uploaded</p>"; request.setAttribute("loginResult", obj); request.getRequestDispatcher("templateLogin.jsp").forward(request, response); return; } client.setUserId(c.getUserId()); if(pattern.length() != 0){ try { client.setPattern(pattern); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } else{ Object obj = new Object(); obj = "<p style='color:red'>*You did not choose a pattern</p>"; request.setAttribute("loginResult", obj); request.getRequestDispatcher("patternLogin.jsp").forward(request, response); return; } if(c.getActivation().equalsIgnoreCase("Pending")){ Object obj = new Object(); obj = "<p style='color:red'>*Your account has not been activated</p>"; request.setAttribute("loginResult", obj); request.getRequestDispatcher("patternLogin.jsp").forward(request, response); return; } else if(c.getActivation().equalsIgnoreCase("Active") || c.getActivation().equalsIgnoreCase("Reset")){ if(client.getImageHash().equals(c.getImageHash()) && client.getPattern().equals(c.getPattern())){ HttpSession existingHttpSession = request.getSession(); Clients existingClient = (Clients)existingHttpSession.getAttribute("client"); if (existingClient!=null){ Sessions existingSessions = new Sessions(existingHttpSession.getId(), existingClient.getUserId()); Set sessionArray = (Set) getServletContext().getAttribute("cyberprime.sessions"); Iterator sessionIt = sessionArray.iterator(); while(sessionIt.hasNext()) { Sessions sess = (Sessions)sessionIt.next(); System.out.println("Client id ="+sess.getClientId()); - if(sess.getClientId().equals(existingClient.getUserId())){ + if(sess.getClientId().equals(existingClient.getUserId()) && !sess.getSessionId().equals(existingHttpSession.getId())){ Object obj = new Object(); obj = "<p style='color:red'>*Your account is already logged in</p>"; request.setAttribute("loginResult", obj); FileMethods.fileDelete(image); request.getRequestDispatcher("templateLogin.jsp").forward(request, response); return; } + else if(sess.getClientId().equals(existingClient.getUserId()) && sess.getSessionId().equals(existingHttpSession.getId())){ + request.getRequestDispatcher("secured/templateNewHome.jsp").forward(request, response); + return; + } } } Sessions s = new Sessions(session.getId(),c.getUserId()); // s = SessionsDAO.createSession(s); // Set sess = Collections.synchronizedSet(new HashSet()); // getServletContext().setAttribute("cyberprime.sessions", sess); //WeakReference sessionRef = new WeakReference(s); Set sessions = (Set)getServletContext().getAttribute("cyberprime.sessions"); sessions.add(s); session.setAttribute("c", c); session.setMaxInactiveInterval(120); if(c.getActivation().equalsIgnoreCase("Active")){ session.removeAttribute("image"); FileMethods.fileDelete(image); request.getRequestDispatcher("secured/templateNewHome.jsp").forward(request, response); } else if(c.getActivation().equalsIgnoreCase("Reset")){ request.getRequestDispatcher("patternReset.jsp").forward(request, response); } } else{ Object obj = new Object(); obj = "<p style='color:red'>*Login failed, wrong pattern / image</p>"; request.setAttribute("loginResult", obj); request.getRequestDispatcher("patternLogin.jsp").forward(request, response); return; } } } }
false
true
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); Clients client = (Clients) session.getAttribute("client"); if(client==null){ Object obj = new Object(); obj = "<p style='color:red'>*Your session has timed out</p>"; request.setAttribute("loginResult", obj); request.getRequestDispatcher("templateLogin.jsp").forward(request, response); return; } String image = (String)session.getAttribute("image"); String pattern = (String)request.getParameter("pattern"); Clients c = ClientsDAO.retrieveClient(client); if(c.getActivation()==null){ Object obj = new Object(); obj = "<p style='color:red'>*There is no user registered with the image uploaded</p>"; request.setAttribute("loginResult", obj); request.getRequestDispatcher("templateLogin.jsp").forward(request, response); return; } client.setUserId(c.getUserId()); if(pattern.length() != 0){ try { client.setPattern(pattern); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } else{ Object obj = new Object(); obj = "<p style='color:red'>*You did not choose a pattern</p>"; request.setAttribute("loginResult", obj); request.getRequestDispatcher("patternLogin.jsp").forward(request, response); return; } if(c.getActivation().equalsIgnoreCase("Pending")){ Object obj = new Object(); obj = "<p style='color:red'>*Your account has not been activated</p>"; request.setAttribute("loginResult", obj); request.getRequestDispatcher("patternLogin.jsp").forward(request, response); return; } else if(c.getActivation().equalsIgnoreCase("Active") || c.getActivation().equalsIgnoreCase("Reset")){ if(client.getImageHash().equals(c.getImageHash()) && client.getPattern().equals(c.getPattern())){ HttpSession existingHttpSession = request.getSession(); Clients existingClient = (Clients)existingHttpSession.getAttribute("client"); if (existingClient!=null){ Sessions existingSessions = new Sessions(existingHttpSession.getId(), existingClient.getUserId()); Set sessionArray = (Set) getServletContext().getAttribute("cyberprime.sessions"); Iterator sessionIt = sessionArray.iterator(); while(sessionIt.hasNext()) { Sessions sess = (Sessions)sessionIt.next(); System.out.println("Client id ="+sess.getClientId()); if(sess.getClientId().equals(existingClient.getUserId())){ Object obj = new Object(); obj = "<p style='color:red'>*Your account is already logged in</p>"; request.setAttribute("loginResult", obj); FileMethods.fileDelete(image); request.getRequestDispatcher("templateLogin.jsp").forward(request, response); return; } } } Sessions s = new Sessions(session.getId(),c.getUserId()); // s = SessionsDAO.createSession(s); // Set sess = Collections.synchronizedSet(new HashSet()); // getServletContext().setAttribute("cyberprime.sessions", sess); //WeakReference sessionRef = new WeakReference(s); Set sessions = (Set)getServletContext().getAttribute("cyberprime.sessions"); sessions.add(s); session.setAttribute("c", c); session.setMaxInactiveInterval(120); if(c.getActivation().equalsIgnoreCase("Active")){ session.removeAttribute("image"); FileMethods.fileDelete(image); request.getRequestDispatcher("secured/templateNewHome.jsp").forward(request, response); } else if(c.getActivation().equalsIgnoreCase("Reset")){ request.getRequestDispatcher("patternReset.jsp").forward(request, response); } } else{ Object obj = new Object(); obj = "<p style='color:red'>*Login failed, wrong pattern / image</p>"; request.setAttribute("loginResult", obj); request.getRequestDispatcher("patternLogin.jsp").forward(request, response); return; } } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); Clients client = (Clients) session.getAttribute("client"); if(client==null){ Object obj = new Object(); obj = "<p style='color:red'>*Your session has timed out</p>"; request.setAttribute("loginResult", obj); request.getRequestDispatcher("templateLogin.jsp").forward(request, response); return; } String image = (String)session.getAttribute("image"); String pattern = (String)request.getParameter("pattern"); Clients c = ClientsDAO.retrieveClient(client); if(c.getActivation()==null){ Object obj = new Object(); obj = "<p style='color:red'>*There is no user registered with the image uploaded</p>"; request.setAttribute("loginResult", obj); request.getRequestDispatcher("templateLogin.jsp").forward(request, response); return; } client.setUserId(c.getUserId()); if(pattern.length() != 0){ try { client.setPattern(pattern); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } else{ Object obj = new Object(); obj = "<p style='color:red'>*You did not choose a pattern</p>"; request.setAttribute("loginResult", obj); request.getRequestDispatcher("patternLogin.jsp").forward(request, response); return; } if(c.getActivation().equalsIgnoreCase("Pending")){ Object obj = new Object(); obj = "<p style='color:red'>*Your account has not been activated</p>"; request.setAttribute("loginResult", obj); request.getRequestDispatcher("patternLogin.jsp").forward(request, response); return; } else if(c.getActivation().equalsIgnoreCase("Active") || c.getActivation().equalsIgnoreCase("Reset")){ if(client.getImageHash().equals(c.getImageHash()) && client.getPattern().equals(c.getPattern())){ HttpSession existingHttpSession = request.getSession(); Clients existingClient = (Clients)existingHttpSession.getAttribute("client"); if (existingClient!=null){ Sessions existingSessions = new Sessions(existingHttpSession.getId(), existingClient.getUserId()); Set sessionArray = (Set) getServletContext().getAttribute("cyberprime.sessions"); Iterator sessionIt = sessionArray.iterator(); while(sessionIt.hasNext()) { Sessions sess = (Sessions)sessionIt.next(); System.out.println("Client id ="+sess.getClientId()); if(sess.getClientId().equals(existingClient.getUserId()) && !sess.getSessionId().equals(existingHttpSession.getId())){ Object obj = new Object(); obj = "<p style='color:red'>*Your account is already logged in</p>"; request.setAttribute("loginResult", obj); FileMethods.fileDelete(image); request.getRequestDispatcher("templateLogin.jsp").forward(request, response); return; } else if(sess.getClientId().equals(existingClient.getUserId()) && sess.getSessionId().equals(existingHttpSession.getId())){ request.getRequestDispatcher("secured/templateNewHome.jsp").forward(request, response); return; } } } Sessions s = new Sessions(session.getId(),c.getUserId()); // s = SessionsDAO.createSession(s); // Set sess = Collections.synchronizedSet(new HashSet()); // getServletContext().setAttribute("cyberprime.sessions", sess); //WeakReference sessionRef = new WeakReference(s); Set sessions = (Set)getServletContext().getAttribute("cyberprime.sessions"); sessions.add(s); session.setAttribute("c", c); session.setMaxInactiveInterval(120); if(c.getActivation().equalsIgnoreCase("Active")){ session.removeAttribute("image"); FileMethods.fileDelete(image); request.getRequestDispatcher("secured/templateNewHome.jsp").forward(request, response); } else if(c.getActivation().equalsIgnoreCase("Reset")){ request.getRequestDispatcher("patternReset.jsp").forward(request, response); } } else{ Object obj = new Object(); obj = "<p style='color:red'>*Login failed, wrong pattern / image</p>"; request.setAttribute("loginResult", obj); request.getRequestDispatcher("patternLogin.jsp").forward(request, response); return; } } }
diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/QueryMapper.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/QueryMapper.java index 22341c58d..d8b0aa3f9 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/QueryMapper.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/QueryMapper.java @@ -1,97 +1,97 @@ /* * Copyright (c) 2011 by the original author(s). * * 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.springframework.data.document.mongodb.query; import java.util.ArrayList; import java.util.List; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import org.bson.types.ObjectId; import org.springframework.core.convert.ConversionFailedException; import org.springframework.data.document.mongodb.MongoReader; import org.springframework.data.document.mongodb.convert.MongoConverter; import org.springframework.data.mapping.model.PersistentEntity; /** * A helper class to encapsulate any modifications of a Query object before it gets submitted to the database. * * @author Jon Brisbin <[email protected]> */ public class QueryMapper<T> { final private DBObject query; final private PersistentEntity<T> entity; final private MongoReader<Object> reader; public QueryMapper(DBObject query, PersistentEntity<T> entity, MongoReader<?> reader) { this.query = query; this.entity = entity; this.reader = (MongoReader<Object>) reader; } public DBObject getMappedObject() { String idKey = null; - if (null != entity) { + if (null != entity && null != entity.getIdProperty()) { idKey = entity.getIdProperty().getName(); } else if (query.containsField("id")) { idKey = "id"; } else if (query.containsField("_id")) { idKey = "_id"; } DBObject newDbo = new BasicDBObject(); for (String key : query.keySet()) { String newKey = key; Object value = query.get(key); if (key.equals(idKey)) { if (value instanceof DBObject) { DBObject valueDbObj = (DBObject) value; if ("$in".equals(key)) { List<Object> ids = new ArrayList<Object>(); for (Object id : (Object[]) ((DBObject) value).get("$in")) { if (null != reader && !(id instanceof ObjectId)) { ObjectId oid = ((MongoConverter) reader).convertObjectId(id); ids.add(oid); } else { ids.add(id); } } newDbo.put("$in", ids.toArray(new ObjectId[ids.size()])); } if (null != reader) { try { value = reader.read(entity.getIdProperty().getType(), valueDbObj); } catch (ConversionFailedException ignored) { } } } else if (null != reader) { try { value = ((MongoConverter) reader).convertObjectId(value); } catch (ConversionFailedException ignored) { } } newKey = "_id"; } else { // TODO: Implement other forms of key conversion (like @Alias and whatnot) } newDbo.put(newKey, value); } return newDbo; } }
true
true
public DBObject getMappedObject() { String idKey = null; if (null != entity) { idKey = entity.getIdProperty().getName(); } else if (query.containsField("id")) { idKey = "id"; } else if (query.containsField("_id")) { idKey = "_id"; } DBObject newDbo = new BasicDBObject(); for (String key : query.keySet()) { String newKey = key; Object value = query.get(key); if (key.equals(idKey)) { if (value instanceof DBObject) { DBObject valueDbObj = (DBObject) value; if ("$in".equals(key)) { List<Object> ids = new ArrayList<Object>(); for (Object id : (Object[]) ((DBObject) value).get("$in")) { if (null != reader && !(id instanceof ObjectId)) { ObjectId oid = ((MongoConverter) reader).convertObjectId(id); ids.add(oid); } else { ids.add(id); } } newDbo.put("$in", ids.toArray(new ObjectId[ids.size()])); } if (null != reader) { try { value = reader.read(entity.getIdProperty().getType(), valueDbObj); } catch (ConversionFailedException ignored) { } } } else if (null != reader) { try { value = ((MongoConverter) reader).convertObjectId(value); } catch (ConversionFailedException ignored) { } } newKey = "_id"; } else { // TODO: Implement other forms of key conversion (like @Alias and whatnot) } newDbo.put(newKey, value); } return newDbo; }
public DBObject getMappedObject() { String idKey = null; if (null != entity && null != entity.getIdProperty()) { idKey = entity.getIdProperty().getName(); } else if (query.containsField("id")) { idKey = "id"; } else if (query.containsField("_id")) { idKey = "_id"; } DBObject newDbo = new BasicDBObject(); for (String key : query.keySet()) { String newKey = key; Object value = query.get(key); if (key.equals(idKey)) { if (value instanceof DBObject) { DBObject valueDbObj = (DBObject) value; if ("$in".equals(key)) { List<Object> ids = new ArrayList<Object>(); for (Object id : (Object[]) ((DBObject) value).get("$in")) { if (null != reader && !(id instanceof ObjectId)) { ObjectId oid = ((MongoConverter) reader).convertObjectId(id); ids.add(oid); } else { ids.add(id); } } newDbo.put("$in", ids.toArray(new ObjectId[ids.size()])); } if (null != reader) { try { value = reader.read(entity.getIdProperty().getType(), valueDbObj); } catch (ConversionFailedException ignored) { } } } else if (null != reader) { try { value = ((MongoConverter) reader).convertObjectId(value); } catch (ConversionFailedException ignored) { } } newKey = "_id"; } else { // TODO: Implement other forms of key conversion (like @Alias and whatnot) } newDbo.put(newKey, value); } return newDbo; }
diff --git a/src/main/java/hudson/plugins/perforce/PerforceSCM.java b/src/main/java/hudson/plugins/perforce/PerforceSCM.java index 1d14aa1..db502c7 100644 --- a/src/main/java/hudson/plugins/perforce/PerforceSCM.java +++ b/src/main/java/hudson/plugins/perforce/PerforceSCM.java @@ -1,2829 +1,2830 @@ package hudson.plugins.perforce; import com.tek42.perforce.Depot; import com.tek42.perforce.PerforceException; import com.tek42.perforce.model.Changelist; import com.tek42.perforce.model.Counter; import com.tek42.perforce.model.Label; import com.tek42.perforce.model.Workspace; import com.tek42.perforce.parse.Counters; import com.tek42.perforce.parse.Workspaces; import com.tek42.perforce.model.Changelist.FileEntry; import hudson.AbortException; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Util; import hudson.FilePath.FileCallable; import hudson.Launcher; import static hudson.Util.fixNull; import hudson.matrix.MatrixBuild; import hudson.matrix.MatrixRun; import hudson.model.*; import hudson.remoting.VirtualChannel; import hudson.scm.ChangeLogParser; import hudson.scm.PollingResult; import hudson.scm.SCM; import hudson.scm.SCMDescriptor; import hudson.scm.SCMRevisionState; import hudson.slaves.EnvironmentVariablesNodeProperty; import hudson.slaves.NodeProperty; import hudson.util.FormValidation; import hudson.util.LogTaskListener; import hudson.util.StreamTaskListener; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import javax.servlet.ServletException; import java.io.File; import java.io.FileFilter; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; import java.net.InetAddress; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * Extends {@link SCM} to provide integration with Perforce SCM repositories. * * @author Mike Wille * @author Brian Westrich * @author Victor Szoltysek */ public class PerforceSCM extends SCM { private Long configVersion; String p4User; String p4Passwd; String p4Port; String p4Client; String clientSpec; String projectPath; String projectOptions; String p4Label; String p4Counter; String p4Stream; /** * Transient so that old XML data will be read but not saved. * @deprecated Replaced by {@link #p4Tool} */ transient String p4Exe; String p4SysDrive = "C:"; String p4SysRoot = "C:\\WINDOWS"; PerforceRepositoryBrowser browser; private static final Logger LOGGER = Logger.getLogger(PerforceSCM.class.getName()); private static final int MAX_CHANGESETS_ON_FIRST_BUILD = 50; /** * Name of the p4 tool installation */ String p4Tool; /** * Use ClientSpec text file from depot to prepare the workspace view */ boolean useClientSpec = false; /** * True if stream depot is used, false otherwise */ boolean useStreamDepot = false; /** * This is being removed, including it as transient to fix exceptions on startup. */ transient int lastChange; /** * force sync is a one time trigger from the config area to force a sync with the depot. * it is reset to false after the first checkout. */ boolean forceSync = false; /** * Always force sync the workspace when running a build */ boolean alwaysForceSync = false; /** * Don't update the 'have' database on the server when syncing. */ boolean dontUpdateServer = false; /** * Disable Workspace pre-build automatic sync and changelog retrieval * This should be renamed if we can implement upgrade logic to handle old configs */ boolean disableAutoSync = false; /** * Disable Workspace syncing */ boolean disableSyncOnly = false; /** * Show integrated changelists */ boolean showIntegChanges = false; /** * This is to allow the client to use the old naming scheme * @deprecated As of 1.0.25, replaced by {@link #clientSuffixType} */ @Deprecated boolean useOldClientName = false; /** * If true, we will create the workspace view within the plugin. If false, we will not. */ Boolean createWorkspace = true; /** * If true, we will manage the workspace view within the plugin. If false, we will leave the * view alone. */ boolean updateView = true; /** * If false we add the slave hostname to the end of the client name when * running on a slave. Defaulting to true so as not to change the behavior * for existing users. * @deprecated As of 1.0.25, replaced by {@link #clientSuffixType} */ @Deprecated boolean dontRenameClient = true; /** * If true we update the named counter to the last changelist value after the sync operation. * If false the counter will be used as the changelist value to sync to. * Defaulting to false since the counter name is not set to begin with. */ boolean updateCounterValue = false; /** * If true, we will never update the client workspace spec on the perforce server. */ boolean dontUpdateClient = false; /** * If true the environment value P4PASSWD will be set to the value of p4Passwd. */ boolean exposeP4Passwd = false; /** * If true, the workspace will be deleted before the checkout commences. */ boolean wipeBeforeBuild = false; /** * If true, the ,repository will be deleted before the checkout commences in addition to the workspace. */ boolean wipeRepoBeforeBuild = false; /** * If > 0, then will override the changelist we sync to for the first build. */ int firstChange = -1; /** * Maximum amount of files that are recorded to a changelist, if < 1 show every file. */ int fileLimit = 0; /** * P4 user name(s) or regex user pattern to exclude from SCM poll to prevent build trigger. * Multiple user names are deliminated by space. */ String excludedUsers; /** * P4 file(s) or regex file pattern to exclude from SCM poll to prevent build trigger. */ String excludedFiles; /** * Use Case sensitive matching on excludedFiles. */ Boolean excludedFilesCaseSensitivity; /** * If a ticket was issued we can use it instead of the password in the environment. */ private String p4Ticket = null; /** * Determines what to append to the end of the client workspace names on slaves * Possible values: * None * Hostname * Hash */ String slaveClientNameFormat = null; /** * We need to store the changelog file name for the build so that we can expose * it to the build environment */ transient private String changelogFilename = null; /** * The value of the LineEnd field in the perforce Client spec. */ private String lineEndValue = "local"; /** * View mask settings for polling and/or syncing against a subset * of files in the client workspace. */ private boolean useViewMask = false; private String viewMask = null; private boolean useViewMaskForPolling = true; private boolean useViewMaskForSyncing = false; /** * Sync only on master option. */ private boolean pollOnlyOnMaster = false; /** * charset options */ private String p4Charset = null; private String p4CommandCharset = null; @DataBoundConstructor public PerforceSCM( String p4User, String p4Passwd, String p4Client, String p4Port, String projectOptions, String p4Tool, String p4SysRoot, String p4SysDrive, String p4Label, String p4Counter, String lineEndValue, String p4Charset, String p4CommandCharset, boolean updateCounterValue, boolean forceSync, boolean dontUpdateServer, boolean alwaysForceSync, boolean createWorkspace, boolean updateView, boolean disableAutoSync, boolean disableSyncOnly, boolean showIntegChanges, boolean wipeBeforeBuild, boolean wipeRepoBeforeBuild, boolean dontUpdateClient, boolean exposeP4Passwd, boolean pollOnlyOnMaster, String slaveClientNameFormat, int firstChange, int fileLimit, PerforceRepositoryBrowser browser, String excludedUsers, String excludedFiles, boolean excludedFilesCaseSensitivity) { this.configVersion = 0L; this.p4User = p4User; this.setP4Passwd(p4Passwd); this.exposeP4Passwd = exposeP4Passwd; this.p4Client = p4Client; this.p4Port = p4Port; this.p4Tool = p4Tool; this.pollOnlyOnMaster = pollOnlyOnMaster; this.projectOptions = (projectOptions != null) ? projectOptions : "noallwrite clobber nocompress unlocked nomodtime rmdir"; if (this.p4Label != null && p4Label != null) { Logger.getLogger(PerforceSCM.class.getName()).warning( "Label found in views and in label field. Using: " + p4Label); } this.p4Label = Util.fixEmptyAndTrim(p4Label); this.p4Counter = Util.fixEmptyAndTrim(p4Counter); this.updateCounterValue = updateCounterValue; this.projectPath = Util.fixEmptyAndTrim(projectPath); if (p4SysRoot != null && p4SysRoot.length() != 0) this.p4SysRoot = Util.fixEmptyAndTrim(p4SysRoot); if (p4SysDrive != null && p4SysDrive.length() != 0) this.p4SysDrive = Util.fixEmptyAndTrim(p4SysDrive); // Get systemDrive,systemRoot computer environment variables from // the current machine. String systemDrive = null; String systemRoot = null; if (Hudson.isWindows()) { try { EnvVars envVars = Computer.currentComputer().getEnvironment(); systemDrive = envVars.get("SystemDrive"); systemRoot = envVars.get("SystemRoot"); } catch (Exception ex) { LOGGER.log(Level.WARNING, ex.getMessage(), ex); } } if (p4SysRoot != null && p4SysRoot.length() != 0) { this.p4SysRoot = Util.fixEmptyAndTrim(p4SysRoot); } else { if (systemRoot != null && !systemRoot.trim().equals("")) { this.p4SysRoot = Util.fixEmptyAndTrim(systemRoot); } } if (p4SysDrive != null && p4SysDrive.length() != 0) { this.p4SysDrive = Util.fixEmptyAndTrim(p4SysDrive); } else { if (systemDrive != null && !systemDrive.trim().equals("")) { this.p4SysDrive = Util.fixEmptyAndTrim(systemDrive); } } this.lineEndValue = lineEndValue; this.forceSync = forceSync; this.dontUpdateServer = dontUpdateServer; this.alwaysForceSync = alwaysForceSync; this.disableAutoSync = disableAutoSync; this.disableSyncOnly = disableSyncOnly; this.showIntegChanges = showIntegChanges; this.browser = browser; this.wipeBeforeBuild = wipeBeforeBuild; this.wipeRepoBeforeBuild = wipeRepoBeforeBuild; this.createWorkspace = Boolean.valueOf(createWorkspace); this.updateView = updateView; this.dontUpdateClient = dontUpdateClient; this.slaveClientNameFormat = slaveClientNameFormat; this.firstChange = firstChange; this.fileLimit = fileLimit; this.dontRenameClient = false; this.useOldClientName = false; this.p4Charset = Util.fixEmptyAndTrim(p4Charset); this.p4CommandCharset = Util.fixEmptyAndTrim(p4CommandCharset); this.excludedUsers = Util.fixEmptyAndTrim(excludedUsers); this.excludedFiles = Util.fixEmptyAndTrim(excludedFiles); this.excludedFilesCaseSensitivity = excludedFilesCaseSensitivity; } /** * This only exists because we need to do initialization after we have been brought * back to life. I'm not quite clear on stapler and how all that works. * At any rate, it doesn't look like we have an init() method for setting up our Depot * after all of the setters have been called. Someone correct me if I'm wrong... * * UPDATE: With the addition of PerforceMailResolver, we now have need to share the depot object. I'm making * this protected to enable that. * * Always create a new Depot to reflect any changes to the machines that * P4 actions will be performed on. * * @param node the value of node */ protected Depot getDepot(Launcher launcher, FilePath workspace, AbstractProject project, AbstractBuild build, Node node) { HudsonP4ExecutorFactory p4Factory = new HudsonP4ExecutorFactory(launcher,workspace); Depot depot = new Depot(p4Factory); depot.setUser(p4User); depot.setPort(p4Port); if(build != null){ depot.setClient(substituteParameters(p4Client, build)); depot.setPassword(getDecryptedP4Passwd(build)); } else if(project != null) { depot.setClient(substituteParameters(p4Client, getDefaultSubstitutions(project))); depot.setPassword(getDecryptedP4Passwd(project)); } else { depot.setClient(p4Client); depot.setPassword(getDecryptedP4Passwd()); } if(node == null) depot.setExecutable(getP4Executable(p4Tool)); else depot.setExecutable(getP4Executable(p4Tool,node,TaskListener.NULL)); depot.setSystemDrive(p4SysDrive); depot.setSystemRoot(p4SysRoot); depot.setCharset(p4Charset); depot.setCommandCharset(p4CommandCharset); return depot; } /** * Override of SCM.buildEnvVars() in order to setup the last change we have * sync'd to as a Hudson * environment variable: P4_CHANGELIST * * @param build * @param env */ @Override public void buildEnvVars(AbstractBuild build, Map<String, String> env) { super.buildEnvVars(build, env); env.put("P4PORT", p4Port); env.put("P4USER", p4User); // if we want to allow p4 commands in script steps this helps if (exposeP4Passwd) { PerforcePasswordEncryptor encryptor = new PerforcePasswordEncryptor(); env.put("P4PASSWD", encryptor.decryptString(p4Passwd)); } // this may help when tickets are used since we are // not storing the ticket on the client during login if (p4Ticket != null) { env.put("P4TICKET", p4Ticket); } env.put("P4CLIENT", getEffectiveClientName(build)); PerforceTagAction pta = build.getAction(PerforceTagAction.class); if (pta != null) { if (pta.getChangeNumber() > 0) { int lastChange = pta.getChangeNumber(); env.put("P4_CHANGELIST", Integer.toString(lastChange)); } else if (pta.getTag() != null) { String label = pta.getTag(); env.put("P4_LABEL", label); } } if(changelogFilename != null) { env.put("HUDSON_CHANGELOG_FILE", changelogFilename); } } /** * Get the path to p4 executable from a Perforce tool installation. * * @param tool the p4 tool installation name * @return path to p4 tool path or an empty string if none is found */ public String getP4Executable(String tool) { PerforceToolInstallation toolInstallation = getP4Tool(tool); if(toolInstallation == null) return "p4"; return toolInstallation.getP4Exe(); } public String getP4Executable(String tool, Node node, TaskListener listener) { PerforceToolInstallation toolInstallation = getP4Tool(tool); if(toolInstallation == null) return "p4"; String p4Exe="p4"; try { p4Exe = toolInstallation.forNode(node, listener).getP4Exe(); }catch(IOException e){ listener.getLogger().println(e); }catch(InterruptedException e){ listener.getLogger().println(e); } return p4Exe; } /** * Get the path to p4 executable from a Perforce tool installation. * * @param tool the p4 tool installation name * @return path to p4 tool installation or null */ public PerforceToolInstallation getP4Tool(String tool) { PerforceToolInstallation[] installations = ((hudson.plugins.perforce.PerforceToolInstallation.DescriptorImpl)Hudson.getInstance(). getDescriptorByType(PerforceToolInstallation.DescriptorImpl.class)).getInstallations(); for(PerforceToolInstallation i : installations) { if(i.getName().equals(tool)) { return i; } } return null; } /** * Use the old job configuration data. This method is called after the object is read by XStream. * We want to create tool installations for each individual "p4Exe" path as field "p4Exe" has been removed. * * @return the new object which is an instance of PerforceSCM */ @SuppressWarnings( "deprecation" ) public Object readResolve() { if(createWorkspace == null) { createWorkspace = Boolean.TRUE; } if(p4Exe != null) { PerforceToolInstallation.migrateOldData(p4Exe); p4Tool = p4Exe; } if(excludedFilesCaseSensitivity == null) { excludedFilesCaseSensitivity = Boolean.TRUE; } if(configVersion == null) { configVersion = 0L; } return this; } private Hashtable<String, String> getDefaultSubstitutions(AbstractProject project) { Hashtable<String, String> subst = new Hashtable<String, String>(); subst.put("JOB_NAME", getSafeJobName(project)); for (NodeProperty nodeProperty: Hudson.getInstance().getGlobalNodeProperties()) { if (nodeProperty instanceof EnvironmentVariablesNodeProperty) { subst.putAll( ((EnvironmentVariablesNodeProperty)nodeProperty).getEnvVars() ); } } ParametersDefinitionProperty pdp = (ParametersDefinitionProperty) project.getProperty(hudson.model.ParametersDefinitionProperty.class); if(pdp != null) { for (ParameterDefinition pd : pdp.getParameterDefinitions()) { try { ParameterValue defaultValue = pd.getDefaultParameterValue(); if(defaultValue != null) { String name = defaultValue.getName(); String value = defaultValue.createVariableResolver(null).resolve(name); subst.put(name, value); } } catch (Exception e) { } } } return subst; } private String getEffectiveProjectPathFromFile(AbstractBuild build, AbstractProject project, PrintStream log, Depot depot) throws PerforceException { String projectPath; String clientSpec; if(build!=null){ clientSpec = substituteParameters(this.clientSpec, build); } else { clientSpec = substituteParameters(this.clientSpec, getDefaultSubstitutions(project)); } log.println("Read ClientSpec from: " + clientSpec); com.tek42.perforce.parse.File f = depot.getFile(clientSpec); projectPath = f.read(); if(build!=null){ projectPath = substituteParameters(projectPath, build); } else { projectPath = substituteParameters(projectPath, getDefaultSubstitutions(project)); } return projectPath; } private int getLastBuildChangeset(AbstractProject project) { Run lastBuild = project.getLastBuild(); return getLastChange(lastBuild); } /** * Perform some manipulation on the workspace URI to get a valid local path * <p> * Is there an issue doing this? What about remote workspaces? does that happen? * * @param path * @return * @throws IOException * @throws InterruptedException */ private String getLocalPathName(FilePath path, boolean isUnix) throws IOException, InterruptedException { return processPathName(path.getRemote(), isUnix); } public static String processPathName(String path, boolean isUnix){ String pathName = path; pathName = pathName.replaceAll("\\\\+", "\\\\"); pathName = pathName.replaceAll("/\\./", "/"); pathName = pathName.replaceAll("\\\\\\.\\\\", "\\\\"); pathName = pathName.replaceAll("/+", "/"); if(isUnix){ pathName = pathName.replaceAll("\\\\", "/"); } else { pathName = pathName.replaceAll("/", "\\\\"); } return pathName; } private static void retrieveUserInformation(Depot depot, List<Changelist> changes) throws PerforceException { // uniqify in order to reduce number of calls to P4. HashSet<String> users = new HashSet<String>(); for(Changelist change : changes){ users.add(change.getUser()); } for(String user : users){ com.tek42.perforce.model.User pu; try{ pu = depot.getUsers().getUser(user); }catch(Exception e){ throw new PerforceException("Problem getting user information for " + user,e); } //If there is no such user in perforce, then ignore and keep going. if(pu == null){ LOGGER.warning("Perforce User ("+user+") does not exist."); continue; } User author = User.get(user); // Need to store the actual perforce user id for later retrieval // because Jenkins does not support all the same characters that // perforce does in the userID. PerforceUserProperty puprop = author.getProperty(PerforceUserProperty.class); if ( puprop == null || puprop.getPerforceId() == null || puprop.getPerforceId().equals("")){ puprop = new PerforceUserProperty(); try { author.addProperty(puprop); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } } puprop.setPerforceEmail(pu.getEmail()); puprop.setPerforceId(user); } } private static class WipeWorkspaceExcludeFilter implements FileFilter, Serializable { private List<String> excluded = new ArrayList<String>(); public WipeWorkspaceExcludeFilter(String... args){ for(String arg : args){ excluded.add(arg); } } public void exclude(String arg){ excluded.add(arg); } public boolean accept(File arg0) { for(String exclude : excluded){ if(arg0.getName().equals(exclude)){ return false; } } return true; } } private static boolean overrideWithBooleanParameter(String paramName, AbstractBuild build, boolean dflt) { boolean value = dflt; Object param; if(build.getBuildVariables() != null){ if((param = build.getBuildVariables().get(paramName)) != null){ String paramString = param.toString(); if(paramString.toUpperCase().equals("TRUE") || paramString.equals("1")){ value = true; } else { value = false; } } } return value; } /* * @see hudson.scm.SCM#checkout(hudson.model.AbstractBuild, hudson.Launcher, hudson.FilePath, hudson.model.BuildListener, java.io.File) */ @Override public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException { PrintStream log = listener.getLogger(); changelogFilename = changelogFile.getAbsolutePath(); boolean wipeBeforeBuild = overrideWithBooleanParameter( "P4CLEANWORKSPACE", build, this.wipeBeforeBuild); boolean wipeRepoBeforeBuild = overrideWithBooleanParameter( "P4CLEANREPOINWORKSPACE", build, this.wipeRepoBeforeBuild); boolean forceSync = overrideWithBooleanParameter( "P4FORCESYNC", build, this.forceSync); boolean disableAutoSync = overrideWithBooleanParameter( "P4DISABLESYNC", build, this.disableAutoSync); boolean disableSyncOnly = overrideWithBooleanParameter( "P4DISABLESYNCONLY", build, this.disableSyncOnly); //Use local variables so that substitutions are not saved String p4Label = substituteParameters(this.p4Label, build); String viewMask = substituteParameters(this.viewMask, build); Depot depot = getDepot(launcher,workspace, build.getProject(), build, build.getBuiltOn()); String p4Stream = substituteParameters(this.p4Stream, build); //If we're doing a matrix build, we should always force sync. if((Object)build instanceof MatrixBuild || (Object)build instanceof MatrixRun){ if(!alwaysForceSync && !wipeBeforeBuild) log.println("This is a matrix build; It is HIGHLY recommended that you enable the " + "'Always Force Sync' or 'Clean Workspace' options. " + "Failing to do so will likely result in child builds not being synced properly."); } try { //keep projectPath local so any modifications for slaves don't get saved String projectPath; if(useClientSpec){ projectPath = getEffectiveProjectPathFromFile(build, build.getProject(), log, depot); } else { projectPath = substituteParameters(this.projectPath, build); } Workspace p4workspace = getPerforceWorkspace(build.getProject(), projectPath, depot, build.getBuiltOn(), build, launcher, workspace, listener, false); boolean dirtyWorkspace = p4workspace.isDirty(); saveWorkspaceIfDirty(depot, p4workspace, log); if(wipeBeforeBuild){ log.println("Clearing workspace..."); String p4config = substituteParameters("${P4CONFIG}", build); WipeWorkspaceExcludeFilter wipeFilter = new WipeWorkspaceExcludeFilter(".p4config",p4config); if(wipeRepoBeforeBuild){ log.println("Clear workspace includes .repository ..."); } else { log.println("Note: .repository directory in workspace (if exists) is skipped."); wipeFilter.exclude(".repository"); } List<FilePath> workspaceDirs = workspace.list(wipeFilter); for(FilePath dir : workspaceDirs){ dir.deleteRecursive(); } log.println("Cleared workspace."); forceSync = true; } //In case of a stream depot, we want Perforce to handle the client views. So let's re-initialize //the p4workspace object if it was changed since the last build. Also, populate projectPath with //the current view from Perforce. We need it for labeling. if (useStreamDepot) { if (dirtyWorkspace) { //Support for concurrent builds String p4Client = getConcurrentClientName(workspace, getEffectiveClientName(build)); p4workspace = depot.getWorkspaces().getWorkspace(p4Client, p4Stream); } projectPath = p4workspace.getTrimmedViewsAsString(); } //If we're not managing the view, populate the projectPath with the current view from perforce //This is both for convenience, and so the labeling mechanism can operate correctly if(!updateView){ projectPath = p4workspace.getTrimmedViewsAsString(); } //Get the list of changes since the last time we looked... String p4WorkspacePath = "//" + p4workspace.getName() + "/..."; int lastChange = getLastChange((Run)build.getPreviousBuild()); log.println("Last build changeset: " + lastChange); int newestChange = lastChange; if(!disableAutoSync) { List<Changelist> changes; if (p4Label != null && !p4Label.trim().isEmpty()) { newestChange = depot.getChanges().getHighestLabelChangeNumber(p4workspace, p4Label.trim(), p4WorkspacePath); } else { String counterName; if (p4Counter != null && !updateCounterValue) counterName = substituteParameters(this.p4Counter, build); else counterName = "change"; Counter counter = depot.getCounters().getCounter(counterName); newestChange = counter.getValue(); } if(build instanceof MatrixRun) { newestChange = getOrSetMatrixChangeSet(build, depot, newestChange, projectPath, log); } if (lastChange <= 0){ lastChange = newestChange - MAX_CHANGESETS_ON_FIRST_BUILD; if (lastChange < 0){ lastChange = 0; } } if (lastChange >= newestChange) { changes = new ArrayList<Changelist>(0); } else { List<Integer> changeNumbersTo; if(useViewMaskForSyncing && useViewMask){ changeNumbersTo = depot.getChanges().getChangeNumbersInRange(p4workspace, lastChange+1, newestChange, viewMask, showIntegChanges); } else { changeNumbersTo = depot.getChanges().getChangeNumbersInRange(p4workspace, lastChange+1, newestChange, showIntegChanges); } changes = depot.getChanges().getChangelistsFromNumbers(changeNumbersTo, fileLimit); } if (changes.size() > 0) { // Save the changes we discovered. PerforceChangeLogSet.saveToChangeLog( new FileOutputStream(changelogFile), changes); newestChange = changes.get(0).getChangeNumber(); // Get and store information about committers retrieveUserInformation(depot, changes); } else { // No new changes discovered (though the definition of the workspace or label may have changed). createEmptyChangeLog(changelogFile, listener, "changelog"); } if(!disableSyncOnly){ // Now we can actually do the sync process... StringBuilder sbMessage = new StringBuilder("Sync'ing workspace to "); StringBuilder sbSyncPath = new StringBuilder(p4WorkspacePath); StringBuilder sbSyncPathSuffix = new StringBuilder(); sbSyncPathSuffix.append("@"); if (p4Label != null && !p4Label.trim().isEmpty()) { sbMessage.append("label "); sbMessage.append(p4Label); sbSyncPathSuffix.append(p4Label); } else { sbMessage.append("changelist "); sbMessage.append(newestChange); sbSyncPathSuffix.append(newestChange); } sbSyncPath.append(sbSyncPathSuffix); if (forceSync || alwaysForceSync) sbMessage.append(" (forcing sync of unchanged files)."); else sbMessage.append("."); log.println(sbMessage.toString()); String syncPath = sbSyncPath.toString(); long startTime = System.currentTimeMillis(); if(useViewMaskForSyncing && useViewMask){ for(String path : viewMask.replaceAll("\r", "").split("\n")){ StringBuilder sbMaskPath = new StringBuilder(path); sbMaskPath.append(sbSyncPathSuffix); String maskPath = sbMaskPath.toString(); depot.getWorkspaces().syncTo(maskPath, forceSync || alwaysForceSync, dontUpdateServer); } } else { depot.getWorkspaces().syncTo(syncPath, forceSync || alwaysForceSync, dontUpdateServer); } long endTime = System.currentTimeMillis(); long duration = endTime - startTime; log.println("Sync complete, took " + duration + " ms"); } } boolean doSaveProject = false; // reset one time use variables... if(this.forceSync == true || this.firstChange != -1){ this.forceSync = false; this.firstChange = -1; //save the one time use variables... doSaveProject = true; } //If we aren't managing the client views, update the current ones //with those from perforce, and save them if they have changed. if(!this.updateView && !projectPath.equals(this.projectPath)){ this.projectPath = projectPath; doSaveProject = true; } if(doSaveProject){ build.getParent().save(); } // Add tagging action that enables the user to create a label // for this build. build.addAction(new PerforceTagAction( build, depot, newestChange, projectPath, p4User)); build.addAction(new PerforceSCMRevisionState(newestChange)); if (p4Counter != null && updateCounterValue) { // Set or create a counter to mark this change Counter counter = new Counter(); - counter.setName(p4Counter); + String counterName = substituteParameters(this.p4Counter, build); + counter.setName(counterName); counter.setValue(newestChange); - log.println("Updating counter " + p4Counter + " to " + newestChange); + log.println("Updating counter " + counterName + " to " + newestChange); depot.getCounters().saveCounter(counter); } // remember the p4Ticket if we were issued one p4Ticket = depot.getP4Ticket(); return true; } catch (PerforceException e) { log.print("Caught exception communicating with perforce. " + e.getMessage()); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); e.printStackTrace(pw); pw.flush(); log.print(sw.toString()); throw new AbortException( "Unable to communicate with perforce. " + e.getMessage()); } catch (InterruptedException e) { throw new IOException( "Unable to get hostname from slave. " + e.getMessage()); } } private synchronized int getOrSetMatrixChangeSet(AbstractBuild build, Depot depot, int newestChange, String projectPath, PrintStream log) { int lastChange = 0; //special consideration for matrix builds if (build instanceof MatrixRun) { log.println("This is a matrix run, trying to use change number from parent/siblings..."); AbstractBuild parentBuild = ((MatrixRun) build).getParentBuild(); if (parentBuild != null) { int parentChange = getLastChange(parentBuild); if (parentChange > 0) { //use existing changeset from parent log.println("Latest change from parent is: "+Integer.toString(parentChange)); lastChange = parentChange; } else { //no changeset on parent, set it for other //matrixruns to use log.println("No change number has been set by parent/siblings. Using latest."); parentBuild.addAction(new PerforceTagAction(build, depot, newestChange, projectPath, p4User)); } } } return lastChange; } /** * compute the path(s) that we search on to detect whether the project * has any unsynched changes * * @param p4workspace the workspace * @return a string of path(s), e.g. //mymodule1/... //mymodule2/... */ private String getChangesPaths(Workspace p4workspace) { return PerforceSCMHelper.computePathFromViews(p4workspace.getViews()); } @Override public PerforceRepositoryBrowser getBrowser() { return browser; } /* * @see hudson.scm.SCM#createChangeLogParser() */ @Override public ChangeLogParser createChangeLogParser() { return new PerforceChangeLogParser(); } /** * Part of the new polling routines. This determines the state of the build specified. * @param ab * @param lnchr * @param tl * @return * @throws IOException * @throws InterruptedException */ @Override public SCMRevisionState calcRevisionsFromBuild(AbstractBuild<?, ?> ab, Launcher lnchr, TaskListener tl) throws IOException, InterruptedException { //This shouldn't be getting called, but in case it is, let's calculate the revision anyways. PerforceTagAction action = (PerforceTagAction)ab.getAction(PerforceTagAction.class); if(action==null){ //something went wrong... return null; } return new PerforceSCMRevisionState(action.getChangeNumber()); } /** * Part of the new polling routines. This compares the specified revision state with the repository, * and returns a polling result. * @param ap * @param lnchr * @param fp * @param tl * @param scmrs * @return * @throws IOException * @throws InterruptedException */ @Override protected PollingResult compareRemoteRevisionWith(AbstractProject<?, ?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState scmrs) throws IOException, InterruptedException { PrintStream logger = listener.getLogger(); logger.println("Looking for changes..."); final PerforceSCMRevisionState baseline; if (scmrs instanceof PerforceSCMRevisionState) { baseline = (PerforceSCMRevisionState)scmrs; } else if (project.getLastBuild()!=null) { baseline = (PerforceSCMRevisionState)calcRevisionsFromBuild(project.getLastBuild(), launcher, listener); } else { baseline = new PerforceSCMRevisionState(-1); } if (project.getLastBuild() == null || baseline == null) { listener.getLogger().println("No previous builds to use for comparison."); return PollingResult.BUILD_NOW; } Hashtable<String, String> subst = getDefaultSubstitutions(project); Depot depot; try { Node buildNode = getPollingNode(project); if (buildNode == null){ depot = getDepot(launcher,workspace,project,null,buildNode); logger.println("Using master"); } else { depot = getDepot(buildNode.createLauncher(listener),buildNode.getRootPath(),project,null, buildNode); logger.println("Using node: " + buildNode.getDisplayName()); } Workspace p4workspace = getPerforceWorkspace(project, substituteParameters(projectPath, subst), depot, buildNode, null, launcher, workspace, listener, true); saveWorkspaceIfDirty(depot, p4workspace, logger); int lastChangeNumber = baseline.getRevision(); SCMRevisionState repositoryState = getCurrentDepotRevisionState(p4workspace, project, depot, logger, lastChangeNumber); PollingResult.Change change; if(repositoryState.equals(baseline)){ change = PollingResult.Change.NONE; } else { change = PollingResult.Change.SIGNIFICANT; } return new PollingResult(baseline, repositoryState, change); } catch (PerforceException e) { System.out.println("Problem: " + e.getMessage()); logger.println("Caught Exception communicating with perforce." + e.getMessage()); throw new IOException("Unable to communicate with perforce. Check log file for: " + e.getMessage()); } } private Node getPollingNode(AbstractProject project) { Node buildNode = project.getLastBuiltOn(); if (pollOnlyOnMaster) { buildNode = null; } else { //try to get an active node that the project is configured to use buildNode = project.getLastBuiltOn(); if (!isNodeOnline(buildNode)) { buildNode = null; } if (buildNode == null && !pollOnlyOnMaster) { buildNode = getOnlineConfiguredNode(project); } if (pollOnlyOnMaster) { buildNode = null; } } return buildNode; } private Node getOnlineConfiguredNode(AbstractProject project) { Node buildNode = null; for (Node node : Hudson.getInstance().getNodes()) { hudson.model.Label l = project.getAssignedLabel(); if (l != null && !l.contains(node)) { continue; } if (l == null && node.getMode() == hudson.model.Node.Mode.EXCLUSIVE) { continue; } if (!isNodeOnline(node)) { continue; } buildNode = node; break; } return buildNode; } private boolean isNodeOnline(Node node) { return node != null && node.toComputer() != null && node.toComputer().isOnline(); } private SCMRevisionState getCurrentDepotRevisionState(Workspace p4workspace, AbstractProject project, Depot depot, PrintStream logger, int lastChangeNumber) throws IOException, InterruptedException, PerforceException { int highestSelectedChangeNumber; List<Integer> changeNumbers; if (p4Counter != null && !updateCounterValue) { // If this is a downstream build that triggers by polling the set counter // use the counter as the value for the newest change instead of the workspace view Counter counter = depot.getCounters().getCounter(p4Counter); highestSelectedChangeNumber = counter.getValue(); logger.println("Latest submitted change selected by named counter is " + highestSelectedChangeNumber); String root = "//" + p4workspace.getName() + "/..."; changeNumbers = depot.getChanges().getChangeNumbersInRange(p4workspace, lastChangeNumber+1, highestSelectedChangeNumber, root, false); } else { // General Case // Has any new change been submitted since then (that is selected // by this workspace). Integer newestChange; String p4Label = substituteParameters(this.p4Label, getDefaultSubstitutions(project)); if (p4Label != null && !p4Label.trim().isEmpty()) { //In case where we are using a rolling label. String root = "//" + p4workspace.getName() + "/..."; newestChange = depot.getChanges().getHighestLabelChangeNumber(p4workspace, p4Label.trim(), root); } else { Counter counter = depot.getCounters().getCounter("change"); newestChange = counter.getValue(); } if(useViewMaskForPolling && useViewMask){ changeNumbers = depot.getChanges().getChangeNumbersInRange(p4workspace, lastChangeNumber+1, newestChange, substituteParameters(viewMask, getDefaultSubstitutions(project)), false); } else { String root = "//" + p4workspace.getName() + "/..."; changeNumbers = depot.getChanges().getChangeNumbersInRange(p4workspace, lastChangeNumber+1, newestChange, root, false); } if (changeNumbers.isEmpty()) { // Wierd, this shouldn't be! I suppose it could happen if the // view selects no files (e.g. //depot/non-existent-branch/...). // This can also happen when using view masks with polling. logger.println("No changes found."); return new PerforceSCMRevisionState(lastChangeNumber); } else { highestSelectedChangeNumber = changeNumbers.get(0).intValue(); logger.println("Latest submitted change selected by workspace is " + highestSelectedChangeNumber); } } if (lastChangeNumber >= highestSelectedChangeNumber) { // Note, can't determine with currently saved info // whether the workspace definition has changed. logger.println("Assuming that the workspace definition has not changed."); return new PerforceSCMRevisionState(lastChangeNumber); } else { for (int changeNumber : changeNumbers) { if (isChangelistExcluded(depot.getChanges().getChangelist(changeNumber, fileLimit), project, logger)) { logger.println("Changelist "+changeNumber+" is composed of file(s) and/or user(s) that are excluded."); } else { return new PerforceSCMRevisionState(changeNumber); } } return new PerforceSCMRevisionState(lastChangeNumber); } } /** * Determines whether or not P4 changelist should be excluded and ignored by the polling trigger. * Exclusions include files, regex patterns of files, and/or changelists submitted by a specific user(s). * * @param changelist the p4 changelist * @return True if changelist only contains user(s) and/or file(s) that are denoted to be excluded */ private boolean isChangelistExcluded(Changelist changelist, AbstractProject project, PrintStream logger) { if (changelist == null){ return false; } if (excludedUsers != null && !excludedUsers.trim().equals("")) { List<String> users = Arrays.asList(substituteParameters(excludedUsers,getDefaultSubstitutions(project)).split("\n")); if ( users.contains(changelist.getUser()) ) { logger.println("Excluded User ["+changelist.getUser()+"] found in changelist."); return true; } // no literal match, try regex Matcher matcher; for (String regex : users) { try { matcher = Pattern.compile(regex).matcher(changelist.getUser()); if (matcher.find()) { logger.println("Excluded User ["+changelist.getUser()+"] found in changelist."); return true; } } catch (PatternSyntaxException pse) { break; // should never occur since we validate regex input before hand, but just be safe } } } if (excludedFiles != null && !excludedFiles.trim().equals("")) { List<String> files = Arrays.asList(substituteParameters(excludedFiles,getDefaultSubstitutions(project)).split("\n")); StringBuffer buff = null; Matcher matcher = null; boolean matchFound; if (files.size() > 0 && changelist.getFiles().size() > 0) { for (FileEntry f : changelist.getFiles()) { if (!doesFilenameMatchAnyP4Pattern(f.getFilename(),files,excludedFilesCaseSensitivity)) { return false; } if (buff == null) { buff = new StringBuffer("Exclude file(s) found:\n"); } buff.append("\t").append(f.getFilename()); } logger.println(buff.toString()); return true; // get here means changelist contains only file(s) to exclude } } return false; } private static boolean doesFilenameMatchAnyP4Pattern(String filename, List<String> patternStrings, boolean caseSensitive){ for(String patternString : patternStrings){ if(patternString.trim().equals("")) continue; if(doesFilenameMatchP4Pattern(filename, patternString, caseSensitive)){ return true; } } return false; } public static boolean doesFilenameMatchP4Pattern(String filename, String patternString, boolean caseSensitive) throws PatternSyntaxException { patternString = patternString.trim(); filename = filename.trim(); patternString = patternString.replaceAll("\\*", "[^/]*"); patternString = patternString.replaceAll("\\.\\.\\.", ".*"); Pattern pattern; if(!caseSensitive){ pattern = Pattern.compile(patternString,Pattern.CASE_INSENSITIVE); } else { pattern = Pattern.compile(patternString); } Matcher matcher = pattern.matcher(filename); if(matcher.matches()){ return true; } else { return false; } } private void flushWorkspaceTo0(Depot depot, Workspace p4workspace, PrintStream log) throws PerforceException { saveWorkspaceIfDirty(depot, p4workspace, log); depot.getWorkspaces().flushTo("//" + p4workspace.getName() + "/...#0"); } // TODO Handle the case where p4Label is set. private boolean wouldSyncChangeWorkspace(AbstractProject project, Depot depot, PrintStream logger) throws IOException, InterruptedException, PerforceException { Workspaces workspaces = depot.getWorkspaces(); String result = workspaces.syncDryRun().toString(); if (result.startsWith("File(s) up-to-date.")) { logger.println("Workspace up-to-date."); return false; } else { logger.println("Workspace not up-to-date."); return true; } } public int getLastChange(Run build) { // If we are starting a new hudson project on existing work and want to skip the prior history... if (firstChange > 0) return firstChange; // If we can't find a PerforceTagAction, we will default to 0. PerforceTagAction action = getMostRecentTagAction(build); if (action == null) return 0; //log.println("Found last change: " + action.getChangeNumber()); return action.getChangeNumber(); } private PerforceTagAction getMostRecentTagAction(Run build) { if (build == null) return null; PerforceTagAction action = build.getAction(PerforceTagAction.class); if (action != null) return action; // if build had no actions, keep going back until we find one that does. return getMostRecentTagAction(build.getPreviousBuild()); } private Workspace getPerforceWorkspace(AbstractProject project, String projectPath, Depot depot, Node buildNode, AbstractBuild build, Launcher launcher, FilePath workspace, TaskListener listener, boolean dontChangeRoot) throws IOException, InterruptedException, PerforceException { PrintStream log = listener.getLogger(); // If we are building on a slave node, and each node is supposed to have // its own unique client, then adjust the client name accordingly. // make sure each slave has a unique client name by adding it's // hostname to the end of the client spec String p4Client; if (build != null) { p4Client = getEffectiveClientName(build); } else { p4Client = getDefaultEffectiveClientName(project, buildNode, workspace); } // If we are running concurrent builds, the Jenkins workspace path is different // for each concurrent build. Append Perforce workspace name with Jenkins // workspace identifier suffix. p4Client = getConcurrentClientName(workspace, p4Client); if (!nodeIsRemote(buildNode)) { log.print("Using master perforce client: "); log.println(p4Client); } else if (dontRenameClient) { log.print("Using shared perforce client: "); log.println(p4Client); } else { log.println("Using remote perforce client: " + p4Client); } depot.setClient(p4Client); String p4Stream = (build == null ? substituteParameters(this.p4Stream, getDefaultSubstitutions(project)) : substituteParameters(this.p4Stream, build)); // Get the clientspec (workspace) from perforce Workspace p4workspace = depot.getWorkspaces().getWorkspace(p4Client, p4Stream); assert p4workspace != null; boolean creatingNewWorkspace = p4workspace.isNew(); // If the client workspace doesn't exist, and we're not managing the clients, // Then terminate the build with an error if(!createWorkspace && creatingNewWorkspace){ log.println("*** Perforce client workspace '" + p4Client +"' doesn't exist."); log.println("*** Please create it, or allow Jenkins to manage clients on it's own."); log.println("*** If the client name mentioned above is not what you expected, "); log.println("*** check your 'Client name format for slaves' advanced config option."); throw new AbortException("Error accessing perforce workspace."); } // Ensure that the clientspec (workspace) name is set correctly // TODO Examine why this would be necessary. p4workspace.setName(p4Client); // Set the workspace options according to the configuration if (projectOptions != null) p4workspace.setOptions(projectOptions); // Set the line ending option according to the configuration if (lineEndValue != null && getAllLineEndChoices().contains(lineEndValue)){ p4workspace.setLineEnd(lineEndValue); } // Ensure that the root is appropriate (it might be wrong if the user // created it, or if we previously built on another node). // Both launcher and workspace can be null if requiresWorkspaceForPolling returns true // So provide 'reasonable' default values. boolean isunix = true; if (launcher!= null) isunix=launcher.isUnix(); String localPath = unescapeP4String(p4workspace.getRoot()); if (workspace!=null) localPath = getLocalPathName(workspace, isunix); else if (localPath.trim().equals("")) localPath = project.getRootDir().getAbsolutePath(); localPath = escapeP4String(localPath); if (!localPath.equals(p4workspace.getRoot()) && !dontChangeRoot && !dontUpdateClient) { log.println("Changing P4 Client Root to: " + localPath); forceSync = true; p4workspace.setRoot(localPath); } if (updateView || creatingNewWorkspace) { // Switch to another stream view if necessary if (useStreamDepot) { p4workspace.setStream(p4Stream); } // If necessary, rewrite the views field in the clientspec. Also, clear the stream. // TODO If dontRenameClient==false, and updateView==false, user // has a lot of work to do to maintain the clientspecs. Seems like // we could copy from a master clientspec to the slaves. else { p4workspace.setStream(""); if (useClientSpec) { projectPath = getEffectiveProjectPathFromFile(build, project, log, depot); } List<String> mappingPairs = parseProjectPath(projectPath, p4Client, log); if (!equalsProjectPath(mappingPairs, p4workspace.getViews())) { log.println("Changing P4 Client View from:\n" + p4workspace.getViewsAsString()); log.println("Changing P4 Client View to: "); p4workspace.clearViews(); for (int i = 0; i < mappingPairs.size(); ) { String depotPath = mappingPairs.get(i++); String clientPath = mappingPairs.get(i++); p4workspace.addView(" " + depotPath + " " + clientPath); log.println(" " + depotPath + " " + clientPath); } } } } // Clean host field so the client can be used on other slaves // such as those operating with the workspace on a network share p4workspace.setHost(""); // NOTE: The workspace is not saved. return p4workspace; } private String getEffectiveClientName(AbstractBuild build) { Node buildNode = build.getBuiltOn(); FilePath workspace = build.getWorkspace(); String p4Client = this.p4Client; p4Client = substituteParameters(p4Client, build); try { p4Client = getEffectiveClientName(p4Client, buildNode); } catch (Exception e){ new StreamTaskListener(System.out).getLogger().println( "Could not get effective client name: " + e.getMessage()); } return p4Client; } private String getDefaultEffectiveClientName(AbstractProject project, Node buildNode, FilePath workspace) throws IOException, InterruptedException { String basename = substituteParameters(this.p4Client, getDefaultSubstitutions(project)); return getEffectiveClientName(basename, buildNode); } private String getEffectiveClientName(String basename, Node buildNode) throws IOException, InterruptedException { String p4Client = basename; if (nodeIsRemote(buildNode) && !getSlaveClientNameFormat().equals("")) { String host=null; Computer c = buildNode.toComputer(); if (c!=null) host = c.getHostName(); if (host==null) { LOGGER.log(Level.WARNING,"Could not get hostname for slave " + buildNode.getDisplayName()); host = "UNKNOWNHOST"; } if (host.contains(".")) { host = String.valueOf(host.subSequence(0, host.indexOf('.'))); } //use hashcode of the nodename to get a unique, slave-specific client name String hash = String.valueOf(buildNode.getNodeName().hashCode()); Map<String, String> substitutions = new Hashtable<String,String>(); substitutions.put("nodename", buildNode.getNodeName()); substitutions.put("hostname", host); substitutions.put("hash", hash); substitutions.put("basename", basename); p4Client = substituteParameters(getSlaveClientNameFormat(), substitutions); } //eliminate spaces, just in case p4Client = p4Client.replaceAll(" ", "_"); return p4Client; } public String getSlaveClientNameFormat() { if(this.slaveClientNameFormat == null || this.slaveClientNameFormat.equals("")){ if(this.dontRenameClient){ slaveClientNameFormat = "${basename}"; } else if(this.useOldClientName) { slaveClientNameFormat = "${basename}-${hostname}"; } else { //Hash should be the new default slaveClientNameFormat = "${basename}-${hash}"; } } return slaveClientNameFormat; } private boolean nodeIsRemote(Node buildNode) { return buildNode != null && buildNode.getNodeName().length() != 0; } private void saveWorkspaceIfDirty(Depot depot, Workspace p4workspace, PrintStream log) throws PerforceException { if (dontUpdateClient) { log.println("'Don't update client' is set. Not saving the client changes."); return; } if (p4workspace.isNew()) { log.println("Saving new client " + p4workspace.getName()); depot.getWorkspaces().saveWorkspace(p4workspace); } else if (p4workspace.isDirty()) { log.println("Saving modified client " + p4workspace.getName()); depot.getWorkspaces().saveWorkspace(p4workspace); } } public static String escapeP4String(String string) { if(string == null) return null; String result = new String(string); result = result.replace("%","%25"); result = result.replace("@","%40"); result = result.replace("#","%23"); result = result.replace("*","%2A"); return result; } public static String unescapeP4String(String string) { if(string == null) return null; String result = new String(string); result = result.replace("%40","@"); result = result.replace("%23","#"); result = result.replace("%2A","*"); result = result.replace("%25","%"); return result; } /** * Append Perforce workspace name with a Jenkins workspace identifier, if this * is a concurrent build job. * * @param workspace Workspace of the current build * @param p4Client User defined client name * @return The new client name. If this is a concurrent build with, append the * client name with a Jenkins workspace identifier. */ private String getConcurrentClientName(FilePath workspace, String p4Client) { if (workspace != null) { //Match @ followed by an integer at the end of the workspace path Pattern p = Pattern.compile(".*@(\\d+)$"); Matcher matcher = p.matcher(workspace.getRemote()); if (matcher.find()) { p4Client += "_" + matcher.group(1); } } return p4Client; } @Extension public static final class PerforceSCMDescriptor extends SCMDescriptor<PerforceSCM> { public PerforceSCMDescriptor() { super(PerforceSCM.class, PerforceRepositoryBrowser.class); load(); } public String getDisplayName() { return "Perforce"; } @Override public SCM newInstance(StaplerRequest req, JSONObject formData) throws FormException { PerforceSCM newInstance = (PerforceSCM)super.newInstance(req, formData); String depotType = req.getParameter("p4.depotType"); boolean useStreamDepot = depotType.equals("stream"); boolean useClientSpec = depotType.equals("file"); newInstance.setUseStreamDepot(useStreamDepot); if (useStreamDepot) { newInstance.setP4Stream(req.getParameter("p4Stream")); } else { newInstance.setUseClientSpec(useClientSpec); if (useClientSpec) { newInstance.setClientSpec(req.getParameter("clientSpec")); } else { newInstance.setProjectPath(req.getParameter("projectPath")); } } newInstance.setUseViewMask(req.getParameter("p4.useViewMask") != null); newInstance.setViewMask(Util.fixEmptyAndTrim(req.getParameter("p4.viewMask"))); newInstance.setUseViewMaskForPolling(req.getParameter("p4.useViewMaskForPolling") != null); newInstance.setUseViewMaskForSyncing(req.getParameter("p4.useViewMaskForSyncing") != null); return newInstance; } /** * List available tool installations. * * @return list of available p4 tool installations */ public List<PerforceToolInstallation> getP4Tools() { PerforceToolInstallation[] p4ToolInstallations = Hudson.getInstance().getDescriptorByType(PerforceToolInstallation.DescriptorImpl.class).getInstallations(); return Arrays.asList(p4ToolInstallations); } public String isValidProjectPath(String path) { if (!path.startsWith("//")) { return "Path must start with '//' (Example: //depot/ProjectName/...)"; } if (!path.endsWith("/...")) { if (!path.contains("@")) { return "Path must end with Perforce wildcard: '/...' (Example: //depot/ProjectName/...)"; } } return null; } protected Depot getDepotFromRequest(StaplerRequest request) { String port = fixNull(request.getParameter("port")).trim(); String tool = fixNull(request.getParameter("tool")).trim(); String user = fixNull(request.getParameter("user")).trim(); String pass = fixNull(request.getParameter("pass")).trim(); if (port.length() == 0 || tool.length() == 0) { // Not enough entered yet return null; } Depot depot = new Depot(); depot.setUser(user); PerforcePasswordEncryptor encryptor = new PerforcePasswordEncryptor(); if (encryptor.appearsToBeAnEncryptedPassword(pass)) { depot.setPassword(encryptor.decryptString(pass)); } else { depot.setPassword(pass); } depot.setPort(port); String exe = ""; PerforceToolInstallation[] installations = ((hudson.plugins.perforce.PerforceToolInstallation.DescriptorImpl)Hudson.getInstance(). getDescriptorByType(PerforceToolInstallation.DescriptorImpl.class)).getInstallations(); for(PerforceToolInstallation i : installations) { if(i.getName().equals(tool)) { exe = i.getP4Exe(); } } depot.setExecutable(exe); try { Counter counter = depot.getCounters().getCounter("change"); if (counter != null) return depot; } catch (PerforceException e) { } return null; } /** * Checks if the perforce login credentials are good. */ public FormValidation doValidatePerforceLogin(StaplerRequest req) { Depot depot = getDepotFromRequest(req); if (depot != null) { try { depot.getStatus().isValid(); } catch (PerforceException e) { return FormValidation.error(e.getMessage()); } } return FormValidation.ok(); } /** * Checks to see if the specified workspace is valid. */ public FormValidation doValidateP4Client(StaplerRequest req) { Depot depot = getDepotFromRequest(req); if (depot == null) { return FormValidation.error( "Unable to check workspace against depot"); } String workspace = Util.fixEmptyAndTrim(req.getParameter("client")); if (workspace == null) { return FormValidation.error("You must enter a workspaces name"); } try { Workspace p4Workspace = depot.getWorkspaces().getWorkspace(workspace, ""); if (p4Workspace.getAccess() == null || p4Workspace.getAccess().equals("")) return FormValidation.warning("Workspace does not exist. " + "If \"Let Hudson/Jenkins Manage Workspace View\" is check" + " the workspace will be automatically created."); } catch (PerforceException e) { return FormValidation.error( "Error accessing perforce while checking workspace"); } return FormValidation.ok(); } /** * Performs syntactical check on the P4Label */ public FormValidation doValidateP4Label(StaplerRequest req, @QueryParameter String label) throws IOException, ServletException { label = Util.fixEmptyAndTrim(label); if (label == null) return FormValidation.ok(); Depot depot = getDepotFromRequest(req); if (depot != null) { try { Label p4Label = depot.getLabels().getLabel(label); if (p4Label.getAccess() == null || p4Label.getAccess().equals("")) return FormValidation.error("Label does not exist"); } catch (PerforceException e) { return FormValidation.error( "Error accessing perforce while checking label"); } } return FormValidation.ok(); } /** * Performs syntactical and permissions check on the P4Counter */ public FormValidation doValidateP4Counter(StaplerRequest req, @QueryParameter String counter) throws IOException, ServletException { counter= Util.fixEmptyAndTrim(counter); if (counter == null) return FormValidation.ok(); Depot depot = getDepotFromRequest(req); if (depot != null) { try { Counters counters = depot.getCounters(); Counter p4Counter = counters.getCounter(counter); // try setting the counter back to the same value to verify permissions counters.saveCounter(p4Counter); } catch (PerforceException e) { return FormValidation.error( "Error accessing perforce while checking counter: " + e.getLocalizedMessage()); } } return FormValidation.ok(); } /** * Checks to see if the specified ClientSpec is valid. */ public FormValidation doValidateClientSpec(StaplerRequest req) throws IOException, ServletException { Depot depot = getDepotFromRequest(req); if (depot == null) { return FormValidation.error( "Unable to check ClientSpec against depot"); } String clientspec = Util.fixEmptyAndTrim(req.getParameter("clientSpec")); if (clientspec == null) { return FormValidation.error("You must enter a path to a ClientSpec file"); } if (!DEPOT_ONLY.matcher(clientspec).matches() && !DEPOT_ONLY_QUOTED.matcher(clientspec).matches()){ return FormValidation.error("Invalid depot path:" + clientspec); } String workspace = Util.fixEmptyAndTrim(req.getParameter("client")); try { if (!depot.getStatus().exists(clientspec)) { return FormValidation.error("ClientSpec does not exist"); } Workspace p4Workspace = depot.getWorkspaces().getWorkspace(workspace, ""); // Warn if workspace exists and is associated with a stream if (p4Workspace.getAccess() != null && !p4Workspace.getAccess().equals("") && p4Workspace.getStream() != null && !p4Workspace.getStream().equals("")) { return FormValidation.warning("Workspace '" + workspace + "' already exists and is associated with a stream. " + "If Jenkins is allowed to manage the workspace view, this workspace will be switched to a local workspace."); } } catch (PerforceException e) { return FormValidation.error( "Error accessing perforce while checking ClientSpec: " + e.getLocalizedMessage()); } return FormValidation.ok(); } /** * Checks if the specified stream is valid. */ public FormValidation doValidateStream(StaplerRequest req) throws IOException, ServletException { Depot depot = getDepotFromRequest(req); if (depot == null) { return FormValidation.error( "Unable to check stream against depot"); } String stream = Util.fixEmptyAndTrim(req.getParameter("stream")); if (stream == null) { return FormValidation.error("You must enter a stream"); } if (!stream.endsWith("/...")) { stream += "/..."; } if (!DEPOT_ONLY.matcher(stream).matches() && !DEPOT_ONLY_QUOTED.matcher(stream).matches()){ return FormValidation.error("Invalid depot path:" + stream); } String workspace = Util.fixEmptyAndTrim(req.getParameter("client")); try { if (!depot.getStatus().exists(stream)) { return FormValidation.error("Stream does not exist"); } Workspace p4Workspace = depot.getWorkspaces().getWorkspace(workspace, ""); // Warn if workspace exists and is not associated with a stream if (p4Workspace.getAccess() != null && !p4Workspace.getAccess().equals("") && (p4Workspace.getStream() == null || p4Workspace.getStream().equals(""))) { return FormValidation.warning("Workspace '" + workspace + "' already exists and is not associated with a stream. " + "If Jenkins is allowed to manage the workspace view, this workspace will be switched to a stream workspace."); } } catch (PerforceException e) { return FormValidation.error( "Error accessing perforce while checking stream: " + e.getLocalizedMessage()); } return FormValidation.ok(); } /** * Checks if the value is a valid Perforce project path. */ public FormValidation doCheckProjectPath(@QueryParameter String value) throws IOException, ServletException { String view = Util.fixEmptyAndTrim(value); if (view != null) { for (String mapping : view.replace("\r","").split("\n")) { if (!DEPOT_ONLY.matcher(mapping).matches() && !DEPOT_AND_WORKSPACE.matcher(mapping).matches() && !DEPOT_ONLY_QUOTED.matcher(mapping).matches() && !DEPOT_AND_WORKSPACE_QUOTED.matcher(mapping).matches() && !DEPOT_AND_QUOTED_WORKSPACE.matcher(mapping).matches() && !COMMENT.matcher(mapping).matches()) return FormValidation.error("Invalid mapping:" + mapping); } } return FormValidation.ok(); } public FormValidation doCheckViewMask(StaplerRequest req) { String view = Util.fixEmptyAndTrim(req.getParameter("viewMask")); if (view != null) { for (String path : view.replace("\r","").split("\n")) { if (path.startsWith("-") || path.startsWith("\"-")) return FormValidation.error("'-' not yet supported in view mask:" + path); if (!DEPOT_ONLY.matcher(path).matches() && !DEPOT_ONLY_QUOTED.matcher(path).matches()) return FormValidation.error("Invalid depot path:" + path); } } return FormValidation.ok(); } /** * Checks if the change list entered exists */ public FormValidation doCheckChangeList(StaplerRequest req) { Depot depot = getDepotFromRequest(req); String change = fixNull(req.getParameter("change")).trim(); if (change.length() == 0) { // nothing entered yet return FormValidation.ok(); } if (depot != null) { try { int number = Integer.parseInt(change); Changelist changelist = depot.getChanges().getChangelist(number, -1); if (changelist.getChangeNumber() != number) throw new PerforceException("broken"); } catch (Exception e) { return FormValidation.error("Changelist: " + change + " does not exist."); } } return FormValidation.ok(); } /** * Checks if the value is a valid user name/regex pattern. */ public FormValidation doValidateExcludedUsers(StaplerRequest req) { String excludedUsers = fixNull(req.getParameter("excludedUsers")).trim(); List<String> users = Arrays.asList(excludedUsers.split("\n")); for (String regex : users) { regex = regex.trim(); if(regex.equals("")) continue; try { regex = regex.replaceAll("\\$\\{[^\\}]*\\}","SOMEVARIABLE"); Pattern.compile(regex); } catch (PatternSyntaxException pse) { return FormValidation.error("Invalid regular express ["+regex+"]: " + pse.getMessage()); } } return FormValidation.ok(); } /** * Checks if the value is a valid file path/regex file pattern. */ public FormValidation doValidateExcludedFiles(StaplerRequest req) { String excludedFiles = fixNull(req.getParameter("excludedFiles")).trim(); Boolean excludedFilesCaseSensitivity = Boolean.valueOf(fixNull(req.getParameter("excludedFilesCaseSensitivity")).trim()); List<String> files = Arrays.asList(excludedFiles.split("\n")); for (String file : files) { // splitting with \n can still leave \r on some OS/browsers // trimming should eliminate it. file = file.trim(); // empty line? lets ignore it. if(file.equals("")) continue; // check to make sure it's a valid file spec if( !DEPOT_ONLY.matcher(file).matches() && !DEPOT_ONLY_QUOTED.matcher(file).matches() ){ return FormValidation.error("Invalid file spec ["+file+"]: Not a perforce file spec."); } // check to make sure the globbing regex will work // (ie, in case there are special characters that the user hasn't escaped properly) try { file = file.replaceAll("\\$\\{[^\\}]*\\}","SOMEVARIABLE"); doesFilenameMatchP4Pattern("somefile", file, excludedFilesCaseSensitivity); } catch (PatternSyntaxException pse) { return FormValidation.error("Invalid file spec ["+file+"]: " + pse.getMessage()); } } return FormValidation.ok(); } public FormValidation doValidateForceSync(StaplerRequest req) { Boolean forceSync = Boolean.valueOf(fixNull(req.getParameter("forceSync")).trim()); Boolean alwaysForceSync = Boolean.valueOf(fixNull(req.getParameter("alwaysForceSync")).trim()); Boolean dontUpdateServer = Boolean.valueOf(fixNull(req.getParameter("dontUpdateServer")).trim()); if((forceSync || alwaysForceSync) && dontUpdateServer){ return FormValidation.error("Don't Update Server Database (-p) option is incompatible with force syncing! Either disable -p, or disable force syncing."); } return FormValidation.ok(); } public List<String> getAllLineEndChoices(){ List<String> allChoices = Arrays.asList( "local", "unix", "mac", "win", "share" ); ArrayList<String> choices = new ArrayList<String>(); //Order choices so that the current one is first in the list //This is required in order for tests to work, unfortunately //choices.add(lineEndValue); for(String choice : allChoices){ //if(!choice.equals(lineEndValue)){ choices.add(choice); //} } return choices; } public String getAppName() { return Hudson.getInstance().getDisplayName(); } } /* Regular expressions for parsing view mappings. */ private static final Pattern COMMENT = Pattern.compile("^\\s*$|^#.*$"); private static final Pattern DEPOT_ONLY = Pattern.compile("^\\s*[+-]?//\\S+?(/\\S+)$"); private static final Pattern DEPOT_ONLY_QUOTED = Pattern.compile("^\\s*\"[+-]?//\\S+?(/[^\"]+)\"$"); private static final Pattern DEPOT_AND_WORKSPACE = Pattern.compile("^\\s*([+-]?//\\S+?/\\S+)\\s+//\\S+?(/\\S+)$"); private static final Pattern DEPOT_AND_WORKSPACE_QUOTED = Pattern.compile("^\\s*\"([+-]?//\\S+?/[^\"]+)\"\\s+\"//\\S+?(/[^\"]+)\"$"); private static final Pattern DEPOT_AND_QUOTED_WORKSPACE = Pattern.compile("^\\s*([+-]?//\\S+?/\\S+)\\s+\"//\\S+?(/[^\"]+)\"$"); /** * Parses the projectPath into a list of pairs of strings representing the depot and client * paths. Even items are depot and odd items are client. * <p> * This parser can handle quoted or non-quoted mappings, normal two-part mappings, or one-part * mappings with an implied right part. It can also deal with +// or -// mapping forms. */ public static List<String> parseProjectPath(String projectPath, String p4Client) { PrintStream log = (new LogTaskListener(LOGGER, Level.WARNING)).getLogger(); return parseProjectPath(projectPath, p4Client, log); } public static List<String> parseProjectPath(String projectPath, String p4Client, PrintStream log) { List<String> parsed = new ArrayList<String>(); for (String line : projectPath.split("\n")) { Matcher depotOnly = DEPOT_ONLY.matcher(line); if (depotOnly.find()) { // add the trimmed depot path, plus a manufactured client path parsed.add(line.trim()); parsed.add("//" + p4Client + depotOnly.group(1)); } else { Matcher depotOnlyQuoted = DEPOT_ONLY_QUOTED.matcher(line); if (depotOnlyQuoted.find()) { // add the trimmed quoted depot path, plus a manufactured quoted client path parsed.add(line.trim()); parsed.add("\"//" + p4Client + depotOnlyQuoted.group(1) + "\""); } else { Matcher depotAndWorkspace = DEPOT_AND_WORKSPACE.matcher(line); if (depotAndWorkspace.find()) { // add the found depot path and the clientname-tweaked client path parsed.add(depotAndWorkspace.group(1)); parsed.add("//" + p4Client + depotAndWorkspace.group(2)); } else { Matcher depotAndWorkspaceQuoted = DEPOT_AND_WORKSPACE_QUOTED.matcher(line); if (depotAndWorkspaceQuoted.find()) { // add the found depot path and the clientname-tweaked client path parsed.add("\"" + depotAndWorkspaceQuoted.group(1) + "\""); parsed.add("\"//" + p4Client + depotAndWorkspaceQuoted.group(2) + "\""); } else { Matcher depotAndQuotedWorkspace = DEPOT_AND_QUOTED_WORKSPACE.matcher(line); if (depotAndQuotedWorkspace.find()) { // add the found depot path and the clientname-tweaked client path parsed.add(depotAndQuotedWorkspace.group(1)); parsed.add("\"//" + p4Client + depotAndQuotedWorkspace.group(2) + "\""); } else { // Assume anything else is a comment and ignore it // Throw a warning anyways. log.println("Warning: Client Spec line invalid, ignoring. ("+line+")"); } } } } } } return parsed; } static String substituteParameters(String string, AbstractBuild build) { Hashtable<String,String> subst = new Hashtable<String,String>(); boolean useEnvironment = true; //get full environment for build from jenkins for(StackTraceElement ste : (new Throwable()).getStackTrace()){ if(ste.getMethodName().equals("buildEnvVars") && ste.getClassName().equals(PerforceSCM.class.getName())){ useEnvironment = false; } } if(useEnvironment){ try { EnvVars vars = build.getEnvironment(TaskListener.NULL); subst.putAll(vars); } catch (IOException ex) { Logger.getLogger(PerforceSCM.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(PerforceSCM.class.getName()).log(Level.SEVERE, null, ex); } } subst.put("JOB_NAME", getSafeJobName(build)); String hudsonName = Hudson.getInstance().getDisplayName().toLowerCase(); subst.put("BUILD_TAG", hudsonName + "-" + build.getProject().getName() + "-" + String.valueOf(build.getNumber())); subst.put("BUILD_ID", build.getId()); subst.put("BUILD_NUMBER", String.valueOf(build.getNumber())); //get global properties for (NodeProperty nodeProperty: Hudson.getInstance().getGlobalNodeProperties()) { if (nodeProperty instanceof EnvironmentVariablesNodeProperty) { subst.putAll( ((EnvironmentVariablesNodeProperty)nodeProperty).getEnvVars() ); } } //get node-specific global properties for(NodeProperty nodeProperty : build.getBuiltOn().getNodeProperties()){ if(nodeProperty instanceof EnvironmentVariablesNodeProperty) { subst.putAll( ((EnvironmentVariablesNodeProperty)nodeProperty).getEnvVars() ); } } String result = substituteParameters(string, subst); result = substituteParameters(result, build.getBuildVariables()); return result; } static String getSafeJobName(AbstractBuild build){ return getSafeJobName(build.getProject()); } static String getSafeJobName(AbstractProject project){ return project.getFullName().replace('/','-').replace('=','-').replace(',','-'); } static String substituteParameters(String string, Map<String,String> subst) { if(string == null) return null; String newString = string; for (Map.Entry<String,String> entry : subst.entrySet()){ newString = newString.replace("${" + entry.getKey() + "}", entry.getValue()); } return newString; } /** * Compares a parsed project path pair list against a list of view * mapping lines from a client spec. */ static boolean equalsProjectPath(List<String> pairs, List<String> lines) { Iterator<String> pi = pairs.iterator(); for (String line : lines) { if (!pi.hasNext()) return false; String p1 = pi.next(); String p2 = pi.next(); // assuming an even number of pair items if (!line.trim().equals(p1.trim() + " " + p2.trim())) return false; } return !pi.hasNext(); // equals iff there are no more pairs } /** * @return the path to the ClientSpec */ public String getClientSpec() { return clientSpec; } /** * @param path the path to the ClientSpec */ public void setClientSpec(String clientSpec) { this.clientSpec = clientSpec; } /** * @return True if we are using a ClientSpec file to setup the workspace view */ public boolean isUseClientSpec() { return useClientSpec; } /** * @param useClientSpec True if a ClientSpec file should be used to setup workspace view, False otherwise */ public void setUseClientSpec(boolean useClientSpec) { this.useClientSpec = useClientSpec; } /** * Check if we are using a stream depot type or a classic depot type. * * @return True if we are using a stream depot type, False otherwise */ public boolean isUseStreamDepot() { return useStreamDepot; } /** * Control the usage of stream depot. * * @param useStreamDepot True if stream depot is used, False otherwise */ public void setUseStreamDepot(boolean useStreamDepot) { this.useStreamDepot = useStreamDepot; } /** * Get the stream name. * * @return the p4Stream */ public String getP4Stream() { return p4Stream; } /** * Set the stream name. * * @param stream the stream name */ public void setP4Stream(String stream) { p4Stream = stream; } /** * @return the projectPath */ public String getProjectPath() { return projectPath; } /** * @param projectPath the projectPath to set */ public void setProjectPath(String projectPath) { // Make it backwards compatible with the old way of specifying a label Matcher m = Pattern.compile("(@\\S+)\\s*").matcher(projectPath); if (m.find()) { p4Label = m.group(1); projectPath = projectPath.substring(0,m.start(1)) + projectPath.substring(m.end(1)); } this.projectPath = projectPath; } /** * @return the p4User */ public String getP4User() { return p4User; } /** * @param user the p4User to set */ public void setP4User(String user) { p4User = user; } /** * @return the p4Passwd */ public String getP4Passwd() { return p4Passwd; } public String getDecryptedP4Passwd() { PerforcePasswordEncryptor encryptor = new PerforcePasswordEncryptor(); return encryptor.decryptString(p4Passwd); } public String getDecryptedP4Passwd(AbstractBuild build) { return substituteParameters(getDecryptedP4Passwd(), build); } public String getDecryptedP4Passwd(AbstractProject project) { return substituteParameters(getDecryptedP4Passwd(), getDefaultSubstitutions(project)); } /** * @param passwd the p4Passwd to set */ public void setP4Passwd(String passwd) { PerforcePasswordEncryptor encryptor = new PerforcePasswordEncryptor(); if (encryptor.appearsToBeAnEncryptedPassword(passwd)) p4Passwd = passwd; else p4Passwd = encryptor.encryptString(passwd); } /** * @return the p4Port */ public String getP4Port() { return p4Port; } /** * @param port the p4Port to set */ public void setP4Port(String port) { p4Port = port; } /** * @return the p4Client */ public String getP4Client() { return p4Client; } /** * @param client the p4Client to set */ public void setP4Client(String client) { p4Client = client; } /** * @return the p4SysDrive */ public String getP4SysDrive() { return p4SysDrive; } /** * @param sysDrive the p4SysDrive to set */ public void setP4SysDrive(String sysDrive) { p4SysDrive = sysDrive; } /** * @return the p4SysRoot */ public String getP4SysRoot() { return p4SysRoot; } /** * @param sysRoot the p4SysRoot to set */ public void setP4SysRoot(String sysRoot) { p4SysRoot = sysRoot; } /** * @deprecated Replaced by {@link #getP4Tool()} */ public String getP4Exe() { return p4Exe; } /** * @deprecated Replaced by {@link #setP4Tool(String)} */ public void setP4Exe(String exe) { p4Exe = exe; } /** * @return the p4Tool */ public String getP4Tool() { return p4Tool; } /** * @param tool the p4 tool installation to set */ public void setP4Tool(String tool) { p4Tool = tool; } /** * @return the p4Label */ public String getP4Label() { return p4Label; } /** * @param label the p4Label to set */ public void setP4Label(String label) { p4Label = label; } /** * @return the p4Counter */ public String getP4Counter() { return p4Counter; } /** * @param counter the p4Counter to set */ public void setP4Counter(String counter) { p4Counter = counter; } /** * @return True if the plugin should update the counter to the last change */ public boolean isUpdateCounterValue() { return updateCounterValue; } /** * @param updateCounterValue True if the plugin should update the counter to the last change */ public void setUpdateCounterValue(boolean updateCounterValue) { this.updateCounterValue = updateCounterValue; } /** * @return True if the P4PASSWD value must be set in the environment */ public boolean isExposeP4Passwd() { return exposeP4Passwd; } /** * @param exposeP4Passwd True if the P4PASSWD value must be set in the environment */ public void setExposeP4Passwd(boolean exposeP4Passwd) { this.exposeP4Passwd = exposeP4Passwd; } /** * The current perforce option set for the view. * @return current perforce view options */ public String getProjectOptions() { return projectOptions; } /** * Set the perforce options for view creation. * @param projectOptions the effective perforce options. */ public void setProjectOptions(String projectOptions) { this.projectOptions = projectOptions; } /** * @param createWorkspace True to let the plugin create the workspace, false to let the user manage it */ public void setCreateWorkspace(boolean val) { this.createWorkspace = Boolean.valueOf(val); } /** * @return True if the plugin manages the view, false if the user does. */ public boolean isCreateWorkspace() { return createWorkspace.booleanValue(); } /** * @param update True to let the plugin manage the view, false to let the user manage it */ public void setUpdateView(boolean update) { this.updateView = update; } /** * @return True if the plugin manages the view, false if the user does. */ public boolean isUpdateView() { return updateView; } /** * @return True if we are performing a one-time force sync */ public boolean isForceSync() { return forceSync; } /** * @return True if we are performing a one-time force sync */ public boolean isAlwaysForceSync() { return alwaysForceSync; } /** * @return True if auto sync is disabled */ public boolean isDisableAutoSync() { return disableAutoSync; } /** * @return True if we are using the old style client names */ public boolean isUseOldClientName() { return this.useOldClientName; } /** * @param force True to perform a one time force sync, false to perform normal sync */ public void setForceSync(boolean force) { this.forceSync = force; } /** * @param force True to perform a one time force sync, false to perform normal sync */ public void setAlwaysForceSync(boolean force) { this.alwaysForceSync = force; } /** * @param disable True to disable the pre-build sync, false to perform pre-build sync */ public void setDisableAutoSync(boolean disable) { this.disableAutoSync = disable; } /** * @param use True to use the old style client names, false to use the new style */ public void setUseOldClientName(boolean use) { this.useOldClientName = use; } /** * @return True if we are using a label */ public boolean isUseLabel() { return p4Label != null; } /** * @param dontRenameClient False if the client will rename the client spec for each * slave */ public void setDontRenameClient(boolean dontRenameClient) { this.dontRenameClient = dontRenameClient; } /** * @return True if the client will rename the client spec for each slave */ public boolean isDontRenameClient() { return dontRenameClient; } /** * @return True if the plugin is to delete the workpsace files before building. */ public boolean isWipeBeforeBuild() { return wipeBeforeBuild; } /** * @return True if the plugin is to delete the workpsace including the.repository files before building. */ public boolean isWipeRepoBeforeBuild() { return wipeRepoBeforeBuild; } /** * @param clientFormat A string defining the format of the client name for slave workspaces. */ public void setSlaveClientNameFormat(String clientFormat){ this.slaveClientNameFormat = clientFormat; } /** * @param wipeBeforeBuild True if the client is to delete the workspace files before building. */ public void setWipeBeforeBuild(boolean wipeBeforeBuild) { this.wipeBeforeBuild = wipeBeforeBuild; } public boolean isDontUpdateClient() { return dontUpdateClient; } public void setDontUpdateClient(boolean dontUpdateClient) { this.dontUpdateClient = dontUpdateClient; } public boolean isUseViewMaskForPolling() { return useViewMaskForPolling; } public void setUseViewMaskForPolling(boolean useViewMaskForPolling) { this.useViewMaskForPolling = useViewMaskForPolling; } public boolean isUseViewMaskForSyncing() { return useViewMaskForSyncing; } public void setUseViewMaskForSyncing(boolean useViewMaskForSyncing) { this.useViewMaskForSyncing = useViewMaskForSyncing; } public String getViewMask() { return viewMask; } public void setViewMask(String viewMask) { this.viewMask = viewMask; } public boolean isUseViewMask() { return useViewMask; } public void setUseViewMask(boolean useViewMask) { this.useViewMask = useViewMask; } public String getP4Charset() { return p4Charset; } public void setP4Charset(String p4Charset) { this.p4Charset = p4Charset; } public String getP4CommandCharset() { return p4CommandCharset; } public void setP4CommandCharset(String p4CommandCharset) { this.p4CommandCharset = p4CommandCharset; } public String getLineEndValue() { return lineEndValue; } public void setLineEndValue(String lineEndValue) { this.lineEndValue = lineEndValue; } public boolean isShowIntegChanges() { return showIntegChanges; } public void setShowIntegChanges(boolean showIntegChanges) { this.showIntegChanges = showIntegChanges; } public boolean isDisableSyncOnly() { return disableSyncOnly; } public void setDisableSyncOnly(boolean disableSyncOnly) { this.disableSyncOnly = disableSyncOnly; } public String getExcludedUsers() { return excludedUsers; } public void setExcludedUsers(String users) { excludedUsers = users; } public String getExcludedFiles() { return excludedFiles; } public void setExcludedFiles(String files) { excludedFiles = files; } public boolean isPollOnlyOnMaster() { return pollOnlyOnMaster; } public void setPollOnlyOnMaster(boolean pollOnlyOnMaster) { this.pollOnlyOnMaster = pollOnlyOnMaster; } public boolean isDontUpdateServer() { return dontUpdateServer; } public void setDontUpdateServer(boolean dontUpdateServer) { this.dontUpdateServer = dontUpdateServer; } public boolean getExcludedFilesCaseSensitivity() { return excludedFilesCaseSensitivity; } public void setExcludedFilesCaseSensitivity(boolean excludedFilesCaseSensitivity) { this.excludedFilesCaseSensitivity = excludedFilesCaseSensitivity; } public List<String> getAllLineEndChoices(){ List<String> allChoices = ((PerforceSCMDescriptor)this.getDescriptor()).getAllLineEndChoices(); ArrayList<String> choices = new ArrayList<String>(); //Order choices so that the current one is first in the list //This is required in order for tests to work, unfortunately choices.add(lineEndValue); for(String choice : allChoices){ if(!choice.equals(lineEndValue)){ choices.add(choice); } } return choices; } /** * This is only for the config screen. Also, it returns a string and not an int. * This is because we want to show an empty value in the config option if it is not being * used. The default value of -1 is not exactly empty. So if we are set to default of * -1, we return an empty string. Anything else and we return the actual change number. * * @return The one time use variable, firstChange. */ public String getFirstChange() { if (firstChange <= 0) return ""; return Integer.valueOf(firstChange).toString(); } /** * This is only for the config screen. Also, it returns a string and not an int. * This is because we want to show an empty value in the config option if it is not being * used. The default value of -1 is not exactly empty. So if we are set to default of * -1, we return an empty string. Anything else and we return the actual change number. * * @return fileLimit */ public String getFileLimit() { if (fileLimit <= 0) return ""; return Integer.valueOf(fileLimit).toString(); } public void setFileLimit(int fileLimit) { this.fileLimit = fileLimit; } /** * With Perforce the server keeps track of files in the workspace. We never * want files deleted without the knowledge of the server so we disable the * cleanup process. * * @param project * The project that owns this {@link SCM}. This is always the same * object for a particular instanceof {@link SCM}. Just passed in here * so that {@link SCM} itself doesn't have to remember the value. * @param workspace * The workspace which is about to be deleted. Never null. This can be * a remote file path. * @param node * The node that hosts the workspace. SCM can use this information to * determine the course of action. * * @return * true if {@link SCM} is OK to let Hudson proceed with deleting the * workspace. * False to veto the workspace deletion. */ @Override public boolean processWorkspaceBeforeDeletion(AbstractProject<?,?> project, FilePath workspace, Node node) { Logger perforceLogger = Logger.getLogger(PerforceSCM.class.getName()); perforceLogger.info( "Workspace '"+workspace.getRemote()+"' is being deleted; flushing workspace to revision 0."); TaskListener loglistener = new LogTaskListener(perforceLogger,Level.INFO); PrintStream log = loglistener.getLogger(); TaskListener listener = new StreamTaskListener(log); Launcher launcher = node.createLauncher(listener); Depot depot = getDepot(launcher, workspace, project, null, node); try { Workspace p4workspace = getPerforceWorkspace( project, substituteParameters(projectPath,getDefaultSubstitutions(project)), depot, node, null, null, workspace, listener, dontRenameClient); flushWorkspaceTo0(depot, p4workspace, log); } catch (Exception ex) { Logger.getLogger(PerforceSCM.class.getName()).log(Level.SEVERE, null, ex); return false; } return true; } @Override public boolean requiresWorkspaceForPolling() { //nodes are allocated and used in the pollChanges() function if available, //so we'll just tell jenkins to provide the master's launcher. return false; } public boolean isSlaveClientNameStatic() { Map<String,String> testSub1 = new Hashtable<String,String>(); testSub1.put("hostname", "HOSTNAME1"); testSub1.put("nodename", "NODENAME1"); testSub1.put("hash", "HASH1"); testSub1.put("basename", this.p4Client); String result1 = substituteParameters(getSlaveClientNameFormat(), testSub1); Map<String,String> testSub2 = new Hashtable<String,String>(); testSub2.put("hostname", "HOSTNAME2"); testSub2.put("nodename", "NODENAME2"); testSub2.put("hash", "HASH2"); testSub2.put("basename", this.p4Client); String result2 = substituteParameters(getSlaveClientNameFormat(), testSub2); return result1.equals(result2); } @Override public boolean supportsPolling() { return true; } }
false
true
public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException { PrintStream log = listener.getLogger(); changelogFilename = changelogFile.getAbsolutePath(); boolean wipeBeforeBuild = overrideWithBooleanParameter( "P4CLEANWORKSPACE", build, this.wipeBeforeBuild); boolean wipeRepoBeforeBuild = overrideWithBooleanParameter( "P4CLEANREPOINWORKSPACE", build, this.wipeRepoBeforeBuild); boolean forceSync = overrideWithBooleanParameter( "P4FORCESYNC", build, this.forceSync); boolean disableAutoSync = overrideWithBooleanParameter( "P4DISABLESYNC", build, this.disableAutoSync); boolean disableSyncOnly = overrideWithBooleanParameter( "P4DISABLESYNCONLY", build, this.disableSyncOnly); //Use local variables so that substitutions are not saved String p4Label = substituteParameters(this.p4Label, build); String viewMask = substituteParameters(this.viewMask, build); Depot depot = getDepot(launcher,workspace, build.getProject(), build, build.getBuiltOn()); String p4Stream = substituteParameters(this.p4Stream, build); //If we're doing a matrix build, we should always force sync. if((Object)build instanceof MatrixBuild || (Object)build instanceof MatrixRun){ if(!alwaysForceSync && !wipeBeforeBuild) log.println("This is a matrix build; It is HIGHLY recommended that you enable the " + "'Always Force Sync' or 'Clean Workspace' options. " + "Failing to do so will likely result in child builds not being synced properly."); } try { //keep projectPath local so any modifications for slaves don't get saved String projectPath; if(useClientSpec){ projectPath = getEffectiveProjectPathFromFile(build, build.getProject(), log, depot); } else { projectPath = substituteParameters(this.projectPath, build); } Workspace p4workspace = getPerforceWorkspace(build.getProject(), projectPath, depot, build.getBuiltOn(), build, launcher, workspace, listener, false); boolean dirtyWorkspace = p4workspace.isDirty(); saveWorkspaceIfDirty(depot, p4workspace, log); if(wipeBeforeBuild){ log.println("Clearing workspace..."); String p4config = substituteParameters("${P4CONFIG}", build); WipeWorkspaceExcludeFilter wipeFilter = new WipeWorkspaceExcludeFilter(".p4config",p4config); if(wipeRepoBeforeBuild){ log.println("Clear workspace includes .repository ..."); } else { log.println("Note: .repository directory in workspace (if exists) is skipped."); wipeFilter.exclude(".repository"); } List<FilePath> workspaceDirs = workspace.list(wipeFilter); for(FilePath dir : workspaceDirs){ dir.deleteRecursive(); } log.println("Cleared workspace."); forceSync = true; } //In case of a stream depot, we want Perforce to handle the client views. So let's re-initialize //the p4workspace object if it was changed since the last build. Also, populate projectPath with //the current view from Perforce. We need it for labeling. if (useStreamDepot) { if (dirtyWorkspace) { //Support for concurrent builds String p4Client = getConcurrentClientName(workspace, getEffectiveClientName(build)); p4workspace = depot.getWorkspaces().getWorkspace(p4Client, p4Stream); } projectPath = p4workspace.getTrimmedViewsAsString(); } //If we're not managing the view, populate the projectPath with the current view from perforce //This is both for convenience, and so the labeling mechanism can operate correctly if(!updateView){ projectPath = p4workspace.getTrimmedViewsAsString(); } //Get the list of changes since the last time we looked... String p4WorkspacePath = "//" + p4workspace.getName() + "/..."; int lastChange = getLastChange((Run)build.getPreviousBuild()); log.println("Last build changeset: " + lastChange); int newestChange = lastChange; if(!disableAutoSync) { List<Changelist> changes; if (p4Label != null && !p4Label.trim().isEmpty()) { newestChange = depot.getChanges().getHighestLabelChangeNumber(p4workspace, p4Label.trim(), p4WorkspacePath); } else { String counterName; if (p4Counter != null && !updateCounterValue) counterName = substituteParameters(this.p4Counter, build); else counterName = "change"; Counter counter = depot.getCounters().getCounter(counterName); newestChange = counter.getValue(); } if(build instanceof MatrixRun) { newestChange = getOrSetMatrixChangeSet(build, depot, newestChange, projectPath, log); } if (lastChange <= 0){ lastChange = newestChange - MAX_CHANGESETS_ON_FIRST_BUILD; if (lastChange < 0){ lastChange = 0; } } if (lastChange >= newestChange) { changes = new ArrayList<Changelist>(0); } else { List<Integer> changeNumbersTo; if(useViewMaskForSyncing && useViewMask){ changeNumbersTo = depot.getChanges().getChangeNumbersInRange(p4workspace, lastChange+1, newestChange, viewMask, showIntegChanges); } else { changeNumbersTo = depot.getChanges().getChangeNumbersInRange(p4workspace, lastChange+1, newestChange, showIntegChanges); } changes = depot.getChanges().getChangelistsFromNumbers(changeNumbersTo, fileLimit); } if (changes.size() > 0) { // Save the changes we discovered. PerforceChangeLogSet.saveToChangeLog( new FileOutputStream(changelogFile), changes); newestChange = changes.get(0).getChangeNumber(); // Get and store information about committers retrieveUserInformation(depot, changes); } else { // No new changes discovered (though the definition of the workspace or label may have changed). createEmptyChangeLog(changelogFile, listener, "changelog"); } if(!disableSyncOnly){ // Now we can actually do the sync process... StringBuilder sbMessage = new StringBuilder("Sync'ing workspace to "); StringBuilder sbSyncPath = new StringBuilder(p4WorkspacePath); StringBuilder sbSyncPathSuffix = new StringBuilder(); sbSyncPathSuffix.append("@"); if (p4Label != null && !p4Label.trim().isEmpty()) { sbMessage.append("label "); sbMessage.append(p4Label); sbSyncPathSuffix.append(p4Label); } else { sbMessage.append("changelist "); sbMessage.append(newestChange); sbSyncPathSuffix.append(newestChange); } sbSyncPath.append(sbSyncPathSuffix); if (forceSync || alwaysForceSync) sbMessage.append(" (forcing sync of unchanged files)."); else sbMessage.append("."); log.println(sbMessage.toString()); String syncPath = sbSyncPath.toString(); long startTime = System.currentTimeMillis(); if(useViewMaskForSyncing && useViewMask){ for(String path : viewMask.replaceAll("\r", "").split("\n")){ StringBuilder sbMaskPath = new StringBuilder(path); sbMaskPath.append(sbSyncPathSuffix); String maskPath = sbMaskPath.toString(); depot.getWorkspaces().syncTo(maskPath, forceSync || alwaysForceSync, dontUpdateServer); } } else { depot.getWorkspaces().syncTo(syncPath, forceSync || alwaysForceSync, dontUpdateServer); } long endTime = System.currentTimeMillis(); long duration = endTime - startTime; log.println("Sync complete, took " + duration + " ms"); } } boolean doSaveProject = false; // reset one time use variables... if(this.forceSync == true || this.firstChange != -1){ this.forceSync = false; this.firstChange = -1; //save the one time use variables... doSaveProject = true; } //If we aren't managing the client views, update the current ones //with those from perforce, and save them if they have changed. if(!this.updateView && !projectPath.equals(this.projectPath)){ this.projectPath = projectPath; doSaveProject = true; } if(doSaveProject){ build.getParent().save(); } // Add tagging action that enables the user to create a label // for this build. build.addAction(new PerforceTagAction( build, depot, newestChange, projectPath, p4User)); build.addAction(new PerforceSCMRevisionState(newestChange)); if (p4Counter != null && updateCounterValue) { // Set or create a counter to mark this change Counter counter = new Counter(); counter.setName(p4Counter); counter.setValue(newestChange); log.println("Updating counter " + p4Counter + " to " + newestChange); depot.getCounters().saveCounter(counter); } // remember the p4Ticket if we were issued one p4Ticket = depot.getP4Ticket(); return true; } catch (PerforceException e) { log.print("Caught exception communicating with perforce. " + e.getMessage()); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); e.printStackTrace(pw); pw.flush(); log.print(sw.toString()); throw new AbortException( "Unable to communicate with perforce. " + e.getMessage()); } catch (InterruptedException e) { throw new IOException( "Unable to get hostname from slave. " + e.getMessage()); } }
public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException { PrintStream log = listener.getLogger(); changelogFilename = changelogFile.getAbsolutePath(); boolean wipeBeforeBuild = overrideWithBooleanParameter( "P4CLEANWORKSPACE", build, this.wipeBeforeBuild); boolean wipeRepoBeforeBuild = overrideWithBooleanParameter( "P4CLEANREPOINWORKSPACE", build, this.wipeRepoBeforeBuild); boolean forceSync = overrideWithBooleanParameter( "P4FORCESYNC", build, this.forceSync); boolean disableAutoSync = overrideWithBooleanParameter( "P4DISABLESYNC", build, this.disableAutoSync); boolean disableSyncOnly = overrideWithBooleanParameter( "P4DISABLESYNCONLY", build, this.disableSyncOnly); //Use local variables so that substitutions are not saved String p4Label = substituteParameters(this.p4Label, build); String viewMask = substituteParameters(this.viewMask, build); Depot depot = getDepot(launcher,workspace, build.getProject(), build, build.getBuiltOn()); String p4Stream = substituteParameters(this.p4Stream, build); //If we're doing a matrix build, we should always force sync. if((Object)build instanceof MatrixBuild || (Object)build instanceof MatrixRun){ if(!alwaysForceSync && !wipeBeforeBuild) log.println("This is a matrix build; It is HIGHLY recommended that you enable the " + "'Always Force Sync' or 'Clean Workspace' options. " + "Failing to do so will likely result in child builds not being synced properly."); } try { //keep projectPath local so any modifications for slaves don't get saved String projectPath; if(useClientSpec){ projectPath = getEffectiveProjectPathFromFile(build, build.getProject(), log, depot); } else { projectPath = substituteParameters(this.projectPath, build); } Workspace p4workspace = getPerforceWorkspace(build.getProject(), projectPath, depot, build.getBuiltOn(), build, launcher, workspace, listener, false); boolean dirtyWorkspace = p4workspace.isDirty(); saveWorkspaceIfDirty(depot, p4workspace, log); if(wipeBeforeBuild){ log.println("Clearing workspace..."); String p4config = substituteParameters("${P4CONFIG}", build); WipeWorkspaceExcludeFilter wipeFilter = new WipeWorkspaceExcludeFilter(".p4config",p4config); if(wipeRepoBeforeBuild){ log.println("Clear workspace includes .repository ..."); } else { log.println("Note: .repository directory in workspace (if exists) is skipped."); wipeFilter.exclude(".repository"); } List<FilePath> workspaceDirs = workspace.list(wipeFilter); for(FilePath dir : workspaceDirs){ dir.deleteRecursive(); } log.println("Cleared workspace."); forceSync = true; } //In case of a stream depot, we want Perforce to handle the client views. So let's re-initialize //the p4workspace object if it was changed since the last build. Also, populate projectPath with //the current view from Perforce. We need it for labeling. if (useStreamDepot) { if (dirtyWorkspace) { //Support for concurrent builds String p4Client = getConcurrentClientName(workspace, getEffectiveClientName(build)); p4workspace = depot.getWorkspaces().getWorkspace(p4Client, p4Stream); } projectPath = p4workspace.getTrimmedViewsAsString(); } //If we're not managing the view, populate the projectPath with the current view from perforce //This is both for convenience, and so the labeling mechanism can operate correctly if(!updateView){ projectPath = p4workspace.getTrimmedViewsAsString(); } //Get the list of changes since the last time we looked... String p4WorkspacePath = "//" + p4workspace.getName() + "/..."; int lastChange = getLastChange((Run)build.getPreviousBuild()); log.println("Last build changeset: " + lastChange); int newestChange = lastChange; if(!disableAutoSync) { List<Changelist> changes; if (p4Label != null && !p4Label.trim().isEmpty()) { newestChange = depot.getChanges().getHighestLabelChangeNumber(p4workspace, p4Label.trim(), p4WorkspacePath); } else { String counterName; if (p4Counter != null && !updateCounterValue) counterName = substituteParameters(this.p4Counter, build); else counterName = "change"; Counter counter = depot.getCounters().getCounter(counterName); newestChange = counter.getValue(); } if(build instanceof MatrixRun) { newestChange = getOrSetMatrixChangeSet(build, depot, newestChange, projectPath, log); } if (lastChange <= 0){ lastChange = newestChange - MAX_CHANGESETS_ON_FIRST_BUILD; if (lastChange < 0){ lastChange = 0; } } if (lastChange >= newestChange) { changes = new ArrayList<Changelist>(0); } else { List<Integer> changeNumbersTo; if(useViewMaskForSyncing && useViewMask){ changeNumbersTo = depot.getChanges().getChangeNumbersInRange(p4workspace, lastChange+1, newestChange, viewMask, showIntegChanges); } else { changeNumbersTo = depot.getChanges().getChangeNumbersInRange(p4workspace, lastChange+1, newestChange, showIntegChanges); } changes = depot.getChanges().getChangelistsFromNumbers(changeNumbersTo, fileLimit); } if (changes.size() > 0) { // Save the changes we discovered. PerforceChangeLogSet.saveToChangeLog( new FileOutputStream(changelogFile), changes); newestChange = changes.get(0).getChangeNumber(); // Get and store information about committers retrieveUserInformation(depot, changes); } else { // No new changes discovered (though the definition of the workspace or label may have changed). createEmptyChangeLog(changelogFile, listener, "changelog"); } if(!disableSyncOnly){ // Now we can actually do the sync process... StringBuilder sbMessage = new StringBuilder("Sync'ing workspace to "); StringBuilder sbSyncPath = new StringBuilder(p4WorkspacePath); StringBuilder sbSyncPathSuffix = new StringBuilder(); sbSyncPathSuffix.append("@"); if (p4Label != null && !p4Label.trim().isEmpty()) { sbMessage.append("label "); sbMessage.append(p4Label); sbSyncPathSuffix.append(p4Label); } else { sbMessage.append("changelist "); sbMessage.append(newestChange); sbSyncPathSuffix.append(newestChange); } sbSyncPath.append(sbSyncPathSuffix); if (forceSync || alwaysForceSync) sbMessage.append(" (forcing sync of unchanged files)."); else sbMessage.append("."); log.println(sbMessage.toString()); String syncPath = sbSyncPath.toString(); long startTime = System.currentTimeMillis(); if(useViewMaskForSyncing && useViewMask){ for(String path : viewMask.replaceAll("\r", "").split("\n")){ StringBuilder sbMaskPath = new StringBuilder(path); sbMaskPath.append(sbSyncPathSuffix); String maskPath = sbMaskPath.toString(); depot.getWorkspaces().syncTo(maskPath, forceSync || alwaysForceSync, dontUpdateServer); } } else { depot.getWorkspaces().syncTo(syncPath, forceSync || alwaysForceSync, dontUpdateServer); } long endTime = System.currentTimeMillis(); long duration = endTime - startTime; log.println("Sync complete, took " + duration + " ms"); } } boolean doSaveProject = false; // reset one time use variables... if(this.forceSync == true || this.firstChange != -1){ this.forceSync = false; this.firstChange = -1; //save the one time use variables... doSaveProject = true; } //If we aren't managing the client views, update the current ones //with those from perforce, and save them if they have changed. if(!this.updateView && !projectPath.equals(this.projectPath)){ this.projectPath = projectPath; doSaveProject = true; } if(doSaveProject){ build.getParent().save(); } // Add tagging action that enables the user to create a label // for this build. build.addAction(new PerforceTagAction( build, depot, newestChange, projectPath, p4User)); build.addAction(new PerforceSCMRevisionState(newestChange)); if (p4Counter != null && updateCounterValue) { // Set or create a counter to mark this change Counter counter = new Counter(); String counterName = substituteParameters(this.p4Counter, build); counter.setName(counterName); counter.setValue(newestChange); log.println("Updating counter " + counterName + " to " + newestChange); depot.getCounters().saveCounter(counter); } // remember the p4Ticket if we were issued one p4Ticket = depot.getP4Ticket(); return true; } catch (PerforceException e) { log.print("Caught exception communicating with perforce. " + e.getMessage()); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); e.printStackTrace(pw); pw.flush(); log.print(sw.toString()); throw new AbortException( "Unable to communicate with perforce. " + e.getMessage()); } catch (InterruptedException e) { throw new IOException( "Unable to get hostname from slave. " + e.getMessage()); } }
diff --git a/modules/plugin/arcsde/datastore/src/test/java/org/geotools/arcsde/data/ArcSDEJavaApiTest.java b/modules/plugin/arcsde/datastore/src/test/java/org/geotools/arcsde/data/ArcSDEJavaApiTest.java index af25f198f..b17b6a29a 100644 --- a/modules/plugin/arcsde/datastore/src/test/java/org/geotools/arcsde/data/ArcSDEJavaApiTest.java +++ b/modules/plugin/arcsde/datastore/src/test/java/org/geotools/arcsde/data/ArcSDEJavaApiTest.java @@ -1,1271 +1,1271 @@ /* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2002-2008, Open Source Geospatial Foundation (OSGeo) * * This library 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; * version 2.1 of the License. * * This library 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. * */ package org.geotools.arcsde.data; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.geotools.arcsde.ArcSdeException; import org.geotools.arcsde.pool.Command; import org.geotools.arcsde.pool.ISession; import org.geotools.arcsde.pool.SessionPool; import org.geotools.arcsde.pool.UnavailableArcSDEConnectionException; import org.geotools.data.DataSourceException; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.esri.sde.sdk.client.SDEPoint; import com.esri.sde.sdk.client.SeColumnDefinition; import com.esri.sde.sdk.client.SeConnection; import com.esri.sde.sdk.client.SeCoordinateReference; import com.esri.sde.sdk.client.SeDelete; import com.esri.sde.sdk.client.SeException; import com.esri.sde.sdk.client.SeExtent; import com.esri.sde.sdk.client.SeFilter; import com.esri.sde.sdk.client.SeInsert; import com.esri.sde.sdk.client.SeLayer; import com.esri.sde.sdk.client.SeObjectId; import com.esri.sde.sdk.client.SeQuery; import com.esri.sde.sdk.client.SeQueryInfo; import com.esri.sde.sdk.client.SeRow; import com.esri.sde.sdk.client.SeShape; import com.esri.sde.sdk.client.SeShapeFilter; import com.esri.sde.sdk.client.SeSqlConstruct; import com.esri.sde.sdk.client.SeState; import com.esri.sde.sdk.client.SeTable; import com.esri.sde.sdk.client.SeVersion; /** * Exercises the ArcSDE Java API to ensure our assumptions are correct. * <p> * Some of this tests asserts the information from the documentation found on <a * href="http://arcsdeonline.esri.com">arcsdeonline </a>, and others are needed to validate our * assumptions in the API behavior due to the very little documentation ESRI provides about the less * obvious things. * </p> * * @author Gabriel Roldan, Axios Engineering * @source $URL: * http://svn.geotools.org/geotools/trunk/gt/modules/plugin/arcsde/datastore/src/test/java * /org/geotools/arcsde/data/ArcSDEJavaApiTest.java $ * @version $Id$ */ public class ArcSDEJavaApiTest { /** package logger */ private static Logger LOGGER = org.geotools.util.logging.Logging .getLogger(ArcSDEJavaApiTest.class.getPackage().getName()); /** utility to load test parameters and build a datastore with them */ private static TestData testData; private ISession session; private SessionPool pool; @BeforeClass public static void oneTimeSetUp() throws Exception { testData = new TestData(); testData.setUp(); final boolean insertTestData = true; testData.createTempTable(insertTestData); } @AfterClass public static void oneTimeTearDown() { boolean cleanTestTable = true; boolean cleanPool = true; testData.tearDown(cleanTestTable, cleanPool); } /** * loads {@code test-data/testparams.properties} into a Properties object, wich is used to * obtain test tables names and is used as parameter to find the DataStore * * @throws Exception * DOCUMENT ME! */ @Before public void setUp() throws Exception { // facilitates running a single test at a time (eclipse lets you do this // and it's very useful) if (testData == null) { oneTimeSetUp(); } this.pool = testData.getConnectionPool(); this.session = this.pool.getSession(); } /** * DOCUMENT ME! * * @throws Exception * DOCUMENT ME! */ @After public void tearDown() throws Exception { if (session != null) { try { session.dispose(); } catch (Exception e) { e.printStackTrace(); } } session = null; pool = null; } @Test public void testNullSQLConstruct() throws Exception { String[] columns = { TestData.TEST_TABLE_COLS[0] }; SeSqlConstruct sql = null; try { session.createAndExecuteQuery(columns, sql); fail("A null SeSqlConstruct should have thrown an exception!"); } catch (IOException e) { assertTrue(true); } } @Test public void testEmptySQLConstruct() throws Exception { String typeName = testData.getTempTableName(); String[] columns = { TestData.TEST_TABLE_COLS[0] }; SeSqlConstruct sql = new SeSqlConstruct(typeName); SeQuery rowQuery = null; try { rowQuery = session.createAndExecuteQuery(columns, sql); } finally { if (rowQuery != null) { session.close(rowQuery); } } } /** * DOCUMENT ME! * * @throws Exception * DOCUMENT ME! */ @Test public void testGetBoundsWhileFetchingRows() throws Exception { final String typeName = testData.getTempTableName(); final String[] columns = { TestData.TEST_TABLE_COLS[0] }; final SeSqlConstruct sql = new SeSqlConstruct(typeName); final SeQueryInfo qInfo = new SeQueryInfo(); qInfo.setConstruct(sql); // add a bounding box filter and verify both spatial and non spatial // constraints affects the COUNT statistics SeExtent extent = new SeExtent(-180, -90, -170, -80); SeLayer layer = session.getLayer(typeName); SeShape filterShape = new SeShape(layer.getCoordRef()); filterShape.generateRectangle(extent); SeShapeFilter bboxFilter = new SeShapeFilter(typeName, layer.getSpatialColumn(), filterShape, SeFilter.METHOD_ENVP, true); final SeFilter[] spatFilters = { bboxFilter }; final Command<Integer> countCmd = new Command<Integer>() { @Override public Integer execute(ISession session, SeConnection connection) throws SeException, IOException { final SeQuery rowQuery = new SeQuery(connection, columns, sql); rowQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE, false, spatFilters); rowQuery.prepareQuery(); rowQuery.execute(); // fetch some rows rowQuery.fetch(); rowQuery.fetch(); rowQuery.fetch(); SeQuery countQuery = new SeQuery(connection, columns, sql); countQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE, true, spatFilters); SeTable.SeTableStats tableStats = countQuery.calculateTableStatistics("POP_ADMIN", SeTable.SeTableStats.SE_COUNT_STATS, qInfo, 0); rowQuery.fetch(); rowQuery.fetch(); int resultCount = tableStats.getCount(); rowQuery.close(); countQuery.close(); return new Integer(resultCount); } }; final Integer resultCount = session.issue(countCmd); final int expCount = 2; assertEquals(expCount, resultCount.intValue()); } /** * @param session * the session to use in obtaining the query result count * @param tableName * the name of the table to query * @param whereClause * where clause, may be null * @param spatFilters * spatial filters, may be null * @param the * state identifier to query over a versioned table, may be {@code null} * @return the sde calculated counts for the given filter * @throws IOException * @throws Exception */ private static int getTempTableCount(final ISession session, final String tableName, final String whereClause, final SeFilter[] spatFilters, final SeState state) throws IOException { final Command<Integer> countCmd = new Command<Integer>() { @Override public Integer execute(ISession session, SeConnection connection) throws SeException, IOException { String[] columns = { "*" }; SeSqlConstruct sql = new SeSqlConstruct(tableName); if (whereClause != null) { sql.setWhere(whereClause); } SeQuery query = new SeQuery(connection, columns, sql); if (state != null) { SeObjectId differencesId = new SeObjectId(SeState.SE_NULL_STATE_ID); query.setState(state.getId(), differencesId, SeState.SE_STATE_DIFF_NOCHECK); } SeQueryInfo qInfo = new SeQueryInfo(); qInfo.setConstruct(sql); if (spatFilters != null) { query.setSpatialConstraints(SeQuery.SE_OPTIMIZE, true, spatFilters); } SeTable.SeTableStats tableStats = query.calculateTableStatistics("INT32_COL", SeTable.SeTableStats.SE_COUNT_STATS, qInfo, 0); int actualCount = tableStats.getCount(); query.close(); return new Integer(actualCount); } }; final Integer count = session.issue(countCmd); return count.intValue(); } /** * DOCUMENT ME! * * @throws Exception * DOCUMENT ME! */ @Test public void testCalculateCount() throws Exception { try { String typeName = testData.getTempTableName(); String where = "INT32_COL < 5"; int expCount = 4; int actualCount; actualCount = getTempTableCount(session, typeName, where, null, null); assertEquals(expCount, actualCount); // add a bounding box filter and verify both spatial and non spatial // constraints affects the COUNT statistics SeExtent extent = new SeExtent(-180, -90, -170, -80); SeLayer layer = session.getLayer(typeName); SeShape filterShape = new SeShape(layer.getCoordRef()); filterShape.generateRectangle(extent); SeShapeFilter bboxFilter = new SeShapeFilter(typeName, layer.getSpatialColumn(), filterShape, SeFilter.METHOD_ENVP, true); SeFilter[] spatFilters = { bboxFilter }; expCount = 1; actualCount = getTempTableCount(session, typeName, where, spatFilters, null); assertEquals(expCount, actualCount); } catch (IOException e) { e.printStackTrace(); throw e; } } @Test public void testCalculateBoundsSqlFilter() throws Exception { String typeName = testData.getTempTableName(); String where = "INT32_COL = 1"; String[] cols = { "SHAPE" }; SeSqlConstruct sqlCons = new SeSqlConstruct(typeName); sqlCons.setWhere(where); final SeQueryInfo seQueryInfo = new SeQueryInfo(); seQueryInfo.setColumns(cols); seQueryInfo.setConstruct(sqlCons); SeExtent extent = session.issue(new Command<SeExtent>() { @Override public SeExtent execute(ISession session, SeConnection connection) throws SeException, IOException { SeQuery spatialQuery = new SeQuery(connection); // spatialQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE, // false, filters); SeExtent extent = spatialQuery.calculateLayerExtent(seQueryInfo); return extent; } }); double minX = Math.round(extent.getMinX()); double minY = Math.round(extent.getMinY()); double maxX = Math.round(extent.getMaxX()); double maxY = Math.round(extent.getMaxY()); assertEquals(0D, minX, 1E-9); assertEquals(0D, minY, 1E-9); assertEquals(0D, maxX, 1E-9); assertEquals(0D, maxY, 1E-9); } @Test public void testCalculateBoundsSpatialFilter() throws Exception { final String typeName = testData.getTempTableName(); // String where = null; String[] cols = { "SHAPE" }; final SeFilter[] spatFilters; try { SeExtent extent = new SeExtent(179, -1, 180, 0); SeLayer layer = session.getLayer(typeName); SeShape filterShape = new SeShape(layer.getCoordRef()); filterShape.generateRectangle(extent); SeShapeFilter bboxFilter = new SeShapeFilter(typeName, layer.getSpatialColumn(), filterShape, SeFilter.METHOD_ENVP, true); spatFilters = new SeFilter[] { bboxFilter }; } catch (SeException eek) { throw new ArcSdeException(eek); } SeSqlConstruct sqlCons = new SeSqlConstruct(typeName); // sqlCons.setWhere(where); final SeQueryInfo seQueryInfo = new SeQueryInfo(); seQueryInfo.setColumns(cols); seQueryInfo.setConstruct(sqlCons); SeExtent extent = session.issue(new Command<SeExtent>() { @Override public SeExtent execute(ISession session, SeConnection connection) throws SeException, IOException { SeQuery spatialQuery = new SeQuery(connection); spatialQuery.setSpatialConstraints(SeQuery.SE_SPATIAL_FIRST, false, spatFilters); SeExtent extent = spatialQuery.calculateLayerExtent(seQueryInfo); return extent; } }); // just checking the extent were returned, which is something as I get // lots of // exceptions with trial and error approaches. checking the coordinate // results seems // hard as the test data or layer or crs is screwing things up and // getting somehing like // 9.223E18. I guess the may be a problem with the test layer accepting // any type of // geometry or the CRS definition used in TestData, not sure assertNotNull(extent); } @Test public void testCalculateBoundsMixedFilter() throws Exception { final String typeName = testData.getTempTableName(); // try { String where = "INT32_COL < 5"; String[] cols = { "SHAPE" }; final SeFilter[] spatFilters; try { SeExtent extent = new SeExtent(179, -1, 180, 0); SeLayer layer = session.getLayer(typeName); SeShape filterShape = new SeShape(layer.getCoordRef()); filterShape.generateRectangle(extent); SeShapeFilter bboxFilter = new SeShapeFilter(typeName, layer.getSpatialColumn(), filterShape, SeFilter.METHOD_ENVP, true); spatFilters = new SeFilter[] { bboxFilter }; } catch (SeException eek) { throw new ArcSdeException(eek); } SeSqlConstruct sqlCons = new SeSqlConstruct(typeName); sqlCons.setWhere(where); final SeQueryInfo seQueryInfo = new SeQueryInfo(); seQueryInfo.setColumns(cols); seQueryInfo.setConstruct(sqlCons); SeExtent extent = session.issue(new Command<SeExtent>() { @Override public SeExtent execute(ISession session, SeConnection connection) throws SeException, IOException { SeQuery spatialQuery = new SeQuery(connection); spatialQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE, false, spatFilters); SeExtent extent = spatialQuery.calculateLayerExtent(seQueryInfo); return extent; } }); assertNotNull(extent); double minX = Math.round(extent.getMinX()); double minY = Math.round(extent.getMinY()); double maxX = Math.round(extent.getMaxX()); double maxY = Math.round(extent.getMaxY()); assertEquals(-170D, minX, 1E-9); assertEquals(-80D, minY, 1E-9); assertEquals(170D, maxX, 1E-9); assertEquals(80D, maxY, 1E-9); // } catch (SeException e) { // LOGGER.warning(e.getSeError().getErrDesc()); // new ArcSdeException(e).printStackTrace(); // throw e; // } } /** * Ensures a point SeShape behaves as expected. * * @throws SeException * if it is thrown while constructing the SeShape */ @Test public void testPointFormat() throws SeException { int numPts = 1; SDEPoint[] ptArray = new SDEPoint[numPts]; ptArray[0] = new SDEPoint(3000, 100); SeShape point = new SeShape(); point.generatePoint(numPts, ptArray); int numParts = 0; double[][][] coords = point.getAllCoords(); assertEquals("Num of parts invalid", numPts, coords.length); for (; numParts < numPts; numParts++) { assertEquals("Num subparts invalid", 1, coords[numParts].length); } for (; numParts < numPts; numParts++) { int numSubParts = 0; for (; numSubParts < coords[numParts].length; numParts++) { assertEquals("Num of points invalid", 2, coords[numParts][numSubParts].length); } } } /** * Ensures a multipoint SeShape behaves as expected. * * @throws SeException * if it is thrown while constructing the SeShape */ @Test public void testMultiPointFormat() throws SeException { int numPts = 4; SDEPoint[] ptArray = new SDEPoint[numPts]; ptArray[0] = new SDEPoint(3000, 100); ptArray[1] = new SDEPoint(3000, 300); ptArray[2] = new SDEPoint(4000, 300); ptArray[3] = new SDEPoint(4000, 100); SeShape point = new SeShape(); point.generatePoint(numPts, ptArray); double[][][] coords = point.getAllCoords(); assertEquals("Num of parts invalid", numPts, coords.length); int numParts = 0; for (; numParts < numPts; numParts++) { assertEquals("Num subparts invalid", 1, coords[numParts].length); } for (; numParts < numPts; numParts++) { int numSubParts = 0; for (; numSubParts < coords[numParts].length; numParts++) { assertEquals("Num of points invalid", 2, coords[numParts][numSubParts].length); } } } /** * Ensures a linestring SeShape behaves as expected. * * @throws SeException * if it is thrown while constructing the SeShape */ @Test public void testLineStringFormat() throws SeException { int numPts = 4; SDEPoint[] ptArray = new SDEPoint[numPts]; ptArray[0] = new SDEPoint(3000, 100); ptArray[1] = new SDEPoint(3000, 300); ptArray[2] = new SDEPoint(4000, 300); ptArray[3] = new SDEPoint(4000, 100); SeShape point = new SeShape(); int numParts = 1; int[] partOffsets = { 0 }; // index of each part's start in the gobal // coordinate array point.generateLine(numPts, numParts, partOffsets, ptArray); double[][][] coords = point.getAllCoords(); assertEquals("Num of parts invalid", 1, coords.length); assertEquals("Num subparts invalid", 1, coords[0].length); assertEquals("Num of points invalid", 2 * numPts, coords[0][0].length); } /** * Ensures a multilinestring SeShape behaves as expected. * * @throws SeException * if it is thrown while constructing the SeShape */ @Test public void testMultiLineStringFormat() throws SeException { int numPts = 4; SDEPoint[] ptArray = new SDEPoint[numPts]; ptArray[0] = new SDEPoint(3000, 100); ptArray[1] = new SDEPoint(3000, 300); ptArray[2] = new SDEPoint(4000, 300); ptArray[3] = new SDEPoint(4000, 100); SeShape point = new SeShape(); int numParts = 2; int[] partOffsets = { 0, 2 }; // index of each part's start in the // gobal coordinate array point.generateLine(numPts, numParts, partOffsets, ptArray); double[][][] coords = point.getAllCoords(); assertEquals("Num of parts invalid", numParts, coords.length); assertEquals("Num subparts invalid", 1, coords[0].length); assertEquals("Num subparts invalid", 1, coords[1].length); assertEquals("Num of points invalid", numPts, coords[0][0].length); assertEquals("Num of points invalid", numPts, coords[1][0].length); } /** * Ensures a polygon SeShape behaves as expected, building a simple polygon and a polygon with a * hole. * * @throws SeException * if it is thrown while constructing the SeShape */ @Test public void testPolygonFormat() throws SeException { /* * Generate an area shape composed of two polygons, the first with a hole */ int numPts = 4; int numParts = 1; int[] partOffsets = new int[numParts]; partOffsets[0] = 0; SDEPoint[] ptArray = new SDEPoint[numPts]; // simple polygon ptArray[0] = new SDEPoint(1600, 1200); ptArray[1] = new SDEPoint(2800, 1650); ptArray[2] = new SDEPoint(1800, 2000); ptArray[3] = new SDEPoint(1600, 1200); SeShape polygon = new SeShape(); polygon.generatePolygon(numPts, numParts, partOffsets, ptArray); double[][][] coords = polygon.getAllCoords(); assertEquals("Num of parts invalid", numParts, coords.length); assertEquals("Num subparts invalid", 1, coords[0].length); assertEquals("Num of points invalid", 2 * 4, coords[0][0].length); numPts = 14; numParts = 1; ptArray = new SDEPoint[numPts]; partOffsets = new int[numParts]; partOffsets[0] = 0; // part one ptArray[0] = new SDEPoint(100, 1100); ptArray[1] = new SDEPoint(1500, 1100); ptArray[2] = new SDEPoint(1500, 1900); ptArray[3] = new SDEPoint(100, 1900); ptArray[4] = new SDEPoint(100, 1100); // Hole - sub part of part one ptArray[5] = new SDEPoint(200, 1200); ptArray[6] = new SDEPoint(200, 1500); ptArray[7] = new SDEPoint(500, 1500); ptArray[8] = new SDEPoint(500, 1700); ptArray[9] = new SDEPoint(800, 1700); ptArray[10] = new SDEPoint(800, 1500); ptArray[11] = new SDEPoint(500, 1500); ptArray[12] = new SDEPoint(500, 1200); ptArray[13] = new SDEPoint(200, 1200); polygon = new SeShape(); polygon.generatePolygon(numPts, numParts, partOffsets, ptArray); coords = polygon.getAllCoords(); assertEquals("Num of parts invalid", numParts, coords.length); assertEquals("Num subparts invalid", 2, coords[0].length); // first part of first polygon (shell) has 5 points assertEquals("Num of points invalid", 2 * 5, coords[0][0].length); // second part of first polygon (hole) has 9 points assertEquals("Num of points invalid", 2 * 9, coords[0][1].length); } /** * Ensures a multipolygon SeShape behaves as expected. * * @throws SeException * if it is thrown while constructing the SeShape */ @Test public void testMultiPolygonFormat() throws SeException { /* * Generate an area shape composed of two polygons, the first with a hole */ int numPts = 18; int numParts = 2; int[] partOffsets = new int[numParts]; partOffsets[0] = 0; partOffsets[1] = 14; SDEPoint[] ptArray = new SDEPoint[numPts]; // part one ptArray[0] = new SDEPoint(100, 1100); ptArray[1] = new SDEPoint(1500, 1100); ptArray[2] = new SDEPoint(1500, 1900); ptArray[3] = new SDEPoint(100, 1900); ptArray[4] = new SDEPoint(100, 1100); // Hole - sub part of part one ptArray[5] = new SDEPoint(200, 1200); ptArray[6] = new SDEPoint(200, 1500); ptArray[7] = new SDEPoint(500, 1500); ptArray[8] = new SDEPoint(500, 1700); ptArray[9] = new SDEPoint(800, 1700); ptArray[10] = new SDEPoint(800, 1500); ptArray[11] = new SDEPoint(500, 1500); ptArray[12] = new SDEPoint(500, 1200); ptArray[13] = new SDEPoint(200, 1200); // part two ptArray[14] = new SDEPoint(1600, 1200); ptArray[15] = new SDEPoint(2800, 1650); ptArray[16] = new SDEPoint(1800, 2000); ptArray[17] = new SDEPoint(1600, 1200); SeShape multipolygon = new SeShape(); multipolygon.generatePolygon(numPts, numParts, partOffsets, ptArray); double[][][] coords = multipolygon.getAllCoords(); assertEquals("Num of parts invalid", numParts, coords.length); // the first polygon has 2 parts assertEquals("Num subparts invalid", 2, coords[0].length); // the second polygon has only 1 part assertEquals("Num subparts invalid", 1, coords[1].length); // first part of first polygon (shell) has 5 points assertEquals("Num of points invalid", 2 * 5, coords[0][0].length); // second part of first polygon (hole) has 9 points assertEquals("Num of points invalid", 2 * 9, coords[0][1].length); // second polygon (shell with no holes) has 4 points assertEquals("Num of points invalid", 2 * 4, coords[1][0].length); } /** * Creates an ArcSDE table, "EXAMPLE", and adds a spatial column, "SHAPE", to it. * <p> * This code is directly taken from the createBaseTable mehtod of the arcsdeonline * "Working with layers" example, to verify that it works prior to blame the gt implementation. * </p> * * @throws SeException * DOCUMENT ME! * @throws IOException * DOCUMENT ME! * @throws UnavailableArcSDEConnectionException * DOCUMENT ME! */ @Test public void testCreateBaseTable() throws SeException, IOException, UnavailableArcSDEConnectionException { final SeColumnDefinition[] colDefs = new SeColumnDefinition[7]; /* * Define the columns and their attributes for the table to be created. NOTE: The valid * range/values of size and scale parameters vary from one database to another. */ boolean isNullable = true; colDefs[0] = new SeColumnDefinition("INT32_COL", SeColumnDefinition.TYPE_INTEGER, 10, 0, isNullable); colDefs[1] = new SeColumnDefinition("INT16_COL", SeColumnDefinition.TYPE_SMALLINT, 4, 0, isNullable); colDefs[2] = new SeColumnDefinition("FLOAT32_COL", SeColumnDefinition.TYPE_FLOAT, 5, 2, isNullable); colDefs[3] = new SeColumnDefinition("FLOAT64_COL", SeColumnDefinition.TYPE_DOUBLE, 15, 4, isNullable); colDefs[4] = new SeColumnDefinition("STRING_COL", SeColumnDefinition.TYPE_STRING, 25, 0, isNullable); colDefs[5] = new SeColumnDefinition("DATE_COL", SeColumnDefinition.TYPE_DATE, 1, 0, isNullable); colDefs[6] = new SeColumnDefinition("INT64_COL", SeColumnDefinition.TYPE_INTEGER, 10, 0, isNullable); final Command<Void> createBaseTableCmd = new Command<Void>() { @Override public Void execute(ISession session, SeConnection connection) throws SeException, IOException { SeLayer layer = new SeLayer(connection); SeTable table = null; /* * Create a qualified table name with current user's name and the name of the table * to be created, "EXAMPLE". */ String tableName = (connection.getUser() + ".EXAMPLE"); table = new SeTable(connection, tableName); layer.setTableName("EXAMPLE"); try { table.delete(); } catch (Exception e) { LOGGER.warning(e.getMessage()); } /* * Create the table using the DBMS default configuration keyword. Valid keywords are * defined in the dbtune table. */ if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("\n--> Creating a table using DBMS Default Keyword"); } table.create(colDefs, testData.getConfigKeyword()); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(" - Done."); } /* * Define the attributes of the spatial column */ layer.setSpatialColumnName("SHAPE"); /* * Set the type of shapes that can be inserted into the layer. Shape type can be * just one or many. NOTE: Layers that contain more than one shape type can only be * accessed through the C and Java APIs and Arc Explorer Java 3.x. They cannot be * seen from ArcGIS desktop applications. */ layer.setShapeTypes(SeLayer.SE_NIL_TYPE_MASK | SeLayer.SE_POINT_TYPE_MASK | SeLayer.SE_LINE_TYPE_MASK | SeLayer.SE_SIMPLE_LINE_TYPE_MASK | SeLayer.SE_AREA_TYPE_MASK | SeLayer.SE_MULTIPART_TYPE_MASK); layer.setGridSizes(1100.0, 0.0, 0.0); layer.setDescription("Layer Example"); SeExtent ext = new SeExtent(0.0, 0.0, 10000.0, 10000.0); layer.setExtent(ext); /* * Define the layer's Coordinate Reference */ SeCoordinateReference coordref = TestData.getGenericCoordRef(); layer.setCoordRef(coordref); /* * Spatially enable the new table... */ if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("\n--> Adding spatial column \"SHAPE\"..."); } layer.setCreationKeyword(testData.getConfigKeyword()); layer.create(3, 4); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(" - Done."); } return null; } }; session.issue(createBaseTableCmd); } // End method createBaseTable /** * Creates an ArcSDE table, "EXAMPLE", and adds a spatial column, "SHAPE", to it. * <p> * This code is directly taken from the createBaseTable mehtod of the arcsdeonline * "Working with layers" example, to verify that it works prior to blame the gt implementation. * </p> * * @throws SeException * DOCUMENT ME! * @throws IOException * DOCUMENT ME! * @throws UnavailableArcSDEConnectionException * DOCUMENT ME! */ @Test public void testCreateNonStandardSchema() throws SeException, IOException, UnavailableArcSDEConnectionException { Command<Void> createCommand = new Command<Void>() { @Override public Void execute(ISession session, SeConnection connection) throws SeException, IOException { final SeLayer layer = new SeLayer(connection); /* * Create a qualified table name with current user's name and the name of the table * to be created, "EXAMPLE". */ final String tableName = (connection.getUser() + ".NOTENDSWITHGEOM"); final SeTable table = new SeTable(connection, tableName); try { layer.setTableName("NOTENDSWITHGEOM"); try { table.delete(); } catch (Exception e) { // intentionally blank } /* * Create the table using the DBMS default configuration keyword. Valid keywords * are defined in the dbtune table. */ if (LOGGER.isLoggable(Level.FINE)) { System.out.println("\n--> Creating a table using DBMS Default Keyword"); } SeColumnDefinition[] tmpCols = new SeColumnDefinition[] { new SeColumnDefinition( "tmp", SeColumnDefinition.TYPE_STRING, 5, 0, true) }; table.create(tmpCols, testData.getConfigKeyword()); if (LOGGER.isLoggable(Level.FINE)) { System.out.println(" - Done."); } SeColumnDefinition[] colDefs = new SeColumnDefinition[7]; /* * Define the columns and their attributes for the table to be created. NOTE: * The valid range/values of size and scale parameters vary from one database to * another. */ boolean isNullable = true; colDefs[0] = new SeColumnDefinition("INT32_COL", SeColumnDefinition.TYPE_INTEGER, 10, 0, isNullable); colDefs[1] = new SeColumnDefinition("INT16_COL", SeColumnDefinition.TYPE_SMALLINT, 4, 0, isNullable); colDefs[2] = new SeColumnDefinition("FLOAT32_COL", SeColumnDefinition.TYPE_FLOAT, 5, 2, isNullable); colDefs[3] = new SeColumnDefinition("FLOAT64_COL", SeColumnDefinition.TYPE_DOUBLE, 15, 4, isNullable); colDefs[4] = new SeColumnDefinition("STRING_COL", SeColumnDefinition.TYPE_STRING, 25, 0, isNullable); colDefs[5] = new SeColumnDefinition("DATE_COL", SeColumnDefinition.TYPE_DATE, 1, 0, isNullable); colDefs[6] = new SeColumnDefinition("INT64_COL", SeColumnDefinition.TYPE_INTEGER, 10, 0, isNullable); table.addColumn(colDefs[0]); table.addColumn(colDefs[1]); table.addColumn(colDefs[2]); table.addColumn(colDefs[3]); table.dropColumn(tmpCols[0].getName()); /* * Define the attributes of the spatial column */ layer.setSpatialColumnName("SHAPE"); /* * Set the type of shapes that can be inserted into the layer. Shape type can be * just one or many. NOTE: Layers that contain more than one shape type can only * be accessed through the C and Java APIs and Arc Explorer Java 3.x. They * cannot be seen from ArcGIS desktop applications. */ layer.setShapeTypes(SeLayer.SE_NIL_TYPE_MASK | SeLayer.SE_POINT_TYPE_MASK | SeLayer.SE_LINE_TYPE_MASK | SeLayer.SE_SIMPLE_LINE_TYPE_MASK | SeLayer.SE_AREA_TYPE_MASK | SeLayer.SE_MULTIPART_TYPE_MASK); layer.setGridSizes(1100.0, 0.0, 0.0); layer.setDescription("Layer Example"); SeExtent ext = new SeExtent(0.0, 0.0, 10000.0, 10000.0); layer.setExtent(ext); /* * Define the layer's Coordinate Reference */ SeCoordinateReference coordref = new SeCoordinateReference(); - coordref.setXY(0, 0, 100); + coordref.setXY(0D, 0D, 100D); layer.setCoordRef(coordref); /* * Spatially enable the new table... */ if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("\n--> Adding spatial column \"SHAPE\"..."); } layer.setCreationKeyword(testData.getConfigKeyword()); layer.create(3, 4); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(" - Done."); } table.addColumn(colDefs[4]); table.addColumn(colDefs[5]); table.addColumn(colDefs[6]); // } catch (SeException e) { // LOGGER.throwing(this.getClass().getName(), // "testCreateNonStandardSchema", e); // throw e; } finally { try { table.delete(); } catch (Exception e) { // intentionally blank } try { layer.delete(); } catch (Exception e) { // intentionally blank } } return null; } }; session.issue(createCommand); } // End method createBaseTable @Test public void testDeleteById() throws IOException, UnavailableArcSDEConnectionException, SeException { final String typeName = testData.getTempTableName(); final SeQuery query = session.createAndExecuteQuery(new String[] { "ROW_ID", "INT32_COL" }, new SeSqlConstruct(typeName)); final int rowId; try { SdeRow row = session.fetch(query); rowId = row.getInteger(0).intValue(); } finally { session.close(query); } session.issue(new Command<Void>() { @Override public Void execute(ISession session, SeConnection connection) throws SeException, IOException { SeDelete delete = new SeDelete(connection); delete.byId(typeName, new SeObjectId(rowId)); delete.close(); return null; } }); final String whereClause = "ROW_ID=" + rowId; final SeSqlConstruct sqlConstruct = new SeSqlConstruct(typeName, whereClause); final SeQuery deletedQuery = session.createAndExecuteQuery(new String[] { "ROW_ID" }, sqlConstruct); SdeRow row = session.fetch(deletedQuery); assertNull(whereClause + " should have returned no records as it was deleted", row); } /** * Does a query over a non autocommit transaction return the added/modified features and hides * the deleted ones? * * @throws DataSourceException */ @Test public void testTransactionStateRead() throws Exception { // connection with a transaction in progress final ISession transSession; testData.truncateTempTable(); { final SessionPool connPool = testData.getConnectionPool(); transSession = connPool.getSession(); // start a transaction on transConn transSession.startTransaction(); } // flag to rollback or not at finally{} boolean commited = false; try { final String[] columns = { "INT32_COL", "STRING_COL" }; final String tableName = testData.getTempTableName(transSession); transSession.issue(new Command<Void>() { @Override public Void execute(ISession session, SeConnection connection) throws SeException, IOException { SeInsert insert = new SeInsert(connection); insert.intoTable(tableName, columns); insert.setWriteMode(true); SeRow row = insert.getRowToSet(); row.setInteger(0, Integer.valueOf(50)); row.setString(1, "inside transaction"); insert.execute(); // IMPORTANT to call close for the diff to take effect insert.close(); return null; } }); final SeSqlConstruct sqlConstruct = new SeSqlConstruct(tableName); final SeRow transRow = transSession.issue(new Command<SeRow>() { @Override public SeRow execute(ISession session, SeConnection connection) throws SeException, IOException { // the query over the transaction connection SeQuery transQuery = new SeQuery(connection, columns, sqlConstruct); // transaction is not committed, so transQuery should give // the // inserted // record and query don't transQuery.prepareQuery(); transQuery.execute(); SeRow transRow = transQuery.fetch(); // querying over a transaction in progress does give diff // assertEquals(Integer.valueOf(50), transRow.getInteger(0)) transQuery.close(); return transRow; } }); assertNotNull(transRow); // commit transaction transSession.commitTransaction(); commited = true; final SeRow noTransRow = session.issue(new Command<SeRow>() { @Override public SeRow execute(ISession session, SeConnection connection) throws SeException, IOException { SeQuery query = new SeQuery(connection, columns, sqlConstruct); query.prepareQuery(); query.execute(); SeRow row = query.fetch(); query.close(); return row; } }); assertNotNull(noTransRow); } catch (Exception e) { e.printStackTrace(); } finally { if (!commited) { transSession.rollbackTransaction(); } transSession.dispose(); // conn.close(); closed at tearDown } } /** * Creates a versioned table with two versions, the default one and another one, makes edits * over the default one, checks states are consistent in both * * @throws Exception */ @Test public void testEditVersionedTable_DefaultVersion() throws Exception { final SeTable versionedTable = testData.createVersionedTable(session); // create a new version final SeVersion defaultVersion; final SeVersion newVersion; { defaultVersion = session.getDefaultVersion(); newVersion = session.issue(new Command<SeVersion>() { @Override public SeVersion execute(ISession session, SeConnection connection) throws SeException, IOException { SeVersion newVersion = new SeVersion(connection, SeVersion.SE_QUALIFIED_DEFAULT_VERSION_NAME); // newVersion.getInfo(); newVersion.setName(connection.getUser() + ".GeoToolsTestVersion"); newVersion.setParentName(defaultVersion.getName()); newVersion.setDescription(defaultVersion.getName() + " child for GeoTools ArcSDE unit tests"); // do not require ArcSDE to create a unique name if the // required // version already exists boolean uniqueName = false; try { newVersion.create(uniqueName, newVersion); } catch (SeException e) { int sdeError = e.getSeError().getSdeError(); if (sdeError != -177) { throw new ArcSdeException(e); } // "VERSION ALREADY EXISTS", ignore and continue.. newVersion.getInfo(); } return newVersion; } }); } // edit default version SeState newState1 = session.issue(new Command<SeState>() { @Override public SeState execute(ISession session, SeConnection connection) throws SeException, IOException { SeObjectId defVersionStateId = defaultVersion.getStateId(); SeState defVersionState = new SeState(connection, defVersionStateId); // create a new state as a child of the current one, the current // one // must be closed if (defVersionState.isOpen()) { defVersionState.close(); } SeState newState1 = new SeState(connection); newState1.create(defVersionState.getId()); return newState1; } }); session.startTransaction(); testData.insertIntoVersionedTable(session, newState1, versionedTable.getName(), "name 1 state 1"); testData.insertIntoVersionedTable(session, newState1, versionedTable.getName(), "name 2 state 1"); final SeObjectId parentStateId = newState1.getId(); session.close(newState1); final SeState newState2 = session.issue(new Command<SeState>() { @Override public SeState execute(ISession session, SeConnection connection) throws SeException, IOException { SeState newState = new SeState(connection); newState.create(parentStateId); return newState; } }); testData.insertIntoVersionedTable(session, newState2, versionedTable.getName(), "name 1 state 2"); session.issue(new Command<Void>() { @Override public Void execute(ISession session, SeConnection connection) throws SeException, IOException { // Change the version's state pointer to the last edit state. defaultVersion.changeState(newState2.getId()); // Trim the state tree. newState2.trimTree(parentStateId, newState2.getId()); return null; } }); session.commitTransaction(); // we edited the default version, lets query the default version and the // new version and assert they have the correct feature count final SeObjectId defaultVersionStateId = defaultVersion.getStateId(); SeState defVersionState = session.createState(defaultVersionStateId); int defVersionCount = getTempTableCount(session, versionedTable.getName(), null, null, defVersionState); assertEquals(3, defVersionCount); SeState newVersionState = session.createState(newVersion.getStateId()); int newVersionCount = getTempTableCount(session, versionedTable.getName(), null, null, newVersionState); assertEquals(0, newVersionCount); } private void insertIntoDifferentTransactionsAndMerge(ISession session) throws IOException { SeVersion defaultVersion = session.getDefaultVersion(); SeState currentState = session.createState(defaultVersion.getStateId()); if (currentState.isOpen()) { try { currentState.close(); } catch (SeException e) { } } // SeState newState1 = session.createchi } }
true
true
public void testCreateNonStandardSchema() throws SeException, IOException, UnavailableArcSDEConnectionException { Command<Void> createCommand = new Command<Void>() { @Override public Void execute(ISession session, SeConnection connection) throws SeException, IOException { final SeLayer layer = new SeLayer(connection); /* * Create a qualified table name with current user's name and the name of the table * to be created, "EXAMPLE". */ final String tableName = (connection.getUser() + ".NOTENDSWITHGEOM"); final SeTable table = new SeTable(connection, tableName); try { layer.setTableName("NOTENDSWITHGEOM"); try { table.delete(); } catch (Exception e) { // intentionally blank } /* * Create the table using the DBMS default configuration keyword. Valid keywords * are defined in the dbtune table. */ if (LOGGER.isLoggable(Level.FINE)) { System.out.println("\n--> Creating a table using DBMS Default Keyword"); } SeColumnDefinition[] tmpCols = new SeColumnDefinition[] { new SeColumnDefinition( "tmp", SeColumnDefinition.TYPE_STRING, 5, 0, true) }; table.create(tmpCols, testData.getConfigKeyword()); if (LOGGER.isLoggable(Level.FINE)) { System.out.println(" - Done."); } SeColumnDefinition[] colDefs = new SeColumnDefinition[7]; /* * Define the columns and their attributes for the table to be created. NOTE: * The valid range/values of size and scale parameters vary from one database to * another. */ boolean isNullable = true; colDefs[0] = new SeColumnDefinition("INT32_COL", SeColumnDefinition.TYPE_INTEGER, 10, 0, isNullable); colDefs[1] = new SeColumnDefinition("INT16_COL", SeColumnDefinition.TYPE_SMALLINT, 4, 0, isNullable); colDefs[2] = new SeColumnDefinition("FLOAT32_COL", SeColumnDefinition.TYPE_FLOAT, 5, 2, isNullable); colDefs[3] = new SeColumnDefinition("FLOAT64_COL", SeColumnDefinition.TYPE_DOUBLE, 15, 4, isNullable); colDefs[4] = new SeColumnDefinition("STRING_COL", SeColumnDefinition.TYPE_STRING, 25, 0, isNullable); colDefs[5] = new SeColumnDefinition("DATE_COL", SeColumnDefinition.TYPE_DATE, 1, 0, isNullable); colDefs[6] = new SeColumnDefinition("INT64_COL", SeColumnDefinition.TYPE_INTEGER, 10, 0, isNullable); table.addColumn(colDefs[0]); table.addColumn(colDefs[1]); table.addColumn(colDefs[2]); table.addColumn(colDefs[3]); table.dropColumn(tmpCols[0].getName()); /* * Define the attributes of the spatial column */ layer.setSpatialColumnName("SHAPE"); /* * Set the type of shapes that can be inserted into the layer. Shape type can be * just one or many. NOTE: Layers that contain more than one shape type can only * be accessed through the C and Java APIs and Arc Explorer Java 3.x. They * cannot be seen from ArcGIS desktop applications. */ layer.setShapeTypes(SeLayer.SE_NIL_TYPE_MASK | SeLayer.SE_POINT_TYPE_MASK | SeLayer.SE_LINE_TYPE_MASK | SeLayer.SE_SIMPLE_LINE_TYPE_MASK | SeLayer.SE_AREA_TYPE_MASK | SeLayer.SE_MULTIPART_TYPE_MASK); layer.setGridSizes(1100.0, 0.0, 0.0); layer.setDescription("Layer Example"); SeExtent ext = new SeExtent(0.0, 0.0, 10000.0, 10000.0); layer.setExtent(ext); /* * Define the layer's Coordinate Reference */ SeCoordinateReference coordref = new SeCoordinateReference(); coordref.setXY(0, 0, 100); layer.setCoordRef(coordref); /* * Spatially enable the new table... */ if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("\n--> Adding spatial column \"SHAPE\"..."); } layer.setCreationKeyword(testData.getConfigKeyword()); layer.create(3, 4); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(" - Done."); } table.addColumn(colDefs[4]); table.addColumn(colDefs[5]); table.addColumn(colDefs[6]); // } catch (SeException e) { // LOGGER.throwing(this.getClass().getName(), // "testCreateNonStandardSchema", e); // throw e; } finally { try { table.delete(); } catch (Exception e) { // intentionally blank } try { layer.delete(); } catch (Exception e) { // intentionally blank } } return null; } }; session.issue(createCommand); } // End method createBaseTable
public void testCreateNonStandardSchema() throws SeException, IOException, UnavailableArcSDEConnectionException { Command<Void> createCommand = new Command<Void>() { @Override public Void execute(ISession session, SeConnection connection) throws SeException, IOException { final SeLayer layer = new SeLayer(connection); /* * Create a qualified table name with current user's name and the name of the table * to be created, "EXAMPLE". */ final String tableName = (connection.getUser() + ".NOTENDSWITHGEOM"); final SeTable table = new SeTable(connection, tableName); try { layer.setTableName("NOTENDSWITHGEOM"); try { table.delete(); } catch (Exception e) { // intentionally blank } /* * Create the table using the DBMS default configuration keyword. Valid keywords * are defined in the dbtune table. */ if (LOGGER.isLoggable(Level.FINE)) { System.out.println("\n--> Creating a table using DBMS Default Keyword"); } SeColumnDefinition[] tmpCols = new SeColumnDefinition[] { new SeColumnDefinition( "tmp", SeColumnDefinition.TYPE_STRING, 5, 0, true) }; table.create(tmpCols, testData.getConfigKeyword()); if (LOGGER.isLoggable(Level.FINE)) { System.out.println(" - Done."); } SeColumnDefinition[] colDefs = new SeColumnDefinition[7]; /* * Define the columns and their attributes for the table to be created. NOTE: * The valid range/values of size and scale parameters vary from one database to * another. */ boolean isNullable = true; colDefs[0] = new SeColumnDefinition("INT32_COL", SeColumnDefinition.TYPE_INTEGER, 10, 0, isNullable); colDefs[1] = new SeColumnDefinition("INT16_COL", SeColumnDefinition.TYPE_SMALLINT, 4, 0, isNullable); colDefs[2] = new SeColumnDefinition("FLOAT32_COL", SeColumnDefinition.TYPE_FLOAT, 5, 2, isNullable); colDefs[3] = new SeColumnDefinition("FLOAT64_COL", SeColumnDefinition.TYPE_DOUBLE, 15, 4, isNullable); colDefs[4] = new SeColumnDefinition("STRING_COL", SeColumnDefinition.TYPE_STRING, 25, 0, isNullable); colDefs[5] = new SeColumnDefinition("DATE_COL", SeColumnDefinition.TYPE_DATE, 1, 0, isNullable); colDefs[6] = new SeColumnDefinition("INT64_COL", SeColumnDefinition.TYPE_INTEGER, 10, 0, isNullable); table.addColumn(colDefs[0]); table.addColumn(colDefs[1]); table.addColumn(colDefs[2]); table.addColumn(colDefs[3]); table.dropColumn(tmpCols[0].getName()); /* * Define the attributes of the spatial column */ layer.setSpatialColumnName("SHAPE"); /* * Set the type of shapes that can be inserted into the layer. Shape type can be * just one or many. NOTE: Layers that contain more than one shape type can only * be accessed through the C and Java APIs and Arc Explorer Java 3.x. They * cannot be seen from ArcGIS desktop applications. */ layer.setShapeTypes(SeLayer.SE_NIL_TYPE_MASK | SeLayer.SE_POINT_TYPE_MASK | SeLayer.SE_LINE_TYPE_MASK | SeLayer.SE_SIMPLE_LINE_TYPE_MASK | SeLayer.SE_AREA_TYPE_MASK | SeLayer.SE_MULTIPART_TYPE_MASK); layer.setGridSizes(1100.0, 0.0, 0.0); layer.setDescription("Layer Example"); SeExtent ext = new SeExtent(0.0, 0.0, 10000.0, 10000.0); layer.setExtent(ext); /* * Define the layer's Coordinate Reference */ SeCoordinateReference coordref = new SeCoordinateReference(); coordref.setXY(0D, 0D, 100D); layer.setCoordRef(coordref); /* * Spatially enable the new table... */ if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("\n--> Adding spatial column \"SHAPE\"..."); } layer.setCreationKeyword(testData.getConfigKeyword()); layer.create(3, 4); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(" - Done."); } table.addColumn(colDefs[4]); table.addColumn(colDefs[5]); table.addColumn(colDefs[6]); // } catch (SeException e) { // LOGGER.throwing(this.getClass().getName(), // "testCreateNonStandardSchema", e); // throw e; } finally { try { table.delete(); } catch (Exception e) { // intentionally blank } try { layer.delete(); } catch (Exception e) { // intentionally blank } } return null; } }; session.issue(createCommand); } // End method createBaseTable
diff --git a/org.agileware.natural.cucumber/src/org/agileware/natural/cucumber/validation/CucumberJavaValidator.java b/org.agileware.natural.cucumber/src/org/agileware/natural/cucumber/validation/CucumberJavaValidator.java index 2ea013c..957e0c3 100644 --- a/org.agileware.natural.cucumber/src/org/agileware/natural/cucumber/validation/CucumberJavaValidator.java +++ b/org.agileware.natural.cucumber/src/org/agileware/natural/cucumber/validation/CucumberJavaValidator.java @@ -1,44 +1,44 @@ package org.agileware.natural.cucumber.validation; import org.agileware.natural.common.JavaAnnotationMatcher; import org.agileware.natural.cucumber.cucumber.CucumberPackage; import org.agileware.natural.cucumber.cucumber.Step; import org.eclipse.jdt.core.IMethod; import org.eclipse.xtext.validation.Check; import com.google.inject.Inject; public class CucumberJavaValidator extends AbstractCucumberJavaValidator { @Inject private JavaAnnotationMatcher matcher; @Check public void checkStepMatching(Step step) { final Counter counter = new Counter(); String description = step.getDescription().substring(step.getDescription().indexOf(' ') + 1); matcher.findMatches(description, new JavaAnnotationMatcher.Command() { public void match(String annotationValue, IMethod method) { counter.increment(); } }); if (counter.get() == 0) { warning("No definition found for `" + description + "`", CucumberPackage.Literals.STEP__DESCRIPTION); } else if (counter.get() > 1) { - warning("Multiple definition found for `" + description + "`", CucumberPackage.Literals.STEP__DESCRIPTION); + warning("Multiple definitions found for `" + description + "`", CucumberPackage.Literals.STEP__DESCRIPTION); } } private final static class Counter { private int count = 0; public void increment() { count++; } public int get() { return count; } } }
true
true
public void checkStepMatching(Step step) { final Counter counter = new Counter(); String description = step.getDescription().substring(step.getDescription().indexOf(' ') + 1); matcher.findMatches(description, new JavaAnnotationMatcher.Command() { public void match(String annotationValue, IMethod method) { counter.increment(); } }); if (counter.get() == 0) { warning("No definition found for `" + description + "`", CucumberPackage.Literals.STEP__DESCRIPTION); } else if (counter.get() > 1) { warning("Multiple definition found for `" + description + "`", CucumberPackage.Literals.STEP__DESCRIPTION); } }
public void checkStepMatching(Step step) { final Counter counter = new Counter(); String description = step.getDescription().substring(step.getDescription().indexOf(' ') + 1); matcher.findMatches(description, new JavaAnnotationMatcher.Command() { public void match(String annotationValue, IMethod method) { counter.increment(); } }); if (counter.get() == 0) { warning("No definition found for `" + description + "`", CucumberPackage.Literals.STEP__DESCRIPTION); } else if (counter.get() > 1) { warning("Multiple definitions found for `" + description + "`", CucumberPackage.Literals.STEP__DESCRIPTION); } }
diff --git a/spring-data-neo4j-rest/src/main/java/org/springframework/data/neo4j/rest/RequestResult.java b/spring-data-neo4j-rest/src/main/java/org/springframework/data/neo4j/rest/RequestResult.java index 700242bf..a1a24e18 100644 --- a/spring-data-neo4j-rest/src/main/java/org/springframework/data/neo4j/rest/RequestResult.java +++ b/spring-data-neo4j-rest/src/main/java/org/springframework/data/neo4j/rest/RequestResult.java @@ -1,58 +1,58 @@ /** * Copyright 2011 the original author or authors. * * 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.springframework.data.neo4j.rest; import com.sun.jersey.api.client.ClientResponse; import javax.ws.rs.core.Response; import java.net.URI; /** * @author mh * @since 27.06.11 */ public class RequestResult { private final int status; private final URI location; private final String entity; RequestResult(int status, URI location, String entity) { this.status = status; this.location = location; this.entity = entity; } public static RequestResult extractFrom(ClientResponse clientResponse) { final int status = clientResponse.getStatus(); final URI location = clientResponse.getLocation(); - final String data = clientResponse.hasEntity() ? clientResponse.getEntity(String.class) : null; + final String data = status != Response.Status.NO_CONTENT.getStatusCode() ? clientResponse.getEntity(String.class) : null; clientResponse.close(); return new RequestResult(status, location, data); } public int getStatus() { return status; } public URI getLocation() { return location; } public String getEntity() { return entity; } }
true
true
public static RequestResult extractFrom(ClientResponse clientResponse) { final int status = clientResponse.getStatus(); final URI location = clientResponse.getLocation(); final String data = clientResponse.hasEntity() ? clientResponse.getEntity(String.class) : null; clientResponse.close(); return new RequestResult(status, location, data); }
public static RequestResult extractFrom(ClientResponse clientResponse) { final int status = clientResponse.getStatus(); final URI location = clientResponse.getLocation(); final String data = status != Response.Status.NO_CONTENT.getStatusCode() ? clientResponse.getEntity(String.class) : null; clientResponse.close(); return new RequestResult(status, location, data); }
diff --git a/src/main/java/hudson/scm/SubversionRepositoryStatus.java b/src/main/java/hudson/scm/SubversionRepositoryStatus.java index fb11b54..19c6ad4 100644 --- a/src/main/java/hudson/scm/SubversionRepositoryStatus.java +++ b/src/main/java/hudson/scm/SubversionRepositoryStatus.java @@ -1,158 +1,158 @@ package hudson.scm; import static java.util.logging.Level.FINE; import static java.util.logging.Level.FINER; import static java.util.logging.Level.WARNING; import static javax.servlet.http.HttpServletResponse.SC_OK; import hudson.model.AbstractModelObject; import hudson.model.AbstractProject; import hudson.model.Hudson; import hudson.scm.SubversionSCM.ModuleLocation; import hudson.scm.SubversionSCM.SvnInfo; import hudson.triggers.SCMTrigger; import hudson.util.QueryParameterMap; import java.io.BufferedReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.UUID; import java.util.logging.Logger; import javax.servlet.ServletException; import org.apache.commons.io.IOUtils; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.tmatesoft.svn.core.SVNException; /** * Per repository status. * * @author Kohsuke Kawaguchi * @see SubversionStatus */ public class SubversionRepositoryStatus extends AbstractModelObject { public final UUID uuid; public SubversionRepositoryStatus(UUID uuid) { this.uuid = uuid; } public String getDisplayName() { return uuid.toString(); } public String getSearchUrl() { return uuid.toString(); } /** * Notify the commit to this repository. * * <p> * Because this URL is not guarded, we can't really trust the data that's sent to us. But we intentionally * don't protect this URL to simplify <tt>post-commit</tt> script set up. */ public void doNotifyCommit(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException { requirePOST(); // compute the affected paths Set<String> affectedPath = new HashSet<String>(); String line; BufferedReader r = new BufferedReader(req.getReader()); try { while((line=r.readLine())!=null) { if (LOGGER.isLoggable(FINER)) { LOGGER.finer("Reading line: "+line); } affectedPath.add(line.substring(4)); if (line.startsWith("svnlook changed --revision ")) { String msg = "Expecting the output from the svnlook command but instead you just sent me the svnlook invocation command line: " + line; LOGGER.warning(msg); throw new IllegalArgumentException(msg); } } } finally { IOUtils.closeQuietly(r); } if(LOGGER.isLoggable(FINE)) LOGGER.fine("Change reported to Subversion repository "+uuid+" on "+affectedPath); boolean scmFound = false, triggerFound = false, uuidFound = false, pathFound = false; // we can't reliably use req.getParameter() as it can try to parse the payload, which we've already consumed above. // servlet container relies on Content-type to decide if it wants to parse the payload or not, and at least // in case of Jetty, it doesn't check if the payload is QueryParameterMap query = new QueryParameterMap(req); String revParam = query.get("rev"); long rev = -1; if (revParam != null) { rev = Long.parseLong(revParam); } else { revParam = req.getHeader("X-Hudson-Subversion-Revision"); if (revParam != null) { rev = Long.parseLong(revParam); } } OUTER: - for (AbstractProject<?,?> p : Hudson.getInstance().getItems(AbstractProject.class)) { + for (AbstractProject<?,?> p : Hudson.getInstance().getAllItems(AbstractProject.class)) { try { SCM scm = p.getScm(); if (scm instanceof SubversionSCM) scmFound = true; else continue; SCMTrigger trigger = p.getTrigger(SCMTrigger.class); if (trigger!=null) triggerFound = true; else continue; SubversionSCM sscm = (SubversionSCM) scm; for (ModuleLocation loc : sscm.getLocations()) { if (loc.getUUID(p).equals(uuid)) uuidFound = true; else continue; String m = loc.getSVNURL().getPath(); String n = loc.getRepositoryRoot(p).getPath(); if(!m.startsWith(n)) continue; // repository root should be a subpath of the module path, but be defensive String remaining = m.substring(n.length()); if(remaining.startsWith("/")) remaining=remaining.substring(1); String remainingSlash = remaining + '/'; final RevisionParameterAction[] actions; if ( rev != -1 ) { SvnInfo info[] = { new SvnInfo(loc.getURL(), rev) }; RevisionParameterAction action = new RevisionParameterAction(info); actions = new RevisionParameterAction[] {action}; } else { actions = new RevisionParameterAction[0]; } for (String path : affectedPath) { if(path.equals(remaining) /*for files*/ || path.startsWith(remainingSlash) /*for dirs*/ || remaining.length()==0/*when someone is checking out the whole repo (that is, m==n)*/) { // this project is possibly changed. poll now. // if any of the data we used was bogus, the trigger will not detect a change LOGGER.fine("Scheduling the immediate polling of "+p); trigger.run(actions); pathFound = true; continue OUTER; } } } } catch (SVNException e) { LOGGER.log(WARNING,"Failed to handle Subversion commit notification",e); } } if (!scmFound) LOGGER.warning("No subversion jobs found"); else if (!triggerFound) LOGGER.warning("No subversion jobs using SCM polling"); else if (!uuidFound) LOGGER.warning("No subversion jobs using repository: " + uuid); else if (!pathFound) LOGGER.fine("No jobs found matching the modified files"); rsp.setStatus(SC_OK); } private static final Logger LOGGER = Logger.getLogger(SubversionRepositoryStatus.class.getName()); }
true
true
public void doNotifyCommit(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException { requirePOST(); // compute the affected paths Set<String> affectedPath = new HashSet<String>(); String line; BufferedReader r = new BufferedReader(req.getReader()); try { while((line=r.readLine())!=null) { if (LOGGER.isLoggable(FINER)) { LOGGER.finer("Reading line: "+line); } affectedPath.add(line.substring(4)); if (line.startsWith("svnlook changed --revision ")) { String msg = "Expecting the output from the svnlook command but instead you just sent me the svnlook invocation command line: " + line; LOGGER.warning(msg); throw new IllegalArgumentException(msg); } } } finally { IOUtils.closeQuietly(r); } if(LOGGER.isLoggable(FINE)) LOGGER.fine("Change reported to Subversion repository "+uuid+" on "+affectedPath); boolean scmFound = false, triggerFound = false, uuidFound = false, pathFound = false; // we can't reliably use req.getParameter() as it can try to parse the payload, which we've already consumed above. // servlet container relies on Content-type to decide if it wants to parse the payload or not, and at least // in case of Jetty, it doesn't check if the payload is QueryParameterMap query = new QueryParameterMap(req); String revParam = query.get("rev"); long rev = -1; if (revParam != null) { rev = Long.parseLong(revParam); } else { revParam = req.getHeader("X-Hudson-Subversion-Revision"); if (revParam != null) { rev = Long.parseLong(revParam); } } OUTER: for (AbstractProject<?,?> p : Hudson.getInstance().getItems(AbstractProject.class)) { try { SCM scm = p.getScm(); if (scm instanceof SubversionSCM) scmFound = true; else continue; SCMTrigger trigger = p.getTrigger(SCMTrigger.class); if (trigger!=null) triggerFound = true; else continue; SubversionSCM sscm = (SubversionSCM) scm; for (ModuleLocation loc : sscm.getLocations()) { if (loc.getUUID(p).equals(uuid)) uuidFound = true; else continue; String m = loc.getSVNURL().getPath(); String n = loc.getRepositoryRoot(p).getPath(); if(!m.startsWith(n)) continue; // repository root should be a subpath of the module path, but be defensive String remaining = m.substring(n.length()); if(remaining.startsWith("/")) remaining=remaining.substring(1); String remainingSlash = remaining + '/'; final RevisionParameterAction[] actions; if ( rev != -1 ) { SvnInfo info[] = { new SvnInfo(loc.getURL(), rev) }; RevisionParameterAction action = new RevisionParameterAction(info); actions = new RevisionParameterAction[] {action}; } else { actions = new RevisionParameterAction[0]; } for (String path : affectedPath) { if(path.equals(remaining) /*for files*/ || path.startsWith(remainingSlash) /*for dirs*/ || remaining.length()==0/*when someone is checking out the whole repo (that is, m==n)*/) { // this project is possibly changed. poll now. // if any of the data we used was bogus, the trigger will not detect a change LOGGER.fine("Scheduling the immediate polling of "+p); trigger.run(actions); pathFound = true; continue OUTER; } } } } catch (SVNException e) { LOGGER.log(WARNING,"Failed to handle Subversion commit notification",e); } } if (!scmFound) LOGGER.warning("No subversion jobs found"); else if (!triggerFound) LOGGER.warning("No subversion jobs using SCM polling"); else if (!uuidFound) LOGGER.warning("No subversion jobs using repository: " + uuid); else if (!pathFound) LOGGER.fine("No jobs found matching the modified files"); rsp.setStatus(SC_OK); }
public void doNotifyCommit(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException { requirePOST(); // compute the affected paths Set<String> affectedPath = new HashSet<String>(); String line; BufferedReader r = new BufferedReader(req.getReader()); try { while((line=r.readLine())!=null) { if (LOGGER.isLoggable(FINER)) { LOGGER.finer("Reading line: "+line); } affectedPath.add(line.substring(4)); if (line.startsWith("svnlook changed --revision ")) { String msg = "Expecting the output from the svnlook command but instead you just sent me the svnlook invocation command line: " + line; LOGGER.warning(msg); throw new IllegalArgumentException(msg); } } } finally { IOUtils.closeQuietly(r); } if(LOGGER.isLoggable(FINE)) LOGGER.fine("Change reported to Subversion repository "+uuid+" on "+affectedPath); boolean scmFound = false, triggerFound = false, uuidFound = false, pathFound = false; // we can't reliably use req.getParameter() as it can try to parse the payload, which we've already consumed above. // servlet container relies on Content-type to decide if it wants to parse the payload or not, and at least // in case of Jetty, it doesn't check if the payload is QueryParameterMap query = new QueryParameterMap(req); String revParam = query.get("rev"); long rev = -1; if (revParam != null) { rev = Long.parseLong(revParam); } else { revParam = req.getHeader("X-Hudson-Subversion-Revision"); if (revParam != null) { rev = Long.parseLong(revParam); } } OUTER: for (AbstractProject<?,?> p : Hudson.getInstance().getAllItems(AbstractProject.class)) { try { SCM scm = p.getScm(); if (scm instanceof SubversionSCM) scmFound = true; else continue; SCMTrigger trigger = p.getTrigger(SCMTrigger.class); if (trigger!=null) triggerFound = true; else continue; SubversionSCM sscm = (SubversionSCM) scm; for (ModuleLocation loc : sscm.getLocations()) { if (loc.getUUID(p).equals(uuid)) uuidFound = true; else continue; String m = loc.getSVNURL().getPath(); String n = loc.getRepositoryRoot(p).getPath(); if(!m.startsWith(n)) continue; // repository root should be a subpath of the module path, but be defensive String remaining = m.substring(n.length()); if(remaining.startsWith("/")) remaining=remaining.substring(1); String remainingSlash = remaining + '/'; final RevisionParameterAction[] actions; if ( rev != -1 ) { SvnInfo info[] = { new SvnInfo(loc.getURL(), rev) }; RevisionParameterAction action = new RevisionParameterAction(info); actions = new RevisionParameterAction[] {action}; } else { actions = new RevisionParameterAction[0]; } for (String path : affectedPath) { if(path.equals(remaining) /*for files*/ || path.startsWith(remainingSlash) /*for dirs*/ || remaining.length()==0/*when someone is checking out the whole repo (that is, m==n)*/) { // this project is possibly changed. poll now. // if any of the data we used was bogus, the trigger will not detect a change LOGGER.fine("Scheduling the immediate polling of "+p); trigger.run(actions); pathFound = true; continue OUTER; } } } } catch (SVNException e) { LOGGER.log(WARNING,"Failed to handle Subversion commit notification",e); } } if (!scmFound) LOGGER.warning("No subversion jobs found"); else if (!triggerFound) LOGGER.warning("No subversion jobs using SCM polling"); else if (!uuidFound) LOGGER.warning("No subversion jobs using repository: " + uuid); else if (!pathFound) LOGGER.fine("No jobs found matching the modified files"); rsp.setStatus(SC_OK); }
diff --git a/src/com/android/providers/contacts/LegacyApiSupport.java b/src/com/android/providers/contacts/LegacyApiSupport.java index 51fb8e0..aa847fc 100644 --- a/src/com/android/providers/contacts/LegacyApiSupport.java +++ b/src/com/android/providers/contacts/LegacyApiSupport.java @@ -1,1466 +1,1467 @@ /* * 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.providers.contacts; import com.android.providers.contacts.OpenHelper.DataColumns; import com.android.providers.contacts.OpenHelper.ExtensionsColumns; import com.android.providers.contacts.OpenHelper.GroupsColumns; import com.android.providers.contacts.OpenHelper.MimetypesColumns; import com.android.providers.contacts.OpenHelper.PhoneColumns; import com.android.providers.contacts.OpenHelper.PresenceColumns; import com.android.providers.contacts.OpenHelper.RawContactsColumns; import com.android.providers.contacts.OpenHelper.Tables; import android.accounts.Account; import android.app.SearchManager; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.database.sqlite.SQLiteStatement; import android.net.Uri; import android.provider.Contacts; import android.provider.ContactsContract; import android.provider.Contacts.ContactMethods; import android.provider.Contacts.Extensions; import android.provider.Contacts.People; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Groups; import android.provider.ContactsContract.Presence; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.CommonDataKinds.Im; import android.provider.ContactsContract.CommonDataKinds.Note; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Photo; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import java.util.HashMap; public class LegacyApiSupport implements OpenHelper.Delegate { private static final String TAG = "ContactsProviderV1"; private static final String NON_EXISTENT_ACCOUNT_TYPE = "android.INVALID_ACCOUNT_TYPE"; private static final String NON_EXISTENT_ACCOUNT_NAME = "invalid"; private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); private static final int PEOPLE = 1; private static final int PEOPLE_ID = 2; private static final int PEOPLE_UPDATE_CONTACT_TIME = 3; private static final int ORGANIZATIONS = 4; private static final int ORGANIZATIONS_ID = 5; private static final int PEOPLE_CONTACTMETHODS = 6; private static final int PEOPLE_CONTACTMETHODS_ID = 7; private static final int CONTACTMETHODS = 8; private static final int CONTACTMETHODS_ID = 9; private static final int PEOPLE_PHONES = 10; private static final int PEOPLE_PHONES_ID = 11; private static final int PHONES = 12; private static final int PHONES_ID = 13; private static final int EXTENSIONS = 14; private static final int EXTENSIONS_ID = 15; private static final int PEOPLE_EXTENSIONS = 16; private static final int PEOPLE_EXTENSIONS_ID = 17; private static final int GROUPS = 18; private static final int GROUPS_ID = 19; private static final int GROUPMEMBERSHIP = 20; private static final int GROUPMEMBERSHIP_ID = 21; private static final int PEOPLE_GROUPMEMBERSHIP = 22; private static final int PEOPLE_GROUPMEMBERSHIP_ID = 23; private static final int PEOPLE_PHOTO = 24; private static final int PHOTOS = 25; private static final int PHOTOS_ID = 26; private static final int PEOPLE_FILTER = 29; private static final int DELETED_PEOPLE = 30; private static final int DELETED_GROUPS = 31; private static final int SEARCH_SUGGESTIONS = 32; private static final int SEARCH_SHORTCUT = 33; private static final int PHONES_FILTER = 34; private static final String PEOPLE_JOINS = " LEFT OUTER JOIN data name ON (raw_contacts._id = name.raw_contact_id" + " AND (SELECT mimetype FROM mimetypes WHERE mimetypes._id = name.mimetype_id)" + "='" + StructuredName.CONTENT_ITEM_TYPE + "')" + " LEFT OUTER JOIN data organization ON (raw_contacts._id = organization.raw_contact_id" + " AND (SELECT mimetype FROM mimetypes WHERE mimetypes._id = organization.mimetype_id)" + "='" + Organization.CONTENT_ITEM_TYPE + "' AND organization.is_primary)" + " LEFT OUTER JOIN data email ON (raw_contacts._id = email.raw_contact_id" + " AND (SELECT mimetype FROM mimetypes WHERE mimetypes._id = email.mimetype_id)" + "='" + Email.CONTENT_ITEM_TYPE + "' AND email.is_primary)" + " LEFT OUTER JOIN data note ON (raw_contacts._id = note.raw_contact_id" + " AND (SELECT mimetype FROM mimetypes WHERE mimetypes._id = note.mimetype_id)" + "='" + Note.CONTENT_ITEM_TYPE + "')" + " LEFT OUTER JOIN data phone ON (raw_contacts._id = phone.raw_contact_id" + " AND (SELECT mimetype FROM mimetypes WHERE mimetypes._id = phone.mimetype_id)" + "='" + Phone.CONTENT_ITEM_TYPE + "' AND phone.is_primary)"; public static final String DATA_JOINS = " JOIN mimetypes ON (mimetypes._id = data.mimetype_id)" + " JOIN raw_contacts ON (raw_contacts._id = data.raw_contact_id)" + PEOPLE_JOINS; public static final String PRESENCE_JOINS = " LEFT OUTER JOIN presence ON (" + " presence.presence_id = (SELECT max(presence_id) FROM presence" + " WHERE people._id = presence_raw_contact_id))"; private static final String PHONETIC_NAME_SQL = "trim(trim(" + "ifnull(name." + StructuredName.PHONETIC_GIVEN_NAME + ",' ')||' '||" + "ifnull(name." + StructuredName.PHONETIC_MIDDLE_NAME + ",' '))||' '||" + "ifnull(name." + StructuredName.PHONETIC_FAMILY_NAME + ",' ')) "; private static final String CONTACT_METHOD_KIND_SQL = "CAST ((CASE WHEN mimetype='" + Email.CONTENT_ITEM_TYPE + "'" + " THEN " + android.provider.Contacts.KIND_EMAIL + " ELSE" + " (CASE WHEN mimetype='" + Im.CONTENT_ITEM_TYPE +"'" + " THEN " + android.provider.Contacts.KIND_IM + " ELSE" + " (CASE WHEN mimetype='" + StructuredPostal.CONTENT_ITEM_TYPE + "'" + " THEN " + android.provider.Contacts.KIND_POSTAL + " ELSE" + " NULL" + " END)" + " END)" + " END) AS INTEGER)"; private static final String IM_PROTOCOL_SQL = "(CASE WHEN " + Presence.PROTOCOL + "=" + Im.PROTOCOL_CUSTOM + " THEN 'custom:'||" + Presence.CUSTOM_PROTOCOL + " ELSE 'pre:'||" + Presence.PROTOCOL + " END)"; private static String CONTACT_METHOD_DATA_SQL = "(CASE WHEN " + Data.MIMETYPE + "='" + Im.CONTENT_ITEM_TYPE + "'" + " THEN (CASE WHEN " + Tables.DATA + "." + Im.PROTOCOL + "=" + Im.PROTOCOL_CUSTOM + " THEN 'custom:'||" + Tables.DATA + "." + Im.CUSTOM_PROTOCOL + " ELSE 'pre:'||" + Tables.DATA + "." + Im.PROTOCOL + " END)" + " ELSE " + DataColumns.CONCRETE_DATA2 + " END)"; public interface LegacyTables { public static final String PEOPLE = "view_v1_people"; public static final String PEOPLE_JOIN_PRESENCE = "view_v1_people people " + PRESENCE_JOINS; public static final String GROUPS = "view_v1_groups"; public static final String ORGANIZATIONS = "view_v1_organizations"; public static final String CONTACT_METHODS = "view_v1_contact_methods"; public static final String PHONES = "view_v1_phones"; public static final String EXTENSIONS = "view_v1_extensions"; public static final String GROUP_MEMBERSHIP = "view_v1_group_membership"; public static final String PHOTOS = "view_v1_photos"; } private static final String[] ORGANIZATION_MIME_TYPES = new String[] { Organization.CONTENT_ITEM_TYPE }; private static final String[] CONTACT_METHOD_MIME_TYPES = new String[] { Email.CONTENT_ITEM_TYPE, Im.CONTENT_ITEM_TYPE, StructuredPostal.CONTENT_ITEM_TYPE, }; private static final String[] PHONE_MIME_TYPES = new String[] { Phone.CONTENT_ITEM_TYPE }; private interface PhotoQuery { String[] COLUMNS = { Data._ID }; int _ID = 0; } /** * A custom data row that is used to store legacy photo data fields no * longer directly supported by the API. */ private interface LegacyPhotoData { public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/photo_v1_extras"; public static final String PHOTO_DATA_ID = Data.DATA1; public static final String LOCAL_VERSION = Data.DATA2; public static final String DOWNLOAD_REQUIRED = Data.DATA3; public static final String EXISTS_ON_SERVER = Data.DATA4; public static final String SYNC_ERROR = Data.DATA5; } public static final String LEGACY_PHOTO_JOIN = " LEFT OUTER JOIN data legacy_photo ON (raw_contacts._id = legacy_photo.raw_contact_id" + " AND (SELECT mimetype FROM mimetypes WHERE mimetypes._id = legacy_photo.mimetype_id)" + "='" + LegacyPhotoData.CONTENT_ITEM_TYPE + "'" + " AND " + DataColumns.CONCRETE_ID + " = legacy_photo." + LegacyPhotoData.PHOTO_DATA_ID + ")"; private static final HashMap<String, String> sPeopleProjectionMap; private static final HashMap<String, String> sOrganizationProjectionMap; private static final HashMap<String, String> sContactMethodProjectionMap; private static final HashMap<String, String> sPhoneProjectionMap; private static final HashMap<String, String> sExtensionProjectionMap; private static final HashMap<String, String> sGroupProjectionMap; private static final HashMap<String, String> sGroupMembershipProjectionMap; private static final HashMap<String, String> sPhotoProjectionMap; static { // Contacts URI matching table UriMatcher matcher = sUriMatcher; String authority = android.provider.Contacts.AUTHORITY; matcher.addURI(authority, "extensions", EXTENSIONS); matcher.addURI(authority, "extensions/#", EXTENSIONS_ID); matcher.addURI(authority, "groups", GROUPS); matcher.addURI(authority, "groups/#", GROUPS_ID); // matcher.addURI(authority, "groups/name/*/members", GROUP_NAME_MEMBERS); // matcher.addURI(authority, "groups/name/*/members/filter/*", // GROUP_NAME_MEMBERS_FILTER); // matcher.addURI(authority, "groups/system_id/*/members", GROUP_SYSTEM_ID_MEMBERS); // matcher.addURI(authority, "groups/system_id/*/members/filter/*", // GROUP_SYSTEM_ID_MEMBERS_FILTER); matcher.addURI(authority, "groupmembership", GROUPMEMBERSHIP); matcher.addURI(authority, "groupmembership/#", GROUPMEMBERSHIP_ID); // matcher.addURI(authority, "groupmembershipraw", GROUPMEMBERSHIP_RAW); matcher.addURI(authority, "people", PEOPLE); // matcher.addURI(authority, "people/strequent", PEOPLE_STREQUENT); // matcher.addURI(authority, "people/strequent/filter/*", PEOPLE_STREQUENT_FILTER); matcher.addURI(authority, "people/filter/*", PEOPLE_FILTER); // matcher.addURI(authority, "people/with_phones_filter/*", // PEOPLE_WITH_PHONES_FILTER); // matcher.addURI(authority, "people/with_email_or_im_filter/*", // PEOPLE_WITH_EMAIL_OR_IM_FILTER); matcher.addURI(authority, "people/#", PEOPLE_ID); matcher.addURI(authority, "people/#/extensions", PEOPLE_EXTENSIONS); matcher.addURI(authority, "people/#/extensions/#", PEOPLE_EXTENSIONS_ID); matcher.addURI(authority, "people/#/phones", PEOPLE_PHONES); matcher.addURI(authority, "people/#/phones/#", PEOPLE_PHONES_ID); // matcher.addURI(authority, "people/#/phones_with_presence", // PEOPLE_PHONES_WITH_PRESENCE); matcher.addURI(authority, "people/#/photo", PEOPLE_PHOTO); // matcher.addURI(authority, "people/#/photo/data", PEOPLE_PHOTO_DATA); matcher.addURI(authority, "people/#/contact_methods", PEOPLE_CONTACTMETHODS); // matcher.addURI(authority, "people/#/contact_methods_with_presence", // PEOPLE_CONTACTMETHODS_WITH_PRESENCE); matcher.addURI(authority, "people/#/contact_methods/#", PEOPLE_CONTACTMETHODS_ID); // matcher.addURI(authority, "people/#/organizations", PEOPLE_ORGANIZATIONS); // matcher.addURI(authority, "people/#/organizations/#", PEOPLE_ORGANIZATIONS_ID); matcher.addURI(authority, "people/#/groupmembership", PEOPLE_GROUPMEMBERSHIP); matcher.addURI(authority, "people/#/groupmembership/#", PEOPLE_GROUPMEMBERSHIP_ID); // matcher.addURI(authority, "people/raw", PEOPLE_RAW); // matcher.addURI(authority, "people/owner", PEOPLE_OWNER); matcher.addURI(authority, "people/#/update_contact_time", PEOPLE_UPDATE_CONTACT_TIME); matcher.addURI(authority, "deleted_people", DELETED_PEOPLE); matcher.addURI(authority, "deleted_groups", DELETED_GROUPS); matcher.addURI(authority, "phones", PHONES); // matcher.addURI(authority, "phones_with_presence", PHONES_WITH_PRESENCE); matcher.addURI(authority, "phones/filter/*", PHONES_FILTER); // matcher.addURI(authority, "phones/filter_name/*", PHONES_FILTER_NAME); // matcher.addURI(authority, "phones/mobile_filter_name/*", // PHONES_MOBILE_FILTER_NAME); matcher.addURI(authority, "phones/#", PHONES_ID); matcher.addURI(authority, "photos", PHOTOS); matcher.addURI(authority, "photos/#", PHOTOS_ID); matcher.addURI(authority, "contact_methods", CONTACTMETHODS); // matcher.addURI(authority, "contact_methods/email", CONTACTMETHODS_EMAIL); // matcher.addURI(authority, "contact_methods/email/*", CONTACTMETHODS_EMAIL_FILTER); matcher.addURI(authority, "contact_methods/#", CONTACTMETHODS_ID); // matcher.addURI(authority, "contact_methods/with_presence", // CONTACTMETHODS_WITH_PRESENCE); matcher.addURI(authority, "organizations", ORGANIZATIONS); matcher.addURI(authority, "organizations/#", ORGANIZATIONS_ID); // matcher.addURI(authority, "voice_dialer_timestamp", VOICE_DIALER_TIMESTAMP); matcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGESTIONS); matcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGESTIONS); matcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/#", SEARCH_SHORTCUT); // matcher.addURI(authority, "settings", SETTINGS); // // matcher.addURI(authority, "live_folders/people", LIVE_FOLDERS_PEOPLE); // matcher.addURI(authority, "live_folders/people/*", // LIVE_FOLDERS_PEOPLE_GROUP_NAME); // matcher.addURI(authority, "live_folders/people_with_phones", // LIVE_FOLDERS_PEOPLE_WITH_PHONES); // matcher.addURI(authority, "live_folders/favorites", // LIVE_FOLDERS_PEOPLE_FAVORITES); HashMap<String, String> peopleProjectionMap = new HashMap<String, String>(); peopleProjectionMap.put(People.NAME, People.NAME); peopleProjectionMap.put(People.DISPLAY_NAME, People.DISPLAY_NAME); peopleProjectionMap.put(People.PHONETIC_NAME, People.PHONETIC_NAME); peopleProjectionMap.put(People.NOTES, People.NOTES); peopleProjectionMap.put(People.TIMES_CONTACTED, People.TIMES_CONTACTED); peopleProjectionMap.put(People.LAST_TIME_CONTACTED, People.LAST_TIME_CONTACTED); peopleProjectionMap.put(People.CUSTOM_RINGTONE, People.CUSTOM_RINGTONE); peopleProjectionMap.put(People.SEND_TO_VOICEMAIL, People.SEND_TO_VOICEMAIL); peopleProjectionMap.put(People.STARRED, People.STARRED); sPeopleProjectionMap = new HashMap<String, String>(peopleProjectionMap); sPeopleProjectionMap.put(People._ID, People._ID); sPeopleProjectionMap.put(People.PRIMARY_ORGANIZATION_ID, People.PRIMARY_ORGANIZATION_ID); sPeopleProjectionMap.put(People.PRIMARY_EMAIL_ID, People.PRIMARY_EMAIL_ID); sPeopleProjectionMap.put(People.PRIMARY_PHONE_ID, People.PRIMARY_PHONE_ID); sPeopleProjectionMap.put(People.NUMBER, People.NUMBER); sPeopleProjectionMap.put(People.TYPE, People.TYPE); sPeopleProjectionMap.put(People.LABEL, People.LABEL); sPeopleProjectionMap.put(People.NUMBER_KEY, People.NUMBER_KEY); sPeopleProjectionMap.put(People.IM_PROTOCOL, IM_PROTOCOL_SQL + " AS " + People.IM_PROTOCOL); sPeopleProjectionMap.put(People.IM_HANDLE, People.IM_HANDLE); sPeopleProjectionMap.put(People.IM_ACCOUNT, People.IM_ACCOUNT); sPeopleProjectionMap.put(People.PRESENCE_STATUS, People.PRESENCE_STATUS); sPeopleProjectionMap.put(People.PRESENCE_CUSTOM_STATUS, People.PRESENCE_CUSTOM_STATUS); sOrganizationProjectionMap = new HashMap<String, String>(); sOrganizationProjectionMap.put(android.provider.Contacts.Organizations._ID, android.provider.Contacts.Organizations._ID); sOrganizationProjectionMap.put(android.provider.Contacts.Organizations.PERSON_ID, android.provider.Contacts.Organizations.PERSON_ID); sOrganizationProjectionMap.put(android.provider.Contacts.Organizations.ISPRIMARY, android.provider.Contacts.Organizations.ISPRIMARY); sOrganizationProjectionMap.put(android.provider.Contacts.Organizations.COMPANY, android.provider.Contacts.Organizations.COMPANY); sOrganizationProjectionMap.put(android.provider.Contacts.Organizations.TYPE, android.provider.Contacts.Organizations.TYPE); sOrganizationProjectionMap.put(android.provider.Contacts.Organizations.LABEL, android.provider.Contacts.Organizations.LABEL); sOrganizationProjectionMap.put(android.provider.Contacts.Organizations.TITLE, android.provider.Contacts.Organizations.TITLE); sContactMethodProjectionMap = new HashMap<String, String>(peopleProjectionMap); sContactMethodProjectionMap.put(ContactMethods._ID, ContactMethods._ID); sContactMethodProjectionMap.put(ContactMethods.PERSON_ID, ContactMethods.PERSON_ID); sContactMethodProjectionMap.put(ContactMethods.KIND, ContactMethods.KIND); sContactMethodProjectionMap.put(ContactMethods.ISPRIMARY, ContactMethods.ISPRIMARY); sContactMethodProjectionMap.put(ContactMethods.TYPE, ContactMethods.TYPE); sContactMethodProjectionMap.put(ContactMethods.DATA, ContactMethods.DATA); sContactMethodProjectionMap.put(ContactMethods.LABEL, ContactMethods.LABEL); sContactMethodProjectionMap.put(ContactMethods.AUX_DATA, ContactMethods.AUX_DATA); sPhoneProjectionMap = new HashMap<String, String>(peopleProjectionMap); sPhoneProjectionMap.put(android.provider.Contacts.Phones._ID, android.provider.Contacts.Phones._ID); sPhoneProjectionMap.put(android.provider.Contacts.Phones.PERSON_ID, android.provider.Contacts.Phones.PERSON_ID); sPhoneProjectionMap.put(android.provider.Contacts.Phones.ISPRIMARY, android.provider.Contacts.Phones.ISPRIMARY); sPhoneProjectionMap.put(android.provider.Contacts.Phones.NUMBER, android.provider.Contacts.Phones.NUMBER); sPhoneProjectionMap.put(android.provider.Contacts.Phones.TYPE, android.provider.Contacts.Phones.TYPE); sPhoneProjectionMap.put(android.provider.Contacts.Phones.LABEL, android.provider.Contacts.Phones.LABEL); sPhoneProjectionMap.put(android.provider.Contacts.Phones.NUMBER_KEY, android.provider.Contacts.Phones.NUMBER_KEY); sExtensionProjectionMap = new HashMap<String, String>(); sExtensionProjectionMap.put(android.provider.Contacts.Extensions._ID, android.provider.Contacts.Extensions._ID); sExtensionProjectionMap.put(android.provider.Contacts.Extensions.PERSON_ID, android.provider.Contacts.Extensions.PERSON_ID); sExtensionProjectionMap.put(android.provider.Contacts.Extensions.NAME, android.provider.Contacts.Extensions.NAME); sExtensionProjectionMap.put(android.provider.Contacts.Extensions.VALUE, android.provider.Contacts.Extensions.VALUE); sGroupProjectionMap = new HashMap<String, String>(); sGroupProjectionMap.put(android.provider.Contacts.Groups._ID, android.provider.Contacts.Groups._ID); sGroupProjectionMap.put(android.provider.Contacts.Groups.NAME, android.provider.Contacts.Groups.NAME); sGroupProjectionMap.put(android.provider.Contacts.Groups.NOTES, android.provider.Contacts.Groups.NOTES); sGroupProjectionMap.put(android.provider.Contacts.Groups.SYSTEM_ID, android.provider.Contacts.Groups.SYSTEM_ID); sGroupMembershipProjectionMap = new HashMap<String, String>(); sGroupMembershipProjectionMap.put(android.provider.Contacts.GroupMembership._ID, android.provider.Contacts.GroupMembership._ID); sGroupMembershipProjectionMap.put(android.provider.Contacts.GroupMembership.PERSON_ID, android.provider.Contacts.GroupMembership.PERSON_ID); sGroupMembershipProjectionMap.put(android.provider.Contacts.GroupMembership.GROUP_ID, android.provider.Contacts.GroupMembership.GROUP_ID); sPhotoProjectionMap = new HashMap<String, String>(); sPhotoProjectionMap.put(android.provider.Contacts.Photos._ID, android.provider.Contacts.Photos._ID); sPhotoProjectionMap.put(android.provider.Contacts.Photos.PERSON_ID, android.provider.Contacts.Photos.PERSON_ID); sPhotoProjectionMap.put(android.provider.Contacts.Photos.DATA, android.provider.Contacts.Photos.DATA); sPhotoProjectionMap.put(android.provider.Contacts.Photos.LOCAL_VERSION, android.provider.Contacts.Photos.LOCAL_VERSION); sPhotoProjectionMap.put(android.provider.Contacts.Photos.DOWNLOAD_REQUIRED, android.provider.Contacts.Photos.DOWNLOAD_REQUIRED); sPhotoProjectionMap.put(android.provider.Contacts.Photos.EXISTS_ON_SERVER, android.provider.Contacts.Photos.EXISTS_ON_SERVER); sPhotoProjectionMap.put(android.provider.Contacts.Photos.SYNC_ERROR, android.provider.Contacts.Photos.SYNC_ERROR); } private final Context mContext; private final OpenHelper mOpenHelper; private final ContactsProvider2 mContactsProvider; private final NameSplitter mPhoneticNameSplitter; private final GlobalSearchSupport mGlobalSearchSupport; /** Precompiled sql statement for incrementing times contacted for a contact */ private final SQLiteStatement mLastTimeContactedUpdate; private final ContentValues mValues = new ContentValues(); private Account mAccount; public LegacyApiSupport(Context context, OpenHelper openHelper, ContactsProvider2 contactsProvider, GlobalSearchSupport globalSearchSupport) { mContext = context; mContactsProvider = contactsProvider; mOpenHelper = openHelper; mGlobalSearchSupport = globalSearchSupport; mOpenHelper.setDelegate(this); mPhoneticNameSplitter = new NameSplitter("", "", "", context.getString(com.android.internal.R.string.common_name_conjunctions)); SQLiteDatabase db = mOpenHelper.getReadableDatabase(); mLastTimeContactedUpdate = db.compileStatement("UPDATE " + Tables.RAW_CONTACTS + " SET " + RawContacts.TIMES_CONTACTED + "=" + RawContacts.TIMES_CONTACTED + "+1," + RawContacts.LAST_TIME_CONTACTED + "=? WHERE " + RawContacts._ID + "=?"); } private void ensureDefaultAccount() { if (mAccount == null) { mAccount = mContactsProvider.getDefaultAccount(); if (mAccount == null) { // This fall-through account will not match any data in the database, which // is the expected behavior mAccount = new Account(NON_EXISTENT_ACCOUNT_NAME, NON_EXISTENT_ACCOUNT_TYPE); } } } public void createDatabase(SQLiteDatabase db) { db.execSQL("DROP VIEW IF EXISTS " + LegacyTables.PEOPLE + ";"); db.execSQL("CREATE VIEW " + LegacyTables.PEOPLE + " AS SELECT " + RawContactsColumns.CONCRETE_ID + " AS " + android.provider.Contacts.People._ID + ", " + "name." + StructuredName.DISPLAY_NAME + " AS " + People.NAME + ", " + Tables.RAW_CONTACTS + "." + RawContactsColumns.DISPLAY_NAME + " AS " + People.DISPLAY_NAME + ", " + PHONETIC_NAME_SQL + " AS " + People.PHONETIC_NAME + " , " + "note." + Note.NOTE + " AS " + People.NOTES + ", " + RawContacts.ACCOUNT_NAME + ", " + RawContacts.ACCOUNT_TYPE + ", " + Tables.RAW_CONTACTS + "." + RawContacts.TIMES_CONTACTED + " AS " + People.TIMES_CONTACTED + ", " + Tables.RAW_CONTACTS + "." + RawContacts.LAST_TIME_CONTACTED + " AS " + People.LAST_TIME_CONTACTED + ", " + Tables.RAW_CONTACTS + "." + RawContacts.CUSTOM_RINGTONE + " AS " + People.CUSTOM_RINGTONE + ", " + Tables.RAW_CONTACTS + "." + RawContacts.SEND_TO_VOICEMAIL + " AS " + People.SEND_TO_VOICEMAIL + ", " + Tables.RAW_CONTACTS + "." + RawContacts.STARRED + " AS " + People.STARRED + ", " + "organization." + Data._ID + " AS " + People.PRIMARY_ORGANIZATION_ID + ", " + "email." + Data._ID + " AS " + People.PRIMARY_EMAIL_ID + ", " + "phone." + Data._ID + " AS " + People.PRIMARY_PHONE_ID + ", " + "phone." + Phone.NUMBER + " AS " + People.NUMBER + ", " + "phone." + Phone.TYPE + " AS " + People.TYPE + ", " + "phone." + Phone.LABEL + " AS " + People.LABEL + ", " + "phone." + PhoneColumns.NORMALIZED_NUMBER + " AS " + People.NUMBER_KEY + " FROM " + Tables.RAW_CONTACTS + PEOPLE_JOINS + " WHERE " + Tables.RAW_CONTACTS + "." + RawContacts.DELETED + "=0" + " AND " + RawContacts.IS_RESTRICTED + "=0" + ";"); db.execSQL("DROP VIEW IF EXISTS " + LegacyTables.ORGANIZATIONS + ";"); db.execSQL("CREATE VIEW " + LegacyTables.ORGANIZATIONS + " AS SELECT " + DataColumns.CONCRETE_ID + " AS " + android.provider.Contacts.Organizations._ID + ", " + Data.RAW_CONTACT_ID + " AS " + android.provider.Contacts.Organizations.PERSON_ID + ", " + Data.IS_PRIMARY + " AS " + android.provider.Contacts.Organizations.ISPRIMARY + ", " + RawContacts.ACCOUNT_NAME + ", " + RawContacts.ACCOUNT_TYPE + ", " + Organization.COMPANY + " AS " + android.provider.Contacts.Organizations.COMPANY + ", " + Organization.TYPE + " AS " + android.provider.Contacts.Organizations.TYPE + ", " + Organization.LABEL + " AS " + android.provider.Contacts.Organizations.LABEL + ", " + Organization.TITLE + " AS " + android.provider.Contacts.Organizations.TITLE + " FROM " + Tables.DATA_JOIN_MIMETYPE_RAW_CONTACTS + " WHERE " + MimetypesColumns.CONCRETE_MIMETYPE + "='" + Organization.CONTENT_ITEM_TYPE + "'" + " AND " + Tables.RAW_CONTACTS + "." + RawContacts.DELETED + "=0" + " AND " + RawContacts.IS_RESTRICTED + "=0" + ";"); db.execSQL("DROP VIEW IF EXISTS " + LegacyTables.CONTACT_METHODS + ";"); db.execSQL("CREATE VIEW " + LegacyTables.CONTACT_METHODS + " AS SELECT " + DataColumns.CONCRETE_ID + " AS " + ContactMethods._ID + ", " + DataColumns.CONCRETE_RAW_CONTACT_ID + " AS " + ContactMethods.PERSON_ID + ", " + CONTACT_METHOD_KIND_SQL + " AS " + ContactMethods.KIND + ", " + DataColumns.CONCRETE_IS_PRIMARY + " AS " + ContactMethods.ISPRIMARY + ", " + DataColumns.CONCRETE_DATA1 + " AS " + ContactMethods.TYPE + ", " + CONTACT_METHOD_DATA_SQL + " AS " + ContactMethods.DATA + ", " + DataColumns.CONCRETE_DATA3 + " AS " + ContactMethods.LABEL + ", " + DataColumns.CONCRETE_DATA14 + " AS " + ContactMethods.AUX_DATA + ", " + "name." + StructuredName.DISPLAY_NAME + " AS " + ContactMethods.NAME + ", " + Tables.RAW_CONTACTS + "." + RawContactsColumns.DISPLAY_NAME + " AS " + ContactMethods.DISPLAY_NAME + ", " + RawContacts.ACCOUNT_NAME + ", " + RawContacts.ACCOUNT_TYPE + ", " + PHONETIC_NAME_SQL + " AS " + ContactMethods.PHONETIC_NAME + " , " + "note." + Note.NOTE + " AS " + ContactMethods.NOTES + ", " + Tables.RAW_CONTACTS + "." + RawContacts.TIMES_CONTACTED + " AS " + ContactMethods.TIMES_CONTACTED + ", " + Tables.RAW_CONTACTS + "." + RawContacts.LAST_TIME_CONTACTED + " AS " + ContactMethods.LAST_TIME_CONTACTED + ", " + Tables.RAW_CONTACTS + "." + RawContacts.CUSTOM_RINGTONE + " AS " + ContactMethods.CUSTOM_RINGTONE + ", " + Tables.RAW_CONTACTS + "." + RawContacts.SEND_TO_VOICEMAIL + " AS " + ContactMethods.SEND_TO_VOICEMAIL + ", " + Tables.RAW_CONTACTS + "." + RawContacts.STARRED + " AS " + ContactMethods.STARRED + " FROM " + Tables.DATA + DATA_JOINS + " WHERE " + ContactMethods.KIND + " IS NOT NULL" + " AND " + Tables.RAW_CONTACTS + "." + RawContacts.DELETED + "=0" + " AND " + RawContacts.IS_RESTRICTED + "=0" + ";"); db.execSQL("DROP VIEW IF EXISTS " + LegacyTables.PHONES + ";"); db.execSQL("CREATE VIEW " + LegacyTables.PHONES + " AS SELECT " + DataColumns.CONCRETE_ID + " AS " + android.provider.Contacts.Phones._ID + ", " + DataColumns.CONCRETE_RAW_CONTACT_ID + " AS " + android.provider.Contacts.Phones.PERSON_ID + ", " + DataColumns.CONCRETE_IS_PRIMARY + " AS " + android.provider.Contacts.Phones.ISPRIMARY + ", " + Tables.DATA + "." + Phone.NUMBER + " AS " + android.provider.Contacts.Phones.NUMBER + ", " + Tables.DATA + "." + Phone.TYPE + " AS " + android.provider.Contacts.Phones.TYPE + ", " + Tables.DATA + "." + Phone.LABEL + " AS " + android.provider.Contacts.Phones.LABEL + ", " + PhoneColumns.CONCRETE_NORMALIZED_NUMBER + " AS " + android.provider.Contacts.Phones.NUMBER_KEY + ", " + "name." + StructuredName.DISPLAY_NAME + " AS " + android.provider.Contacts.Phones.NAME + ", " + Tables.RAW_CONTACTS + "." + RawContactsColumns.DISPLAY_NAME + " AS " + android.provider.Contacts.Phones.DISPLAY_NAME + ", " + RawContacts.ACCOUNT_NAME + ", " + RawContacts.ACCOUNT_TYPE + ", " + PHONETIC_NAME_SQL + " AS " + android.provider.Contacts.Phones.PHONETIC_NAME + " , " + "note." + Note.NOTE + " AS " + android.provider.Contacts.Phones.NOTES + ", " + Tables.RAW_CONTACTS + "." + RawContacts.TIMES_CONTACTED + " AS " + android.provider.Contacts.Phones.TIMES_CONTACTED + ", " + Tables.RAW_CONTACTS + "." + RawContacts.LAST_TIME_CONTACTED + " AS " + android.provider.Contacts.Phones.LAST_TIME_CONTACTED + ", " + Tables.RAW_CONTACTS + "." + RawContacts.CUSTOM_RINGTONE + " AS " + android.provider.Contacts.Phones.CUSTOM_RINGTONE + ", " + Tables.RAW_CONTACTS + "." + RawContacts.SEND_TO_VOICEMAIL + " AS " + android.provider.Contacts.Phones.SEND_TO_VOICEMAIL + ", " + Tables.RAW_CONTACTS + "." + RawContacts.STARRED + " AS " + android.provider.Contacts.Phones.STARRED + " FROM " + Tables.DATA + DATA_JOINS + " WHERE " + MimetypesColumns.CONCRETE_MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + " AND " + Tables.RAW_CONTACTS + "." + RawContacts.DELETED + "=0" + " AND " + RawContacts.IS_RESTRICTED + "=0" + ";"); db.execSQL("DROP VIEW IF EXISTS " + LegacyTables.EXTENSIONS + ";"); db.execSQL("CREATE VIEW " + LegacyTables.EXTENSIONS + " AS SELECT " + DataColumns.CONCRETE_ID + " AS " + android.provider.Contacts.Extensions._ID + ", " + DataColumns.CONCRETE_RAW_CONTACT_ID + " AS " + android.provider.Contacts.Extensions.PERSON_ID + ", " + RawContacts.ACCOUNT_NAME + ", " + RawContacts.ACCOUNT_TYPE + ", " + ExtensionsColumns.NAME + " AS " + android.provider.Contacts.Extensions.NAME + ", " + ExtensionsColumns.VALUE + " AS " + android.provider.Contacts.Extensions.VALUE + " FROM " + Tables.DATA_JOIN_MIMETYPE_RAW_CONTACTS + " WHERE " + MimetypesColumns.CONCRETE_MIMETYPE + "='" + android.provider.Contacts.Extensions.CONTENT_ITEM_TYPE + "'" + " AND " + Tables.RAW_CONTACTS + "." + RawContacts.DELETED + "=0" + " AND " + RawContacts.IS_RESTRICTED + "=0" + ";"); db.execSQL("DROP VIEW IF EXISTS " + LegacyTables.GROUPS + ";"); db.execSQL("CREATE VIEW " + LegacyTables.GROUPS + " AS SELECT " + GroupsColumns.CONCRETE_ID + " AS " + android.provider.Contacts.Groups._ID + ", " + Groups.ACCOUNT_NAME + ", " + Groups.ACCOUNT_TYPE + ", " + Groups.TITLE + " AS " + android.provider.Contacts.Groups.NAME + ", " + Groups.NOTES + " AS " + android.provider.Contacts.Groups.NOTES + " , " + Groups.SYSTEM_ID + " AS " + android.provider.Contacts.Groups.SYSTEM_ID + " FROM " + Tables.GROUPS + ";"); db.execSQL("DROP VIEW IF EXISTS " + LegacyTables.GROUP_MEMBERSHIP + ";"); db.execSQL("CREATE VIEW " + LegacyTables.GROUP_MEMBERSHIP + " AS SELECT " + DataColumns.CONCRETE_ID + " AS " + android.provider.Contacts.GroupMembership._ID + ", " + DataColumns.CONCRETE_RAW_CONTACT_ID + " AS " + android.provider.Contacts.GroupMembership.PERSON_ID + ", " + Tables.RAW_CONTACTS + "." + RawContacts.ACCOUNT_NAME + " AS " + RawContacts.ACCOUNT_NAME + ", " + Tables.RAW_CONTACTS + "." + RawContacts.ACCOUNT_TYPE + " AS " + RawContacts.ACCOUNT_TYPE + ", " + GroupMembership.GROUP_ROW_ID + " AS " + android.provider.Contacts.GroupMembership.GROUP_ID + ", " + Groups.TITLE + " AS " + android.provider.Contacts.GroupMembership.NAME + ", " + Groups.NOTES + " AS " + android.provider.Contacts.GroupMembership.NOTES + " , " + Groups.SYSTEM_ID + " AS " + android.provider.Contacts.GroupMembership.SYSTEM_ID + " FROM " + Tables.DATA_JOIN_PACKAGES_MIMETYPES_RAW_CONTACTS_GROUPS + " WHERE " + MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE + "'" + " AND " + Tables.RAW_CONTACTS + "." + RawContacts.DELETED + "=0" + ";"); db.execSQL("DROP VIEW IF EXISTS " + LegacyTables.PHOTOS + ";"); db.execSQL("CREATE VIEW " + LegacyTables.PHOTOS + " AS SELECT " + DataColumns.CONCRETE_ID + " AS " + android.provider.Contacts.Photos._ID + ", " + DataColumns.CONCRETE_RAW_CONTACT_ID + " AS " + android.provider.Contacts.Photos.PERSON_ID + ", " + RawContacts.ACCOUNT_NAME + ", " + RawContacts.ACCOUNT_TYPE + ", " + Tables.DATA + "." + Photo.PHOTO + " AS " + android.provider.Contacts.Photos.DATA + ", " + "legacy_photo." + LegacyPhotoData.EXISTS_ON_SERVER + " AS " + android.provider.Contacts.Photos.EXISTS_ON_SERVER + ", " + "legacy_photo." + LegacyPhotoData.DOWNLOAD_REQUIRED + " AS " + android.provider.Contacts.Photos.DOWNLOAD_REQUIRED + ", " + "legacy_photo." + LegacyPhotoData.LOCAL_VERSION + " AS " + android.provider.Contacts.Photos.LOCAL_VERSION + ", " + "legacy_photo." + LegacyPhotoData.SYNC_ERROR + " AS " + android.provider.Contacts.Photos.SYNC_ERROR + " FROM " + Tables.DATA + DATA_JOINS + LEGACY_PHOTO_JOIN + " WHERE " + MimetypesColumns.CONCRETE_MIMETYPE + "='" + Photo.CONTENT_ITEM_TYPE + "'" + " AND " + Tables.RAW_CONTACTS + "." + RawContacts.DELETED + "=0" + " AND " + RawContacts.IS_RESTRICTED + "=0" + ";"); } public Uri insert(Uri uri, ContentValues values) { final int match = sUriMatcher.match(uri); long id = 0; switch (match) { case PEOPLE: id = insertPeople(values); break; case ORGANIZATIONS: id = insertOrganization(values); break; case PEOPLE_CONTACTMETHODS: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); id = insertContactMethod(rawContactId, values); break; } case CONTACTMETHODS: { long rawContactId = getRequiredValue(values, ContactMethods.PERSON_ID); id = insertContactMethod(rawContactId, values); break; } case PHONES: { long rawContactId = getRequiredValue(values, android.provider.Contacts.Phones.PERSON_ID); id = insertPhone(rawContactId, values); break; } case EXTENSIONS: { long rawContactId = getRequiredValue(values, android.provider.Contacts.Extensions.PERSON_ID); id = insertExtension(rawContactId, values); break; } case GROUPS: id = insertGroup(values); break; case GROUPMEMBERSHIP: { long rawContactId = getRequiredValue(values, android.provider.Contacts.GroupMembership.PERSON_ID); long groupId = getRequiredValue(values, android.provider.Contacts.GroupMembership.GROUP_ID); id = insertGroupMembership(rawContactId, groupId); break; } default: throw new UnsupportedOperationException("Unknown uri: " + uri); } if (id < 0) { return null; } final Uri result = ContentUris.withAppendedId(uri, id); onChange(result); return result; } private long getRequiredValue(ContentValues values, String column) { if (!values.containsKey(column)) { throw new RuntimeException("Required value: " + column); } return values.getAsLong(column); } private long insertPeople(ContentValues values) { ensureDefaultAccount(); mValues.clear(); OpenHelper.copyStringValue(mValues, RawContacts.CUSTOM_RINGTONE, values, People.CUSTOM_RINGTONE); OpenHelper.copyLongValue(mValues, RawContacts.SEND_TO_VOICEMAIL, values, People.SEND_TO_VOICEMAIL); OpenHelper.copyLongValue(mValues, RawContacts.LAST_TIME_CONTACTED, values, People.LAST_TIME_CONTACTED); OpenHelper.copyLongValue(mValues, RawContacts.TIMES_CONTACTED, values, People.TIMES_CONTACTED); OpenHelper.copyLongValue(mValues, RawContacts.STARRED, values, People.STARRED); mValues.put(RawContacts.ACCOUNT_NAME, mAccount.name); mValues.put(RawContacts.ACCOUNT_TYPE, mAccount.type); Uri contactUri = mContactsProvider.insert(RawContacts.CONTENT_URI, mValues); long rawContactId = ContentUris.parseId(contactUri); if (values.containsKey(People.NAME) || values.containsKey(People.PHONETIC_NAME)) { mValues.clear(); mValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId); mValues.put(ContactsContract.Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); OpenHelper.copyStringValue(mValues, StructuredName.DISPLAY_NAME, values, People.NAME); if (values.containsKey(People.PHONETIC_NAME)) { String phoneticName = values.getAsString(People.PHONETIC_NAME); NameSplitter.Name parsedName = new NameSplitter.Name(); mPhoneticNameSplitter.split(parsedName, phoneticName); mValues.put(StructuredName.PHONETIC_GIVEN_NAME, parsedName.getGivenNames()); mValues.put(StructuredName.PHONETIC_MIDDLE_NAME, parsedName.getMiddleName()); mValues.put(StructuredName.PHONETIC_FAMILY_NAME, parsedName.getFamilyName()); } mContactsProvider.insert(ContactsContract.Data.CONTENT_URI, mValues); } if (values.containsKey(People.NOTES)) { mValues.clear(); mValues.put(Data.RAW_CONTACT_ID, rawContactId); mValues.put(Data.MIMETYPE, Note.CONTENT_ITEM_TYPE); OpenHelper.copyStringValue(mValues, Note.NOTE, values, People.NOTES); mContactsProvider.insert(Data.CONTENT_URI, mValues); } // TODO instant aggregation return rawContactId; } private long insertOrganization(ContentValues values) { mValues.clear(); OpenHelper.copyLongValue(mValues, Data.RAW_CONTACT_ID, values, android.provider.Contacts.Organizations.PERSON_ID); mValues.put(Data.MIMETYPE, Organization.CONTENT_ITEM_TYPE); OpenHelper.copyLongValue(mValues, Data.IS_PRIMARY, values, android.provider.Contacts.Organizations.ISPRIMARY); OpenHelper.copyStringValue(mValues, Organization.COMPANY, values, android.provider.Contacts.Organizations.COMPANY); // TYPE values happen to remain the same between V1 and V2 - can just copy the value OpenHelper.copyLongValue(mValues, Organization.TYPE, values, android.provider.Contacts.Organizations.TYPE); OpenHelper.copyStringValue(mValues, Organization.LABEL, values, android.provider.Contacts.Organizations.LABEL); OpenHelper.copyStringValue(mValues, Organization.TITLE, values, android.provider.Contacts.Organizations.TITLE); Uri uri = mContactsProvider.insert(Data.CONTENT_URI, mValues); return ContentUris.parseId(uri); } private long insertPhone(long rawContactId, ContentValues values) { mValues.clear(); mValues.put(Data.RAW_CONTACT_ID, rawContactId); mValues.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); OpenHelper.copyLongValue(mValues, Data.IS_PRIMARY, values, android.provider.Contacts.Phones.ISPRIMARY); OpenHelper.copyStringValue(mValues, Phone.NUMBER, values, android.provider.Contacts.Phones.NUMBER); // TYPE values happen to remain the same between V1 and V2 - can just copy the value OpenHelper.copyLongValue(mValues, Phone.TYPE, values, android.provider.Contacts.Phones.TYPE); OpenHelper.copyStringValue(mValues, Phone.LABEL, values, android.provider.Contacts.Phones.LABEL); Uri uri = mContactsProvider.insert(Data.CONTENT_URI, mValues); return ContentUris.parseId(uri); } private long insertContactMethod(long rawContactId, ContentValues values) { Integer kind = values.getAsInteger(ContactMethods.KIND); if (kind == null) { throw new RuntimeException("Required value: " + ContactMethods.KIND); } mValues.clear(); mValues.put(Data.RAW_CONTACT_ID, rawContactId); OpenHelper.copyLongValue(mValues, Data.IS_PRIMARY, values, ContactMethods.ISPRIMARY); switch (kind) { case android.provider.Contacts.KIND_EMAIL: { copyCommonFields(values, Email.CONTENT_ITEM_TYPE, Email.TYPE, Email.LABEL, Data.DATA14); OpenHelper.copyStringValue(mValues, Email.DATA, values, ContactMethods.DATA); break; } case android.provider.Contacts.KIND_IM: { String protocol = values.getAsString(ContactMethods.DATA); if (protocol.startsWith("pre:")) { mValues.put(Im.PROTOCOL, Integer.parseInt(protocol.substring(4))); } else if (protocol.startsWith("custom:")) { mValues.put(Im.PROTOCOL, Im.PROTOCOL_CUSTOM); mValues.put(Im.CUSTOM_PROTOCOL, protocol.substring(7)); } copyCommonFields(values, Im.CONTENT_ITEM_TYPE, Im.TYPE, Im.LABEL, Data.DATA14); break; } case android.provider.Contacts.KIND_POSTAL: { copyCommonFields(values, StructuredPostal.CONTENT_ITEM_TYPE, StructuredPostal.TYPE, StructuredPostal.LABEL, Data.DATA14); OpenHelper.copyStringValue(mValues, StructuredPostal.FORMATTED_ADDRESS, values, ContactMethods.DATA); break; } } Uri uri = mContactsProvider.insert(Data.CONTENT_URI, mValues); return ContentUris.parseId(uri); } private void copyCommonFields(ContentValues values, String mimeType, String typeColumn, String labelColumn, String auxDataColumn) { mValues.put(Data.MIMETYPE, mimeType); OpenHelper.copyLongValue(mValues, typeColumn, values, ContactMethods.TYPE); OpenHelper.copyStringValue(mValues, labelColumn, values, ContactMethods.LABEL); OpenHelper.copyStringValue(mValues, auxDataColumn, values, ContactMethods.AUX_DATA); } private long insertExtension(long rawContactId, ContentValues values) { mValues.clear(); mValues.put(Data.RAW_CONTACT_ID, rawContactId); mValues.put(Data.MIMETYPE, android.provider.Contacts.Extensions.CONTENT_ITEM_TYPE); OpenHelper.copyStringValue(mValues, ExtensionsColumns.NAME, values, android.provider.Contacts.People.Extensions.NAME); OpenHelper.copyStringValue(mValues, ExtensionsColumns.VALUE, values, android.provider.Contacts.People.Extensions.VALUE); Uri uri = mContactsProvider.insert(Data.CONTENT_URI, mValues); return ContentUris.parseId(uri); } private long insertGroup(ContentValues values) { ensureDefaultAccount(); mValues.clear(); OpenHelper.copyStringValue(mValues, Groups.TITLE, values, android.provider.Contacts.Groups.NAME); OpenHelper.copyStringValue(mValues, Groups.NOTES, values, android.provider.Contacts.Groups.NOTES); OpenHelper.copyStringValue(mValues, Groups.SYSTEM_ID, values, android.provider.Contacts.Groups.SYSTEM_ID); mValues.put(Groups.ACCOUNT_NAME, mAccount.name); mValues.put(Groups.ACCOUNT_TYPE, mAccount.type); Uri uri = mContactsProvider.insert(Groups.CONTENT_URI, mValues); return ContentUris.parseId(uri); } private long insertGroupMembership(long rawContactId, long groupId) { mValues.clear(); mValues.put(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE); mValues.put(GroupMembership.RAW_CONTACT_ID, rawContactId); mValues.put(GroupMembership.GROUP_ROW_ID, groupId); Uri uri = mContactsProvider.insert(Data.CONTENT_URI, mValues); return ContentUris.parseId(uri); } public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { final int match = sUriMatcher.match(uri); int count = 0; switch(match) { case PEOPLE_UPDATE_CONTACT_TIME: count = updateContactTime(uri, values); break; case PEOPLE_PHOTO: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); return updatePhoto(rawContactId, values); } case PHOTOS: // TODO break; case PHOTOS_ID: // TODO break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } if (count > 0) { mContext.getContentResolver().notifyChange(uri, null); } return count; } private int updateContactTime(Uri uri, ContentValues values) { // TODO check sanctions long lastTimeContacted; if (values.containsKey(People.LAST_TIME_CONTACTED)) { lastTimeContacted = values.getAsLong(People.LAST_TIME_CONTACTED); } else { lastTimeContacted = System.currentTimeMillis(); } long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); long contactId = mOpenHelper.getContactId(rawContactId); if (contactId != 0) { mContactsProvider.updateContactTime(contactId, lastTimeContacted); } else { mLastTimeContactedUpdate.bindLong(1, lastTimeContacted); mLastTimeContactedUpdate.bindLong(2, rawContactId); mLastTimeContactedUpdate.execute(); } return 1; } private int updatePhoto(long rawContactId, ContentValues values) { // TODO check sanctions int count; long dataId = -1; Cursor c = mContactsProvider.query(Data.CONTENT_URI, PhotoQuery.COLUMNS, Data.RAW_CONTACT_ID + "=" + rawContactId + " AND " + Data.MIMETYPE + "=" + mOpenHelper.getMimeTypeId(Photo.CONTENT_ITEM_TYPE), null, null); try { if (c.moveToFirst()) { dataId = c.getLong(PhotoQuery._ID); } } finally { c.close(); } mValues.clear(); byte[] bytes = values.getAsByteArray(android.provider.Contacts.Photos.DATA); mValues.put(Photo.PHOTO, bytes); if (dataId == -1) { mValues.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); mValues.put(Data.RAW_CONTACT_ID, rawContactId); Uri dataUri = mContactsProvider.insert(Data.CONTENT_URI, mValues); dataId = ContentUris.parseId(dataUri); count = 1; } else { Uri dataUri = ContentUris.withAppendedId(Data.CONTENT_URI, dataId); count = mContactsProvider.update(dataUri, mValues, null, null); } mValues.clear(); OpenHelper.copyStringValue(mValues, LegacyPhotoData.LOCAL_VERSION, values, android.provider.Contacts.Photos.LOCAL_VERSION); OpenHelper.copyStringValue(mValues, LegacyPhotoData.DOWNLOAD_REQUIRED, values, android.provider.Contacts.Photos.DOWNLOAD_REQUIRED); OpenHelper.copyStringValue(mValues, LegacyPhotoData.EXISTS_ON_SERVER, values, android.provider.Contacts.Photos.EXISTS_ON_SERVER); OpenHelper.copyStringValue(mValues, LegacyPhotoData.SYNC_ERROR, values, android.provider.Contacts.Photos.SYNC_ERROR); int updated = mContactsProvider.update(Data.CONTENT_URI, mValues, Data.MIMETYPE + "='" + LegacyPhotoData.CONTENT_ITEM_TYPE + "'" + " AND " + Data.RAW_CONTACT_ID + "=" + rawContactId + " AND " + LegacyPhotoData.PHOTO_DATA_ID + "=" + dataId, null); if (updated == 0) { mValues.put(Data.RAW_CONTACT_ID, rawContactId); mValues.put(Data.MIMETYPE, LegacyPhotoData.CONTENT_ITEM_TYPE); mValues.put(LegacyPhotoData.PHOTO_DATA_ID, dataId); mContactsProvider.insert(Data.CONTENT_URI, mValues); } return count; } public int delete(Uri uri, String selection, String[] selectionArgs) { final int match = sUriMatcher.match(uri); int count = 0; switch (match) { case PEOPLE_ID: count = mContactsProvider.deleteRawContact(ContentUris.parseId(uri), false); break; case ORGANIZATIONS_ID: count = mContactsProvider.deleteData(ContentUris.parseId(uri), ORGANIZATION_MIME_TYPES); break; case CONTACTMETHODS_ID: count = mContactsProvider.deleteData(ContentUris.parseId(uri), CONTACT_METHOD_MIME_TYPES); break; case PHONES_ID: count = mContactsProvider.deleteData(ContentUris.parseId(uri), PHONE_MIME_TYPES); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } return count; } public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, String limit) { ensureDefaultAccount(); final SQLiteDatabase db = mOpenHelper.getReadableDatabase(); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String groupBy = null; final int match = sUriMatcher.match(uri); switch (match) { case PEOPLE: { qb.setTables(LegacyTables.PEOPLE_JOIN_PRESENCE); qb.setProjectionMap(sPeopleProjectionMap); applyRawContactsAccount(qb, uri); break; } case PEOPLE_ID: qb.setTables(LegacyTables.PEOPLE_JOIN_PRESENCE); qb.setProjectionMap(sPeopleProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + People._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_FILTER: { qb.setTables(LegacyTables.PEOPLE_JOIN_PRESENCE); qb.setProjectionMap(sPeopleProjectionMap); applyRawContactsAccount(qb, uri); String filterParam = uri.getPathSegments().get(2); qb.appendWhere(" AND " + People._ID + " IN " + mContactsProvider.getRawContactsByFilterAsNestedQuery(filterParam)); break; } case ORGANIZATIONS: qb.setTables(LegacyTables.ORGANIZATIONS + " organizations"); qb.setProjectionMap(sOrganizationProjectionMap); applyRawContactsAccount(qb, uri); break; case ORGANIZATIONS_ID: qb.setTables(LegacyTables.ORGANIZATIONS + " organizations"); qb.setProjectionMap(sOrganizationProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Organizations._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case CONTACTMETHODS: qb.setTables(LegacyTables.CONTACT_METHODS + " contact_methods"); qb.setProjectionMap(sContactMethodProjectionMap); applyRawContactsAccount(qb, uri); break; case CONTACTMETHODS_ID: qb.setTables(LegacyTables.CONTACT_METHODS + " contact_methods"); qb.setProjectionMap(sContactMethodProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + ContactMethods._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_CONTACTMETHODS: qb.setTables(LegacyTables.CONTACT_METHODS + " contact_methods"); qb.setProjectionMap(sContactMethodProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + ContactMethods.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + ContactMethods.KIND + " IS NOT NULL"); break; case PEOPLE_CONTACTMETHODS_ID: qb.setTables(LegacyTables.CONTACT_METHODS + " contact_methods"); qb.setProjectionMap(sContactMethodProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + ContactMethods.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + ContactMethods._ID + "="); qb.appendWhere(uri.getPathSegments().get(3)); qb.appendWhere(" AND " + ContactMethods.KIND + " IS NOT NULL"); break; case PHONES: qb.setTables(LegacyTables.PHONES + " phones"); qb.setProjectionMap(sPhoneProjectionMap); applyRawContactsAccount(qb, uri); break; case PHONES_ID: qb.setTables(LegacyTables.PHONES + " phones"); qb.setProjectionMap(sPhoneProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Phones._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PHONES_FILTER: qb.setTables(LegacyTables.PHONES + " phones"); qb.setProjectionMap(sPhoneProjectionMap); applyRawContactsAccount(qb, uri); if (uri.getPathSegments().size() > 2) { String filterParam = uri.getLastPathSegment(); qb.appendWhere(" AND person ="); qb.appendWhere(mOpenHelper.buildPhoneLookupAsNestedQuery(filterParam)); } break; case PEOPLE_PHONES: qb.setTables(LegacyTables.PHONES + " phones"); qb.setProjectionMap(sPhoneProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Phones.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_PHONES_ID: qb.setTables(LegacyTables.PHONES + " phones"); qb.setProjectionMap(sPhoneProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Phones.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + android.provider.Contacts.Phones._ID + "="); qb.appendWhere(uri.getPathSegments().get(3)); break; case EXTENSIONS: qb.setTables(LegacyTables.EXTENSIONS + " extensions"); qb.setProjectionMap(sExtensionProjectionMap); applyRawContactsAccount(qb, uri); break; case EXTENSIONS_ID: qb.setTables(LegacyTables.EXTENSIONS + " extensions"); qb.setProjectionMap(sExtensionProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Extensions._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_EXTENSIONS: qb.setTables(LegacyTables.EXTENSIONS + " extensions"); qb.setProjectionMap(sExtensionProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Extensions.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_EXTENSIONS_ID: qb.setTables(LegacyTables.EXTENSIONS + " extensions"); qb.setProjectionMap(sExtensionProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Extensions.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + android.provider.Contacts.Extensions._ID + "="); qb.appendWhere(uri.getPathSegments().get(3)); break; case GROUPS: qb.setTables(LegacyTables.GROUPS + " groups"); qb.setProjectionMap(sGroupProjectionMap); applyGroupAccount(qb, uri); break; case GROUPS_ID: qb.setTables(LegacyTables.GROUPS + " groups"); qb.setProjectionMap(sGroupProjectionMap); applyGroupAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Groups._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case GROUPMEMBERSHIP: qb.setTables(LegacyTables.GROUP_MEMBERSHIP + " groupmembership"); qb.setProjectionMap(sGroupMembershipProjectionMap); applyRawContactsAccount(qb, uri); break; case GROUPMEMBERSHIP_ID: qb.setTables(LegacyTables.GROUP_MEMBERSHIP + " groupmembership"); qb.setProjectionMap(sGroupMembershipProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.GroupMembership._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_GROUPMEMBERSHIP: qb.setTables(LegacyTables.GROUP_MEMBERSHIP + " groupmembership"); qb.setProjectionMap(sGroupMembershipProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.GroupMembership.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_GROUPMEMBERSHIP_ID: qb.setTables(LegacyTables.GROUP_MEMBERSHIP + " groupmembership"); qb.setProjectionMap(sGroupMembershipProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.GroupMembership.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + android.provider.Contacts.GroupMembership._ID + "="); qb.appendWhere(uri.getPathSegments().get(3)); break; case PEOPLE_PHOTO: qb.setTables(LegacyTables.PHOTOS + " photos"); qb.setProjectionMap(sPhotoProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Photos.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); limit = "1"; break; case SEARCH_SUGGESTIONS: // No legacy compatibility for search suggestions return mGlobalSearchSupport.handleSearchSuggestionsQuery(db, uri, limit); case SEARCH_SHORTCUT: { long contactId = ContentUris.parseId(uri); return mGlobalSearchSupport.handleSearchShortcutRefresh(db, contactId, projection); } case DELETED_PEOPLE: case DELETED_GROUPS: throw new UnsupportedOperationException(); default: throw new IllegalArgumentException("Unknown URL " + uri); } // Perform the query and set the notification uri final Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, null, sortOrder, limit); if (c != null) { - c.setNotificationUri(mContext.getContentResolver(), RawContacts.CONTENT_URI); + c.setNotificationUri(mContext.getContentResolver(), + android.provider.Contacts.CONTENT_URI); } return c; } private void applyRawContactsAccount(SQLiteQueryBuilder qb, Uri uri) { StringBuilder sb = new StringBuilder(); sb.append(RawContacts.ACCOUNT_NAME + "="); DatabaseUtils.appendEscapedSQLString(sb, mAccount.name); sb.append(" AND " + RawContacts.ACCOUNT_TYPE + "="); DatabaseUtils.appendEscapedSQLString(sb, mAccount.type); qb.appendWhere(sb.toString()); } private void applyGroupAccount(SQLiteQueryBuilder qb, Uri uri) { StringBuilder sb = new StringBuilder(); sb.append(Groups.ACCOUNT_NAME + "="); DatabaseUtils.appendEscapedSQLString(sb, mAccount.name); sb.append(" AND " + Groups.ACCOUNT_TYPE + "="); DatabaseUtils.appendEscapedSQLString(sb, mAccount.type); qb.appendWhere(sb.toString()); } /** * Called when a change has been made. * * @param uri the uri that the change was made to */ private void onChange(Uri uri) { mContext.getContentResolver().notifyChange(android.provider.Contacts.CONTENT_URI, null); } public String getType(Uri uri) { int match = sUriMatcher.match(uri); switch (match) { case EXTENSIONS: case PEOPLE_EXTENSIONS: return Extensions.CONTENT_TYPE; case EXTENSIONS_ID: case PEOPLE_EXTENSIONS_ID: return Extensions.CONTENT_ITEM_TYPE; case PEOPLE: return "vnd.android.cursor.dir/person"; case PEOPLE_ID: return "vnd.android.cursor.item/person"; case PEOPLE_PHONES: return "vnd.android.cursor.dir/phone"; case PEOPLE_PHONES_ID: return "vnd.android.cursor.item/phone"; case PEOPLE_CONTACTMETHODS: return "vnd.android.cursor.dir/contact-methods"; case PEOPLE_CONTACTMETHODS_ID: return getContactMethodType(uri); case PHONES: return "vnd.android.cursor.dir/phone"; case PHONES_ID: return "vnd.android.cursor.item/phone"; case PHONES_FILTER: return "vnd.android.cursor.dir/phone"; case PHOTOS_ID: return "vnd.android.cursor.item/photo"; case PHOTOS: return "vnd.android.cursor.dir/photo"; case PEOPLE_PHOTO: return "vnd.android.cursor.item/photo"; case CONTACTMETHODS: return "vnd.android.cursor.dir/contact-methods"; case CONTACTMETHODS_ID: return getContactMethodType(uri); case ORGANIZATIONS: return "vnd.android.cursor.dir/organizations"; case ORGANIZATIONS_ID: return "vnd.android.cursor.item/organization"; case SEARCH_SUGGESTIONS: return SearchManager.SUGGEST_MIME_TYPE; case SEARCH_SHORTCUT: return SearchManager.SHORTCUT_MIME_TYPE; default: throw new IllegalArgumentException("Unknown URI"); } } private String getContactMethodType(Uri url) { String mime = null; Cursor c = query(url, new String[] {ContactMethods.KIND}, null, null, null, null); if (c != null) { try { if (c.moveToFirst()) { int kind = c.getInt(0); switch (kind) { case Contacts.KIND_EMAIL: mime = "vnd.android.cursor.item/email"; break; case Contacts.KIND_IM: mime = "vnd.android.cursor.item/jabber-im"; break; case Contacts.KIND_POSTAL: mime = "vnd.android.cursor.item/postal-address"; break; } } } finally { c.close(); } } return mime; } }
true
true
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, String limit) { ensureDefaultAccount(); final SQLiteDatabase db = mOpenHelper.getReadableDatabase(); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String groupBy = null; final int match = sUriMatcher.match(uri); switch (match) { case PEOPLE: { qb.setTables(LegacyTables.PEOPLE_JOIN_PRESENCE); qb.setProjectionMap(sPeopleProjectionMap); applyRawContactsAccount(qb, uri); break; } case PEOPLE_ID: qb.setTables(LegacyTables.PEOPLE_JOIN_PRESENCE); qb.setProjectionMap(sPeopleProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + People._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_FILTER: { qb.setTables(LegacyTables.PEOPLE_JOIN_PRESENCE); qb.setProjectionMap(sPeopleProjectionMap); applyRawContactsAccount(qb, uri); String filterParam = uri.getPathSegments().get(2); qb.appendWhere(" AND " + People._ID + " IN " + mContactsProvider.getRawContactsByFilterAsNestedQuery(filterParam)); break; } case ORGANIZATIONS: qb.setTables(LegacyTables.ORGANIZATIONS + " organizations"); qb.setProjectionMap(sOrganizationProjectionMap); applyRawContactsAccount(qb, uri); break; case ORGANIZATIONS_ID: qb.setTables(LegacyTables.ORGANIZATIONS + " organizations"); qb.setProjectionMap(sOrganizationProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Organizations._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case CONTACTMETHODS: qb.setTables(LegacyTables.CONTACT_METHODS + " contact_methods"); qb.setProjectionMap(sContactMethodProjectionMap); applyRawContactsAccount(qb, uri); break; case CONTACTMETHODS_ID: qb.setTables(LegacyTables.CONTACT_METHODS + " contact_methods"); qb.setProjectionMap(sContactMethodProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + ContactMethods._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_CONTACTMETHODS: qb.setTables(LegacyTables.CONTACT_METHODS + " contact_methods"); qb.setProjectionMap(sContactMethodProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + ContactMethods.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + ContactMethods.KIND + " IS NOT NULL"); break; case PEOPLE_CONTACTMETHODS_ID: qb.setTables(LegacyTables.CONTACT_METHODS + " contact_methods"); qb.setProjectionMap(sContactMethodProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + ContactMethods.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + ContactMethods._ID + "="); qb.appendWhere(uri.getPathSegments().get(3)); qb.appendWhere(" AND " + ContactMethods.KIND + " IS NOT NULL"); break; case PHONES: qb.setTables(LegacyTables.PHONES + " phones"); qb.setProjectionMap(sPhoneProjectionMap); applyRawContactsAccount(qb, uri); break; case PHONES_ID: qb.setTables(LegacyTables.PHONES + " phones"); qb.setProjectionMap(sPhoneProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Phones._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PHONES_FILTER: qb.setTables(LegacyTables.PHONES + " phones"); qb.setProjectionMap(sPhoneProjectionMap); applyRawContactsAccount(qb, uri); if (uri.getPathSegments().size() > 2) { String filterParam = uri.getLastPathSegment(); qb.appendWhere(" AND person ="); qb.appendWhere(mOpenHelper.buildPhoneLookupAsNestedQuery(filterParam)); } break; case PEOPLE_PHONES: qb.setTables(LegacyTables.PHONES + " phones"); qb.setProjectionMap(sPhoneProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Phones.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_PHONES_ID: qb.setTables(LegacyTables.PHONES + " phones"); qb.setProjectionMap(sPhoneProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Phones.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + android.provider.Contacts.Phones._ID + "="); qb.appendWhere(uri.getPathSegments().get(3)); break; case EXTENSIONS: qb.setTables(LegacyTables.EXTENSIONS + " extensions"); qb.setProjectionMap(sExtensionProjectionMap); applyRawContactsAccount(qb, uri); break; case EXTENSIONS_ID: qb.setTables(LegacyTables.EXTENSIONS + " extensions"); qb.setProjectionMap(sExtensionProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Extensions._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_EXTENSIONS: qb.setTables(LegacyTables.EXTENSIONS + " extensions"); qb.setProjectionMap(sExtensionProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Extensions.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_EXTENSIONS_ID: qb.setTables(LegacyTables.EXTENSIONS + " extensions"); qb.setProjectionMap(sExtensionProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Extensions.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + android.provider.Contacts.Extensions._ID + "="); qb.appendWhere(uri.getPathSegments().get(3)); break; case GROUPS: qb.setTables(LegacyTables.GROUPS + " groups"); qb.setProjectionMap(sGroupProjectionMap); applyGroupAccount(qb, uri); break; case GROUPS_ID: qb.setTables(LegacyTables.GROUPS + " groups"); qb.setProjectionMap(sGroupProjectionMap); applyGroupAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Groups._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case GROUPMEMBERSHIP: qb.setTables(LegacyTables.GROUP_MEMBERSHIP + " groupmembership"); qb.setProjectionMap(sGroupMembershipProjectionMap); applyRawContactsAccount(qb, uri); break; case GROUPMEMBERSHIP_ID: qb.setTables(LegacyTables.GROUP_MEMBERSHIP + " groupmembership"); qb.setProjectionMap(sGroupMembershipProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.GroupMembership._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_GROUPMEMBERSHIP: qb.setTables(LegacyTables.GROUP_MEMBERSHIP + " groupmembership"); qb.setProjectionMap(sGroupMembershipProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.GroupMembership.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_GROUPMEMBERSHIP_ID: qb.setTables(LegacyTables.GROUP_MEMBERSHIP + " groupmembership"); qb.setProjectionMap(sGroupMembershipProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.GroupMembership.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + android.provider.Contacts.GroupMembership._ID + "="); qb.appendWhere(uri.getPathSegments().get(3)); break; case PEOPLE_PHOTO: qb.setTables(LegacyTables.PHOTOS + " photos"); qb.setProjectionMap(sPhotoProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Photos.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); limit = "1"; break; case SEARCH_SUGGESTIONS: // No legacy compatibility for search suggestions return mGlobalSearchSupport.handleSearchSuggestionsQuery(db, uri, limit); case SEARCH_SHORTCUT: { long contactId = ContentUris.parseId(uri); return mGlobalSearchSupport.handleSearchShortcutRefresh(db, contactId, projection); } case DELETED_PEOPLE: case DELETED_GROUPS: throw new UnsupportedOperationException(); default: throw new IllegalArgumentException("Unknown URL " + uri); } // Perform the query and set the notification uri final Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, null, sortOrder, limit); if (c != null) { c.setNotificationUri(mContext.getContentResolver(), RawContacts.CONTENT_URI); } return c; }
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, String limit) { ensureDefaultAccount(); final SQLiteDatabase db = mOpenHelper.getReadableDatabase(); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String groupBy = null; final int match = sUriMatcher.match(uri); switch (match) { case PEOPLE: { qb.setTables(LegacyTables.PEOPLE_JOIN_PRESENCE); qb.setProjectionMap(sPeopleProjectionMap); applyRawContactsAccount(qb, uri); break; } case PEOPLE_ID: qb.setTables(LegacyTables.PEOPLE_JOIN_PRESENCE); qb.setProjectionMap(sPeopleProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + People._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_FILTER: { qb.setTables(LegacyTables.PEOPLE_JOIN_PRESENCE); qb.setProjectionMap(sPeopleProjectionMap); applyRawContactsAccount(qb, uri); String filterParam = uri.getPathSegments().get(2); qb.appendWhere(" AND " + People._ID + " IN " + mContactsProvider.getRawContactsByFilterAsNestedQuery(filterParam)); break; } case ORGANIZATIONS: qb.setTables(LegacyTables.ORGANIZATIONS + " organizations"); qb.setProjectionMap(sOrganizationProjectionMap); applyRawContactsAccount(qb, uri); break; case ORGANIZATIONS_ID: qb.setTables(LegacyTables.ORGANIZATIONS + " organizations"); qb.setProjectionMap(sOrganizationProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Organizations._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case CONTACTMETHODS: qb.setTables(LegacyTables.CONTACT_METHODS + " contact_methods"); qb.setProjectionMap(sContactMethodProjectionMap); applyRawContactsAccount(qb, uri); break; case CONTACTMETHODS_ID: qb.setTables(LegacyTables.CONTACT_METHODS + " contact_methods"); qb.setProjectionMap(sContactMethodProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + ContactMethods._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_CONTACTMETHODS: qb.setTables(LegacyTables.CONTACT_METHODS + " contact_methods"); qb.setProjectionMap(sContactMethodProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + ContactMethods.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + ContactMethods.KIND + " IS NOT NULL"); break; case PEOPLE_CONTACTMETHODS_ID: qb.setTables(LegacyTables.CONTACT_METHODS + " contact_methods"); qb.setProjectionMap(sContactMethodProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + ContactMethods.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + ContactMethods._ID + "="); qb.appendWhere(uri.getPathSegments().get(3)); qb.appendWhere(" AND " + ContactMethods.KIND + " IS NOT NULL"); break; case PHONES: qb.setTables(LegacyTables.PHONES + " phones"); qb.setProjectionMap(sPhoneProjectionMap); applyRawContactsAccount(qb, uri); break; case PHONES_ID: qb.setTables(LegacyTables.PHONES + " phones"); qb.setProjectionMap(sPhoneProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Phones._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PHONES_FILTER: qb.setTables(LegacyTables.PHONES + " phones"); qb.setProjectionMap(sPhoneProjectionMap); applyRawContactsAccount(qb, uri); if (uri.getPathSegments().size() > 2) { String filterParam = uri.getLastPathSegment(); qb.appendWhere(" AND person ="); qb.appendWhere(mOpenHelper.buildPhoneLookupAsNestedQuery(filterParam)); } break; case PEOPLE_PHONES: qb.setTables(LegacyTables.PHONES + " phones"); qb.setProjectionMap(sPhoneProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Phones.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_PHONES_ID: qb.setTables(LegacyTables.PHONES + " phones"); qb.setProjectionMap(sPhoneProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Phones.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + android.provider.Contacts.Phones._ID + "="); qb.appendWhere(uri.getPathSegments().get(3)); break; case EXTENSIONS: qb.setTables(LegacyTables.EXTENSIONS + " extensions"); qb.setProjectionMap(sExtensionProjectionMap); applyRawContactsAccount(qb, uri); break; case EXTENSIONS_ID: qb.setTables(LegacyTables.EXTENSIONS + " extensions"); qb.setProjectionMap(sExtensionProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Extensions._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_EXTENSIONS: qb.setTables(LegacyTables.EXTENSIONS + " extensions"); qb.setProjectionMap(sExtensionProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Extensions.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_EXTENSIONS_ID: qb.setTables(LegacyTables.EXTENSIONS + " extensions"); qb.setProjectionMap(sExtensionProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Extensions.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + android.provider.Contacts.Extensions._ID + "="); qb.appendWhere(uri.getPathSegments().get(3)); break; case GROUPS: qb.setTables(LegacyTables.GROUPS + " groups"); qb.setProjectionMap(sGroupProjectionMap); applyGroupAccount(qb, uri); break; case GROUPS_ID: qb.setTables(LegacyTables.GROUPS + " groups"); qb.setProjectionMap(sGroupProjectionMap); applyGroupAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Groups._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case GROUPMEMBERSHIP: qb.setTables(LegacyTables.GROUP_MEMBERSHIP + " groupmembership"); qb.setProjectionMap(sGroupMembershipProjectionMap); applyRawContactsAccount(qb, uri); break; case GROUPMEMBERSHIP_ID: qb.setTables(LegacyTables.GROUP_MEMBERSHIP + " groupmembership"); qb.setProjectionMap(sGroupMembershipProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.GroupMembership._ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_GROUPMEMBERSHIP: qb.setTables(LegacyTables.GROUP_MEMBERSHIP + " groupmembership"); qb.setProjectionMap(sGroupMembershipProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.GroupMembership.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); break; case PEOPLE_GROUPMEMBERSHIP_ID: qb.setTables(LegacyTables.GROUP_MEMBERSHIP + " groupmembership"); qb.setProjectionMap(sGroupMembershipProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.GroupMembership.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + android.provider.Contacts.GroupMembership._ID + "="); qb.appendWhere(uri.getPathSegments().get(3)); break; case PEOPLE_PHOTO: qb.setTables(LegacyTables.PHOTOS + " photos"); qb.setProjectionMap(sPhotoProjectionMap); applyRawContactsAccount(qb, uri); qb.appendWhere(" AND " + android.provider.Contacts.Photos.PERSON_ID + "="); qb.appendWhere(uri.getPathSegments().get(1)); limit = "1"; break; case SEARCH_SUGGESTIONS: // No legacy compatibility for search suggestions return mGlobalSearchSupport.handleSearchSuggestionsQuery(db, uri, limit); case SEARCH_SHORTCUT: { long contactId = ContentUris.parseId(uri); return mGlobalSearchSupport.handleSearchShortcutRefresh(db, contactId, projection); } case DELETED_PEOPLE: case DELETED_GROUPS: throw new UnsupportedOperationException(); default: throw new IllegalArgumentException("Unknown URL " + uri); } // Perform the query and set the notification uri final Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, null, sortOrder, limit); if (c != null) { c.setNotificationUri(mContext.getContentResolver(), android.provider.Contacts.CONTENT_URI); } return c; }
diff --git a/grisu-core/src/main/java/grisu/backend/model/job/gt5/Gram5JobListener.java b/grisu-core/src/main/java/grisu/backend/model/job/gt5/Gram5JobListener.java index 0e428c86..db3c1a28 100644 --- a/grisu-core/src/main/java/grisu/backend/model/job/gt5/Gram5JobListener.java +++ b/grisu-core/src/main/java/grisu/backend/model/job/gt5/Gram5JobListener.java @@ -1,46 +1,56 @@ package grisu.backend.model.job.gt5; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.globus.gram.GramJob; import org.globus.gram.GramJobListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Gram5JobListener implements GramJobListener { static final Logger myLogger = LoggerFactory.getLogger(GT5Submitter.class .getName()); private static Gram5JobListener l = new Gram5JobListener(); public static Gram5JobListener getJobListener() { return l; } private final Map<String, Integer> statuses; private final Map<String, Integer> errors; private Gram5JobListener() { statuses = Collections.synchronizedMap(new HashMap<String, Integer>()); errors = Collections.synchronizedMap(new HashMap<String, Integer>()); } public Integer getError(String handle) { return errors.get(handle); } public Integer getStatus(String handle) { return statuses.get(handle); } public void statusChanged(GramJob job) { - myLogger.debug("job status changed to " + job.getStatus()); - statuses.put(job.getIDAsString(), job.getStatus()); - errors.put(job.getIDAsString(), job.getError()); + int jobStatus = job.getStatus(); + String jobId = job.getIDAsString(); + myLogger.debug("job status changed to " + jobStatus); + statuses.put(jobId, jobStatus); + errors.put(jobId, job.getError()); + try { + if ((jobStatus == GramJob.STATUS_DONE) || (jobStatus == GramJob.STATUS_FAILED)){ + job.signal(GramJob.SIGNAL_COMMIT_END); + } + } catch (Exception e) { + String state = job.getStatusAsString(); + myLogger.error("Failed to send COMMIT_END to job " + jobId + " in state " + state, e); + } } }
true
true
public void statusChanged(GramJob job) { myLogger.debug("job status changed to " + job.getStatus()); statuses.put(job.getIDAsString(), job.getStatus()); errors.put(job.getIDAsString(), job.getError()); }
public void statusChanged(GramJob job) { int jobStatus = job.getStatus(); String jobId = job.getIDAsString(); myLogger.debug("job status changed to " + jobStatus); statuses.put(jobId, jobStatus); errors.put(jobId, job.getError()); try { if ((jobStatus == GramJob.STATUS_DONE) || (jobStatus == GramJob.STATUS_FAILED)){ job.signal(GramJob.SIGNAL_COMMIT_END); } } catch (Exception e) { String state = job.getStatusAsString(); myLogger.error("Failed to send COMMIT_END to job " + jobId + " in state " + state, e); } }
diff --git a/library/src/org/deri/any23/rdf/Any23ValueFactoryWrapper.java b/library/src/org/deri/any23/rdf/Any23ValueFactoryWrapper.java index 8e822f62..c2c4c5de 100644 --- a/library/src/org/deri/any23/rdf/Any23ValueFactoryWrapper.java +++ b/library/src/org/deri/any23/rdf/Any23ValueFactoryWrapper.java @@ -1,177 +1,177 @@ package org.deri.any23.rdf; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.datatype.XMLGregorianCalendar; import org.openrdf.model.BNode; import org.openrdf.model.Literal; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.model.ValueFactory; public class Any23ValueFactoryWrapper implements ValueFactory{ private static final Logger logger = Logger.getLogger(Any23ValueFactoryWrapper.class.getName()); private final ValueFactory _vFactory; public Any23ValueFactoryWrapper(final ValueFactory vFactory) { _vFactory = vFactory; } @Override public BNode createBNode() { return _vFactory.createBNode(); } @Override public BNode createBNode(String arg0) { return _vFactory.createBNode(arg0); } @Override public Literal createLiteral(String arg0) { return _vFactory.createLiteral(arg0); } @Override public Literal createLiteral(boolean arg0) { return _vFactory.createLiteral(arg0); } @Override public Literal createLiteral(byte arg0) { return _vFactory.createLiteral(arg0); } @Override public Literal createLiteral(short arg0) { return _vFactory.createLiteral(arg0); } @Override public Literal createLiteral(int arg0) { return _vFactory.createLiteral(arg0); } @Override public Literal createLiteral(long arg0) { return _vFactory.createLiteral(arg0); } @Override public Literal createLiteral(float arg0) { return _vFactory.createLiteral(arg0); } @Override public Literal createLiteral(double arg0) { return _vFactory.createLiteral(arg0); } @Override public Literal createLiteral(XMLGregorianCalendar arg0) { return _vFactory.createLiteral(arg0); } @Override public Literal createLiteral(String arg0, String arg1) { return _vFactory.createLiteral(arg0,arg1); } @Override public Literal createLiteral(String arg0, URI arg1) { return _vFactory.createLiteral(arg0,arg1); } @Override public Statement createStatement(Resource arg0, URI arg1, Value arg2) { return _vFactory.createStatement(arg0,arg1,arg2); } @Override public Statement createStatement(Resource arg0, URI arg1, Value arg2, Resource arg3) { return _vFactory.createStatement(arg0,arg1,arg2,arg3); } @Override /** * @param arg0 * @return a valid sesame URI or null if any exception occured */ public URI createURI(String arg0) { try{ return _vFactory.createURI(escapeURI(arg0)); }catch(Exception e){ logger.log(Level.WARNING,e.getMessage()); return null; } } /** * * @return a valid sesame URI or null if any exception occured */ public URI createURI(String arg0, String arg1) { try{ return _vFactory.createURI(escapeURI(arg0),arg1); }catch(Exception e){ logger.log(Level.WARNING,e.getMessage()); return null; } } /** *These appear to be good rules: * * Remove whitespace or '\' or '"' in beginning and end * Replace space with %20 * Drop the triple if it matches this regex (only protocol): ^[a-zA-Z0-9]+:(//)?$ * Drop the triple if it matches this regex: ^javascript: * Truncate ">.*$ from end of lines (Neko didn't quite manage to fix broken markup) * Drop the triple if any of these appear in the URL: <>[]|*{}"<>\ */ private String escapeURI(String unescapedURI) { // Remove starting and ending whitespace String escapedURI = unescapedURI.trim(); //Replace space with %20 escapedURI = escapedURI.replaceAll(" ", "%20"); //strip linebreaks escapedURI = escapedURI.replaceAll("\n", ""); //'Remove starting "\" or '"' if(escapedURI.startsWith("\\") || escapedURI.startsWith("\"")) escapedURI = escapedURI.substring(1); //Remove ending "\" or '"' if(escapedURI.endsWith("\\") || escapedURI.endsWith("\"")) escapedURI = escapedURI.substring(0,escapedURI.length()-1); //Drop the triple if it matches this regex (only protocol): ^[a-zA-Z0-9]+:(//)?$ if(escapedURI.matches("^[a-zA-Z0-9]+:(//)?$")) throw new IllegalArgumentException("no authority in URI"); //Drop the triple if it matches this regex: ^javascript: if(escapedURI.matches("^javascript:")) throw new IllegalArgumentException("URI starts with javascript"); - if(!escapedURI.matches("^[a-zA-Z0-9]+:(//)")) throw new IllegalArgumentException("no scheme in URI"); + if(escapedURI.matches("^[a-zA-Z0-9]+:(//)")) throw new IllegalArgumentException("no scheme in URI"); // //stripHTML // escapedURI = escapedURI.replaceAll("\\<.*?\\>", ""); //>.*$ from end of lines (Neko didn't quite manage to fix broken markup) escapedURI = escapedURI.replaceAll(">.*$", ""); //Drop the triple if any of these appear in the URL: <>[]|*{}"<>\ if(escapedURI.matches("<>\\[\\]|\\*\\{\\}\"\\\\")) throw new IllegalArgumentException("Invalid character in URI"); return escapedURI; } }
true
true
private String escapeURI(String unescapedURI) { // Remove starting and ending whitespace String escapedURI = unescapedURI.trim(); //Replace space with %20 escapedURI = escapedURI.replaceAll(" ", "%20"); //strip linebreaks escapedURI = escapedURI.replaceAll("\n", ""); //'Remove starting "\" or '"' if(escapedURI.startsWith("\\") || escapedURI.startsWith("\"")) escapedURI = escapedURI.substring(1); //Remove ending "\" or '"' if(escapedURI.endsWith("\\") || escapedURI.endsWith("\"")) escapedURI = escapedURI.substring(0,escapedURI.length()-1); //Drop the triple if it matches this regex (only protocol): ^[a-zA-Z0-9]+:(//)?$ if(escapedURI.matches("^[a-zA-Z0-9]+:(//)?$")) throw new IllegalArgumentException("no authority in URI"); //Drop the triple if it matches this regex: ^javascript: if(escapedURI.matches("^javascript:")) throw new IllegalArgumentException("URI starts with javascript"); if(!escapedURI.matches("^[a-zA-Z0-9]+:(//)")) throw new IllegalArgumentException("no scheme in URI"); // //stripHTML // escapedURI = escapedURI.replaceAll("\\<.*?\\>", ""); //>.*$ from end of lines (Neko didn't quite manage to fix broken markup) escapedURI = escapedURI.replaceAll(">.*$", ""); //Drop the triple if any of these appear in the URL: <>[]|*{}"<>\ if(escapedURI.matches("<>\\[\\]|\\*\\{\\}\"\\\\")) throw new IllegalArgumentException("Invalid character in URI"); return escapedURI; }
private String escapeURI(String unescapedURI) { // Remove starting and ending whitespace String escapedURI = unescapedURI.trim(); //Replace space with %20 escapedURI = escapedURI.replaceAll(" ", "%20"); //strip linebreaks escapedURI = escapedURI.replaceAll("\n", ""); //'Remove starting "\" or '"' if(escapedURI.startsWith("\\") || escapedURI.startsWith("\"")) escapedURI = escapedURI.substring(1); //Remove ending "\" or '"' if(escapedURI.endsWith("\\") || escapedURI.endsWith("\"")) escapedURI = escapedURI.substring(0,escapedURI.length()-1); //Drop the triple if it matches this regex (only protocol): ^[a-zA-Z0-9]+:(//)?$ if(escapedURI.matches("^[a-zA-Z0-9]+:(//)?$")) throw new IllegalArgumentException("no authority in URI"); //Drop the triple if it matches this regex: ^javascript: if(escapedURI.matches("^javascript:")) throw new IllegalArgumentException("URI starts with javascript"); if(escapedURI.matches("^[a-zA-Z0-9]+:(//)")) throw new IllegalArgumentException("no scheme in URI"); // //stripHTML // escapedURI = escapedURI.replaceAll("\\<.*?\\>", ""); //>.*$ from end of lines (Neko didn't quite manage to fix broken markup) escapedURI = escapedURI.replaceAll(">.*$", ""); //Drop the triple if any of these appear in the URL: <>[]|*{}"<>\ if(escapedURI.matches("<>\\[\\]|\\*\\{\\}\"\\\\")) throw new IllegalArgumentException("Invalid character in URI"); return escapedURI; }
diff --git a/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/utils/UIUtils.java b/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/utils/UIUtils.java index 4106215..2b7f847 100644 --- a/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/utils/UIUtils.java +++ b/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/utils/UIUtils.java @@ -1,424 +1,426 @@ // $codepro.audit.disable com.instantiations.assist.eclipse.analysis.audit.rule.effectivejava.alwaysOverridetoString.alwaysOverrideToString, com.instantiations.assist.eclipse.analysis.deserializeabilitySecurity, com.instantiations.assist.eclipse.analysis.disallowReturnMutable, com.instantiations.assist.eclipse.analysis.enforceCloneableUsageSecurity /******************************************************************************* * Copyright (c) 2010 Ericsson Research Canada * * 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 * * Description: * * This class provides general utility methods used in the UI implementation * * Contributors: * Sebastien Dubois - Created for Mylyn Review R4E project * ******************************************************************************/ package org.eclipse.mylyn.reviews.r4e.ui.internal.utils; import java.io.File; import java.lang.reflect.Field; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import org.eclipse.compare.ICompareNavigator; import org.eclipse.compare.contentmergeviewer.TextMergeViewer; import org.eclipse.compare.internal.CompareContentViewerSwitchingPane; import org.eclipse.compare.internal.CompareEditorInputNavigator; import org.eclipse.compare.internal.MergeSourceViewer; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.mylyn.reviews.r4e.core.model.R4EParticipant; import org.eclipse.mylyn.reviews.r4e.core.model.drules.R4EDesignRuleClass; import org.eclipse.mylyn.reviews.r4e.core.model.drules.R4EDesignRuleRank; import org.eclipse.mylyn.reviews.r4e.core.model.serial.impl.OutOfSyncException; import org.eclipse.mylyn.reviews.r4e.core.model.serial.impl.ResourceHandlingException; import org.eclipse.mylyn.reviews.r4e.core.rfs.spi.ReviewsFileStorageException; import org.eclipse.mylyn.reviews.r4e.core.versions.ReviewVersionsException; import org.eclipse.mylyn.reviews.r4e.ui.Activator; import org.eclipse.mylyn.reviews.r4e.ui.internal.editors.R4ECompareEditorInput; import org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement; import org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIPosition; import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIAnomalyBasic; import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIComment; import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIContent; import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIModelController; import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUITextPosition; import org.eclipse.mylyn.reviews.userSearch.userInfo.IUserInfo; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.texteditor.ITextEditor; /** * @author lmcdubo * @version $Revision: 1.0 $ */ public class UIUtils { // ------------------------------------------------------------------------ // Constants // ------------------------------------------------------------------------ //NOTE: THese values are used in the hack to change cursor position in compare editor. /** * Field COMPARE_EDITOR_TEXT_CLASS_NAME. (value is ""org.eclipse.compare.contentmergeviewer.TextMergeViewer"") */ private static final String COMPARE_EDITOR_TEXT_CLASS_NAME = "org.eclipse.compare.contentmergeviewer.TextMergeViewer"; /** * Field COMPARE_EDITOR_TEXT_FIELD_LEFT. (value is ""fLeft"") */ private static final String COMPARE_EDITOR_TEXT_FIELD_LEFT = "fLeft"; /** * Field DEFAULT_OBJECT_CLASS_NAME. (value is ""Object"") */ private static final String DEFAULT_OBJECT_CLASS_NAME = "Object"; // ------------------------------------------------------------------------ // Methods // ------------------------------------------------------------------------ /** * Load the current image and add it to the image registry * * @param url * - the localtion of the image to load * @return Image */ public static Image loadIcon(String url) { final Activator plugin = Activator.getDefault(); Image icon = plugin.getImageRegistry().get(url); if (null == icon) { final URL imageURL = plugin.getBundle().getEntry(url); final ImageDescriptor descriptor = ImageDescriptor.createFromURL(imageURL); icon = descriptor.createImage(); plugin.getImageRegistry().put(url, icon); } return icon; } /** * Method displayResourceErrorDialog. * * @param e * ResourceHandlingException */ public static void displayResourceErrorDialog(ResourceHandlingException e) { Activator.Ftracer.traceError("Exception: " + e.toString() + " (" + e.getMessage() + ")"); Activator.getDefault().logError("Exception: " + e.toString(), e); final ErrorDialog dialog = new ErrorDialog(null, R4EUIConstants.DIALOG_TITLE_ERROR, "Resource Error Detected", new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, e.getMessage(), e), IStatus.ERROR); dialog.open(); } /** * Method displaySyncErrorDialog. * * @param e * OutOfSyncException */ public static void displaySyncErrorDialog(OutOfSyncException e) { Activator.Ftracer.traceWarning("Exception: " + e.toString() + " (" + e.getMessage() + ")"); final ErrorDialog dialog = new ErrorDialog( null, R4EUIConstants.DIALOG_TITLE_ERROR, "Synchronization Error Detected" + "Please refresh the review navigator view and try the command again", new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, e.getMessage(), e), IStatus.ERROR); dialog.open(); // TODO later we will want to do this automatically } /** * Method displayVersionErrorDialog. * * @param e * ReviewVersionsException */ public static void displayVersionErrorDialog(ReviewVersionsException e) { Activator.Ftracer.traceError("Exception: " + e.toString() + " (" + e.getMessage() + ")"); Activator.getDefault().logError("Exception: " + e.toString(), e); final ErrorDialog dialog = new ErrorDialog(null, R4EUIConstants.DIALOG_TITLE_ERROR, "Version Error Detected", new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, e.getMessage(), e), IStatus.ERROR); dialog.open(); } /** * Method displayVersionErrorDialog. * * @param e * ReviewVersionsException */ public static void displayReviewsFileStorageErrorDialog(ReviewsFileStorageException e) { Activator.Ftracer.traceError("Exception: " + e.toString() + " (" + e.getMessage() + ")"); Activator.getDefault().logError("Exception: " + e.toString(), e); final ErrorDialog dialog = new ErrorDialog(null, R4EUIConstants.DIALOG_TITLE_ERROR, "Local Review Storage Error Detected", new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, e.getMessage(), e), IStatus.ERROR); dialog.open(); } /** * Method displayCoreErrorDialog. * * @param e * CoreException */ public static void displayCoreErrorDialog(CoreException e) { Activator.Ftracer.traceError("Exception: " + e.toString() + " (" + e.getMessage() + ")"); Activator.getDefault().logError("Exception: " + e.toString(), e); final ErrorDialog dialog = new ErrorDialog(null, R4EUIConstants.DIALOG_TITLE_ERROR, "Eclipse Runtime Core Error Detected", new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, e.getMessage(), e), IStatus.ERROR); dialog.open(); } /** * Method isFilterPreferenceSet. * * @param aFilterSet * Object * @return boolean */ public static boolean isFilterPreferenceSet(Object aFilterSet) { if (null != aFilterSet && aFilterSet.toString().equals(R4EUIConstants.VALUE_TRUE_STR)) { return true; } return false; } /** * Method parseStringList. * * @param aStringList * String * @return List<String> */ public static List<String> parseStringList(String aStringList) { final List<String> stringArray = new ArrayList<String>(); if (null != aStringList) { final StringTokenizer st = new StringTokenizer(aStringList, File.pathSeparator + System.getProperty("line.separator")); while (st.hasMoreElements()) { stringArray.add((String) st.nextElement()); } } return stringArray; } /** * Method addTabbedPropertiesTextResizeListener. Resizes a Text widget in a ScrolledComposite to fit the text being * typed. It also adds scrollbars to the composite as needed * * @param aText * Text - The Text widget */ //TODO this only works for flatFormComposites and not vanilla ones. For now this is not a big deal, but we will want to review it later //A new auto-resizable text widget class should be created for this eventually public static void addTabbedPropertiesTextResizeListener(final Text aText) { aText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { //compute new Text field size final Point newSize = aText.computeSize(SWT.DEFAULT, SWT.DEFAULT); final Point oldSize = aText.getSize(); final int heightDiff = newSize.y - oldSize.y; if (0 != heightDiff) { aText.setSize(newSize); aText.getParent().layout(); //Set scrollable height so that scrollbar appear if needed final ScrolledComposite scrolledParent = (ScrolledComposite) aText.getParent() .getParent() .getParent() .getParent() .getParent() .getParent(); scrolledParent.setMinSize(aText.getParent().computeSize(SWT.DEFAULT, SWT.DEFAULT)); //If the text falls outside of the display scroll down to reposition if ((aText.getLocation().y + aText.getCaretLocation().y + aText.getLineHeight()) > (scrolledParent.getClientArea().y + scrolledParent.getClientArea().height)) { final Point origin = scrolledParent.getOrigin(); origin.y += heightDiff; scrolledParent.setOrigin(origin); } } } }); } /** * Method mapParticipantToIndex. * * @param aParticipant * String * @return int */ public static int mapParticipantToIndex(String aParticipant) { if (null == R4EUIModelController.getActiveReview()) { return 0; } final List<R4EParticipant> participants = R4EUIModelController.getActiveReview().getParticipants(); final int numParticipants = participants.size(); for (int i = 0; i < numParticipants; i++) { if (participants.get(i).getId().equals(aParticipant)) { return i; } } return R4EUIConstants.INVALID_VALUE; //should never happen } /** * Method getClassFromString. * * @param aClass * String * @return R4ECommentClass */ public static R4EDesignRuleClass getClassFromString(String aClass) { if (aClass.equals(R4EUIConstants.ANOMALY_CLASS_ERRONEOUS)) { return R4EDesignRuleClass.R4E_CLASS_ERRONEOUS; } else if (aClass.equals(R4EUIConstants.ANOMALY_CLASS_SUPERFLUOUS)) { return R4EDesignRuleClass.R4E_CLASS_SUPERFLUOUS; } else if (aClass.equals(R4EUIConstants.ANOMALY_CLASS_IMPROVEMENT)) { return R4EDesignRuleClass.R4E_CLASS_IMPROVEMENT; } else if (aClass.equals(R4EUIConstants.ANOMALY_CLASS_QUESTION)) { return R4EDesignRuleClass.R4E_CLASS_QUESTION; } else { return null; //should never happen } } /** * Method getRankFromString. * * @param aRank * String * @return R4EAnomalyRank */ public static R4EDesignRuleRank getRankFromString(String aRank) { if (aRank.equals(R4EUIConstants.ANOMALY_RANK_NONE)) { return R4EDesignRuleRank.R4E_RANK_NONE; } else if (aRank.equals(R4EUIConstants.ANOMALY_RANK_MINOR)) { return R4EDesignRuleRank.R4E_RANK_MINOR; } else if (aRank.equals(R4EUIConstants.ANOMALY_RANK_MAJOR)) { return R4EDesignRuleRank.R4E_RANK_MAJOR; } else { return null; //should never happen } } /** * Method getClasses. * * @return String[] */ public static String[] getClasses() { return R4EUIConstants.CLASS_VALUES; } /** * Method getRanks. * * @return String[] */ public static String[] getRanks() { return R4EUIConstants.RANK_VALUES; } /** * Method buildUserDetailsString. * * @param aUserInfo * IUserInfo * @return String */ public static String buildUserDetailsString(IUserInfo aUserInfo) { final StringBuffer tempStr = new StringBuffer(100); final int numAttributeTypes = aUserInfo.getAttributeTypes().length; for (int i = 0; i < numAttributeTypes; i++) { tempStr.append(aUserInfo.getAttributeTypes()[i] + " = " + aUserInfo.getAttributeValues()[i] + System.getProperty("line.separator")); } return tempStr.toString(); } /** * Method selectElementInEditor. * * @param aInput * R4ECompareEditorInput */ public static void selectElementInEditor(R4ECompareEditorInput aInput) { //NOTE: This is a dirty hack that involves accessing class and field we shouldn't, but that's // the only way to select the current position in the compare editor. Hopefully this code can // be removed later when the Eclipse compare editor allows this. ISelection selection = R4EUIModelController.getNavigatorView().getTreeViewer().getSelection(); IR4EUIModelElement element = (IR4EUIModelElement) ((IStructuredSelection) selection).getFirstElement(); IR4EUIPosition position = null; if (element instanceof R4EUIAnomalyBasic) { position = ((R4EUIAnomalyBasic) element).getPosition(); } else if (element instanceof R4EUIComment) { position = ((R4EUIAnomalyBasic) element.getParent()).getPosition(); } else if (element instanceof R4EUIContent) { position = ((R4EUIContent) element).getPosition(); + } else { + return; //Do nothing if any other element is selected } ICompareNavigator navigator = aInput.getNavigator(); if (navigator instanceof CompareEditorInputNavigator) { Object[] panes = ((CompareEditorInputNavigator) navigator).getPanes(); for (Object pane : panes) { if (pane instanceof CompareContentViewerSwitchingPane) { Viewer viewer = ((CompareContentViewerSwitchingPane) pane).getViewer(); if (viewer instanceof TextMergeViewer) { TextMergeViewer textViewer = (TextMergeViewer) viewer; Class textViewerClass = textViewer.getClass(); if (!textViewerClass.getName().equals(COMPARE_EDITOR_TEXT_CLASS_NAME)) { do { textViewerClass = textViewerClass.getSuperclass(); if (textViewerClass.getName().equals(DEFAULT_OBJECT_CLASS_NAME)) { break; } } while (!textViewerClass.getName().equals(COMPARE_EDITOR_TEXT_CLASS_NAME)); } Field field; try { field = textViewerClass.getDeclaredField(COMPARE_EDITOR_TEXT_FIELD_LEFT); field.setAccessible(true); MergeSourceViewer sourceViewer = (MergeSourceViewer) field.get(textViewer); ITextEditor adapter = (ITextEditor) sourceViewer.getAdapter(ITextEditor.class); adapter.selectAndReveal(((R4EUITextPosition) position).getOffset(), ((R4EUITextPosition) position).getLength()); } catch (SecurityException e) { //just continue } catch (NoSuchFieldException e) { //just continue } catch (IllegalArgumentException e) { //just continue } catch (IllegalAccessException e) { //just continue } } } } } } }
true
true
public static void selectElementInEditor(R4ECompareEditorInput aInput) { //NOTE: This is a dirty hack that involves accessing class and field we shouldn't, but that's // the only way to select the current position in the compare editor. Hopefully this code can // be removed later when the Eclipse compare editor allows this. ISelection selection = R4EUIModelController.getNavigatorView().getTreeViewer().getSelection(); IR4EUIModelElement element = (IR4EUIModelElement) ((IStructuredSelection) selection).getFirstElement(); IR4EUIPosition position = null; if (element instanceof R4EUIAnomalyBasic) { position = ((R4EUIAnomalyBasic) element).getPosition(); } else if (element instanceof R4EUIComment) { position = ((R4EUIAnomalyBasic) element.getParent()).getPosition(); } else if (element instanceof R4EUIContent) { position = ((R4EUIContent) element).getPosition(); } ICompareNavigator navigator = aInput.getNavigator(); if (navigator instanceof CompareEditorInputNavigator) { Object[] panes = ((CompareEditorInputNavigator) navigator).getPanes(); for (Object pane : panes) { if (pane instanceof CompareContentViewerSwitchingPane) { Viewer viewer = ((CompareContentViewerSwitchingPane) pane).getViewer(); if (viewer instanceof TextMergeViewer) { TextMergeViewer textViewer = (TextMergeViewer) viewer; Class textViewerClass = textViewer.getClass(); if (!textViewerClass.getName().equals(COMPARE_EDITOR_TEXT_CLASS_NAME)) { do { textViewerClass = textViewerClass.getSuperclass(); if (textViewerClass.getName().equals(DEFAULT_OBJECT_CLASS_NAME)) { break; } } while (!textViewerClass.getName().equals(COMPARE_EDITOR_TEXT_CLASS_NAME)); } Field field; try { field = textViewerClass.getDeclaredField(COMPARE_EDITOR_TEXT_FIELD_LEFT); field.setAccessible(true); MergeSourceViewer sourceViewer = (MergeSourceViewer) field.get(textViewer); ITextEditor adapter = (ITextEditor) sourceViewer.getAdapter(ITextEditor.class); adapter.selectAndReveal(((R4EUITextPosition) position).getOffset(), ((R4EUITextPosition) position).getLength()); } catch (SecurityException e) { //just continue } catch (NoSuchFieldException e) { //just continue } catch (IllegalArgumentException e) { //just continue } catch (IllegalAccessException e) { //just continue } } } } } }
public static void selectElementInEditor(R4ECompareEditorInput aInput) { //NOTE: This is a dirty hack that involves accessing class and field we shouldn't, but that's // the only way to select the current position in the compare editor. Hopefully this code can // be removed later when the Eclipse compare editor allows this. ISelection selection = R4EUIModelController.getNavigatorView().getTreeViewer().getSelection(); IR4EUIModelElement element = (IR4EUIModelElement) ((IStructuredSelection) selection).getFirstElement(); IR4EUIPosition position = null; if (element instanceof R4EUIAnomalyBasic) { position = ((R4EUIAnomalyBasic) element).getPosition(); } else if (element instanceof R4EUIComment) { position = ((R4EUIAnomalyBasic) element.getParent()).getPosition(); } else if (element instanceof R4EUIContent) { position = ((R4EUIContent) element).getPosition(); } else { return; //Do nothing if any other element is selected } ICompareNavigator navigator = aInput.getNavigator(); if (navigator instanceof CompareEditorInputNavigator) { Object[] panes = ((CompareEditorInputNavigator) navigator).getPanes(); for (Object pane : panes) { if (pane instanceof CompareContentViewerSwitchingPane) { Viewer viewer = ((CompareContentViewerSwitchingPane) pane).getViewer(); if (viewer instanceof TextMergeViewer) { TextMergeViewer textViewer = (TextMergeViewer) viewer; Class textViewerClass = textViewer.getClass(); if (!textViewerClass.getName().equals(COMPARE_EDITOR_TEXT_CLASS_NAME)) { do { textViewerClass = textViewerClass.getSuperclass(); if (textViewerClass.getName().equals(DEFAULT_OBJECT_CLASS_NAME)) { break; } } while (!textViewerClass.getName().equals(COMPARE_EDITOR_TEXT_CLASS_NAME)); } Field field; try { field = textViewerClass.getDeclaredField(COMPARE_EDITOR_TEXT_FIELD_LEFT); field.setAccessible(true); MergeSourceViewer sourceViewer = (MergeSourceViewer) field.get(textViewer); ITextEditor adapter = (ITextEditor) sourceViewer.getAdapter(ITextEditor.class); adapter.selectAndReveal(((R4EUITextPosition) position).getOffset(), ((R4EUITextPosition) position).getLength()); } catch (SecurityException e) { //just continue } catch (NoSuchFieldException e) { //just continue } catch (IllegalArgumentException e) { //just continue } catch (IllegalAccessException e) { //just continue } } } } } }
diff --git a/resource-bundle-translation-site/src/main/java/biz/eelis/translation/TranslationSynchronizer.java b/resource-bundle-translation-site/src/main/java/biz/eelis/translation/TranslationSynchronizer.java index 8ca621f..0fd9b64 100644 --- a/resource-bundle-translation-site/src/main/java/biz/eelis/translation/TranslationSynchronizer.java +++ b/resource-bundle-translation-site/src/main/java/biz/eelis/translation/TranslationSynchronizer.java @@ -1,315 +1,304 @@ /** * Copyright 2013 Tommi S.E. Laukkanen * * 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 biz.eelis.translation; import biz.eelis.translation.model.Entry; import org.apache.log4j.Logger; import org.vaadin.addons.sitekit.dao.CompanyDao; import org.vaadin.addons.sitekit.dao.UserDao; import org.vaadin.addons.sitekit.model.Company; import org.vaadin.addons.sitekit.model.Group; import org.vaadin.addons.sitekit.model.User; import org.vaadin.addons.sitekit.util.EmailUtil; import org.vaadin.addons.sitekit.util.PropertiesUtil; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; /** * Class which synchronizes bundles to database and back. * * @author Tommi S.E. Laukkanen */ public class TranslationSynchronizer { /** The logger. */ private static final Logger LOGGER = Logger.getLogger(TranslationSynchronizer.class); /** * The entity manager. */ private final EntityManager entityManager; /** * Synchronization thread. */ private final Thread thread; /** * Shutdown requested. */ private boolean shutdown = false; /** * Constructor which starts synchronizer. * * @param entityManager the entity manager. */ public TranslationSynchronizer(final EntityManager entityManager) { this.entityManager = entityManager; thread = new Thread(new Runnable() { @Override public void run() { while (!shutdown) { synchronize(); try { Thread.sleep(60000); } catch (final InterruptedException e) { LOGGER.debug(e); } } } }); thread.start(); } /** * Synchronizes bundles and database. */ private void synchronize() { entityManager.clear(); final String bundleCharacterSet = PropertiesUtil.getProperty("translation-site", "bundle-character-set"); final String[] prefixes = PropertiesUtil.getProperty("translation-site", "bundle-path-prefixes").split(","); for (final String prefixPart : prefixes) { final String prefix = prefixPart.split(":")[1]; final String host = prefixPart.split(":")[0]; final Company company = CompanyDao.getCompany(entityManager, host); final File baseBundle = new File(prefix + ".properties"); if (!baseBundle.exists()) { LOGGER.info("Base bundle does not exist: " + baseBundle.getAbsolutePath()); continue; } LOGGER.info("Base bundle exists: " + baseBundle.getAbsolutePath()); String baseName = baseBundle.getName().substring(0, baseBundle.getName().length() - 11); if (baseName.indexOf('_') >= 0) { baseName = baseName.substring(0, baseName.indexOf('_')); } final File bundleDirectory = baseBundle.getParentFile(); final String bundleDirectoryPath = bundleDirectory.getAbsolutePath(); LOGGER.info("Basename: " + baseName); LOGGER.info("Path: " + bundleDirectoryPath); final Set<Object> keys; final Properties baseBundleProperties; try { baseBundleProperties = new Properties(); final FileInputStream baseBundleInputStream = new FileInputStream(baseBundle); baseBundleProperties.load(new InputStreamReader(baseBundleInputStream, bundleCharacterSet)); keys = baseBundleProperties.keySet(); baseBundleInputStream.close(); } catch (Exception e) { LOGGER.error("Error reading bundle: " + baseName, e); continue; } final Map<String, List<String>> missingKeys = new HashMap<String, List<String>>(); final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss"); for (final File candidate : bundleDirectory.listFiles()) { if (candidate.getName().startsWith(baseName) && candidate.getName().endsWith(".properties")) { final String name = candidate.getName().split("\\.")[0]; final String[] parts = name.split("_"); String candidateBaseName = parts[0]; if (candidateBaseName.equals(baseName)) { String language = ""; String country = ""; if (parts.length > 1) { language = parts [1]; if (parts.length > 2) { country = parts[2]; } } LOGGER.info("Bundle basename: '" + candidateBaseName + "' language: '" + language + "' country: '" + country + "'"); entityManager.getTransaction().begin(); try { final Properties properties = new Properties(); final FileInputStream bundleInputStream = new FileInputStream(candidate); properties.load(new InputStreamReader(bundleInputStream, bundleCharacterSet)); bundleInputStream.close(); final TypedQuery<Entry> query = entityManager.createQuery("select e from Entry as e where " + "e.path=:path and e.basename=:basename and " + "e.language=:language and e.country=:country order by e.key", Entry.class); query.setParameter("path", bundleDirectoryPath); query.setParameter("basename", baseName); query.setParameter("language", language); query.setParameter("country", country); final List<Entry> entries = query.getResultList(); final Set<String> existingKeys = new HashSet<String>(); for (final Entry entry : entries) { if (keys.contains(entry.getKey())) { if (candidate.equals(baseBundle) || (entry.getValue().length() == 0 && properties.containsKey(entry.getKey()) && ((String) properties.get(entry.getKey())).length() > 0)) { entry.setValue((String) properties.get(entry.getKey())); entityManager.persist(entry); } } existingKeys.add(entry.getKey()); } for (final Object obj : keys) { final String key = (String) obj; final String value; - if (properties.containsKey(properties)) { + if (properties.containsKey(key)) { value = (String) properties.get(key); } else { value = ""; } if (!existingKeys.contains(key)) { final Entry entry = new Entry(); entry.setOwner(company); entry.setPath(bundleDirectoryPath); entry.setBasename(baseName); entry.setLanguage(language); entry.setCountry(country); entry.setKey(key); entry.setValue(value); entry.setCreated(new Date()); entry.setModified(entry.getCreated()); entityManager.persist(entry); final String locale = entry.getLanguage() + "_" + entry.getCountry(); if (!missingKeys.containsKey(locale)) { missingKeys.put(locale, new ArrayList<String>()); } missingKeys.get(locale).add(entry.getKey()); } } entityManager.getTransaction().commit(); if (!candidate.equals(baseBundle)) { - /*properties.clear(); - for (final Entry entry : entries) { - if (keys.contains(entry.getKey())) { - if (entry.getValue().length() > 0) { - properties.put(entry.getKey(), entry.getValue()); - } - } - } final FileOutputStream fileOutputStream = new FileOutputStream(candidate, false); - properties.store(new OutputStreamWriter(fileOutputStream, bundleCharacterSet), ""); - fileOutputStream.close();*/ - final FileOutputStream fileOutputStream = new FileOutputStream(candidate, false); final OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, bundleCharacterSet); final PrintWriter printWriter = new PrintWriter(writer); for (final Entry entry : query.getResultList()) { printWriter.print("# Modified: "); printWriter.print(format.format(entry.getModified())); if (entry.getAuthor() != null) { printWriter.print(" Author: "); printWriter.print(entry.getAuthor()); } printWriter.println(); printWriter.print(entry.getKey()); printWriter.print("="); printWriter.println(entry.getValue()); } printWriter.flush(); printWriter.close(); fileOutputStream.close(); } } catch (Exception e) { if (entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); } LOGGER.error("Error reading bundle: " + baseName, e); continue; } } } } final String smtpHost = PropertiesUtil.getProperty("translation-site", "smtp-host"); for (final String locale : missingKeys.keySet()) { final List<String> keySet = missingKeys.get(locale); final String subject = "Please translate " + locale; String content = "Missing keys are: "; for (final String key : keySet) { content += key + "\n"; } final Group group = UserDao.getGroup(entityManager, company, locale); if (group != null) { final List<User> users = UserDao.getGroupMembers(entityManager, company, group); for (final User user : users) { LOGGER.info("Sending translation request to " + user.getEmailAddress() + " for " + locale + " keys " + keySet); EmailUtil.send(smtpHost, user.getEmailAddress(), company.getSupportEmailAddress(), subject, content); } } } } } /** * Shutdown. */ public final void shutdown() { shutdown = true; try { thread.interrupt(); thread.join(); } catch (final InterruptedException e) { LOGGER.debug(e); } } }
false
true
private void synchronize() { entityManager.clear(); final String bundleCharacterSet = PropertiesUtil.getProperty("translation-site", "bundle-character-set"); final String[] prefixes = PropertiesUtil.getProperty("translation-site", "bundle-path-prefixes").split(","); for (final String prefixPart : prefixes) { final String prefix = prefixPart.split(":")[1]; final String host = prefixPart.split(":")[0]; final Company company = CompanyDao.getCompany(entityManager, host); final File baseBundle = new File(prefix + ".properties"); if (!baseBundle.exists()) { LOGGER.info("Base bundle does not exist: " + baseBundle.getAbsolutePath()); continue; } LOGGER.info("Base bundle exists: " + baseBundle.getAbsolutePath()); String baseName = baseBundle.getName().substring(0, baseBundle.getName().length() - 11); if (baseName.indexOf('_') >= 0) { baseName = baseName.substring(0, baseName.indexOf('_')); } final File bundleDirectory = baseBundle.getParentFile(); final String bundleDirectoryPath = bundleDirectory.getAbsolutePath(); LOGGER.info("Basename: " + baseName); LOGGER.info("Path: " + bundleDirectoryPath); final Set<Object> keys; final Properties baseBundleProperties; try { baseBundleProperties = new Properties(); final FileInputStream baseBundleInputStream = new FileInputStream(baseBundle); baseBundleProperties.load(new InputStreamReader(baseBundleInputStream, bundleCharacterSet)); keys = baseBundleProperties.keySet(); baseBundleInputStream.close(); } catch (Exception e) { LOGGER.error("Error reading bundle: " + baseName, e); continue; } final Map<String, List<String>> missingKeys = new HashMap<String, List<String>>(); final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss"); for (final File candidate : bundleDirectory.listFiles()) { if (candidate.getName().startsWith(baseName) && candidate.getName().endsWith(".properties")) { final String name = candidate.getName().split("\\.")[0]; final String[] parts = name.split("_"); String candidateBaseName = parts[0]; if (candidateBaseName.equals(baseName)) { String language = ""; String country = ""; if (parts.length > 1) { language = parts [1]; if (parts.length > 2) { country = parts[2]; } } LOGGER.info("Bundle basename: '" + candidateBaseName + "' language: '" + language + "' country: '" + country + "'"); entityManager.getTransaction().begin(); try { final Properties properties = new Properties(); final FileInputStream bundleInputStream = new FileInputStream(candidate); properties.load(new InputStreamReader(bundleInputStream, bundleCharacterSet)); bundleInputStream.close(); final TypedQuery<Entry> query = entityManager.createQuery("select e from Entry as e where " + "e.path=:path and e.basename=:basename and " + "e.language=:language and e.country=:country order by e.key", Entry.class); query.setParameter("path", bundleDirectoryPath); query.setParameter("basename", baseName); query.setParameter("language", language); query.setParameter("country", country); final List<Entry> entries = query.getResultList(); final Set<String> existingKeys = new HashSet<String>(); for (final Entry entry : entries) { if (keys.contains(entry.getKey())) { if (candidate.equals(baseBundle) || (entry.getValue().length() == 0 && properties.containsKey(entry.getKey()) && ((String) properties.get(entry.getKey())).length() > 0)) { entry.setValue((String) properties.get(entry.getKey())); entityManager.persist(entry); } } existingKeys.add(entry.getKey()); } for (final Object obj : keys) { final String key = (String) obj; final String value; if (properties.containsKey(properties)) { value = (String) properties.get(key); } else { value = ""; } if (!existingKeys.contains(key)) { final Entry entry = new Entry(); entry.setOwner(company); entry.setPath(bundleDirectoryPath); entry.setBasename(baseName); entry.setLanguage(language); entry.setCountry(country); entry.setKey(key); entry.setValue(value); entry.setCreated(new Date()); entry.setModified(entry.getCreated()); entityManager.persist(entry); final String locale = entry.getLanguage() + "_" + entry.getCountry(); if (!missingKeys.containsKey(locale)) { missingKeys.put(locale, new ArrayList<String>()); } missingKeys.get(locale).add(entry.getKey()); } } entityManager.getTransaction().commit(); if (!candidate.equals(baseBundle)) { /*properties.clear(); for (final Entry entry : entries) { if (keys.contains(entry.getKey())) { if (entry.getValue().length() > 0) { properties.put(entry.getKey(), entry.getValue()); } } } final FileOutputStream fileOutputStream = new FileOutputStream(candidate, false); properties.store(new OutputStreamWriter(fileOutputStream, bundleCharacterSet), ""); fileOutputStream.close();*/ final FileOutputStream fileOutputStream = new FileOutputStream(candidate, false); final OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, bundleCharacterSet); final PrintWriter printWriter = new PrintWriter(writer); for (final Entry entry : query.getResultList()) { printWriter.print("# Modified: "); printWriter.print(format.format(entry.getModified())); if (entry.getAuthor() != null) { printWriter.print(" Author: "); printWriter.print(entry.getAuthor()); } printWriter.println(); printWriter.print(entry.getKey()); printWriter.print("="); printWriter.println(entry.getValue()); } printWriter.flush(); printWriter.close(); fileOutputStream.close(); } } catch (Exception e) { if (entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); } LOGGER.error("Error reading bundle: " + baseName, e); continue; } } } } final String smtpHost = PropertiesUtil.getProperty("translation-site", "smtp-host"); for (final String locale : missingKeys.keySet()) { final List<String> keySet = missingKeys.get(locale); final String subject = "Please translate " + locale; String content = "Missing keys are: "; for (final String key : keySet) { content += key + "\n"; } final Group group = UserDao.getGroup(entityManager, company, locale); if (group != null) { final List<User> users = UserDao.getGroupMembers(entityManager, company, group); for (final User user : users) { LOGGER.info("Sending translation request to " + user.getEmailAddress() + " for " + locale + " keys " + keySet); EmailUtil.send(smtpHost, user.getEmailAddress(), company.getSupportEmailAddress(), subject, content); } } } } }
private void synchronize() { entityManager.clear(); final String bundleCharacterSet = PropertiesUtil.getProperty("translation-site", "bundle-character-set"); final String[] prefixes = PropertiesUtil.getProperty("translation-site", "bundle-path-prefixes").split(","); for (final String prefixPart : prefixes) { final String prefix = prefixPart.split(":")[1]; final String host = prefixPart.split(":")[0]; final Company company = CompanyDao.getCompany(entityManager, host); final File baseBundle = new File(prefix + ".properties"); if (!baseBundle.exists()) { LOGGER.info("Base bundle does not exist: " + baseBundle.getAbsolutePath()); continue; } LOGGER.info("Base bundle exists: " + baseBundle.getAbsolutePath()); String baseName = baseBundle.getName().substring(0, baseBundle.getName().length() - 11); if (baseName.indexOf('_') >= 0) { baseName = baseName.substring(0, baseName.indexOf('_')); } final File bundleDirectory = baseBundle.getParentFile(); final String bundleDirectoryPath = bundleDirectory.getAbsolutePath(); LOGGER.info("Basename: " + baseName); LOGGER.info("Path: " + bundleDirectoryPath); final Set<Object> keys; final Properties baseBundleProperties; try { baseBundleProperties = new Properties(); final FileInputStream baseBundleInputStream = new FileInputStream(baseBundle); baseBundleProperties.load(new InputStreamReader(baseBundleInputStream, bundleCharacterSet)); keys = baseBundleProperties.keySet(); baseBundleInputStream.close(); } catch (Exception e) { LOGGER.error("Error reading bundle: " + baseName, e); continue; } final Map<String, List<String>> missingKeys = new HashMap<String, List<String>>(); final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss"); for (final File candidate : bundleDirectory.listFiles()) { if (candidate.getName().startsWith(baseName) && candidate.getName().endsWith(".properties")) { final String name = candidate.getName().split("\\.")[0]; final String[] parts = name.split("_"); String candidateBaseName = parts[0]; if (candidateBaseName.equals(baseName)) { String language = ""; String country = ""; if (parts.length > 1) { language = parts [1]; if (parts.length > 2) { country = parts[2]; } } LOGGER.info("Bundle basename: '" + candidateBaseName + "' language: '" + language + "' country: '" + country + "'"); entityManager.getTransaction().begin(); try { final Properties properties = new Properties(); final FileInputStream bundleInputStream = new FileInputStream(candidate); properties.load(new InputStreamReader(bundleInputStream, bundleCharacterSet)); bundleInputStream.close(); final TypedQuery<Entry> query = entityManager.createQuery("select e from Entry as e where " + "e.path=:path and e.basename=:basename and " + "e.language=:language and e.country=:country order by e.key", Entry.class); query.setParameter("path", bundleDirectoryPath); query.setParameter("basename", baseName); query.setParameter("language", language); query.setParameter("country", country); final List<Entry> entries = query.getResultList(); final Set<String> existingKeys = new HashSet<String>(); for (final Entry entry : entries) { if (keys.contains(entry.getKey())) { if (candidate.equals(baseBundle) || (entry.getValue().length() == 0 && properties.containsKey(entry.getKey()) && ((String) properties.get(entry.getKey())).length() > 0)) { entry.setValue((String) properties.get(entry.getKey())); entityManager.persist(entry); } } existingKeys.add(entry.getKey()); } for (final Object obj : keys) { final String key = (String) obj; final String value; if (properties.containsKey(key)) { value = (String) properties.get(key); } else { value = ""; } if (!existingKeys.contains(key)) { final Entry entry = new Entry(); entry.setOwner(company); entry.setPath(bundleDirectoryPath); entry.setBasename(baseName); entry.setLanguage(language); entry.setCountry(country); entry.setKey(key); entry.setValue(value); entry.setCreated(new Date()); entry.setModified(entry.getCreated()); entityManager.persist(entry); final String locale = entry.getLanguage() + "_" + entry.getCountry(); if (!missingKeys.containsKey(locale)) { missingKeys.put(locale, new ArrayList<String>()); } missingKeys.get(locale).add(entry.getKey()); } } entityManager.getTransaction().commit(); if (!candidate.equals(baseBundle)) { final FileOutputStream fileOutputStream = new FileOutputStream(candidate, false); final OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, bundleCharacterSet); final PrintWriter printWriter = new PrintWriter(writer); for (final Entry entry : query.getResultList()) { printWriter.print("# Modified: "); printWriter.print(format.format(entry.getModified())); if (entry.getAuthor() != null) { printWriter.print(" Author: "); printWriter.print(entry.getAuthor()); } printWriter.println(); printWriter.print(entry.getKey()); printWriter.print("="); printWriter.println(entry.getValue()); } printWriter.flush(); printWriter.close(); fileOutputStream.close(); } } catch (Exception e) { if (entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); } LOGGER.error("Error reading bundle: " + baseName, e); continue; } } } } final String smtpHost = PropertiesUtil.getProperty("translation-site", "smtp-host"); for (final String locale : missingKeys.keySet()) { final List<String> keySet = missingKeys.get(locale); final String subject = "Please translate " + locale; String content = "Missing keys are: "; for (final String key : keySet) { content += key + "\n"; } final Group group = UserDao.getGroup(entityManager, company, locale); if (group != null) { final List<User> users = UserDao.getGroupMembers(entityManager, company, group); for (final User user : users) { LOGGER.info("Sending translation request to " + user.getEmailAddress() + " for " + locale + " keys " + keySet); EmailUtil.send(smtpHost, user.getEmailAddress(), company.getSupportEmailAddress(), subject, content); } } } } }
diff --git a/utgb-shell/src/test/java/org/utgenome/shell/Sam2WigTest.java b/utgb-shell/src/test/java/org/utgenome/shell/Sam2WigTest.java index 475b5364..7ff24c4e 100755 --- a/utgb-shell/src/test/java/org/utgenome/shell/Sam2WigTest.java +++ b/utgb-shell/src/test/java/org/utgenome/shell/Sam2WigTest.java @@ -1,47 +1,47 @@ /*-------------------------------------------------------------------------- * Copyright 2008 utgenome.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. *--------------------------------------------------------------------------*/ //-------------------------------------- // utgb-shell Project // // Sam2WigTest.java // Since: 2010/09/28 // // $URL$ // $Author$ //-------------------------------------- package org.utgenome.shell; import java.io.File; import org.junit.Test; import org.utgenome.util.TestHelper; import org.xerial.util.FileUtil; public class Sam2WigTest { @Test public void convert() throws Exception { File work = new File("target"); File bam = TestHelper.createTempFileFrom(Sam2WigTest.class, "sample.bam"); File bai = TestHelper.createTempFileFrom(Sam2WigTest.class, "sample.bam.bai", new File(bam + ".bai")); File out = FileUtil.createTempFile(work, "output", ".wig"); UTGBShell.runCommand(String.format("readdepth %s %s", bam, out)); - UTGBShell.runCommand(String.format("import -w %s", out)); + UTGBShell.runCommand(String.format("import -t wig %s", out)); } }
true
true
public void convert() throws Exception { File work = new File("target"); File bam = TestHelper.createTempFileFrom(Sam2WigTest.class, "sample.bam"); File bai = TestHelper.createTempFileFrom(Sam2WigTest.class, "sample.bam.bai", new File(bam + ".bai")); File out = FileUtil.createTempFile(work, "output", ".wig"); UTGBShell.runCommand(String.format("readdepth %s %s", bam, out)); UTGBShell.runCommand(String.format("import -w %s", out)); }
public void convert() throws Exception { File work = new File("target"); File bam = TestHelper.createTempFileFrom(Sam2WigTest.class, "sample.bam"); File bai = TestHelper.createTempFileFrom(Sam2WigTest.class, "sample.bam.bai", new File(bam + ".bai")); File out = FileUtil.createTempFile(work, "output", ".wig"); UTGBShell.runCommand(String.format("readdepth %s %s", bam, out)); UTGBShell.runCommand(String.format("import -t wig %s", out)); }
diff --git a/JREngage/src/com/janrain/android/engage/types/JRActivityObject.java b/JREngage/src/com/janrain/android/engage/types/JRActivityObject.java index a101ea8..8ccf633 100644 --- a/JREngage/src/com/janrain/android/engage/types/JRActivityObject.java +++ b/JREngage/src/com/janrain/android/engage/types/JRActivityObject.java @@ -1,579 +1,579 @@ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (c) 2010, Janrain, Inc. 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 Janrain, Inc. 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 com.janrain.android.engage.types; import android.text.Html; import android.util.Log; import com.janrain.android.engage.net.JRConnectionManager; import com.janrain.android.engage.net.JRConnectionManagerDelegate; import com.janrain.android.engage.session.JRSessionData; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONStringer; import org.json.JSONTokener; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /* * @file * @brief Interface for creating and populating activities that you wish to publish. * * Interface for creating and populating activities that you wish to publish * to your user's social networks. Create an activity object, fill in the * object's fields, and pass the object to the JREngage library when you * are ready to share. */ /** * @brief An activity object you create, populate, and post to the user's activity stream. * * Create an activity object, fill in the object's fields, and pass the object to * the JREngage library when you are ready to publish. Currently supported providers are: * - Facebook * - LinkedIn * - Twitter * - MySpace * - Yahoo! * * Janrain Engage will make a best effort to use all of the fields submitted in the activity * request, but note that how they get presented (and which ones are used) ultimately depends on * the provider. * * This API will work if and only if: * - Your Janrain Engage application has been configured with the given provider * - The user has already authenticated and has given consent to publish activity * * Otherwise, you will be given an error response indicating what was wrong. Detailed error * responses will also be given if the activity parameter does not meet the formatting requirements * described below. * * @sa For more information of Janrain Engage's activity api, see <a * href="https://rpxnow.com/docs#api_activity">the activity section</a> of our API Documentation. * * @nosubgrouping **/ public class JRActivityObject { private static final String TAG = JRActivityObject.class.getSimpleName(); /** * @name Private Attributes * The various properties of the JRActivityObject that you can access and configure through the * object's constructor, getters, and setters **/ /*@{*/ /** * A string describing what the user did, written in the third person (e.g., * "wrote a restaurant review", "posted a comment", "took a quiz"). * * @par Getter: * #getAction() **/ private String mAction; /** * The URL of the resource being mentioned in the activity update. * * @par Getter: * #getUrl() **/ private String mUrl; //url associated with the action /** * A string containing user-supplied content, such as a comment or the first paragraph of * an article that the user wrote. * * @note * Some providers (Twitter in particular) may truncate this value. * * @par Getter/Setter: * #getUserGeneratedContent(), #setUserGeneratedContent() **/ private String mUserGeneratedContent; /** * The title of the resource being mentioned in the activity update. * * @note No length restriction on the status is imposed by Janrain Engage, however Yahoo * truncates this value to 256 characters. * * @par Getter/Setter: * #getTitle(), #setTitle() **/ private String mTitle = ""; /** * A description of the resource mentioned in the activity update. * * @par Getter/Setter: * #getDescription(), #setDescription() **/ private String mDescription = ""; /** * An array of JRActionLink objects, each having two attributes: \e text and \e href. * An action link is a link a user can use to take action on an activity update on the provider. * * @par Example: * @code * action_links: * [ * { * "text": "Rate this quiz result", * "href": "http://example.com/quiz/12345/result/6789/rate" * }, * { * "text": "Take this quiz", * "href": "http://example.com/quiz/12345/take" * } * ] * @endcode * * @note * Any objects added to this array that are not of type JRActionLink will * be ignored. * * @par Getter/Setter: * #getActionLinks(), #setActionLinks(), #addActionLink() **/ private List<JRActionLink> mActionLinks = new ArrayList<JRActionLink>(); /** * An array of objects with base class \e JRMediaObject (i.e. JRImageMediaObject, * JRFlashMediaObject, JRMp3MediaObject). * * To publish attached media objects with your activity, create the preferred * object, populate the object's fields, then add the object to the #mMedia array. * You can attach pictures, videos, and mp3s to your activity, although how the * media objects get presented and whether or not they are used, depend on the provider. * * If you include more than one media type in the array, JREngage will * choose only one of these types, in this order: * -# image * -# flash * -# mp3 * * Also, any objects added to this array that do not inherit from \e JRMediaObject * will be ignored. * * @sa Media object format and rules are identical to those described on the <a * href="http://developers.facebook.com/docs/guides/attachments">Facebook Developer page * on Attachments</a>. * * @par Getter/Setter: * #getMedia(), #setMedia(List<JRMediaObject>), #setMedia(JRMediaObject) **/ private List<JRMediaObject> mMedia = new ArrayList<JRMediaObject>(); /** * An object with attributes describing properties of the update. An attribute \e value can be * a string or an object with two attributes, \e text and \e href. * * @par Example: * @code * properties: * { * "Time": "05:00", * "Location": * { * "text": "Portland", * "href": "http://en.wikipedia.org/wiki/Portland,_Oregon" * } * } * @endcode * * @par Getter/Setter: * #getProperties(), #setProperties() **/ private Map<String, Object> mProperties = new HashMap<String, Object>(); /** * A JREmailObject to use to prefill a sharing email sent by the user */ private JREmailObject mEmail; /** * A JRSmsObject to use to prefill a sharing SMS sent by the user */ private JRSmsObject mSms; /*@}*/ /** * @name Constructors * Constructor for JRActivityObject **/ /*@{*/ /** * Returns a JRActivityObject initialized with the given action and url. * * @param action * A string describing what the user did, written in the third person. This value cannot * be null * * @param url * The URL of the resource being mentioned in the activity update * * @throws IllegalArgumentException * if text or href is null **/ public JRActivityObject(String action, String url) { if (action == null) throw new IllegalArgumentException("illegal null action or null href"); Log.d(TAG, "created with action: " + action + " url: " + url); mAction = action; mUrl = url; } /*@}*/ /** * @name Getters/Setters * Getters and setters for the JRActivityObject's private properties **/ /*@{*/ /** * Getter for the activity object's #mAction property. * * @return * A string describing what the user did, written in the third person (e.g., * "wrote a restaurant review", "posted a comment", "took a quiz") **/ public String getAction() { /* (readonly) */ return mAction; } /** * Getter for the activity object's #mUrl property. * * @return * The URL of the resource being mentioned in the activity update **/ public String getUrl() { /* (readonly) */ return mUrl; } /** * Getter for the activity object's #mUserGeneratedContent property. * * @return * A string containing user-supplied content, such as a comment or the first paragraph of * an article that the user wrote **/ public String getUserGeneratedContent() { return mUserGeneratedContent; } /** * Setter for the activity object's #mUserGeneratedContent property. * * @param userGeneratedContent * A string containing user-supplied content, such as a comment or the first paragraph of * an article that the user wrote **/ public void setUserGeneratedContent(String userGeneratedContent) { mUserGeneratedContent = userGeneratedContent; } /** * Getter for the activity object's #mTitle property. * * @return * The title of the resource being mentioned in the activity update **/ public String getTitle() { return mTitle; } /** * Setter for the activity object's #mTitle property. * * @param title * The title of the resource being mentioned in the activity update **/ public void setTitle(String title) { mTitle = title; } /** * Getter for the activity object's #mDescription property. * * @return * A description of the resource mentioned in the activity update **/ public String getDescription() { return mDescription; } /** * Setter for the activity object's #mDescription property. * * @param description * A description of the resource mentioned in the activity update **/ public void setDescription(String description) { mDescription = description; } /** * Getter for the activity object's #mActionLinks property. * * @return * An array of JRActionLink objects, each having two attributes: \e text and \e href. * An action link is a link a user can use to take action on an activity update on the provider **/ public List<JRActionLink> getActionLinks() { return mActionLinks; } /** * Setter for the activity object's #mActionLinks property. * * @param actionLinks * An array of JRActionLink objects, each having two attributes: \e text and \e href. * An action link is a link a user can use to take action on an activity update on the provider **/ public void setActionLinks(List<JRActionLink> actionLinks) { mActionLinks = actionLinks; } /** * Setter for the activity object's #mActionLinks property. * * @param actionLink * A single JRActionLink to be added to the array of action links, creating the array if * it hasn't already been created **/ public void addActionLink(JRActionLink actionLink) { if (mActionLinks == null) mActionLinks = new ArrayList<JRActionLink>(); mActionLinks.add(actionLink); } /** * Getter for the activity object's #mMedia property. * * @return * An array of objects with base class \e JRMediaObject (i.e. JRImageMediaObject, * JRFlashMediaObject, JRMp3MediaObject) **/ public List<JRMediaObject> getMedia() { return mMedia; } /** * Setter for the activity object's #mMedia property. * * @param media * An array of objects with base class \e JRMediaObject (i.e. JRImageMediaObject, * JRFlashMediaObject, JRMp3MediaObject) **/ public void setMedia(List<JRMediaObject> media) { mMedia = media; } /** * Setter for the activity object's #mMedia property. * * @param mediaObject * An single JRImageMediaObject, JRFlashMediaObject, or JRMp3MediaObject to be added to * the array of media objects, creating the array if it hasn't already been created **/ public void setMedia(JRMediaObject mediaObject) { if (mMedia == null) mMedia = new ArrayList<JRMediaObject>(); mMedia.add(mediaObject); } /** * Getter for the activity object's #mProperties property. * * @return * An object with attributes describing properties of the update. An attribute value can be * a string or an object with two attributes, \e text and \e href. **/ public Map<String, Object> getProperties() { return mProperties; } /** * Setter for the activity object's #mProperties property. * * @param properties * An object with attributes describing properties of the update. An attribute value can be * a string or an object with two attributes, \e text and \e href. **/ public void setProperties(Map<String, Object> properties) { mProperties = properties; } public void setEmail(JREmailObject email) { mEmail = email; } public JREmailObject getEmail() { return mEmail; } public void setSms(JRSmsObject sms) { mSms = sms; } public JRSmsObject getSms() { return mSms; } /*@}*/ /** * @internal * Returns a HashMap (Dictionary) representing the JRActivityObject. * * @return * An HashMap (Dictionary) of String objects representing the JRActivityObject. * * NOTE: This function should not be used directly. It is intended only for use by the * JREngage library. * */ public JRDictionary toJRDictionary() { JRDictionary map = new JRDictionary(); map.put("url", mUrl); map.put("action", mAction); map.put("user_generated_content", mUserGeneratedContent); map.put("title", mTitle); map.put("description", mDescription); map.put("action_links", mActionLinks); map.put("media", mMedia); map.put("properties", mProperties); return map; } public interface ShortenedUrlCallback { public void setShortenedUrl(String shortenedUrl); } public void shortenUrls(final ShortenedUrlCallback callback) { final JRSessionData sessionData = JRSessionData.getInstance(); try { // todo invoke when the activity object is created (or maybe when publish is called?) List<String> emptyList = new ArrayList<String>(); final List<String> emailUrls = mEmail == null ? emptyList : mEmail.getUrls(); final List<String> smsUrls = mSms == null ? emptyList : mSms.getUrls(); // Make the JSON string JSONStringer jss = (new JSONStringer()) .object() .key("activity") .array() .value(getUrl()) .endArray() - .key("email_urls") + .key("email") .array(); for (String url : emailUrls) jss.value(url); jss.endArray() - .key("sms_urls") + .key("sms") .array(); for (String url : smsUrls) jss.value(url); jss.endArray() .endObject(); // Make the URL final String jsonEncodedActivityUrl = jss.toString(); - String htmlEncodedJson = URLEncoder.encode(jsonEncodedActivityUrl, "UTF8"); + String urlEncodedJson = URLEncoder.encode(jsonEncodedActivityUrl, "UTF8"); final String getUrlsUrl = sessionData.getBaseUrl() + "/openid/get_urls?" - + "urls=" + htmlEncodedJson + + "urls=" + urlEncodedJson + "&app_name=" + sessionData.getUrlEncodedAppName() + "&device=android"; // Define the network callback JRConnectionManagerDelegate jrcmd = new JRConnectionManagerDelegate.SimpleJRConnectionManagerDelegate() { public void connectionDidFinishLoading(String payload, String requestUrl, Object userdata) { String shortUrl = getUrl(); try { Log.d(TAG, "fetchShortenedURLs connectionDidFinishLoading: " + payload); JSONObject jso = (JSONObject) (new JSONTokener(payload)).nextValue(); jso = jso.getJSONObject("urls"); JSONObject jsonActivityUrls = jso.getJSONObject("activity"); - JSONObject jsonSmsUrls = jso.getJSONObject("sms_urls"); - JSONObject jsonEmailUrls = jso.getJSONObject("email_urls"); + JSONObject jsonSmsUrls = jso.getJSONObject("sms"); + JSONObject jsonEmailUrls = jso.getJSONObject("email"); shortUrl = jsonActivityUrls.getString(getUrl()); if (mEmail != null) { List<String> shortEmailUrls = new ArrayList<String>(); for (String longUrl : emailUrls) shortEmailUrls.add(jsonEmailUrls.getString(longUrl)); mEmail.setShortUrls(shortEmailUrls); } if (mSms != null) { List<String> shortSmsUrls = new ArrayList<String>(); for (String longUrl : smsUrls) shortSmsUrls.add(jsonSmsUrls.getString(longUrl)); mSms.setShortUrls(shortSmsUrls); } } catch (JSONException e) { Log.e(TAG, "URL shortening JSON parse error", e); } catch (ClassCastException e) { Log.e(TAG, "URL shortening JSON parse error", e); } updateUI(shortUrl); } void updateUI(String shortenedUrl) { callback.setShortenedUrl(shortenedUrl); } public void connectionDidFail(Exception ex, String requestUrl, Object userdata) { updateUI(getUrl()); } public void connectionWasStopped(Object userdata) { updateUI(getUrl()); } }; // Invoke the network call JRConnectionManager.createConnection(getUrlsUrl, jrcmd, false, null); } catch (JSONException e) { Log.e(TAG, "URL shortening JSON error", e); } catch (UnsupportedEncodingException e) { Log.e(TAG, "URL shortening error", e); } } }
false
true
public void shortenUrls(final ShortenedUrlCallback callback) { final JRSessionData sessionData = JRSessionData.getInstance(); try { // todo invoke when the activity object is created (or maybe when publish is called?) List<String> emptyList = new ArrayList<String>(); final List<String> emailUrls = mEmail == null ? emptyList : mEmail.getUrls(); final List<String> smsUrls = mSms == null ? emptyList : mSms.getUrls(); // Make the JSON string JSONStringer jss = (new JSONStringer()) .object() .key("activity") .array() .value(getUrl()) .endArray() .key("email_urls") .array(); for (String url : emailUrls) jss.value(url); jss.endArray() .key("sms_urls") .array(); for (String url : smsUrls) jss.value(url); jss.endArray() .endObject(); // Make the URL final String jsonEncodedActivityUrl = jss.toString(); String htmlEncodedJson = URLEncoder.encode(jsonEncodedActivityUrl, "UTF8"); final String getUrlsUrl = sessionData.getBaseUrl() + "/openid/get_urls?" + "urls=" + htmlEncodedJson + "&app_name=" + sessionData.getUrlEncodedAppName() + "&device=android"; // Define the network callback JRConnectionManagerDelegate jrcmd = new JRConnectionManagerDelegate.SimpleJRConnectionManagerDelegate() { public void connectionDidFinishLoading(String payload, String requestUrl, Object userdata) { String shortUrl = getUrl(); try { Log.d(TAG, "fetchShortenedURLs connectionDidFinishLoading: " + payload); JSONObject jso = (JSONObject) (new JSONTokener(payload)).nextValue(); jso = jso.getJSONObject("urls"); JSONObject jsonActivityUrls = jso.getJSONObject("activity"); JSONObject jsonSmsUrls = jso.getJSONObject("sms_urls"); JSONObject jsonEmailUrls = jso.getJSONObject("email_urls"); shortUrl = jsonActivityUrls.getString(getUrl()); if (mEmail != null) { List<String> shortEmailUrls = new ArrayList<String>(); for (String longUrl : emailUrls) shortEmailUrls.add(jsonEmailUrls.getString(longUrl)); mEmail.setShortUrls(shortEmailUrls); } if (mSms != null) { List<String> shortSmsUrls = new ArrayList<String>(); for (String longUrl : smsUrls) shortSmsUrls.add(jsonSmsUrls.getString(longUrl)); mSms.setShortUrls(shortSmsUrls); } } catch (JSONException e) { Log.e(TAG, "URL shortening JSON parse error", e); } catch (ClassCastException e) { Log.e(TAG, "URL shortening JSON parse error", e); } updateUI(shortUrl); } void updateUI(String shortenedUrl) { callback.setShortenedUrl(shortenedUrl); } public void connectionDidFail(Exception ex, String requestUrl, Object userdata) { updateUI(getUrl()); } public void connectionWasStopped(Object userdata) { updateUI(getUrl()); } }; // Invoke the network call JRConnectionManager.createConnection(getUrlsUrl, jrcmd, false, null); } catch (JSONException e) { Log.e(TAG, "URL shortening JSON error", e); } catch (UnsupportedEncodingException e) { Log.e(TAG, "URL shortening error", e); } }
public void shortenUrls(final ShortenedUrlCallback callback) { final JRSessionData sessionData = JRSessionData.getInstance(); try { // todo invoke when the activity object is created (or maybe when publish is called?) List<String> emptyList = new ArrayList<String>(); final List<String> emailUrls = mEmail == null ? emptyList : mEmail.getUrls(); final List<String> smsUrls = mSms == null ? emptyList : mSms.getUrls(); // Make the JSON string JSONStringer jss = (new JSONStringer()) .object() .key("activity") .array() .value(getUrl()) .endArray() .key("email") .array(); for (String url : emailUrls) jss.value(url); jss.endArray() .key("sms") .array(); for (String url : smsUrls) jss.value(url); jss.endArray() .endObject(); // Make the URL final String jsonEncodedActivityUrl = jss.toString(); String urlEncodedJson = URLEncoder.encode(jsonEncodedActivityUrl, "UTF8"); final String getUrlsUrl = sessionData.getBaseUrl() + "/openid/get_urls?" + "urls=" + urlEncodedJson + "&app_name=" + sessionData.getUrlEncodedAppName() + "&device=android"; // Define the network callback JRConnectionManagerDelegate jrcmd = new JRConnectionManagerDelegate.SimpleJRConnectionManagerDelegate() { public void connectionDidFinishLoading(String payload, String requestUrl, Object userdata) { String shortUrl = getUrl(); try { Log.d(TAG, "fetchShortenedURLs connectionDidFinishLoading: " + payload); JSONObject jso = (JSONObject) (new JSONTokener(payload)).nextValue(); jso = jso.getJSONObject("urls"); JSONObject jsonActivityUrls = jso.getJSONObject("activity"); JSONObject jsonSmsUrls = jso.getJSONObject("sms"); JSONObject jsonEmailUrls = jso.getJSONObject("email"); shortUrl = jsonActivityUrls.getString(getUrl()); if (mEmail != null) { List<String> shortEmailUrls = new ArrayList<String>(); for (String longUrl : emailUrls) shortEmailUrls.add(jsonEmailUrls.getString(longUrl)); mEmail.setShortUrls(shortEmailUrls); } if (mSms != null) { List<String> shortSmsUrls = new ArrayList<String>(); for (String longUrl : smsUrls) shortSmsUrls.add(jsonSmsUrls.getString(longUrl)); mSms.setShortUrls(shortSmsUrls); } } catch (JSONException e) { Log.e(TAG, "URL shortening JSON parse error", e); } catch (ClassCastException e) { Log.e(TAG, "URL shortening JSON parse error", e); } updateUI(shortUrl); } void updateUI(String shortenedUrl) { callback.setShortenedUrl(shortenedUrl); } public void connectionDidFail(Exception ex, String requestUrl, Object userdata) { updateUI(getUrl()); } public void connectionWasStopped(Object userdata) { updateUI(getUrl()); } }; // Invoke the network call JRConnectionManager.createConnection(getUrlsUrl, jrcmd, false, null); } catch (JSONException e) { Log.e(TAG, "URL shortening JSON error", e); } catch (UnsupportedEncodingException e) { Log.e(TAG, "URL shortening error", e); } }
diff --git a/src/me/Hoot215/TabListColours/TabListColoursPlayerListener.java b/src/me/Hoot215/TabListColours/TabListColoursPlayerListener.java index 6912280..4bf2596 100644 --- a/src/me/Hoot215/TabListColours/TabListColoursPlayerListener.java +++ b/src/me/Hoot215/TabListColours/TabListColoursPlayerListener.java @@ -1,48 +1,57 @@ /* * Customizable colours for the tab player listing. * Copyright (C) 2013 Andrew Stevanus (Hoot215) <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.Hoot215.TabListColours; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; public class TabListColoursPlayerListener implements Listener { private TabListColours plugin; public TabListColoursPlayerListener(TabListColours instance) { plugin = instance; } @EventHandler(priority = EventPriority.NORMAL) public void onPlayerJoin (PlayerJoinEvent event) { Player player = event.getPlayer(); String prefix = plugin.getChat().getPlayerPrefix(player); if (prefix != null && !prefix.isEmpty()) { - prefix = prefix.substring(0, 2).replace('&', '§'); + String playerName = player.getName(); + String name = playerName; + name = + playerName.length() > 12 ? prefix.substring(0, 2).replace('&', + '§') + + playerName.substring(0, playerName.length() < 14 + ? playerName.length() - 1 : 14) : prefix + .substring(0, 2).replace('&', '§') + + playerName + + ChatColor.WHITE; + player.setPlayerListName(name); } - player.setPlayerListName(prefix + player.getName() + ChatColor.WHITE); } }
false
true
public void onPlayerJoin (PlayerJoinEvent event) { Player player = event.getPlayer(); String prefix = plugin.getChat().getPlayerPrefix(player); if (prefix != null && !prefix.isEmpty()) { prefix = prefix.substring(0, 2).replace('&', '§'); } player.setPlayerListName(prefix + player.getName() + ChatColor.WHITE); }
public void onPlayerJoin (PlayerJoinEvent event) { Player player = event.getPlayer(); String prefix = plugin.getChat().getPlayerPrefix(player); if (prefix != null && !prefix.isEmpty()) { String playerName = player.getName(); String name = playerName; name = playerName.length() > 12 ? prefix.substring(0, 2).replace('&', '§') + playerName.substring(0, playerName.length() < 14 ? playerName.length() - 1 : 14) : prefix .substring(0, 2).replace('&', '§') + playerName + ChatColor.WHITE; player.setPlayerListName(name); } }
diff --git a/src/husacct/define/presentation/jpanel/ruledetails/FactoryDetails.java b/src/husacct/define/presentation/jpanel/ruledetails/FactoryDetails.java index 8d38288b..5837dd87 100644 --- a/src/husacct/define/presentation/jpanel/ruledetails/FactoryDetails.java +++ b/src/husacct/define/presentation/jpanel/ruledetails/FactoryDetails.java @@ -1,162 +1,162 @@ package husacct.define.presentation.jpanel.ruledetails; import husacct.define.presentation.jpanel.ruledetails.contentsmodule.InterfaceConventionJPanel; import husacct.define.presentation.jpanel.ruledetails.contentsmodule.NamingConventionExceptionJPanel; import husacct.define.presentation.jpanel.ruledetails.contentsmodule.NamingConventionJPanel; import husacct.define.presentation.jpanel.ruledetails.contentsmodule.SubClassConventionJPanel; import husacct.define.presentation.jpanel.ruledetails.contentsmodule.VisibilityConventionExceptionJPanel; import husacct.define.presentation.jpanel.ruledetails.contentsmodule.VisibilityConventionJPanel; import husacct.define.presentation.jpanel.ruledetails.dependencylimitation.CyclesBetweenModulesExceptionJPanel; import husacct.define.presentation.jpanel.ruledetails.dependencylimitation.CyclesBetweenModulesJPanel; import husacct.define.presentation.jpanel.ruledetails.legalitydependency.BackCallJPanel; import husacct.define.presentation.jpanel.ruledetails.legalitydependency.IsAllowedToUseJPanel; import husacct.define.presentation.jpanel.ruledetails.legalitydependency.IsNotAllowedToUseJPanel; import husacct.define.presentation.jpanel.ruledetails.legalitydependency.IsOnlyAllowedToUseJPanel; import husacct.define.presentation.jpanel.ruledetails.legalitydependency.IsOnlyModuleAllowedToUseJPanel; import husacct.define.presentation.jpanel.ruledetails.legalitydependency.MustUseJPanel; import husacct.define.presentation.jpanel.ruledetails.legalitydependency.SkipCallJPanel; import husacct.define.task.AppliedRuleController; import org.apache.log4j.Logger; public class FactoryDetails { //Rules on the Contents of a module private InterfaceConventionJPanel interfaceConventionJPanel; private SubClassConventionJPanel subClassConventionJPanel; private VisibilityConventionJPanel visibilityConventionJPanel; private VisibilityConventionExceptionJPanel visibilityConventionExceptionJPanel; private NamingConventionJPanel namingConventionJPanel; private NamingConventionExceptionJPanel namingConventionExceptionJPanel; //Rules of the Legality of Dependency private IsNotAllowedToUseJPanel isNotAllowedToUseJPanel; private IsAllowedToUseJPanel isAllowedToUseJPanel; private IsOnlyAllowedToUseJPanel isOnlyAllowedToUseJPanel; private IsOnlyModuleAllowedToUseJPanel isOnlyModuleAllowedToUseJPanel; private MustUseJPanel mustUseJPanel; private SkipCallJPanel skipCallJPanel; private BackCallJPanel backCallJPanel; //Rules on the Dependency Limitation private CyclesBetweenModulesJPanel cyclesBetweenModules; private CyclesBetweenModulesExceptionJPanel cyclesBetweenModulesExceptionJPanel; public AbstractDetailsJPanel create(AppliedRuleController appliedRuleController, String ruleTypeKey){ //Rules on the Contents of a module if (ruleTypeKey.equals(InterfaceConventionJPanel.ruleTypeKey)){ interfaceConventionJPanel = new InterfaceConventionJPanel(appliedRuleController); return interfaceConventionJPanel; } else if (ruleTypeKey.equals(SubClassConventionJPanel.ruleTypeKey)){ subClassConventionJPanel = new SubClassConventionJPanel(appliedRuleController); return subClassConventionJPanel; } else if (ruleTypeKey.equals(VisibilityConventionJPanel.ruleTypeKey)){ visibilityConventionJPanel = new VisibilityConventionJPanel(appliedRuleController); return visibilityConventionJPanel; }else if (ruleTypeKey.equals(VisibilityConventionExceptionJPanel.ruleTypeKey)){ visibilityConventionExceptionJPanel = new VisibilityConventionExceptionJPanel(appliedRuleController); return visibilityConventionExceptionJPanel; }else if (ruleTypeKey.equals(NamingConventionJPanel.ruleTypeKey)){ namingConventionJPanel = new NamingConventionJPanel(appliedRuleController); return namingConventionJPanel; }else if (ruleTypeKey.equals(NamingConventionExceptionJPanel.ruleTypeKey)){ namingConventionExceptionJPanel = new NamingConventionExceptionJPanel(appliedRuleController); return namingConventionExceptionJPanel; //Rules of the Legality of Dependency } else if (ruleTypeKey.equals(IsNotAllowedToUseJPanel.ruleTypeKey)) { isNotAllowedToUseJPanel = new IsNotAllowedToUseJPanel(appliedRuleController); return isNotAllowedToUseJPanel; } else if (ruleTypeKey.equals(IsAllowedToUseJPanel.ruleTypeKey)){ isAllowedToUseJPanel = new IsAllowedToUseJPanel(appliedRuleController); return isAllowedToUseJPanel; }else if (ruleTypeKey.equals(IsOnlyAllowedToUseJPanel.ruleTypeKey)){ isOnlyAllowedToUseJPanel = new IsOnlyAllowedToUseJPanel(appliedRuleController); return isOnlyAllowedToUseJPanel; }else if (ruleTypeKey.equals(IsOnlyModuleAllowedToUseJPanel.ruleTypeKey)){ isOnlyModuleAllowedToUseJPanel = new IsOnlyModuleAllowedToUseJPanel(appliedRuleController); return isOnlyModuleAllowedToUseJPanel; }else if (ruleTypeKey.equals(MustUseJPanel.ruleTypeKey)){ mustUseJPanel = new MustUseJPanel(appliedRuleController); return mustUseJPanel; }else if (ruleTypeKey.equals(SkipCallJPanel.ruleTypeKey)){ skipCallJPanel = new SkipCallJPanel(appliedRuleController); return skipCallJPanel; }else if (ruleTypeKey.equals(BackCallJPanel.ruleTypeKey)){ backCallJPanel = new BackCallJPanel(appliedRuleController); return backCallJPanel; //Rules on the Dependency Limitation }else if (ruleTypeKey.equals(CyclesBetweenModulesJPanel.ruleTypeKey)){ cyclesBetweenModules = new CyclesBetweenModulesJPanel(appliedRuleController); return cyclesBetweenModules; }else if (ruleTypeKey.equals(CyclesBetweenModulesExceptionJPanel.ruleTypeKey)){ cyclesBetweenModulesExceptionJPanel = new CyclesBetweenModulesExceptionJPanel(appliedRuleController); return cyclesBetweenModulesExceptionJPanel; //Not Known }else { Logger.getLogger(FactoryDetails.class).error("No known AbstractDetailsJPanel for key: " + ruleTypeKey); // throw new RuntimeException("No known AbstractDetailsJPanel for key: " + ruleTypeKey); - loopsInModuleExceptionJPanel = new LoopsInModuleExceptionJPanel(appliedRuleController); - return loopsInModuleExceptionJPanel; + cyclesBetweenModules = new CyclesBetweenModulesJPanel(appliedRuleController); + return cyclesBetweenModules; } } /** * * @param ruleTypeKey * @return returns a the instance of the AbstractDetailsJPanel corrisonding with the ruleTypeKey. * If the Implemented AbstractDetailsJPanel is null then it will return a new instance. */ public AbstractDetailsJPanel get(AppliedRuleController appliedRuleController, String ruleTypeKey){ //Rules on the Contents of a module if (ruleTypeKey.equals(InterfaceConventionJPanel.ruleTypeKey)){ if (interfaceConventionJPanel == null) {interfaceConventionJPanel = new InterfaceConventionJPanel(appliedRuleController);} return interfaceConventionJPanel; } else if (ruleTypeKey.equals(SubClassConventionJPanel.ruleTypeKey)){ if (subClassConventionJPanel == null) {subClassConventionJPanel = new SubClassConventionJPanel(appliedRuleController);} return subClassConventionJPanel; } else if (ruleTypeKey.equals(VisibilityConventionJPanel.ruleTypeKey)){ if (visibilityConventionJPanel == null) {visibilityConventionJPanel = new VisibilityConventionJPanel(appliedRuleController);} return visibilityConventionJPanel; }else if (ruleTypeKey.equals(VisibilityConventionExceptionJPanel.ruleTypeKey)){ if (visibilityConventionExceptionJPanel == null) {visibilityConventionExceptionJPanel = new VisibilityConventionExceptionJPanel(appliedRuleController);} return visibilityConventionExceptionJPanel; }else if (ruleTypeKey.equals(NamingConventionJPanel.ruleTypeKey)){ if (namingConventionJPanel == null) {namingConventionJPanel = new NamingConventionJPanel(appliedRuleController);} return namingConventionJPanel; }else if (ruleTypeKey.equals(NamingConventionExceptionJPanel.ruleTypeKey)){ if (namingConventionExceptionJPanel == null) {namingConventionExceptionJPanel = new NamingConventionExceptionJPanel(appliedRuleController);} return namingConventionExceptionJPanel; //Rules of the Legality of Dependency } else if (ruleTypeKey.equals(IsNotAllowedToUseJPanel.ruleTypeKey)) { if (isNotAllowedToUseJPanel == null) {isNotAllowedToUseJPanel = new IsNotAllowedToUseJPanel(appliedRuleController);} return isNotAllowedToUseJPanel; } else if (ruleTypeKey.equals(IsAllowedToUseJPanel.ruleTypeKey)){ if (isAllowedToUseJPanel == null) {isAllowedToUseJPanel = new IsAllowedToUseJPanel(appliedRuleController);} return isAllowedToUseJPanel; }else if (ruleTypeKey.equals(IsOnlyAllowedToUseJPanel.ruleTypeKey)){ if (isOnlyAllowedToUseJPanel == null) {isOnlyAllowedToUseJPanel = new IsOnlyAllowedToUseJPanel(appliedRuleController);} return isOnlyAllowedToUseJPanel; }else if (ruleTypeKey.equals(IsOnlyModuleAllowedToUseJPanel.ruleTypeKey)){ if (isOnlyModuleAllowedToUseJPanel == null) {isOnlyModuleAllowedToUseJPanel = new IsOnlyModuleAllowedToUseJPanel(appliedRuleController);} return isOnlyModuleAllowedToUseJPanel; }else if (ruleTypeKey.equals(MustUseJPanel.ruleTypeKey)){ if (mustUseJPanel == null) {mustUseJPanel = new MustUseJPanel(appliedRuleController);} return mustUseJPanel; }else if (ruleTypeKey.equals(SkipCallJPanel.ruleTypeKey)){ if (skipCallJPanel == null) {skipCallJPanel = new SkipCallJPanel(appliedRuleController);} return skipCallJPanel; }else if (ruleTypeKey.equals(BackCallJPanel.ruleTypeKey)){ if (backCallJPanel == null) {backCallJPanel = new BackCallJPanel(appliedRuleController);} return backCallJPanel; //Rules on the Dependency Limitation }else if (ruleTypeKey.equals(CyclesBetweenModulesJPanel.ruleTypeKey)){ if (cyclesBetweenModules == null) {cyclesBetweenModules = new CyclesBetweenModulesJPanel(appliedRuleController);} return cyclesBetweenModules; }else if (ruleTypeKey.equals(CyclesBetweenModulesExceptionJPanel.ruleTypeKey)){ if (cyclesBetweenModulesExceptionJPanel == null) {cyclesBetweenModulesExceptionJPanel = new CyclesBetweenModulesExceptionJPanel(appliedRuleController);} return cyclesBetweenModulesExceptionJPanel; //Not Known }else { Logger.getLogger(FactoryDetails.class).error("No known AbstractDetailsJPanel for key: " + ruleTypeKey); throw new RuntimeException("No known AbstractDetailsJPanel for key: " + ruleTypeKey); } } }
true
true
public AbstractDetailsJPanel create(AppliedRuleController appliedRuleController, String ruleTypeKey){ //Rules on the Contents of a module if (ruleTypeKey.equals(InterfaceConventionJPanel.ruleTypeKey)){ interfaceConventionJPanel = new InterfaceConventionJPanel(appliedRuleController); return interfaceConventionJPanel; } else if (ruleTypeKey.equals(SubClassConventionJPanel.ruleTypeKey)){ subClassConventionJPanel = new SubClassConventionJPanel(appliedRuleController); return subClassConventionJPanel; } else if (ruleTypeKey.equals(VisibilityConventionJPanel.ruleTypeKey)){ visibilityConventionJPanel = new VisibilityConventionJPanel(appliedRuleController); return visibilityConventionJPanel; }else if (ruleTypeKey.equals(VisibilityConventionExceptionJPanel.ruleTypeKey)){ visibilityConventionExceptionJPanel = new VisibilityConventionExceptionJPanel(appliedRuleController); return visibilityConventionExceptionJPanel; }else if (ruleTypeKey.equals(NamingConventionJPanel.ruleTypeKey)){ namingConventionJPanel = new NamingConventionJPanel(appliedRuleController); return namingConventionJPanel; }else if (ruleTypeKey.equals(NamingConventionExceptionJPanel.ruleTypeKey)){ namingConventionExceptionJPanel = new NamingConventionExceptionJPanel(appliedRuleController); return namingConventionExceptionJPanel; //Rules of the Legality of Dependency } else if (ruleTypeKey.equals(IsNotAllowedToUseJPanel.ruleTypeKey)) { isNotAllowedToUseJPanel = new IsNotAllowedToUseJPanel(appliedRuleController); return isNotAllowedToUseJPanel; } else if (ruleTypeKey.equals(IsAllowedToUseJPanel.ruleTypeKey)){ isAllowedToUseJPanel = new IsAllowedToUseJPanel(appliedRuleController); return isAllowedToUseJPanel; }else if (ruleTypeKey.equals(IsOnlyAllowedToUseJPanel.ruleTypeKey)){ isOnlyAllowedToUseJPanel = new IsOnlyAllowedToUseJPanel(appliedRuleController); return isOnlyAllowedToUseJPanel; }else if (ruleTypeKey.equals(IsOnlyModuleAllowedToUseJPanel.ruleTypeKey)){ isOnlyModuleAllowedToUseJPanel = new IsOnlyModuleAllowedToUseJPanel(appliedRuleController); return isOnlyModuleAllowedToUseJPanel; }else if (ruleTypeKey.equals(MustUseJPanel.ruleTypeKey)){ mustUseJPanel = new MustUseJPanel(appliedRuleController); return mustUseJPanel; }else if (ruleTypeKey.equals(SkipCallJPanel.ruleTypeKey)){ skipCallJPanel = new SkipCallJPanel(appliedRuleController); return skipCallJPanel; }else if (ruleTypeKey.equals(BackCallJPanel.ruleTypeKey)){ backCallJPanel = new BackCallJPanel(appliedRuleController); return backCallJPanel; //Rules on the Dependency Limitation }else if (ruleTypeKey.equals(CyclesBetweenModulesJPanel.ruleTypeKey)){ cyclesBetweenModules = new CyclesBetweenModulesJPanel(appliedRuleController); return cyclesBetweenModules; }else if (ruleTypeKey.equals(CyclesBetweenModulesExceptionJPanel.ruleTypeKey)){ cyclesBetweenModulesExceptionJPanel = new CyclesBetweenModulesExceptionJPanel(appliedRuleController); return cyclesBetweenModulesExceptionJPanel; //Not Known }else { Logger.getLogger(FactoryDetails.class).error("No known AbstractDetailsJPanel for key: " + ruleTypeKey); // throw new RuntimeException("No known AbstractDetailsJPanel for key: " + ruleTypeKey); loopsInModuleExceptionJPanel = new LoopsInModuleExceptionJPanel(appliedRuleController); return loopsInModuleExceptionJPanel; } }
public AbstractDetailsJPanel create(AppliedRuleController appliedRuleController, String ruleTypeKey){ //Rules on the Contents of a module if (ruleTypeKey.equals(InterfaceConventionJPanel.ruleTypeKey)){ interfaceConventionJPanel = new InterfaceConventionJPanel(appliedRuleController); return interfaceConventionJPanel; } else if (ruleTypeKey.equals(SubClassConventionJPanel.ruleTypeKey)){ subClassConventionJPanel = new SubClassConventionJPanel(appliedRuleController); return subClassConventionJPanel; } else if (ruleTypeKey.equals(VisibilityConventionJPanel.ruleTypeKey)){ visibilityConventionJPanel = new VisibilityConventionJPanel(appliedRuleController); return visibilityConventionJPanel; }else if (ruleTypeKey.equals(VisibilityConventionExceptionJPanel.ruleTypeKey)){ visibilityConventionExceptionJPanel = new VisibilityConventionExceptionJPanel(appliedRuleController); return visibilityConventionExceptionJPanel; }else if (ruleTypeKey.equals(NamingConventionJPanel.ruleTypeKey)){ namingConventionJPanel = new NamingConventionJPanel(appliedRuleController); return namingConventionJPanel; }else if (ruleTypeKey.equals(NamingConventionExceptionJPanel.ruleTypeKey)){ namingConventionExceptionJPanel = new NamingConventionExceptionJPanel(appliedRuleController); return namingConventionExceptionJPanel; //Rules of the Legality of Dependency } else if (ruleTypeKey.equals(IsNotAllowedToUseJPanel.ruleTypeKey)) { isNotAllowedToUseJPanel = new IsNotAllowedToUseJPanel(appliedRuleController); return isNotAllowedToUseJPanel; } else if (ruleTypeKey.equals(IsAllowedToUseJPanel.ruleTypeKey)){ isAllowedToUseJPanel = new IsAllowedToUseJPanel(appliedRuleController); return isAllowedToUseJPanel; }else if (ruleTypeKey.equals(IsOnlyAllowedToUseJPanel.ruleTypeKey)){ isOnlyAllowedToUseJPanel = new IsOnlyAllowedToUseJPanel(appliedRuleController); return isOnlyAllowedToUseJPanel; }else if (ruleTypeKey.equals(IsOnlyModuleAllowedToUseJPanel.ruleTypeKey)){ isOnlyModuleAllowedToUseJPanel = new IsOnlyModuleAllowedToUseJPanel(appliedRuleController); return isOnlyModuleAllowedToUseJPanel; }else if (ruleTypeKey.equals(MustUseJPanel.ruleTypeKey)){ mustUseJPanel = new MustUseJPanel(appliedRuleController); return mustUseJPanel; }else if (ruleTypeKey.equals(SkipCallJPanel.ruleTypeKey)){ skipCallJPanel = new SkipCallJPanel(appliedRuleController); return skipCallJPanel; }else if (ruleTypeKey.equals(BackCallJPanel.ruleTypeKey)){ backCallJPanel = new BackCallJPanel(appliedRuleController); return backCallJPanel; //Rules on the Dependency Limitation }else if (ruleTypeKey.equals(CyclesBetweenModulesJPanel.ruleTypeKey)){ cyclesBetweenModules = new CyclesBetweenModulesJPanel(appliedRuleController); return cyclesBetweenModules; }else if (ruleTypeKey.equals(CyclesBetweenModulesExceptionJPanel.ruleTypeKey)){ cyclesBetweenModulesExceptionJPanel = new CyclesBetweenModulesExceptionJPanel(appliedRuleController); return cyclesBetweenModulesExceptionJPanel; //Not Known }else { Logger.getLogger(FactoryDetails.class).error("No known AbstractDetailsJPanel for key: " + ruleTypeKey); // throw new RuntimeException("No known AbstractDetailsJPanel for key: " + ruleTypeKey); cyclesBetweenModules = new CyclesBetweenModulesJPanel(appliedRuleController); return cyclesBetweenModules; } }
diff --git a/core/src/main/groovyx/gaelyk/datastore/DatastoreEntityCoercion.java b/core/src/main/groovyx/gaelyk/datastore/DatastoreEntityCoercion.java index 15d8670..df29479 100644 --- a/core/src/main/groovyx/gaelyk/datastore/DatastoreEntityCoercion.java +++ b/core/src/main/groovyx/gaelyk/datastore/DatastoreEntityCoercion.java @@ -1,96 +1,98 @@ package groovyx.gaelyk.datastore; import groovy.lang.GString; import groovyx.gaelyk.extensions.DatastoreExtensions; import com.google.appengine.api.datastore.Entities; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Text; public class DatastoreEntityCoercion { public static Entity convert(DatastoreEntity<?> dsEntity){ if(dsEntity == null) return null; String kind = dsEntity.getClass().getSimpleName(); Entity entity = null; if(dsEntity.hasDatastoreKey()){ Object key = dsEntity.getDatastoreKey(); if(key instanceof CharSequence && key != null){ if (dsEntity.hasDatastoreParent()) { entity = new Entity(kind, key.toString(), dsEntity.getDatastoreParent()); } else { entity = new Entity(kind, key.toString()); } } else if (key instanceof Number && key != null && ((Number) key).longValue() != 0) { if (dsEntity.hasDatastoreParent()) { entity = new Entity(kind, ((Number) key).longValue(), dsEntity.getDatastoreParent()); } else { entity = new Entity(kind, ((Number) key).longValue()); } + } else if(dsEntity.hasDatastoreParent()){ + entity = new Entity(kind, dsEntity.getDatastoreParent()); } } if(entity == null){ entity = new Entity(kind); } for(String propertyName : dsEntity.getDatastoreIndexedProperties()){ entity.setProperty(propertyName, transformValueForStorage(dsEntity.getProperty(propertyName))); } for(String propertyName : dsEntity.getDatastoreUnindexedProperties()){ entity.setUnindexedProperty(propertyName, transformValueForStorage(dsEntity.getProperty(propertyName))); } return entity; } private static Object transformValueForStorage(Object value) { Object newValue = value instanceof GString ? value.toString() : value; // if we store a string longer than 500 characters // it needs to be wrapped in a Text instance if (newValue instanceof String && ((String)newValue).length() > 500) { newValue = new Text((String) newValue); } return newValue; } @SuppressWarnings("unchecked") public static <E extends DatastoreEntity<?>> E convert(Entity en, Class<E> dsEntityClass) throws InstantiationException, IllegalAccessException{ E dsEntity = dsEntityClass.newInstance(); if(dsEntity.hasDatastoreKey()){ if(dsEntity.hasDatastoreNumericKey()){ ((DatastoreEntity<Long>)dsEntity).setDatastoreKey(en.getKey().getId()); } else { ((DatastoreEntity<String>)dsEntity).setDatastoreKey(en.getKey().getName()); } } if (dsEntity.hasDatastoreParent()) { dsEntity.setDatastoreParent(en.getKey().getParent()); } if (dsEntity.hasDatastoreVersion()) { try { dsEntity.setDatastoreVersion(Entities.getVersionProperty(DatastoreExtensions.get(Entities.createEntityGroupKey(en.getKey())))); } catch (Exception e) { dsEntity.setDatastoreVersion(0); } } for(String propertyName : dsEntity.getDatastoreIndexedProperties()){ setEntityProperty(en, dsEntity, propertyName); } for(String propertyName : dsEntity.getDatastoreUnindexedProperties()){ setEntityProperty(en, dsEntity, propertyName); } return dsEntity; } private static <E extends DatastoreEntity<?>> void setEntityProperty(Entity en, E dsEntity, String propertyName) { Object value = en.getProperty(propertyName); if (value instanceof Text) { dsEntity.setProperty(propertyName, ((Text) value).getValue()); } else { dsEntity.setProperty(propertyName, value); } } }
true
true
public static Entity convert(DatastoreEntity<?> dsEntity){ if(dsEntity == null) return null; String kind = dsEntity.getClass().getSimpleName(); Entity entity = null; if(dsEntity.hasDatastoreKey()){ Object key = dsEntity.getDatastoreKey(); if(key instanceof CharSequence && key != null){ if (dsEntity.hasDatastoreParent()) { entity = new Entity(kind, key.toString(), dsEntity.getDatastoreParent()); } else { entity = new Entity(kind, key.toString()); } } else if (key instanceof Number && key != null && ((Number) key).longValue() != 0) { if (dsEntity.hasDatastoreParent()) { entity = new Entity(kind, ((Number) key).longValue(), dsEntity.getDatastoreParent()); } else { entity = new Entity(kind, ((Number) key).longValue()); } } } if(entity == null){ entity = new Entity(kind); } for(String propertyName : dsEntity.getDatastoreIndexedProperties()){ entity.setProperty(propertyName, transformValueForStorage(dsEntity.getProperty(propertyName))); } for(String propertyName : dsEntity.getDatastoreUnindexedProperties()){ entity.setUnindexedProperty(propertyName, transformValueForStorage(dsEntity.getProperty(propertyName))); } return entity; }
public static Entity convert(DatastoreEntity<?> dsEntity){ if(dsEntity == null) return null; String kind = dsEntity.getClass().getSimpleName(); Entity entity = null; if(dsEntity.hasDatastoreKey()){ Object key = dsEntity.getDatastoreKey(); if(key instanceof CharSequence && key != null){ if (dsEntity.hasDatastoreParent()) { entity = new Entity(kind, key.toString(), dsEntity.getDatastoreParent()); } else { entity = new Entity(kind, key.toString()); } } else if (key instanceof Number && key != null && ((Number) key).longValue() != 0) { if (dsEntity.hasDatastoreParent()) { entity = new Entity(kind, ((Number) key).longValue(), dsEntity.getDatastoreParent()); } else { entity = new Entity(kind, ((Number) key).longValue()); } } else if(dsEntity.hasDatastoreParent()){ entity = new Entity(kind, dsEntity.getDatastoreParent()); } } if(entity == null){ entity = new Entity(kind); } for(String propertyName : dsEntity.getDatastoreIndexedProperties()){ entity.setProperty(propertyName, transformValueForStorage(dsEntity.getProperty(propertyName))); } for(String propertyName : dsEntity.getDatastoreUnindexedProperties()){ entity.setUnindexedProperty(propertyName, transformValueForStorage(dsEntity.getProperty(propertyName))); } return entity; }
diff --git a/src/org/intellij/erlang/editor/ErlangAnnotator.java b/src/org/intellij/erlang/editor/ErlangAnnotator.java index 65aba72b..07ef2cc5 100644 --- a/src/org/intellij/erlang/editor/ErlangAnnotator.java +++ b/src/org/intellij/erlang/editor/ErlangAnnotator.java @@ -1,132 +1,133 @@ package org.intellij.erlang.editor; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.util.io.FileUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.psi.impl.source.tree.LeafPsiElement; import org.intellij.erlang.psi.*; import org.jetbrains.annotations.NotNull; import static org.intellij.erlang.psi.impl.ErlangPsiImplUtil.*; /** * @author ignatov */ public class ErlangAnnotator implements Annotator, DumbAware { @Override public void annotate(@NotNull PsiElement psiElement, @NotNull final AnnotationHolder annotationHolder) { psiElement.accept(new ErlangVisitor() { @Override public void visitQVar(@NotNull ErlangQVar o) { setHighlighting(o, annotationHolder, ErlangSyntaxHighlighter.VARIABLES); if (inDefinition(o) || isLeftPartOfAssignment(o) || inAtomAttribute(o) || isMacros(o) || isForseScipped(o) || inSpecification(o)) return; markIfUnresolved(o, o, annotationHolder, "Unresolved variable " + o.getText()); } @Override public void visitRecordExpression(@NotNull ErlangRecordExpression o) { ErlangQAtom atomName = o.getAtomName(); if (atomName != null) { PsiElement prevSibling = atomName.getPrevSibling(); if (prevSibling != null && "#".equals(prevSibling.getText())) { - markIfUnresolved(o, atomName, annotationHolder, "Unresolved record " + atomName.getText()); + o.getReference(); // todo: rewrite + markIfUnresolved(atomName, atomName, annotationHolder, "Unresolved record " + atomName.getText()); } } } @Override public void visitAtomAttribute(@NotNull ErlangAtomAttribute o) { setHighlighting(o.getQAtom(), annotationHolder, ErlangSyntaxHighlighter.KEYWORD); } @Override public void visitCallbackSpec(@NotNull ErlangCallbackSpec o) { markFirstChildAsKeyword(o, annotationHolder); } @Override public void visitSpecification(@NotNull ErlangSpecification o) { markFirstChildAsKeyword(o, annotationHolder); } @Override public void visitAttribute(@NotNull ErlangAttribute o) { markFirstChildAsKeyword(o, annotationHolder); } @Override public void visitExport(@NotNull ErlangExport o) { markFirstChildAsKeyword(o, annotationHolder); } @Override public void visitInclude(@NotNull ErlangInclude o) { markFirstChildAsKeyword(o, annotationHolder); markAttributeNameAsKeyword(o, annotationHolder, "include"); markAttributeNameAsKeyword(o, annotationHolder, "include_lib"); } @Override public void visitModule(@NotNull ErlangModule o) { markFirstChildAsKeyword(o, annotationHolder); String ext = FileUtil.getExtension(o.getContainingFile().getName()); String withoutExtension = FileUtil.getNameWithoutExtension(o.getContainingFile().getName()); String moduleName = o.getName(); ErlangCompositeElement atom = o.getQAtom(); if (atom != null && !moduleName.equals(withoutExtension)) { annotationHolder.createErrorAnnotation(atom, "Module with name '" + moduleName + "' should be declared in a file named '" + moduleName + "." + ext + "'."); } } @Override public void visitRecordDefinition(@NotNull ErlangRecordDefinition o) { markFirstChildAsKeyword(o, annotationHolder); markAttributeNameAsKeyword(o, annotationHolder, "record"); } @Override public void visitExportFunction(@NotNull ErlangExportFunction o) { markIfUnresolved(o, o, annotationHolder, "Unresolved function " + o.getText()); } // todo: add export, import and other bundled attributes }); } private static void markAttributeNameAsKeyword(ErlangCompositeElement o, AnnotationHolder annotationHolder, String name) { PsiElement rec = o.getFirstChild(); while (rec != null) { if (rec instanceof LeafPsiElement && name.equals(rec.getText())) break; rec = rec.getNextSibling(); } if (rec != null) { setHighlighting(rec, annotationHolder, ErlangSyntaxHighlighter.KEYWORD); } } private static void markIfUnresolved(ErlangCompositeElement o, ErlangCompositeElement errorElement, AnnotationHolder annotationHolder, String text) { PsiReference reference = o.getReference(); if (reference != null && reference.resolve() == null) { annotationHolder.createErrorAnnotation(errorElement, text); } } private static void markFirstChildAsKeyword(ErlangCompositeElement o, AnnotationHolder annotationHolder) { final PsiElement firstChild = o.getFirstChild(); if (firstChild != null) { setHighlighting(firstChild, annotationHolder, ErlangSyntaxHighlighter.KEYWORD); } } private static void setHighlighting(@NotNull PsiElement element, @NotNull AnnotationHolder holder, final TextAttributesKey key) { holder.createInfoAnnotation(element, null).setEnforcedTextAttributes(TextAttributes.ERASE_MARKER); holder.createInfoAnnotation(element, null).setEnforcedTextAttributes(EditorColorsManager.getInstance().getGlobalScheme().getAttributes(key)); } }
true
true
public void annotate(@NotNull PsiElement psiElement, @NotNull final AnnotationHolder annotationHolder) { psiElement.accept(new ErlangVisitor() { @Override public void visitQVar(@NotNull ErlangQVar o) { setHighlighting(o, annotationHolder, ErlangSyntaxHighlighter.VARIABLES); if (inDefinition(o) || isLeftPartOfAssignment(o) || inAtomAttribute(o) || isMacros(o) || isForseScipped(o) || inSpecification(o)) return; markIfUnresolved(o, o, annotationHolder, "Unresolved variable " + o.getText()); } @Override public void visitRecordExpression(@NotNull ErlangRecordExpression o) { ErlangQAtom atomName = o.getAtomName(); if (atomName != null) { PsiElement prevSibling = atomName.getPrevSibling(); if (prevSibling != null && "#".equals(prevSibling.getText())) { markIfUnresolved(o, atomName, annotationHolder, "Unresolved record " + atomName.getText()); } } } @Override public void visitAtomAttribute(@NotNull ErlangAtomAttribute o) { setHighlighting(o.getQAtom(), annotationHolder, ErlangSyntaxHighlighter.KEYWORD); } @Override public void visitCallbackSpec(@NotNull ErlangCallbackSpec o) { markFirstChildAsKeyword(o, annotationHolder); } @Override public void visitSpecification(@NotNull ErlangSpecification o) { markFirstChildAsKeyword(o, annotationHolder); } @Override public void visitAttribute(@NotNull ErlangAttribute o) { markFirstChildAsKeyword(o, annotationHolder); } @Override public void visitExport(@NotNull ErlangExport o) { markFirstChildAsKeyword(o, annotationHolder); } @Override public void visitInclude(@NotNull ErlangInclude o) { markFirstChildAsKeyword(o, annotationHolder); markAttributeNameAsKeyword(o, annotationHolder, "include"); markAttributeNameAsKeyword(o, annotationHolder, "include_lib"); } @Override public void visitModule(@NotNull ErlangModule o) { markFirstChildAsKeyword(o, annotationHolder); String ext = FileUtil.getExtension(o.getContainingFile().getName()); String withoutExtension = FileUtil.getNameWithoutExtension(o.getContainingFile().getName()); String moduleName = o.getName(); ErlangCompositeElement atom = o.getQAtom(); if (atom != null && !moduleName.equals(withoutExtension)) { annotationHolder.createErrorAnnotation(atom, "Module with name '" + moduleName + "' should be declared in a file named '" + moduleName + "." + ext + "'."); } } @Override public void visitRecordDefinition(@NotNull ErlangRecordDefinition o) { markFirstChildAsKeyword(o, annotationHolder); markAttributeNameAsKeyword(o, annotationHolder, "record"); } @Override public void visitExportFunction(@NotNull ErlangExportFunction o) { markIfUnresolved(o, o, annotationHolder, "Unresolved function " + o.getText()); } // todo: add export, import and other bundled attributes }); }
public void annotate(@NotNull PsiElement psiElement, @NotNull final AnnotationHolder annotationHolder) { psiElement.accept(new ErlangVisitor() { @Override public void visitQVar(@NotNull ErlangQVar o) { setHighlighting(o, annotationHolder, ErlangSyntaxHighlighter.VARIABLES); if (inDefinition(o) || isLeftPartOfAssignment(o) || inAtomAttribute(o) || isMacros(o) || isForseScipped(o) || inSpecification(o)) return; markIfUnresolved(o, o, annotationHolder, "Unresolved variable " + o.getText()); } @Override public void visitRecordExpression(@NotNull ErlangRecordExpression o) { ErlangQAtom atomName = o.getAtomName(); if (atomName != null) { PsiElement prevSibling = atomName.getPrevSibling(); if (prevSibling != null && "#".equals(prevSibling.getText())) { o.getReference(); // todo: rewrite markIfUnresolved(atomName, atomName, annotationHolder, "Unresolved record " + atomName.getText()); } } } @Override public void visitAtomAttribute(@NotNull ErlangAtomAttribute o) { setHighlighting(o.getQAtom(), annotationHolder, ErlangSyntaxHighlighter.KEYWORD); } @Override public void visitCallbackSpec(@NotNull ErlangCallbackSpec o) { markFirstChildAsKeyword(o, annotationHolder); } @Override public void visitSpecification(@NotNull ErlangSpecification o) { markFirstChildAsKeyword(o, annotationHolder); } @Override public void visitAttribute(@NotNull ErlangAttribute o) { markFirstChildAsKeyword(o, annotationHolder); } @Override public void visitExport(@NotNull ErlangExport o) { markFirstChildAsKeyword(o, annotationHolder); } @Override public void visitInclude(@NotNull ErlangInclude o) { markFirstChildAsKeyword(o, annotationHolder); markAttributeNameAsKeyword(o, annotationHolder, "include"); markAttributeNameAsKeyword(o, annotationHolder, "include_lib"); } @Override public void visitModule(@NotNull ErlangModule o) { markFirstChildAsKeyword(o, annotationHolder); String ext = FileUtil.getExtension(o.getContainingFile().getName()); String withoutExtension = FileUtil.getNameWithoutExtension(o.getContainingFile().getName()); String moduleName = o.getName(); ErlangCompositeElement atom = o.getQAtom(); if (atom != null && !moduleName.equals(withoutExtension)) { annotationHolder.createErrorAnnotation(atom, "Module with name '" + moduleName + "' should be declared in a file named '" + moduleName + "." + ext + "'."); } } @Override public void visitRecordDefinition(@NotNull ErlangRecordDefinition o) { markFirstChildAsKeyword(o, annotationHolder); markAttributeNameAsKeyword(o, annotationHolder, "record"); } @Override public void visitExportFunction(@NotNull ErlangExportFunction o) { markIfUnresolved(o, o, annotationHolder, "Unresolved function " + o.getText()); } // todo: add export, import and other bundled attributes }); }
diff --git a/src/main/java/com/censoredsoftware/Demigods/Episodes/Demo/Structure/Obelisk.java b/src/main/java/com/censoredsoftware/Demigods/Episodes/Demo/Structure/Obelisk.java index 561bd03a..7d100b5a 100644 --- a/src/main/java/com/censoredsoftware/Demigods/Episodes/Demo/Structure/Obelisk.java +++ b/src/main/java/com/censoredsoftware/Demigods/Episodes/Demo/Structure/Obelisk.java @@ -1,320 +1,320 @@ package com.censoredsoftware.Demigods.Episodes.Demo.Structure; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import com.censoredsoftware.Demigods.Engine.Demigods; import com.censoredsoftware.Demigods.Engine.Object.Player.PlayerCharacter; import com.censoredsoftware.Demigods.Engine.Object.Player.PlayerWrapper; import com.censoredsoftware.Demigods.Engine.Object.Structure.StructureBlockData; import com.censoredsoftware.Demigods.Engine.Object.Structure.StructureInfo; import com.censoredsoftware.Demigods.Engine.Object.Structure.StructureSave; import com.censoredsoftware.Demigods.Engine.Object.Structure.StructureSchematic; import com.censoredsoftware.Demigods.Engine.Utility.AdminUtility; import com.censoredsoftware.Demigods.Engine.Utility.DataUtility; import com.censoredsoftware.Demigods.Engine.Utility.StructureUtility; import com.censoredsoftware.Demigods.Engine.Utility.TextUtility; import com.censoredsoftware.Demigods.Episodes.Demo.EpisodeDemo; public class Obelisk implements StructureInfo { @Override public Set<Flag> getFlags() { return new HashSet<Flag>() { { add(Flag.HAS_OWNER); add(Flag.NO_GRIEFING_ZONE); add(Flag.PROTECTED_BLOCKS); } }; } @Override public String getStructureType() { return "Obelisk"; } @Override public Set<StructureSchematic> getSchematics() { return new HashSet<StructureSchematic>() { { // Clickable block. add(new StructureSchematic(0, 0, 2, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK, (byte) 3)); } })); // Everything else. - add(new StructureSchematic(0, 0, -1, 1, 3, 0, new ArrayList<StructureBlockData>() + add(new StructureSchematic(1, 0, -1, 1, 3, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); - add(new StructureSchematic(0, 0, 1, 1, 3, 2, new ArrayList<StructureBlockData>() + add(new StructureSchematic(1, 0, 1, 1, 3, 2, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); - add(new StructureSchematic(1, 0, 0, 2, 3, 1, new ArrayList<StructureBlockData>() + add(new StructureSchematic(2, 0, 0, 2, 3, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); - add(new StructureSchematic(-1, 0, 0, 0, 3, 1, new ArrayList<StructureBlockData>() + add(new StructureSchematic(-1, 0, 0, -1, 3, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(0, 3, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_BLOCK)); } })); add(new StructureSchematic(0, 4, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_BLOCK)); } })); add(new StructureSchematic(0, 3, -1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_LAMP_ON)); } })); add(new StructureSchematic(0, 3, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_LAMP_ON)); } })); add(new StructureSchematic(1, 3, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_LAMP_ON)); } })); add(new StructureSchematic(-1, 3, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_LAMP_ON)); } })); add(new StructureSchematic(0, 5, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_LAMP_ON)); } })); - add(new StructureSchematic(0, 4, -1, 1, 6, 0, new ArrayList<StructureBlockData>() + add(new StructureSchematic(1, 4, -1, 1, 6, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); - add(new StructureSchematic(0, 4, 1, 1, 6, 2, new ArrayList<StructureBlockData>() + add(new StructureSchematic(1, 4, 1, 1, 6, 2, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); - add(new StructureSchematic(1, 4, 0, 2, 6, 1, new ArrayList<StructureBlockData>() + add(new StructureSchematic(2, 4, 0, 2, 6, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); - add(new StructureSchematic(-1, 4, 0, 0, 6, 1, new ArrayList<StructureBlockData>() + add(new StructureSchematic(-1, 4, 0, -1, 6, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(-1, 5, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.VINE, (byte) 4, 2)); add(new StructureBlockData(Material.AIR, (byte) 0, 3)); } })); add(new StructureSchematic(1, 5, -1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.VINE, (byte) 1, 2)); add(new StructureBlockData(Material.AIR, (byte) 0, 3)); } })); add(new StructureSchematic(1, 5, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.VINE, (byte) 4, 2)); add(new StructureBlockData(Material.AIR, (byte) 0, 3)); } })); add(new StructureSchematic(-1, 5, -1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.VINE, (byte) 1, 2)); add(new StructureBlockData(Material.AIR, (byte) 0, 3)); } })); } }; } @Override public int getRadius() { return Demigods.config.getSettingInt("zones.obelisk_radius"); } @Override public Location getClickableBlock(Location reference) { return reference.clone().add(0, 0, 2); } @Override public Listener getUniqueListener() { return new ObeliskListener(); } @Override public Set<StructureSave> getAll() { return new HashSet<StructureSave>() { { for(StructureSave saved : StructureSave.loadAll()) { if(saved.getStructureInfo().getStructureType().equals(getStructureType())) add(saved); } } }; } @Override public StructureSave createNew(Location reference, boolean generate) { StructureSave save = new StructureSave(); save.setReferenceLocation(reference); save.setStructureType(getStructureType()); save.save(); if(generate) save.generate(); return save; } public static boolean validBlockConfiguration(Block block) { if(!block.getType().equals(Material.REDSTONE_BLOCK)) return false; if(!block.getRelative(1, 0, 0).getType().equals(Material.COBBLESTONE)) return false; if(!block.getRelative(-1, 0, 0).getType().equals(Material.COBBLESTONE)) return false; if(!block.getRelative(0, 0, 1).getType().equals(Material.COBBLESTONE)) return false; if(!block.getRelative(0, 0, -1).getType().equals(Material.COBBLESTONE)) return false; if(block.getRelative(1, 0, 1).getType().isSolid()) return false; if(block.getRelative(1, 0, -1).getType().isSolid()) return false; return !block.getRelative(-1, 0, 1).getType().isSolid() && !block.getRelative(-1, 0, -1).getType().isSolid(); } public static boolean noPvPStructureNearby(Location location) { for(StructureSave structureSave : StructureSave.loadAll()) { if(structureSave.getStructureInfo().getFlags().contains(Flag.NO_PVP_ZONE) && structureSave.getReferenceLocation().distance(location) <= (Demigods.config.getSettingInt("altar_radius") + Demigods.config.getSettingInt("obelisk_radius") + 6)) return true; } return false; } } class ObeliskListener implements Listener { @EventHandler(priority = EventPriority.HIGH) public void createAndRemove(PlayerInteractEvent event) { if(event.getClickedBlock() == null) return; // Define variables Block clickedBlock = event.getClickedBlock(); Location location = clickedBlock.getLocation(); Player player = event.getPlayer(); if(PlayerWrapper.isImmortal(player)) { PlayerCharacter character = PlayerWrapper.getPlayer(player).getCurrent(); if(event.getAction() == Action.RIGHT_CLICK_BLOCK && character.getDeity().getInfo().getClaimItems().contains(event.getPlayer().getItemInHand().getType()) && Obelisk.validBlockConfiguration(event.getClickedBlock())) { if(Obelisk.noPvPStructureNearby(location)) { player.sendMessage(ChatColor.YELLOW + "This location is too close to a no-pvp zone, please try again."); return; } try { // Obelisk created! AdminUtility.sendDebug(ChatColor.RED + "Obelisk created by " + character.getName() + " at: " + ChatColor.GRAY + "(" + location.getWorld().getName() + ") " + location.getX() + ", " + location.getY() + ", " + location.getZ()); StructureSave save = EpisodeDemo.Structures.OBELISK.getStructure().createNew(location, true); save.setOwner(character); location.getWorld().strikeLightningEffect(location); player.sendMessage(ChatColor.GRAY + Demigods.text.getText(TextUtility.Text.CREATE_OBELISK)); } catch(Exception e) { // Creation of shrine failed... e.printStackTrace(); } } } if(AdminUtility.useWand(player) && StructureUtility.partOfStructureWithType(location, "Obelisk")) { event.setCancelled(true); StructureSave save = StructureUtility.getStructure(location); PlayerCharacter owner = save.getOwner(); if(DataUtility.hasTimed(player.getName(), "destroy_obelisk")) { // Remove the Obelisk save.remove(); DataUtility.removeTimed(player.getName(), "destroy_obelisk"); AdminUtility.sendDebug(ChatColor.RED + "Obelisk owned by (" + owner.getName() + ") at: " + ChatColor.GRAY + "(" + location.getWorld().getName() + ") " + location.getX() + ", " + location.getY() + ", " + location.getZ() + " removed."); player.sendMessage(ChatColor.GREEN + Demigods.text.getText(TextUtility.Text.ADMIN_WAND_REMOVE_SHRINE_COMPLETE)); } else { DataUtility.saveTimed(player.getName(), "destroy_obelisk", true, 5); player.sendMessage(ChatColor.RED + Demigods.text.getText(TextUtility.Text.ADMIN_WAND_REMOVE_SHRINE)); } } } }
false
true
public Set<StructureSchematic> getSchematics() { return new HashSet<StructureSchematic>() { { // Clickable block. add(new StructureSchematic(0, 0, 2, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK, (byte) 3)); } })); // Everything else. add(new StructureSchematic(0, 0, -1, 1, 3, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(0, 0, 1, 1, 3, 2, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(1, 0, 0, 2, 3, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(-1, 0, 0, 0, 3, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(0, 3, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_BLOCK)); } })); add(new StructureSchematic(0, 4, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_BLOCK)); } })); add(new StructureSchematic(0, 3, -1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_LAMP_ON)); } })); add(new StructureSchematic(0, 3, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_LAMP_ON)); } })); add(new StructureSchematic(1, 3, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_LAMP_ON)); } })); add(new StructureSchematic(-1, 3, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_LAMP_ON)); } })); add(new StructureSchematic(0, 5, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_LAMP_ON)); } })); add(new StructureSchematic(0, 4, -1, 1, 6, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(0, 4, 1, 1, 6, 2, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(1, 4, 0, 2, 6, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(-1, 4, 0, 0, 6, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(-1, 5, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.VINE, (byte) 4, 2)); add(new StructureBlockData(Material.AIR, (byte) 0, 3)); } })); add(new StructureSchematic(1, 5, -1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.VINE, (byte) 1, 2)); add(new StructureBlockData(Material.AIR, (byte) 0, 3)); } })); add(new StructureSchematic(1, 5, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.VINE, (byte) 4, 2)); add(new StructureBlockData(Material.AIR, (byte) 0, 3)); } })); add(new StructureSchematic(-1, 5, -1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.VINE, (byte) 1, 2)); add(new StructureBlockData(Material.AIR, (byte) 0, 3)); } })); } }; }
public Set<StructureSchematic> getSchematics() { return new HashSet<StructureSchematic>() { { // Clickable block. add(new StructureSchematic(0, 0, 2, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK, (byte) 3)); } })); // Everything else. add(new StructureSchematic(1, 0, -1, 1, 3, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(1, 0, 1, 1, 3, 2, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(2, 0, 0, 2, 3, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(-1, 0, 0, -1, 3, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(0, 3, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_BLOCK)); } })); add(new StructureSchematic(0, 4, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_BLOCK)); } })); add(new StructureSchematic(0, 3, -1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_LAMP_ON)); } })); add(new StructureSchematic(0, 3, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_LAMP_ON)); } })); add(new StructureSchematic(1, 3, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_LAMP_ON)); } })); add(new StructureSchematic(-1, 3, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_LAMP_ON)); } })); add(new StructureSchematic(0, 5, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.REDSTONE_LAMP_ON)); } })); add(new StructureSchematic(1, 4, -1, 1, 6, 0, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(1, 4, 1, 1, 6, 2, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(2, 4, 0, 2, 6, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(-1, 4, 0, -1, 6, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.SMOOTH_BRICK)); } })); add(new StructureSchematic(-1, 5, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.VINE, (byte) 4, 2)); add(new StructureBlockData(Material.AIR, (byte) 0, 3)); } })); add(new StructureSchematic(1, 5, -1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.VINE, (byte) 1, 2)); add(new StructureBlockData(Material.AIR, (byte) 0, 3)); } })); add(new StructureSchematic(1, 5, 1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.VINE, (byte) 4, 2)); add(new StructureBlockData(Material.AIR, (byte) 0, 3)); } })); add(new StructureSchematic(-1, 5, -1, new ArrayList<StructureBlockData>() { { add(new StructureBlockData(Material.VINE, (byte) 1, 2)); add(new StructureBlockData(Material.AIR, (byte) 0, 3)); } })); } }; }
diff --git a/src/main/java/org/vanbest/xmltv/Main.java b/src/main/java/org/vanbest/xmltv/Main.java index a633079..782cc32 100644 --- a/src/main/java/org/vanbest/xmltv/Main.java +++ b/src/main/java/org/vanbest/xmltv/Main.java @@ -1,439 +1,440 @@ package org.vanbest.xmltv; /* Copyright (c) 2012 Jan-Pascal van Best <[email protected]> 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. The full license text can be found in the LICENSE file. */ import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.Parser; import org.apache.commons.io.FileUtils; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class Main { private File configFile; private Config config; private PrintStream outputWriter; private int days = 5; private int offset = 0; private boolean clearCache = false; static Logger logger = Logger.getLogger(Main.class); /** * @param args */ public Main() { this.configFile = defaultConfigFile(); this.outputWriter = System.out; //PropertyConfigurator.configure(args[0]); } public void showHeader() { logger.info("tv_grab_nl_java version "+config.project_version + " (built "+config.build_time+")"); logger.info("Copyright (C) 2012 Jan-Pascal van Best <[email protected]>"); logger.info("tv_grab_nl_java comes with ABSOLUTELY NO WARRANTY. It is free software, and you are welcome to redistribute it"); logger.info("under certain conditions; `tv_grab_nl_java --license' for details."); } public void run() throws FactoryConfigurationError, Exception { if (!config.quiet) { showHeader(); logger.info("Fetching programme data for " + this.days + " days starting from day " + this.offset); int enabledCount = 0; for(Channel c: config.channels) { if (c.enabled) enabledCount++; } logger.info("... from " + enabledCount + " channels"); logger.info("... using cache at " + config.cacheDbHandle); } if (clearCache) { ProgrammeCache cache = new ProgrammeCache(config); cache.clear(); cache.close(); } Map<Integer,EPGSource> guides = new HashMap<Integer,EPGSource>(); EPGSourceFactory factory = EPGSourceFactory.newInstance(); //EPGSource gids = new TvGids(config); //if (clearCache) gids.clearCache(); XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(outputWriter); writer.writeStartDocument(); writer.writeCharacters("\n"); writer.writeDTD("<!DOCTYPE tv SYSTEM \"xmltv.dtd\">"); writer.writeCharacters("\n"); writer.writeStartElement("tv"); writer.writeAttribute("generator-info-url","http://github.com/janpascal/tv_grab_nl_java"); writer.writeAttribute("source-info-url", "http://tvgids.nl/"); writer.writeAttribute("source-info-name", "TvGids.nl"); writer.writeAttribute("generator-info-name", "tv_grab_nl_java release "+config.project_version + ", built " + config.build_time); writer.writeCharacters(System.getProperty("line.separator")); for(Channel c: config.channels) if (c.enabled) c.serialize(writer); for (int day=offset; day<offset+days; day++) { if (!config.quiet) System.out.print("Fetching information for day " + day); for(Channel c: config.channels) { if (!c.enabled) continue; if (!config.quiet) System.out.print("."); if(!guides.containsKey(c.source)) { guides.put(c.source, factory.createEPGSource(c.source, config)); } List<Programme> programmes = guides.get(c.source).getProgrammes(c, day); for (Programme p: programmes) p.serialize(writer); writer.flush(); } if (!config.quiet) System.out.println(); } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); for(int source: guides.keySet()) { guides.get(source).close(); } if (!config.quiet) { EPGSource.Stats stats = new EPGSource.Stats(); for(int source: guides.keySet()) { EPGSource.Stats part = guides.get(source).getStats(); stats.cacheHits += part.cacheHits; stats.cacheMisses += part.cacheMisses; stats.fetchErrors += part.fetchErrors; } logger.info("Number of programmes from cache: " + stats.cacheHits); logger.info("Number of programmes fetched: " + stats.cacheMisses); logger.warn("Number of fetch errors: " + stats.fetchErrors); } } public void configure() throws IOException { showHeader(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Delay between each request to the server (in milliseconds, default="+config.niceMilliseconds+"):"); while(true) { String s = reader.readLine().toLowerCase(); if (s.isEmpty()) { break; } try { config.niceMilliseconds = Integer.parseInt(s); break; } catch (NumberFormatException e) { System.out.println("\""+s+"\" is not a valid number, please try again"); continue; } } // TODO configure cache location // public String cacheDbHandle; // public String cacheDbUser; // public String cacheDbPassword; Set<String> oldChannels = new HashSet<String>(); Set<Integer> oldGuides = new HashSet<Integer>(); for (Channel c: config.channels) { if (c.enabled) { oldChannels.add(c.source+"::"+c.id); oldGuides.add(c.source); } } EPGSourceFactory factory = EPGSourceFactory.newInstance(); int[] sources = factory.getAll(); System.out.println("Please select the TV programme information sources to use"); List<EPGSource> guides = new ArrayList<EPGSource>(); for(int source: sources) { boolean selected = oldGuides.contains(source); EPGSource guide = factory.createEPGSource(source, config); System.out.print(" Use \"" + guide.getName() + "\" (Y/N, default=" + (selected?"Y":"N")+"):"); while(true) { String s = reader.readLine().toLowerCase(); if (s.isEmpty()) { if(selected) guides.add(guide); break; } else if (s.startsWith("y")) { guides.add(guide); break; } else if (s.startsWith("n")) { break; } } } List<Channel> channels = new ArrayList<Channel>(); for(EPGSource guide: guides) { channels.addAll(guide.getChannels()); } boolean all = false; boolean none = false; boolean keep = false; for (Channel c: channels) { boolean selected = oldChannels.contains(c.source+"::"+c.id); System.out.print("add channel " + c.getXmltvChannelId() + " (" + c.defaultName() + ") [[y]es,[n]o,[a]ll,[none],[k]eep selection (default=" + (selected?"yes":"no") + ")] "); if (keep) { c.enabled = selected; System.out.println(selected?"Y":"N"); continue; } if (all) { c.enabled = true; System.out.println("Y"); continue; } if (none) { c.enabled = false; System.out.println("N"); continue; } while(true) { String s = reader.readLine().toLowerCase(); if (s.isEmpty()) { c.enabled = selected; break; } else if ( s.startsWith("k")) { c.enabled = selected; keep = true; break; } else if ( s.startsWith("y")) { c.enabled = true; break; } else if ( s.startsWith("a")) { c.enabled = true; all = true; break; } else if ( s.startsWith("none")) { c.enabled = false; none = true; break; } else if ( s.startsWith("n")) { c.enabled = false; break; } } } config.setChannels(channels); try { config.writeConfig(configFile); logger.info("Configuration file written to " + configFile.getPath()); } catch (FileNotFoundException e) { logger.warn("File not found trying to write config file to "+configFile.getPath(), e); } catch (IOException e) { logger.warn("IO Exception trying to write config file to "+configFile.getPath(), e); } } static String copyright = "Copyright (c) 2012 Jan-Pascal van Best <[email protected]>" + System.getProperty("line.separator") + "" + System.getProperty("line.separator") + "This program is free software; you can redistribute it and/or modify" + System.getProperty("line.separator") + "it under the terms of the GNU General Public License as published by" + System.getProperty("line.separator") + "the Free Software Foundation; either version 2 of the License, or" + System.getProperty("line.separator") + "(at your option) any later version." + System.getProperty("line.separator") + "" + System.getProperty("line.separator") + "This program is distributed in the hope that it will be useful," + System.getProperty("line.separator") + "but WITHOUT ANY WARRANTY; without even the implied warranty of" + System.getProperty("line.separator") + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the" + System.getProperty("line.separator") + "GNU General Public License for more details." + System.getProperty("line.separator") + "" + System.getProperty("line.separator") + "You should have received a copy of the GNU General Public License along" + System.getProperty("line.separator") + "with this program; if not, write to the Free Software Foundation, Inc.," + System.getProperty("line.separator") + "51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA."; public void showLicense() { System.out.println(copyright); } public void processOptions(String[] args) throws FileNotFoundException { Options options = new Options(); options.addOption(OptionBuilder .withLongOpt("description") .withDescription("Display a description to identify this grabber") .create()) .addOption(OptionBuilder .withLongOpt("capabilities") .withDescription("Show grabber capabilities") .create()) .addOption(OptionBuilder .withLongOpt("quiet") .withDescription("Be quiet") .create()) .addOption(OptionBuilder .withLongOpt("output") .hasArg() .withDescription("Set xlmtv output filename") .create()) .addOption(OptionBuilder .withLongOpt("days") .hasArg() .withDescription("Number of days to grab") .create()) .addOption(OptionBuilder .withLongOpt("offset") .hasArg() .withDescription("Start day for grabbing (0=today)") .create()) .addOption(OptionBuilder .withLongOpt("configure") .withDescription("Interactive configuration") .create()) .addOption(OptionBuilder .withLongOpt("config-file") .hasArg() .withDescription("Configuration file location") .create()) .addOption(OptionBuilder .withLongOpt("cache") .hasArg() .withDescription("Cache file location") .create()) .addOption(OptionBuilder .withLongOpt("clear-cache") .withDescription("Clear cache, remove all cached info") .create()) .addOption(OptionBuilder .withLongOpt("help") .withDescription("Show this help") .create()) .addOption(OptionBuilder .withLongOpt("log-level") .hasArg() .withDescription("Set log level (ERROR,WARN,INFO,DEBUG,TRACE)") .create()) .addOption(OptionBuilder .withLongOpt("license") .withDescription("Show license information") .create()); //.addOption(OptionBuilder.withLongOpt("preferredmethod").withDescription("Show preferred method").create(); CommandLine line = null; try { line = new GnuParser().parse(options, args); } catch (ParseException e) { logger.error("Error parsing command-line options", e); } if(line.hasOption("license")) { showHeader(); showLicense(); System.exit(0); } if(line.hasOption("config-file")) { configFile = new File(line.getOptionValue("config-file")); } config = Config.readConfig(configFile); if (line.hasOption("quiet")) { config.quiet = true; + Logger.getRootLogger().setLevel(Level.ERROR); } if (line.hasOption("description")) { showHeader(); System.out.println(); System.out.println("tv_grab_nl_java is a parser for Dutch TV listings using the tvgids.nl JSON interface"); System.exit(0); } if (line.hasOption("help")) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "tv_grab_nl_java", options ); System.exit(0); } if (line.hasOption("output")) { this.outputWriter = new PrintStream( new FileOutputStream(line.getOptionValue("output"))); } if (line.hasOption("log-level")) { String arg = line.getOptionValue("log-level"); - // TODO: make distinction between levels for console and - // file appenders - Logger.getRootLogger().setLevel(Level.toLevel(arg, Level.INFO)); + // TODO: make distinction between levels for console and + // file appenders + Logger.getRootLogger().setLevel(Level.toLevel(arg, Level.INFO)); } if (line.hasOption("cache")) { config.setCacheFile(line.getOptionValue("cache")); } if (line.hasOption("clear-cache")) { clearCache = true; } if (line.hasOption("days")) { this.days = Integer.parseInt(line.getOptionValue("days")); } if (line.hasOption("offset")) { this.offset = Integer.parseInt(line.getOptionValue("offset")); } if (line.hasOption("capabilities")) { System.out.println("baseline"); System.out.println("manualconfig"); System.out.println("cache"); // System.out.println("preferredmethod"); System.exit(0); } if (line.hasOption("configure")) { try { configure(); } catch (IOException e) { logger.warn("Exception during configure"); logger.debug("Stack trace: ", e); } System.exit(0); } } public static File defaultConfigFile() { return FileUtils.getFile(FileUtils.getUserDirectory(), ".xmltv", "tv_grab_nl_java.conf"); } public static void main(String[] args) { Main main = new Main(); try { main.processOptions(args); main.run(); } catch (Exception e) { logger.error("Error in tv_grab_nl_java application", e); } } }
false
true
public void processOptions(String[] args) throws FileNotFoundException { Options options = new Options(); options.addOption(OptionBuilder .withLongOpt("description") .withDescription("Display a description to identify this grabber") .create()) .addOption(OptionBuilder .withLongOpt("capabilities") .withDescription("Show grabber capabilities") .create()) .addOption(OptionBuilder .withLongOpt("quiet") .withDescription("Be quiet") .create()) .addOption(OptionBuilder .withLongOpt("output") .hasArg() .withDescription("Set xlmtv output filename") .create()) .addOption(OptionBuilder .withLongOpt("days") .hasArg() .withDescription("Number of days to grab") .create()) .addOption(OptionBuilder .withLongOpt("offset") .hasArg() .withDescription("Start day for grabbing (0=today)") .create()) .addOption(OptionBuilder .withLongOpt("configure") .withDescription("Interactive configuration") .create()) .addOption(OptionBuilder .withLongOpt("config-file") .hasArg() .withDescription("Configuration file location") .create()) .addOption(OptionBuilder .withLongOpt("cache") .hasArg() .withDescription("Cache file location") .create()) .addOption(OptionBuilder .withLongOpt("clear-cache") .withDescription("Clear cache, remove all cached info") .create()) .addOption(OptionBuilder .withLongOpt("help") .withDescription("Show this help") .create()) .addOption(OptionBuilder .withLongOpt("log-level") .hasArg() .withDescription("Set log level (ERROR,WARN,INFO,DEBUG,TRACE)") .create()) .addOption(OptionBuilder .withLongOpt("license") .withDescription("Show license information") .create()); //.addOption(OptionBuilder.withLongOpt("preferredmethod").withDescription("Show preferred method").create(); CommandLine line = null; try { line = new GnuParser().parse(options, args); } catch (ParseException e) { logger.error("Error parsing command-line options", e); } if(line.hasOption("license")) { showHeader(); showLicense(); System.exit(0); } if(line.hasOption("config-file")) { configFile = new File(line.getOptionValue("config-file")); } config = Config.readConfig(configFile); if (line.hasOption("quiet")) { config.quiet = true; } if (line.hasOption("description")) { showHeader(); System.out.println(); System.out.println("tv_grab_nl_java is a parser for Dutch TV listings using the tvgids.nl JSON interface"); System.exit(0); } if (line.hasOption("help")) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "tv_grab_nl_java", options ); System.exit(0); } if (line.hasOption("output")) { this.outputWriter = new PrintStream( new FileOutputStream(line.getOptionValue("output"))); } if (line.hasOption("log-level")) { String arg = line.getOptionValue("log-level"); // TODO: make distinction between levels for console and // file appenders Logger.getRootLogger().setLevel(Level.toLevel(arg, Level.INFO)); } if (line.hasOption("cache")) { config.setCacheFile(line.getOptionValue("cache")); } if (line.hasOption("clear-cache")) { clearCache = true; } if (line.hasOption("days")) { this.days = Integer.parseInt(line.getOptionValue("days")); } if (line.hasOption("offset")) { this.offset = Integer.parseInt(line.getOptionValue("offset")); } if (line.hasOption("capabilities")) { System.out.println("baseline"); System.out.println("manualconfig"); System.out.println("cache"); // System.out.println("preferredmethod"); System.exit(0); } if (line.hasOption("configure")) { try { configure(); } catch (IOException e) { logger.warn("Exception during configure"); logger.debug("Stack trace: ", e); } System.exit(0); } }
public void processOptions(String[] args) throws FileNotFoundException { Options options = new Options(); options.addOption(OptionBuilder .withLongOpt("description") .withDescription("Display a description to identify this grabber") .create()) .addOption(OptionBuilder .withLongOpt("capabilities") .withDescription("Show grabber capabilities") .create()) .addOption(OptionBuilder .withLongOpt("quiet") .withDescription("Be quiet") .create()) .addOption(OptionBuilder .withLongOpt("output") .hasArg() .withDescription("Set xlmtv output filename") .create()) .addOption(OptionBuilder .withLongOpt("days") .hasArg() .withDescription("Number of days to grab") .create()) .addOption(OptionBuilder .withLongOpt("offset") .hasArg() .withDescription("Start day for grabbing (0=today)") .create()) .addOption(OptionBuilder .withLongOpt("configure") .withDescription("Interactive configuration") .create()) .addOption(OptionBuilder .withLongOpt("config-file") .hasArg() .withDescription("Configuration file location") .create()) .addOption(OptionBuilder .withLongOpt("cache") .hasArg() .withDescription("Cache file location") .create()) .addOption(OptionBuilder .withLongOpt("clear-cache") .withDescription("Clear cache, remove all cached info") .create()) .addOption(OptionBuilder .withLongOpt("help") .withDescription("Show this help") .create()) .addOption(OptionBuilder .withLongOpt("log-level") .hasArg() .withDescription("Set log level (ERROR,WARN,INFO,DEBUG,TRACE)") .create()) .addOption(OptionBuilder .withLongOpt("license") .withDescription("Show license information") .create()); //.addOption(OptionBuilder.withLongOpt("preferredmethod").withDescription("Show preferred method").create(); CommandLine line = null; try { line = new GnuParser().parse(options, args); } catch (ParseException e) { logger.error("Error parsing command-line options", e); } if(line.hasOption("license")) { showHeader(); showLicense(); System.exit(0); } if(line.hasOption("config-file")) { configFile = new File(line.getOptionValue("config-file")); } config = Config.readConfig(configFile); if (line.hasOption("quiet")) { config.quiet = true; Logger.getRootLogger().setLevel(Level.ERROR); } if (line.hasOption("description")) { showHeader(); System.out.println(); System.out.println("tv_grab_nl_java is a parser for Dutch TV listings using the tvgids.nl JSON interface"); System.exit(0); } if (line.hasOption("help")) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "tv_grab_nl_java", options ); System.exit(0); } if (line.hasOption("output")) { this.outputWriter = new PrintStream( new FileOutputStream(line.getOptionValue("output"))); } if (line.hasOption("log-level")) { String arg = line.getOptionValue("log-level"); // TODO: make distinction between levels for console and // file appenders Logger.getRootLogger().setLevel(Level.toLevel(arg, Level.INFO)); } if (line.hasOption("cache")) { config.setCacheFile(line.getOptionValue("cache")); } if (line.hasOption("clear-cache")) { clearCache = true; } if (line.hasOption("days")) { this.days = Integer.parseInt(line.getOptionValue("days")); } if (line.hasOption("offset")) { this.offset = Integer.parseInt(line.getOptionValue("offset")); } if (line.hasOption("capabilities")) { System.out.println("baseline"); System.out.println("manualconfig"); System.out.println("cache"); // System.out.println("preferredmethod"); System.exit(0); } if (line.hasOption("configure")) { try { configure(); } catch (IOException e) { logger.warn("Exception during configure"); logger.debug("Stack trace: ", e); } System.exit(0); } }
diff --git a/web/src/main/java/org/fao/geonet/monitor/health/DatabaseHealthCheck.java b/web/src/main/java/org/fao/geonet/monitor/health/DatabaseHealthCheck.java index ebd88ab713..5a0e5db242 100644 --- a/web/src/main/java/org/fao/geonet/monitor/health/DatabaseHealthCheck.java +++ b/web/src/main/java/org/fao/geonet/monitor/health/DatabaseHealthCheck.java @@ -1,37 +1,37 @@ package org.fao.geonet.monitor.health; import com.yammer.metrics.core.HealthCheck; import jeeves.monitor.HealthCheckFactory; import jeeves.resources.dbms.Dbms; import jeeves.server.context.ServiceContext; import org.fao.geonet.constants.Geonet; /** * Checks to ensure that the database is accessible and readable * <p/> * User: jeichar * Date: 3/26/12 * Time: 9:01 AM */ public class DatabaseHealthCheck implements HealthCheckFactory { public HealthCheck create(final ServiceContext context) { return new HealthCheck("Database Connection") { @Override protected Result check() throws Exception { Dbms dbms = null; try { // TODO add timeout dbms = (Dbms) context.getResourceManager().openDirect(Geonet.Res.MAIN_DB); - dbms.select("SELECT id from Metadata LIMIT 1"); + dbms.select("SELECT count(*) from settings"); return Result.healthy(); } catch (Throwable e) { return Result.unhealthy(e); } finally { if (dbms != null) context.getResourceManager().close(Geonet.Res.MAIN_DB, dbms); } } }; } }
true
true
public HealthCheck create(final ServiceContext context) { return new HealthCheck("Database Connection") { @Override protected Result check() throws Exception { Dbms dbms = null; try { // TODO add timeout dbms = (Dbms) context.getResourceManager().openDirect(Geonet.Res.MAIN_DB); dbms.select("SELECT id from Metadata LIMIT 1"); return Result.healthy(); } catch (Throwable e) { return Result.unhealthy(e); } finally { if (dbms != null) context.getResourceManager().close(Geonet.Res.MAIN_DB, dbms); } } }; }
public HealthCheck create(final ServiceContext context) { return new HealthCheck("Database Connection") { @Override protected Result check() throws Exception { Dbms dbms = null; try { // TODO add timeout dbms = (Dbms) context.getResourceManager().openDirect(Geonet.Res.MAIN_DB); dbms.select("SELECT count(*) from settings"); return Result.healthy(); } catch (Throwable e) { return Result.unhealthy(e); } finally { if (dbms != null) context.getResourceManager().close(Geonet.Res.MAIN_DB, dbms); } } }; }
diff --git a/src/main/java/org/spout/server/SpoutRegion.java b/src/main/java/org/spout/server/SpoutRegion.java index 9fa73ff09..a91fc9ca1 100644 --- a/src/main/java/org/spout/server/SpoutRegion.java +++ b/src/main/java/org/spout/server/SpoutRegion.java @@ -1,678 +1,678 @@ /* * This file is part of Spout (http://www.spout.org/). * * Spout is licensed under the SpoutDev License Version 1. * * Spout 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. * * In addition, 180 days after any changes are published, you can use the * software, incorporating those changes, under the terms of the MIT license, * as described in the SpoutDev License Version 1. * * Spout 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, * the MIT license and the SpoutDev License Version 1 along with this program. * If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public * License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license, * including the MIT license. */ package org.spout.server; import java.util.Collections; import java.util.Iterator; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import org.spout.api.Spout; import org.spout.api.entity.Controller; import org.spout.api.entity.Entity; import org.spout.api.entity.PlayerController; import org.spout.api.event.entity.EntitySpawnEvent; import org.spout.api.generator.WorldGenerator; import org.spout.api.geo.World; import org.spout.api.geo.cuboid.Blockm; import org.spout.api.geo.cuboid.Chunk; import org.spout.api.geo.cuboid.Region; import org.spout.api.material.BlockMaterial; import org.spout.api.protocol.NetworkSynchronizer; import org.spout.api.util.cuboid.CuboidShortBuffer; import org.spout.api.util.set.TByteTripleHashSet; import org.spout.api.util.thread.DelayedWrite; import org.spout.api.util.thread.LiveRead; import org.spout.server.entity.EntityManager; import org.spout.server.entity.SpoutEntity; import org.spout.server.player.SpoutPlayer; import org.spout.server.util.TripleInt; import org.spout.server.util.thread.ThreadAsyncExecutor; import org.spout.server.util.thread.snapshotable.SnapshotManager; public class SpoutRegion extends Region { private AtomicInteger numberActiveChunks = new AtomicInteger(); // Can't extend AsyncManager and Region private final SpoutRegionManager manager; private ConcurrentLinkedQueue<TripleInt> saveMarked = new ConcurrentLinkedQueue<TripleInt>(); @SuppressWarnings("unchecked") public AtomicReference<SpoutChunk>[][][] chunks = new AtomicReference[Region.REGION_SIZE][Region.REGION_SIZE][Region.REGION_SIZE]; /** * Region coordinates of the lower, left start of the region. Add * {@link Region#REGION_SIZE} to the coords to get the upper right end of * the region. */ private final int x, y, z; /** * The maximum number of chunks that will be processed for population each tick. */ private static final int POPULATE_PER_TICK = 5; /** * The maximum number of chunks that will be processed for lighting updates each tick. */ private static final int LIGHT_PER_TICK = 5; /** * The source of this region */ private final RegionSource source; /** * Snapshot manager for this region */ protected SnapshotManager snapshotManager = new SnapshotManager(); /** * Holds all of the entities to be simulated */ protected final EntityManager entityManager = new EntityManager(); /** * Holds all not populated chunks */ protected Set<Chunk> nonPopulatedChunks = Collections.newSetFromMap(new ConcurrentHashMap<Chunk, Boolean>()); private boolean isPopulatingChunks = false; protected Queue<Chunk> unloadQueue = new ConcurrentLinkedQueue<Chunk>(); public static final byte POPULATE_CHUNK_MARGIN = 1; /** * A set of all blocks in this region that need a physics update in the next * tick. The coordinates in this set are relative to this region, so (0, 0, * 0) translates to (0 + x * 256, 0 + y * 256, 0 + z * 256)), where (x, y, * z) are the region coordinates. */ //TODO thresholds? private final TByteTripleHashSet queuedPhysicsUpdates = new TByteTripleHashSet(); private final int blockCoordMask; private final int blockShifts; /** * A queue of chunks that have columns of light that need to be recalculated */ private final Queue<SpoutChunk> lightingQueue = new ConcurrentLinkedQueue<SpoutChunk>(); /** * A queue of chunks that need to be populated */ private final Queue<Chunk> populationQueue = new ConcurrentLinkedQueue<Chunk>(); private final Queue<Entity> spawnQueue = new ConcurrentLinkedQueue<Entity>(); private final Queue<Entity> removeQueue = new ConcurrentLinkedQueue<Entity>(); public SpoutRegion(SpoutWorld world, float x, float y, float z, RegionSource source) { this(world, x, y, z, source, false); } public SpoutRegion(SpoutWorld world, float x, float y, float z, RegionSource source, boolean load) { super(world, x, y, z); this.x = (int) Math.floor(x); this.y = (int) Math.floor(y); this.z = (int) Math.floor(z); this.source = source; blockCoordMask = Region.REGION_SIZE * Chunk.CHUNK_SIZE - 1; blockShifts = Region.REGION_SIZE_BITS + Chunk.CHUNK_SIZE_BITS; manager = new SpoutRegionManager(this, 2, new ThreadAsyncExecutor(), world.getServer()); for (int dx = 0; dx < Region.REGION_SIZE; dx++) { for (int dy = 0; dy < Region.REGION_SIZE; dy++) { for (int dz = 0; dz < Region.REGION_SIZE; dz++) { chunks[dx][dy][dz] = new AtomicReference<SpoutChunk>(load ? getChunk(dx, dy, dz, true) : null); } } } } public SpoutWorld getWorld() { return (SpoutWorld) super.getWorld(); } @Override @LiveRead public SpoutChunk getChunk(int x, int y, int z) { return getChunk(x, y, z, true); } @Override @LiveRead public SpoutChunk getChunk(int x, int y, int z, boolean load) { if (x < Region.REGION_SIZE && x >= 0 && y < Region.REGION_SIZE && y >= 0 && z < Region.REGION_SIZE && z >= 0) { SpoutChunk chunk = chunks[x][y][z].get(); if (chunk != null || !load) { return chunk; } AtomicReference<SpoutChunk> ref = chunks[x][y][z]; boolean success = false; while (!success) { int cx = (this.x << Region.REGION_SIZE_BITS) + x; int cy = (this.y << Region.REGION_SIZE_BITS) + y; int cz = (this.z << Region.REGION_SIZE_BITS) + z; CuboidShortBuffer buffer = new CuboidShortBuffer(getWorld(), cx << Chunk.CHUNK_SIZE_BITS, cy << Chunk.CHUNK_SIZE_BITS, cz << Chunk.CHUNK_SIZE_BITS, Chunk.CHUNK_SIZE, Chunk.CHUNK_SIZE, Chunk.CHUNK_SIZE); WorldGenerator generator = getWorld().getGenerator(); generator.generate(buffer, cx, cy, cz); SpoutChunk newChunk = new SpoutChunk(getWorld(), this, cx, cy, cz, buffer.getRawArray()); success = ref.compareAndSet(null, newChunk); if (success) { numberActiveChunks.incrementAndGet(); if (!newChunk.isPopulated()) { nonPopulatedChunks.add(newChunk); } return newChunk; } else { SpoutChunk oldChunk = ref.get(); if (oldChunk != null) { return oldChunk; } } } } throw new IndexOutOfBoundsException("Invalid coordinates (" + x + ", " + y + ", " + z + ")"); } /** * Removes a chunk from the region and indicates if the region is empty * * @param c the chunk to remove * @return true if the region is now empty */ public boolean removeChunk(Chunk c) { if (c.getRegion() != this) { return false; } int cx = c.getX() & Region.REGION_SIZE - 1; int cy = c.getY() & Region.REGION_SIZE - 1; int cz = c.getZ() & Region.REGION_SIZE - 1; AtomicReference<SpoutChunk> current = chunks[cx][cy][cz]; SpoutChunk currentChunk = current.get(); if (currentChunk != c) { return false; } boolean success = current.compareAndSet(currentChunk, null); if (success) { int num = numberActiveChunks.decrementAndGet(); ((SpoutChunk) currentChunk).setUnloaded(); if (num == 0) { return true; } else if (num < 0) { throw new IllegalStateException("Region has less than 0 active chunks"); } } return false; } @Override public boolean hasChunk(int x, int y, int z) { if (x < Region.REGION_SIZE && x >= 0 && y < Region.REGION_SIZE && y >= 0 && z < Region.REGION_SIZE && z >= 0) { return chunks[x][y][z].get() != null; } return false; } SpoutRegionManager getManager() { return manager; } /** * Queues a Chunk for saving */ @Override @DelayedWrite public void saveChunk(int x, int y, int z) { SpoutChunk c = getChunk(x, y, z, false); if (c != null) { c.save(); } } /** * Queues all chunks for saving */ @Override @DelayedWrite public void save() { for (int dx = 0; dx < Region.REGION_SIZE; dx++) { for (int dy = 0; dy < Region.REGION_SIZE; dy++) { for (int dz = 0; dz < Region.REGION_SIZE; dz++) { SpoutChunk chunk = chunks[dx][dy][dz].get(); if (chunk != null) { chunk.saveNoMark(); } } } } markForSaveUnload(); } @Override public void unload(boolean save) { for (int dx = 0; dx < Region.REGION_SIZE; dx++) { for (int dy = 0; dy < Region.REGION_SIZE; dy++) { for (int dz = 0; dz < Region.REGION_SIZE; dz++) { SpoutChunk chunk = chunks[dx][dy][dz].get(); if (chunk != null) { chunk.unloadNoMark(save); } } } } markForSaveUnload(); } @Override public void unloadChunk(int x, int y, int z, boolean save) { SpoutChunk c = getChunk(x, y, z, false); if (c != null) { c.unload(save); } } public void markForSaveUnload(Chunk c) { if (c.getRegion() != this) { return; } int cx = c.getX() & Region.REGION_SIZE - 1; int cy = c.getY() & Region.REGION_SIZE - 1; int cz = c.getZ() & Region.REGION_SIZE - 1; markForSaveUnload(cx, cy, cz); } public void markForSaveUnload(int x, int y, int z) { saveMarked.add(new TripleInt(x, y, z)); } public void markForSaveUnload() { saveMarked.add(TripleInt.NULL); } public void copySnapshotRun() throws InterruptedException { entityManager.copyAllSnapshots(); for (int dx = 0; dx < Region.REGION_SIZE; dx++) { for (int dy = 0; dy < Region.REGION_SIZE; dy++) { for (int dz = 0; dz < Region.REGION_SIZE; dz++) { Chunk chunk = chunks[dx][dy][dz].get(); if (chunk != null) { ((SpoutChunk) chunk).copySnapshotRun(); } } } } snapshotManager.copyAllSnapshots(); boolean empty = false; TripleInt chunkCoords; while ((chunkCoords = saveMarked.poll()) != null) { if (chunkCoords == TripleInt.NULL) { for (int dx = 0; dx < Region.REGION_SIZE; dx++) { for (int dy = 0; dy < Region.REGION_SIZE; dy++) { for (int dz = 0; dz < Region.REGION_SIZE; dz++) { if (processChunkSaveUnload(dx, dy, dz)) { empty = true; } } } } // No point in checking any others, since all processed saveMarked.clear(); break; } else { processChunkSaveUnload(chunkCoords.x, chunkCoords.y, chunkCoords.z); } } // Updates on nulled chunks snapshotManager.copyAllSnapshots(); if (empty) { source.removeRegion(this); } } public boolean processChunkSaveUnload(int x, int y, int z) { boolean empty = false; SpoutChunk c = (SpoutChunk) getChunk(x, y, z, false); if (c != null) { SpoutChunk.SaveState oldState = c.getAndResetSaveState(); if (oldState.isSave()) { c.syncSave(); } if (oldState.isUnload()) { if (removeChunk(c)) { System.out.println("Region is now empty ... remove?"); empty = true; } } } return empty; } protected void queueChunkForPopulation(Chunk c) { if (!populationQueue.contains(c)) { populationQueue.add(c); } } protected void queueLighting(SpoutChunk c) { if (!lightingQueue.contains(c)) { lightingQueue.add(c); } } public void addEntity(Entity e) { if (spawnQueue.contains(e)) return; if (removeQueue.contains(e)) { throw new IllegalArgumentException("Cannot add an entity marked for removal"); } spawnQueue.add(e); } public void removeEntity(Entity e) { if (removeQueue.contains(e)) return; if (spawnQueue.contains(e)) { spawnQueue.remove(e); return; } removeQueue.add(e); } public void startTickRun(int stage, long delta) throws InterruptedException { switch (stage) { case 0: { //Add or remove entities if(!spawnQueue.isEmpty()) { SpoutEntity e; while ((e = (SpoutEntity)spawnQueue.poll()) != null) { this.allocate(e); - EntitySpawnEvent event = new EntitySpawnEvent(e, e.getPoint()); + EntitySpawnEvent event = new EntitySpawnEvent(e, e.getPosition()); Spout.getGame().getEventManager().callEvent(event); if (event.isCancelled()) { this.deallocate((SpoutEntity) e); } } } if(!removeQueue.isEmpty()) { SpoutEntity e; while ((e = (SpoutEntity)removeQueue.poll()) != null) { this.deallocate(e); } } float dt = delta / 1000.f; //Update all entities for (SpoutEntity ent : entityManager) { try { ent.onTick(dt); } catch (Exception e) { Spout.getGame().getLogger().severe("Unhandled exception during tick for " + ent.toString()); e.printStackTrace(); } } World world = getWorld(); int[] updates; synchronized (queuedPhysicsUpdates) { updates = queuedPhysicsUpdates.toArray(); queuedPhysicsUpdates.clear(); } for (int key : updates) { int x = TByteTripleHashSet.key1(key); int y = TByteTripleHashSet.key2(key); int z = TByteTripleHashSet.key3(key); //switch region block coords (0-255) to a chunk index Chunk chunk = chunks[x >> Chunk.CHUNK_SIZE_BITS][y >> Chunk.CHUNK_SIZE_BITS][z >> Chunk.CHUNK_SIZE_BITS].get(); if (chunk != null) { BlockMaterial material = chunk.getBlockMaterial(x, y, z); if (material.hasPhysics()) { //switch region block coords (0-255) to world block coords material.onUpdate(world, x + (this.x << blockShifts), y + (this.y << blockShifts), z + (this.z << blockShifts)); } } } for(int i = 0; i < LIGHT_PER_TICK; i++) { SpoutChunk toLight = lightingQueue.poll(); if (toLight == null) break; if (toLight.isLoaded()) { toLight.processQueuedLighting(); } } for(int i = 0; i < POPULATE_PER_TICK; i++) { Chunk toPopulate = populationQueue.poll(); if (toPopulate == null) break; if (toPopulate.isLoaded()) { toPopulate.populate(); } } Chunk toUnload = unloadQueue.poll(); if (toUnload != null) { toUnload.unload(true); } break; } case 1: { //Resolve and collisions and prepare for a snapshot. for (SpoutEntity ent : entityManager) { try { ent.resolve(); } catch (Exception e) { Spout.getGame().getLogger().severe("Unhandled exception during tick resolution for " + ent.toString()); e.printStackTrace(); } } break; } default: { throw new IllegalStateException("Number of states exceeded limit for SpoutRegion"); } } } public void haltRun() throws InterruptedException { } public void finalizeRun() throws InterruptedException { entityManager.finalizeRun(); // Compress at most 1 chunk per tick per region boolean chunkCompressed = false; for (int dx = 0; dx < Region.REGION_SIZE && !chunkCompressed; dx++) { for (int dy = 0; dy < Region.REGION_SIZE && !chunkCompressed; dy++) { for (int dz = 0; dz < Region.REGION_SIZE && !chunkCompressed; dz++) { Chunk chunk = chunks[dx][dy][dz].get(); if (chunk != null) { chunkCompressed |= ((SpoutChunk) chunk).compressIfRequired(); } } } } } private void syncChunkToPlayers(SpoutChunk chunk, Entity entity){ SpoutPlayer player = (SpoutPlayer)((PlayerController) entity.getController()).getPlayer(); NetworkSynchronizer synchronizer = player.getNetworkSynchronizer(); if (synchronizer != null) { if (!chunk.isDirtyOverflow()) { for (int i = 0; true; i++) { Blockm block = chunk.getDirtyBlock(i, new SpoutBlockm(getWorld(), 0, 0, 0)); if (block == null) { break; } else { try { synchronizer.updateBlock(chunk, block.getX(), block.getY(), block.getZ()); } catch (Exception e) { Spout.getGame().getLogger().log(Level.SEVERE, "Exception thrown by plugin when attempting to send a block update to " + player.getName()); } } } } else { synchronizer.sendChunk(chunk); } } } public void preSnapshotRun() throws InterruptedException { entityManager.preSnapshotRun(); for (int dx = 0; dx < Region.REGION_SIZE; dx++) { for (int dy = 0; dy < Region.REGION_SIZE; dy++) { for (int dz = 0; dz < Region.REGION_SIZE; dz++) { Chunk chunk = chunks[dx][dy][dz].get(); if (chunk == null) continue; SpoutChunk spoutChunk = (SpoutChunk) chunk; if (spoutChunk.isDirty()) { for (Entity entity : spoutChunk.getObserversLive()) { //chunk.refreshObserver(entity); if(!(entity.getController() instanceof PlayerController)) continue; syncChunkToPlayers(spoutChunk, entity); } spoutChunk.resetDirtyArrays(); } spoutChunk.preSnapshot(); } } } } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public Set<Entity> getAll(Class<? extends Controller> type) { return (Set) entityManager.getAll(type); } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public Set<Entity> getAll() { return (Set) entityManager.getAll(); } @Override public SpoutEntity getEntity(int id) { return entityManager.getEntity(id); } /** * Allocates the id for an entity. * * @param entity The entity. * @return The id. */ public int allocate(SpoutEntity entity) { return entityManager.allocate(entity); } /** * Deallocates the id for an entity. * * @param entity The entity. */ public void deallocate(SpoutEntity entity) { entityManager.deallocate(entity); } public Iterator<SpoutEntity> iterator() { return entityManager.iterator(); } public EntityManager getEntityManager() { return entityManager; } public void onChunkPopulated(SpoutChunk chunk) { if (!isPopulatingChunks) { nonPopulatedChunks.remove(chunk); } } /** * Queues a block for a physic update at the next available tick. * * @param x, the block x coordinate * @param y, the block y coordinate * @param z, the block z coordinate */ public void queuePhysicsUpdate(int x, int y, int z) { synchronized (queuedPhysicsUpdates) { queuedPhysicsUpdates.add(x & blockCoordMask, y & blockCoordMask, z & blockCoordMask); } } @Override public int getNumLoadedChunks() { return numberActiveChunks.get(); } @Override public String toString() { return "SpoutRegion{ ( " + x + ", " + y + ", " + z + "), World: " + this.getWorld() + "}"; } public Thread getExceutionThread(){ return ((ThreadAsyncExecutor)manager.getExecutor()); } }
true
true
public void startTickRun(int stage, long delta) throws InterruptedException { switch (stage) { case 0: { //Add or remove entities if(!spawnQueue.isEmpty()) { SpoutEntity e; while ((e = (SpoutEntity)spawnQueue.poll()) != null) { this.allocate(e); EntitySpawnEvent event = new EntitySpawnEvent(e, e.getPoint()); Spout.getGame().getEventManager().callEvent(event); if (event.isCancelled()) { this.deallocate((SpoutEntity) e); } } } if(!removeQueue.isEmpty()) { SpoutEntity e; while ((e = (SpoutEntity)removeQueue.poll()) != null) { this.deallocate(e); } } float dt = delta / 1000.f; //Update all entities for (SpoutEntity ent : entityManager) { try { ent.onTick(dt); } catch (Exception e) { Spout.getGame().getLogger().severe("Unhandled exception during tick for " + ent.toString()); e.printStackTrace(); } } World world = getWorld(); int[] updates; synchronized (queuedPhysicsUpdates) { updates = queuedPhysicsUpdates.toArray(); queuedPhysicsUpdates.clear(); } for (int key : updates) { int x = TByteTripleHashSet.key1(key); int y = TByteTripleHashSet.key2(key); int z = TByteTripleHashSet.key3(key); //switch region block coords (0-255) to a chunk index Chunk chunk = chunks[x >> Chunk.CHUNK_SIZE_BITS][y >> Chunk.CHUNK_SIZE_BITS][z >> Chunk.CHUNK_SIZE_BITS].get(); if (chunk != null) { BlockMaterial material = chunk.getBlockMaterial(x, y, z); if (material.hasPhysics()) { //switch region block coords (0-255) to world block coords material.onUpdate(world, x + (this.x << blockShifts), y + (this.y << blockShifts), z + (this.z << blockShifts)); } } } for(int i = 0; i < LIGHT_PER_TICK; i++) { SpoutChunk toLight = lightingQueue.poll(); if (toLight == null) break; if (toLight.isLoaded()) { toLight.processQueuedLighting(); } } for(int i = 0; i < POPULATE_PER_TICK; i++) { Chunk toPopulate = populationQueue.poll(); if (toPopulate == null) break; if (toPopulate.isLoaded()) { toPopulate.populate(); } } Chunk toUnload = unloadQueue.poll(); if (toUnload != null) { toUnload.unload(true); } break; } case 1: { //Resolve and collisions and prepare for a snapshot. for (SpoutEntity ent : entityManager) { try { ent.resolve(); } catch (Exception e) { Spout.getGame().getLogger().severe("Unhandled exception during tick resolution for " + ent.toString()); e.printStackTrace(); } } break; } default: { throw new IllegalStateException("Number of states exceeded limit for SpoutRegion"); } } }
public void startTickRun(int stage, long delta) throws InterruptedException { switch (stage) { case 0: { //Add or remove entities if(!spawnQueue.isEmpty()) { SpoutEntity e; while ((e = (SpoutEntity)spawnQueue.poll()) != null) { this.allocate(e); EntitySpawnEvent event = new EntitySpawnEvent(e, e.getPosition()); Spout.getGame().getEventManager().callEvent(event); if (event.isCancelled()) { this.deallocate((SpoutEntity) e); } } } if(!removeQueue.isEmpty()) { SpoutEntity e; while ((e = (SpoutEntity)removeQueue.poll()) != null) { this.deallocate(e); } } float dt = delta / 1000.f; //Update all entities for (SpoutEntity ent : entityManager) { try { ent.onTick(dt); } catch (Exception e) { Spout.getGame().getLogger().severe("Unhandled exception during tick for " + ent.toString()); e.printStackTrace(); } } World world = getWorld(); int[] updates; synchronized (queuedPhysicsUpdates) { updates = queuedPhysicsUpdates.toArray(); queuedPhysicsUpdates.clear(); } for (int key : updates) { int x = TByteTripleHashSet.key1(key); int y = TByteTripleHashSet.key2(key); int z = TByteTripleHashSet.key3(key); //switch region block coords (0-255) to a chunk index Chunk chunk = chunks[x >> Chunk.CHUNK_SIZE_BITS][y >> Chunk.CHUNK_SIZE_BITS][z >> Chunk.CHUNK_SIZE_BITS].get(); if (chunk != null) { BlockMaterial material = chunk.getBlockMaterial(x, y, z); if (material.hasPhysics()) { //switch region block coords (0-255) to world block coords material.onUpdate(world, x + (this.x << blockShifts), y + (this.y << blockShifts), z + (this.z << blockShifts)); } } } for(int i = 0; i < LIGHT_PER_TICK; i++) { SpoutChunk toLight = lightingQueue.poll(); if (toLight == null) break; if (toLight.isLoaded()) { toLight.processQueuedLighting(); } } for(int i = 0; i < POPULATE_PER_TICK; i++) { Chunk toPopulate = populationQueue.poll(); if (toPopulate == null) break; if (toPopulate.isLoaded()) { toPopulate.populate(); } } Chunk toUnload = unloadQueue.poll(); if (toUnload != null) { toUnload.unload(true); } break; } case 1: { //Resolve and collisions and prepare for a snapshot. for (SpoutEntity ent : entityManager) { try { ent.resolve(); } catch (Exception e) { Spout.getGame().getLogger().severe("Unhandled exception during tick resolution for " + ent.toString()); e.printStackTrace(); } } break; } default: { throw new IllegalStateException("Number of states exceeded limit for SpoutRegion"); } } }
diff --git a/spring-integration-samples/errorhandling/src/main/java/org/springframework/integration/samples/errorhandling/PartyDemo.java b/spring-integration-samples/errorhandling/src/main/java/org/springframework/integration/samples/errorhandling/PartyDemo.java index b779a58718..5a84e01a1c 100644 --- a/spring-integration-samples/errorhandling/src/main/java/org/springframework/integration/samples/errorhandling/PartyDemo.java +++ b/spring-integration-samples/errorhandling/src/main/java/org/springframework/integration/samples/errorhandling/PartyDemo.java @@ -1,46 +1,46 @@ /** * Copyright 2002-2009 the original author or authors. * * 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.springframework.integration.samples.errorhandling; import java.io.IOException; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Demonstrates the handling of Exceptions in an asynchronous messaging * environment. View the 'errorHandlingDemo.xml' configuration file within * this same package. Notice the use of a &lt;header-enricher/&gt; element * within a &lt;chain/&gt; that establishes an 'error-channel' reference * prior to passing the message to a &lt;service-activator/&gt;. * * @author Iwein Fuld */ public class PartyDemo { public static void main(String[] args) { new ClassPathXmlApplicationContext("errorHandlingDemo.xml", PartyDemo.class); - System.out.println("hit any key to stop"); + System.out.println("### Hit ENTER to stop ###"); try { System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } System.exit(0); } }
true
true
public static void main(String[] args) { new ClassPathXmlApplicationContext("errorHandlingDemo.xml", PartyDemo.class); System.out.println("hit any key to stop"); try { System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } System.exit(0); }
public static void main(String[] args) { new ClassPathXmlApplicationContext("errorHandlingDemo.xml", PartyDemo.class); System.out.println("### Hit ENTER to stop ###"); try { System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } System.exit(0); }
diff --git a/src/org/jruby/debug/DebugEventHook.java b/src/org/jruby/debug/DebugEventHook.java index b633c00..8a7cf40 100644 --- a/src/org/jruby/debug/DebugEventHook.java +++ b/src/org/jruby/debug/DebugEventHook.java @@ -1,615 +1,615 @@ /* * header & license * Copyright (c) 2007 Martin Krauskopf * Copyright (c) 2007 Peter Brant * * 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 org.jruby.debug; import java.io.File; import org.jruby.MetaClass; import org.jruby.Ruby; import org.jruby.RubyArray; import org.jruby.RubyBinding; import org.jruby.RubyBoolean; import org.jruby.RubyException; import org.jruby.RubyFile; import org.jruby.RubyFixnum; import org.jruby.RubyFloat; import org.jruby.RubyKernel; import org.jruby.RubyModule; import org.jruby.RubyNil; import org.jruby.RubyString; import org.jruby.RubySymbol; import org.jruby.RubyThread; import org.jruby.RubyUndef; import org.jruby.debug.DebugContext.StopReason; import org.jruby.debug.DebugFrame.Info; import org.jruby.debug.Debugger.DebugContextPair; import org.jruby.exceptions.RaiseException; import org.jruby.runtime.Block; import org.jruby.runtime.EventHook; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; final class DebugEventHook implements EventHook { private final Debugger debugger; private final Ruby runtime; private int hookCount; private int lastDebuggedThnum; private int lastCheck; private boolean inDebugger; public DebugEventHook(final Debugger debugger, final Ruby runtime) { this.debugger = debugger; lastDebuggedThnum = -1; this.runtime = runtime; } public void event(final ThreadContext tCtx, final int event, final String file, final int line0, final String methodName, final IRubyObject klass) { boolean needsSuspend = false; RubyThread currThread; DebugContextPair contexts; currThread = tCtx.getThread(); contexts = debugger.threadContextLookup(currThread, true); // return if thread is marked as 'ignored'. debugger's threads are marked this way if (contexts.debugContext.isIgnored()) { return; } /* ignore a skipped section of code */ if (contexts.debugContext.isSkipped()) { cleanUp(contexts.debugContext); return; } needsSuspend = contexts.debugContext.isSuspended(); if (needsSuspend) { RubyThread.stop(currThread); } synchronized (this) { if (isInDebugger()) { return; } //dumpEvent(event, file, line0, methodName, klass); setInDebugger(true); try { processEvent(tCtx, event, file, line0, methodName, klass, contexts); } finally { setInDebugger(false); } } } @SuppressWarnings("fallthrough") private void processEvent(final ThreadContext tCtx, final int event, final String file, final int line0, final String methodName, final IRubyObject klass, DebugContextPair contexts) { // one-based; jruby by default passes zero-based int line = line0 + 1; hookCount++; Ruby runtime = tCtx.getRuntime(); IRubyObject breakpoint = getNil(); IRubyObject binding = getNil(); IRubyObject context = contexts.context; DebugContext debugContext = contexts.debugContext; // debug("jrubydebug> %s:%d [%s] %s\n", file, line, EVENT_NAMES[event], methodName); boolean moved = false; if (debugContext.getLastLine() != line || debugContext.getLastFile() == null || !debugContext.getLastFile().equals(file)) { debugContext.setEnableBreakpoint(true); moved = true; } // else if(event != RUBY_EVENT_RETURN && event != RUBY_EVENT_C_RETURN) { // if(debug == Qtrue) // fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName)); // goto cleanup; // } else { // if(debug == Qtrue) // fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName)); // } if (event != RUBY_EVENT_LINE) { debugContext.setStepped(true); } switch (event) { case RUBY_EVENT_LINE: if (debugContext.getStackSize() == 0) { saveCallFrame(event, tCtx, file, line, methodName, debugContext); } else { setFrameSource(event, debugContext, tCtx, file, line, methodName); } if (debugger.isTracing() || debugContext.isTracing()) { IRubyObject[] args = new IRubyObject[]{ runtime.newString(file), runtime.newFixnum(line) }; context.callMethod(tCtx, DebugContext.AT_TRACING, args); } if (debugContext.getDestFrame() == -1 || debugContext.getStackSize() == debugContext.getDestFrame()) { if (moved || !debugContext.isForceMove()) { debugContext.setStopNext(debugContext.getStopNext() - 1); } if (debugContext.getStopNext() < 0) { debugContext.setStopNext(-1); } if (moved || (debugContext.isStepped() && !debugContext.isForceMove())) { debugContext.setStopLine(debugContext.getStopLine() - 1); debugContext.setStepped(false); } } else if (debugContext.getStackSize() < debugContext.getDestFrame()) { debugContext.setStopNext(0); } if (debugContext.getStopNext() == 0 || debugContext.getStopLine() == 0 || !(breakpoint = checkBreakpointsByPos(debugContext, file, line)).isNil()) { binding = (tCtx != null ? RubyBinding.newBinding(runtime) : getNil()); saveTopBinding(debugContext, binding); debugContext.setStopReason(DebugContext.StopReason.STEP); /* Check breakpoint expression. */ if (!breakpoint.isNil()) { if (!checkBreakpointExpression(breakpoint, binding)) { break; } if (!checkBreakpointHitCondition(breakpoint)) { break; } if (breakpoint != debugContext.getBreakpoint()) { debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT); context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint); } else { debugContext.setBreakpoint(getNil()); } } /* reset all pointers */ debugContext.setDestFrame(-1); debugContext.setStopLine(-1); debugContext.setStopNext(-1); callAtLine(tCtx, context, debugContext, runtime, file, line); } break; case RUBY_EVENT_CALL: saveCallFrame(event, tCtx, file, line, methodName, debugContext); breakpoint = checkBreakpointsByMethod(debugContext, klass, methodName); if (!breakpoint.isNil()) { DebugFrame debugFrame = getTopFrame(debugContext); if (debugFrame != null) { binding = debugFrame.getBinding(); } - if (!binding.isNil() && tCtx != null) { - binding = (tCtx != null ? RubyBinding.newBinding(runtime) : getNil()); + if (tCtx != null && binding.isNil()) { + binding = RubyBinding.newBinding(runtime); } saveTopBinding(debugContext, binding); if(!checkBreakpointExpression(breakpoint, binding)) break; if(!checkBreakpointHitCondition(breakpoint)) break; if (breakpoint != debugContext.getBreakpoint()) { debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT); context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint); } else { debugContext.setBreakpoint(getNil()); } callAtLine(tCtx, context, debugContext, runtime, file, line); } break; case RUBY_EVENT_C_CALL: if(cCallNewFrameP(klass, methodName)) { saveCallFrame(event, tCtx, file, line, methodName, debugContext); } else { setFrameSource(event, debugContext, tCtx, file, line, methodName); } break; case RUBY_EVENT_C_RETURN: /* note if a block is given we fall through! */ if (!cCallNewFrameP(klass, methodName)) { break; } case RUBY_EVENT_RETURN: case RUBY_EVENT_END: if (debugContext.getStackSize() == debugContext.getStopFrame()) { debugContext.setStopNext(1); debugContext.setStopFrame(0); } while (debugContext.getStackSize() > 0) { DebugFrame topFrame = debugContext.popFrame(); String origMethodName = topFrame.getOrigMethodName(); if ((origMethodName == null && methodName == null) || (origMethodName != null && origMethodName.equals(methodName))) { break; } } debugContext.setEnableBreakpoint(true); break; case RUBY_EVENT_CLASS: resetFrameMid(debugContext); saveCallFrame(event, tCtx, file, line, methodName, debugContext); break; case RUBY_EVENT_RAISE: setFrameSource(event, debugContext, tCtx, file, line, methodName); // XXX Implement post mortem debugging RubyException exception = (RubyException)runtime.getGlobalVariables().get("$!"); if (exception.isKindOf(runtime.getClass("SystemExit"))) { // Can't do this because this unhooks the event hook causing // a ConcurrentModificationException because the runtime // is still iterating over event hooks. Shouldn't really // matter. We're on our way out regardless. // debugger.stop(runtime); break; } if (debugger.getCatchpoint().isNil()) { break; } RubyArray ancestors = exception.getType().ancestors(); int l = ancestors.getLength(); for (int i = 0; i < l; i++) { RubyModule m = (RubyModule)ancestors.get(i); if (m.getName().equals(debugger.getCatchpointAsString())) { debugContext.setStopReason(DebugContext.StopReason.CATCHPOINT); context.callMethod(tCtx, DebugContext.AT_CATCHPOINT, breakpoint); DebugFrame debugFrame = getTopFrame(debugContext); if (debugFrame != null) { binding = debugFrame.getBinding(); } - if (!binding.isNil() && tCtx != null) { - binding = (tCtx != null ? RubyBinding.newBinding(runtime) : getNil()); + if (tCtx != null && binding.isNil()) { + binding = RubyBinding.newBinding(runtime); } saveTopBinding(debugContext, binding); callAtLine(tCtx, context, debugContext, runtime, file, line); break; } } break; } cleanUp(debugContext); } private IRubyObject getNil() { return runtime.getNil(); } private IRubyObject getBreakpoints() { return debugger.getBreakpoints(); } private void cleanUp(DebugContext debugContext) { debugContext.setStopReason(StopReason.NONE); /* check that all contexts point to alive threads */ if(hookCount - lastCheck > 3000) { debugger.checkThreadContexts(runtime); lastCheck = hookCount; } } public boolean isInterestedInEvent(int event) { return true; } /* private void debug(final String format, final Object... args) { System.err.printf(format, args); } private void dumpEvent(int event, String file, int line, String name, IRubyObject klass) { System.out.println("DEBUG> event: \"" + EVENT_NAMES[event] + '\"'); System.out.println("DEBUG> file: \"" + file + '\"'); System.out.println("DEBUG> line: \"" + line + '\"'); System.out.println("DEBUG> name: \"" + name + '\"'); // System.out.println("DEBUG> klass: \"" + klass + '\"'); } */ private void saveCallFrame(final int event, final ThreadContext tCtx, final String file, final int line, final String methodName, final DebugContext debugContext) { IRubyObject binding = (debugger.isKeepFrameBinding()) ? RubyBinding.newBinding(tCtx.getRuntime()) : tCtx.getRuntime().getNil(); DebugFrame debugFrame = new DebugFrame(); debugFrame.setFile(file); debugFrame.setLine(line); debugFrame.setBinding(binding); debugFrame.setMethodName(methodName); debugFrame.setOrigMethodName(methodName); debugFrame.setDead(false); debugFrame.setSelf(tCtx.getFrameSelf()); Info info = debugFrame.getInfo(); info.setFrame(tCtx.getCurrentFrame()); info.setScope(tCtx.getCurrentScope().getStaticScope()); info.setDynaVars(event == RUBY_EVENT_LINE ? tCtx.getCurrentScope() : null); debugContext.addFrame(debugFrame); if (debugger.isTrackFrameArgs()) { copyScalarArgs(tCtx, debugFrame); } else { debugFrame.setArgValues(runtime.getNil()); } } private boolean isArgValueSmall(IRubyObject value) { return value instanceof RubyFixnum || value instanceof RubyFloat || value instanceof RubyNil || value instanceof RubyModule || value instanceof RubyFile || value instanceof RubyBoolean || value instanceof RubyUndef || value instanceof RubySymbol; } /** Save scalar arguments or a class name. */ private void copyScalarArgs(ThreadContext tCtx, DebugFrame debugFrame) { RubyArray args = (RubyArray)runtime.newArray(tCtx.getCurrentScope().getArgValues()); int len = args.getLength(); for (int i = 0; i < len; i++) { IRubyObject obj = (IRubyObject)args.entry(i); if (! isArgValueSmall(obj)) { args.store(i, runtime.newString(obj.getType().getName())); } } debugFrame.setArgValues(args); } private void setFrameSource(int event, DebugContext debug_context, ThreadContext tCtx, String file, int line, String methodName) { DebugFrame topFrame = getTopFrame(debug_context); if (topFrame != null) { topFrame.setSelf(tCtx.getFrameSelf()); topFrame.setFile(file); topFrame.setLine(line); topFrame.setMethodName(methodName); topFrame.getInfo().setDynaVars(event == RUBY_EVENT_C_CALL ? null : tCtx.getCurrentScope()); } } private DebugFrame getTopFrame(final DebugContext debugContext) { if (debugContext.getStackSize() == 0) { return null; } else { return debugContext.getTopFrame(); } } private IRubyObject checkBreakpointsByPos(DebugContext debugContext, String file, int line) { if (!debugContext.isEnableBreakpoint()) { return getNil(); } if (checkBreakpointByPos(debugContext.getBreakpoint(), file, line)) { return debugContext.getBreakpoint(); } RubyArray arr = getBreakpoints().convertToArray(); if (arr.isEmpty()) { return getNil(); } for (int i = 0; i < arr.size(); i++) { IRubyObject breakpoint = arr.entry(i); if (checkBreakpointByPos(breakpoint, file, line)) { return breakpoint; } } return getNil(); } private boolean checkBreakpointByPos(IRubyObject breakpoint, String file, int line) { if (breakpoint.isNil()) { return false; } DebugBreakpoint debugBreakpoint = (DebugBreakpoint) breakpoint.dataGetStruct(); if (debugBreakpoint.getType() != DebugBreakpoint.Type.POS) { return false; } if (debugBreakpoint.getPos().getLine() != line) { return false; } String source = ((RubyString) debugBreakpoint.getSource()).toString(); String sourceName = new File(source).getName(); String fileName = new File(file).getName(); if (sourceName.equals(fileName)) { return true; } return false; } private IRubyObject checkBreakpointsByMethod(DebugContext debugContext, IRubyObject klass, String methodName) { if (!debugContext.isEnableBreakpoint()) { return getNil(); } if (checkBreakpointByMethod(debugContext.getBreakpoint(), klass, methodName)) { return debugContext.getBreakpoint(); } RubyArray arr = getBreakpoints().convertToArray(); if (arr.isEmpty()) { return getNil(); } for (int i = 0; i < arr.size(); i++) { IRubyObject breakpoint = arr.entry(i); if (checkBreakpointByMethod(breakpoint, klass, methodName)) { return breakpoint; } } return getNil(); } private boolean checkBreakpointByMethod(IRubyObject breakpoint, IRubyObject klass, String methodName) { if (breakpoint.isNil()) { return false; } DebugBreakpoint debugBreakpoint = (DebugBreakpoint) breakpoint.dataGetStruct(); if (debugBreakpoint.getType() != DebugBreakpoint.Type.METHOD) { return false; } if (! debugBreakpoint.getPos().getMethodName().equals(methodName)) { return false; } if (debugBreakpoint.getSource().asString().eql(klass.asString())) { return true; } return false; } private boolean checkBreakpointExpression(IRubyObject breakpoint, IRubyObject binding) { DebugBreakpoint debugBreakpoint = (DebugBreakpoint) breakpoint.dataGetStruct(); if (debugBreakpoint.getExpr().isNil()) { return true; } try { IRubyObject result = RubyKernel.eval( breakpoint, new IRubyObject[] { debugBreakpoint.getExpr(), binding }, Block.NULL_BLOCK); return result.isTrue(); } catch (RaiseException e) { // XXX Seems like we should tell the user about this, but this how // ruby-debug behaves return false; } } private boolean checkBreakpointHitCondition(IRubyObject breakpoint) { DebugBreakpoint debugBreakpoint = (DebugBreakpoint) breakpoint.dataGetStruct(); debugBreakpoint.setHitCount(debugBreakpoint.getHitCount()+1); if (debugBreakpoint.getHitCondition() == null) { return true; } switch (debugBreakpoint.getHitCondition()) { case NONE: return true; case GE: if (debugBreakpoint.getHitCount() >= debugBreakpoint.getHitValue()) { return true; } break; case EQ: if (debugBreakpoint.getHitCount() == debugBreakpoint.getHitValue()) { return true; } break; case MOD: if (debugBreakpoint.getHitCount() % debugBreakpoint.getHitValue() == 0) { return true; } break; } return false; } private void saveTopBinding(DebugContext context, IRubyObject binding) { DebugFrame debugFrame = getTopFrame(context); if (debugFrame != null) { debugFrame.setBinding(binding); } } private IRubyObject callAtLine(ThreadContext tCtx, IRubyObject context, DebugContext debugContext, Ruby runtime, String file, int line) { return callAtLine(tCtx, context, debugContext, runtime.newString(file), runtime.newFixnum(line)); } private IRubyObject callAtLine(ThreadContext tCtx, IRubyObject context, DebugContext debugContext, IRubyObject file, IRubyObject line) { lastDebuggedThnum = debugContext.getThnum(); saveCurrentPosition(debugContext); IRubyObject[] args = new IRubyObject[]{ file, line }; return context.callMethod(tCtx, DebugContext.AT_LINE, args); } private void saveCurrentPosition(final DebugContext debugContext) { DebugFrame debugFrame = getTopFrame(debugContext); if (debugFrame == null) { return; } debugContext.setLastFile(debugFrame.getFile()); debugContext.setLastLine(debugFrame.getLine()); debugContext.setEnableBreakpoint(false); debugContext.setStepped(false); debugContext.setForceMove(false); } private boolean cCallNewFrameP(IRubyObject klass, String methodName) { klass = realClass(klass); // TODO - block_given? // if(rb_block_given_p()) return true; String cName = klass.getType().getName(); return "Proc".equals(cName) || "RubyKernel".equals(cName) || "Module".equals(cName); } private IRubyObject realClass(IRubyObject klass) { if (klass instanceof MetaClass) { return ((MetaClass)klass).getRealClass(); } return klass; } private void resetFrameMid(DebugContext debugContext) { DebugFrame topFrame = getTopFrame(debugContext); if (topFrame != null) { topFrame.setMethodName(""); } } private boolean isInDebugger() { return inDebugger; } private void setInDebugger(boolean inDebugger) { this.inDebugger = inDebugger; } int getLastDebuggedThnum() { return lastDebuggedThnum; } }
false
true
private void processEvent(final ThreadContext tCtx, final int event, final String file, final int line0, final String methodName, final IRubyObject klass, DebugContextPair contexts) { // one-based; jruby by default passes zero-based int line = line0 + 1; hookCount++; Ruby runtime = tCtx.getRuntime(); IRubyObject breakpoint = getNil(); IRubyObject binding = getNil(); IRubyObject context = contexts.context; DebugContext debugContext = contexts.debugContext; // debug("jrubydebug> %s:%d [%s] %s\n", file, line, EVENT_NAMES[event], methodName); boolean moved = false; if (debugContext.getLastLine() != line || debugContext.getLastFile() == null || !debugContext.getLastFile().equals(file)) { debugContext.setEnableBreakpoint(true); moved = true; } // else if(event != RUBY_EVENT_RETURN && event != RUBY_EVENT_C_RETURN) { // if(debug == Qtrue) // fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName)); // goto cleanup; // } else { // if(debug == Qtrue) // fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName)); // } if (event != RUBY_EVENT_LINE) { debugContext.setStepped(true); } switch (event) { case RUBY_EVENT_LINE: if (debugContext.getStackSize() == 0) { saveCallFrame(event, tCtx, file, line, methodName, debugContext); } else { setFrameSource(event, debugContext, tCtx, file, line, methodName); } if (debugger.isTracing() || debugContext.isTracing()) { IRubyObject[] args = new IRubyObject[]{ runtime.newString(file), runtime.newFixnum(line) }; context.callMethod(tCtx, DebugContext.AT_TRACING, args); } if (debugContext.getDestFrame() == -1 || debugContext.getStackSize() == debugContext.getDestFrame()) { if (moved || !debugContext.isForceMove()) { debugContext.setStopNext(debugContext.getStopNext() - 1); } if (debugContext.getStopNext() < 0) { debugContext.setStopNext(-1); } if (moved || (debugContext.isStepped() && !debugContext.isForceMove())) { debugContext.setStopLine(debugContext.getStopLine() - 1); debugContext.setStepped(false); } } else if (debugContext.getStackSize() < debugContext.getDestFrame()) { debugContext.setStopNext(0); } if (debugContext.getStopNext() == 0 || debugContext.getStopLine() == 0 || !(breakpoint = checkBreakpointsByPos(debugContext, file, line)).isNil()) { binding = (tCtx != null ? RubyBinding.newBinding(runtime) : getNil()); saveTopBinding(debugContext, binding); debugContext.setStopReason(DebugContext.StopReason.STEP); /* Check breakpoint expression. */ if (!breakpoint.isNil()) { if (!checkBreakpointExpression(breakpoint, binding)) { break; } if (!checkBreakpointHitCondition(breakpoint)) { break; } if (breakpoint != debugContext.getBreakpoint()) { debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT); context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint); } else { debugContext.setBreakpoint(getNil()); } } /* reset all pointers */ debugContext.setDestFrame(-1); debugContext.setStopLine(-1); debugContext.setStopNext(-1); callAtLine(tCtx, context, debugContext, runtime, file, line); } break; case RUBY_EVENT_CALL: saveCallFrame(event, tCtx, file, line, methodName, debugContext); breakpoint = checkBreakpointsByMethod(debugContext, klass, methodName); if (!breakpoint.isNil()) { DebugFrame debugFrame = getTopFrame(debugContext); if (debugFrame != null) { binding = debugFrame.getBinding(); } if (!binding.isNil() && tCtx != null) { binding = (tCtx != null ? RubyBinding.newBinding(runtime) : getNil()); } saveTopBinding(debugContext, binding); if(!checkBreakpointExpression(breakpoint, binding)) break; if(!checkBreakpointHitCondition(breakpoint)) break; if (breakpoint != debugContext.getBreakpoint()) { debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT); context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint); } else { debugContext.setBreakpoint(getNil()); } callAtLine(tCtx, context, debugContext, runtime, file, line); } break; case RUBY_EVENT_C_CALL: if(cCallNewFrameP(klass, methodName)) { saveCallFrame(event, tCtx, file, line, methodName, debugContext); } else { setFrameSource(event, debugContext, tCtx, file, line, methodName); } break; case RUBY_EVENT_C_RETURN: /* note if a block is given we fall through! */ if (!cCallNewFrameP(klass, methodName)) { break; } case RUBY_EVENT_RETURN: case RUBY_EVENT_END: if (debugContext.getStackSize() == debugContext.getStopFrame()) { debugContext.setStopNext(1); debugContext.setStopFrame(0); } while (debugContext.getStackSize() > 0) { DebugFrame topFrame = debugContext.popFrame(); String origMethodName = topFrame.getOrigMethodName(); if ((origMethodName == null && methodName == null) || (origMethodName != null && origMethodName.equals(methodName))) { break; } } debugContext.setEnableBreakpoint(true); break; case RUBY_EVENT_CLASS: resetFrameMid(debugContext); saveCallFrame(event, tCtx, file, line, methodName, debugContext); break; case RUBY_EVENT_RAISE: setFrameSource(event, debugContext, tCtx, file, line, methodName); // XXX Implement post mortem debugging RubyException exception = (RubyException)runtime.getGlobalVariables().get("$!"); if (exception.isKindOf(runtime.getClass("SystemExit"))) { // Can't do this because this unhooks the event hook causing // a ConcurrentModificationException because the runtime // is still iterating over event hooks. Shouldn't really // matter. We're on our way out regardless. // debugger.stop(runtime); break; } if (debugger.getCatchpoint().isNil()) { break; } RubyArray ancestors = exception.getType().ancestors(); int l = ancestors.getLength(); for (int i = 0; i < l; i++) { RubyModule m = (RubyModule)ancestors.get(i); if (m.getName().equals(debugger.getCatchpointAsString())) { debugContext.setStopReason(DebugContext.StopReason.CATCHPOINT); context.callMethod(tCtx, DebugContext.AT_CATCHPOINT, breakpoint); DebugFrame debugFrame = getTopFrame(debugContext); if (debugFrame != null) { binding = debugFrame.getBinding(); } if (!binding.isNil() && tCtx != null) { binding = (tCtx != null ? RubyBinding.newBinding(runtime) : getNil()); } saveTopBinding(debugContext, binding); callAtLine(tCtx, context, debugContext, runtime, file, line); break; } } break; } cleanUp(debugContext); }
private void processEvent(final ThreadContext tCtx, final int event, final String file, final int line0, final String methodName, final IRubyObject klass, DebugContextPair contexts) { // one-based; jruby by default passes zero-based int line = line0 + 1; hookCount++; Ruby runtime = tCtx.getRuntime(); IRubyObject breakpoint = getNil(); IRubyObject binding = getNil(); IRubyObject context = contexts.context; DebugContext debugContext = contexts.debugContext; // debug("jrubydebug> %s:%d [%s] %s\n", file, line, EVENT_NAMES[event], methodName); boolean moved = false; if (debugContext.getLastLine() != line || debugContext.getLastFile() == null || !debugContext.getLastFile().equals(file)) { debugContext.setEnableBreakpoint(true); moved = true; } // else if(event != RUBY_EVENT_RETURN && event != RUBY_EVENT_C_RETURN) { // if(debug == Qtrue) // fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName)); // goto cleanup; // } else { // if(debug == Qtrue) // fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName)); // } if (event != RUBY_EVENT_LINE) { debugContext.setStepped(true); } switch (event) { case RUBY_EVENT_LINE: if (debugContext.getStackSize() == 0) { saveCallFrame(event, tCtx, file, line, methodName, debugContext); } else { setFrameSource(event, debugContext, tCtx, file, line, methodName); } if (debugger.isTracing() || debugContext.isTracing()) { IRubyObject[] args = new IRubyObject[]{ runtime.newString(file), runtime.newFixnum(line) }; context.callMethod(tCtx, DebugContext.AT_TRACING, args); } if (debugContext.getDestFrame() == -1 || debugContext.getStackSize() == debugContext.getDestFrame()) { if (moved || !debugContext.isForceMove()) { debugContext.setStopNext(debugContext.getStopNext() - 1); } if (debugContext.getStopNext() < 0) { debugContext.setStopNext(-1); } if (moved || (debugContext.isStepped() && !debugContext.isForceMove())) { debugContext.setStopLine(debugContext.getStopLine() - 1); debugContext.setStepped(false); } } else if (debugContext.getStackSize() < debugContext.getDestFrame()) { debugContext.setStopNext(0); } if (debugContext.getStopNext() == 0 || debugContext.getStopLine() == 0 || !(breakpoint = checkBreakpointsByPos(debugContext, file, line)).isNil()) { binding = (tCtx != null ? RubyBinding.newBinding(runtime) : getNil()); saveTopBinding(debugContext, binding); debugContext.setStopReason(DebugContext.StopReason.STEP); /* Check breakpoint expression. */ if (!breakpoint.isNil()) { if (!checkBreakpointExpression(breakpoint, binding)) { break; } if (!checkBreakpointHitCondition(breakpoint)) { break; } if (breakpoint != debugContext.getBreakpoint()) { debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT); context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint); } else { debugContext.setBreakpoint(getNil()); } } /* reset all pointers */ debugContext.setDestFrame(-1); debugContext.setStopLine(-1); debugContext.setStopNext(-1); callAtLine(tCtx, context, debugContext, runtime, file, line); } break; case RUBY_EVENT_CALL: saveCallFrame(event, tCtx, file, line, methodName, debugContext); breakpoint = checkBreakpointsByMethod(debugContext, klass, methodName); if (!breakpoint.isNil()) { DebugFrame debugFrame = getTopFrame(debugContext); if (debugFrame != null) { binding = debugFrame.getBinding(); } if (tCtx != null && binding.isNil()) { binding = RubyBinding.newBinding(runtime); } saveTopBinding(debugContext, binding); if(!checkBreakpointExpression(breakpoint, binding)) break; if(!checkBreakpointHitCondition(breakpoint)) break; if (breakpoint != debugContext.getBreakpoint()) { debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT); context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint); } else { debugContext.setBreakpoint(getNil()); } callAtLine(tCtx, context, debugContext, runtime, file, line); } break; case RUBY_EVENT_C_CALL: if(cCallNewFrameP(klass, methodName)) { saveCallFrame(event, tCtx, file, line, methodName, debugContext); } else { setFrameSource(event, debugContext, tCtx, file, line, methodName); } break; case RUBY_EVENT_C_RETURN: /* note if a block is given we fall through! */ if (!cCallNewFrameP(klass, methodName)) { break; } case RUBY_EVENT_RETURN: case RUBY_EVENT_END: if (debugContext.getStackSize() == debugContext.getStopFrame()) { debugContext.setStopNext(1); debugContext.setStopFrame(0); } while (debugContext.getStackSize() > 0) { DebugFrame topFrame = debugContext.popFrame(); String origMethodName = topFrame.getOrigMethodName(); if ((origMethodName == null && methodName == null) || (origMethodName != null && origMethodName.equals(methodName))) { break; } } debugContext.setEnableBreakpoint(true); break; case RUBY_EVENT_CLASS: resetFrameMid(debugContext); saveCallFrame(event, tCtx, file, line, methodName, debugContext); break; case RUBY_EVENT_RAISE: setFrameSource(event, debugContext, tCtx, file, line, methodName); // XXX Implement post mortem debugging RubyException exception = (RubyException)runtime.getGlobalVariables().get("$!"); if (exception.isKindOf(runtime.getClass("SystemExit"))) { // Can't do this because this unhooks the event hook causing // a ConcurrentModificationException because the runtime // is still iterating over event hooks. Shouldn't really // matter. We're on our way out regardless. // debugger.stop(runtime); break; } if (debugger.getCatchpoint().isNil()) { break; } RubyArray ancestors = exception.getType().ancestors(); int l = ancestors.getLength(); for (int i = 0; i < l; i++) { RubyModule m = (RubyModule)ancestors.get(i); if (m.getName().equals(debugger.getCatchpointAsString())) { debugContext.setStopReason(DebugContext.StopReason.CATCHPOINT); context.callMethod(tCtx, DebugContext.AT_CATCHPOINT, breakpoint); DebugFrame debugFrame = getTopFrame(debugContext); if (debugFrame != null) { binding = debugFrame.getBinding(); } if (tCtx != null && binding.isNil()) { binding = RubyBinding.newBinding(runtime); } saveTopBinding(debugContext, binding); callAtLine(tCtx, context, debugContext, runtime, file, line); break; } } break; } cleanUp(debugContext); }
diff --git a/core/query/src/main/java/org/openrdf/query/impl/DatasetImpl.java b/core/query/src/main/java/org/openrdf/query/impl/DatasetImpl.java index 9e0406178..e49a8f695 100644 --- a/core/query/src/main/java/org/openrdf/query/impl/DatasetImpl.java +++ b/core/query/src/main/java/org/openrdf/query/impl/DatasetImpl.java @@ -1,156 +1,158 @@ /* * Copyright Aduna (http://www.aduna-software.com/) (c) 2007. * * Licensed under the Aduna BSD-style license. */ package org.openrdf.query.impl; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import org.openrdf.model.URI; import org.openrdf.query.Dataset; /** * @author Arjohn Kampman * @author James Leigh */ public class DatasetImpl implements Dataset { private Set<URI> defaultRemoveGraphs = new LinkedHashSet<URI>(); private URI defaultInsertGraph; private Set<URI> defaultGraphs = new LinkedHashSet<URI>(); private Set<URI> namedGraphs = new LinkedHashSet<URI>(); public DatasetImpl() { } public Set<URI> getDefaultRemoveGraphs() { return Collections.unmodifiableSet(defaultRemoveGraphs); } /** * Adds a graph URI to the set of default remove graph URIs. */ public void addDefaultRemoveGraph(URI graphURI) { defaultRemoveGraphs.add(graphURI); } /** * Removes a graph URI from the set of default remove graph URIs. * * @return <tt>true</tt> if the URI was removed from the set, <tt>false</tt> * if the set did not contain the URI. */ public boolean removeDefaultRemoveGraph(URI graphURI) { return defaultRemoveGraphs.remove(graphURI); } /** * @return Returns the default insert graph. */ public URI getDefaultInsertGraph() { return defaultInsertGraph; } /** * @param defaultUpdateGraph * The default insert graph to used. */ public void setDefaultInsertGraph(URI defaultInsertGraph) { this.defaultInsertGraph = defaultInsertGraph; } public Set<URI> getDefaultGraphs() { return Collections.unmodifiableSet(defaultGraphs); } /** * Adds a graph URI to the set of default graph URIs. */ public void addDefaultGraph(URI graphURI) { defaultGraphs.add(graphURI); } /** * Removes a graph URI from the set of default graph URIs. * * @return <tt>true</tt> if the URI was removed from the set, <tt>false</tt> * if the set did not contain the URI. */ public boolean removeDefaultGraph(URI graphURI) { return defaultGraphs.remove(graphURI); } /** * Gets the (unmodifiable) set of named graph URIs. */ public Set<URI> getNamedGraphs() { return Collections.unmodifiableSet(namedGraphs); } /** * Adds a graph URI to the set of named graph URIs. */ public void addNamedGraph(URI graphURI) { namedGraphs.add(graphURI); } /** * Removes a graph URI from the set of named graph URIs. * * @return <tt>true</tt> if the URI was removed from the set, <tt>false</tt> * if the set did not contain the URI. */ public boolean removeNamedGraph(URI graphURI) { return namedGraphs.remove(graphURI); } /** * Removes all graph URIs (both default and named) from this dataset. */ public void clear() { defaultRemoveGraphs.clear(); defaultInsertGraph = null; defaultGraphs.clear(); namedGraphs.clear(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (URI uri : getDefaultRemoveGraphs()) { sb.append("DELETE FROM "); appendURI(sb, uri); } - sb.append("INSERT INTO "); - appendURI(sb, getDefaultInsertGraph()); + if (getDefaultInsertGraph() != null) { + sb.append("INSERT INTO "); + appendURI(sb, getDefaultInsertGraph()); + } for (URI uri : getDefaultGraphs()) { sb.append("USING "); appendURI(sb, uri); } for (URI uri : getNamedGraphs()) { sb.append("USING NAMED "); appendURI(sb, uri); } if (getDefaultGraphs().isEmpty() && getNamedGraphs().isEmpty()) { sb.append("## empty dataset ##"); } return sb.toString(); } private void appendURI(StringBuilder sb, URI uri) { String str = uri.toString(); if (str.length() > 50) { sb.append("<").append(str, 0, 19).append(".."); sb.append(str, str.length() - 29, str.length()).append(">\n"); } else { sb.append("<").append(uri).append(">\n"); } } }
true
true
public String toString() { StringBuilder sb = new StringBuilder(); for (URI uri : getDefaultRemoveGraphs()) { sb.append("DELETE FROM "); appendURI(sb, uri); } sb.append("INSERT INTO "); appendURI(sb, getDefaultInsertGraph()); for (URI uri : getDefaultGraphs()) { sb.append("USING "); appendURI(sb, uri); } for (URI uri : getNamedGraphs()) { sb.append("USING NAMED "); appendURI(sb, uri); } if (getDefaultGraphs().isEmpty() && getNamedGraphs().isEmpty()) { sb.append("## empty dataset ##"); } return sb.toString(); }
public String toString() { StringBuilder sb = new StringBuilder(); for (URI uri : getDefaultRemoveGraphs()) { sb.append("DELETE FROM "); appendURI(sb, uri); } if (getDefaultInsertGraph() != null) { sb.append("INSERT INTO "); appendURI(sb, getDefaultInsertGraph()); } for (URI uri : getDefaultGraphs()) { sb.append("USING "); appendURI(sb, uri); } for (URI uri : getNamedGraphs()) { sb.append("USING NAMED "); appendURI(sb, uri); } if (getDefaultGraphs().isEmpty() && getNamedGraphs().isEmpty()) { sb.append("## empty dataset ##"); } return sb.toString(); }
diff --git a/stripes/src/net/sourceforge/stripes/tag/LinkTag.java b/stripes/src/net/sourceforge/stripes/tag/LinkTag.java index 11cb483e..9d57ba52 100644 --- a/stripes/src/net/sourceforge/stripes/tag/LinkTag.java +++ b/stripes/src/net/sourceforge/stripes/tag/LinkTag.java @@ -1,118 +1,121 @@ /* Copyright 2005-2006 Tim Fennell * * 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 net.sourceforge.stripes.tag; import net.sourceforge.stripes.exception.StripesJspException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.BodyTag; import java.io.IOException; /** * Tag for generating links to pages or ActionBeans within a Stripes application. Provides * basic services such as including the context path at the start of the href URL (only * when the URL starts with a '/' and does not contain the context path already), and * including a parameter to name the source page from which the link came. Also provides the * ability to add complex parameters to the URL through the use of nested Param tags. * * @see ParamTag * @author Tim Fennell */ public class LinkTag extends LinkTagSupport implements BodyTag { /** * Does nothing. * @return EVAL_BODY_BUFFERED in all cases */ @Override public int doStartTag() throws JspException { return EVAL_BODY_BUFFERED; } /** Does nothing. */ public void doInitBody() throws JspException { /* Do Nothing. */ } /** * Does nothing. * @return SKIP_BODY in all cases */ public int doAfterBody() throws JspException { return SKIP_BODY; } /** * Prepends the context to the href attribute if necessary, and then folds all the * registered parameters into the URL. * * @return EVAL_PAGE in all cases * @throws JspException */ @Override public int doEndTag() throws JspException { try { set("href", buildUrl()); writeOpenTag(getPageContext().getOut(), "a"); String body = getBodyContentAsString(); + if (body == null) { + body = get("href"); + } if (body != null) { getPageContext().getOut().write(body.trim()); } writeCloseTag(getPageContext().getOut(), "a"); } catch (IOException ioe) { throw new StripesJspException("IOException while writing output in LinkTag.", ioe); } // Restore state and go on with the page getAttributes().remove("href"); clearParameters(); return EVAL_PAGE; } /** Pass through to {@link LinkTagSupport#setUrl(String)}. */ public void setHref(String href) { setUrl(href); } /** Pass through to {@link LinkTagSupport#getUrl()}. */ public String getHref() { return getUrl(); } /////////////////////////////////////////////////////////////////////////// // Additional HTML Attributes supported by the tag /////////////////////////////////////////////////////////////////////////// public void setCharset(String charset) { set("charset", charset); } public String getCharset() { return get("charset"); } public void setCoords(String coords) { set("coords", coords); } public String getCoords() { return get("coords"); } public void setHreflang(String hreflang) { set("hreflang", hreflang); } public String getHreflang() { return get("hreflang"); } public void setName(String name) { set("name", name); } public String getName() { return get("name"); } public void setRel(String rel) { set("rel", rel); } public String getRel() { return get("rel"); } public void setRev(String rev) { set("rev", rev); } public String getRev() { return get("rev"); } public void setShape(String shape) { set("shape", shape); } public String getShape() { return get("shape"); } public void setTarget(String target) { set("target", target); } public String getTarget() { return get("target"); } public void setType(String type) { set("type", type); } public String getType() { return get("type"); } }
true
true
public int doEndTag() throws JspException { try { set("href", buildUrl()); writeOpenTag(getPageContext().getOut(), "a"); String body = getBodyContentAsString(); if (body != null) { getPageContext().getOut().write(body.trim()); } writeCloseTag(getPageContext().getOut(), "a"); } catch (IOException ioe) { throw new StripesJspException("IOException while writing output in LinkTag.", ioe); } // Restore state and go on with the page getAttributes().remove("href"); clearParameters(); return EVAL_PAGE; }
public int doEndTag() throws JspException { try { set("href", buildUrl()); writeOpenTag(getPageContext().getOut(), "a"); String body = getBodyContentAsString(); if (body == null) { body = get("href"); } if (body != null) { getPageContext().getOut().write(body.trim()); } writeCloseTag(getPageContext().getOut(), "a"); } catch (IOException ioe) { throw new StripesJspException("IOException while writing output in LinkTag.", ioe); } // Restore state and go on with the page getAttributes().remove("href"); clearParameters(); return EVAL_PAGE; }
diff --git a/de.walware.statet.r.console.core/src/de/walware/statet/r/nico/impl/RjsController.java b/de.walware.statet.r.console.core/src/de/walware/statet/r/nico/impl/RjsController.java index a1b29c76..872cdbc0 100644 --- a/de.walware.statet.r.console.core/src/de/walware/statet/r/nico/impl/RjsController.java +++ b/de.walware.statet.r.console.core/src/de/walware/statet/r/nico/impl/RjsController.java @@ -1,1176 +1,1176 @@ /******************************************************************************* * Copyright (c) 2008-2011 WalWare/StatET-Project (www.walware.de/goto/statet). * 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: * Stephan Wahlbrink - initial API and implementation *******************************************************************************/ package de.walware.statet.r.nico.impl; import static de.walware.statet.nico.core.runtime.IToolEventHandler.LOGIN_ADDRESS_DATA_KEY; import static de.walware.statet.nico.core.runtime.IToolEventHandler.LOGIN_CALLBACKS_DATA_KEY; import static de.walware.statet.nico.core.runtime.IToolEventHandler.LOGIN_MESSAGE_DATA_KEY; import static de.walware.statet.nico.core.runtime.IToolEventHandler.LOGIN_USERNAME_DATA_KEY; import java.io.InputStream; import java.io.OutputStream; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.locks.Lock; import javax.security.auth.callback.Callback; import javax.security.auth.login.LoginException; import com.ibm.icu.text.DateFormat; import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.debug.core.model.IProcess; import org.eclipse.osgi.util.NLS; import de.walware.ecommons.ICommonStatusConstants; import de.walware.ecommons.io.FileUtil; import de.walware.ecommons.ltk.IModelElement; import de.walware.ecommons.ltk.IModelElement.Filter; import de.walware.ecommons.ltk.ISourceUnit; import de.walware.ecommons.ltk.ast.IAstNode; import de.walware.ecommons.net.RMIAddress; import de.walware.ecommons.ts.IToolRunnable; import de.walware.ecommons.ts.IToolService; import de.walware.statet.nico.core.runtime.IRemoteEngineController; import de.walware.statet.nico.core.runtime.IToolEventHandler; import de.walware.statet.nico.core.runtime.ToolProcess; import de.walware.statet.nico.core.util.TrackingConfiguration; import de.walware.rj.RjException; import de.walware.rj.data.RDataJConverter; import de.walware.rj.data.RList; import de.walware.rj.data.RObject; import de.walware.rj.data.RObjectFactory; import de.walware.rj.data.RReference; import de.walware.rj.data.defaultImpl.RObjectFactoryImpl; import de.walware.rj.eclient.graphics.comclient.ERClientGraphicActions; import de.walware.rj.server.ConsoleEngine; import de.walware.rj.server.DbgCmdItem; import de.walware.rj.server.FxCallback; import de.walware.rj.server.RjsComConfig; import de.walware.rj.server.RjsStatus; import de.walware.rj.server.Server; import de.walware.rj.server.ServerInfo; import de.walware.rj.server.ServerLogin; import de.walware.rj.server.client.AbstractRJComClient; import de.walware.rj.server.client.FunctionCallImpl; import de.walware.rj.server.client.RClientGraphicFactory; import de.walware.rj.server.client.RGraphicCreatorImpl; import de.walware.rj.server.dbg.CallStack; import de.walware.rj.server.dbg.DbgEnablement; import de.walware.rj.server.dbg.DbgFilterState; import de.walware.rj.server.dbg.ElementTracepointInstallationReport; import de.walware.rj.server.dbg.ElementTracepointInstallationRequest; import de.walware.rj.server.dbg.FrameContext; import de.walware.rj.server.dbg.FrameContextDetailRequest; import de.walware.rj.server.dbg.SetDebugReport; import de.walware.rj.server.dbg.SetDebugRequest; import de.walware.rj.server.dbg.SrcfileData; import de.walware.rj.server.dbg.TracepointEvent; import de.walware.rj.server.dbg.TracepointStatesUpdate; import de.walware.rj.services.FunctionCall; import de.walware.rj.services.RGraphicCreator; import de.walware.rj.services.RPlatform; import de.walware.rj.services.RServiceControlExtension; import de.walware.statet.r.console.core.IRBasicAdapter; import de.walware.statet.r.console.core.IRDataAdapter; import de.walware.statet.r.console.core.RDbg; import de.walware.statet.r.console.core.RProcess; import de.walware.statet.r.console.core.RTool; import de.walware.statet.r.console.core.RWorkspace; import de.walware.statet.r.core.data.ICombinedRElement; import de.walware.statet.r.core.model.IRElement; import de.walware.statet.r.core.model.IRLangSourceElement; import de.walware.statet.r.core.model.IRModelInfo; import de.walware.statet.r.core.model.IRModelManager; import de.walware.statet.r.core.model.IRWorkspaceSourceUnit; import de.walware.statet.r.core.model.RElementName; import de.walware.statet.r.core.model.RModel; import de.walware.statet.r.core.rsource.ast.FDef; import de.walware.statet.r.core.rsource.ast.RAst; import de.walware.statet.r.core.rsource.ast.RAstNode; import de.walware.statet.r.internal.console.core.RConsoleCorePlugin; import de.walware.statet.r.internal.nico.RNicoMessages; import de.walware.statet.r.internal.rdata.CombinedElement; import de.walware.statet.r.internal.rdata.CombinedFactory; import de.walware.statet.r.nico.AbstractRDbgController; import de.walware.statet.r.nico.ICombinedRDataAdapter; import de.walware.statet.r.nico.IRModelSrcref; import de.walware.statet.r.nico.IRSrcref; import de.walware.statet.r.nico.RWorkspaceConfig; /** * Controller for RJ-Server */ public class RjsController extends AbstractRDbgController implements IRemoteEngineController, IRDataAdapter, ICombinedRDataAdapter, RServiceControlExtension { static { RjsComConfig.registerRObjectFactory(CombinedFactory.FACTORY_ID, CombinedFactory.INSTANCE); } public static class RjsConnection { private final RMIAddress fRMIAddress; private final Server fServer; private RjsConnection(final RMIAddress rmiAddress, final Server server) { fRMIAddress = rmiAddress; fServer = server; } public RMIAddress getRMIAddress() { return fRMIAddress; } public Server getServer() { return fServer; } } public static RjsConnection lookup(final Registry registry, final RemoteException registryException, final RMIAddress address) throws CoreException { if (address == null) { throw new NullPointerException(); } final int[] clientVersion = AbstractRJComClient.version(); clientVersion[2] = -1; final Server server; int[] version; try { if (registryException != null) { throw registryException; } server = (Server) registry.lookup(address.getName()); version = server.getVersion(); } catch (final NotBoundException e) { throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, "The specified R engine is not in the service registry (RMI).", e )); } catch (final RemoteException e) { throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, NLS.bind("Cannot access the host/service registry (RMI) at ''{0}''.", address.getRegistryAddress()), e )); } catch (final ClassCastException e) { throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, NLS.bind("The specified R engine ({0}) is incompatibel to this client ({1}).", RjsUtil.getVersionString(null), RjsUtil.getVersionString(clientVersion)), e )); } if (version.length != 3 || version[0] != clientVersion[0] || version[1] != clientVersion[1]) { throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, NLS.bind("The specified R engine ({0}) is incompatibel to this client ({1}).", RjsUtil.getVersionString(version), RjsUtil.getVersionString(clientVersion)), null )); } return new RjsConnection(address, server); } private static final Filter<IModelElement> TAG_ELEMENT_FILTER = new Filter<IModelElement>() { public boolean include(final IModelElement element) { return ((element.getElementType() & IRElement.MASK_C1) == IRElement.C1_METHOD); } }; private class NicoComClient extends AbstractRJComClient { public NicoComClient() { } @Override protected void initGraphicFactory() { final IToolEventHandler eventHandler = getEventHandler(INIT_RGRAPHIC_FACTORY_HANDLER_ID); final Map<String, Object> data = new HashMap<String, Object>(); final IStatus status = eventHandler.handle(INIT_RGRAPHIC_FACTORY_HANDLER_ID, RjsController.this, data, null); final RClientGraphicFactory factory = (RClientGraphicFactory) data.get("factory"); //$NON-NLS-1$ if (status.isOK() && factory != null) { setGraphicFactory(factory, new ERClientGraphicActions(this, fProcess)); } } @Override protected void updateBusy(final boolean isBusy) { // try { fIsBusy = isBusy; // } // catch (Exception e) { // } } @Override protected void updatePrompt(final String text, final boolean addToHistory) { try { RjsController.this.setCurrentPromptL(text, addToHistory); } catch (final Exception e) { } } @Override protected void writeStdOutput(final String text) { try { fDefaultOutputStream.append(text, getCurrentSubmitType(), 0); } catch (final Exception e) { } } @Override protected void writeErrOutput(final String text) { try { fErrorOutputStream.append(text, getCurrentSubmitType(), 0); } catch (final Exception e) { } } @Override protected void showMessage(final String text) { try { fInfoStream.append(text, getCurrentSubmitType(), 0); } catch (final Exception e) { } } @Override protected RList handleUICallback(final String commandId, final RList args, final IProgressMonitor monitor) throws Exception { // TODO: allow handlers to use RJ data objects // TODO: allow handlers to return values // TODO: provide extension point for event handlers final IToolEventHandler handler = getEventHandler(commandId); if (handler != null) { final RDataJConverter converter = new RDataJConverter(); converter.setKeepArray1(false); converter.setRObjectFactory(fRObjectFactory); final Map<String, Object> javaArgs = new HashMap<String, Object>(); if (args != null) { for (int i = 0; i < args.getLength(); i++) { javaArgs.put(args.getName(i), converter.toJava(args.get(i))); } } final IStatus status = handler.handle(commandId, RjsController.this, javaArgs, monitor); switch (status.getSeverity()) { case IStatus.OK: break; default: throw new CoreException(status); } Map<String, Object> javaAnswer = null; if (commandId.equals("common/chooseFile")) { //$NON-NLS-1$ javaAnswer = Collections.singletonMap( "filename", javaArgs.get("filename") ); //$NON-NLS-1$ //$NON-NLS-2$ } if (javaAnswer != null) { final RList answer = (RList) converter.toRJ(javaAnswer); return answer; } else { return null; } } return super.handleUICallback(commandId, args, monitor); } @Override protected void handleDbgEvent(final byte dbgOp, final Object event) { if (dbgOp == DbgCmdItem.OP_NOTIFY_TP_EVENT) { handle((TracepointEvent) event); } super.handleDbgEvent(dbgOp, event); } @Override protected void log(final IStatus status) { RConsoleCorePlugin.log(status); } @Override protected void handleServerStatus(final RjsStatus serverStatus, final IProgressMonitor monitor) throws CoreException { String specialMessage = null; switch (serverStatus.getCode()) { case 0: return; case Server.S_DISCONNECTED: fConnectionState = Server.S_DISCONNECTED; //$FALL-THROUGH$ case Server.S_LOST: if (fConnectionState == Server.S_DISCONNECTED) { specialMessage = RNicoMessages.R_Info_Disconnected_message; break; } else if (!fEmbedded) { fConnectionState = Server.S_LOST; specialMessage = RNicoMessages.R_Info_ConnectionLost_message; break; } //$FALL-THROUGH$ case Server.S_STOPPED: fConnectionState = Server.S_STOPPED; specialMessage = RNicoMessages.R_Info_Stopped_message; break; default: throw new IllegalStateException(); } if (!isClosed()) { markAsTerminated(); setClosed(true); handleStatus(new Status(IStatus.INFO, RConsoleCorePlugin.PLUGIN_ID, addTimestampToMessage(specialMessage, System.currentTimeMillis())), monitor); } throw new CoreException(new Status(IStatus.CANCEL, RConsoleCorePlugin.PLUGIN_ID, specialMessage)); } @Override protected void handleStatus(final Status status, final IProgressMonitor monitor) { RjsController.this.handleStatus(status, monitor); } @Override protected void processHotMode() { RjsController.this.runHotModeLoop(); } @Override protected void processExtraMode(final int position) { RjsController.this.runSuspendedLoopL(SUSPENDED_DEEPLEVEL); } @Override protected void scheduleConnectionCheck() { synchronized (fQueue) { if (getStatusL().isWaiting()) { scheduleControllerRunnable(new ControllerSystemRunnable( "r/check", "Connection Check") { //$NON-NLS-1$ public void run(final IToolService s, final IProgressMonitor monitor) throws CoreException { fRjs.runMainLoopPing(monitor); } }); } } } } private final RMIAddress fAddress; private final String[] fRArgs; private boolean fIsBusy = true; private final RjsConnection fRjsConnection; private final NicoComClient fRjs = new NicoComClient(); private int fRjsId; private final boolean fEmbedded; private final boolean fStartup; private final Map<String, Object> fRjsProperties; private int fConnectionState; private final RObjectFactory fRObjectFactory = RObjectFactoryImpl.INSTANCE; /** * * @param process the R process the controller belongs to * @param address the RMI address * @param initData the initialization data * @param embedded flag if running in embedded mode * @param startup flag to start R (otherwise connect only) * @param rArgs R arguments (required only if startup is <code>true</code>) * @param initialWD */ public RjsController(final RProcess process, final RMIAddress address, final RjsConnection connection, final Map<String, Object> initData, final boolean embedded, final boolean startup, final String[] rArgs, final Map<String, Object> rjsProperties, final IFileStore initialWD, final RWorkspaceConfig workspaceConfig, final List<TrackingConfiguration> trackingConfigurations) { super(process, initData); if (address == null || connection == null) { throw new IllegalArgumentException(); } process.registerFeatureSet(RTool.R_DATA_FEATURESET_ID); process.registerFeatureSet("de.walware.rj.services.RService"); //$NON-NLS-1$ if (!embedded) { process.registerFeatureSet(IRemoteEngineController.FEATURE_SET_ID); } fAddress = address; fRjsConnection = connection; fEmbedded = embedded; fStartup = startup; fRArgs = rArgs; fRjsProperties = (rjsProperties != null) ? rjsProperties : new HashMap<String, Object>(); fTrackingConfigurations = trackingConfigurations; fWorkspaceData = new RWorkspace(this, (embedded || address.isLocalHost()) ? null : address.getHostAddress().getHostAddress(), workspaceConfig ); setWorkspaceDirL(initialWD); initRunnableAdapterL(); } @Override public boolean supportsBusy() { return true; } @Override public boolean isBusy() { return fIsBusy; } public boolean isDisconnected() { return (fConnectionState == Server.S_DISCONNECTED || fConnectionState == Server.S_LOST); } /** * This is an async operation * cancel is not supported by this implementation * * @param monitor a progress monitor */ public void disconnect(final IProgressMonitor monitor) throws CoreException { switch (getStatus()) { case STARTED_IDLING: case STARTED_SUSPENDED: case STARTED_PROCESSING: case STARTED_PAUSED: monitor.beginTask("Disconnecting from R remote engine...", 1); synchronized (fQueue) { beginInternalTask(); } try { fRjs.getConsoleServer().disconnect(); fConnectionState = Server.S_DISCONNECTED; } catch (final RemoteException e) { throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, "Disconnecting from R remote engine failed.", e)); } finally { synchronized (fQueue) { scheduleControllerRunnable(new ControllerSystemRunnable( "common/disconnect/finish", "Disconnect") { //$NON-NLS-1$ public void run(final IToolService s, final IProgressMonitor monitor) throws CoreException { if (!isTerminated()) { fRjs.runMainLoopPing(monitor); fRjs.handleServerStatus(new RjsStatus(RjsStatus.INFO, Server.S_DISCONNECTED), monitor); } } }); endInternalTask(); } monitor.done(); } } } @Override protected IToolRunnable createStartRunnable() { return new StartRunnable() { @Override public String getLabel() { return "Connect to and load remote R engine."; } }; } @Override protected void startToolL(final IProgressMonitor monitor) throws CoreException { fRjsId = RjsComConfig.registerClientComHandler(fRjs); fRjs.initClient(getTool(), this, fRjsProperties, fRjsId); try { final Map<String, Object> data = new HashMap<String, Object>(); final IToolEventHandler loginHandler = getEventHandler(IToolEventHandler.LOGIN_REQUEST_EVENT_ID); String msg = null; boolean connected = false; while (!connected) { final Map<String, Object> initData = getInitData(); final ServerLogin login = fRjsConnection.getServer().createLogin(Server.C_CONSOLE_CONNECT); try { final Callback[] callbacks = login.getCallbacks(); if (callbacks != null) { final List<Callback> checked = new ArrayList<Callback>(); FxCallback fx = null; for (final Callback callback : callbacks) { if (callback instanceof FxCallback) { fx = (FxCallback) callback; } else { checked.add(callback); } } if (initData != null) { data.putAll(initData); } data.put(LOGIN_ADDRESS_DATA_KEY, (fx != null) ? fAddress.getHost() : fAddress.getAddress()); data.put(LOGIN_MESSAGE_DATA_KEY, msg); data.put(LOGIN_CALLBACKS_DATA_KEY, checked.toArray(new Callback[checked.size()])); if (loginHandler == null) { throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, "Login requested but not supported by this configuration.", null )); } if (!loginHandler.handle(IToolEventHandler.LOGIN_REQUEST_EVENT_ID, this, data, monitor).isOK()) { throw new CoreException(Status.CANCEL_STATUS); } if (fx != null) { RjsUtil.handleFxCallback(RjsUtil.getSession(data, new SubProgressMonitor(monitor, 1)), fx, new SubProgressMonitor(monitor, 1)); } } msg = null; if (monitor.isCanceled()) { throw new CoreException(Status.CANCEL_STATUS); } final Map<String, Object> args = new HashMap<String, Object>(); args.putAll(fRjsProperties); ConsoleEngine rjServer; if (fStartup) { args.put("args", fRArgs); //$NON-NLS-1$ rjServer = (ConsoleEngine) fRjsConnection.getServer().execute(Server.C_CONSOLE_START, args, login.createAnswer()); } else { rjServer = (ConsoleEngine) fRjsConnection.getServer().execute(Server.C_CONSOLE_CONNECT, args, login.createAnswer()); } fRjs.setServer(rjServer, 0); connected = true; if (callbacks != null) { loginHandler.handle(IToolEventHandler.LOGIN_OK_EVENT_ID, this, data, monitor); if (initData != null) { initData.put(LOGIN_USERNAME_DATA_KEY, data.get(LOGIN_USERNAME_DATA_KEY)); } } } catch (final LoginException e) { msg = e.getLocalizedMessage(); } finally { if (login != null) { login.clearData(); } } } final ServerInfo info = fRjsConnection.getServer().getInfo(); if (fWorkspaceData.isRemote()) { try { final String wd = FileUtil.toString(fWorkspaceData.toFileStore(info.getDirectory())); if (wd != null) { setStartupWD(wd); } } catch (final CoreException e) {} } else { setStartupWD(info.getDirectory()); } final long timestamp = info.getTimestamp(); if (timestamp != 0) { setStartupTimestamp(timestamp); } final List<IStatus> warnings = new ArrayList<IStatus>(); initTracks(info.getDirectory(), monitor, warnings); if (fStartup && !fStartupsRunnables.isEmpty()) { fQueue.add(fStartupsRunnables.toArray(new IToolRunnable[fStartupsRunnables.size()])); fStartupsRunnables.clear(); } if (!fStartup) { handleStatus(new Status(IStatus.INFO, RConsoleCorePlugin.PLUGIN_ID, addTimestampToMessage(RNicoMessages.R_Info_Reconnected_message, fProcess.getConnectionTimestamp()) ), monitor); } - fRjs.runMainLoop(null, null, monitor); + // fRjs.runMainLoop(null, null, monitor); must not wait at server side fRjs.activateConsole(); scheduleControllerRunnable(new ControllerSystemRunnable( "r/rj/start2", "Finish Initialization / Read Output") { //$NON-NLS-1$ public void run(final IToolService s, final IProgressMonitor monitor) throws CoreException { if (!fRjs.isConsoleReady()) { // R is still working fRjs.runMainLoop(null, null, monitor); } for (final IStatus status : warnings) { handleStatus(status, monitor); } } }); } catch (final RemoteException e) { throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, "The R engine could not be started.", e )); } catch (final RjException e) { throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, "An error occured when creating login data.", e )); } } // public void controlNotification(final RjsComObject com) throws RemoteException { // if (com instanceof RjsStatus) { // final RjsStatusImpl2 serverStatus = (RjsStatusImpl2) com; // if (serverStatus.getCode() == Server.S_DISCONNECTED || serverStatus.getCode() == Server.S_STOPPED) { // scheduleControllerRunnable(new IToolRunnable() { // public String getTypeId() { // return null; // } // public String getLabel() { // return "Update State"; // } // public SubmitType getSubmitType() { // return SubmitType.OTHER; // } // public void changed(final int event, final ToolProcess process) { // } // public void run(final IToolRunnableControllerAdapter tools, final IProgressMonitor monitor) // throws InterruptedException, CoreException { // if (!isTerminated()) { // rjsHandleStatus(serverStatus, monitor); // } // } // // }); // } // } // } protected String addTimestampToMessage(final String message, final long timestamp) { final String datetime = DateFormat.getDateTimeInstance().format(System.currentTimeMillis()); return datetime + " - " + message; //$NON-NLS-1$ } @Override protected void requestHotMode(final boolean async) { fRjs.requestHotMode(async); } @Override protected boolean initilizeHotMode() { return fRjs.startHotMode(); } @Override protected int setSuspended(final int level, final int enterDetail, final Object enterData) { final int diff = super.setSuspended(level, enterDetail, enterData); if (level > 0 && diff > 0) { fRjs.requestExtraMode( (AbstractRJComClient.EXTRA_BEFORE | AbstractRJComClient.EXTRA_NESTED) ); } return diff; } @Override protected CallStack doEvalCallStack(final IProgressMonitor monitor) throws CoreException { return (CallStack) fRjs.execSyncDbgOp(DbgCmdItem.OP_LOAD_FRAME_LIST, null, monitor ); } @Override protected FrameContext doEvalFrameContext(final int position, final IProgressMonitor monitor) throws Exception { return (FrameContext) fRjs.execSyncDbgOp(DbgCmdItem.OP_LOAD_FRAME_CONTEXT, new FrameContextDetailRequest(position), monitor ); } @Override protected void interruptTool(final int hardness) throws UnsupportedOperationException { if (hardness < 10) { fRjs.runAsyncInterrupt(); } if (hardness > 6) { super.interruptTool(hardness); } } @Override protected void postCancelTask(final int options, final IProgressMonitor monitor) throws CoreException { super.postCancelTask(options, monitor); fCurrentInput = ""; //$NON-NLS-1$ doSubmitL(monitor); fCurrentInput = ""; //$NON-NLS-1$ doSubmitL(monitor); } @Override protected boolean isToolAlive() { if (fConnectionState != 0 || !fRjs.runAsyncPing()) { return false; } if (Thread.currentThread() == getControllerThread() && !isInHotModeL() && !fRjs.isConsoleReady()) { return false; } return true; } @Override protected void killTool(final IProgressMonitor monitor) { if (getControllerThread() == null) { markAsTerminated(); return; } interruptTool(9); synchronized (fQueue) { fQueue.notifyAll(); } fRjs.setClosed(true); final ToolProcess consoleProcess = getTool(); // TODO: kill remote command? final IProcess[] processes = consoleProcess.getLaunch().getProcesses(); for (int i = 0; i < processes.length; i++) { if (processes[i] != consoleProcess && !processes[i].isTerminated()) { try { processes[i].terminate(); } catch (final Exception e) { } } } interruptTool(10); markAsTerminated(); } @Override protected void clear() { fRjs.setClosed(true); super.clear(); if (fEmbedded && !isDisconnected()) { try { Naming.unbind(fAddress.getAddress()); } catch (final Throwable e) { } } fRjs.disposeAllGraphics(); if (fRjsId > 0) { RjsComConfig.unregisterClientComHandler(fRjsId); fRjsId = 0; } } @Override protected int finishToolL() { int exitCode = 0; if (isDisconnected()) { exitCode = ToolProcess.EXITCODE_DISCONNECTED; } return exitCode; } @Override protected boolean canSuspend(final IProgressMonitor monitor) { return (fRjs.getDataLevel() == 0); } @Override protected void doRequestSuspend(final IProgressMonitor monitor) throws CoreException { fRjs.execSyncDbgOp(DbgCmdItem.OP_REQUEST_SUSPEND, null, monitor ); } @Override protected SetDebugReport doExec(final SetDebugRequest request, final IProgressMonitor monitor) throws CoreException { return (SetDebugReport) fRjs.execSyncDbgOp(DbgCmdItem.OP_SET_DEBUG, request, monitor); } @Override protected void doPrepareSrcfile(final String srcfile, final String statetPath, final IProgressMonitor monitor) throws CoreException { final FunctionCall prepare = createFunctionCall("rj:::.statet.prepareSrcfile"); prepare.addChar("filename", srcfile); prepare.addChar("path", statetPath); prepare.evalVoid(monitor); } @Override public ElementTracepointInstallationReport exec( final ElementTracepointInstallationRequest request, final IProgressMonitor monitor) throws CoreException { return (ElementTracepointInstallationReport) fRjs.execSyncDbgOp( DbgCmdItem.OP_INSTALL_TP_POSITIONS, request, monitor ); } @Override public void exec(final DbgEnablement request) throws CoreException { fRjs.execAsyncDbgOp(DbgCmdItem.OP_SET_ENABLEMENT, request); } @Override public void exec(final DbgFilterState request) throws CoreException { fRjs.execAsyncDbgOp(DbgCmdItem.OP_RESET_FILTER_STATE, request); } @Override public void exec(final TracepointStatesUpdate request) throws CoreException { fRjs.execAsyncDbgOp(DbgCmdItem.OP_UPDATE_TP_STATES, request); } @Override public void exec(final TracepointStatesUpdate request, final IProgressMonitor monitor) throws CoreException { fRjs.execSyncDbgOp(DbgCmdItem.OP_UPDATE_TP_STATES, request, monitor); } @Override protected void doSubmitCommandL(final String[] lines, final SrcfileData srcfile, final IRSrcref srcref, final IProgressMonitor monitor) throws CoreException { if ((fCurrentPrompt.meta & (IRBasicAdapter.META_PROMPT_DEFAULT | IRBasicAdapter.META_PROMPT_SUSPENDED)) == 0) { super.doSubmitCommandL(lines, srcfile, srcref, monitor); return; } final FunctionCall prepare = createFunctionCall("rj:::.statet.prepareCommand"); prepare.add("lines", fRObjectFactory.createVector(fRObjectFactory.createCharData(lines))); if (srcfile != null && srcref != null) { final List<String> attributeNames = new ArrayList<String>(); final List<RObject> attributeValues = new ArrayList<RObject>(); if (srcfile.getName() != null) { prepare.addChar("filename", srcfile.getName()); } // if (srcfile.workspacePath != null) { // attributeNames.add("statet.Path"); // attributeValues.add(fRObjectFactory.createVector(fRObjectFactory.createCharData( // new String[] { srcfile.workspacePath } ))); // } if (srcfile.getTimestamp() != 0) { attributeNames.add("timestamp"); attributeValues.add(fRObjectFactory.createVector(fRObjectFactory.createNumData( new double[] { srcfile.getTimestamp() } ))); } final int[] rjSrcref = RDbg.createRJSrcref(srcref); if (rjSrcref != null) { attributeNames.add("linesSrcref"); attributeValues.add(fRObjectFactory.createVector(fRObjectFactory.createIntData( rjSrcref ))); } if (attributeNames.size() > 0) { prepare.add("srcfileAttributes", fRObjectFactory.createList( attributeValues.toArray(new RObject[attributeValues.size()]), attributeNames.toArray(new String[attributeNames.size()]) )); } if (srcref instanceof IRModelSrcref) { // Move to abstract controller or breakpoint adapter? final IRModelSrcref modelSrcref = (IRModelSrcref) srcref; final List<IRLangSourceElement> elements = modelSrcref.getElements(); if (elements.size() > 0) { final List<String> elementIds = new ArrayList<String>(elements.size()); final List<RObject> elementIndexes = new ArrayList<RObject>(elements.size()); for (final IRLangSourceElement element : elements) { if (TAG_ELEMENT_FILTER.include(element)) { final FDef fdef = (FDef) element.getAdapter(FDef.class); if (fdef != null) { final String elementId = RDbg.getElementId(element); final RAstNode cont = fdef.getContChild(); final int[] path = RAst.computeRExpressionIndex(cont, RAst.getRRootNode(cont, modelSrcref) ); if (elementId != null && path != null) { final int[] fullPath = new int[path.length+1]; fullPath[0] = 1; System.arraycopy(path, 0, fullPath, 1, path.length); elementIds.add(elementId); elementIndexes.add(fRObjectFactory.createVector( fRObjectFactory.createIntData(fullPath))); } } } } if (elementIds.size() > 0) { prepare.add("elementIds", fRObjectFactory.createList( elementIndexes.toArray(new RObject[elementIndexes.size()]), elementIds.toArray(new String[elementIds.size()]) )); } } } } prepare.evalVoid(monitor); final boolean addToHistory = (fCurrentPrompt.meta & IRBasicAdapter.META_HISTORY_DONTADD) == 0; fCurrentInput = lines[0]; doBeforeSubmitL(); for (int i = 1; i < lines.length; i++) { setCurrentPromptL(fContinuePromptText, addToHistory); fCurrentInput = lines[i]; doBeforeSubmitL(); } fCurrentInput = "rj:::.statet.evalCommand()"; doSubmitL(monitor); } @Override public void doSubmitFileCommandToConsole(final String[] lines, final SrcfileData srcfile, final ISourceUnit su, final IProgressMonitor monitor) throws CoreException { if (srcfile != null && su instanceof IRWorkspaceSourceUnit && su.getModelTypeId() == RModel.TYPE_ID) { try { final IRModelInfo modelInfo = (IRModelInfo) su.getModelInfo(RModel.TYPE_ID, IRModelManager.MODEL_FILE, monitor ); if (modelInfo != null) { final IRLangSourceElement fileElement = modelInfo.getSourceElement(); final RAstNode rootNode = (RAstNode) fileElement.getAdapter(IAstNode.class); final List<? extends IRLangSourceElement> elements = modelInfo.getSourceElement() .getSourceChildren(TAG_ELEMENT_FILTER); final List<String> elementIds = new ArrayList<String>(elements.size()); final List<RObject> elementIndexes = new ArrayList<RObject>(elements.size()); for (final IRLangSourceElement element : elements) { final FDef fdef = (FDef) element.getAdapter(FDef.class); if (fdef != null) { final String elementId = RDbg.getElementId(element); final RAstNode cont = fdef.getContChild(); final int[] path = RAst.computeRExpressionIndex(cont, rootNode); if (elementId != null && path != null) { elementIds.add(elementId); elementIndexes.add(fRObjectFactory.createVector( fRObjectFactory.createIntData(path))); } } } final FunctionCall prepare = createFunctionCall("rj:::.statet.prepareSource"); //$NON-NLS-1$ prepare.add(fRObjectFactory.createList(new RObject[] { fRObjectFactory.createVector(fRObjectFactory.createCharData( new String[] { srcfile.getPath() })), fRObjectFactory.createVector(fRObjectFactory.createNumData( new double[] { srcfile.getTimestamp() })), fRObjectFactory.createVector(fRObjectFactory.createIntData( new int[] { rootNode.getChildCount() })), fRObjectFactory.createList( elementIndexes.toArray(new RObject[elementIndexes.size()]), elementIds.toArray(new String[elementIds.size()]) ), }, new String[] { "path", "timestamp", "exprsLength", "elementIds" })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ prepare.evalVoid(monitor); } } catch (final CoreException e) { RConsoleCorePlugin.log(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, -1, NLS.bind("An error occurred when preparing element tagging for file ''{0}''.", srcfile.getPath() ), e )); } } super.doSubmitFileCommandToConsole(lines, srcfile, su, monitor); } @Override protected void doSubmitL(final IProgressMonitor monitor) throws CoreException { fRjs.answerConsole(fCurrentInput + fLineSeparator, monitor); } public RPlatform getPlatform() { return fRjs.getRPlatform(); } public void evalVoid(final String command, final IProgressMonitor monitor) throws CoreException { fRjs.evalVoid(command, null, monitor); } public RObject evalData(final String command, final IProgressMonitor monitor) throws CoreException { return fRjs.evalData(command, null, null, 0, -1, monitor); } public RObject evalData(final String command, final String factoryId, final int options, final int depth, final IProgressMonitor monitor) throws CoreException { return fRjs.evalData(command, null, factoryId, options, depth, monitor); } public RObject evalData(final String command, final RObject envir, final String factoryId, final int options, final int depth, final IProgressMonitor monitor) throws CoreException { return fRjs.evalData(command, envir, factoryId, options, depth, monitor); } public RObject evalData(final RReference reference, final IProgressMonitor monitor) throws CoreException { return fRjs.evalData(reference, null, 0, -1, monitor); } public RObject evalData(final RReference reference, final String factoryId, final int options, final int depth, final IProgressMonitor monitor) throws CoreException { return fRjs.evalData(reference, factoryId, options, depth, monitor); } public RObject[] findData(final String symbol, final RObject envir, final boolean inherits, final String factoryId, final int options, final int depth, final IProgressMonitor monitor) throws CoreException { return fRjs.findData(symbol, envir, inherits, factoryId, options, depth, monitor); } public ICombinedRElement evalCombinedStruct(final String command, final int options, final int depth, final RElementName name, final IProgressMonitor monitor) throws CoreException { final RObject data = evalData(command, CombinedFactory.FACTORY_ID, (options | RObjectFactory.F_ONLY_STRUCT), depth, monitor ); if (data instanceof CombinedElement) { final CombinedElement e = (CombinedElement) data; CombinedFactory.INSTANCE.setElementName(e, name); return e; } return null; } public ICombinedRElement evalCombinedStruct(final String command, final RObject envir, final int options, final int depth, final RElementName name, final IProgressMonitor monitor) throws CoreException { final RObject data = evalData(command, envir, CombinedFactory.FACTORY_ID, (options | RObjectFactory.F_ONLY_STRUCT), depth, monitor ); if (data instanceof CombinedElement) { final CombinedElement e = (CombinedElement) data; CombinedFactory.INSTANCE.setElementName(e, name); return e; } return null; } public ICombinedRElement evalCombinedStruct(final RElementName name, final int options, final int depth, final IProgressMonitor monitor) throws CoreException { final String command = RElementName.createDisplayName(name, RElementName.DISPLAY_NS_PREFIX | RElementName.DISPLAY_EXACT); if (command == null) { throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, 0, "Illegal R element name.", null)); } return evalCombinedStruct(command, options, depth, name, monitor); } public ICombinedRElement evalCombinedStruct(final RReference reference, final int options, final int depth, final RElementName name, final IProgressMonitor monitor) throws CoreException { final RObject data = evalData(reference, CombinedFactory.FACTORY_ID, (options | RObjectFactory.F_ONLY_STRUCT), depth, monitor); if (data instanceof CombinedElement) { final CombinedElement e = (CombinedElement) data; CombinedFactory.INSTANCE.setElementName(e, name); return e; } return null; } public void assignData(final String expression, final RObject data, final IProgressMonitor monitor) throws CoreException { fRjs.assignData(expression, data, null, monitor); } public void downloadFile(final OutputStream out, final String fileName, final int options, final IProgressMonitor monitor) throws CoreException { fRjs.downloadFile(out, fileName, options, monitor); } public byte[] downloadFile(final String fileName, final int options, final IProgressMonitor monitor) throws CoreException { return fRjs.downloadFile(fileName, options, monitor); } public void uploadFile(final InputStream in, final long length, final String fileName, final int options, final IProgressMonitor monitor) throws CoreException { fRjs.uploadFile(in, length, fileName, options, monitor); } public FunctionCall createFunctionCall(final String name) throws CoreException { return new FunctionCallImpl(fRjs, name, fRObjectFactory); } public RGraphicCreator createRGraphicCreator(final int options) throws CoreException { return new RGraphicCreatorImpl(this, fRjs, options); } public void addCancelHandler(final Callable<Boolean> handler) { fRjs.addCancelHandler(handler); } public void removeCancelHandler(final Callable<Boolean> handler) { fRjs.removeCancelHandler(handler); } public Lock getWaitLock() { return fRjs.getWaitLock(); } public void waitingForUser(final IProgressMonitor monitor) { fRjs.waitingForUser(); } public void resume() { fRjs.resume(); } }
true
true
protected void startToolL(final IProgressMonitor monitor) throws CoreException { fRjsId = RjsComConfig.registerClientComHandler(fRjs); fRjs.initClient(getTool(), this, fRjsProperties, fRjsId); try { final Map<String, Object> data = new HashMap<String, Object>(); final IToolEventHandler loginHandler = getEventHandler(IToolEventHandler.LOGIN_REQUEST_EVENT_ID); String msg = null; boolean connected = false; while (!connected) { final Map<String, Object> initData = getInitData(); final ServerLogin login = fRjsConnection.getServer().createLogin(Server.C_CONSOLE_CONNECT); try { final Callback[] callbacks = login.getCallbacks(); if (callbacks != null) { final List<Callback> checked = new ArrayList<Callback>(); FxCallback fx = null; for (final Callback callback : callbacks) { if (callback instanceof FxCallback) { fx = (FxCallback) callback; } else { checked.add(callback); } } if (initData != null) { data.putAll(initData); } data.put(LOGIN_ADDRESS_DATA_KEY, (fx != null) ? fAddress.getHost() : fAddress.getAddress()); data.put(LOGIN_MESSAGE_DATA_KEY, msg); data.put(LOGIN_CALLBACKS_DATA_KEY, checked.toArray(new Callback[checked.size()])); if (loginHandler == null) { throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, "Login requested but not supported by this configuration.", null )); } if (!loginHandler.handle(IToolEventHandler.LOGIN_REQUEST_EVENT_ID, this, data, monitor).isOK()) { throw new CoreException(Status.CANCEL_STATUS); } if (fx != null) { RjsUtil.handleFxCallback(RjsUtil.getSession(data, new SubProgressMonitor(monitor, 1)), fx, new SubProgressMonitor(monitor, 1)); } } msg = null; if (monitor.isCanceled()) { throw new CoreException(Status.CANCEL_STATUS); } final Map<String, Object> args = new HashMap<String, Object>(); args.putAll(fRjsProperties); ConsoleEngine rjServer; if (fStartup) { args.put("args", fRArgs); //$NON-NLS-1$ rjServer = (ConsoleEngine) fRjsConnection.getServer().execute(Server.C_CONSOLE_START, args, login.createAnswer()); } else { rjServer = (ConsoleEngine) fRjsConnection.getServer().execute(Server.C_CONSOLE_CONNECT, args, login.createAnswer()); } fRjs.setServer(rjServer, 0); connected = true; if (callbacks != null) { loginHandler.handle(IToolEventHandler.LOGIN_OK_EVENT_ID, this, data, monitor); if (initData != null) { initData.put(LOGIN_USERNAME_DATA_KEY, data.get(LOGIN_USERNAME_DATA_KEY)); } } } catch (final LoginException e) { msg = e.getLocalizedMessage(); } finally { if (login != null) { login.clearData(); } } } final ServerInfo info = fRjsConnection.getServer().getInfo(); if (fWorkspaceData.isRemote()) { try { final String wd = FileUtil.toString(fWorkspaceData.toFileStore(info.getDirectory())); if (wd != null) { setStartupWD(wd); } } catch (final CoreException e) {} } else { setStartupWD(info.getDirectory()); } final long timestamp = info.getTimestamp(); if (timestamp != 0) { setStartupTimestamp(timestamp); } final List<IStatus> warnings = new ArrayList<IStatus>(); initTracks(info.getDirectory(), monitor, warnings); if (fStartup && !fStartupsRunnables.isEmpty()) { fQueue.add(fStartupsRunnables.toArray(new IToolRunnable[fStartupsRunnables.size()])); fStartupsRunnables.clear(); } if (!fStartup) { handleStatus(new Status(IStatus.INFO, RConsoleCorePlugin.PLUGIN_ID, addTimestampToMessage(RNicoMessages.R_Info_Reconnected_message, fProcess.getConnectionTimestamp()) ), monitor); } fRjs.runMainLoop(null, null, monitor); fRjs.activateConsole(); scheduleControllerRunnable(new ControllerSystemRunnable( "r/rj/start2", "Finish Initialization / Read Output") { //$NON-NLS-1$ public void run(final IToolService s, final IProgressMonitor monitor) throws CoreException { if (!fRjs.isConsoleReady()) { // R is still working fRjs.runMainLoop(null, null, monitor); } for (final IStatus status : warnings) { handleStatus(status, monitor); } } }); } catch (final RemoteException e) { throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, "The R engine could not be started.", e )); } catch (final RjException e) { throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, "An error occured when creating login data.", e )); } }
protected void startToolL(final IProgressMonitor monitor) throws CoreException { fRjsId = RjsComConfig.registerClientComHandler(fRjs); fRjs.initClient(getTool(), this, fRjsProperties, fRjsId); try { final Map<String, Object> data = new HashMap<String, Object>(); final IToolEventHandler loginHandler = getEventHandler(IToolEventHandler.LOGIN_REQUEST_EVENT_ID); String msg = null; boolean connected = false; while (!connected) { final Map<String, Object> initData = getInitData(); final ServerLogin login = fRjsConnection.getServer().createLogin(Server.C_CONSOLE_CONNECT); try { final Callback[] callbacks = login.getCallbacks(); if (callbacks != null) { final List<Callback> checked = new ArrayList<Callback>(); FxCallback fx = null; for (final Callback callback : callbacks) { if (callback instanceof FxCallback) { fx = (FxCallback) callback; } else { checked.add(callback); } } if (initData != null) { data.putAll(initData); } data.put(LOGIN_ADDRESS_DATA_KEY, (fx != null) ? fAddress.getHost() : fAddress.getAddress()); data.put(LOGIN_MESSAGE_DATA_KEY, msg); data.put(LOGIN_CALLBACKS_DATA_KEY, checked.toArray(new Callback[checked.size()])); if (loginHandler == null) { throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, "Login requested but not supported by this configuration.", null )); } if (!loginHandler.handle(IToolEventHandler.LOGIN_REQUEST_EVENT_ID, this, data, monitor).isOK()) { throw new CoreException(Status.CANCEL_STATUS); } if (fx != null) { RjsUtil.handleFxCallback(RjsUtil.getSession(data, new SubProgressMonitor(monitor, 1)), fx, new SubProgressMonitor(monitor, 1)); } } msg = null; if (monitor.isCanceled()) { throw new CoreException(Status.CANCEL_STATUS); } final Map<String, Object> args = new HashMap<String, Object>(); args.putAll(fRjsProperties); ConsoleEngine rjServer; if (fStartup) { args.put("args", fRArgs); //$NON-NLS-1$ rjServer = (ConsoleEngine) fRjsConnection.getServer().execute(Server.C_CONSOLE_START, args, login.createAnswer()); } else { rjServer = (ConsoleEngine) fRjsConnection.getServer().execute(Server.C_CONSOLE_CONNECT, args, login.createAnswer()); } fRjs.setServer(rjServer, 0); connected = true; if (callbacks != null) { loginHandler.handle(IToolEventHandler.LOGIN_OK_EVENT_ID, this, data, monitor); if (initData != null) { initData.put(LOGIN_USERNAME_DATA_KEY, data.get(LOGIN_USERNAME_DATA_KEY)); } } } catch (final LoginException e) { msg = e.getLocalizedMessage(); } finally { if (login != null) { login.clearData(); } } } final ServerInfo info = fRjsConnection.getServer().getInfo(); if (fWorkspaceData.isRemote()) { try { final String wd = FileUtil.toString(fWorkspaceData.toFileStore(info.getDirectory())); if (wd != null) { setStartupWD(wd); } } catch (final CoreException e) {} } else { setStartupWD(info.getDirectory()); } final long timestamp = info.getTimestamp(); if (timestamp != 0) { setStartupTimestamp(timestamp); } final List<IStatus> warnings = new ArrayList<IStatus>(); initTracks(info.getDirectory(), monitor, warnings); if (fStartup && !fStartupsRunnables.isEmpty()) { fQueue.add(fStartupsRunnables.toArray(new IToolRunnable[fStartupsRunnables.size()])); fStartupsRunnables.clear(); } if (!fStartup) { handleStatus(new Status(IStatus.INFO, RConsoleCorePlugin.PLUGIN_ID, addTimestampToMessage(RNicoMessages.R_Info_Reconnected_message, fProcess.getConnectionTimestamp()) ), monitor); } // fRjs.runMainLoop(null, null, monitor); must not wait at server side fRjs.activateConsole(); scheduleControllerRunnable(new ControllerSystemRunnable( "r/rj/start2", "Finish Initialization / Read Output") { //$NON-NLS-1$ public void run(final IToolService s, final IProgressMonitor monitor) throws CoreException { if (!fRjs.isConsoleReady()) { // R is still working fRjs.runMainLoop(null, null, monitor); } for (final IStatus status : warnings) { handleStatus(status, monitor); } } }); } catch (final RemoteException e) { throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, "The R engine could not be started.", e )); } catch (final RjException e) { throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, "An error occured when creating login data.", e )); } }
diff --git a/Essentials/src/com/earth2me/essentials/yaml/ConfigLoader.java b/Essentials/src/com/earth2me/essentials/yaml/ConfigLoader.java index a8254606..7058a501 100644 --- a/Essentials/src/com/earth2me/essentials/yaml/ConfigLoader.java +++ b/Essentials/src/com/earth2me/essentials/yaml/ConfigLoader.java @@ -1,12 +1,12 @@ package com.earth2me.essentials.yaml; public class ConfigLoader { public ConfigLoader() { - new Settings().getTest(); + new Settings(); } }
true
true
public ConfigLoader() { new Settings().getTest(); }
public ConfigLoader() { new Settings(); }
diff --git a/org.eclipse.gmf.runtime.draw2d.ui.render.awt/src/org/eclipse/gmf/runtime/draw2d/ui/render/awt/internal/graphics/GraphicsToGraphics2DAdaptor.java b/org.eclipse.gmf.runtime.draw2d.ui.render.awt/src/org/eclipse/gmf/runtime/draw2d/ui/render/awt/internal/graphics/GraphicsToGraphics2DAdaptor.java index e52b3ceb..99c74516 100644 --- a/org.eclipse.gmf.runtime.draw2d.ui.render.awt/src/org/eclipse/gmf/runtime/draw2d/ui/render/awt/internal/graphics/GraphicsToGraphics2DAdaptor.java +++ b/org.eclipse.gmf.runtime.draw2d.ui.render.awt/src/org/eclipse/gmf/runtime/draw2d/ui/render/awt/internal/graphics/GraphicsToGraphics2DAdaptor.java @@ -1,1580 +1,1579 @@ /****************************************************************************** * Copyright (c) 2004, 2014 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.gmf.runtime.draw2d.ui.render.awt.internal.graphics; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Composite; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Polygon; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.geom.AffineTransform; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.util.Stack; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.SWTGraphics; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.PointList; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.gmf.runtime.common.ui.util.DisplayUtils; import org.eclipse.gmf.runtime.draw2d.ui.mapmode.MapModeTypes; import org.eclipse.gmf.runtime.draw2d.ui.render.RenderInfo; import org.eclipse.gmf.runtime.draw2d.ui.render.RenderedImage; import org.eclipse.gmf.runtime.draw2d.ui.render.awt.internal.image.ImageConverter; import org.eclipse.gmf.runtime.draw2d.ui.render.awt.internal.svg.metafile.GdiFont; import org.eclipse.gmf.runtime.draw2d.ui.render.internal.DrawableRenderedImage; import org.eclipse.gmf.runtime.draw2d.ui.render.internal.RenderingListener; import org.eclipse.gmf.runtime.draw2d.ui.text.TextUtilitiesEx; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.FontMetrics; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.LineAttributes; import org.eclipse.swt.graphics.Path; import org.eclipse.swt.graphics.PathData; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.TextLayout; /** * Objects of this class can be used with draw2d to render to a Graphics2D object. * * @author jschofie / sshaw */ public class GraphicsToGraphics2DAdaptor extends Graphics implements DrawableRenderedImage { private static class State { /** * translateX */ public int translateX = 0; /** * translateY */ public int translateY = 0; /** * clipping rectangle x coordinate */ public int clipX = 0; /** * clipping rectangle y coordinate */ public int clipY = 0; /** * clipping rectangle width */ public int clipW = 0; /** * clipping rectangle height */ public int clipH = 0; /** Font value **/ /** * cached font */ public Font font; /** * cached xor mode value */ public boolean XorMode = false; /** * cached foreground color */ public Color fgColor; /** * cached background color */ public Color bgColor; /** * cached alpha value */ public int alpha; /** * Line attributes value */ public LineAttributes lineAttributes = new LineAttributes(1); int graphicHints; /** * Copy the values from a given state to this state * * @param state * the state to copy from */ public void copyFrom(State state) { translateX = state.translateX; translateY = state.translateY; clipX = state.clipX; clipY = state.clipY; clipW = state.clipW; clipH = state.clipH; font = state.font; fgColor = state.fgColor; bgColor = state.bgColor; XorMode = state.XorMode; alpha = state.alpha; graphicHints = state.graphicHints; lineAttributes = SWTGraphics.clone(state.lineAttributes); } } static final int ADVANCED_GRAPHICS_MASK; static final int ADVANCED_SHIFT; static final int FILL_RULE_MASK; static final int FILL_RULE_SHIFT; static final int FILL_RULE_WHOLE_NUMBER = -1; /* * It's consistent with SWTGraphics flags in case some other flags from SWTGraphics need to be here */ static { FILL_RULE_SHIFT = 14; ADVANCED_SHIFT = 15; FILL_RULE_MASK = 1 << FILL_RULE_SHIFT; //If changed to more than 1-bit, check references! ADVANCED_GRAPHICS_MASK = 1 << ADVANCED_SHIFT; } private SWTGraphics swtGraphics; private Graphics2D graphics2D; private BasicStroke stroke; private Stack<State> states = new Stack<State>(); private final State currentState = new State(); private final State appliedState = new State(); /** * Some strings, Asian string in particular, are painted differently between * SWT and AWT. SWT falls back to some default locale font if Asian string * cannot be painted with the current font - this is done via the platform. * AWT, unlike platform biased SWT, does not. Hence, Asian string widths are * very different between SWT and AWT. To workaround the issue, if the flag * below is set to <code>true</code> then once SWT and AWT string width are * not equal, a bitmap of the SWT string will be painted. Otherwise the * string is always painted with AWT Graphics 2D string rendering. */ protected boolean paintNotCompatibleStringsAsBitmaps = true; private static final TextUtilitiesEx TEXT_UTILITIES = new TextUtilitiesEx(MapModeTypes.IDENTITY_MM); private Rectangle relativeClipRegion; private org.eclipse.swt.graphics.Rectangle viewBox; private Image image; /** * x coordinate for graphics translation */ private int transX = 0; /** * y coordinate for graphics translation */ private int transY = 0; /** * Constructor * * @param graphics the <code>Graphics2D</code> object that this object is delegating * calls to. * @param viewPort the <code>Rectangle</code> that defines the logical area being rendered * by the graphics object. */ public GraphicsToGraphics2DAdaptor( Graphics2D graphics, Rectangle viewPort ) { this( graphics, new org.eclipse.swt.graphics.Rectangle( viewPort.x, viewPort.y, viewPort.width, viewPort.height) ); } /** * Alternate Constructor that takes an swt Rectangle * * @param graphics the <code>Graphics2D</code> object that this object is delegating * calls to. * @param viewPort the <code>org.eclipse.swt.graphics.Rectangle</code> that defines the logical area * being rendered by the graphics object. */ public GraphicsToGraphics2DAdaptor(Graphics2D graphics, org.eclipse.swt.graphics.Rectangle viewPort) { // Save the ViewPort to add to the root DOM element viewBox = viewPort; // Create the SWT Graphics Object createSWTGraphics(); // Initialize the SVG Graphics Object initSVGGraphics(graphics); // Initialize the States init(); } /** * This is a helper method used to create the SWT Graphics object */ private void createSWTGraphics() { //we need this temp Rect just to instantiate an swt image in order to keep //state, the size of this Rect is of no consequence and we just set it to //such a small size in order to minimize memory allocation org.eclipse.swt.graphics.Rectangle tempRect = new org.eclipse.swt.graphics.Rectangle(0, 0, 10, 10); image = new Image(DisplayUtils.getDisplay(), tempRect); GC gc = new GC(image); swtGraphics = new SWTGraphics(gc); } /** * Create the SVG graphics object and initializes it with the current line * stlye and width */ private void initSVGGraphics(Graphics2D graphics) { this.graphics2D = graphics; relativeClipRegion = new Rectangle(viewBox.x, viewBox.y, viewBox.width, viewBox.height); // Initialize the line style and width stroke = new BasicStroke( swtGraphics.getLineWidth(), BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 0, null, 0); LineAttributes lineAttributes = new LineAttributes(1); swtGraphics.getLineAttributes(lineAttributes); setLineAttributes(lineAttributes); setFillRule(swtGraphics.getFillRule()); setAdvanced(swtGraphics.getAdvanced()); getGraphics2D().setStroke(stroke); } /** * This method should only be called by the constructor. Initializes state * information for the currentState */ private void init() { // Initialize drawing styles setForegroundColor(getForegroundColor()); setBackgroundColor(getBackgroundColor()); setXORMode(getXORMode()); // Initialize Font setFont(getFont()); currentState.font = appliedState.font = getFont(); // Initialize translations currentState.translateX = appliedState.translateX = transX; currentState.translateY = appliedState.translateY = transY; // Initialize Clip Regions currentState.clipX = appliedState.clipX = relativeClipRegion.x; currentState.clipY = appliedState.clipY = relativeClipRegion.y; currentState.clipW = appliedState.clipW = relativeClipRegion.width; currentState.clipH = appliedState.clipH = relativeClipRegion.height; currentState.alpha = appliedState.alpha = getAlpha(); } /** * Verifies that the applied state is up to date with the current state and updates * the applied state accordingly. */ protected void checkState() { if( appliedState.font != currentState.font ) { appliedState.font = currentState.font; setFont(currentState.font); } if (appliedState.clipX != currentState.clipX || appliedState.clipY != currentState.clipY || appliedState.clipW != currentState.clipW || appliedState.clipH != currentState.clipH) { appliedState.clipX = currentState.clipX; appliedState.clipY = currentState.clipY; appliedState.clipW = currentState.clipW; appliedState.clipH = currentState.clipH; // Adjust the clip for SVG getGraphics2D().setClip( currentState.clipX - 1, currentState.clipY - 1, currentState.clipW + 2, currentState.clipH + 2); } if( appliedState.alpha != currentState.alpha ) { appliedState.alpha = currentState.alpha; setAlpha(currentState.alpha); } appliedState.graphicHints = currentState.graphicHints; } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#clipRect(org.eclipse.draw2d.geometry.Rectangle) */ public void clipRect(Rectangle rect) { relativeClipRegion.intersect(rect); setClipAbsolute( relativeClipRegion.x + transX, relativeClipRegion.y + transY, relativeClipRegion.width, relativeClipRegion.height); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#dispose() */ public void dispose() { swtGraphics.dispose(); if (image != null) { image.dispose(); } states.clear(); } /** * This method is used to convert an SWT Color to an AWT Color. * * @param toConvert * SWT Color to convert * @return AWT Color */ protected java.awt.Color getColor(Color toConvert) { return new java.awt.Color( toConvert.getRed(), toConvert.getGreen(), toConvert.getBlue()); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#drawArc(int, int, int, int, int, int) */ public void drawArc( int x, int y, int width, int height, int startAngle, int endAngle) { Arc2D arc = new Arc2D.Float( x + transX, y + transY, width - 1, height, startAngle, endAngle, Arc2D.OPEN); checkState(); getGraphics2D().setPaint(getColor(swtGraphics.getForegroundColor())); getGraphics2D().setStroke(createStroke()); getGraphics2D().draw(arc); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#fillArc(int, int, int, int, int, int) */ public void fillArc(int x, int y, int w, int h, int offset, int length) { Arc2D arc = new Arc2D.Float( x + transX, y + transY, w, h, offset, length, Arc2D.OPEN); checkState(); getGraphics2D().setPaint(getColor(swtGraphics.getBackgroundColor())); getGraphics2D().fill(arc); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#drawFocus(int, int, int, int) */ public void drawFocus(int x, int y, int w, int h) { drawRectangle(x, y, w, h); } @Override public void drawTextLayout(TextLayout layout, int x, int y, int selectionStart, int selectionEnd, Color selectionForeground, Color selectionBackground) { checkState(); if (!layout.getBounds().isEmpty()) { Image image = new Image(DisplayUtils.getDisplay(), layout.getBounds().width, layout.getBounds().height); GC gc = new GC(image); cloneGC(gc); layout.draw(gc, 0, 0, selectionStart, selectionEnd, selectionForeground, selectionBackground); ImageData imageData = image.getImageData(); imageData.transparentPixel = imageData.palette.getPixel(getBackgroundColor().getRGB()); gc.dispose(); image.dispose(); getGraphics2D().drawImage(ImageConverter.convertFromImageData(imageData), x + transX, y + transY, null); } } private void cloneGC(GC gc) { gc.setAdvanced(getAdvanced()); gc.setAlpha(getAlpha()); gc.setAntialias(getAntialias()); gc.setFillRule(getFillRule()); gc.setFont(getFont()); gc.setInterpolation(getInterpolation()); gc.setLineAttributes(getLineAttributes()); gc.setTextAntialias(getTextAntialias()); gc.setBackground(getBackgroundColor()); gc.setForeground(getForegroundColor()); } @Override public int getInterpolation() { return swtGraphics.getInterpolation(); } @Override public LineAttributes getLineAttributes() { LineAttributes la = new LineAttributes(1); swtGraphics.getLineAttributes(la); return la; } @Override public int getTextAntialias() { return swtGraphics.getTextAntialias(); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#drawImage(org.eclipse.swt.graphics.Image, * int, int) */ public void drawImage(Image srcImage, int xpos, int ypos) { // Translate the Coordinates xpos += transX; ypos += transY; // Convert the SWT Image into an AWT BufferedImage BufferedImage toDraw = ImageConverter.convert(srcImage); checkState(); getGraphics2D().drawImage( toDraw, new AffineTransform(1f, 0f, 0f, 1f, xpos, ypos), null); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#drawImage(org.eclipse.swt.graphics.Image, * int, int, int, int, int, int, int, int) */ public void drawImage( Image srcImage, int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2) { x2 += transX; y2 += transY; BufferedImage toDraw = ImageConverter.convert(srcImage); checkState(); getGraphics2D().drawImage(toDraw, x2, y2, w2, h2, null); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#drawLine(int, int, int, int) */ public void drawLine(int x1, int y1, int x2, int y2) { Line2D line = new Line2D.Float( x1 + transX, y1 + transY, x2 + transX, y2 + transY); checkState(); getGraphics2D().setPaint(getColor(swtGraphics.getForegroundColor())); getGraphics2D().setStroke(createStroke()); getGraphics2D().draw(line); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#drawOval(int, int, int, int) */ public void drawOval(int x, int y, int w, int h) { Ellipse2D ellipse = new Ellipse2D.Float(x + transX, y + transY, w, h); checkState(); getGraphics2D().setPaint(getColor(swtGraphics.getForegroundColor())); getGraphics2D().setStroke(createStroke()); getGraphics2D().draw(ellipse); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#fillOval(int, int, int, int) */ public void fillOval(int x, int y, int w, int h) { Ellipse2D ellipse = new Ellipse2D.Float(x + transX, y + transY, w-1, h-1); checkState(); getGraphics2D().setPaint(getColor(swtGraphics.getBackgroundColor())); getGraphics2D().fill(ellipse); } private Polygon createPolygon(PointList pointList) { Polygon toCreate = new Polygon(); for (int i = 0; i < pointList.size(); i++) { Point pt = pointList.getPoint(i); toCreate.addPoint(pt.x + transX, pt.y + transY); } return toCreate; } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#drawPolygon(org.eclipse.draw2d.geometry.PointList) */ public void drawPolygon(PointList pointList) { checkState(); getGraphics2D().setPaint(getColor(swtGraphics.getForegroundColor())); getGraphics2D().setStroke(createStroke()); getGraphics2D().draw(createPolygon(pointList)); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#fillPolygon(org.eclipse.draw2d.geometry.PointList) */ public void fillPolygon(PointList pointList) { checkState(); getGraphics2D().setPaint(getColor(swtGraphics.getBackgroundColor())); getGraphics2D().fill(createPolygon(pointList)); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#drawPolyline(org.eclipse.draw2d.geometry.PointList) */ public void drawPolyline(PointList pointList) { // Draw polylines as a series of lines for (int x = 1; x < pointList.size(); x++) { Point p1 = pointList.getPoint(x - 1); Point p2 = pointList.getPoint(x); drawLine(p1.x, p1.y, p2.x, p2.y); } } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#drawRectangle(int, int, int, int) */ public void drawRectangle(int x, int y, int w, int h) { Rectangle2D rect = new Rectangle2D.Float(x + transX, y + transY, w, h); checkState(); getGraphics2D().setPaint(getColor(swtGraphics.getForegroundColor())); getGraphics2D().setStroke(createStroke()); getGraphics2D().draw(rect); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#fillRectangle(int, int, int, int) */ public void fillRectangle(int x, int y, int width, int height) { Rectangle2D rect = new Rectangle2D.Float( x + transX, y + transY, width, height); checkState(); getGraphics2D().setPaint(getColor(swtGraphics.getBackgroundColor())); getGraphics2D().fill(rect); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#drawRoundRectangle(org.eclipse.draw2d.geometry.Rectangle, * int, int) */ public void drawRoundRectangle( Rectangle rect, int arcWidth, int arcHeight) { RoundRectangle2D roundRect = new RoundRectangle2D.Float( rect.x + transX, rect.y + transY, rect.width, rect.height, arcWidth, arcHeight); checkState(); getGraphics2D().setPaint(getColor(swtGraphics.getForegroundColor())); getGraphics2D().setStroke(createStroke()); getGraphics2D().draw(roundRect); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#fillRoundRectangle(org.eclipse.draw2d.geometry.Rectangle, * int, int) */ public void fillRoundRectangle( Rectangle rect, int arcWidth, int arcHeight) { RoundRectangle2D roundRect = new RoundRectangle2D.Float( rect.x + transX, rect.y + transY, rect.width, rect.height, arcWidth, arcHeight); checkState(); getGraphics2D().setPaint(getColor(swtGraphics.getBackgroundColor())); getGraphics2D().fill(roundRect); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#drawText(java.lang.String, int, int) */ public void drawText(String s, int x, int y) { drawString(s, x, y); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#drawString(java.lang.String, int, int) */ public void drawString(String s, int x, int y) { if (s == null || s.length() == 0) return; java.awt.FontMetrics metrics = getGraphics2D().getFontMetrics(); int stringLength = metrics.stringWidth(s); Dimension swtStringSize = TEXT_UTILITIES.getStringExtents(s, swtGraphics.getFont()); float xpos = x + transX; float ypos = y + transY; int lineWidth; - if (paintNotCompatibleStringsAsBitmaps && - ( (getGraphics2D().getFont().canDisplayUpTo(s) != -1) || ( Math.abs(swtStringSize.width - stringLength) > 2) ) ) { + if (paintNotCompatibleStringsAsBitmaps && (getGraphics2D().getFont().canDisplayUpTo(s) != -1)) { // create SWT bitmap of the string then Image image = new Image(DisplayUtils.getDisplay(), swtStringSize.width, swtStringSize.height); GC gc = new GC(image); gc.setForeground(getForegroundColor()); gc.setBackground(getBackgroundColor()); gc.setAntialias(getAntialias()); gc.setFont(getFont()); gc.drawString(s, 0, 0); gc.dispose(); ImageData data = image.getImageData(); image.dispose(); RGB backgroundRGB = getBackgroundColor().getRGB(); for (int i = 0; i < data.width; i++) { for (int j = 0; j < data.height; j++) { if (data.palette.getRGB(data.getPixel(i, j)).equals( backgroundRGB)) { data.setAlpha(i, j, 0); } else { data.setAlpha(i, j, 255); } } } checkState(); getGraphics2D().drawImage( ImageConverter.convertFromImageData(data), new AffineTransform(1f, 0f, 0f, 1f, xpos, ypos), null); stringLength = swtStringSize.width; } else { ypos += metrics.getAscent(); checkState(); getGraphics2D() .setPaint(getColor(swtGraphics.getForegroundColor())); getGraphics2D().drawString(s, xpos, ypos); } if (isFontUnderlined(getFont())) { int baseline = y + metrics.getAscent(); lineWidth = getLineWidth(); setLineWidth(1); drawLine(x, baseline, x + stringLength, baseline); setLineWidth(lineWidth); } if (isFontStrikeout(getFont())) { int strikeline = y + (metrics.getHeight() / 2); lineWidth = getLineWidth(); setLineWidth(1); drawLine(x, strikeline, x + stringLength, strikeline); setLineWidth(lineWidth); } } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#fillString(java.lang.String, int, int) */ public void fillString(String s, int x, int y) { // Not implemented } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#fillText(java.lang.String, int, int) */ public void fillText(String s, int x, int y) { // Not implemented } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#getBackgroundColor() */ public Color getBackgroundColor() { return swtGraphics.getBackgroundColor(); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#getClip(org.eclipse.draw2d.geometry.Rectangle) */ public Rectangle getClip(Rectangle rect) { rect.setBounds(relativeClipRegion); return rect; } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#getFont() */ public Font getFont() { return swtGraphics.getFont(); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#getFontMetrics() */ public FontMetrics getFontMetrics() { return swtGraphics.getFontMetrics(); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#getForegroundColor() */ public Color getForegroundColor() { return swtGraphics.getForegroundColor(); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#getLineStyle() */ public int getLineStyle() { return swtGraphics.getLineStyle(); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#getLineWidth() */ public int getLineWidth() { return swtGraphics.getLineWidth(); } public float getLineWidthFloat() { return swtGraphics.getLineWidthFloat(); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#getXORMode() */ public boolean getXORMode() { return swtGraphics.getXORMode(); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#popState() */ public void popState() { swtGraphics.popState(); restoreState(states.pop()); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#pushState() */ public void pushState() { swtGraphics.pushState(); // Make a copy of the current state and push it onto the stack State toPush = new State(); toPush.copyFrom(currentState); states.push(toPush); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#restoreState() */ public void restoreState() { swtGraphics.restoreState(); restoreState(states.peek()); } private void restoreState(State state) { setBackgroundColor(state.bgColor); setForegroundColor(state.fgColor); setLineAttributes(state.lineAttributes); setXORMode(state.XorMode); setClipAbsolute(state.clipX, state.clipY, state.clipW, state.clipH); transX = currentState.translateX = state.translateX; transY = currentState.translateY = state.translateY; relativeClipRegion.x = state.clipX - transX; relativeClipRegion.y = state.clipY - transY; relativeClipRegion.width = state.clipW; relativeClipRegion.height = state.clipH; currentState.font = state.font; currentState.alpha = state.alpha; } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#scale(double) */ public void scale(double amount) { swtGraphics.scale(amount); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#setBackgroundColor(org.eclipse.swt.graphics.Color) */ public void setBackgroundColor(Color rgb) { currentState.bgColor = rgb; swtGraphics.setBackgroundColor(rgb); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#setClip(org.eclipse.draw2d.geometry.Rectangle) */ public void setClip(Rectangle rect) { relativeClipRegion.x = rect.x; relativeClipRegion.y = rect.y; relativeClipRegion.width = rect.width; relativeClipRegion.height = rect.height; setClipAbsolute( rect.x + transX, rect.y + transY, rect.width, rect.height); } /** * Sets the current clip values * * @param x * the x value * @param y * the y value * @param width * the width value * @param height * the height value */ private void setClipAbsolute(int x, int y, int width, int height) { currentState.clipX = x; currentState.clipY = y; currentState.clipW = width; currentState.clipH = height; } private boolean isFontUnderlined(Font f) { return false; } private boolean isFontStrikeout(Font f) { return false; } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#setFont(org.eclipse.swt.graphics.Font) */ @Override public void setFont(Font f) { swtGraphics.setFont(f); currentState.font = f; FontData[] fontInfo = f.getFontData(); if (fontInfo[0] != null) { int height = fontInfo[0].getHeight(); float fsize = (float) height * (float) DisplayUtils.getDisplay().getDPI().x / 72.0f; height = Math.round(fsize); int style = fontInfo[0].getStyle(); boolean bItalic = (style & SWT.ITALIC) == SWT.ITALIC; boolean bBold = (style & SWT.BOLD) == SWT.BOLD; String faceName = fontInfo[0].getName(); int escapement = 0; boolean bUnderline = isFontUnderlined(f); boolean bStrikeout = isFontStrikeout(f); GdiFont font = new GdiFont( height, bItalic, bUnderline, bStrikeout, bBold, faceName, escapement); getGraphics2D().setFont(font.getFont()); } } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#setForegroundColor(org.eclipse.swt.graphics.Color) */ @Override public void setForegroundColor(Color rgb) { currentState.fgColor = rgb; swtGraphics.setForegroundColor(rgb); } /** * Sets the dash pattern when the custom line style is in use. Because this * feature is rarely used, the dash pattern may not be preserved when calling * {@link #pushState()} and {@link #popState()}. * @param dash the pixel pattern * */ @Override public void setLineDash(int[] dash) { float dashFlt[] = new float[dash.length]; for (int i=0; i<dash.length; i++) { dashFlt[i] = dash[i]; } setLineDash(dashFlt); } @Override public void setLineDash(float[] dash) { currentState.lineAttributes.dash = dash; setLineStyle(SWTGraphics.LINE_CUSTOM); swtGraphics.setLineDash(dash); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#setLineStyle(int) */ @Override public void setLineStyle(int style) { currentState.lineAttributes.style = style; swtGraphics.setLineStyle(style); } /** * ignored */ @Override public void setLineMiterLimit(float miterLimit) { // do nothing } /** * ignored */ @Override public void setLineCap(int cap) { // do nothing } /** * ignored */ @Override public void setLineJoin(int join) { // do nothing } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#setLineWidth(int) */ @Override public void setLineWidth(int width) { setLineWidthFloat(width); } @Override public void setLineWidthFloat(float width) { currentState.lineAttributes.width = width; swtGraphics.setLineWidthFloat(width); } @Override public void setLineAttributes(LineAttributes lineAttributes) { SWTGraphics.copyLineAttributes(currentState.lineAttributes, lineAttributes); swtGraphics.setLineAttributes(lineAttributes); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Graphics#setXORMode(boolean) */ @Override public void setXORMode(boolean xorMode) { currentState.XorMode = xorMode; swtGraphics.setXORMode(xorMode); } /** * Sets the current translation values * * @param x * the x translation value * @param y * the y translation value */ private void setTranslation(int x, int y) { transX = currentState.translateX = x; transY = currentState.translateY = y; } /* * (non-Javadoc) * @see org.eclipse.draw2d.Graphics#translate(int, int) */ @Override public void translate(int dx, int dy) { swtGraphics.translate(dx, dy); setTranslation(transX + dx, transY + dy); relativeClipRegion.x -= dx; relativeClipRegion.y -= dy; } /** * @return the <code>Graphics2D</code> that this is delegating to. */ protected Graphics2D getGraphics2D() { return graphics2D; } /** * @return Returns the swtGraphics. */ private SWTGraphics getSWTGraphics() { return swtGraphics; } /* * (non-Javadoc) * @see org.eclipse.draw2d.Graphics#fillGradient(int, int, int, int, boolean) */ @Override public void fillGradient(int x, int y, int w, int h, boolean vertical) { GradientPaint gradient; checkState(); // Gradients in SWT start with Foreground Color and end at Background java.awt.Color start = getColor( getSWTGraphics().getForegroundColor() ); java.awt.Color stop = getColor( getSWTGraphics().getBackgroundColor() ); // Create the Gradient based on horizontal or vertical if( vertical ) { gradient = new GradientPaint(x+transX,y+transY, start, x+transX, y+h+transY, stop); } else { gradient = new GradientPaint(x+transX,y+transY, start, x+w+transX, y+transY, stop); } Paint oldPaint = getGraphics2D().getPaint(); getGraphics2D().setPaint(gradient); getGraphics2D().fill(new Rectangle2D.Double(x+transX, y+transY, w, h)); getGraphics2D().setPaint(oldPaint); } /* (non-Javadoc) * @see org.eclipse.draw2d.Graphics#drawPath(org.eclipse.swt.graphics.Path) */ public void drawPath(Path path) { checkState(); getGraphics2D().setPaint(getColor(swtGraphics.getForegroundColor())); getGraphics2D().setStroke(createStroke()); getGraphics2D().draw(createPathAWT(path)); } /* (non-Javadoc) * @see org.eclipse.draw2d.Graphics#fillPath(org.eclipse.swt.graphics.Path) */ public void fillPath(Path path) { checkState(); getGraphics2D().setPaint(getColor(swtGraphics.getBackgroundColor())); getGraphics2D().fill(createPathAWT(path)); } /* (non-Javadoc) * @see org.eclipse.draw2d.Graphics#setClip(org.eclipse.swt.graphics.Path) */ public void setClip(Path path) { if (((appliedState.graphicHints ^ currentState.graphicHints) & FILL_RULE_MASK) != 0) { //If there is a pending change to the fill rule, apply it first. //As long as the FILL_RULE is stored in a single bit, just toggling it works. appliedState.graphicHints ^= FILL_RULE_MASK; } getGraphics2D().setClip(createPathAWT(path)); appliedState.clipX = currentState.clipX = 0; appliedState.clipY = currentState.clipY = 0; appliedState.clipW = currentState.clipW = 0; appliedState.clipH = currentState.clipH = 0; } /* (non-Javadoc) * @see org.eclipse.draw2d.Graphics#getFillRule() */ public int getFillRule() { return ((currentState.graphicHints & FILL_RULE_MASK) >> FILL_RULE_SHIFT) - FILL_RULE_WHOLE_NUMBER; } /* (non-Javadoc) * @see org.eclipse.draw2d.Graphics#setFillRule(int) */ public void setFillRule(int rule) { currentState.graphicHints &= ~FILL_RULE_MASK; currentState.graphicHints |= (rule + FILL_RULE_WHOLE_NUMBER) << FILL_RULE_SHIFT; } private GeneralPath createPathAWT(Path path) { GeneralPath pathAWT = new GeneralPath(); PathData pathData = path.getPathData(); int idx = 0; for (int i = 0; i < pathData.types.length; i++) { switch (pathData.types[i]) { case SWT.PATH_MOVE_TO: pathAWT.moveTo(pathData.points[idx++] + transX, pathData.points[idx++] + transY); break; case SWT.PATH_LINE_TO: pathAWT.lineTo(pathData.points[idx++] + transX, pathData.points[idx++] + transY); break; case SWT.PATH_CUBIC_TO: pathAWT.curveTo(pathData.points[idx++] + transX, pathData.points[idx++] + transY, pathData.points[idx++] + transX, pathData.points[idx++] + transY, pathData.points[idx++] + transX, pathData.points[idx++] + transY); break; case SWT.PATH_QUAD_TO: pathAWT.quadTo(pathData.points[idx++] + transX, pathData.points[idx++] + transY, pathData.points[idx++] + transX, pathData.points[idx++] + transY); break; case SWT.PATH_CLOSE: pathAWT.closePath(); break; default: dispose(); SWT.error(SWT.ERROR_INVALID_ARGUMENT); } } int swtWindingRule = ((appliedState.graphicHints & FILL_RULE_MASK) >> FILL_RULE_SHIFT) - FILL_RULE_WHOLE_NUMBER; if (swtWindingRule == SWT.FILL_WINDING) { pathAWT.setWindingRule(GeneralPath.WIND_NON_ZERO); } else if (swtWindingRule == SWT.FILL_EVEN_ODD) { pathAWT.setWindingRule(GeneralPath.WIND_EVEN_ODD); } else { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } return pathAWT; } /* (non-Javadoc) * @see org.eclipse.gmf.runtime.draw2d.ui.render.awt.internal.DrawableRenderedImage#drawRenderedImage(org.eclipse.gmf.runtime.draw2d.ui.render.RenderedImage, org.eclipse.draw2d.geometry.Rectangle, org.eclipse.gmf.runtime.draw2d.ui.render.RenderingListener) */ public RenderedImage drawRenderedImage(RenderedImage srcImage, Rectangle rect, RenderingListener listener) { RenderInfo info = srcImage.getRenderInfo(); info.setValues(rect.width, rect.height, info.shouldMaintainAspectRatio(), info.shouldAntiAlias(), info.getBackgroundColor(), info.getForegroundColor()); RenderedImage img = srcImage.getNewRenderedImage(info); BufferedImage bufImg = (BufferedImage)img.getAdapter(BufferedImage.class); if (bufImg == null) { bufImg = ImageConverter.convert(img.getSWTImage()); } // Translate the Coordinates int x = rect.x + transX; int y = rect.y + transY + rect.height - bufImg.getHeight(); checkState(); getGraphics2D().drawImage( bufImg, new AffineTransform(1f, 0f, 0f, 1f, x, y), null); return img; } /* * (non-Javadoc) * @see org.eclipse.gmf.runtime.draw2d.ui.render.awt.internal.DrawableRenderedImage#allowDelayRender() */ public boolean shouldAllowDelayRender() { return false; } /* (non-Javadoc) * @see org.eclipse.gmf.runtime.draw2d.ui.render.awt.internal.DrawableRenderedImage#getMaximumRenderSize() */ public Dimension getMaximumRenderSize() { return null; } /** * Accessor method to return the translation offset for the graphics object * * @return <code>Point</code> x coordinate for graphics translation */ protected Point getTranslationOffset() { return new Point(transX, transY); } /* * (non-Javadoc) * @see org.eclipse.draw2d.Graphics#getAntialias() */ @Override public int getAntialias() { Object antiAlias = getGraphics2D().getRenderingHint(RenderingHints.KEY_ANTIALIASING); if (antiAlias != null) { if (antiAlias.equals(RenderingHints.VALUE_ANTIALIAS_ON)) return SWT.ON; else if (antiAlias.equals(RenderingHints.VALUE_ANTIALIAS_OFF)) return SWT.OFF; else if (antiAlias.equals(RenderingHints.VALUE_ANTIALIAS_DEFAULT)) return SWT.DEFAULT; } return SWT.DEFAULT; } /* * (non-Javadoc) * @see org.eclipse.draw2d.Graphics#setAntialias(int) */ @Override public void setAntialias(int value) { if (value == SWT.ON) { getGraphics2D().setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } else if (value == SWT.OFF) { getGraphics2D().setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } setAdvanced(true); } @Override public int getAlpha() { return swtGraphics.getAlpha(); } @Override public void setAlpha(int alpha) { swtGraphics.setAlpha(alpha); currentState.alpha = alpha; Composite composite = getGraphics2D().getComposite(); if (composite instanceof AlphaComposite) { AlphaComposite newComposite = AlphaComposite.getInstance( ((AlphaComposite) composite).getRule(), (float) alpha / (float) 255); getGraphics2D().setComposite(newComposite); } } protected BasicStroke getStroke(){ return stroke; } protected void setStroke(BasicStroke stroke){ this.stroke = stroke; getGraphics2D().setStroke(stroke); } /** * Sets and retirns AWT Stroke based on the value of * <code>LineAttributes</code> within the current state object * * @return the new AWT stroke */ private Stroke createStroke() { float factor = currentState.lineAttributes.width > 0 ? currentState.lineAttributes.width : 3; float awt_dash[]; int awt_cap; int awt_join; switch (currentState.lineAttributes.style) { case SWTGraphics.LINE_DASH : awt_dash = new float[]{ factor * 6, factor * 3 }; break; case SWTGraphics.LINE_DASHDOT : awt_dash = new float[] { factor * 3, factor, factor, factor }; break; case SWTGraphics.LINE_DASHDOTDOT : awt_dash = new float[] { factor * 3, factor, factor, factor, factor, factor }; break; case SWTGraphics.LINE_DOT : awt_dash = new float[] { factor, factor }; break; case SWTGraphics.LINE_CUSTOM : awt_dash = currentState.lineAttributes.dash; break; default : awt_dash = null; } switch (currentState.lineAttributes.cap) { case SWT.CAP_FLAT: awt_cap = BasicStroke.CAP_BUTT; break; case SWT.CAP_ROUND: awt_cap = BasicStroke.CAP_ROUND; break; case SWT.CAP_SQUARE: awt_cap = BasicStroke.CAP_SQUARE; break; default: awt_cap = BasicStroke.CAP_BUTT; } switch (currentState.lineAttributes.join) { case SWT.JOIN_BEVEL: awt_join = BasicStroke.JOIN_BEVEL; break; case SWT.JOIN_MITER: awt_join = BasicStroke.JOIN_MITER; break; case SWT.JOIN_ROUND: awt_join = BasicStroke.JOIN_ROUND; break; default: awt_join = BasicStroke.JOIN_MITER; } /* * SWT paints line width == 0 as if it is == 1, so AWT is synced up with that below. */ stroke = new BasicStroke( currentState.lineAttributes.width != 0 ? currentState.lineAttributes.width : 1, awt_cap, awt_join, currentState.lineAttributes.miterLimit, awt_dash, currentState.lineAttributes.dashOffset); return stroke; } public boolean getAdvanced() { return (currentState.graphicHints & ADVANCED_GRAPHICS_MASK) != 0; } public void setAdvanced(boolean value) { if(value) { currentState.graphicHints |= ADVANCED_GRAPHICS_MASK; } else { currentState.graphicHints &= ~ADVANCED_GRAPHICS_MASK; } } @Override public void clipPath(Path path) { if (((appliedState.graphicHints ^ currentState.graphicHints) & FILL_RULE_MASK) != 0) { //If there is a pending change to the fill rule, apply it first. //As long as the FILL_RULE is stored in a single bit, just toggling it works. appliedState.graphicHints ^= FILL_RULE_MASK; } setClip(path); getGraphics2D().clipRect(relativeClipRegion.x + transX, relativeClipRegion.y + transY, relativeClipRegion.width, relativeClipRegion.height); java.awt.Rectangle bounds = getGraphics2D().getClip().getBounds(); relativeClipRegion = new Rectangle(bounds.x, bounds.y, bounds.width, bounds.height); } }
true
true
public void drawString(String s, int x, int y) { if (s == null || s.length() == 0) return; java.awt.FontMetrics metrics = getGraphics2D().getFontMetrics(); int stringLength = metrics.stringWidth(s); Dimension swtStringSize = TEXT_UTILITIES.getStringExtents(s, swtGraphics.getFont()); float xpos = x + transX; float ypos = y + transY; int lineWidth; if (paintNotCompatibleStringsAsBitmaps && ( (getGraphics2D().getFont().canDisplayUpTo(s) != -1) || ( Math.abs(swtStringSize.width - stringLength) > 2) ) ) { // create SWT bitmap of the string then Image image = new Image(DisplayUtils.getDisplay(), swtStringSize.width, swtStringSize.height); GC gc = new GC(image); gc.setForeground(getForegroundColor()); gc.setBackground(getBackgroundColor()); gc.setAntialias(getAntialias()); gc.setFont(getFont()); gc.drawString(s, 0, 0); gc.dispose(); ImageData data = image.getImageData(); image.dispose(); RGB backgroundRGB = getBackgroundColor().getRGB(); for (int i = 0; i < data.width; i++) { for (int j = 0; j < data.height; j++) { if (data.palette.getRGB(data.getPixel(i, j)).equals( backgroundRGB)) { data.setAlpha(i, j, 0); } else { data.setAlpha(i, j, 255); } } } checkState(); getGraphics2D().drawImage( ImageConverter.convertFromImageData(data), new AffineTransform(1f, 0f, 0f, 1f, xpos, ypos), null); stringLength = swtStringSize.width; } else { ypos += metrics.getAscent(); checkState(); getGraphics2D() .setPaint(getColor(swtGraphics.getForegroundColor())); getGraphics2D().drawString(s, xpos, ypos); } if (isFontUnderlined(getFont())) { int baseline = y + metrics.getAscent(); lineWidth = getLineWidth(); setLineWidth(1); drawLine(x, baseline, x + stringLength, baseline); setLineWidth(lineWidth); } if (isFontStrikeout(getFont())) { int strikeline = y + (metrics.getHeight() / 2); lineWidth = getLineWidth(); setLineWidth(1); drawLine(x, strikeline, x + stringLength, strikeline); setLineWidth(lineWidth); } }
public void drawString(String s, int x, int y) { if (s == null || s.length() == 0) return; java.awt.FontMetrics metrics = getGraphics2D().getFontMetrics(); int stringLength = metrics.stringWidth(s); Dimension swtStringSize = TEXT_UTILITIES.getStringExtents(s, swtGraphics.getFont()); float xpos = x + transX; float ypos = y + transY; int lineWidth; if (paintNotCompatibleStringsAsBitmaps && (getGraphics2D().getFont().canDisplayUpTo(s) != -1)) { // create SWT bitmap of the string then Image image = new Image(DisplayUtils.getDisplay(), swtStringSize.width, swtStringSize.height); GC gc = new GC(image); gc.setForeground(getForegroundColor()); gc.setBackground(getBackgroundColor()); gc.setAntialias(getAntialias()); gc.setFont(getFont()); gc.drawString(s, 0, 0); gc.dispose(); ImageData data = image.getImageData(); image.dispose(); RGB backgroundRGB = getBackgroundColor().getRGB(); for (int i = 0; i < data.width; i++) { for (int j = 0; j < data.height; j++) { if (data.palette.getRGB(data.getPixel(i, j)).equals( backgroundRGB)) { data.setAlpha(i, j, 0); } else { data.setAlpha(i, j, 255); } } } checkState(); getGraphics2D().drawImage( ImageConverter.convertFromImageData(data), new AffineTransform(1f, 0f, 0f, 1f, xpos, ypos), null); stringLength = swtStringSize.width; } else { ypos += metrics.getAscent(); checkState(); getGraphics2D() .setPaint(getColor(swtGraphics.getForegroundColor())); getGraphics2D().drawString(s, xpos, ypos); } if (isFontUnderlined(getFont())) { int baseline = y + metrics.getAscent(); lineWidth = getLineWidth(); setLineWidth(1); drawLine(x, baseline, x + stringLength, baseline); setLineWidth(lineWidth); } if (isFontStrikeout(getFont())) { int strikeline = y + (metrics.getHeight() / 2); lineWidth = getLineWidth(); setLineWidth(1); drawLine(x, strikeline, x + stringLength, strikeline); setLineWidth(lineWidth); } }
diff --git a/apps/routerconsole/java/src/net/i2p/router/web/GraphHelper.java b/apps/routerconsole/java/src/net/i2p/router/web/GraphHelper.java index e9c603c89..4a96f6d6f 100644 --- a/apps/routerconsole/java/src/net/i2p/router/web/GraphHelper.java +++ b/apps/routerconsole/java/src/net/i2p/router/web/GraphHelper.java @@ -1,153 +1,154 @@ package net.i2p.router.web; import java.io.IOException; import java.io.Writer; import java.util.*; import net.i2p.data.DataHelper; import net.i2p.stat.Rate; import net.i2p.router.RouterContext; public class GraphHelper { private RouterContext _context; private Writer _out; private int _periodCount; private boolean _showEvents; private int _width; private int _height; private int _refreshDelaySeconds; /** * Configure this bean to query a particular router context * * @param contextId begging few characters of the routerHash, or null to pick * the first one we come across. */ public void setContextId(String contextId) { try { _context = ContextHelper.getContext(contextId); } catch (Throwable t) { t.printStackTrace(); } } public GraphHelper() { _periodCount = 60; // SummaryListener.PERIODS; _showEvents = false; _width = 250; _height = 100; _refreshDelaySeconds = 60; } public void setOut(Writer out) { _out = out; } public void setPeriodCount(String str) { try { _periodCount = Integer.parseInt(str); } catch (NumberFormatException nfe) {} } public void setShowEvents(boolean b) { _showEvents = b; } public void setHeight(String str) { try { _height = Integer.parseInt(str); } catch (NumberFormatException nfe) {} } public void setWidth(String str) { try { _width = Integer.parseInt(str); } catch (NumberFormatException nfe) {} } public void setRefreshDelay(String str) { try { _refreshDelaySeconds = Integer.parseInt(str); } catch (NumberFormatException nfe) {} } public String getImages() { try { List listeners = StatSummarizer.instance().getListeners(); TreeSet ordered = new TreeSet(new AlphaComparator()); ordered.addAll(listeners); // go to some trouble to see if we have the data for the combined bw graph boolean hasTx = false; boolean hasRx = false; for (Iterator iter = ordered.iterator(); iter.hasNext(); ) { SummaryListener lsnr = (SummaryListener)iter.next(); String title = lsnr.getRate().getRateStat().getName(); if (title.equals("bw.sendRate")) hasTx = true; else if (title.equals("bw.recvRate")) hasRx = true; } - if (hasTx && hasRx && !_showEvents) + if (hasTx && hasRx && !_showEvents) { _out.write("<a href=\"viewstat.jsp?stat=bw.combined" + "&amp;periodCount=" + (3 * _periodCount ) + "&amp;width=" + (3 * _width) + "&amp;height=" + (3 * _height) + "\" />"); _out.write("<img width=\"" + (_width + 83) + "\" height=\"" + (_height + 92) + "\" src=\"viewstat.jsp?stat=bw.combined" + "&amp;periodCount=" + _periodCount + "&amp;width=" + _width + "&amp;height=" + (_height - 14) + "\" title=\"Combined bandwidth graph\" /></a>\n"); + } for (Iterator iter = ordered.iterator(); iter.hasNext(); ) { SummaryListener lsnr = (SummaryListener)iter.next(); Rate r = lsnr.getRate(); String title = r.getRateStat().getName() + " for " + DataHelper.formatDuration(_periodCount * r.getPeriod()); _out.write("<a href=\"viewstat.jsp?stat=" + r.getRateStat().getName() + "&amp;showEvents=" + _showEvents + "&amp;period=" + r.getPeriod() + "&amp;periodCount=" + (3 * _periodCount) + "&amp;width=" + (3 * _width) + "&amp;height=" + (3 * _height) + "\" />"); _out.write("<img border=\"0\" width=\"" + (_width + 83) + "\" height=\"" + (_height + 92) + "\" src=\"viewstat.jsp?stat=" + r.getRateStat().getName() + "&amp;showEvents=" + _showEvents + "&amp;period=" + r.getPeriod() + "&amp;periodCount=" + _periodCount + "&amp;width=" + _width + "&amp;height=" + _height + "\" title=\"" + title + "\" /></a>\n"); } if (_refreshDelaySeconds > 0) _out.write("<meta http-equiv=\"refresh\" content=\"" + _refreshDelaySeconds + "\" />\n"); } catch (IOException ioe) { ioe.printStackTrace(); } return ""; } public String getForm() { try { _out.write("<p /><a href=\"configstats.jsp\">Select Stats to Graph</a><p />"); _out.write("<form action=\"graphs.jsp\" method=\"GET\">"); _out.write("Periods: <input size=\"3\" type=\"text\" name=\"periodCount\" value=\"" + _periodCount + "\" /><br />\n"); _out.write("Plot averages: <input type=\"radio\" name=\"showEvents\" value=\"false\" " + (_showEvents ? "" : "checked=\"true\" ") + " /> "); _out.write("or plot events: <input type=\"radio\" name=\"showEvents\" value=\"true\" "+ (_showEvents ? "checked=\"true\" " : "") + " /><br />\n"); _out.write("Image sizes: width: <input size=\"4\" type=\"text\" name=\"width\" value=\"" + _width + "\" /> pixels, height: <input size=\"4\" type=\"text\" name=\"height\" value=\"" + _height + "\" /><br />\n"); _out.write("Refresh delay: <select name=\"refreshDelay\"><option value=\"60\">1 minute</option><option value=\"120\">2 minutes</option><option value=\"300\">5 minutes</option><option value=\"600\">10 minutes</option><option value=\"-1\">Never</option></select><br />\n"); _out.write("<input type=\"submit\" value=\"Redraw\" />"); } catch (IOException ioe) { ioe.printStackTrace(); } return ""; } public String getPeerSummary() { try { _context.commSystem().renderStatusHTML(_out); _context.bandwidthLimiter().renderStatusHTML(_out); } catch (IOException ioe) { ioe.printStackTrace(); } return ""; } } class AlphaComparator implements Comparator { public int compare(Object lhs, Object rhs) { SummaryListener l = (SummaryListener)lhs; SummaryListener r = (SummaryListener)rhs; String lName = l.getRate().getRateStat().getName() + "." + l.getRate().getPeriod(); String rName = r.getRate().getRateStat().getName() + "." + r.getRate().getPeriod(); return lName.compareTo(rName); } }
false
true
public String getImages() { try { List listeners = StatSummarizer.instance().getListeners(); TreeSet ordered = new TreeSet(new AlphaComparator()); ordered.addAll(listeners); // go to some trouble to see if we have the data for the combined bw graph boolean hasTx = false; boolean hasRx = false; for (Iterator iter = ordered.iterator(); iter.hasNext(); ) { SummaryListener lsnr = (SummaryListener)iter.next(); String title = lsnr.getRate().getRateStat().getName(); if (title.equals("bw.sendRate")) hasTx = true; else if (title.equals("bw.recvRate")) hasRx = true; } if (hasTx && hasRx && !_showEvents) _out.write("<a href=\"viewstat.jsp?stat=bw.combined" + "&amp;periodCount=" + (3 * _periodCount ) + "&amp;width=" + (3 * _width) + "&amp;height=" + (3 * _height) + "\" />"); _out.write("<img width=\"" + (_width + 83) + "\" height=\"" + (_height + 92) + "\" src=\"viewstat.jsp?stat=bw.combined" + "&amp;periodCount=" + _periodCount + "&amp;width=" + _width + "&amp;height=" + (_height - 14) + "\" title=\"Combined bandwidth graph\" /></a>\n"); for (Iterator iter = ordered.iterator(); iter.hasNext(); ) { SummaryListener lsnr = (SummaryListener)iter.next(); Rate r = lsnr.getRate(); String title = r.getRateStat().getName() + " for " + DataHelper.formatDuration(_periodCount * r.getPeriod()); _out.write("<a href=\"viewstat.jsp?stat=" + r.getRateStat().getName() + "&amp;showEvents=" + _showEvents + "&amp;period=" + r.getPeriod() + "&amp;periodCount=" + (3 * _periodCount) + "&amp;width=" + (3 * _width) + "&amp;height=" + (3 * _height) + "\" />"); _out.write("<img border=\"0\" width=\"" + (_width + 83) + "\" height=\"" + (_height + 92) + "\" src=\"viewstat.jsp?stat=" + r.getRateStat().getName() + "&amp;showEvents=" + _showEvents + "&amp;period=" + r.getPeriod() + "&amp;periodCount=" + _periodCount + "&amp;width=" + _width + "&amp;height=" + _height + "\" title=\"" + title + "\" /></a>\n"); } if (_refreshDelaySeconds > 0) _out.write("<meta http-equiv=\"refresh\" content=\"" + _refreshDelaySeconds + "\" />\n"); } catch (IOException ioe) { ioe.printStackTrace(); } return ""; }
public String getImages() { try { List listeners = StatSummarizer.instance().getListeners(); TreeSet ordered = new TreeSet(new AlphaComparator()); ordered.addAll(listeners); // go to some trouble to see if we have the data for the combined bw graph boolean hasTx = false; boolean hasRx = false; for (Iterator iter = ordered.iterator(); iter.hasNext(); ) { SummaryListener lsnr = (SummaryListener)iter.next(); String title = lsnr.getRate().getRateStat().getName(); if (title.equals("bw.sendRate")) hasTx = true; else if (title.equals("bw.recvRate")) hasRx = true; } if (hasTx && hasRx && !_showEvents) { _out.write("<a href=\"viewstat.jsp?stat=bw.combined" + "&amp;periodCount=" + (3 * _periodCount ) + "&amp;width=" + (3 * _width) + "&amp;height=" + (3 * _height) + "\" />"); _out.write("<img width=\"" + (_width + 83) + "\" height=\"" + (_height + 92) + "\" src=\"viewstat.jsp?stat=bw.combined" + "&amp;periodCount=" + _periodCount + "&amp;width=" + _width + "&amp;height=" + (_height - 14) + "\" title=\"Combined bandwidth graph\" /></a>\n"); } for (Iterator iter = ordered.iterator(); iter.hasNext(); ) { SummaryListener lsnr = (SummaryListener)iter.next(); Rate r = lsnr.getRate(); String title = r.getRateStat().getName() + " for " + DataHelper.formatDuration(_periodCount * r.getPeriod()); _out.write("<a href=\"viewstat.jsp?stat=" + r.getRateStat().getName() + "&amp;showEvents=" + _showEvents + "&amp;period=" + r.getPeriod() + "&amp;periodCount=" + (3 * _periodCount) + "&amp;width=" + (3 * _width) + "&amp;height=" + (3 * _height) + "\" />"); _out.write("<img border=\"0\" width=\"" + (_width + 83) + "\" height=\"" + (_height + 92) + "\" src=\"viewstat.jsp?stat=" + r.getRateStat().getName() + "&amp;showEvents=" + _showEvents + "&amp;period=" + r.getPeriod() + "&amp;periodCount=" + _periodCount + "&amp;width=" + _width + "&amp;height=" + _height + "\" title=\"" + title + "\" /></a>\n"); } if (_refreshDelaySeconds > 0) _out.write("<meta http-equiv=\"refresh\" content=\"" + _refreshDelaySeconds + "\" />\n"); } catch (IOException ioe) { ioe.printStackTrace(); } return ""; }
diff --git a/parser/org/eclipse/cdt/core/dom/parser/cpp/GPPScannerExtensionConfiguration.java b/parser/org/eclipse/cdt/core/dom/parser/cpp/GPPScannerExtensionConfiguration.java index 20b1f4412..d3f8db547 100644 --- a/parser/org/eclipse/cdt/core/dom/parser/cpp/GPPScannerExtensionConfiguration.java +++ b/parser/org/eclipse/cdt/core/dom/parser/cpp/GPPScannerExtensionConfiguration.java @@ -1,48 +1,47 @@ /******************************************************************************* * Copyright (c) 2004, 2008 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 - Initial API and implementation * Ed Swartz (Nokia) * Anton Leherbauer (Wind River Systems) * Markus Schorn (Wind River Systems) * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.core.dom.parser.cpp; import org.eclipse.cdt.core.dom.parser.GNUScannerExtensionConfiguration; import org.eclipse.cdt.core.parser.IToken; import org.eclipse.cdt.core.parser.Keywords; /** * Configures the preprocessor for c++-sources as accepted by g++. */ public class GPPScannerExtensionConfiguration extends GNUScannerExtensionConfiguration { private static GPPScannerExtensionConfiguration sInstance= new GPPScannerExtensionConfiguration(); /** * @since 5.1 */ public static GPPScannerExtensionConfiguration getInstance() { return sInstance; } public GPPScannerExtensionConfiguration() { addMacro("__null", "0"); //$NON-NLS-1$//$NON-NLS-2$ - addKeyword(Keywords.cRESTRICT, IToken.t_restrict); addKeyword(Keywords.c_COMPLEX, IToken.t__Complex); addKeyword(Keywords.c_IMAGINARY, IToken.t__Imaginary); } /* (non-Javadoc) * @see org.eclipse.cdt.internal.core.parser.scanner2.IScannerConfiguration#supportMinAndMaxOperators() */ @Override public boolean supportMinAndMaxOperators() { return true; } }
true
true
public GPPScannerExtensionConfiguration() { addMacro("__null", "0"); //$NON-NLS-1$//$NON-NLS-2$ addKeyword(Keywords.cRESTRICT, IToken.t_restrict); addKeyword(Keywords.c_COMPLEX, IToken.t__Complex); addKeyword(Keywords.c_IMAGINARY, IToken.t__Imaginary); }
public GPPScannerExtensionConfiguration() { addMacro("__null", "0"); //$NON-NLS-1$//$NON-NLS-2$ addKeyword(Keywords.c_COMPLEX, IToken.t__Complex); addKeyword(Keywords.c_IMAGINARY, IToken.t__Imaginary); }
diff --git a/HC_Loopsassignment.java b/HC_Loopsassignment.java index c030bf6..7c223df 100644 --- a/HC_Loopsassignment.java +++ b/HC_Loopsassignment.java @@ -1,138 +1,137 @@ import java.util.Arrays; import java.util.Collections; import javax.swing.JOptionPane; public class HC_Loopsassignment { /** *@author HunterCaron * Mr.Marco * ICS 3U1 * If StatmentsAssingment 5 */ public static void main(String[] args) { while(true) { //input and conversion int choice = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter the question number: (0 to quit)", "Loop Assigment", JOptionPane.QUESTION_MESSAGE)); //switch statement switch (choice) { case 0: System.exit(0); break; case 1: for (int i = 1; i <= 16; i+=3) System.out.println(i); break; case 2: for (int i = 20; i >= 5; i-=5) System.out.println(i); break; case 3: for (int i = 1; i <= 500; i++){ System.out.print("*");} System.out.println(); break; case 4: int astrix = Integer.parseInt(JOptionPane.showInputDialog("Enter the amount of astrixes you want to print")); for (int i = 1; i <= astrix; i++) System.out.print("*"); System.out.println(); break; case 5: int odd = Integer.parseInt(JOptionPane.showInputDialog("Enter the max number")); for (int i = 1; i <= odd; i+=2) System.out.println(i); break; case 7: int amount = 0; float total = 0; do { float value = Float.parseFloat(JOptionPane.showInputDialog("Enter a number, -1 to find the average")); total += value; amount++; System.out.println("The sum so far is: " + total + "\n#'s so far = " + amount); if (value == -1) { System.out.println("The average is: " + total/amount); break; } } while (true); break; case 8: for (char ch = 'Z' ;ch >= 'A' ; ch--) System.out.println(ch); for (char ch = 'z' ;ch >= 'a' ; ch--) System.out.println(ch); break; case 9: char letter = 'a'; String UorL = null, VCorD = null; do { String letterinput = JOptionPane.showInputDialog("Enter a letter: (* to exit)"); String lwcase = letterinput.toLowerCase(); char letterLW = lwcase.charAt(0); letter = letterinput.charAt(0); if (letter == letterLW) { UorL = "lowercase"; if (letter == '1' || letter == '2' || letter == '3' || letter == '4' || letter == '5' || letter == '6' || letter == '7' || letter == '8' || letter == '9' || letter == '0') UorL = "Neither upper or lower case because:"; } else UorL = "uppercase"; if (letterLW == 'a' || letterLW == 'e' || letterLW == 'i' || letterLW == 'o' || letterLW == 'u') VCorD = "Vowel"; else if (letter == '1' || letter == '2' || letter == '3' || letter == '4' || letter == '5' || letterLW == '6' || letter == '7' || letter == '8' || letter == '9') VCorD = "Digit"; else VCorD = "Consonant"; JOptionPane.showMessageDialog(null, "Your character is " + UorL + "\nYour character is a " + VCorD); } while (letter != '*'); break; case 10: double x = 0; double denominator = 2; for (int i = 2; i <= 20; i++) { x = 1/denominator; System.out.println(x); denominator++; } break; case 11: int int1 = 0; do { int1 = Integer.parseInt(JOptionPane.showInputDialog("Enter integer 1 (-1 to exit)")); int int2 = Integer.parseInt(JOptionPane.showInputDialog("Enter integer 2")); int int3 = Integer.parseInt(JOptionPane.showInputDialog("Enter integer 3")); int maxVal = Collections.max(Arrays.asList(int1, int2, int3)); System.out.println("The max value is: " + maxVal); } while (int1 != 0); break; case 12: int digit = 0; int sum = 0; int input = 0; do { - input = Integer.parseInt(JOptionPane.showInputDialog("Enter an integer (-1 to exit)")); - do { - digit = input%10; - int calc = input/10; - } - while (digit != 0); + input = JOptionPane.showInputDialog("Enter an integer (type exit to exit)"); + do { + digit = input.charAt(0); sum += digit; - System.out.println("Sum so far is: " + sum); + i++; + } + while (digit == '1' || digit == '2' || digit == '3' || digit == '4' || digit == '5' || digit == '6' || digit == '7' || digit == '8' || digit == '9' || digit == '0'); System.out.println("The sum of the digits is: " + sum); } - while (input != 1); + while (input != "exit"); } } } }
false
true
public static void main(String[] args) { while(true) { //input and conversion int choice = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter the question number: (0 to quit)", "Loop Assigment", JOptionPane.QUESTION_MESSAGE)); //switch statement switch (choice) { case 0: System.exit(0); break; case 1: for (int i = 1; i <= 16; i+=3) System.out.println(i); break; case 2: for (int i = 20; i >= 5; i-=5) System.out.println(i); break; case 3: for (int i = 1; i <= 500; i++){ System.out.print("*");} System.out.println(); break; case 4: int astrix = Integer.parseInt(JOptionPane.showInputDialog("Enter the amount of astrixes you want to print")); for (int i = 1; i <= astrix; i++) System.out.print("*"); System.out.println(); break; case 5: int odd = Integer.parseInt(JOptionPane.showInputDialog("Enter the max number")); for (int i = 1; i <= odd; i+=2) System.out.println(i); break; case 7: int amount = 0; float total = 0; do { float value = Float.parseFloat(JOptionPane.showInputDialog("Enter a number, -1 to find the average")); total += value; amount++; System.out.println("The sum so far is: " + total + "\n#'s so far = " + amount); if (value == -1) { System.out.println("The average is: " + total/amount); break; } } while (true); break; case 8: for (char ch = 'Z' ;ch >= 'A' ; ch--) System.out.println(ch); for (char ch = 'z' ;ch >= 'a' ; ch--) System.out.println(ch); break; case 9: char letter = 'a'; String UorL = null, VCorD = null; do { String letterinput = JOptionPane.showInputDialog("Enter a letter: (* to exit)"); String lwcase = letterinput.toLowerCase(); char letterLW = lwcase.charAt(0); letter = letterinput.charAt(0); if (letter == letterLW) { UorL = "lowercase"; if (letter == '1' || letter == '2' || letter == '3' || letter == '4' || letter == '5' || letter == '6' || letter == '7' || letter == '8' || letter == '9' || letter == '0') UorL = "Neither upper or lower case because:"; } else UorL = "uppercase"; if (letterLW == 'a' || letterLW == 'e' || letterLW == 'i' || letterLW == 'o' || letterLW == 'u') VCorD = "Vowel"; else if (letter == '1' || letter == '2' || letter == '3' || letter == '4' || letter == '5' || letterLW == '6' || letter == '7' || letter == '8' || letter == '9') VCorD = "Digit"; else VCorD = "Consonant"; JOptionPane.showMessageDialog(null, "Your character is " + UorL + "\nYour character is a " + VCorD); } while (letter != '*'); break; case 10: double x = 0; double denominator = 2; for (int i = 2; i <= 20; i++) { x = 1/denominator; System.out.println(x); denominator++; } break; case 11: int int1 = 0; do { int1 = Integer.parseInt(JOptionPane.showInputDialog("Enter integer 1 (-1 to exit)")); int int2 = Integer.parseInt(JOptionPane.showInputDialog("Enter integer 2")); int int3 = Integer.parseInt(JOptionPane.showInputDialog("Enter integer 3")); int maxVal = Collections.max(Arrays.asList(int1, int2, int3)); System.out.println("The max value is: " + maxVal); } while (int1 != 0); break; case 12: int digit = 0; int sum = 0; int input = 0; do { input = Integer.parseInt(JOptionPane.showInputDialog("Enter an integer (-1 to exit)")); do { digit = input%10; int calc = input/10; } while (digit != 0); sum += digit; System.out.println("Sum so far is: " + sum); } while (input != 1); } } }
public static void main(String[] args) { while(true) { //input and conversion int choice = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter the question number: (0 to quit)", "Loop Assigment", JOptionPane.QUESTION_MESSAGE)); //switch statement switch (choice) { case 0: System.exit(0); break; case 1: for (int i = 1; i <= 16; i+=3) System.out.println(i); break; case 2: for (int i = 20; i >= 5; i-=5) System.out.println(i); break; case 3: for (int i = 1; i <= 500; i++){ System.out.print("*");} System.out.println(); break; case 4: int astrix = Integer.parseInt(JOptionPane.showInputDialog("Enter the amount of astrixes you want to print")); for (int i = 1; i <= astrix; i++) System.out.print("*"); System.out.println(); break; case 5: int odd = Integer.parseInt(JOptionPane.showInputDialog("Enter the max number")); for (int i = 1; i <= odd; i+=2) System.out.println(i); break; case 7: int amount = 0; float total = 0; do { float value = Float.parseFloat(JOptionPane.showInputDialog("Enter a number, -1 to find the average")); total += value; amount++; System.out.println("The sum so far is: " + total + "\n#'s so far = " + amount); if (value == -1) { System.out.println("The average is: " + total/amount); break; } } while (true); break; case 8: for (char ch = 'Z' ;ch >= 'A' ; ch--) System.out.println(ch); for (char ch = 'z' ;ch >= 'a' ; ch--) System.out.println(ch); break; case 9: char letter = 'a'; String UorL = null, VCorD = null; do { String letterinput = JOptionPane.showInputDialog("Enter a letter: (* to exit)"); String lwcase = letterinput.toLowerCase(); char letterLW = lwcase.charAt(0); letter = letterinput.charAt(0); if (letter == letterLW) { UorL = "lowercase"; if (letter == '1' || letter == '2' || letter == '3' || letter == '4' || letter == '5' || letter == '6' || letter == '7' || letter == '8' || letter == '9' || letter == '0') UorL = "Neither upper or lower case because:"; } else UorL = "uppercase"; if (letterLW == 'a' || letterLW == 'e' || letterLW == 'i' || letterLW == 'o' || letterLW == 'u') VCorD = "Vowel"; else if (letter == '1' || letter == '2' || letter == '3' || letter == '4' || letter == '5' || letterLW == '6' || letter == '7' || letter == '8' || letter == '9') VCorD = "Digit"; else VCorD = "Consonant"; JOptionPane.showMessageDialog(null, "Your character is " + UorL + "\nYour character is a " + VCorD); } while (letter != '*'); break; case 10: double x = 0; double denominator = 2; for (int i = 2; i <= 20; i++) { x = 1/denominator; System.out.println(x); denominator++; } break; case 11: int int1 = 0; do { int1 = Integer.parseInt(JOptionPane.showInputDialog("Enter integer 1 (-1 to exit)")); int int2 = Integer.parseInt(JOptionPane.showInputDialog("Enter integer 2")); int int3 = Integer.parseInt(JOptionPane.showInputDialog("Enter integer 3")); int maxVal = Collections.max(Arrays.asList(int1, int2, int3)); System.out.println("The max value is: " + maxVal); } while (int1 != 0); break; case 12: int digit = 0; int sum = 0; int input = 0; do { input = JOptionPane.showInputDialog("Enter an integer (type exit to exit)"); do { digit = input.charAt(0); sum += digit; i++; } while (digit == '1' || digit == '2' || digit == '3' || digit == '4' || digit == '5' || digit == '6' || digit == '7' || digit == '8' || digit == '9' || digit == '0'); System.out.println("The sum of the digits is: " + sum); } while (input != "exit"); } } }
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java index 6c348718a..263a0607b 100644 --- a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java +++ b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java @@ -1,261 +1,264 @@ package brooklyn.entity.brooklynnode; import static java.lang.String.format; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import brooklyn.entity.drivers.downloads.DownloadResolver; import brooklyn.entity.java.JarBuilder; import brooklyn.entity.java.JavaSoftwareProcessSshDriver; import brooklyn.location.basic.SshMachineLocation; import brooklyn.util.NetworkUtils; import brooklyn.util.ResourceUtils; import brooklyn.util.collections.MutableMap; import brooklyn.util.ssh.CommonCommands; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; public class BrooklynNodeSshDriver extends JavaSoftwareProcessSshDriver implements BrooklynNodeDriver { private String expandedInstallDir; public BrooklynNodeSshDriver(BrooklynNodeImpl entity, SshMachineLocation machine) { super(entity, machine); } @Override public BrooklynNodeImpl getEntity() { return (BrooklynNodeImpl) super.getEntity(); } public String getBrooklynHome() { return getInstallDir()+"/brooklyn-"+getVersion(); } @Override protected String getLogFileLocation() { return format("%s/console", getRunDir()); } private String getPidFile() { return "pid_java"; } protected String getExpandedInstallDir() { if (expandedInstallDir == null) throw new IllegalStateException("expandedInstallDir is null; most likely install was not called"); return expandedInstallDir; } @Override public void install() { String uploadUrl = entity.getConfig(BrooklynNode.DISTRO_UPLOAD_URL); DownloadResolver resolver = entity.getManagementContext().getEntityDownloadsManager().newDownloader(this); List<String> urls = resolver.getTargets(); String saveAs = resolver.getFilename(); expandedInstallDir = getInstallDir()+"/"+resolver.getUnpackedDirectoryName(format("brooklyn-%s", getVersion())); newScript("createInstallDir") .body.append("mkdir -p "+getInstallDir()) .failOnNonZeroResultCode() .execute(); List<String> commands = Lists.newArrayList(); if (uploadUrl != null) { // Only upload if not already installed boolean exists = newScript("checkIfInstalled") .body.append("cd "+getInstallDir(), "test -f BROOKLYN") .execute() == 0; if (!exists) { InputStream distroStream = new ResourceUtils(entity).getResourceFromUrl(uploadUrl); getMachine().copyTo(distroStream, getInstallDir()+"/"+saveAs); } } else { commands.addAll(CommonCommands.downloadUrlAs(urls, saveAs)); } commands.add(CommonCommands.INSTALL_TAR); commands.add("tar xzfv " + saveAs); newScript(INSTALLING). failOnNonZeroResultCode(). body.append(commands).execute(); } @Override public void customize() { newScript(CUSTOMIZING) .failOnNonZeroResultCode() .body.append( format("cp -R %s/brooklyn-%s/{bin,conf} .", getInstallDir(), getVersion()), "mkdir -p ./lib/") .execute(); SshMachineLocation machine = getMachine(); BrooklynNode entity = getEntity(); String brooklynPropertiesTempRemotePath = String.format("%s/brooklyn.properties", getRunDir()); String brooklynPropertiesRemotePath = entity.getConfig(BrooklynNode.BROOKLYN_PROPERTIES_REMOTE_PATH); String brooklynPropertiesContents = entity.getConfig(BrooklynNode.BROOKLYN_PROPERTIES_CONTENTS); String brooklynPropertiesUri = entity.getConfig(BrooklynNode.BROOKLYN_PROPERTIES_URI); // Override the ~/.brooklyn/brooklyn.properties if required if (brooklynPropertiesContents != null || brooklynPropertiesUri != null) { if (brooklynPropertiesContents != null) { machine.copyTo(new ByteArrayInputStream(brooklynPropertiesContents.getBytes()), brooklynPropertiesTempRemotePath); } else if (brooklynPropertiesUri != null) { InputStream propertiesStream = new ResourceUtils(entity).getResourceFromUrl(brooklynPropertiesUri); machine.copyTo(propertiesStream, brooklynPropertiesTempRemotePath); } newScript(CUSTOMIZING) - .body.append(format("cp -p %s %s", brooklynPropertiesTempRemotePath, brooklynPropertiesRemotePath)) + .failOnNonZeroResultCode() + .body.append( + format("mkdir -p %s", brooklynPropertiesRemotePath.subSequence(0, brooklynPropertiesRemotePath.lastIndexOf("/"))), + format("cp -p %s %s", brooklynPropertiesTempRemotePath, brooklynPropertiesRemotePath)) .execute(); } String brooklynCatalogTempRemotePath = String.format("%s/catalog.xml", getRunDir()); String brooklynCatalogRemotePath = entity.getConfig(BrooklynNode.BROOKLYN_CATALOG_REMOTE_PATH); String brooklynCatalogContents = entity.getConfig(BrooklynNode.BROOKLYN_CATALOG_CONTENTS); String brooklynCatalogUri = entity.getConfig(BrooklynNode.BROOKLYN_CATALOG_URI); // Override the ~/.brooklyn/catalog.xml if required if (brooklynCatalogContents != null || brooklynCatalogUri != null) { if (brooklynCatalogContents != null) { machine.copyTo(new ByteArrayInputStream(brooklynCatalogContents.getBytes()), brooklynCatalogTempRemotePath); } else if (brooklynCatalogUri != null) { InputStream catalogStream = new ResourceUtils(entity).getResourceFromUrl(brooklynCatalogUri); machine.copyTo(catalogStream, brooklynCatalogTempRemotePath); } newScript(CUSTOMIZING) .body.append(format("cp -p %s %s", brooklynCatalogTempRemotePath, brooklynCatalogRemotePath)) .execute(); } // Copy additional resources to the server for (Map.Entry<String,String> entry : getEntity().getAttribute(BrooklynNode.COPY_TO_RUNDIR).entrySet()) { Map<String, String> substitutions = ImmutableMap.of("RUN", getRunDir()); String localResource = entry.getKey(); String remotePath = entry.getValue(); String resolvedRemotePath = remotePath; for (Map.Entry<String,String> substitution : substitutions.entrySet()) { String key = substitution.getKey(); String val = substitution.getValue(); resolvedRemotePath = resolvedRemotePath.replace("${"+key+"}", val).replace("$"+key, val); } machine.copyTo(MutableMap.of("permissions", "0600"), new ResourceUtils(entity).getResourceFromUrl(localResource), resolvedRemotePath); } // TODO Copied from VanillaJavaApp; share code there? Or delete this functionality from here? for (String f : getEntity().getClasspath()) { // TODO support wildcards // If a local folder, then jar it up String toinstall; if (new File(f).isDirectory()) { try { File jarFile = JarBuilder.buildJar(new File(f)); toinstall = jarFile.getAbsolutePath(); } catch (IOException e) { throw new IllegalStateException("Error jarring classpath entry, for directory "+f, e); } } else { toinstall = f; } int result = machine.installTo(new ResourceUtils(entity), toinstall, getRunDir() + "/" + "lib" + "/"); if (result != 0) throw new IllegalStateException(format("unable to install classpath entry %s for %s at %s",f,entity,machine)); // if it's a zip or tgz then expand // FIXME dedup with code in machine.installTo above String destName = f; destName = destName.contains("?") ? destName.substring(0, destName.indexOf('?')) : destName; destName = destName.substring(destName.lastIndexOf('/') + 1); if (destName.toLowerCase().endsWith(".zip")) { result = machine.run(format("cd %s/lib && unzip %s",getRunDir(),destName)); } else if (destName.toLowerCase().endsWith(".tgz") || destName.toLowerCase().endsWith(".tar.gz")) { result = machine.run(format("cd %s/lib && tar xvfz %s",getRunDir(),destName)); } else if (destName.toLowerCase().endsWith(".tar")) { result = machine.run(format("cd %s/lib && tar xvfz %s",getRunDir(),destName)); } if (result != 0) throw new IllegalStateException(format("unable to install classpath entry %s for %s at %s (failed to expand archive)",f,entity,machine)); } } @Override public void launch() { String app = getEntity().getAttribute(BrooklynNode.APP); String locations = getEntity().getAttribute(BrooklynNode.LOCATIONS); Integer httpPort = getEntity().getAttribute(BrooklynNode.HTTP_PORT); String cmd = "./bin/brooklyn launch"; if (app != null) { cmd += " --app "+app; } if (locations != null) { cmd += " --locations "+locations; } if (getEntity().isHttpProtocolEnabled("http")) { NetworkUtils.checkPortsValid(ImmutableMap.of("httpPort", httpPort)); cmd += " --port "+httpPort; } else if (getEntity().getEnabledHttpProtocols().isEmpty()) { cmd += " --noConsole"; } else { throw new IllegalStateException("Unsupported http protocol: "+getEntity().getEnabledHttpProtocols()); } if (getEntity().getAttribute(BrooklynNode.NO_WEB_CONSOLE_AUTHENTICATION)) { cmd += " --noConsoleSecurity "; } cmd += format(" >> %s/console 2>&1 </dev/null &", getRunDir()); log.info("Starting brooklyn on {} using command {}", getMachine(), cmd); // relies on brooklyn script creating pid file newScript(ImmutableMap.of("usePidFile", false), LAUNCHING). body.append( format("export BROOKLYN_CLASSPATH=%s", getRunDir()+"/lib/\"*\""), format("export BROOKLYN_HOME=%s", getBrooklynHome()), format(cmd) ).execute(); } @Override public boolean isRunning() { Map<String,String> flags = ImmutableMap.of("usePidFile", getPidFile()); int result = newScript(flags, CHECK_RUNNING).execute(); return result == 0; } @Override public void stop() { Map<String,String> flags = ImmutableMap.of("usePidFile", getPidFile()); newScript(flags, STOPPING).execute(); } @Override public void kill() { Map<String,String> flags = ImmutableMap.of("usePidFile", getPidFile()); newScript(flags, KILLING).execute(); } @Override public Map<String, String> getShellEnvironment() { Map<String, String> orig = super.getShellEnvironment(); String origClasspath = orig.get("CLASSPATH"); String newClasspath = (origClasspath == null ? "" : origClasspath+":") + getRunDir()+"/conf/" + ":" + getRunDir()+"/lib/\"*\""; Map<String,String> results = new LinkedHashMap<String,String>(); results.putAll(orig); results.put("BROOKLYN_CLASSPATH", newClasspath); results.put("BROOKLYN_HOME", getBrooklynHome()); results.put("RUN", getRunDir()); return results; } }
true
true
public void customize() { newScript(CUSTOMIZING) .failOnNonZeroResultCode() .body.append( format("cp -R %s/brooklyn-%s/{bin,conf} .", getInstallDir(), getVersion()), "mkdir -p ./lib/") .execute(); SshMachineLocation machine = getMachine(); BrooklynNode entity = getEntity(); String brooklynPropertiesTempRemotePath = String.format("%s/brooklyn.properties", getRunDir()); String brooklynPropertiesRemotePath = entity.getConfig(BrooklynNode.BROOKLYN_PROPERTIES_REMOTE_PATH); String brooklynPropertiesContents = entity.getConfig(BrooklynNode.BROOKLYN_PROPERTIES_CONTENTS); String brooklynPropertiesUri = entity.getConfig(BrooklynNode.BROOKLYN_PROPERTIES_URI); // Override the ~/.brooklyn/brooklyn.properties if required if (brooklynPropertiesContents != null || brooklynPropertiesUri != null) { if (brooklynPropertiesContents != null) { machine.copyTo(new ByteArrayInputStream(brooklynPropertiesContents.getBytes()), brooklynPropertiesTempRemotePath); } else if (brooklynPropertiesUri != null) { InputStream propertiesStream = new ResourceUtils(entity).getResourceFromUrl(brooklynPropertiesUri); machine.copyTo(propertiesStream, brooklynPropertiesTempRemotePath); } newScript(CUSTOMIZING) .body.append(format("cp -p %s %s", brooklynPropertiesTempRemotePath, brooklynPropertiesRemotePath)) .execute(); } String brooklynCatalogTempRemotePath = String.format("%s/catalog.xml", getRunDir()); String brooklynCatalogRemotePath = entity.getConfig(BrooklynNode.BROOKLYN_CATALOG_REMOTE_PATH); String brooklynCatalogContents = entity.getConfig(BrooklynNode.BROOKLYN_CATALOG_CONTENTS); String brooklynCatalogUri = entity.getConfig(BrooklynNode.BROOKLYN_CATALOG_URI); // Override the ~/.brooklyn/catalog.xml if required if (brooklynCatalogContents != null || brooklynCatalogUri != null) { if (brooklynCatalogContents != null) { machine.copyTo(new ByteArrayInputStream(brooklynCatalogContents.getBytes()), brooklynCatalogTempRemotePath); } else if (brooklynCatalogUri != null) { InputStream catalogStream = new ResourceUtils(entity).getResourceFromUrl(brooklynCatalogUri); machine.copyTo(catalogStream, brooklynCatalogTempRemotePath); } newScript(CUSTOMIZING) .body.append(format("cp -p %s %s", brooklynCatalogTempRemotePath, brooklynCatalogRemotePath)) .execute(); } // Copy additional resources to the server for (Map.Entry<String,String> entry : getEntity().getAttribute(BrooklynNode.COPY_TO_RUNDIR).entrySet()) { Map<String, String> substitutions = ImmutableMap.of("RUN", getRunDir()); String localResource = entry.getKey(); String remotePath = entry.getValue(); String resolvedRemotePath = remotePath; for (Map.Entry<String,String> substitution : substitutions.entrySet()) { String key = substitution.getKey(); String val = substitution.getValue(); resolvedRemotePath = resolvedRemotePath.replace("${"+key+"}", val).replace("$"+key, val); } machine.copyTo(MutableMap.of("permissions", "0600"), new ResourceUtils(entity).getResourceFromUrl(localResource), resolvedRemotePath); } // TODO Copied from VanillaJavaApp; share code there? Or delete this functionality from here? for (String f : getEntity().getClasspath()) { // TODO support wildcards // If a local folder, then jar it up String toinstall; if (new File(f).isDirectory()) { try { File jarFile = JarBuilder.buildJar(new File(f)); toinstall = jarFile.getAbsolutePath(); } catch (IOException e) { throw new IllegalStateException("Error jarring classpath entry, for directory "+f, e); } } else { toinstall = f; } int result = machine.installTo(new ResourceUtils(entity), toinstall, getRunDir() + "/" + "lib" + "/"); if (result != 0) throw new IllegalStateException(format("unable to install classpath entry %s for %s at %s",f,entity,machine)); // if it's a zip or tgz then expand // FIXME dedup with code in machine.installTo above String destName = f; destName = destName.contains("?") ? destName.substring(0, destName.indexOf('?')) : destName; destName = destName.substring(destName.lastIndexOf('/') + 1); if (destName.toLowerCase().endsWith(".zip")) { result = machine.run(format("cd %s/lib && unzip %s",getRunDir(),destName)); } else if (destName.toLowerCase().endsWith(".tgz") || destName.toLowerCase().endsWith(".tar.gz")) { result = machine.run(format("cd %s/lib && tar xvfz %s",getRunDir(),destName)); } else if (destName.toLowerCase().endsWith(".tar")) { result = machine.run(format("cd %s/lib && tar xvfz %s",getRunDir(),destName)); } if (result != 0) throw new IllegalStateException(format("unable to install classpath entry %s for %s at %s (failed to expand archive)",f,entity,machine)); } }
public void customize() { newScript(CUSTOMIZING) .failOnNonZeroResultCode() .body.append( format("cp -R %s/brooklyn-%s/{bin,conf} .", getInstallDir(), getVersion()), "mkdir -p ./lib/") .execute(); SshMachineLocation machine = getMachine(); BrooklynNode entity = getEntity(); String brooklynPropertiesTempRemotePath = String.format("%s/brooklyn.properties", getRunDir()); String brooklynPropertiesRemotePath = entity.getConfig(BrooklynNode.BROOKLYN_PROPERTIES_REMOTE_PATH); String brooklynPropertiesContents = entity.getConfig(BrooklynNode.BROOKLYN_PROPERTIES_CONTENTS); String brooklynPropertiesUri = entity.getConfig(BrooklynNode.BROOKLYN_PROPERTIES_URI); // Override the ~/.brooklyn/brooklyn.properties if required if (brooklynPropertiesContents != null || brooklynPropertiesUri != null) { if (brooklynPropertiesContents != null) { machine.copyTo(new ByteArrayInputStream(brooklynPropertiesContents.getBytes()), brooklynPropertiesTempRemotePath); } else if (brooklynPropertiesUri != null) { InputStream propertiesStream = new ResourceUtils(entity).getResourceFromUrl(brooklynPropertiesUri); machine.copyTo(propertiesStream, brooklynPropertiesTempRemotePath); } newScript(CUSTOMIZING) .failOnNonZeroResultCode() .body.append( format("mkdir -p %s", brooklynPropertiesRemotePath.subSequence(0, brooklynPropertiesRemotePath.lastIndexOf("/"))), format("cp -p %s %s", brooklynPropertiesTempRemotePath, brooklynPropertiesRemotePath)) .execute(); } String brooklynCatalogTempRemotePath = String.format("%s/catalog.xml", getRunDir()); String brooklynCatalogRemotePath = entity.getConfig(BrooklynNode.BROOKLYN_CATALOG_REMOTE_PATH); String brooklynCatalogContents = entity.getConfig(BrooklynNode.BROOKLYN_CATALOG_CONTENTS); String brooklynCatalogUri = entity.getConfig(BrooklynNode.BROOKLYN_CATALOG_URI); // Override the ~/.brooklyn/catalog.xml if required if (brooklynCatalogContents != null || brooklynCatalogUri != null) { if (brooklynCatalogContents != null) { machine.copyTo(new ByteArrayInputStream(brooklynCatalogContents.getBytes()), brooklynCatalogTempRemotePath); } else if (brooklynCatalogUri != null) { InputStream catalogStream = new ResourceUtils(entity).getResourceFromUrl(brooklynCatalogUri); machine.copyTo(catalogStream, brooklynCatalogTempRemotePath); } newScript(CUSTOMIZING) .body.append(format("cp -p %s %s", brooklynCatalogTempRemotePath, brooklynCatalogRemotePath)) .execute(); } // Copy additional resources to the server for (Map.Entry<String,String> entry : getEntity().getAttribute(BrooklynNode.COPY_TO_RUNDIR).entrySet()) { Map<String, String> substitutions = ImmutableMap.of("RUN", getRunDir()); String localResource = entry.getKey(); String remotePath = entry.getValue(); String resolvedRemotePath = remotePath; for (Map.Entry<String,String> substitution : substitutions.entrySet()) { String key = substitution.getKey(); String val = substitution.getValue(); resolvedRemotePath = resolvedRemotePath.replace("${"+key+"}", val).replace("$"+key, val); } machine.copyTo(MutableMap.of("permissions", "0600"), new ResourceUtils(entity).getResourceFromUrl(localResource), resolvedRemotePath); } // TODO Copied from VanillaJavaApp; share code there? Or delete this functionality from here? for (String f : getEntity().getClasspath()) { // TODO support wildcards // If a local folder, then jar it up String toinstall; if (new File(f).isDirectory()) { try { File jarFile = JarBuilder.buildJar(new File(f)); toinstall = jarFile.getAbsolutePath(); } catch (IOException e) { throw new IllegalStateException("Error jarring classpath entry, for directory "+f, e); } } else { toinstall = f; } int result = machine.installTo(new ResourceUtils(entity), toinstall, getRunDir() + "/" + "lib" + "/"); if (result != 0) throw new IllegalStateException(format("unable to install classpath entry %s for %s at %s",f,entity,machine)); // if it's a zip or tgz then expand // FIXME dedup with code in machine.installTo above String destName = f; destName = destName.contains("?") ? destName.substring(0, destName.indexOf('?')) : destName; destName = destName.substring(destName.lastIndexOf('/') + 1); if (destName.toLowerCase().endsWith(".zip")) { result = machine.run(format("cd %s/lib && unzip %s",getRunDir(),destName)); } else if (destName.toLowerCase().endsWith(".tgz") || destName.toLowerCase().endsWith(".tar.gz")) { result = machine.run(format("cd %s/lib && tar xvfz %s",getRunDir(),destName)); } else if (destName.toLowerCase().endsWith(".tar")) { result = machine.run(format("cd %s/lib && tar xvfz %s",getRunDir(),destName)); } if (result != 0) throw new IllegalStateException(format("unable to install classpath entry %s for %s at %s (failed to expand archive)",f,entity,machine)); } }
diff --git a/app-impl/src/main/java/org/cytoscape/app/internal/ui/InstallAppsPanel.java b/app-impl/src/main/java/org/cytoscape/app/internal/ui/InstallAppsPanel.java index 95e11f72c..8cbbe5564 100644 --- a/app-impl/src/main/java/org/cytoscape/app/internal/ui/InstallAppsPanel.java +++ b/app-impl/src/main/java/org/cytoscape/app/internal/ui/InstallAppsPanel.java @@ -1,983 +1,985 @@ package org.cytoscape.app.internal.ui; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Desktop; import java.awt.Font; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.Vector; import javax.swing.ComboBoxEditor; import javax.swing.DefaultComboBoxModel; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.text.html.HTMLDocument; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import org.cytoscape.app.internal.event.AppsChangedEvent; import org.cytoscape.app.internal.event.AppsChangedListener; import org.cytoscape.app.internal.manager.App; import org.cytoscape.app.internal.manager.App.AppStatus; import org.cytoscape.app.internal.manager.AppManager; import org.cytoscape.app.internal.manager.AppParser; import org.cytoscape.app.internal.manager.BundleApp; import org.cytoscape.app.internal.net.DownloadStatus; import org.cytoscape.app.internal.net.ResultsFilterer; import org.cytoscape.app.internal.net.Update; import org.cytoscape.app.internal.net.WebApp; import org.cytoscape.app.internal.net.WebQuerier; import org.cytoscape.app.internal.net.WebQuerier.AppTag; import org.cytoscape.app.internal.ui.downloadsites.DownloadSite; import org.cytoscape.app.internal.ui.downloadsites.DownloadSitesManager; import org.cytoscape.app.internal.ui.downloadsites.DownloadSitesManager.DownloadSitesChangedEvent; import org.cytoscape.app.internal.ui.downloadsites.DownloadSitesManager.DownloadSitesChangedListener; import org.cytoscape.app.internal.util.DebugHelper; import org.cytoscape.util.swing.FileChooserFilter; import org.cytoscape.util.swing.FileUtil; import org.cytoscape.work.Task; import org.cytoscape.work.TaskIterator; import org.cytoscape.work.TaskManager; import org.cytoscape.work.TaskMonitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class represents the panel in the App Manager dialog's tab used for installing new apps. * Its UI setup code is generated by the Netbeans 7 GUI builder. */ public class InstallAppsPanel extends javax.swing.JPanel { private static final Logger logger = LoggerFactory.getLogger(InstallAppsPanel.class); /** Long serial version identifier required by the Serializable class */ private static final long serialVersionUID = -1208176142084829272L; private javax.swing.JButton closeButton; private javax.swing.JPanel descriptionPanel; private javax.swing.JScrollPane descriptionScrollPane; private javax.swing.JSplitPane descriptionSplitPane; private javax.swing.JTextPane descriptionTextPane; private javax.swing.JComboBox downloadSiteComboBox; private javax.swing.JLabel downloadSiteLabel; private javax.swing.JTextField filterTextField; private javax.swing.JButton installButton; private javax.swing.JButton installFromFileButton; private javax.swing.JButton manageSitesButton; private javax.swing.JScrollPane resultsScrollPane; private javax.swing.JTree resultsTree; private javax.swing.JLabel searchAppsLabel; private javax.swing.JScrollPane tagsScrollPane; private javax.swing.JSplitPane tagsSplitPane; private javax.swing.JTree tagsTree; private javax.swing.JButton viewOnAppStoreButton; private JFileChooser fileChooser; private AppManager appManager; private DownloadSitesManager downloadSitesManager; private FileUtil fileUtil; private TaskManager taskManager; private Container parent; private WebApp selectedApp; private WebQuerier.AppTag currentSelectedAppTag; private Set<WebApp> resultsTreeApps; public InstallAppsPanel(final AppManager appManager, DownloadSitesManager downloadSitesManager, FileUtil fileUtil, TaskManager taskManager, Container parent) { this.appManager = appManager; this.downloadSitesManager = downloadSitesManager; this.fileUtil = fileUtil; this.taskManager = taskManager; this.parent = parent; initComponents(); tagsTree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { updateResultsTree(); updateDescriptionBox(); } }); resultsTree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { updateDescriptionBox(); } }); setupTextFieldListener(); setupDownloadSitesChangedListener(); queryForApps(); appManager.addAppListener(new AppsChangedListener() { @Override public void appsChanged(AppsChangedEvent event) { TreePath[] selectionPaths = resultsTree.getSelectionPaths(); updateDescriptionBox(); fillResultsTree(resultsTreeApps); resultsTree.setSelectionPaths(selectionPaths); } }); } private void setupDownloadSitesChangedListener() { downloadSitesManager.addDownloadSitesChangedListener(new DownloadSitesChangedListener() { @Override public void downloadSitesChanged( DownloadSitesChangedEvent downloadSitesChangedEvent) { final DefaultComboBoxModel defaultComboBoxModel = new DefaultComboBoxModel( new Vector<DownloadSite>(downloadSitesManager.getDownloadSites())); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { downloadSiteComboBox.setModel(defaultComboBoxModel); } }); } }); } // Queries the currently set app store url for available apps. private void queryForApps() { taskManager.execute(new TaskIterator(new Task() { // Obtain information for all available apps, then append tag information @Override public void run(TaskMonitor taskMonitor) throws Exception { WebQuerier webQuerier = appManager.getWebQuerier(); taskMonitor.setTitle("Getting available apps"); taskMonitor.setStatusMessage("Obtaining apps from: " + webQuerier.getCurrentAppStoreUrl()); Set<WebApp> availableApps = webQuerier.getAllApps(); // Once the information is obtained, update the tree SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // populateTree(appManager.getWebQuerier().getAllApps()); buildTagsTree(); fillResultsTree(appManager.getWebQuerier().getAllApps()); } }); } @Override public void cancel() { } })); } private void initComponents() { searchAppsLabel = new javax.swing.JLabel(); installFromFileButton = new javax.swing.JButton(); filterTextField = new javax.swing.JTextField(); descriptionSplitPane = new javax.swing.JSplitPane(); tagsSplitPane = new javax.swing.JSplitPane(); tagsScrollPane = new javax.swing.JScrollPane(); tagsTree = new javax.swing.JTree(); resultsScrollPane = new javax.swing.JScrollPane(); resultsTree = new javax.swing.JTree(); descriptionPanel = new javax.swing.JPanel(); descriptionScrollPane = new javax.swing.JScrollPane(); descriptionTextPane = new javax.swing.JTextPane(); viewOnAppStoreButton = new javax.swing.JButton(); installButton = new javax.swing.JButton(); downloadSiteLabel = new javax.swing.JLabel(); downloadSiteComboBox = new javax.swing.JComboBox(); closeButton = new javax.swing.JButton(); manageSitesButton = new javax.swing.JButton(); searchAppsLabel.setText("Search:"); installFromFileButton.setText("Install from File..."); installFromFileButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { installFromFileButtonActionPerformed(evt); } }); descriptionSplitPane.setDividerLocation(390); tagsSplitPane.setDividerLocation(175); javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root"); javax.swing.tree.DefaultMutableTreeNode treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("all apps (0)"); treeNode1.add(treeNode2); tagsTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1)); tagsTree.setFocusable(false); tagsTree.setRootVisible(false); + tagsTree.getSelectionModel().setSelectionMode(javax.swing.tree.TreeSelectionModel.SINGLE_TREE_SELECTION); tagsScrollPane.setViewportView(tagsTree); tagsSplitPane.setLeftComponent(tagsScrollPane); treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root"); resultsTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1)); resultsTree.setFocusable(false); resultsTree.setRootVisible(false); + resultsTree.getSelectionModel().setSelectionMode(javax.swing.tree.TreeSelectionModel.SINGLE_TREE_SELECTION); resultsScrollPane.setViewportView(resultsTree); tagsSplitPane.setRightComponent(resultsScrollPane); descriptionSplitPane.setLeftComponent(tagsSplitPane); descriptionPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); descriptionTextPane.setContentType("text/html"); descriptionTextPane.setEditable(false); //descriptionTextPane.setText("<html>\n <head>\n\n </head>\n <body>\n <p style=\"margin-top: 0\">\n App description is displayed here.\n </p>\n </body>\n</html>\n"); descriptionTextPane.setText(""); descriptionScrollPane.setViewportView(descriptionTextPane); javax.swing.GroupLayout descriptionPanelLayout = new javax.swing.GroupLayout(descriptionPanel); descriptionPanel.setLayout(descriptionPanelLayout); descriptionPanelLayout.setHorizontalGroup( descriptionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(descriptionScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE) ); descriptionPanelLayout.setVerticalGroup( descriptionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(descriptionScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE) ); descriptionSplitPane.setRightComponent(descriptionPanel); viewOnAppStoreButton.setText("View on App Store"); viewOnAppStoreButton.setEnabled(false); viewOnAppStoreButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { viewOnAppStoreButtonActionPerformed(evt); } }); installButton.setText("Install"); installButton.setEnabled(false); installButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { installButtonActionPerformed(evt); } }); downloadSiteLabel.setText("Download Site:"); downloadSiteComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { WebQuerier.DEFAULT_APP_STORE_URL })); downloadSiteComboBox.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { downloadSiteComboBoxItemStateChanged(evt); } }); downloadSiteComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { downloadSiteComboBoxActionPerformed(evt); } }); downloadSiteComboBox.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { downloadSiteComboBoxKeyPressed(evt); } }); closeButton.setText("Close"); closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeButtonActionPerformed(evt); } }); manageSitesButton.setText("Manage Sites..."); manageSitesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { manageSitesButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(descriptionSplitPane) .addGroup(layout.createSequentialGroup() .addComponent(installFromFileButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 80, Short.MAX_VALUE) .addComponent(viewOnAppStoreButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(installButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(closeButton)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(searchAppsLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(filterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(downloadSiteLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(downloadSiteComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(manageSitesButton))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(downloadSiteLabel) .addComponent(downloadSiteComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(manageSitesButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(searchAppsLabel) .addComponent(filterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(descriptionSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(installFromFileButton) .addComponent(viewOnAppStoreButton) .addComponent(installButton) .addComponent(closeButton)) .addContainerGap()) ); // Add a key listener to the download site combo box to listen for the enter key event final WebQuerier webQuerier = this.appManager.getWebQuerier(); downloadSiteComboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { final ComboBoxEditor editor = downloadSiteComboBox.getEditor(); final Object selectedValue = editor.getItem(); if (e.isActionKey() || e.getKeyCode() == KeyEvent.VK_ENTER) { if (downloadSiteComboBox.getModel() instanceof DefaultComboBoxModel && selectedValue != null) { final DefaultComboBoxModel comboBoxModel = (DefaultComboBoxModel) downloadSiteComboBox.getModel(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { boolean selectedAlreadyInList = false; for (int i = 0; i < comboBoxModel.getSize(); i++) { Object listElement = comboBoxModel.getElementAt(i); if (listElement.equals(selectedValue)) { selectedAlreadyInList = true; break; } } if (!selectedAlreadyInList) { comboBoxModel.insertElementAt(selectedValue, 1); editor.setItem(selectedValue); } } }); } if (webQuerier.getCurrentAppStoreUrl() != selectedValue.toString()) { webQuerier.setCurrentAppStoreUrl(selectedValue.toString()); queryForApps(); } } } }); // Make the JTextPane render HTML using the default UI font Font font = UIManager.getFont("Label.font"); String bodyRule = "body { font-family: " + font.getFamily() + "; " + "font-size: " + font.getSize() + "pt; }"; ((HTMLDocument) descriptionTextPane.getDocument()).getStyleSheet().addRule(bodyRule); // Setup the TreeCellRenderer to make the app tags use the folder icon instead of the default leaf icon, // and have it use the opened folder icon when selected DefaultTreeCellRenderer tagsTreeCellRenderer = new DefaultTreeCellRenderer() { private static final long serialVersionUID = 3311980250590351751L; @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component defaultResult = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); // Make leaves use the open folder icon when selected if (selected && leaf) { setIcon(getOpenIcon()); } return defaultResult; } }; tagsTreeCellRenderer.setLeafIcon(tagsTreeCellRenderer.getDefaultClosedIcon()); tagsTree.setCellRenderer(tagsTreeCellRenderer); } private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void installFromFileButtonActionPerformed(java.awt.event.ActionEvent evt) { // Setup a the file filter for the open file dialog FileChooserFilter fileChooserFilter = new FileChooserFilter("Jar, Zip, and Karaf Kar Files (*.jar, *.zip, *.kar)", new String[]{"jar", "zip", "kar"}); Collection<FileChooserFilter> fileChooserFilters = new LinkedList<FileChooserFilter>(); fileChooserFilters.add(fileChooserFilter); // Show the dialog final File[] files = fileUtil.getFiles(parent, "Choose file(s)", FileUtil.LOAD, FileUtil.LAST_DIRECTORY, "Install", true, fileChooserFilters); if (files != null) { taskManager.execute(new TaskIterator(new Task() { @Override public void run(TaskMonitor taskMonitor) throws Exception { taskMonitor.setTitle("Installing requested app"); int installedAppCount = 0; double progress = 0; taskMonitor.setStatusMessage("Downloading app.."); for (int index = 0; index < files.length; index++) { AppParser appParser = appManager.getAppParser(); App parsedApp = null; parsedApp = appParser.parseApp(files[index]); { String parsedAppName = parsedApp.getAppName(); Set<App> collidingApps = checkAppNameCollision(parsedAppName); // TODO: Only do replace for bundle apps due to simple apps requiring restart for uninstall. // TODO: Possibly may be good idea to show whether an app is a bundle app, on the app description page. if (collidingApps.size() == 1 && collidingApps.iterator().next() instanceof BundleApp) { App app = collidingApps.iterator().next(); int response; response = JOptionPane.showConfirmDialog(parent, "There is an app \"" + app.getAppName() + "\" with the same name. It is version " + app.getVersion() + ", while the" + " one you're about to install is version " + parsedApp.getVersion() + ". Replace it?", "Replace App?", JOptionPane.YES_NO_CANCEL_OPTION); if (response == JOptionPane.YES_OPTION) { installedAppCount += 1; appManager.uninstallApp(app); appManager.installApp(parsedApp); } if (response == JOptionPane.NO_OPTION) { // Install both appManager.installApp(parsedApp); } if (response == JOptionPane.CANCEL_OPTION) { // Do nothing } } else { installedAppCount += 1; System.out.println("Installing"); appManager.installApp(parsedApp); } } } taskMonitor.setProgress(1.0); if (parent instanceof AppManagerDialog) { if (installedAppCount > 0) { ((AppManagerDialog) parent).changeTab(1); } } } @Override public void cancel() { } })); } } private Set<App> checkAppNameCollision(String appName) { Set<App> collidingApps = new HashSet<App>(); for (App app : appManager.getApps()) { if (appName.equalsIgnoreCase(app.getAppName())) { if (app.isDetached() == false) { collidingApps.add(app); } } } return collidingApps; } /** * Attempts to insert newlines into a given string such that each line has no * more than the specified number of characters. */ private String splitIntoLines(String text, int charsPerLine) { return null; } private void setupTextFieldListener() { filterTextField.getDocument().addDocumentListener(new DocumentListener() { ResultsFilterer resultsFilterer = new ResultsFilterer(); private void showFilteredApps() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { tagsTree.clearSelection(); fillResultsTree(resultsFilterer.findMatches(filterTextField.getText(), appManager.getWebQuerier().getAllApps())); } }); } @Override public void removeUpdate(DocumentEvent arg0) { if (filterTextField.getText().length() != 0) { showFilteredApps(); } } @Override public void insertUpdate(DocumentEvent arg0) { showFilteredApps(); } @Override public void changedUpdate(DocumentEvent arg0) { } }); } private void installButtonActionPerformed(java.awt.event.ActionEvent evt) { final WebQuerier webQuerier = appManager.getWebQuerier(); final WebApp appToDownload = selectedApp; taskManager.execute(new TaskIterator(new Task() { private DownloadStatus status; @Override public void run(TaskMonitor taskMonitor) throws Exception { status = new DownloadStatus(taskMonitor); taskMonitor.setTitle("Installing App from App Store"); double progress = 0; taskMonitor.setStatusMessage("Installing app: " + appToDownload.getFullName()); // Download app File appFile = webQuerier.downloadApp(appToDownload, null, new File(appManager.getDownloadedAppsPath()), status); if (appFile != null) { // Parse app App parsedApp = appManager.getAppParser().parseApp(appFile); // Check for name collisions Set<App> collidingApps = checkAppNameCollision(parsedApp.getAppName()); // TODO: Only do replace for bundle apps due to simple apps requiring restart for uninstall. if (collidingApps.size() == 1 && collidingApps.iterator().next() instanceof BundleApp) { App collidingApp = collidingApps.iterator().next(); int response = JOptionPane.showConfirmDialog(parent, "There is an app \"" + collidingApp.getAppName() + "\" with the same name, version " + collidingApp.getVersion() + ". The" + " one you're about to install is version " + parsedApp.getVersion() + ". Replace it?", "Replace App?", JOptionPane.YES_NO_CANCEL_OPTION); if (response == JOptionPane.YES_OPTION) { // Replace app appManager.uninstallApp(collidingApp); appManager.installApp(parsedApp); } if (response == JOptionPane.NO_OPTION) { // Install both appManager.installApp(parsedApp); } if (response == JOptionPane.CANCEL_OPTION) { // Do nothing, do not install } } else { appManager.installApp(parsedApp); } } else { // Log error: no download links were found for app logger.warn("Unable to find download URL for about-to-be-installed " + appToDownload.getFullName()); DebugHelper.print("Unable to find download url for: " + appToDownload.getFullName()); } taskMonitor.setProgress(1.0); } @Override public void cancel() { if (status != null) { status.cancel(); } } })); } private void buildTagsTree() { WebQuerier webQuerier = appManager.getWebQuerier(); // Get all available apps and tags Set<WebApp> availableApps = webQuerier.getAllApps(); Set<WebQuerier.AppTag> availableTags = webQuerier.getAllTags(); List<WebQuerier.AppTag> sortedTags = new LinkedList<WebQuerier.AppTag>(availableTags); Collections.sort(sortedTags, new Comparator<WebQuerier.AppTag>() { @Override public int compare(AppTag tag, AppTag other) { return other.getCount() - tag.getCount(); } }); DefaultMutableTreeNode root = new DefaultMutableTreeNode("root"); DefaultMutableTreeNode allAppsTreeNode = new DefaultMutableTreeNode("all apps" + " (" + availableApps.size() + ")"); root.add(allAppsTreeNode); DefaultMutableTreeNode appsByTagTreeNode = new DefaultMutableTreeNode("apps by tag"); // Only show the "apps by tag" node if we have at least 1 app if (availableApps.size() > 0) { root.add(appsByTagTreeNode); } DefaultMutableTreeNode treeNode = null; for (final WebQuerier.AppTag appTag : sortedTags) { if (appTag.getCount() > 0) { treeNode = new DefaultMutableTreeNode(appTag); appsByTagTreeNode.add(treeNode); } } tagsTree.setModel(new DefaultTreeModel(root)); // tagsTree.expandRow(2); currentSelectedAppTag = null; } private void updateResultsTree() { TreePath selectionPath = tagsTree.getSelectionPath(); // DebugHelper.print(String.valueOf(selectedNode.getUserObject())); currentSelectedAppTag = null; if (selectionPath != null) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectionPath.getLastPathComponent(); // Check if the "all apps" node is selected if (selectedNode.getLevel() == 1 && String.valueOf(selectedNode.getUserObject()).startsWith("all apps")) { fillResultsTree(appManager.getWebQuerier().getAllApps()); } else if (selectedNode.getUserObject() instanceof WebQuerier.AppTag) { WebQuerier.AppTag selectedTag = (WebQuerier.AppTag) selectedNode.getUserObject(); fillResultsTree(appManager.getWebQuerier().getAppsByTag(selectedTag.getName())); currentSelectedAppTag = selectedTag; } else { // Clear tree resultsTree.setModel(new DefaultTreeModel(null)); } } else { // fillResultsTree(appManager.getWebQuerier().getAllApps()); // System.out.println("selection path null, not updating results tree"); } } private void fillResultsTree(Set<WebApp> webApps) { appManager.getWebQuerier().checkWebAppInstallStatus( appManager.getWebQuerier().getAllApps(), appManager); Set<WebApp> appsToShow = webApps; List<WebApp> sortedApps = new LinkedList<WebApp>(appsToShow); // Sort apps by alphabetical order Collections.sort(sortedApps, new Comparator<WebApp>() { @Override public int compare(WebApp webApp, WebApp other) { return (webApp.getName().compareToIgnoreCase(other.getName())); } }); DefaultMutableTreeNode root = new DefaultMutableTreeNode("root"); DefaultMutableTreeNode treeNode; for (WebApp webApp : sortedApps) { if (webApp.getCorrespondingApp() != null && webApp.getCorrespondingApp().getStatus() == AppStatus.INSTALLED) { webApp.setAppListDisplayName(webApp.getFullName() + " (Installed)"); } else { webApp.setAppListDisplayName(webApp.getFullName()); } treeNode = new DefaultMutableTreeNode(webApp); root.add(treeNode); } resultsTree.setModel(new DefaultTreeModel(root)); resultsTreeApps = new HashSet<WebApp>(webApps); } private void updateDescriptionBox() { TreePath selectedPath = resultsTree.getSelectionPath(); if (selectedPath != null) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) resultsTree.getSelectionPath().getLastPathComponent(); WebApp selectedApp = (WebApp) selectedNode.getUserObject(); boolean appAlreadyInstalled = (selectedApp.getCorrespondingApp() != null && selectedApp.getCorrespondingApp().getStatus() == AppStatus.INSTALLED); String text = ""; // text += "<html> <head> </head> <body hspace=\"4\" vspace=\"4\">"; text += "<html> <body hspace=\"4\" vspace=\"2\">"; // App hyperlink to web store page // text += "<p style=\"margin-top: 0\"> <a href=\"" + selectedApp.getPageUrl() + "\">" + selectedApp.getPageUrl() + "</a> </p>"; // App name, version text += "<b>" + selectedApp.getFullName() + "</b>"; String latestReleaseVersion = selectedApp.getReleases().get(selectedApp.getReleases().size() - 1).getReleaseVersion(); text += "<br />" + latestReleaseVersion; if (appAlreadyInstalled) { if (!selectedApp.getCorrespondingApp().getVersion().equalsIgnoreCase(latestReleaseVersion)) { text += " (installed: " + selectedApp.getCorrespondingApp().getVersion() + ")"; } } /* text += "<p>"; text += "<b>" + selectedApp.getFullName() + "</b>"; text += "<br />" + selectedApp.getReleases().get(selectedApp.getReleases().size() - 1).getReleaseVersion(); text += "</p>"; */ text += "<p>"; // App image text += "<img border=\"0\" "; text += "src=\"" + appManager.getWebQuerier().getDefaultAppStoreUrl() + selectedApp.getIconUrl() + "\" alt=\"" + selectedApp.getFullName() + "\"/>"; text += "</p>"; // App description text += "<p>"; text += (String.valueOf(selectedApp.getDescription()).equalsIgnoreCase("null") ? "App description not found." : selectedApp.getDescription()); text += "</p>"; text += "</body> </html>"; descriptionTextPane.setText(text); this.selectedApp = selectedApp; if (appAlreadyInstalled) { installButton.setEnabled(false); } else { installButton.setEnabled(true); } viewOnAppStoreButton.setEnabled(true); } else { //descriptionTextPane.setText("App description is displayed here."); descriptionTextPane.setText(""); this.selectedApp = null; installButton.setEnabled(false); viewOnAppStoreButton.setEnabled(false); } } private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void viewOnAppStoreButtonActionPerformed(java.awt.event.ActionEvent evt) { if (selectedApp == null) { return; } if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); try { desktop.browse((new URL(selectedApp.getPageUrl())).toURI()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) { ((javax.swing.JDialog)InstallAppsPanel.this.parent).dispose(); } private void downloadSiteComboBoxItemStateChanged(java.awt.event.ItemEvent evt) { } private void downloadSiteComboBoxActionPerformed(java.awt.event.ActionEvent evt) { final Object selected = downloadSiteComboBox.getSelectedItem(); if (downloadSiteComboBox.getModel() instanceof DefaultComboBoxModel && selected != null) { final DefaultComboBoxModel comboBoxModel = (DefaultComboBoxModel) downloadSiteComboBox.getModel(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { boolean selectedAlreadyInList = false; for (int i = 0; i < comboBoxModel.getSize(); i++) { Object listElement = comboBoxModel.getElementAt(i); if (listElement.equals(selected)) { selectedAlreadyInList = true; if (i > 0) { // comboBoxModel.removeElementAt(i); // comboBoxModel.insertElementAt(listElement, 1); } break; } } if (!selectedAlreadyInList) { comboBoxModel.insertElementAt(selected, 1); } } }); if (appManager.getWebQuerier().getCurrentAppStoreUrl() != selected.toString()) { appManager.getWebQuerier().setCurrentAppStoreUrl(selected.toString()); queryForApps(); } } } private void downloadSiteComboBoxKeyPressed(java.awt.event.KeyEvent evt) { } private void manageSitesButtonActionPerformed(java.awt.event.ActionEvent evt) { if (parent instanceof AppManagerDialog) { ((AppManagerDialog) parent).showManageDownloadSitesDialog(); } } }
false
true
private void initComponents() { searchAppsLabel = new javax.swing.JLabel(); installFromFileButton = new javax.swing.JButton(); filterTextField = new javax.swing.JTextField(); descriptionSplitPane = new javax.swing.JSplitPane(); tagsSplitPane = new javax.swing.JSplitPane(); tagsScrollPane = new javax.swing.JScrollPane(); tagsTree = new javax.swing.JTree(); resultsScrollPane = new javax.swing.JScrollPane(); resultsTree = new javax.swing.JTree(); descriptionPanel = new javax.swing.JPanel(); descriptionScrollPane = new javax.swing.JScrollPane(); descriptionTextPane = new javax.swing.JTextPane(); viewOnAppStoreButton = new javax.swing.JButton(); installButton = new javax.swing.JButton(); downloadSiteLabel = new javax.swing.JLabel(); downloadSiteComboBox = new javax.swing.JComboBox(); closeButton = new javax.swing.JButton(); manageSitesButton = new javax.swing.JButton(); searchAppsLabel.setText("Search:"); installFromFileButton.setText("Install from File..."); installFromFileButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { installFromFileButtonActionPerformed(evt); } }); descriptionSplitPane.setDividerLocation(390); tagsSplitPane.setDividerLocation(175); javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root"); javax.swing.tree.DefaultMutableTreeNode treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("all apps (0)"); treeNode1.add(treeNode2); tagsTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1)); tagsTree.setFocusable(false); tagsTree.setRootVisible(false); tagsScrollPane.setViewportView(tagsTree); tagsSplitPane.setLeftComponent(tagsScrollPane); treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root"); resultsTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1)); resultsTree.setFocusable(false); resultsTree.setRootVisible(false); resultsScrollPane.setViewportView(resultsTree); tagsSplitPane.setRightComponent(resultsScrollPane); descriptionSplitPane.setLeftComponent(tagsSplitPane); descriptionPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); descriptionTextPane.setContentType("text/html"); descriptionTextPane.setEditable(false); //descriptionTextPane.setText("<html>\n <head>\n\n </head>\n <body>\n <p style=\"margin-top: 0\">\n App description is displayed here.\n </p>\n </body>\n</html>\n"); descriptionTextPane.setText(""); descriptionScrollPane.setViewportView(descriptionTextPane); javax.swing.GroupLayout descriptionPanelLayout = new javax.swing.GroupLayout(descriptionPanel); descriptionPanel.setLayout(descriptionPanelLayout); descriptionPanelLayout.setHorizontalGroup( descriptionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(descriptionScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE) ); descriptionPanelLayout.setVerticalGroup( descriptionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(descriptionScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE) ); descriptionSplitPane.setRightComponent(descriptionPanel); viewOnAppStoreButton.setText("View on App Store"); viewOnAppStoreButton.setEnabled(false); viewOnAppStoreButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { viewOnAppStoreButtonActionPerformed(evt); } }); installButton.setText("Install"); installButton.setEnabled(false); installButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { installButtonActionPerformed(evt); } }); downloadSiteLabel.setText("Download Site:"); downloadSiteComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { WebQuerier.DEFAULT_APP_STORE_URL })); downloadSiteComboBox.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { downloadSiteComboBoxItemStateChanged(evt); } }); downloadSiteComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { downloadSiteComboBoxActionPerformed(evt); } }); downloadSiteComboBox.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { downloadSiteComboBoxKeyPressed(evt); } }); closeButton.setText("Close"); closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeButtonActionPerformed(evt); } }); manageSitesButton.setText("Manage Sites..."); manageSitesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { manageSitesButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(descriptionSplitPane) .addGroup(layout.createSequentialGroup() .addComponent(installFromFileButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 80, Short.MAX_VALUE) .addComponent(viewOnAppStoreButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(installButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(closeButton)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(searchAppsLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(filterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(downloadSiteLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(downloadSiteComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(manageSitesButton))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(downloadSiteLabel) .addComponent(downloadSiteComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(manageSitesButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(searchAppsLabel) .addComponent(filterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(descriptionSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(installFromFileButton) .addComponent(viewOnAppStoreButton) .addComponent(installButton) .addComponent(closeButton)) .addContainerGap()) ); // Add a key listener to the download site combo box to listen for the enter key event final WebQuerier webQuerier = this.appManager.getWebQuerier(); downloadSiteComboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { final ComboBoxEditor editor = downloadSiteComboBox.getEditor(); final Object selectedValue = editor.getItem(); if (e.isActionKey() || e.getKeyCode() == KeyEvent.VK_ENTER) { if (downloadSiteComboBox.getModel() instanceof DefaultComboBoxModel && selectedValue != null) { final DefaultComboBoxModel comboBoxModel = (DefaultComboBoxModel) downloadSiteComboBox.getModel(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { boolean selectedAlreadyInList = false; for (int i = 0; i < comboBoxModel.getSize(); i++) { Object listElement = comboBoxModel.getElementAt(i); if (listElement.equals(selectedValue)) { selectedAlreadyInList = true; break; } } if (!selectedAlreadyInList) { comboBoxModel.insertElementAt(selectedValue, 1); editor.setItem(selectedValue); } } }); } if (webQuerier.getCurrentAppStoreUrl() != selectedValue.toString()) { webQuerier.setCurrentAppStoreUrl(selectedValue.toString()); queryForApps(); } } } }); // Make the JTextPane render HTML using the default UI font Font font = UIManager.getFont("Label.font"); String bodyRule = "body { font-family: " + font.getFamily() + "; " + "font-size: " + font.getSize() + "pt; }"; ((HTMLDocument) descriptionTextPane.getDocument()).getStyleSheet().addRule(bodyRule); // Setup the TreeCellRenderer to make the app tags use the folder icon instead of the default leaf icon, // and have it use the opened folder icon when selected DefaultTreeCellRenderer tagsTreeCellRenderer = new DefaultTreeCellRenderer() { private static final long serialVersionUID = 3311980250590351751L; @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component defaultResult = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); // Make leaves use the open folder icon when selected if (selected && leaf) { setIcon(getOpenIcon()); } return defaultResult; } }; tagsTreeCellRenderer.setLeafIcon(tagsTreeCellRenderer.getDefaultClosedIcon()); tagsTree.setCellRenderer(tagsTreeCellRenderer); }
private void initComponents() { searchAppsLabel = new javax.swing.JLabel(); installFromFileButton = new javax.swing.JButton(); filterTextField = new javax.swing.JTextField(); descriptionSplitPane = new javax.swing.JSplitPane(); tagsSplitPane = new javax.swing.JSplitPane(); tagsScrollPane = new javax.swing.JScrollPane(); tagsTree = new javax.swing.JTree(); resultsScrollPane = new javax.swing.JScrollPane(); resultsTree = new javax.swing.JTree(); descriptionPanel = new javax.swing.JPanel(); descriptionScrollPane = new javax.swing.JScrollPane(); descriptionTextPane = new javax.swing.JTextPane(); viewOnAppStoreButton = new javax.swing.JButton(); installButton = new javax.swing.JButton(); downloadSiteLabel = new javax.swing.JLabel(); downloadSiteComboBox = new javax.swing.JComboBox(); closeButton = new javax.swing.JButton(); manageSitesButton = new javax.swing.JButton(); searchAppsLabel.setText("Search:"); installFromFileButton.setText("Install from File..."); installFromFileButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { installFromFileButtonActionPerformed(evt); } }); descriptionSplitPane.setDividerLocation(390); tagsSplitPane.setDividerLocation(175); javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root"); javax.swing.tree.DefaultMutableTreeNode treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("all apps (0)"); treeNode1.add(treeNode2); tagsTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1)); tagsTree.setFocusable(false); tagsTree.setRootVisible(false); tagsTree.getSelectionModel().setSelectionMode(javax.swing.tree.TreeSelectionModel.SINGLE_TREE_SELECTION); tagsScrollPane.setViewportView(tagsTree); tagsSplitPane.setLeftComponent(tagsScrollPane); treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root"); resultsTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1)); resultsTree.setFocusable(false); resultsTree.setRootVisible(false); resultsTree.getSelectionModel().setSelectionMode(javax.swing.tree.TreeSelectionModel.SINGLE_TREE_SELECTION); resultsScrollPane.setViewportView(resultsTree); tagsSplitPane.setRightComponent(resultsScrollPane); descriptionSplitPane.setLeftComponent(tagsSplitPane); descriptionPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); descriptionTextPane.setContentType("text/html"); descriptionTextPane.setEditable(false); //descriptionTextPane.setText("<html>\n <head>\n\n </head>\n <body>\n <p style=\"margin-top: 0\">\n App description is displayed here.\n </p>\n </body>\n</html>\n"); descriptionTextPane.setText(""); descriptionScrollPane.setViewportView(descriptionTextPane); javax.swing.GroupLayout descriptionPanelLayout = new javax.swing.GroupLayout(descriptionPanel); descriptionPanel.setLayout(descriptionPanelLayout); descriptionPanelLayout.setHorizontalGroup( descriptionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(descriptionScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE) ); descriptionPanelLayout.setVerticalGroup( descriptionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(descriptionScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE) ); descriptionSplitPane.setRightComponent(descriptionPanel); viewOnAppStoreButton.setText("View on App Store"); viewOnAppStoreButton.setEnabled(false); viewOnAppStoreButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { viewOnAppStoreButtonActionPerformed(evt); } }); installButton.setText("Install"); installButton.setEnabled(false); installButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { installButtonActionPerformed(evt); } }); downloadSiteLabel.setText("Download Site:"); downloadSiteComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { WebQuerier.DEFAULT_APP_STORE_URL })); downloadSiteComboBox.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { downloadSiteComboBoxItemStateChanged(evt); } }); downloadSiteComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { downloadSiteComboBoxActionPerformed(evt); } }); downloadSiteComboBox.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { downloadSiteComboBoxKeyPressed(evt); } }); closeButton.setText("Close"); closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeButtonActionPerformed(evt); } }); manageSitesButton.setText("Manage Sites..."); manageSitesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { manageSitesButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(descriptionSplitPane) .addGroup(layout.createSequentialGroup() .addComponent(installFromFileButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 80, Short.MAX_VALUE) .addComponent(viewOnAppStoreButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(installButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(closeButton)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(searchAppsLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(filterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(downloadSiteLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(downloadSiteComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(manageSitesButton))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(downloadSiteLabel) .addComponent(downloadSiteComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(manageSitesButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(searchAppsLabel) .addComponent(filterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(descriptionSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(installFromFileButton) .addComponent(viewOnAppStoreButton) .addComponent(installButton) .addComponent(closeButton)) .addContainerGap()) ); // Add a key listener to the download site combo box to listen for the enter key event final WebQuerier webQuerier = this.appManager.getWebQuerier(); downloadSiteComboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { final ComboBoxEditor editor = downloadSiteComboBox.getEditor(); final Object selectedValue = editor.getItem(); if (e.isActionKey() || e.getKeyCode() == KeyEvent.VK_ENTER) { if (downloadSiteComboBox.getModel() instanceof DefaultComboBoxModel && selectedValue != null) { final DefaultComboBoxModel comboBoxModel = (DefaultComboBoxModel) downloadSiteComboBox.getModel(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { boolean selectedAlreadyInList = false; for (int i = 0; i < comboBoxModel.getSize(); i++) { Object listElement = comboBoxModel.getElementAt(i); if (listElement.equals(selectedValue)) { selectedAlreadyInList = true; break; } } if (!selectedAlreadyInList) { comboBoxModel.insertElementAt(selectedValue, 1); editor.setItem(selectedValue); } } }); } if (webQuerier.getCurrentAppStoreUrl() != selectedValue.toString()) { webQuerier.setCurrentAppStoreUrl(selectedValue.toString()); queryForApps(); } } } }); // Make the JTextPane render HTML using the default UI font Font font = UIManager.getFont("Label.font"); String bodyRule = "body { font-family: " + font.getFamily() + "; " + "font-size: " + font.getSize() + "pt; }"; ((HTMLDocument) descriptionTextPane.getDocument()).getStyleSheet().addRule(bodyRule); // Setup the TreeCellRenderer to make the app tags use the folder icon instead of the default leaf icon, // and have it use the opened folder icon when selected DefaultTreeCellRenderer tagsTreeCellRenderer = new DefaultTreeCellRenderer() { private static final long serialVersionUID = 3311980250590351751L; @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component defaultResult = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); // Make leaves use the open folder icon when selected if (selected && leaf) { setIcon(getOpenIcon()); } return defaultResult; } }; tagsTreeCellRenderer.setLeafIcon(tagsTreeCellRenderer.getDefaultClosedIcon()); tagsTree.setCellRenderer(tagsTreeCellRenderer); }
diff --git a/mud/client/src/main/java/pl/edu/agh/two/mud/client/Client.java b/mud/client/src/main/java/pl/edu/agh/two/mud/client/Client.java index 67437c0..e4a2210 100644 --- a/mud/client/src/main/java/pl/edu/agh/two/mud/client/Client.java +++ b/mud/client/src/main/java/pl/edu/agh/two/mud/client/Client.java @@ -1,49 +1,49 @@ package pl.edu.agh.two.mud.client; import java.io.*; import org.apache.log4j.*; import pl.edu.agh.two.mud.client.configuration.*; public class Client { private static final String DEFAULT_IP = "127.0.0.1"; private Connection connection; private Gui gui; private Logger logger = Logger.getLogger(Client.class); public void start(String host, int port) { try { gui.show(); connection.connect(host, port); gui.setLabel(connection.read().toString()); } catch (Exception e) { logger.error("Connection with \"" + host + ":" + port + "\" Error: " + e.getMessage()); - gui.setLabel(e.toString()); + gui.setLabel("Connection with \"" + host + ":" + port + "\" Error: " + e.getMessage()); } } public void setGui(Gui gui) { this.gui = gui; } public void setConnection(Connection connection) { this.connection = connection; } public static void main(String[] args) throws IOException, ClassNotFoundException { Client client = (Client) ApplicationContext.getBean("client"); String host = getHostFromArgsOrDefault(args); client.start(host, 13933); } private static String getHostFromArgsOrDefault(String[] args) { return args.length == 0 ? DEFAULT_IP : args[0]; } }
true
true
public void start(String host, int port) { try { gui.show(); connection.connect(host, port); gui.setLabel(connection.read().toString()); } catch (Exception e) { logger.error("Connection with \"" + host + ":" + port + "\" Error: " + e.getMessage()); gui.setLabel(e.toString()); } }
public void start(String host, int port) { try { gui.show(); connection.connect(host, port); gui.setLabel(connection.read().toString()); } catch (Exception e) { logger.error("Connection with \"" + host + ":" + port + "\" Error: " + e.getMessage()); gui.setLabel("Connection with \"" + host + ":" + port + "\" Error: " + e.getMessage()); } }
diff --git a/src/edu/worcester/cs499summer2012/activity/ViewTaskActivity.java b/src/edu/worcester/cs499summer2012/activity/ViewTaskActivity.java index 61da064..32e1dd0 100644 --- a/src/edu/worcester/cs499summer2012/activity/ViewTaskActivity.java +++ b/src/edu/worcester/cs499summer2012/activity/ViewTaskActivity.java @@ -1,212 +1,212 @@ /* * ViewTaskActivity.java * * Copyright 2012 Jonathan Hasenzahl, James Celona, Dhimitraq Jorgji * * 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 edu.worcester.cs499summer2012.activity; import java.util.GregorianCalendar; import android.content.Intent; import android.os.Bundle; import android.text.format.DateFormat; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import edu.worcester.cs499summer2012.R; import edu.worcester.cs499summer2012.database.TasksDataSource; import edu.worcester.cs499summer2012.task.Category; import edu.worcester.cs499summer2012.task.Task; /** * Activity for adding a new task. * @author Jonathan Hasenzahl */ public class ViewTaskActivity extends SherlockActivity implements OnClickListener { /************************************************************************** * Static fields and methods * **************************************************************************/ /************************************************************************** * Private fields * **************************************************************************/ private TasksDataSource data_source; private Task task; private Intent intent; /************************************************************************** * Class methods * **************************************************************************/ /** * Displays a message in a Toast notification for a short duration. */ private void toast(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } /************************************************************************** * Overridden parent methods * **************************************************************************/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_task); // Allow Action bar icon to act as a button ActionBar action_bar = getSupportActionBar(); action_bar.setHomeButtonEnabled(true); action_bar.setDisplayHomeAsUpEnabled(true); // Get instance of the db data_source = TasksDataSource.getInstance(this); // Get the task from the intent task = data_source.getTask(getIntent().getIntExtra(Task.EXTRA_TASK_ID, 0)); // Set name ((TextView) findViewById(R.id.text_view_task_name)).setText(task.getName()); // Set completion button Button button = (Button) findViewById(R.id.button_complete_task); if (!task.isCompleted()) button.setText(R.string.button_not_completed); else button.setText(R.string.button_completed); button.setOnClickListener(this); // Set priority ((TextView) findViewById(R.id.text_priority)).setText(Task.LABELS[task.getPriority()]); // Set priority icon switch (task.getPriority()) { case Task.URGENT: ((ImageView) findViewById(R.id.image_priority)).setImageResource(R.drawable.ic_urgent); break; case Task.NORMAL: ((ImageView) findViewById(R.id.image_priority)).setImageResource(R.drawable.ic_normal); break; case Task.TRIVIAL: ((ImageView) findViewById(R.id.image_priority)).setImageResource(R.drawable.ic_trivial); break; } // Set category (if category ID is not 1, i.e. no category) if (task.getCategory() != 1) { Category category = data_source.getCategory(task.getCategory()); ((ImageView) findViewById(R.id.image_category)).setBackgroundColor(category.getColor()); ((TextView) findViewById(R.id.text_category)).setText(category.getName()); } // Set due date if (task.hasDateDue()) ((TextView) findViewById(R.id.text_date_due)).setText(DateFormat.format("MM/dd/yy 'at' h:mm AA", task.getDateDueCal())); else ((TextView) findViewById(R.id.text_date_due)).setText(R.string.text_no_due_date); // Set final due date if (task.hasFinalDateDue()) ((TextView) findViewById(R.id.text_alarm)).setText(DateFormat.format("MM/dd/yy 'at' h:mm AA", task.getFinalDateDueCal())); else ((TextView) findViewById(R.id.text_alarm)).setText(R.string.text_no_final_due_date); // Set repetition if (task.isRepeating()) { - ((TextView) findViewById(R.id.text_repeat)).setText("Repeat every " + task.getRepeatInterval() + ' ' + Task.REPEAT_LABELS[task.getRepeatInterval()]); + ((TextView) findViewById(R.id.text_repeat)).setText("Repeat every " + task.getRepeatInterval() + ' ' + Task.REPEAT_LABELS[task.getRepeatType()]); if (task.hasStopRepeatingDate()) ((TextView) findViewById(R.id.text_repeat_2)).setText(DateFormat.format("'until' MM/dd/yy 'at' h:mm AA", task.getStopRepeatingDateCal())); else ((TextView) findViewById(R.id.text_repeat_2)).setText(R.string.text_no_stop_repeating_date); } else { ((TextView) findViewById(R.id.text_repeat)).setText(R.string.text_no_repetition); ((TextView) findViewById(R.id.text_repeat_2)).setVisibility(View.GONE); } // Set notes ((TextView) findViewById(R.id.text_notes)).setText(task.getNotes()); // Set date created ((TextView) findViewById(R.id.text_date_created)).setText(DateFormat.format("MM/dd/yy 'at' h:mm AA", task.getDateCreatedCal())); // Set date modified ((TextView) findViewById(R.id.text_date_modified)).setText(DateFormat.format("MM/dd/yy 'at' h:mm AA", task.getDateModifiedCal())); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getSupportMenuInflater(); inflater.inflate(R.menu.activity_view_task, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: case R.id.menu_view_task_back: setResult(RESULT_CANCELED); finish(); return true; case R.id.menu_view_task_edit: case R.id.menu_view_task_delete: default: return super.onOptionsItemSelected(item); } } /************************************************************************** * Methods implementing OnClickListener interface * **************************************************************************/ @Override public void onClick(View v) { if (v.getId() == R.id.button_complete_task) { task.toggleIsCompleted(); task.setDateModified(GregorianCalendar.getInstance().getTimeInMillis()); if (task.isCompleted()) toast("Task completed!"); else toast("Task not completed"); } data_source.updateTask(task); intent = new Intent(this, MainActivity.class); intent.putExtra(Task.EXTRA_TASK_ID, task.getID()); setResult(RESULT_OK, intent); finish(); } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_task); // Allow Action bar icon to act as a button ActionBar action_bar = getSupportActionBar(); action_bar.setHomeButtonEnabled(true); action_bar.setDisplayHomeAsUpEnabled(true); // Get instance of the db data_source = TasksDataSource.getInstance(this); // Get the task from the intent task = data_source.getTask(getIntent().getIntExtra(Task.EXTRA_TASK_ID, 0)); // Set name ((TextView) findViewById(R.id.text_view_task_name)).setText(task.getName()); // Set completion button Button button = (Button) findViewById(R.id.button_complete_task); if (!task.isCompleted()) button.setText(R.string.button_not_completed); else button.setText(R.string.button_completed); button.setOnClickListener(this); // Set priority ((TextView) findViewById(R.id.text_priority)).setText(Task.LABELS[task.getPriority()]); // Set priority icon switch (task.getPriority()) { case Task.URGENT: ((ImageView) findViewById(R.id.image_priority)).setImageResource(R.drawable.ic_urgent); break; case Task.NORMAL: ((ImageView) findViewById(R.id.image_priority)).setImageResource(R.drawable.ic_normal); break; case Task.TRIVIAL: ((ImageView) findViewById(R.id.image_priority)).setImageResource(R.drawable.ic_trivial); break; } // Set category (if category ID is not 1, i.e. no category) if (task.getCategory() != 1) { Category category = data_source.getCategory(task.getCategory()); ((ImageView) findViewById(R.id.image_category)).setBackgroundColor(category.getColor()); ((TextView) findViewById(R.id.text_category)).setText(category.getName()); } // Set due date if (task.hasDateDue()) ((TextView) findViewById(R.id.text_date_due)).setText(DateFormat.format("MM/dd/yy 'at' h:mm AA", task.getDateDueCal())); else ((TextView) findViewById(R.id.text_date_due)).setText(R.string.text_no_due_date); // Set final due date if (task.hasFinalDateDue()) ((TextView) findViewById(R.id.text_alarm)).setText(DateFormat.format("MM/dd/yy 'at' h:mm AA", task.getFinalDateDueCal())); else ((TextView) findViewById(R.id.text_alarm)).setText(R.string.text_no_final_due_date); // Set repetition if (task.isRepeating()) { ((TextView) findViewById(R.id.text_repeat)).setText("Repeat every " + task.getRepeatInterval() + ' ' + Task.REPEAT_LABELS[task.getRepeatInterval()]); if (task.hasStopRepeatingDate()) ((TextView) findViewById(R.id.text_repeat_2)).setText(DateFormat.format("'until' MM/dd/yy 'at' h:mm AA", task.getStopRepeatingDateCal())); else ((TextView) findViewById(R.id.text_repeat_2)).setText(R.string.text_no_stop_repeating_date); } else { ((TextView) findViewById(R.id.text_repeat)).setText(R.string.text_no_repetition); ((TextView) findViewById(R.id.text_repeat_2)).setVisibility(View.GONE); } // Set notes ((TextView) findViewById(R.id.text_notes)).setText(task.getNotes()); // Set date created ((TextView) findViewById(R.id.text_date_created)).setText(DateFormat.format("MM/dd/yy 'at' h:mm AA", task.getDateCreatedCal())); // Set date modified ((TextView) findViewById(R.id.text_date_modified)).setText(DateFormat.format("MM/dd/yy 'at' h:mm AA", task.getDateModifiedCal())); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_task); // Allow Action bar icon to act as a button ActionBar action_bar = getSupportActionBar(); action_bar.setHomeButtonEnabled(true); action_bar.setDisplayHomeAsUpEnabled(true); // Get instance of the db data_source = TasksDataSource.getInstance(this); // Get the task from the intent task = data_source.getTask(getIntent().getIntExtra(Task.EXTRA_TASK_ID, 0)); // Set name ((TextView) findViewById(R.id.text_view_task_name)).setText(task.getName()); // Set completion button Button button = (Button) findViewById(R.id.button_complete_task); if (!task.isCompleted()) button.setText(R.string.button_not_completed); else button.setText(R.string.button_completed); button.setOnClickListener(this); // Set priority ((TextView) findViewById(R.id.text_priority)).setText(Task.LABELS[task.getPriority()]); // Set priority icon switch (task.getPriority()) { case Task.URGENT: ((ImageView) findViewById(R.id.image_priority)).setImageResource(R.drawable.ic_urgent); break; case Task.NORMAL: ((ImageView) findViewById(R.id.image_priority)).setImageResource(R.drawable.ic_normal); break; case Task.TRIVIAL: ((ImageView) findViewById(R.id.image_priority)).setImageResource(R.drawable.ic_trivial); break; } // Set category (if category ID is not 1, i.e. no category) if (task.getCategory() != 1) { Category category = data_source.getCategory(task.getCategory()); ((ImageView) findViewById(R.id.image_category)).setBackgroundColor(category.getColor()); ((TextView) findViewById(R.id.text_category)).setText(category.getName()); } // Set due date if (task.hasDateDue()) ((TextView) findViewById(R.id.text_date_due)).setText(DateFormat.format("MM/dd/yy 'at' h:mm AA", task.getDateDueCal())); else ((TextView) findViewById(R.id.text_date_due)).setText(R.string.text_no_due_date); // Set final due date if (task.hasFinalDateDue()) ((TextView) findViewById(R.id.text_alarm)).setText(DateFormat.format("MM/dd/yy 'at' h:mm AA", task.getFinalDateDueCal())); else ((TextView) findViewById(R.id.text_alarm)).setText(R.string.text_no_final_due_date); // Set repetition if (task.isRepeating()) { ((TextView) findViewById(R.id.text_repeat)).setText("Repeat every " + task.getRepeatInterval() + ' ' + Task.REPEAT_LABELS[task.getRepeatType()]); if (task.hasStopRepeatingDate()) ((TextView) findViewById(R.id.text_repeat_2)).setText(DateFormat.format("'until' MM/dd/yy 'at' h:mm AA", task.getStopRepeatingDateCal())); else ((TextView) findViewById(R.id.text_repeat_2)).setText(R.string.text_no_stop_repeating_date); } else { ((TextView) findViewById(R.id.text_repeat)).setText(R.string.text_no_repetition); ((TextView) findViewById(R.id.text_repeat_2)).setVisibility(View.GONE); } // Set notes ((TextView) findViewById(R.id.text_notes)).setText(task.getNotes()); // Set date created ((TextView) findViewById(R.id.text_date_created)).setText(DateFormat.format("MM/dd/yy 'at' h:mm AA", task.getDateCreatedCal())); // Set date modified ((TextView) findViewById(R.id.text_date_modified)).setText(DateFormat.format("MM/dd/yy 'at' h:mm AA", task.getDateModifiedCal())); }
diff --git a/src/mecanique/Spring.java b/src/mecanique/Spring.java index 7d5a393..9cab6b0 100644 --- a/src/mecanique/Spring.java +++ b/src/mecanique/Spring.java @@ -1,55 +1,62 @@ package mecanique; import java.awt.Color; import java.awt.geom.Point2D; public class Spring extends RubberBand { protected static final double RIGOR = 0.8666; public Spring(PhysicalObject l, PhysicalObject r) { super(l, r); } @Override protected Color getTenseColor() { return Color.PINK; } @Override protected Color getNormalColor() { return Color.GRAY; } @Override public Point2D getAcceleration(PhysicalObject object) { double d = distance(); double f = Math.abs(RIGOR * (d - LENGTH)); double theta = Math.atan2(getY2() - getY1(), getX2() - getX1()); - int direction = object == left_object ? 1 : -1; int invert = d < LENGTH ? -1 : 1; + int direction; + if (object == left_object) + direction = 1; + else if (object == right_object) + direction = -1; + // Ignorer les objets qui ne sont pas attachés à l'élastique + else + direction = 0; return new Point2D.Double( invert * direction * f * Math.cos(theta), invert * direction * f * Math.sin(theta) ); } public static class Placement extends RubberBand.Placement { protected Placement(SystemDisplay panneau) { super(panneau); } @Override protected RubberBand getInstance(PhysicalObject left_po) { return new Spring(left_po, null); } @Override public String getName() { return "Ressort"; } } }
false
true
public Point2D getAcceleration(PhysicalObject object) { double d = distance(); double f = Math.abs(RIGOR * (d - LENGTH)); double theta = Math.atan2(getY2() - getY1(), getX2() - getX1()); int direction = object == left_object ? 1 : -1; int invert = d < LENGTH ? -1 : 1; return new Point2D.Double( invert * direction * f * Math.cos(theta), invert * direction * f * Math.sin(theta) ); }
public Point2D getAcceleration(PhysicalObject object) { double d = distance(); double f = Math.abs(RIGOR * (d - LENGTH)); double theta = Math.atan2(getY2() - getY1(), getX2() - getX1()); int invert = d < LENGTH ? -1 : 1; int direction; if (object == left_object) direction = 1; else if (object == right_object) direction = -1; // Ignorer les objets qui ne sont pas attachés à l'élastique else direction = 0; return new Point2D.Double( invert * direction * f * Math.cos(theta), invert * direction * f * Math.sin(theta) ); }
diff --git a/alvis/plugins/de.unisiegen.informatik.bs.alvis.compiler/src/de/unisiegen/informatik/bs/alvis/compiler/CompilerAccess.java b/alvis/plugins/de.unisiegen.informatik.bs.alvis.compiler/src/de/unisiegen/informatik/bs/alvis/compiler/CompilerAccess.java index f317218..351c345 100644 --- a/alvis/plugins/de.unisiegen.informatik.bs.alvis.compiler/src/de/unisiegen/informatik/bs/alvis/compiler/CompilerAccess.java +++ b/alvis/plugins/de.unisiegen.informatik.bs.alvis.compiler/src/de/unisiegen/informatik/bs/alvis/compiler/CompilerAccess.java @@ -1,821 +1,824 @@ package de.unisiegen.informatik.bs.alvis.compiler; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.Token; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Platform; import de.uni_siegen.informatik.bs.alvic.AbstractTLexer; import de.uni_siegen.informatik.bs.alvic.Compiler; import de.uni_siegen.informatik.bs.alvic.TParser; import de.unisiegen.informatik.bs.alvis.io.files.FileCopy; import de.unisiegen.informatik.bs.alvis.io.logger.Logger; import de.unisiegen.informatik.bs.alvis.primitive.datatypes.PCObject; /** * @author mays * @author Colin Benner * @author Eduard Boos * */ public class CompilerAccess { /** * The compiler used to do all the real work. */ private Compiler compiler; /** * These are the types the user may use. */ private Collection<PCObject> types; /** * These are the packages available to the user. They will automatically be * imported by the compiler. */ private Collection<String> packages; /** * This is the absolute path to the file that is to be compiled. */ private String algorithmPath = null; /** * This is the generated Java code. */ private String javaCode; private static CompilerAccess instance; /** * This is used to translate token names to the corresponding characters. */ private static Map<String, List<String>> translateCompletion = null; /** * Add possible results for a given key. * * @param key * The token name to translate. * @param arg * The possible characters. */ private static void add(String key, String... arg) { translateCompletion.put(key, Arrays.asList(arg)); } /** * Fill the translateCompletion map. */ private void loadTranslation() { translateCompletion = new HashMap<String, List<String>>(); add("MAIN", "main "); add("IF", "if ("); add("FOR", "for "); add("WHILE", "while ("); add("IN", "in "); add("RETURN", "return"); add("SIGN", "+", "-"); add("BANG", "!"); add("EQUAL", "="); add("PLUS", "+"); add("MINUS", "-"); add("STAR", "*"); add("SLASH", "/"); add("PERCENT", "%"); add("AMPAMP", "&&"); add("PIPEPIPE", "||"); add("EQEQ", "=="); add("BANGEQ", "!="); add("LESS", "<"); add("GREATER", ">"); add("LESSEQ", "<="); add("GREATEREQ", ">="); add("LPAREN", "("); add("RPAREN", ")"); add("LARRAY", "["); add("RARRAY", "]"); add("SEMICOLON", ";"); add("COMMA", ","); add("COLON", ":"); add("DOT", "."); add("SCOPEL", "begin", "{"); add("SCOPER", "end", "}"); add("NULL", "null"); add("BOOL", "false", "true"); add("INFTY", "infty"); translateCompletion.put("TYPE", new ArrayList<String>(AbstractTLexer.getTypes())); } public static CompilerAccess getDefault() { if (instance == null) instance = new CompilerAccess(); return instance; } /** * Compile the source found at algorithmPath. * * @return The File representing the file containing the generated Java * code. * @throws RecognitionException * @throws IOException */ public File compile() throws RecognitionException, IOException { return compile(algorithmPath, true); } /** * Use the compiler to compile the source code found in the given file. * Before calling this method you should provide the names of all packages * and classes that the user may use (using the setDatatypes and * setDatatypePackages methods). * * @param path * path to the source code that * @return path to the generated .java file if it exists, null otherwise * * @throws IOException */ public File compile(String path) throws IOException { return compile(path, false); } /** * Use the compiler to compile the source code found in the given file. * Before calling this method you should provide the names of all packages * and classes that the user may use (using the setDatatypes and * setDatatypePackages methods). * * @param path * path to the source code that we want to compile. * @param isAbsolutePath * true if the path is absolute. * @return path to the generated .java file if it exists, null otherwise * * @throws IOException */ public File compile(String path, Boolean isAbsolutePath) throws IOException { if (isAbsolutePath) algorithmPath = path; else algorithmPath = currentPath() + path; compileString(readFile(algorithmPath)); if (null == javaCode) return null; return writeJavaCode(getWorkspacePath(algorithmPath), "Algorithm"); } /** * Write the generated Java code to a file. The file will be placed in the * given directory and will be called 'algorithmName + ".java"'. * * @param directory * The directory in which the file will be created. * @param algorithmName * The name of the class used for the algorithm. * @return the file with the Java source code. * @throws IOException */ public File writeJavaCode(File directory, String algorithmName) throws IOException { File result = null; BufferedWriter out = null; FileWriter fstream; try { result = new File(directory, algorithmName + ".java"); fstream = new FileWriter(result); out = new BufferedWriter(fstream); out.write(javaCode.replaceAll("#ALGORITHM_NAME#", algorithmName)); } finally { if (out != null) out.close(); } return result; } /** * Given the pseudo code to compile create a string containing the generated * Java code. * * @param code * The pseudo code to be compiled. * @return the Java code the compiler generated. * @throws IOException */ public String compileString(String code) throws IOException { compiler = new Compiler(types, packages); loadTranslation(); return javaCode = compiler.compile(code); } public String generateLatex(String code) throws IOException { compiler = new Compiler(types, packages); return compiler.compile(code, "LaTeX.stg"); } /** * Run lexer, parser and the type checker on the code given. * * @param code * The code to check. * @return list of the exceptions created when lexing, parsing and type * checking the code. */ public List<RecognitionException> checkCode(String code) { compiler = new Compiler(types, packages); return compiler.check(code); } /** * @return path to working directory. */ private String currentPath() { return Platform.getInstanceLocation().getURL().getPath(); } /** * Get parent directory of the file given by its path. * * @param fileWithPath * The file of which we want to get the parent directory. * @return the path to the parent directory. */ private File getWorkspacePath(String fileWithPath) { return new File(fileWithPath).getAbsoluteFile().getParentFile(); } /** * Read a file given by its path into a String. * * @param fileName * the file to read * @return the contents of the file * @throws IOException */ private String readFile(String fileName) throws IOException { BufferedReader fstream = new BufferedReader(new FileReader(fileName)); String result = ""; while (fstream.ready()) result += fstream.readLine() + System.getProperty("line.separator"); return result; } /** * Translates the token names given into the PseudoCode representation. * * @param possibleTokens * the token to translate * @return the List of translated Strings. */ private List<String> translateAutocompletionString( List<String> possibleTokens) { ArrayList<String> translatedCompletions = new ArrayList<String>(); for (String toTranslate : possibleTokens) { List<String> translations = translateCompletion.get(toTranslate); if (null == translations) translatedCompletions.add(toTranslate); else for (String t : translations) translatedCompletions.add(t); } return translatedCompletions; } /** * Finds the previous Token to the position given. * * @param the * line of the Position * @param charPositionInLine * the offset in the line. * @return the previous token to the position given. Null if the given * position is the first Token. */ private Token findPreviousToken(int line, int charPositionInLine) { Token currentToken = compiler.getLexer().getTokenByNumbers(line, charPositionInLine); if (currentToken != null && ((currentToken.getLine() < line || (currentToken .getCharPositionInLine() + currentToken.getText() .length()) < charPositionInLine))) { currentToken = null; } Token previousToken = null; /* * currentToken is null, when Whitespace is currentChar --> find * previous Token */ if (currentToken == null) { List<Token> tokens = compiler.getLexer().getTokens(); for (Token token : tokens) { if (line > token.getLine() || ((line == token.getLine()) && charPositionInLine >= token .getCharPositionInLine())) { currentToken = token; } else { return currentToken; } } } else { int previousTokenIndex = currentToken.getTokenIndex() - 1; // channel = 99 indicates a whitespace or comment token while (previousToken == null || previousToken.getChannel() == 99) { if (previousTokenIndex < 0) { break; } else { previousToken = compiler.getLexer().getTokens() .get(previousTokenIndex); previousTokenIndex--; } } } /* previousToken is null when, the token to Complete is the first token */ return previousToken; } /** * Returns the ArrayList<String[]> containing all variables declared until * this line at charPositionInLine. * * @param line * the line * @param charPositionInLine * the offset in the line given * @return the ArrayList<String[]> containing all variables declared until * the position given by the parameters. The String Array contains * the Type at index 0 and the variable name at index 1; */ private ArrayList<String[]> getDefinedVariables(int line, int charPositionInLine) { /* HashMap contains varName -> Type entry */ // HashMap<String,String> variables = new HashMap<String,String>(); ArrayList<String[]> variables = new ArrayList<String[]>(); List<Token> tokenList = getTokens(); for (Token token : tokenList) { if (token.getType() != -1 && getTokenName(token.getType()).equals("TYPE")) { if (token.getLine() <= line && token.getCharPositionInLine() <= charPositionInLine) { /* * This Token can be start of variable definition and fits * the condition */ int tokenIndex = token.getTokenIndex(); if ((tokenIndex) <= tokenList.size()) ; Token nextToken = tokenList.get(tokenIndex + 1); String nextTokenName = getTokenName(nextToken.getType()); if (nextTokenName.equals("ID")) { String[] variableSet = { nextToken.getText(), token.getText() }; variables.add(variableSet); } } } } return variables; } /** * @return exceptions produced when lexing, parsing and type checking the * code. */ public List<RecognitionException> getExceptions() { return compiler.getExceptions(); } /** * This method copies the Dummy Algorithm file next to the PCAlgorithm file * that is written by the user. To get the path of the created file see * getAlgorithmPath(). * * @param pathToAlgorithm * relative to Alvis-workspace e.g.: "project/src/Algorithm.algo" * @return Name of the Java Algorithm file */ public File compileThisDummy(String pathToAlgorithm) { String SLASH = File.separator; // the path were the translated java file is. String pathWhereTheJavaIs = ""; try { pathWhereTheJavaIs = FileLocator .getBundleFile(Activator.getDefault().getBundle()) .getCanonicalPath().toString(); } catch (IOException e) { e.printStackTrace(); } // The compiled algorithm File source = new File(pathWhereTheJavaIs + SLASH + "Algorithm.java"); // Get the path to algorithm and separate path and filename String algoWorkSpacePath = new File(pathToAlgorithm).getParent(); algorithmPath = currentPath() + algoWorkSpacePath + SLASH; File destination = new File(algorithmPath + "Algorithm.java"); // Copy compiled file into the workspace FileCopy fileCopy = new FileCopy(); fileCopy.copy(source, destination); return destination; } /** * @return a list of all type names available for the user. */ public Collection<String> getDatatypes() { return compiler.getDatatypes(); } /** * Tell the compiler which types are allowed. * * @param datatypes * the types */ public void setDatatypes(Collection<PCObject> datatypes) { this.types = datatypes; } /** * Tell the compiler which packages the user can use. I.e. what packages the * compiler is supposed to import. * * @param datatypePackages * the packages */ public void setDatatypePackages(Collection<String> datatypePackages) { this.packages = datatypePackages; } /** * Tell the lexer to read the input stream so it can provide auto completion * and help for syntax highlighting. */ public void reLex() { compiler.getLexer().scan(); } /** * Computes the possible autoCompletion for the line and charPositionInLine * given. Returns a List containing all available completions as * CompletionInformation. * * @param line * the line * @param charPositionInLine * the offset in the line given * @return the List of CompletionInformation available at this line at * charPositionInLine. */ public List<CompletionInformation> tryAutoCompletion(int line, int charPositionInLine) { Token tokenToComplete = compiler.getLexer().getTokenByNumbers(line, charPositionInLine); if (tokenToComplete != null && ((tokenToComplete.getLine() < line || (tokenToComplete .getCharPositionInLine() + tokenToComplete.getText() .length()) < charPositionInLine))) { tokenToComplete = null; } int prefixLength = 0; String prefix = ""; if (tokenToComplete != null) { /* * getPrefix and prefixLength and override line and * charPositionInLine */ prefixLength = charPositionInLine - tokenToComplete.getCharPositionInLine(); prefix = tokenToComplete.getText().substring(0, prefixLength); line = tokenToComplete.getLine(); charPositionInLine = tokenToComplete.getCharPositionInLine(); } Token previousToken = null; if (tokenToComplete != null && (tokenToComplete.getText().equals(".") || tokenToComplete.getText().equals("(") || tokenToComplete .getText().equals("{"))) { previousToken = tokenToComplete; prefix = ""; prefixLength = 0; charPositionInLine = tokenToComplete.getCharPositionInLine() + tokenToComplete.getText().length(); } else { previousToken = findPreviousToken(line, charPositionInLine); } List<CompletionInformation> availableProposals = new ArrayList<CompletionInformation>(); if (previousToken == null) { /** current token is first token */ List<Token> tokens = compiler.getLexer().getTokens(); boolean containsMain = false; for (Token currToken : tokens) { if (getTokenName(currToken.getType()) != null && getTokenName(currToken.getType()).equals("MAIN")) { containsMain = true; } } if (!containsMain) { prefixLength = charPositionInLine; - prefix = tokenToComplete.getText().substring(0, prefixLength); - line = tokenToComplete.getLine(); - charPositionInLine = tokenToComplete.getCharPositionInLine(); + if(tokenToComplete!=null) + { + prefix = tokenToComplete.getText().substring(0, prefixLength); + line = tokenToComplete.getLine(); + charPositionInLine = tokenToComplete.getCharPositionInLine(); + } availableProposals.add(new CompletionInformation("main", line, charPositionInLine, prefixLength)); } } else { /* * previousToken was set --> get possibleFollowing Tokens and create * code-Completion Information */ List<String> possibleTokens = compiler.getParser() .possibleFollowingTokens(TParser.class, getTokenName(previousToken.getType())); /* Remove the tokens which should not be completed */ possibleTokens.remove("DOT"); List<String> viableCompletionStrings = translateAutocompletionString(possibleTokens); /* Some cases have to be handled separately */ /* Handle SEMICOLON Token */ if (getTokenName(previousToken.getType()).equals("SEMICOLON")) { /* add all variable names which are available at this position */ ArrayList<String[]> definedVariables = getDefinedVariables( line, charPositionInLine); Iterator<String[]> iterator = definedVariables.iterator(); while (iterator.hasNext()) { String[] varSet = iterator.next(); if (varSet.length == 2) { viableCompletionStrings.add(varSet[0]); } } viableCompletionStrings.addAll(AbstractTLexer.getTypes()); } /* EndOf Handle SEMICOLON token */ /* Handle ID Token */ if (possibleTokens.contains("ID")) { if (getTokenName(previousToken.getType()).equals("DOT")) { /* getting full prefix(until whitespace is found */ int currentTokenIndex = previousToken.getTokenIndex() - 1; Token currentToken = compiler.getLexer().getTokens() .get(currentTokenIndex); String stillPrefix = "ID"; Stack<String> idToTest = new Stack<String>(); while (currentTokenIndex > 0 && getTokenName(currentToken.getType()).equals( stillPrefix)) { if (stillPrefix.equals("ID")) { idToTest.push(currentToken.getText()); stillPrefix = "DOT"; } else { stillPrefix = "ID"; } currentTokenIndex = currentTokenIndex - 1; currentToken = compiler.getLexer().getTokens() .get(currentTokenIndex); } List<Token> identifiers = getIdentifiers(); if (!idToTest.isEmpty()) { String firstID = idToTest.pop(); /* getting first index of id */ int idIndex = -1; for (int i = 0; i < identifiers.size(); i++) { Token token = identifiers.get(i); if (token.getText().equals(firstID)) { idIndex = i; break; } } if (idIndex != -1) { Token varToken = identifiers.get(idIndex); Token varType = getTokens().get( varToken.getTokenIndex() - 1); if (getTokenName(varType.getType()).equals("TYPE")) { for (PCObject dataType : this.types) { try { String type = (dataType.getClass()) .getMethod("getTypeName", null) .invoke(null, null).toString(); if (type.equals(varType.getText())) { viableCompletionStrings .addAll(dataType .getMembers()); /* * add () to mark methods as methods */ List<String> methods = dataType .getMethods(); for (String method : methods) { viableCompletionStrings .add(method + "()"); } } } catch (IllegalArgumentException e) { Logger.getInstance() .log("alvis.compiler->CompilerAccess", Logger.ERROR, "IlligelArgumentException in tryAutoCompletion : " + e.getMessage()); } catch (SecurityException e) { Logger.getInstance() .log("alvis.compiler->CompilerAccess", Logger.ERROR, "IlligelArgumentException in tryAutoCompletion : " + e.getMessage()); } catch (IllegalAccessException e) { Logger.getInstance() .log("alvis.compiler->CompilerAccess", Logger.ERROR, "IlligelArgumentException in tryAutoCompletion : " + e.getMessage()); } catch (InvocationTargetException e) { Logger.getInstance() .log("alvis.compiler->CompilerAccess", Logger.ERROR, "IlligelArgumentException in tryAutoCompletion : " + e.getMessage()); } catch (NoSuchMethodException e) { Logger.getInstance() .log("alvis.compiler->CompilerAccess", Logger.ERROR, "IlligelArgumentException in tryAutoCompletion : " + e.getMessage()); } } } } } } } /* EndOF Handle ID */ /* * create a CompletionInformation Object if prefix fits the * viableCompletionString */ for (String completionString : viableCompletionStrings) { if (completionString.startsWith(prefix)) { CompletionInformation completionInfomation = new CompletionInformation( completionString, line, charPositionInLine, prefixLength); availableProposals.add(completionInfomation); } } } return availableProposals; } /** * @return List of Tokens that are forbidden because they are Java keywords. */ public List<Token> getForbidden() { return compiler.getLexer().getForbidden(); } /** * @return List of all identifiers used in the code */ public List<Token> getIdentifiers() { return compiler.getLexer().getIdentifiers(); } /** * @return List of all keywords the compiler recognizes (e.g. 'if', 'else', * ...) */ public List<Token> getKeywords() { return compiler.getLexer().getKeywords(); } /** * Create a list of all the tokens in the given source code that mark the * beginning of a block. * * @return List of tokens that mark the beginning of a block */ public List<Token> beginBlock() { return compiler.getLexer().beginBlock(); } /** * Create a list of all the tokens in the given source code that mark the * end of a block. * * @return List of tokens that mark the end of a block */ public List<Token> endBlock() { return compiler.getLexer().endBlock(); } /** * @return List of all available keywords. */ public List<String> allKeywords() { return AbstractTLexer.allKeywords(); } /** * Return a list of all the Java keywords that the pseudo code does not use. * * @return List of forbidden words */ public List<String> allForbidden() { return AbstractTLexer.allForbidden(); } /** * @return List of all tokens created by the lexer. */ public List<Token> getTokens() { return compiler.getLexer().getTokens(); } /** * Translate the internal number of a token type to its name. * * @param tokenNumber * The number to translate. * @return The name of the token type with that number. */ public String getTokenName(int tokenNumber) { return compiler.getParser().getTokenName(tokenNumber); } /** * Method for checking whether the compiler is informed correctly about * available packages and types. */ @SuppressWarnings("unchecked") public void testDatatypes() { try { System.out.println("Compiler shows its datatypes:"); for (PCObject obj : types) { System.out.println(obj.getClass()); List<String> tmp = ((List<String>) obj.getClass() .getMethod("getMembers").invoke(obj)); System.out.println("available attributes:" + (tmp == null ? "null" : tmp)); tmp = ((List<String>) obj.getClass().getMethod("getMethods") .invoke(obj)); System.out.println("available methods:" + (tmp == null ? "null" : tmp)); } System.out.println("Compiler shows its packages:"); for (String obj : packages) { System.out.println(obj); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } }
true
true
public List<CompletionInformation> tryAutoCompletion(int line, int charPositionInLine) { Token tokenToComplete = compiler.getLexer().getTokenByNumbers(line, charPositionInLine); if (tokenToComplete != null && ((tokenToComplete.getLine() < line || (tokenToComplete .getCharPositionInLine() + tokenToComplete.getText() .length()) < charPositionInLine))) { tokenToComplete = null; } int prefixLength = 0; String prefix = ""; if (tokenToComplete != null) { /* * getPrefix and prefixLength and override line and * charPositionInLine */ prefixLength = charPositionInLine - tokenToComplete.getCharPositionInLine(); prefix = tokenToComplete.getText().substring(0, prefixLength); line = tokenToComplete.getLine(); charPositionInLine = tokenToComplete.getCharPositionInLine(); } Token previousToken = null; if (tokenToComplete != null && (tokenToComplete.getText().equals(".") || tokenToComplete.getText().equals("(") || tokenToComplete .getText().equals("{"))) { previousToken = tokenToComplete; prefix = ""; prefixLength = 0; charPositionInLine = tokenToComplete.getCharPositionInLine() + tokenToComplete.getText().length(); } else { previousToken = findPreviousToken(line, charPositionInLine); } List<CompletionInformation> availableProposals = new ArrayList<CompletionInformation>(); if (previousToken == null) { /** current token is first token */ List<Token> tokens = compiler.getLexer().getTokens(); boolean containsMain = false; for (Token currToken : tokens) { if (getTokenName(currToken.getType()) != null && getTokenName(currToken.getType()).equals("MAIN")) { containsMain = true; } } if (!containsMain) { prefixLength = charPositionInLine; prefix = tokenToComplete.getText().substring(0, prefixLength); line = tokenToComplete.getLine(); charPositionInLine = tokenToComplete.getCharPositionInLine(); availableProposals.add(new CompletionInformation("main", line, charPositionInLine, prefixLength)); } } else { /* * previousToken was set --> get possibleFollowing Tokens and create * code-Completion Information */ List<String> possibleTokens = compiler.getParser() .possibleFollowingTokens(TParser.class, getTokenName(previousToken.getType())); /* Remove the tokens which should not be completed */ possibleTokens.remove("DOT"); List<String> viableCompletionStrings = translateAutocompletionString(possibleTokens); /* Some cases have to be handled separately */ /* Handle SEMICOLON Token */ if (getTokenName(previousToken.getType()).equals("SEMICOLON")) { /* add all variable names which are available at this position */ ArrayList<String[]> definedVariables = getDefinedVariables( line, charPositionInLine); Iterator<String[]> iterator = definedVariables.iterator(); while (iterator.hasNext()) { String[] varSet = iterator.next(); if (varSet.length == 2) { viableCompletionStrings.add(varSet[0]); } } viableCompletionStrings.addAll(AbstractTLexer.getTypes()); } /* EndOf Handle SEMICOLON token */ /* Handle ID Token */ if (possibleTokens.contains("ID")) { if (getTokenName(previousToken.getType()).equals("DOT")) { /* getting full prefix(until whitespace is found */ int currentTokenIndex = previousToken.getTokenIndex() - 1; Token currentToken = compiler.getLexer().getTokens() .get(currentTokenIndex); String stillPrefix = "ID"; Stack<String> idToTest = new Stack<String>(); while (currentTokenIndex > 0 && getTokenName(currentToken.getType()).equals( stillPrefix)) { if (stillPrefix.equals("ID")) { idToTest.push(currentToken.getText()); stillPrefix = "DOT"; } else { stillPrefix = "ID"; } currentTokenIndex = currentTokenIndex - 1; currentToken = compiler.getLexer().getTokens() .get(currentTokenIndex); } List<Token> identifiers = getIdentifiers(); if (!idToTest.isEmpty()) { String firstID = idToTest.pop(); /* getting first index of id */ int idIndex = -1; for (int i = 0; i < identifiers.size(); i++) { Token token = identifiers.get(i); if (token.getText().equals(firstID)) { idIndex = i; break; } } if (idIndex != -1) { Token varToken = identifiers.get(idIndex); Token varType = getTokens().get( varToken.getTokenIndex() - 1); if (getTokenName(varType.getType()).equals("TYPE")) { for (PCObject dataType : this.types) { try { String type = (dataType.getClass()) .getMethod("getTypeName", null) .invoke(null, null).toString(); if (type.equals(varType.getText())) { viableCompletionStrings .addAll(dataType .getMembers()); /* * add () to mark methods as methods */ List<String> methods = dataType .getMethods(); for (String method : methods) { viableCompletionStrings .add(method + "()"); } } } catch (IllegalArgumentException e) { Logger.getInstance() .log("alvis.compiler->CompilerAccess", Logger.ERROR, "IlligelArgumentException in tryAutoCompletion : " + e.getMessage()); } catch (SecurityException e) { Logger.getInstance() .log("alvis.compiler->CompilerAccess", Logger.ERROR, "IlligelArgumentException in tryAutoCompletion : " + e.getMessage()); } catch (IllegalAccessException e) { Logger.getInstance() .log("alvis.compiler->CompilerAccess", Logger.ERROR, "IlligelArgumentException in tryAutoCompletion : " + e.getMessage()); } catch (InvocationTargetException e) { Logger.getInstance() .log("alvis.compiler->CompilerAccess", Logger.ERROR, "IlligelArgumentException in tryAutoCompletion : " + e.getMessage()); } catch (NoSuchMethodException e) { Logger.getInstance() .log("alvis.compiler->CompilerAccess", Logger.ERROR, "IlligelArgumentException in tryAutoCompletion : " + e.getMessage()); } } } } } } } /* EndOF Handle ID */ /* * create a CompletionInformation Object if prefix fits the * viableCompletionString */ for (String completionString : viableCompletionStrings) { if (completionString.startsWith(prefix)) { CompletionInformation completionInfomation = new CompletionInformation( completionString, line, charPositionInLine, prefixLength); availableProposals.add(completionInfomation); } } } return availableProposals; }
public List<CompletionInformation> tryAutoCompletion(int line, int charPositionInLine) { Token tokenToComplete = compiler.getLexer().getTokenByNumbers(line, charPositionInLine); if (tokenToComplete != null && ((tokenToComplete.getLine() < line || (tokenToComplete .getCharPositionInLine() + tokenToComplete.getText() .length()) < charPositionInLine))) { tokenToComplete = null; } int prefixLength = 0; String prefix = ""; if (tokenToComplete != null) { /* * getPrefix and prefixLength and override line and * charPositionInLine */ prefixLength = charPositionInLine - tokenToComplete.getCharPositionInLine(); prefix = tokenToComplete.getText().substring(0, prefixLength); line = tokenToComplete.getLine(); charPositionInLine = tokenToComplete.getCharPositionInLine(); } Token previousToken = null; if (tokenToComplete != null && (tokenToComplete.getText().equals(".") || tokenToComplete.getText().equals("(") || tokenToComplete .getText().equals("{"))) { previousToken = tokenToComplete; prefix = ""; prefixLength = 0; charPositionInLine = tokenToComplete.getCharPositionInLine() + tokenToComplete.getText().length(); } else { previousToken = findPreviousToken(line, charPositionInLine); } List<CompletionInformation> availableProposals = new ArrayList<CompletionInformation>(); if (previousToken == null) { /** current token is first token */ List<Token> tokens = compiler.getLexer().getTokens(); boolean containsMain = false; for (Token currToken : tokens) { if (getTokenName(currToken.getType()) != null && getTokenName(currToken.getType()).equals("MAIN")) { containsMain = true; } } if (!containsMain) { prefixLength = charPositionInLine; if(tokenToComplete!=null) { prefix = tokenToComplete.getText().substring(0, prefixLength); line = tokenToComplete.getLine(); charPositionInLine = tokenToComplete.getCharPositionInLine(); } availableProposals.add(new CompletionInformation("main", line, charPositionInLine, prefixLength)); } } else { /* * previousToken was set --> get possibleFollowing Tokens and create * code-Completion Information */ List<String> possibleTokens = compiler.getParser() .possibleFollowingTokens(TParser.class, getTokenName(previousToken.getType())); /* Remove the tokens which should not be completed */ possibleTokens.remove("DOT"); List<String> viableCompletionStrings = translateAutocompletionString(possibleTokens); /* Some cases have to be handled separately */ /* Handle SEMICOLON Token */ if (getTokenName(previousToken.getType()).equals("SEMICOLON")) { /* add all variable names which are available at this position */ ArrayList<String[]> definedVariables = getDefinedVariables( line, charPositionInLine); Iterator<String[]> iterator = definedVariables.iterator(); while (iterator.hasNext()) { String[] varSet = iterator.next(); if (varSet.length == 2) { viableCompletionStrings.add(varSet[0]); } } viableCompletionStrings.addAll(AbstractTLexer.getTypes()); } /* EndOf Handle SEMICOLON token */ /* Handle ID Token */ if (possibleTokens.contains("ID")) { if (getTokenName(previousToken.getType()).equals("DOT")) { /* getting full prefix(until whitespace is found */ int currentTokenIndex = previousToken.getTokenIndex() - 1; Token currentToken = compiler.getLexer().getTokens() .get(currentTokenIndex); String stillPrefix = "ID"; Stack<String> idToTest = new Stack<String>(); while (currentTokenIndex > 0 && getTokenName(currentToken.getType()).equals( stillPrefix)) { if (stillPrefix.equals("ID")) { idToTest.push(currentToken.getText()); stillPrefix = "DOT"; } else { stillPrefix = "ID"; } currentTokenIndex = currentTokenIndex - 1; currentToken = compiler.getLexer().getTokens() .get(currentTokenIndex); } List<Token> identifiers = getIdentifiers(); if (!idToTest.isEmpty()) { String firstID = idToTest.pop(); /* getting first index of id */ int idIndex = -1; for (int i = 0; i < identifiers.size(); i++) { Token token = identifiers.get(i); if (token.getText().equals(firstID)) { idIndex = i; break; } } if (idIndex != -1) { Token varToken = identifiers.get(idIndex); Token varType = getTokens().get( varToken.getTokenIndex() - 1); if (getTokenName(varType.getType()).equals("TYPE")) { for (PCObject dataType : this.types) { try { String type = (dataType.getClass()) .getMethod("getTypeName", null) .invoke(null, null).toString(); if (type.equals(varType.getText())) { viableCompletionStrings .addAll(dataType .getMembers()); /* * add () to mark methods as methods */ List<String> methods = dataType .getMethods(); for (String method : methods) { viableCompletionStrings .add(method + "()"); } } } catch (IllegalArgumentException e) { Logger.getInstance() .log("alvis.compiler->CompilerAccess", Logger.ERROR, "IlligelArgumentException in tryAutoCompletion : " + e.getMessage()); } catch (SecurityException e) { Logger.getInstance() .log("alvis.compiler->CompilerAccess", Logger.ERROR, "IlligelArgumentException in tryAutoCompletion : " + e.getMessage()); } catch (IllegalAccessException e) { Logger.getInstance() .log("alvis.compiler->CompilerAccess", Logger.ERROR, "IlligelArgumentException in tryAutoCompletion : " + e.getMessage()); } catch (InvocationTargetException e) { Logger.getInstance() .log("alvis.compiler->CompilerAccess", Logger.ERROR, "IlligelArgumentException in tryAutoCompletion : " + e.getMessage()); } catch (NoSuchMethodException e) { Logger.getInstance() .log("alvis.compiler->CompilerAccess", Logger.ERROR, "IlligelArgumentException in tryAutoCompletion : " + e.getMessage()); } } } } } } } /* EndOF Handle ID */ /* * create a CompletionInformation Object if prefix fits the * viableCompletionString */ for (String completionString : viableCompletionStrings) { if (completionString.startsWith(prefix)) { CompletionInformation completionInfomation = new CompletionInformation( completionString, line, charPositionInLine, prefixLength); availableProposals.add(completionInfomation); } } } return availableProposals; }
diff --git a/src/org/xbmc/api/object/Movie.java b/src/org/xbmc/api/object/Movie.java index 6741b76..51f11ad 100644 --- a/src/org/xbmc/api/object/Movie.java +++ b/src/org/xbmc/api/object/Movie.java @@ -1,267 +1,268 @@ /* * Copyright (C) 2005-2009 Team XBMC * http://xbmc.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, 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 XBMC Remote; see the file license. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ package org.xbmc.api.object; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.xbmc.android.jsonrpc.api.model.VideoModel.MovieDetail; import org.xbmc.android.util.Crc32; import org.xbmc.api.type.MediaType; /** * Stores what we can get from the movieview table. * * @author Team XBMC */ public class Movie implements ICoverArt, Serializable, INamedResource { /** * Points to where the movie thumbs are stored */ public final static String THUMB_PREFIX = "special://profile/Thumbnails/Video/"; /** * Constructor * @param id Database ID * @param name Album name * @param artist Artist */ public Movie(int id, String title, int year, String path, String filename, String director, String runtime, String genres, double rating, int numWatched, String imdbId) { this.id = id; this.title = title; this.year = year; this.director.add(director); this.runtime = runtime; this.genres.add(genres); this.rating = rating; this.localPath = path; this.filename = filename; this.numWatched = numWatched; this.imdbId=imdbId; } public Movie(MovieDetail detail) { this.id = detail.movieid; this.title = detail.title; this.year = detail.year; this.director = detail.director; - this.runtime = Integer.toString(detail.runtime); + // runtime is in minutes + this.runtime = Integer.toString(detail.runtime / 60); this.genres = detail.genre; this.rating = detail.rating; this.localPath = ""; this.filename = detail.file; this.numWatched = detail.playcount; this.imdbId = detail.imdbnumber; this.thumbnail = detail.thumbnail; } public int getMediaType() { return MediaType.VIDEO_MOVIE; } /** * Returns the path XBMC needs to play the movie. This can either * localPath + filename or filename only (in case of stacks) * @return */ public String getPath() { if (filename.contains("://")) { return filename; } else { return localPath + filename; } } public String getShortName() { return this.title; } public static String getThumbUri(ICoverArt cover) { if(cover.getThumbnail() != null) { return cover.getThumbnail(); } final String hex = Crc32.formatAsHexLowerCase(cover.getCrc()); return THUMB_PREFIX + hex.charAt(0) + "/" + hex + ".tbn"; } public static String getFallbackThumbUri(ICoverArt cover) { final int crc = cover.getFallbackCrc(); if (crc != 0) { final String hex = Crc32.formatAsHexLowerCase(cover.getFallbackCrc()); return THUMB_PREFIX + hex.charAt(0) + "/" + hex + ".tbn"; } else { return null; } } /** * Returns the CRC of the movie on which the thumb name is based upon. * @return CRC32 */ public long getCrc() { if (thumbID == 0L && filename.startsWith("stack://")) { final String[] file = filename.substring(8).split(" , "); thumbID = Crc32.computeLowerCase(file[0]); } else if (thumbID == 0L) { thumbID = Crc32.computeLowerCase(localPath.concat(filename)); } return thumbID; } /** * If no album thumb CRC is found, try to get the thumb of the album's * directory. * @return 0-char CRC32 */ public int getFallbackCrc() { if (localPath != null && filename != null) { return Crc32.computeLowerCase(localPath); } else { return 0; } } /** * Returns database ID. * @return */ public int getId() { return this.id; } /** * @return The Movie's IMDbId */ public String getIMDbId(){ return this.imdbId; } /** * Returns database ID. * @return */ public String getName() { return title + " (" + year + ")"; } public String getThumbnail() { return thumbnail; } /** * Something descriptive */ public String toString() { return "[" + id + "] " + title + " (" + year + ")"; } /** * Database ID */ private final int id; /** * Movie title */ public final String title; /** * Director(s), can be several separated by " / " */ public List<String> director = new ArrayList<String>(); /** * Runtime, can be several also, separated by " | " */ public final String runtime; /** * Genre(s), can be several, normally separated by " / " */ public List<String> genres = new ArrayList<String>(); /** * Year released, -1 if unknown */ public final int year; /** * Local path of the movie (without file name) */ public final String localPath; /** * File name of the movie */ public final String filename; /** * Rating */ public double rating = 0.0; /** * URL to the trailer, if available. */ public String trailerUrl = null; /** * Movie plot */ public String plot = null; /** * Movie's tagline */ public String tagline = null; /** * Number of votes, -1 if not set. */ public int numVotes = -1; /** * Parental Rating with description (e.g.: "Rated R for strong violence, sexuality, drug use and language.") */ public String rated = null; /** * Studio */ public List<String> studio = new ArrayList<String>(); /** * Number of watched, -1 if not set. */ public final int numWatched; /** * List of actors; */ public ArrayList<Actor> actors = new ArrayList<Actor>(); /** * The movie's imdbId */ private final String imdbId; /** * Save this once it's calculated */ public long thumbID = 0L; public String thumbnail; private static final long serialVersionUID = 4779827915067184250L; }
true
true
public Movie(MovieDetail detail) { this.id = detail.movieid; this.title = detail.title; this.year = detail.year; this.director = detail.director; this.runtime = Integer.toString(detail.runtime); this.genres = detail.genre; this.rating = detail.rating; this.localPath = ""; this.filename = detail.file; this.numWatched = detail.playcount; this.imdbId = detail.imdbnumber; this.thumbnail = detail.thumbnail; }
public Movie(MovieDetail detail) { this.id = detail.movieid; this.title = detail.title; this.year = detail.year; this.director = detail.director; // runtime is in minutes this.runtime = Integer.toString(detail.runtime / 60); this.genres = detail.genre; this.rating = detail.rating; this.localPath = ""; this.filename = detail.file; this.numWatched = detail.playcount; this.imdbId = detail.imdbnumber; this.thumbnail = detail.thumbnail; }
diff --git a/publicMAIN/src/org/publicmain/gui/registrationWindow.java b/publicMAIN/src/org/publicmain/gui/registrationWindow.java index 5bb6ce2..d283adf 100644 --- a/publicMAIN/src/org/publicmain/gui/registrationWindow.java +++ b/publicMAIN/src/org/publicmain/gui/registrationWindow.java @@ -1,213 +1,212 @@ package org.publicmain.gui; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.JTextField; import org.publicmain.sql.BackupDBConnection; public class registrationWindow { private static registrationWindow me; private BackupDBConnection bdb; private JFrame registrationWindowFrame; private JLabel wellcomeLogo; private JLabel wellcomeLabel1; private JLabel nickNameLabel; private JTextField nickNameTextField; private JLabel userNameLabel; private JTextField userNameTextField; private JLabel passWordLabel; private JPasswordField passWordTextField; private JLabel firstNameLabel; private JTextField firstNameTextField; private JLabel lastNameLabel; private JTextField lastNameTextField; private JLabel eMailLabel; private JTextField eMailTextField; private JLabel birthDayLabel; private JTextField birthDayTextField; private JLabel backupserverIPLabel; private JTextField backupserverIPTextField; private JTextField statusTextField; private JButton backButton; private JButton submitButton; private GridBagConstraints c; private Insets set; private registrationWindow() { this.registrationWindowFrame= new JFrame(); this.wellcomeLogo = new JLabel(new ImageIcon(getClass().getResource("textlogo.png"))); this.wellcomeLabel1 = new JLabel("Please Enter your personal data"); this.nickNameLabel = new JLabel("Nickname"); this.nickNameTextField = new JTextField(); this.userNameLabel = new JLabel("Username"); this.userNameTextField = new JTextField(); this.passWordLabel = new JLabel("Password"); this.passWordTextField = new JPasswordField(); this.firstNameLabel = new JLabel("First name"); this.firstNameTextField = new JTextField(); this.lastNameLabel = new JLabel("Last name"); this.lastNameTextField = new JTextField(); this.eMailLabel = new JLabel("eMail"); this.eMailTextField = new JTextField(); this.birthDayLabel = new JLabel("Birthday"); this.birthDayTextField = new JTextField(); this.backupserverIPLabel = new JLabel("IP of your Backupserver"); this.backupserverIPTextField= new JTextField(); this.statusTextField = new JTextField(); this.backButton = new JButton("Apply Changes"); this.submitButton = new JButton("Register"); this.submitButton.addActionListener(new registrationWindowButtonController()); this.backButton.addActionListener(new registrationWindowButtonController()); this.c = new GridBagConstraints(); this.set = new Insets(5, 5, 5, 5); registrationWindowFrame.setTitle("Registration"); registrationWindowFrame.setIconImage(new ImageIcon(getClass().getResource("pM_Logo2.png")).getImage()); registrationWindowFrame.getContentPane().setBackground(Color.WHITE); registrationWindowFrame.setMinimumSize(new Dimension(200, 180)); statusTextField.setBackground(new Color(229, 195, 0)); statusTextField.setEditable(false); registrationWindowFrame.setLayout(new GridBagLayout()); c.insets = set; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.LINE_START; // hinzuf�gen der Komponenten zum startWindowFrame c.gridx = 0; c.gridy = 0; c.gridwidth = 2; registrationWindowFrame.add(wellcomeLogo ,c); c.gridy = 1; c.gridwidth = 2; registrationWindowFrame.add(wellcomeLabel1, c); c.gridy = 2; c.gridwidth = 1; registrationWindowFrame.add(nickNameLabel, c); c.gridx = 1; registrationWindowFrame.add(nickNameTextField, c); c.gridx = 0; c.gridy = 3; registrationWindowFrame.add(userNameLabel, c); c.gridx = 1; registrationWindowFrame.add(userNameTextField, c); c.gridx = 0; c.gridy = 5; registrationWindowFrame.add(passWordLabel, c); c.gridx = 1; registrationWindowFrame.add(passWordTextField, c); c.gridx = 0; c.gridy = 6; registrationWindowFrame.add(firstNameLabel, c); c.gridx = 1; registrationWindowFrame.add(firstNameTextField, c); c.gridx = 0; c.gridy = 7; registrationWindowFrame.add(lastNameLabel, c); c.gridx = 1; registrationWindowFrame.add(lastNameTextField, c); c.gridx = 0; c.gridy = 8; registrationWindowFrame.add(eMailLabel, c); c.gridx = 1; registrationWindowFrame.add(eMailTextField, c); c.gridx = 0; c.gridy = 9; registrationWindowFrame.add(birthDayLabel, c); c.gridx = 1; registrationWindowFrame.add(birthDayTextField, c); c.gridx = 0; c.gridy = 10; registrationWindowFrame.add(backupserverIPLabel, c); c.gridx = 1; registrationWindowFrame.add(backupserverIPTextField, c); c.gridx = 0; c.gridy = 11; c.gridwidth = 2; registrationWindowFrame.add(statusTextField, c); c.gridy = 12; c.gridwidth = 1; registrationWindowFrame.add(backButton, c); c.gridx = 1; registrationWindowFrame.add(submitButton, c); registrationWindowFrame.pack(); registrationWindowFrame.setResizable(false); - registrationWindowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - registrationWindowFrame.setLocationRelativeTo(null); + registrationWindowFrame.setLocationRelativeTo(GUI.getGUI()); registrationWindowFrame.setVisible(true); } public static registrationWindow getRegistrationWindow(){ if (me == null) { me = new registrationWindow(); return me; } else { return me; } } class registrationWindowButtonController implements ActionListener { public registrationWindowButtonController() { } public void actionPerformed(ActionEvent evt) { bdb = BackupDBConnection.getBackupDBConnection(); JButton source = (JButton) evt.getSource(); switch (source.getText()) { case "Apply Changes": //TODO Hier wie gew�nscht das �bernehmen die �nderungen initiieren break; case "Register": bdb.createNewUser(statusTextField, backupserverIPTextField, userNameTextField, passWordTextField); break; } } } }
true
true
private registrationWindow() { this.registrationWindowFrame= new JFrame(); this.wellcomeLogo = new JLabel(new ImageIcon(getClass().getResource("textlogo.png"))); this.wellcomeLabel1 = new JLabel("Please Enter your personal data"); this.nickNameLabel = new JLabel("Nickname"); this.nickNameTextField = new JTextField(); this.userNameLabel = new JLabel("Username"); this.userNameTextField = new JTextField(); this.passWordLabel = new JLabel("Password"); this.passWordTextField = new JPasswordField(); this.firstNameLabel = new JLabel("First name"); this.firstNameTextField = new JTextField(); this.lastNameLabel = new JLabel("Last name"); this.lastNameTextField = new JTextField(); this.eMailLabel = new JLabel("eMail"); this.eMailTextField = new JTextField(); this.birthDayLabel = new JLabel("Birthday"); this.birthDayTextField = new JTextField(); this.backupserverIPLabel = new JLabel("IP of your Backupserver"); this.backupserverIPTextField= new JTextField(); this.statusTextField = new JTextField(); this.backButton = new JButton("Apply Changes"); this.submitButton = new JButton("Register"); this.submitButton.addActionListener(new registrationWindowButtonController()); this.backButton.addActionListener(new registrationWindowButtonController()); this.c = new GridBagConstraints(); this.set = new Insets(5, 5, 5, 5); registrationWindowFrame.setTitle("Registration"); registrationWindowFrame.setIconImage(new ImageIcon(getClass().getResource("pM_Logo2.png")).getImage()); registrationWindowFrame.getContentPane().setBackground(Color.WHITE); registrationWindowFrame.setMinimumSize(new Dimension(200, 180)); statusTextField.setBackground(new Color(229, 195, 0)); statusTextField.setEditable(false); registrationWindowFrame.setLayout(new GridBagLayout()); c.insets = set; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.LINE_START; // hinzuf�gen der Komponenten zum startWindowFrame c.gridx = 0; c.gridy = 0; c.gridwidth = 2; registrationWindowFrame.add(wellcomeLogo ,c); c.gridy = 1; c.gridwidth = 2; registrationWindowFrame.add(wellcomeLabel1, c); c.gridy = 2; c.gridwidth = 1; registrationWindowFrame.add(nickNameLabel, c); c.gridx = 1; registrationWindowFrame.add(nickNameTextField, c); c.gridx = 0; c.gridy = 3; registrationWindowFrame.add(userNameLabel, c); c.gridx = 1; registrationWindowFrame.add(userNameTextField, c); c.gridx = 0; c.gridy = 5; registrationWindowFrame.add(passWordLabel, c); c.gridx = 1; registrationWindowFrame.add(passWordTextField, c); c.gridx = 0; c.gridy = 6; registrationWindowFrame.add(firstNameLabel, c); c.gridx = 1; registrationWindowFrame.add(firstNameTextField, c); c.gridx = 0; c.gridy = 7; registrationWindowFrame.add(lastNameLabel, c); c.gridx = 1; registrationWindowFrame.add(lastNameTextField, c); c.gridx = 0; c.gridy = 8; registrationWindowFrame.add(eMailLabel, c); c.gridx = 1; registrationWindowFrame.add(eMailTextField, c); c.gridx = 0; c.gridy = 9; registrationWindowFrame.add(birthDayLabel, c); c.gridx = 1; registrationWindowFrame.add(birthDayTextField, c); c.gridx = 0; c.gridy = 10; registrationWindowFrame.add(backupserverIPLabel, c); c.gridx = 1; registrationWindowFrame.add(backupserverIPTextField, c); c.gridx = 0; c.gridy = 11; c.gridwidth = 2; registrationWindowFrame.add(statusTextField, c); c.gridy = 12; c.gridwidth = 1; registrationWindowFrame.add(backButton, c); c.gridx = 1; registrationWindowFrame.add(submitButton, c); registrationWindowFrame.pack(); registrationWindowFrame.setResizable(false); registrationWindowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); registrationWindowFrame.setLocationRelativeTo(null); registrationWindowFrame.setVisible(true); }
private registrationWindow() { this.registrationWindowFrame= new JFrame(); this.wellcomeLogo = new JLabel(new ImageIcon(getClass().getResource("textlogo.png"))); this.wellcomeLabel1 = new JLabel("Please Enter your personal data"); this.nickNameLabel = new JLabel("Nickname"); this.nickNameTextField = new JTextField(); this.userNameLabel = new JLabel("Username"); this.userNameTextField = new JTextField(); this.passWordLabel = new JLabel("Password"); this.passWordTextField = new JPasswordField(); this.firstNameLabel = new JLabel("First name"); this.firstNameTextField = new JTextField(); this.lastNameLabel = new JLabel("Last name"); this.lastNameTextField = new JTextField(); this.eMailLabel = new JLabel("eMail"); this.eMailTextField = new JTextField(); this.birthDayLabel = new JLabel("Birthday"); this.birthDayTextField = new JTextField(); this.backupserverIPLabel = new JLabel("IP of your Backupserver"); this.backupserverIPTextField= new JTextField(); this.statusTextField = new JTextField(); this.backButton = new JButton("Apply Changes"); this.submitButton = new JButton("Register"); this.submitButton.addActionListener(new registrationWindowButtonController()); this.backButton.addActionListener(new registrationWindowButtonController()); this.c = new GridBagConstraints(); this.set = new Insets(5, 5, 5, 5); registrationWindowFrame.setTitle("Registration"); registrationWindowFrame.setIconImage(new ImageIcon(getClass().getResource("pM_Logo2.png")).getImage()); registrationWindowFrame.getContentPane().setBackground(Color.WHITE); registrationWindowFrame.setMinimumSize(new Dimension(200, 180)); statusTextField.setBackground(new Color(229, 195, 0)); statusTextField.setEditable(false); registrationWindowFrame.setLayout(new GridBagLayout()); c.insets = set; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.LINE_START; // hinzuf�gen der Komponenten zum startWindowFrame c.gridx = 0; c.gridy = 0; c.gridwidth = 2; registrationWindowFrame.add(wellcomeLogo ,c); c.gridy = 1; c.gridwidth = 2; registrationWindowFrame.add(wellcomeLabel1, c); c.gridy = 2; c.gridwidth = 1; registrationWindowFrame.add(nickNameLabel, c); c.gridx = 1; registrationWindowFrame.add(nickNameTextField, c); c.gridx = 0; c.gridy = 3; registrationWindowFrame.add(userNameLabel, c); c.gridx = 1; registrationWindowFrame.add(userNameTextField, c); c.gridx = 0; c.gridy = 5; registrationWindowFrame.add(passWordLabel, c); c.gridx = 1; registrationWindowFrame.add(passWordTextField, c); c.gridx = 0; c.gridy = 6; registrationWindowFrame.add(firstNameLabel, c); c.gridx = 1; registrationWindowFrame.add(firstNameTextField, c); c.gridx = 0; c.gridy = 7; registrationWindowFrame.add(lastNameLabel, c); c.gridx = 1; registrationWindowFrame.add(lastNameTextField, c); c.gridx = 0; c.gridy = 8; registrationWindowFrame.add(eMailLabel, c); c.gridx = 1; registrationWindowFrame.add(eMailTextField, c); c.gridx = 0; c.gridy = 9; registrationWindowFrame.add(birthDayLabel, c); c.gridx = 1; registrationWindowFrame.add(birthDayTextField, c); c.gridx = 0; c.gridy = 10; registrationWindowFrame.add(backupserverIPLabel, c); c.gridx = 1; registrationWindowFrame.add(backupserverIPTextField, c); c.gridx = 0; c.gridy = 11; c.gridwidth = 2; registrationWindowFrame.add(statusTextField, c); c.gridy = 12; c.gridwidth = 1; registrationWindowFrame.add(backButton, c); c.gridx = 1; registrationWindowFrame.add(submitButton, c); registrationWindowFrame.pack(); registrationWindowFrame.setResizable(false); registrationWindowFrame.setLocationRelativeTo(GUI.getGUI()); registrationWindowFrame.setVisible(true); }
diff --git a/common/com/pahimar/ee3/core/handlers/TransmutationTargetOverlayHandler.java b/common/com/pahimar/ee3/core/handlers/TransmutationTargetOverlayHandler.java index 11afbf0e..9498f1e9 100644 --- a/common/com/pahimar/ee3/core/handlers/TransmutationTargetOverlayHandler.java +++ b/common/com/pahimar/ee3/core/handlers/TransmutationTargetOverlayHandler.java @@ -1,149 +1,149 @@ package com.pahimar.ee3.core.handlers; import java.util.EnumSet; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import com.pahimar.ee3.client.renderer.RenderUtils; import com.pahimar.ee3.configuration.ConfigurationSettings; import com.pahimar.ee3.core.util.TransmutationHelper; import com.pahimar.ee3.item.ITransmutationStone; import com.pahimar.ee3.lib.Reference; import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.common.ITickHandler; import cpw.mods.fml.common.TickType; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; /** * Equivalent-Exchange-3 * * TransmutationTargetOverlayHandler * * @author pahimar * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) * */ @SideOnly(Side.CLIENT) public class TransmutationTargetOverlayHandler implements ITickHandler { @Override public void tickStart(EnumSet<TickType> type, Object... tickData) { } @Override public void tickEnd(EnumSet<TickType> type, Object... tickData) { Minecraft minecraft = FMLClientHandler.instance().getClient(); EntityPlayer player = minecraft.thePlayer; ItemStack currentItemStack = null; if (type.contains(TickType.RENDER)) { if (player != null) { currentItemStack = player.inventory.getCurrentItem(); if (Minecraft.isGuiEnabled() && minecraft.inGameHasFocus) { if (currentItemStack != null && currentItemStack.getItem() instanceof ITransmutationStone && ConfigurationSettings.ENABLE_OVERLAY_WORLD_TRANSMUTATION) { renderStoneHUD(minecraft, player, currentItemStack, (Float) tickData[0]); } } } } } @Override public EnumSet<TickType> ticks() { return EnumSet.of(TickType.CLIENT, TickType.RENDER); } @Override public String getLabel() { return Reference.MOD_NAME + ": " + this.getClass().getSimpleName(); } private static void renderStoneHUD(Minecraft minecraft, EntityPlayer player, ItemStack stack, float partialTicks) { float overlayScale = ConfigurationSettings.TARGET_BLOCK_OVERLAY_SCALE; float blockScale = overlayScale / 2; float overlayOpacity = ConfigurationSettings.TARGET_BLOCK_OVERLAY_OPACITY; GL11.glPushMatrix(); ScaledResolution sr = new ScaledResolution(minecraft.gameSettings, minecraft.displayWidth, minecraft.displayHeight); - GL11.glClear(256); + GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(0.0D, sr.getScaledWidth_double(), sr.getScaledHeight_double(), 0.0D, 1000.0D, 3000.0D); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); GL11.glTranslatef(0.0F, 0.0F, -2000.0F); GL11.glPushMatrix(); RenderHelper.enableGUIStandardItemLighting(); GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glEnable(GL11.GL_COLOR_MATERIAL); GL11.glEnable(GL11.GL_LIGHTING); int hudOverlayX = 0; int hudOverlayY = 0; int hudBlockX = 0; int hudBlockY = 0; switch (ConfigurationSettings.TARGET_BLOCK_OVERLAY_POSITION) { case 0: { hudOverlayX = 0; hudBlockX = (int) (16 * overlayScale / 2 - 8); hudOverlayY = 0; hudBlockY = (int) (16 * overlayScale / 2 - 8); break; } case 1: { hudOverlayX = (int) (sr.getScaledWidth() - 16 * overlayScale); hudBlockX = (int) (sr.getScaledWidth() - 16 * overlayScale / 2 - 8); hudOverlayY = 0; hudBlockY = (int) (16 * overlayScale / 2 - 8); break; } case 2: { hudOverlayX = 0; hudBlockX = (int) (16 * overlayScale / 2 - 8); hudOverlayY = (int) (sr.getScaledHeight() - 16 * overlayScale); hudBlockY = (int) (sr.getScaledHeight() - 16 * overlayScale / 2 - 8); break; } case 3: { hudOverlayX = (int) (sr.getScaledWidth() - 16 * overlayScale); hudBlockX = (int) (sr.getScaledWidth() - 16 * overlayScale / 2 - 8); hudOverlayY = (int) (sr.getScaledHeight() - 16 * overlayScale); hudBlockY = (int) (sr.getScaledHeight() - 16 * overlayScale / 2 - 8); break; } default: { break; } } RenderUtils.renderItemIntoGUI(minecraft.fontRenderer, stack, hudOverlayX, hudOverlayY, overlayOpacity, overlayScale); if (TransmutationHelper.targetBlockStack != null && TransmutationHelper.targetBlockStack.getItem() instanceof ItemBlock) { RenderUtils.renderRotatingBlockIntoGUI(minecraft.fontRenderer, TransmutationHelper.targetBlockStack, hudBlockX, hudBlockY, -90, blockScale); } GL11.glDisable(GL11.GL_LIGHTING); GL11.glPopMatrix(); GL11.glPopMatrix(); } }
true
true
private static void renderStoneHUD(Minecraft minecraft, EntityPlayer player, ItemStack stack, float partialTicks) { float overlayScale = ConfigurationSettings.TARGET_BLOCK_OVERLAY_SCALE; float blockScale = overlayScale / 2; float overlayOpacity = ConfigurationSettings.TARGET_BLOCK_OVERLAY_OPACITY; GL11.glPushMatrix(); ScaledResolution sr = new ScaledResolution(minecraft.gameSettings, minecraft.displayWidth, minecraft.displayHeight); GL11.glClear(256); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(0.0D, sr.getScaledWidth_double(), sr.getScaledHeight_double(), 0.0D, 1000.0D, 3000.0D); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); GL11.glTranslatef(0.0F, 0.0F, -2000.0F); GL11.glPushMatrix(); RenderHelper.enableGUIStandardItemLighting(); GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glEnable(GL11.GL_COLOR_MATERIAL); GL11.glEnable(GL11.GL_LIGHTING); int hudOverlayX = 0; int hudOverlayY = 0; int hudBlockX = 0; int hudBlockY = 0; switch (ConfigurationSettings.TARGET_BLOCK_OVERLAY_POSITION) { case 0: { hudOverlayX = 0; hudBlockX = (int) (16 * overlayScale / 2 - 8); hudOverlayY = 0; hudBlockY = (int) (16 * overlayScale / 2 - 8); break; } case 1: { hudOverlayX = (int) (sr.getScaledWidth() - 16 * overlayScale); hudBlockX = (int) (sr.getScaledWidth() - 16 * overlayScale / 2 - 8); hudOverlayY = 0; hudBlockY = (int) (16 * overlayScale / 2 - 8); break; } case 2: { hudOverlayX = 0; hudBlockX = (int) (16 * overlayScale / 2 - 8); hudOverlayY = (int) (sr.getScaledHeight() - 16 * overlayScale); hudBlockY = (int) (sr.getScaledHeight() - 16 * overlayScale / 2 - 8); break; } case 3: { hudOverlayX = (int) (sr.getScaledWidth() - 16 * overlayScale); hudBlockX = (int) (sr.getScaledWidth() - 16 * overlayScale / 2 - 8); hudOverlayY = (int) (sr.getScaledHeight() - 16 * overlayScale); hudBlockY = (int) (sr.getScaledHeight() - 16 * overlayScale / 2 - 8); break; } default: { break; } } RenderUtils.renderItemIntoGUI(minecraft.fontRenderer, stack, hudOverlayX, hudOverlayY, overlayOpacity, overlayScale); if (TransmutationHelper.targetBlockStack != null && TransmutationHelper.targetBlockStack.getItem() instanceof ItemBlock) { RenderUtils.renderRotatingBlockIntoGUI(minecraft.fontRenderer, TransmutationHelper.targetBlockStack, hudBlockX, hudBlockY, -90, blockScale); } GL11.glDisable(GL11.GL_LIGHTING); GL11.glPopMatrix(); GL11.glPopMatrix(); }
private static void renderStoneHUD(Minecraft minecraft, EntityPlayer player, ItemStack stack, float partialTicks) { float overlayScale = ConfigurationSettings.TARGET_BLOCK_OVERLAY_SCALE; float blockScale = overlayScale / 2; float overlayOpacity = ConfigurationSettings.TARGET_BLOCK_OVERLAY_OPACITY; GL11.glPushMatrix(); ScaledResolution sr = new ScaledResolution(minecraft.gameSettings, minecraft.displayWidth, minecraft.displayHeight); GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(0.0D, sr.getScaledWidth_double(), sr.getScaledHeight_double(), 0.0D, 1000.0D, 3000.0D); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); GL11.glTranslatef(0.0F, 0.0F, -2000.0F); GL11.glPushMatrix(); RenderHelper.enableGUIStandardItemLighting(); GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glEnable(GL11.GL_COLOR_MATERIAL); GL11.glEnable(GL11.GL_LIGHTING); int hudOverlayX = 0; int hudOverlayY = 0; int hudBlockX = 0; int hudBlockY = 0; switch (ConfigurationSettings.TARGET_BLOCK_OVERLAY_POSITION) { case 0: { hudOverlayX = 0; hudBlockX = (int) (16 * overlayScale / 2 - 8); hudOverlayY = 0; hudBlockY = (int) (16 * overlayScale / 2 - 8); break; } case 1: { hudOverlayX = (int) (sr.getScaledWidth() - 16 * overlayScale); hudBlockX = (int) (sr.getScaledWidth() - 16 * overlayScale / 2 - 8); hudOverlayY = 0; hudBlockY = (int) (16 * overlayScale / 2 - 8); break; } case 2: { hudOverlayX = 0; hudBlockX = (int) (16 * overlayScale / 2 - 8); hudOverlayY = (int) (sr.getScaledHeight() - 16 * overlayScale); hudBlockY = (int) (sr.getScaledHeight() - 16 * overlayScale / 2 - 8); break; } case 3: { hudOverlayX = (int) (sr.getScaledWidth() - 16 * overlayScale); hudBlockX = (int) (sr.getScaledWidth() - 16 * overlayScale / 2 - 8); hudOverlayY = (int) (sr.getScaledHeight() - 16 * overlayScale); hudBlockY = (int) (sr.getScaledHeight() - 16 * overlayScale / 2 - 8); break; } default: { break; } } RenderUtils.renderItemIntoGUI(minecraft.fontRenderer, stack, hudOverlayX, hudOverlayY, overlayOpacity, overlayScale); if (TransmutationHelper.targetBlockStack != null && TransmutationHelper.targetBlockStack.getItem() instanceof ItemBlock) { RenderUtils.renderRotatingBlockIntoGUI(minecraft.fontRenderer, TransmutationHelper.targetBlockStack, hudBlockX, hudBlockY, -90, blockScale); } GL11.glDisable(GL11.GL_LIGHTING); GL11.glPopMatrix(); GL11.glPopMatrix(); }
diff --git a/src/main/java/edu/lmu/cs/xlg/spitfire/entities/NumberLiteral.java b/src/main/java/edu/lmu/cs/xlg/spitfire/entities/NumberLiteral.java index b88ff35..57d700d 100644 --- a/src/main/java/edu/lmu/cs/xlg/spitfire/entities/NumberLiteral.java +++ b/src/main/java/edu/lmu/cs/xlg/spitfire/entities/NumberLiteral.java @@ -1,42 +1,42 @@ package edu.lmu.cs.xlg.manatee.entities; import edu.lmu.cs.xlg.util.Log; /** * A number literal, like "2.3", "4.6634E-231", etc. */ public class NumberLiteral extends Literal { private Double value; /** * Creates a real literal from its lexeme. */ public NumberLiteral(String lexeme) { super(lexeme); } /** * Returns the value. */ public Double getValue() { return value; } /** * Analyzes this literal, determining its value. */ @Override public void analyze(Log log, SymbolTable table, Subroutine owner, boolean inLoop) { type = Type.NUMBER; String lexeme = getLexeme(); try { if (lexeme.contains("^")) { lexeme = lexeme.replaceAll("(x|\\xd7)10\\^", "E"); } value = Double.valueOf(lexeme); } catch (NumberFormatException e) { - log.error("bad_number", getLexeme()); + log.error("non_integer", getLexeme()); } } }
true
true
public void analyze(Log log, SymbolTable table, Subroutine owner, boolean inLoop) { type = Type.NUMBER; String lexeme = getLexeme(); try { if (lexeme.contains("^")) { lexeme = lexeme.replaceAll("(x|\\xd7)10\\^", "E"); } value = Double.valueOf(lexeme); } catch (NumberFormatException e) { log.error("bad_number", getLexeme()); } }
public void analyze(Log log, SymbolTable table, Subroutine owner, boolean inLoop) { type = Type.NUMBER; String lexeme = getLexeme(); try { if (lexeme.contains("^")) { lexeme = lexeme.replaceAll("(x|\\xd7)10\\^", "E"); } value = Double.valueOf(lexeme); } catch (NumberFormatException e) { log.error("non_integer", getLexeme()); } }
diff --git a/src/org/nosco/Function.java b/src/org/nosco/Function.java index 23a6697..1c86d02 100644 --- a/src/org/nosco/Function.java +++ b/src/org/nosco/Function.java @@ -1,815 +1,819 @@ package org.nosco; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.nosco.Condition.Binary2; import org.nosco.Constants.CALENDAR; import org.nosco.Constants.DB_TYPE; import org.nosco.Table.__SimplePrimaryKey; /** * A collection of SQL functions. &nbsp; Use these to call functions on fields * or values in the generated SQL. &nbsp; For example: * * <pre> import static org.nosco.Function.*; * SomeClass.ALL.where(SomeClass.BIRTH_DATE.gt(NOW())).count()</pre> * * <p>would generate: * * <pre> select * from some_class where birth_date > NOW()</pre> * * @author Derek Anderson */ public abstract class Function<T> { /** * Create a SQL function for IFNULL() (ISNULL() on SQL Server). * @param f * @param v * @return */ public static <T> Function<Boolean> IFNULL(final Field<? extends T> f, final T v) { final Object[] oa = new Object[] {f, v}; return new Custom<Boolean>(", ", "ifnull", "isnull", "ifnull", oa); } /** * Create a SQL function for IFNULL() (ISNULL() on SQL Server). * @param f * @param v * @return */ public static <T> Function<Boolean> IFNULL(final Function<? extends T> f, final T v) { final Object[] oa = new Object[] {f, v}; return new Custom<Boolean>(", ", "ifnull", "isnull", "ifnull", oa); } /** * @return the sql NOW() function (or GETDATE() on sql server) */ public static Function<java.sql.Date> NOW() { final Object[] oa = new Object[] {}; return new Custom<java.sql.Date>(", ", "now", "getdate", "now", oa); } /** * GETDATE and GETUTCDATE functions both return the current date and time. However, * GETUTCDATE returns the current Universal Time Coordinate (UTC) time, whereas * GETDATE returns the date and time on the computer where SQL Server is running. * @return same as NOW() */ public static Function<java.sql.Date> GETDATE() { return NOW(); } /** * GETDATE and GETUTCDATE functions both return the current date and time. However, * GETUTCDATE returns the current Universal Time Coordinate (UTC) time, whereas * GETDATE returns the date and time on the computer where SQL Server is running. * @return the sql GETUTCDATE() function */ public static Function<java.sql.Date> GETUTCDATE() { return new Custom<java.sql.Date>(", ", "GETUTCDATE", "GETUTCDATE", "GETUTCDATE"); } /** * COALESCE is a sql function that will return the first non-null parameter value. * All objects other than functions or fields are passed verbatim to the * PreparedStatement with setObject(). * @param fields * @return */ public static <T> Function<T> COALESCE(final Object... fields) { return new Custom<T>("coalesce", fields); } /** * DATEADD function is deterministic; it adds a certain period of time to the * existing date and time value. * @param f1 * @param count * @param component * @return */ public static <T> Function<java.sql.Date> DATEADD(final Function<? extends T> f1, final int count, final CALENDAR component) { return new Function<java.sql.Date>() { @Override void getSQL(final StringBuffer sb, final List<Object> bindings, final SqlContext context) { if (context.dbType == DB_TYPE.MYSQL) { sb.append("date_add("); f1.getSQL(sb, bindings, context); sb.append(", interval ? "+ component +")"); bindings.add(count); } else if ((context.dbType == DB_TYPE.HSQL)) { sb.append("TIMESTAMPADD(SQL_TSI_" + component +", ?, "); bindings.add(count); f1.getSQL(sb, bindings, context); sb.append(")"); } else { sb.append("dateadd(" + component +", ?, "); bindings.add(count); f1.getSQL(sb, bindings, context); sb.append(")"); } } }; } /** * DATEADD function is deterministic; it adds a certain period of time to the * existing date and time value. * @param f1 * @param count * @param component * @return */ public static <T> Function<java.sql.Date> DATEADD(final Field<? extends T> field, final int count, final CALENDAR component) { return new Function<java.sql.Date>() { @Override void getSQL(final StringBuffer sb, final List<Object> bindings, final SqlContext context) { final String sql = Util.derefField(field, context); final DB_TYPE dbType = context==null ? null : context.dbType; if (dbType == DB_TYPE.MYSQL) { sb.append("date_add(" + sql +", interval ? "+ component +")"); bindings.add(count); } else if ((dbType == DB_TYPE.HSQL)) { sb.append("TIMESTAMPADD(SQL_TSI_" + component +", ?, "+ sql +")"); bindings.add(count); } else { sb.append("dateadd(" + component +", ?, "+ sql +")"); bindings.add(count); } } }; } /** * The DATEPART function allows retrieving any part of the date and time variable provided. * This function is deterministic except when used with days of the week. * <p> * The DATEPART function takes two parameters: the part of the date that you want to * retrieve and the date itself. The DATEPART function returns an integer representing any * of the following parts of the supplied date: year, quarter, month, day of the year, day, * week number, weekday number, hour, minute, second, or millisecond. * @param component * @param f * @return */ public static Function<Integer> DATEPART(final CALENDAR component, final Function<?> f) { return new Custom<Integer>("DATEPART", component, f); } /** * The DATEPART function allows retrieving any part of the date and time variable provided. * This function is deterministic except when used with days of the week. * <p> * The DATEPART function takes two parameters: the part of the date that you want to * retrieve and the date itself. The DATEPART function returns an integer representing any * of the following parts of the supplied date: year, quarter, month, day of the year, day, * week number, weekday number, hour, minute, second, or millisecond. * @param component * @param f * @return */ public static Function<Integer> DATEPART(final CALENDAR component, final Field<?> f) { return new Custom<Integer>("DATEPART", component, f); } /** * DAY, MONTH and YEAR functions are deterministic. Each of these accepts a single date * value as a parameter and returns respective portions of the date as an integer. * @param f * @return */ public static Function<Integer> DAY(final Field<?> f) { return new Custom<Integer>("DAY", f); } /** * DAY, MONTH and YEAR functions are deterministic. Each of these accepts a single date * value as a parameter and returns respective portions of the date as an integer. * @param f * @return */ public static Function<Integer> MONTH(final Field<?> f) { return new Custom<Integer>("MONTH", f); } /** * DAY, MONTH and YEAR functions are deterministic. Each of these accepts a single date * value as a parameter and returns respective portions of the date as an integer. * @param f * @return */ public static Function<Integer> YEAR(final Field<?> f) { return new Custom<Integer>("YEAR", f); } /** * DATEDIFF function is deterministic; it accepts two DATETIME values and a date portion * (minute, hour, day, month, etc) as parameters. DATEDIFF() determines the difference * between the two date values passed, expressed in the date portion specified. * @param component * @param f1 * @param f2 * @return */ public static Function<Integer> DATEDIFF(final CALENDAR component, final Field<?> f1, final Field<?> f2) { return new Custom<Integer>("DATEDIFF", component, f1, f2); } /** * DATEDIFF function is deterministic; it accepts two DATETIME values and a date portion * (minute, hour, day, month, etc) as parameters. DATEDIFF() determines the difference * between the two date values passed, expressed in the date portion specified. * @param component * @param f1 * @param f2 * @return */ public static Function<Integer> DATEDIFF(final CALENDAR component, final Field<?> f1, final Function<?> f2) { return new Custom<Integer>("DATEDIFF", component, f1, f2); } /** * DATEDIFF function is deterministic; it accepts two DATETIME values and a date portion * (minute, hour, day, month, etc) as parameters. DATEDIFF() determines the difference * between the two date values passed, expressed in the date portion specified. * @param component * @param f1 * @param f2 * @return */ public static Function<Integer> DATEDIFF(final CALENDAR component, final Function<?> f1, final Field<?> f2) { return new Custom<Integer>("DATEDIFF", component, f1, f2); } /** * DATEDIFF function is deterministic; it accepts two DATETIME values and a date portion * (minute, hour, day, month, etc) as parameters. DATEDIFF() determines the difference * between the two date values passed, expressed in the date portion specified. * @param component * @param f1 * @param f2 * @return */ public static Function<Integer> DATEDIFF(final CALENDAR component, final Function<?> f1, final Function<?> f2) { return new Custom<Integer>("DATEDIFF", component, f1, f2); } /** * The CONCAT() function is used to concatenate the values of any number of * string arguments passed to it. * @param fields * @return */ public static Function<String> CONCAT(final Object... fields) { return new Function<String>() { @Override void getSQL(final StringBuffer sb, final List<Object> bindings, final SqlContext context) { final DB_TYPE dbType = context==null ? null : context.dbType; if (dbType == DB_TYPE.SQLSERVER) { new Custom<String>(" + ", null, null, null, fields).getSQL(sb, bindings, context); } else { new Custom<String>("CONCAT", fields).getSQL(sb, bindings, context); } } }; } /* ======================================================================== */ abstract void getSQL(StringBuffer sb, List<Object> bindings, SqlContext context); /** * The list of built-in functions is far from comprehensive. * Use this to implement your own one-off functions. * Please submit functions you think are useful back to the project! */ public static class Custom<T> extends Function<T> { private final String mysql; private final String sqlserver; private final String hsql; private Object[] objects = null; private final String sql = null; private final List<Object> bindings = new ArrayList<Object>(); private String sep = ", "; /** * For a simple, no argument SQL function like NOW(). * @param func */ public Custom(final String func) { this.mysql = func; this.sqlserver = func; this.hsql = func; } /** * For functions that take arguments. The first string is the function name. * The remaining parameters are passed as arguments. * If an argument is a field it is referenced to a table in the from clause. * For all others, the object is passed verbatim to the PreparedStatement with setObject(). * @param func the name of the function * @param objects the arguments of the function */ public Custom(final String func, final Object... objects) { this.mysql = func; this.sqlserver = func; this.hsql = func; this.objects = objects; } Custom(final String mysql, final String sqlserver, final String hsql) { this.mysql = mysql; this.sqlserver = sqlserver; this.hsql = hsql; } Custom(final String sep, final String mysql, final String sqlserver, final String hsql, final Object[] objects) { this.sep = sep; this.mysql = mysql; this.sqlserver = sqlserver; this.hsql = hsql; this.objects = objects; } Custom(final Object o1, final String sep, final Object o2) { this.sqlserver = null; this.hsql = null; this.mysql = null; this.sep = sep; this.objects = new Object[] {o1, o2}; } @Override void getSQL(final StringBuffer sb, final List<Object> bindings, final SqlContext context) { final DB_TYPE dbType = context==null ? null : context.dbType; - switch (dbType) { - case MYSQL: sb.append(mysql==null ? "" : mysql); break; - case SQLSERVER: sb.append(sqlserver==null ? "" : sqlserver); break; - case HSQL: sb.append(hsql==null ? "" : hsql); break; - default: throw new RuntimeException("unknown DB_TYPE "+ dbType); + if (dbType != null) { + switch (dbType) { + case MYSQL: sb.append(mysql==null ? "" : mysql); break; + case SQLSERVER: sb.append(sqlserver==null ? "" : sqlserver); break; + case HSQL: sb.append(hsql==null ? "" : hsql); break; + default: throw new RuntimeException("unknown DB_TYPE "+ dbType); + } + } else { + sb.append(hsql!=null ? hsql : mysql!=null ? mysql : sqlserver!=null ? sqlserver : "<UNK DB_TYPE>"); } sb.append("("); if (objects != null) { for (int i=0; i<objects.length; ++i) { final Object o = objects[i]; if (o instanceof Field<?>) { sb.append(Util.derefField((Field<?>) o, context)); } else if (o instanceof Function<?>) { final Function<?> f = (Function<?>) o; f.getSQL(sb, bindings, context); } else if (o instanceof CALENDAR) { sb.append(o.toString()); } else { sb.append("?"); bindings.add(o); } if (i < objects.length-1) sb.append(sep); } } sb.append(")"); } } /* ======================================================================== */ /** * Creates a condition representing this function equal to the literal value of the parameter. * @param v * @return */ public Condition eq(final T v) { return new Binary2(this, "=", v); } /** * Creates a condition representing this function equal to some other field. * @param v * @return */ public Condition eq(final Field<T> v) { return new Binary2(this, "=", v); } public Condition eq(final __SimplePrimaryKey<?,T> v) { return eq(v.value()); } /** * Creates a condition representing this function equal to some function. * @param v * @return */ public Condition eq(final Function<?> v) { return new Binary2(this, "=", v); } /** * Creates a condition representing this function not equal to the literal value of the parameter. * @param v * @return */ public Condition neq(final T v) { return new Binary2(this, "!=", v); } /** * Creates a condition representing this function not equal to some other field. * @param v * @return */ public Condition neq(final Field<T> v) { return new Binary2(this, "!=", v); } /** * Creates a condition representing this function not equal to some function. * @param v * @return */ public Condition neq(final Function<?> v) { return new Binary2(this, "!=", v); } /** * Creates a condition representing this function less than the literal value of the parameter. * @param v * @return */ public Condition lt(final T v) { return new Binary2(this, "<", v); } /** * Creates a condition representing this function less than some other field. * @param v * @return */ public Condition lt(final Field<T> v) { return new Binary2(this, "<", v); } /** * Creates a condition representing this function less than some function. * @param v * @return */ public Condition lt(final Function<?> v) { return new Binary2(this, "<", v); } /** * Creates a condition representing this function less than or equal to the literal value of the parameter. * @param v * @return */ public Condition lte(final T v) { return new Binary2(this, "<=", v); } /** * Creates a condition representing this function less than or equal to some other field. * @param v * @return */ public Condition lte(final Field<T> v) { return new Binary2(this, "<=", v); } /** * Creates a condition representing this function less than or equal to some function. * @param v * @return */ public Condition lte(final Function<?> v) { return new Binary2(this, "<=", v); } /** * Creates a condition representing this function greater than the literal value of the parameter. * @param v * @return */ public Condition gt(final T v) { return new Binary2(this, ">", v); } /** * Creates a condition representing this function greater than some other field. * @param v * @return */ public Condition gt(final Field<T> v) { return new Binary2(this, ">", v); } /** * Creates a condition representing this function greater than some function. * @param v * @return */ public Condition gt(final Function<?> v) { return new Binary2(this, ">", v); } /** * Creates a condition representing this function greater than or equal to the literal value of the parameter. * @param v * @return */ public Condition gte(final T v) { return new Binary2(this, ">=", v); } /** * Creates a condition representing this function greater than or equal to some other field. * @param v * @return */ public Condition gte(final Field<T> v) { return new Binary2(this, ">=", v); } /** * Creates a condition representing this function greater than or equal to some function. * @param v * @return */ public Condition gte(final Function<?> v) { return new Binary2(this, ">=", v); } /** * Performs a mathematical function on this function. * @param v * @return */ public Function<T> add(final T v) { return new Function.Custom<T>(this, "+", v); } /** * Performs a mathematical function on this function. * @param v * @return */ public Function<T> add(final Field<T> v) { return new Function.Custom<T>(this, "+", v); } /** * Performs a mathematical function on this function. * @param v * @return */ public Function<T> add(final Function v) { return new Function.Custom<T>(this, "+", v); } /** * Performs a mathematical function on this function. * @param v * @return */ public Function<T> sub(final T v) { return new Function.Custom<T>(this, "-", v); } /** * Performs a mathematical function on this function. * @param v * @return */ public Function<T> sub(final Field<T> v) { return new Function.Custom<T>(this, "-", v); } /** * Performs a mathematical function on this function. * @param v * @return */ public Function<T> sub(final Function v) { return new Function.Custom<T>(this, "-", v); } /** * Performs a mathematical function on this function. * @param v * @return */ public Function<T> mul(final T v) { return new Function.Custom<T>(this, "*", v); } /** * Performs a mathematical function on this function. * @param v * @return */ public Function<T> mul(final Field<T> v) { return new Function.Custom<T>(this, "*", v); } /** * Performs a mathematical function on this function. * @param v * @return */ public Function<T> mul(final Function v) { return new Function.Custom<T>(this, "*", v); } /** * Performs a mathematical function on this function. * @param v * @return */ public Function<T> div(final T v) { return new Function.Custom<T>(this, "/", v); } /** * Performs a mathematical function on this function. * @param v * @return */ public Function<T> div(final Field<T> v) { return new Function.Custom<T>(this, "/", v); } /** * Performs a mathematical function on this function. * @param v * @return */ public Function<T> div(final Function v) { return new Function.Custom<T>(this, "/", v); } /** * Performs a mathematical function on this function. * @param v * @return */ public Function<T> mod(final T v) { return new Function.Custom<T>(this, "%", v); } /** * Performs a mathematical function on this function. * @param v * @return */ public Function<T> mod(final Field<T> v) { return new Function.Custom<T>(this, "%", v); } /** * Performs a mathematical function on this function. * @param v * @return */ public Function<T> mod(final Function v) { return new Function.Custom<T>(this, "%", v); } /** * Performs a mathematical function on this function. * @param v * @return * @deprecated use sub() */ public Function<T> subtract(final T v) { return new Function.Custom<T>(this, "-", v); } /** * Performs a mathematical function on this function. * @param v * @return * @deprecated use sub() */ public Function<T> subtract(final Field<T> v) { return new Function.Custom<T>(this, "-", v); } /** * Performs a mathematical function on this function. * @param v * @return * @deprecated use sub() */ public Function<T> subtract(final Function v) { return new Function.Custom<T>(this, "-", v); } /** * Performs a mathematical function on this function. * @param v * @return * @deprecated use mul() */ public Function<T> multiply(final T v) { return new Function.Custom<T>(this, "*", v); } /** * Performs a mathematical function on this function. * @param v * @return * @deprecated use mul() */ public Function<T> multiply(final Field<T> v) { return new Function.Custom<T>(this, "*", v); } /** * Performs a mathematical function on this function. * @param v * @return * @deprecated use mul() */ public Function<T> multiply(final Function v) { return new Function.Custom<T>(this, "*", v); } /** * Performs a mathematical function on this function. * @param v * @return * @deprecated use div() */ public Function<T> divide(final T v) { return new Function.Custom<T>(this, "/", v); } /** * Performs a mathematical function on this function. * @param v * @return * @deprecated use div() */ public Function<T> divide(final Field<T> v) { return new Function.Custom<T>(this, "/", v); } /** * Performs a mathematical function on this function. * @param v * @return * @deprecated use div() */ public Function<T> divide(final Function v) { return new Function.Custom<T>(this, "/", v); } /** * Performs a mathematical function on this function. * @param v * @return * @deprecated use mod() */ public Function<T> modulus(final T v) { return new Function.Custom<T>(this, "%", v); } /** * Performs a mathematical function on this function. * @param v * @return * @deprecated use mod() */ public Function<T> modulus(final Field<T> v) { return new Function.Custom<T>(this, "%", v); } /** * Performs a mathematical function on this function. * @param v * @return * @deprecated use mod() */ public Function<T> modulus(final Function v) { return new Function.Custom<T>(this, "%", v); } }
true
true
void getSQL(final StringBuffer sb, final List<Object> bindings, final SqlContext context) { final DB_TYPE dbType = context==null ? null : context.dbType; switch (dbType) { case MYSQL: sb.append(mysql==null ? "" : mysql); break; case SQLSERVER: sb.append(sqlserver==null ? "" : sqlserver); break; case HSQL: sb.append(hsql==null ? "" : hsql); break; default: throw new RuntimeException("unknown DB_TYPE "+ dbType); } sb.append("("); if (objects != null) { for (int i=0; i<objects.length; ++i) { final Object o = objects[i]; if (o instanceof Field<?>) { sb.append(Util.derefField((Field<?>) o, context)); } else if (o instanceof Function<?>) { final Function<?> f = (Function<?>) o; f.getSQL(sb, bindings, context); } else if (o instanceof CALENDAR) { sb.append(o.toString()); } else { sb.append("?"); bindings.add(o); } if (i < objects.length-1) sb.append(sep); } } sb.append(")"); }
void getSQL(final StringBuffer sb, final List<Object> bindings, final SqlContext context) { final DB_TYPE dbType = context==null ? null : context.dbType; if (dbType != null) { switch (dbType) { case MYSQL: sb.append(mysql==null ? "" : mysql); break; case SQLSERVER: sb.append(sqlserver==null ? "" : sqlserver); break; case HSQL: sb.append(hsql==null ? "" : hsql); break; default: throw new RuntimeException("unknown DB_TYPE "+ dbType); } } else { sb.append(hsql!=null ? hsql : mysql!=null ? mysql : sqlserver!=null ? sqlserver : "<UNK DB_TYPE>"); } sb.append("("); if (objects != null) { for (int i=0; i<objects.length; ++i) { final Object o = objects[i]; if (o instanceof Field<?>) { sb.append(Util.derefField((Field<?>) o, context)); } else if (o instanceof Function<?>) { final Function<?> f = (Function<?>) o; f.getSQL(sb, bindings, context); } else if (o instanceof CALENDAR) { sb.append(o.toString()); } else { sb.append("?"); bindings.add(o); } if (i < objects.length-1) sb.append(sep); } } sb.append(")"); }
diff --git a/src/com/pokebros/android/pokemononline/Channel.java b/src/com/pokebros/android/pokemononline/Channel.java index 7cf42664..d2709dd4 100644 --- a/src/com/pokebros/android/pokemononline/Channel.java +++ b/src/com/pokebros/android/pokemononline/Channel.java @@ -1,177 +1,185 @@ package com.pokebros.android.pokemononline; import java.util.Hashtable; import java.util.LinkedList; import android.text.Html; import android.text.SpannableStringBuilder; import android.util.Log; import com.pokebros.android.pokemononline.player.PlayerInfo; /** * Contains all info regarding a channel: name, id, joined, * and if joined a player list and chat history. * */ public class Channel { protected String name; protected int id; public int lastSeen = 0; protected boolean isReadyToQuit = false; public boolean joined = false; public final static int HIST_LIMIT = 1000; public static final String TAG = "Pokemon Online Channel"; public Hashtable<Integer, PlayerInfo> players = new Hashtable<Integer, PlayerInfo>(); LinkedList<SpannableStringBuilder> messageList = new LinkedList<SpannableStringBuilder>(); public void writeToHist(CharSequence text) { SpannableStringBuilder spannable; if (text.getClass() != SpannableStringBuilder.class) spannable = new SpannableStringBuilder(text); else spannable = (SpannableStringBuilder)text; synchronized(messageList) { messageList.add(spannable); lastSeen++; if (messageList.size() > HIST_LIMIT) messageList.remove(); } } private NetworkService netServ; public String name(){ return name; } public String toString() { return name; } public Channel(int i, String n, NetworkService net) { id = i; name = n; netServ = net; } public void addPlayer(PlayerInfo p) { if(p != null) { players.put(p.id, p); if(netServ != null && netServ.chatActivity != null && this.equals(netServ.chatActivity.currentChannel())) netServ.chatActivity.addPlayer(p); } else Log.w(TAG, "Tried to add nonexistant player id to channel " + name + ", ignoring"); } public void removePlayer(PlayerInfo p){ if(p != null){ players.remove(p.id); if(netServ != null) { if (netServ.chatActivity.currentChannel() == this) { netServ.chatActivity.removePlayer(p); } netServ.onPlayerLeaveChannel(p.id); } } else Log.w(TAG, "Tried to remove nonexistant player id from channel " + name + ", ignoring"); } public void handleChannelMsg(Command c, Bais msg) { switch(c) { case ChannelPlayers: { int numPlayers = msg.readInt(); for(int i = 0; i < numPlayers; i++) { addPlayer(netServ.players.get(msg.readInt())); } break; } case JoinChannel: { int pid = msg.readInt(); if (pid == netServ.myid) { // We joined the channel netServ.joinedChannels.addFirst(this); joined = true; if (netServ.chatActivity != null) { netServ.chatActivity.populateUI(true); netServ.chatActivity.progressDialog.dismiss(); } writeToHist(Html.fromHtml("<i>Joined channel: <b>" + name + "</b></i>")); } addPlayer(netServ.players.get(pid)); break; } /* case ChannelMessage: { // decorate the message just like Qt client String message = msg.readQString(); // /me like message if (message.length() >= 3 && message.substring(0, 3).equals("***")) { // TODO: choose a color near magenta which is knows by android html message = "<font color='magenta'>" + NetworkService.escapeHtml(message) + "</font>"; writeToHist(Html.fromHtml(message)); break; } String[] name_message = message.split(":", 2); // decorate only if : is present if (name_message.length == 2) { PlayerInfo info = netServ.getPlayerByName(name_message[0]); String color; boolean auth = false; // player exists if (info != null) { color = info.color.toHexString(); auth = 0 < info.auth && info.auth <= 3; System.out.println(color != null ? "playercolor: " + color : "null color"); if (color == null) { color = ColorEnums.defaultPlayerColors[info.id % ColorEnums.defaultPlayerColors.length]; } } else { // special names if (name_message[0].equals("~~Server~~")) color = "orange"; else if (name_message[0].equals("Welcome Message")) color = "blue"; else color = "#3daa68"; } if (auth) { message = "<b><font color='" + color + "'>+<i>" + NetworkService.escapeHtml(name_message[0]) + ":</font></i></b>" + NetworkService.escapeHtml(name_message[1]); } else { message = "<b><font color='" + color + "'>" + NetworkService.escapeHtml(name_message[0]) + ":</font></b>"; if (info != null && info.auth > 3) // don't escape html for higher message += name_message[1]; else message += NetworkService.escapeHtml(name_message[1]); } } writeToHist(Html.fromHtml(message)); break; } case HtmlChannel: writeToHist(Html.fromHtml(msg.readQString())); break; */ case LeaveChannel: int pid = msg.readInt(); if (pid == netServ.myid) { // We left the channel players.clear(); joined = false; netServ.joinedChannels.remove(this); if (netServ.chatActivity != null) { netServ.chatActivity.populateUI(true); } writeToHist(Html.fromHtml("<i>Left channel: <b>" + name + "</b></i>")); } - removePlayer(netServ.players.get(pid)); + /* If a pmed players logs out, we receive the log out message before the leave channel one + * so there's this work around... + */ + PlayerInfo p = netServ.players.get(pid); + if (p == null) { + p = new PlayerInfo(); + p.id = pid; + } + removePlayer(p); break; default: break; } } }
true
true
public void handleChannelMsg(Command c, Bais msg) { switch(c) { case ChannelPlayers: { int numPlayers = msg.readInt(); for(int i = 0; i < numPlayers; i++) { addPlayer(netServ.players.get(msg.readInt())); } break; } case JoinChannel: { int pid = msg.readInt(); if (pid == netServ.myid) { // We joined the channel netServ.joinedChannels.addFirst(this); joined = true; if (netServ.chatActivity != null) { netServ.chatActivity.populateUI(true); netServ.chatActivity.progressDialog.dismiss(); } writeToHist(Html.fromHtml("<i>Joined channel: <b>" + name + "</b></i>")); } addPlayer(netServ.players.get(pid)); break; } /* case ChannelMessage: { // decorate the message just like Qt client String message = msg.readQString(); // /me like message if (message.length() >= 3 && message.substring(0, 3).equals("***")) { // TODO: choose a color near magenta which is knows by android html message = "<font color='magenta'>" + NetworkService.escapeHtml(message) + "</font>"; writeToHist(Html.fromHtml(message)); break; } String[] name_message = message.split(":", 2); // decorate only if : is present if (name_message.length == 2) { PlayerInfo info = netServ.getPlayerByName(name_message[0]); String color; boolean auth = false; // player exists if (info != null) { color = info.color.toHexString(); auth = 0 < info.auth && info.auth <= 3; System.out.println(color != null ? "playercolor: " + color : "null color"); if (color == null) { color = ColorEnums.defaultPlayerColors[info.id % ColorEnums.defaultPlayerColors.length]; } } else { // special names if (name_message[0].equals("~~Server~~")) color = "orange"; else if (name_message[0].equals("Welcome Message")) color = "blue"; else color = "#3daa68"; } if (auth) { message = "<b><font color='" + color + "'>+<i>" + NetworkService.escapeHtml(name_message[0]) + ":</font></i></b>" + NetworkService.escapeHtml(name_message[1]); } else { message = "<b><font color='" + color + "'>" + NetworkService.escapeHtml(name_message[0]) + ":</font></b>"; if (info != null && info.auth > 3) // don't escape html for higher message += name_message[1]; else message += NetworkService.escapeHtml(name_message[1]); } } writeToHist(Html.fromHtml(message)); break; } case HtmlChannel: writeToHist(Html.fromHtml(msg.readQString())); break; */ case LeaveChannel: int pid = msg.readInt(); if (pid == netServ.myid) { // We left the channel players.clear(); joined = false; netServ.joinedChannels.remove(this); if (netServ.chatActivity != null) { netServ.chatActivity.populateUI(true); } writeToHist(Html.fromHtml("<i>Left channel: <b>" + name + "</b></i>")); } removePlayer(netServ.players.get(pid)); break; default: break; }
public void handleChannelMsg(Command c, Bais msg) { switch(c) { case ChannelPlayers: { int numPlayers = msg.readInt(); for(int i = 0; i < numPlayers; i++) { addPlayer(netServ.players.get(msg.readInt())); } break; } case JoinChannel: { int pid = msg.readInt(); if (pid == netServ.myid) { // We joined the channel netServ.joinedChannels.addFirst(this); joined = true; if (netServ.chatActivity != null) { netServ.chatActivity.populateUI(true); netServ.chatActivity.progressDialog.dismiss(); } writeToHist(Html.fromHtml("<i>Joined channel: <b>" + name + "</b></i>")); } addPlayer(netServ.players.get(pid)); break; } /* case ChannelMessage: { // decorate the message just like Qt client String message = msg.readQString(); // /me like message if (message.length() >= 3 && message.substring(0, 3).equals("***")) { // TODO: choose a color near magenta which is knows by android html message = "<font color='magenta'>" + NetworkService.escapeHtml(message) + "</font>"; writeToHist(Html.fromHtml(message)); break; } String[] name_message = message.split(":", 2); // decorate only if : is present if (name_message.length == 2) { PlayerInfo info = netServ.getPlayerByName(name_message[0]); String color; boolean auth = false; // player exists if (info != null) { color = info.color.toHexString(); auth = 0 < info.auth && info.auth <= 3; System.out.println(color != null ? "playercolor: " + color : "null color"); if (color == null) { color = ColorEnums.defaultPlayerColors[info.id % ColorEnums.defaultPlayerColors.length]; } } else { // special names if (name_message[0].equals("~~Server~~")) color = "orange"; else if (name_message[0].equals("Welcome Message")) color = "blue"; else color = "#3daa68"; } if (auth) { message = "<b><font color='" + color + "'>+<i>" + NetworkService.escapeHtml(name_message[0]) + ":</font></i></b>" + NetworkService.escapeHtml(name_message[1]); } else { message = "<b><font color='" + color + "'>" + NetworkService.escapeHtml(name_message[0]) + ":</font></b>"; if (info != null && info.auth > 3) // don't escape html for higher message += name_message[1]; else message += NetworkService.escapeHtml(name_message[1]); } } writeToHist(Html.fromHtml(message)); break; } case HtmlChannel: writeToHist(Html.fromHtml(msg.readQString())); break; */ case LeaveChannel: int pid = msg.readInt(); if (pid == netServ.myid) { // We left the channel players.clear(); joined = false; netServ.joinedChannels.remove(this); if (netServ.chatActivity != null) { netServ.chatActivity.populateUI(true); } writeToHist(Html.fromHtml("<i>Left channel: <b>" + name + "</b></i>")); } /* If a pmed players logs out, we receive the log out message before the leave channel one * so there's this work around... */ PlayerInfo p = netServ.players.get(pid); if (p == null) { p = new PlayerInfo(); p.id = pid; } removePlayer(p); break; default: break; }
diff --git a/src/com/android/launcher2/AppsCustomizePagedView.java b/src/com/android/launcher2/AppsCustomizePagedView.java index 924349da..8ef758d5 100644 --- a/src/com/android/launcher2/AppsCustomizePagedView.java +++ b/src/com/android/launcher2/AppsCustomizePagedView.java @@ -1,1488 +1,1489 @@ /* * Copyright (C) 2011 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.launcher2; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProviderInfo; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.MaskFilter; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.TableMaskFilter; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Process; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.widget.GridLayout; import android.widget.ImageView; import android.widget.Toast; import com.android.launcher.R; import com.android.launcher2.DropTarget.DragObject; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * A simple callback interface which also provides the results of the task. */ interface AsyncTaskCallback { void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data); } /** * The data needed to perform either of the custom AsyncTasks. */ class AsyncTaskPageData { enum Type { LoadWidgetPreviewData, LoadHolographicIconsData } AsyncTaskPageData(int p, ArrayList<Object> l, ArrayList<Bitmap> si, AsyncTaskCallback bgR, AsyncTaskCallback postR) { page = p; items = l; sourceImages = si; generatedImages = new ArrayList<Bitmap>(); cellWidth = cellHeight = -1; doInBackgroundCallback = bgR; postExecuteCallback = postR; } AsyncTaskPageData(int p, ArrayList<Object> l, int cw, int ch, int ccx, AsyncTaskCallback bgR, AsyncTaskCallback postR) { page = p; items = l; generatedImages = new ArrayList<Bitmap>(); cellWidth = cw; cellHeight = ch; cellCountX = ccx; doInBackgroundCallback = bgR; postExecuteCallback = postR; } void cleanup(boolean cancelled) { // Clean up any references to source/generated bitmaps if (sourceImages != null) { if (cancelled) { for (Bitmap b : sourceImages) { b.recycle(); } } sourceImages.clear(); } if (generatedImages != null) { if (cancelled) { for (Bitmap b : generatedImages) { b.recycle(); } } generatedImages.clear(); } } int page; ArrayList<Object> items; ArrayList<Bitmap> sourceImages; ArrayList<Bitmap> generatedImages; int cellWidth; int cellHeight; int cellCountX; AsyncTaskCallback doInBackgroundCallback; AsyncTaskCallback postExecuteCallback; } /** * A generic template for an async task used in AppsCustomize. */ class AppsCustomizeAsyncTask extends AsyncTask<AsyncTaskPageData, Void, AsyncTaskPageData> { AppsCustomizeAsyncTask(int p, AsyncTaskPageData.Type ty) { page = p; threadPriority = Process.THREAD_PRIORITY_DEFAULT; dataType = ty; } @Override protected AsyncTaskPageData doInBackground(AsyncTaskPageData... params) { if (params.length != 1) return null; // Load each of the widget previews in the background params[0].doInBackgroundCallback.run(this, params[0]); return params[0]; } @Override protected void onPostExecute(AsyncTaskPageData result) { // All the widget previews are loaded, so we can just callback to inflate the page result.postExecuteCallback.run(this, result); } void setThreadPriority(int p) { threadPriority = p; } void syncThreadPriority() { Process.setThreadPriority(threadPriority); } // The page that this async task is associated with AsyncTaskPageData.Type dataType; int page; int threadPriority; } /** * The Apps/Customize page that displays all the applications, widgets, and shortcuts. */ public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements AllAppsView, View.OnClickListener, DragSource { static final String LOG_TAG = "AppsCustomizePagedView"; /** * The different content types that this paged view can show. */ public enum ContentType { Applications, Widgets } // Refs private Launcher mLauncher; private DragController mDragController; private final LayoutInflater mLayoutInflater; private final PackageManager mPackageManager; // Save and Restore private int mSaveInstanceStateItemIndex = -1; // Content private ArrayList<ApplicationInfo> mApps; private ArrayList<Object> mWidgets; // Cling private int mClingFocusedX; private int mClingFocusedY; // Caching private Canvas mCanvas; private Drawable mDefaultWidgetBackground; private IconCache mIconCache; private int mDragViewMultiplyColor; // Dimens private int mContentWidth; private int mAppIconSize; private int mMaxAppCellCountX, mMaxAppCellCountY; private int mWidgetCountX, mWidgetCountY; private int mWidgetWidthGap, mWidgetHeightGap; private final int mWidgetPreviewIconPaddedDimension; private final float sWidgetPreviewIconPaddingPercentage = 0.25f; private PagedViewCellLayout mWidgetSpacingLayout; private int mNumAppsPages; private int mNumWidgetPages; // Relating to the scroll and overscroll effects Workspace.ZInterpolator mZInterpolator = new Workspace.ZInterpolator(0.5f); private static float CAMERA_DISTANCE = 6500; private static float TRANSITION_SCALE_FACTOR = 0.74f; private static float TRANSITION_PIVOT = 0.65f; private static float TRANSITION_MAX_ROTATION = 22; private static final boolean PERFORM_OVERSCROLL_ROTATION = true; private AccelerateInterpolator mAlphaInterpolator = new AccelerateInterpolator(0.9f); private DecelerateInterpolator mLeftScreenAlphaInterpolator = new DecelerateInterpolator(4); // Previews & outlines ArrayList<AppsCustomizeAsyncTask> mRunningTasks; private HolographicOutlineHelper mHolographicOutlineHelper; private static final int sPageSleepDelay = 150; public AppsCustomizePagedView(Context context, AttributeSet attrs) { super(context, attrs); mLayoutInflater = LayoutInflater.from(context); mPackageManager = context.getPackageManager(); mApps = new ArrayList<ApplicationInfo>(); mWidgets = new ArrayList<Object>(); mIconCache = ((LauncherApplication) context.getApplicationContext()).getIconCache(); mHolographicOutlineHelper = new HolographicOutlineHelper(); mCanvas = new Canvas(); mRunningTasks = new ArrayList<AppsCustomizeAsyncTask>(); // Save the default widget preview background Resources resources = context.getResources(); mDefaultWidgetBackground = resources.getDrawable(R.drawable.default_widget_preview_holo); mAppIconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size); mDragViewMultiplyColor = resources.getColor(R.color.drag_view_multiply_color); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0); mMaxAppCellCountX = a.getInt(R.styleable.AppsCustomizePagedView_maxAppCellCountX, -1); mMaxAppCellCountY = a.getInt(R.styleable.AppsCustomizePagedView_maxAppCellCountY, -1); mWidgetWidthGap = a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellWidthGap, 0); mWidgetHeightGap = a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellHeightGap, 0); mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2); mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2); mClingFocusedX = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedX, 0); mClingFocusedY = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedY, 0); a.recycle(); mWidgetSpacingLayout = new PagedViewCellLayout(getContext()); // The padding on the non-matched dimension for the default widget preview icons // (top + bottom) mWidgetPreviewIconPaddedDimension = (int) (mAppIconSize * (1 + (2 * sWidgetPreviewIconPaddingPercentage))); mFadeInAdjacentScreens = false; } @Override protected void init() { super.init(); mCenterPagesVertically = false; Context context = getContext(); Resources r = context.getResources(); setDragSlopeThreshold(r.getInteger(R.integer.config_appsCustomizeDragSlopeThreshold)/100f); } @Override protected void onUnhandledTap(MotionEvent ev) { if (LauncherApplication.isScreenLarge()) { // Dismiss AppsCustomize if we tap mLauncher.showWorkspace(true); } } /** Returns the item index of the center item on this page so that we can restore to this * item index when we rotate. */ private int getMiddleComponentIndexOnCurrentPage() { int i = -1; if (getPageCount() > 0) { int currentPage = getCurrentPage(); if (currentPage < mNumAppsPages) { PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(currentPage); PagedViewCellLayoutChildren childrenLayout = layout.getChildrenLayout(); int numItemsPerPage = mCellCountX * mCellCountY; int childCount = childrenLayout.getChildCount(); if (childCount > 0) { i = (currentPage * numItemsPerPage) + (childCount / 2); } } else { int numApps = mApps.size(); PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(currentPage); int numItemsPerPage = mWidgetCountX * mWidgetCountY; int childCount = layout.getChildCount(); if (childCount > 0) { i = numApps + ((currentPage - mNumAppsPages) * numItemsPerPage) + (childCount / 2); } } } return i; } /** Get the index of the item to restore to if we need to restore the current page. */ int getSaveInstanceStateIndex() { if (mSaveInstanceStateItemIndex == -1) { mSaveInstanceStateItemIndex = getMiddleComponentIndexOnCurrentPage(); } return mSaveInstanceStateItemIndex; } /** Returns the page in the current orientation which is expected to contain the specified * item index. */ int getPageForComponent(int index) { if (index < 0) return 0; if (index < mApps.size()) { int numItemsPerPage = mCellCountX * mCellCountY; return (index / numItemsPerPage); } else { int numItemsPerPage = mWidgetCountX * mWidgetCountY; return mNumAppsPages + ((index - mApps.size()) / numItemsPerPage); } } /** * This differs from isDataReady as this is the test done if isDataReady is not set. */ private boolean testDataReady() { // We only do this test once, and we default to the Applications page, so we only really // have to wait for there to be apps. // TODO: What if one of them is validly empty return !mApps.isEmpty() && !mWidgets.isEmpty(); } /** Restores the page for an item at the specified index */ void restorePageForIndex(int index) { if (index < 0) return; mSaveInstanceStateItemIndex = index; } private void updatePageCounts() { mNumWidgetPages = (int) Math.ceil(mWidgets.size() / (float) (mWidgetCountX * mWidgetCountY)); mNumAppsPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY)); } protected void onDataReady(int width, int height) { // Note that we transpose the counts in portrait so that we get a similar layout boolean isLandscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; int maxCellCountX = Integer.MAX_VALUE; int maxCellCountY = Integer.MAX_VALUE; if (LauncherApplication.isScreenLarge()) { maxCellCountX = (isLandscape ? LauncherModel.getCellCountX() : LauncherModel.getCellCountY()); maxCellCountY = (isLandscape ? LauncherModel.getCellCountY() : LauncherModel.getCellCountX()); } if (mMaxAppCellCountX > -1) { maxCellCountX = Math.min(maxCellCountX, mMaxAppCellCountX); } if (mMaxAppCellCountY > -1) { maxCellCountY = Math.min(maxCellCountY, mMaxAppCellCountY); } // Now that the data is ready, we can calculate the content width, the number of cells to // use for each page mWidgetSpacingLayout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap); mWidgetSpacingLayout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, mPageLayoutPaddingRight, mPageLayoutPaddingBottom); mWidgetSpacingLayout.calculateCellCount(width, height, maxCellCountX, maxCellCountY); mCellCountX = mWidgetSpacingLayout.getCellCountX(); mCellCountY = mWidgetSpacingLayout.getCellCountY(); updatePageCounts(); // Force a measure to update recalculate the gaps int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); mWidgetSpacingLayout.measure(widthSpec, heightSpec); mContentWidth = mWidgetSpacingLayout.getContentWidth(); // Restore the page int page = getPageForComponent(mSaveInstanceStateItemIndex); invalidatePageData(Math.max(0, page)); // Calculate the position for the cling punch through int[] offset = new int[2]; int[] pos = mWidgetSpacingLayout.estimateCellPosition(mClingFocusedX, mClingFocusedY); mLauncher.getDragLayer().getLocationInDragLayer(this, offset); pos[0] += (getMeasuredWidth() - mWidgetSpacingLayout.getMeasuredWidth()) / 2 + offset[0]; pos[1] += (getMeasuredHeight() - mWidgetSpacingLayout.getMeasuredHeight()) / 2 + offset[1]; mLauncher.showFirstRunAllAppsCling(pos); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); if (!isDataReady()) { if (testDataReady()) { setDataIsReady(); setMeasuredDimension(width, height); onDataReady(width, height); } } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } /** Removes and returns the ResolveInfo with the specified ComponentName */ private ResolveInfo removeResolveInfoWithComponentName(List<ResolveInfo> list, ComponentName cn) { Iterator<ResolveInfo> iter = list.iterator(); while (iter.hasNext()) { ResolveInfo rinfo = iter.next(); ActivityInfo info = rinfo.activityInfo; ComponentName c = new ComponentName(info.packageName, info.name); if (c.equals(cn)) { iter.remove(); return rinfo; } } return null; } public void onPackagesUpdated() { // TODO: this isn't ideal, but we actually need to delay here. This call is triggered // by a broadcast receiver, and in order for it to work correctly, we need to know that // the AppWidgetService has already received and processed the same broadcast. Since there // is no guarantee about ordering of broadcast receipt, we just delay here. Ideally, // we should have a more precise way of ensuring the AppWidgetService is up to date. postDelayed(new Runnable() { public void run() { updatePackages(); } }, 500); } public void updatePackages() { // Get the list of widgets and shortcuts boolean wasEmpty = mWidgets.isEmpty(); mWidgets.clear(); List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(mLauncher).getInstalledProviders(); Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); List<ResolveInfo> shortcuts = mPackageManager.queryIntentActivities(shortcutsIntent, 0); mWidgets.addAll(widgets); mWidgets.addAll(shortcuts); Collections.sort(mWidgets, new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager)); updatePageCounts(); if (wasEmpty) { // The next layout pass will trigger data-ready if both widgets and apps are set, so request // a layout to do this test and invalidate the page data when ready. if (testDataReady()) requestLayout(); } else { cancelAllTasks(); invalidatePageData(); } } @Override public void onClick(View v) { // When we have exited all apps or are in transition, disregard clicks if (!mLauncher.isAllAppsCustomizeOpen() || mLauncher.getWorkspace().isSwitchingState()) return; if (v instanceof PagedViewIcon) { // Animate some feedback to the click final ApplicationInfo appInfo = (ApplicationInfo) v.getTag(); animateClickFeedback(v, new Runnable() { @Override public void run() { mLauncher.startActivitySafely(appInfo.intent, appInfo); } }); } else if (v instanceof PagedViewWidget) { // Let the user know that they have to long press to add a widget Toast.makeText(getContext(), R.string.long_press_widget_to_add, Toast.LENGTH_SHORT).show(); // Create a little animation to show that the widget can move float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); final ImageView p = (ImageView) v.findViewById(R.id.widget_preview); AnimatorSet bounce = new AnimatorSet(); ValueAnimator tyuAnim = ObjectAnimator.ofFloat(p, "translationY", offsetY); tyuAnim.setDuration(125); ValueAnimator tydAnim = ObjectAnimator.ofFloat(p, "translationY", 0f); tydAnim.setDuration(100); bounce.play(tyuAnim).before(tydAnim); bounce.setInterpolator(new AccelerateInterpolator()); bounce.start(); } } /* * PagedViewWithDraggableItems implementation */ @Override protected void determineDraggingStart(android.view.MotionEvent ev) { // Disable dragging by pulling an app down for now. } private void beginDraggingApplication(View v) { mLauncher.getWorkspace().onDragStartedWithItem(v); mLauncher.getWorkspace().beginDragShared(v, this); } private void beginDraggingWidget(View v) { // Get the widget preview as the drag representation ImageView image = (ImageView) v.findViewById(R.id.widget_preview); PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag(); // Compose the drag image Bitmap b; Drawable preview = image.getDrawable(); RectF mTmpScaleRect = new RectF(0f,0f,1f,1f); image.getImageMatrix().mapRect(mTmpScaleRect); float scale = mTmpScaleRect.right; int w = (int) (preview.getIntrinsicWidth() * scale); int h = (int) (preview.getIntrinsicHeight() * scale); if (createItemInfo instanceof PendingAddWidgetInfo) { PendingAddWidgetInfo createWidgetInfo = (PendingAddWidgetInfo) createItemInfo; int[] spanXY = mLauncher.getSpanForWidget(createWidgetInfo, null); createItemInfo.spanX = spanXY[0]; createItemInfo.spanY = spanXY[1]; b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); renderDrawableToBitmap(preview, b, 0, 0, w, h, scale, mDragViewMultiplyColor); } else { // Workaround for the fact that we don't keep the original ResolveInfo associated with // the shortcut around. To get the icon, we just render the preview image (which has // the shortcut icon) to a new drag bitmap that clips the non-icon space. b = Bitmap.createBitmap(mWidgetPreviewIconPaddedDimension, mWidgetPreviewIconPaddedDimension, Bitmap.Config.ARGB_8888); mCanvas.setBitmap(b); mCanvas.save(); preview.draw(mCanvas); mCanvas.restore(); mCanvas.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY); mCanvas.setBitmap(null); createItemInfo.spanX = createItemInfo.spanY = 1; } // We use a custom alpha clip table for the default widget previews Paint alphaClipPaint = null; if (createItemInfo instanceof PendingAddWidgetInfo) { if (((PendingAddWidgetInfo) createItemInfo).hasDefaultPreview) { MaskFilter alphaClipTable = TableMaskFilter.CreateClipTable(0, 255); alphaClipPaint = new Paint(); alphaClipPaint.setMaskFilter(alphaClipTable); } } // Start the drag mLauncher.lockScreenOrientationOnLargeUI(); mLauncher.getWorkspace().onDragStartedWithItemSpans(createItemInfo.spanX, createItemInfo.spanY, b, alphaClipPaint); mDragController.startDrag(image, b, this, createItemInfo, DragController.DRAG_ACTION_COPY, null); b.recycle(); } @Override protected boolean beginDragging(View v) { // Dismiss the cling mLauncher.dismissAllAppsCling(null); if (!super.beginDragging(v)) return false; // Go into spring loaded mode (must happen before we startDrag()) mLauncher.enterSpringLoadedDragMode(); if (v instanceof PagedViewIcon) { beginDraggingApplication(v); } else if (v instanceof PagedViewWidget) { beginDraggingWidget(v); } return true; } private void endDragging(View target, boolean success) { mLauncher.getWorkspace().onDragStopped(success); if (!success || (target != mLauncher.getWorkspace() && !(target instanceof DeleteDropTarget))) { // Exit spring loaded mode if we have not successfully dropped or have not handled the // drop in Workspace mLauncher.exitSpringLoadedDragMode(); } mLauncher.unlockScreenOrientationOnLargeUI(); } @Override public void onDropCompleted(View target, DragObject d, boolean success) { endDragging(target, success); // Display an error message if the drag failed due to there not being enough space on the // target layout we were dropping on. if (!success) { boolean showOutOfSpaceMessage = false; if (target instanceof Workspace) { int currentScreen = mLauncher.getCurrentWorkspaceScreen(); Workspace workspace = (Workspace) target; CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen); ItemInfo itemInfo = (ItemInfo) d.dragInfo; if (layout != null) { layout.calculateSpans(itemInfo); showOutOfSpaceMessage = !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY); } } if (showOutOfSpaceMessage) { mLauncher.showOutOfSpaceMessage(); } } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); cancelAllTasks(); } private void cancelAllTasks() { // Clean up all the async tasks Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); while (iter.hasNext()) { AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); task.cancel(false); iter.remove(); } } public void setContentType(ContentType type) { if (type == ContentType.Widgets) { invalidatePageData(mNumAppsPages, true); } else if (type == ContentType.Applications) { invalidatePageData(0, true); } } protected void snapToPage(int whichPage, int delta, int duration) { super.snapToPage(whichPage, delta, duration); updateCurrentTab(whichPage); } private void updateCurrentTab(int currentPage) { AppsCustomizeTabHost tabHost = getTabHost(); String tag = tabHost.getCurrentTabTag(); if (tag != null) { if (currentPage >= mNumAppsPages && !tag.equals(tabHost.getTabTagForContentType(ContentType.Widgets))) { tabHost.setCurrentTabFromContent(ContentType.Widgets); } else if (currentPage < mNumAppsPages && !tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) { tabHost.setCurrentTabFromContent(ContentType.Applications); } } } /* * Apps PagedView implementation */ private void setVisibilityOnChildren(ViewGroup layout, int visibility) { int childCount = layout.getChildCount(); for (int i = 0; i < childCount; ++i) { layout.getChildAt(i).setVisibility(visibility); } } private void setupPage(PagedViewCellLayout layout) { layout.setCellCount(mCellCountX, mCellCountY); layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap); layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, mPageLayoutPaddingRight, mPageLayoutPaddingBottom); // Note: We force a measure here to get around the fact that when we do layout calculations // immediately after syncing, we don't have a proper width. That said, we already know the // expected page width, so we can actually optimize by hiding all the TextView-based // children that are expensive to measure, and let that happen naturally later. setVisibilityOnChildren(layout, View.GONE); int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); layout.setMinimumWidth(getPageContentWidth()); layout.measure(widthSpec, heightSpec); setVisibilityOnChildren(layout, View.VISIBLE); } public void syncAppsPageItems(int page, boolean immediate) { // ensure that we have the right number of items on the pages int numCells = mCellCountX * mCellCountY; int startIndex = page * numCells; int endIndex = Math.min(startIndex + numCells, mApps.size()); PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(page); layout.removeAllViewsOnPage(); ArrayList<Object> items = new ArrayList<Object>(); ArrayList<Bitmap> images = new ArrayList<Bitmap>(); for (int i = startIndex; i < endIndex; ++i) { ApplicationInfo info = mApps.get(i); PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate( R.layout.apps_customize_application, layout, false); icon.applyFromApplicationInfo(info, true, mHolographicOutlineHelper); icon.setOnClickListener(this); icon.setOnLongClickListener(this); icon.setOnTouchListener(this); int index = i - startIndex; int x = index % mCellCountX; int y = index / mCellCountX; layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1)); items.add(info); images.add(info.iconBitmap); } layout.createHardwareLayers(); /* TEMPORARILY DISABLE HOLOGRAPHIC ICONS if (mFadeInAdjacentScreens) { prepareGenerateHoloOutlinesTask(page, items, images); } */ } /** * Return the appropriate thread priority for loading for a given page (we give the current * page much higher priority) */ private int getThreadPriorityForPage(int page) { // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below int pageDiff = Math.abs(page - mCurrentPage); if (pageDiff <= 0) { // return Process.THREAD_PRIORITY_DEFAULT; return Process.THREAD_PRIORITY_MORE_FAVORABLE; } else if (pageDiff <= 1) { // return Process.THREAD_PRIORITY_BACKGROUND; return Process.THREAD_PRIORITY_DEFAULT; } else { // return Process.THREAD_PRIORITY_LOWEST; return Process.THREAD_PRIORITY_DEFAULT; } } private int getSleepForPage(int page) { int pageDiff = Math.abs(page - mCurrentPage) - 1; return Math.max(0, pageDiff * sPageSleepDelay); } /** * Creates and executes a new AsyncTask to load a page of widget previews. */ private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets, int cellWidth, int cellHeight, int cellCountX) { // Prune all tasks that are no longer needed Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); while (iter.hasNext()) { AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); int taskPage = task.page; if ((taskPage == page) || taskPage < getAssociatedLowerPageBound(mCurrentPage - mNumAppsPages) || taskPage > getAssociatedUpperPageBound(mCurrentPage - mNumAppsPages)) { task.cancel(false); iter.remove(); } else { task.setThreadPriority(getThreadPriorityForPage(taskPage + mNumAppsPages)); } } // We introduce a slight delay to order the loading of side pages so that we don't thrash final int sleepMs = getSleepForPage(page + mNumAppsPages); AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight, cellCountX, new AsyncTaskCallback() { @Override public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { try { try { Thread.sleep(sleepMs); } catch (Exception e) {} loadWidgetPreviewsInBackground(task, data); } finally { if (task.isCancelled()) { data.cleanup(true); } } } }, new AsyncTaskCallback() { @Override public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { try { mRunningTasks.remove(task); if (task.isCancelled()) return; onSyncWidgetPageItems(data); } finally { data.cleanup(task.isCancelled()); } } }); // Ensure that the task is appropriately prioritized and runs in parallel AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page, AsyncTaskPageData.Type.LoadWidgetPreviewData); t.setThreadPriority(getThreadPriorityForPage(page)); t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData); mRunningTasks.add(t); } /** * Creates and executes a new AsyncTask to load the outlines for a page of content. */ private void prepareGenerateHoloOutlinesTask(int page, ArrayList<Object> items, ArrayList<Bitmap> images) { // Prune old tasks for this page Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); while (iter.hasNext()) { AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); int taskPage = task.page; if ((taskPage == page) && (task.dataType == AsyncTaskPageData.Type.LoadHolographicIconsData)) { task.cancel(false); iter.remove(); } } AsyncTaskPageData pageData = new AsyncTaskPageData(page, items, images, new AsyncTaskCallback() { @Override public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { try { // Ensure that this task starts running at the correct priority task.syncThreadPriority(); ArrayList<Bitmap> images = data.generatedImages; ArrayList<Bitmap> srcImages = data.sourceImages; int count = srcImages.size(); Canvas c = new Canvas(); for (int i = 0; i < count && !task.isCancelled(); ++i) { // Before work on each item, ensure that this task is running at the correct // priority task.syncThreadPriority(); Bitmap b = srcImages.get(i); Bitmap outline = Bitmap.createBitmap(b.getWidth(), b.getHeight(), Bitmap.Config.ARGB_8888); c.setBitmap(outline); c.save(); c.drawBitmap(b, 0, 0, null); c.restore(); c.setBitmap(null); images.add(outline); } } finally { if (task.isCancelled()) { data.cleanup(true); } } } }, new AsyncTaskCallback() { @Override public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { try { mRunningTasks.remove(task); if (task.isCancelled()) return; onHolographicPageItemsLoaded(data); } finally { data.cleanup(task.isCancelled()); } } }); // Ensure that the outline task always runs in the background, serially AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page, AsyncTaskPageData.Type.LoadHolographicIconsData); t.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); t.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, pageData); mRunningTasks.add(t); } /* * Widgets PagedView implementation */ private void setupPage(PagedViewGridLayout layout) { layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, mPageLayoutPaddingRight, mPageLayoutPaddingBottom); // Note: We force a measure here to get around the fact that when we do layout calculations // immediately after syncing, we don't have a proper width. int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); layout.setMinimumWidth(getPageContentWidth()); layout.measure(widthSpec, heightSpec); } private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h) { renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f, 0xFFFFFFFF); } private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h, float scale) { renderDrawableToBitmap(d, bitmap, x, y, w, h, scale, 0xFFFFFFFF); } private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h, float scale, int multiplyColor) { if (bitmap != null) { Canvas c = new Canvas(bitmap); c.scale(scale, scale); Rect oldBounds = d.copyBounds(); d.setBounds(x, y, x + w, y + h); d.draw(c); d.setBounds(oldBounds); // Restore the bounds if (multiplyColor != 0xFFFFFFFF) { c.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY); } c.setBitmap(null); } } private Bitmap getShortcutPreview(ResolveInfo info, int cellWidth, int cellHeight) { // Render the background int offset = 0; int bitmapSize = mAppIconSize; Bitmap preview = Bitmap.createBitmap(bitmapSize, bitmapSize, Config.ARGB_8888); // Render the icon Drawable icon = mIconCache.getFullResIcon(info); renderDrawableToBitmap(icon, preview, offset, offset, mAppIconSize, mAppIconSize); return preview; } private Bitmap getWidgetPreview(AppWidgetProviderInfo info, int cellHSpan, int cellVSpan, int cellWidth, int cellHeight) { // Load the preview image if possible String packageName = info.provider.getPackageName(); Drawable drawable = null; Bitmap preview = null; if (info.previewImage != 0) { drawable = mPackageManager.getDrawable(packageName, info.previewImage, null); if (drawable == null) { Log.w(LOG_TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon) + " for provider: " + info.provider); } else { // Map the target width/height to the cell dimensions int targetWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan); int targetHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan); int targetCellWidth; int targetCellHeight; if (targetWidth >= targetHeight) { targetCellWidth = Math.min(targetWidth, cellWidth); targetCellHeight = (int) (cellHeight * ((float) targetCellWidth / cellWidth)); } else { targetCellHeight = Math.min(targetHeight, cellHeight); targetCellWidth = (int) (cellWidth * ((float) targetCellHeight / cellHeight)); } // Map the preview to the target cell dimensions int bitmapWidth = Math.min(targetCellWidth, drawable.getIntrinsicWidth()); int bitmapHeight = (int) (drawable.getIntrinsicHeight() * ((float) bitmapWidth / drawable.getIntrinsicWidth())); preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888); renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth, bitmapHeight); } } // Generate a preview image if we couldn't load one if (drawable == null) { // TODO: This actually uses the apps customize cell layout params, where as we make want // the Workspace params for more accuracy. int targetWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan); int targetHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan); int bitmapWidth = targetWidth; int bitmapHeight = targetHeight; int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage); float iconScale = 1f; // Determine the size of the bitmap we want to draw if (cellHSpan == cellVSpan) { // For square widgets, we just have a fixed size for 1x1 and larger-than-1x1 if (cellHSpan <= 1) { bitmapWidth = bitmapHeight = mAppIconSize + 2 * minOffset; } else { bitmapWidth = bitmapHeight = mAppIconSize + 4 * minOffset; } } else { // Otherwise, ensure that we are properly sized within the cellWidth/Height if (targetWidth >= targetHeight) { bitmapWidth = Math.min(targetWidth, cellWidth); bitmapHeight = (int) (targetHeight * ((float) bitmapWidth / targetWidth)); iconScale = Math.min((float) bitmapHeight / (mAppIconSize + 2 * minOffset), 1f); } else { bitmapHeight = Math.min(targetHeight, cellHeight); bitmapWidth = (int) (targetWidth * ((float) bitmapHeight / targetHeight)); iconScale = Math.min((float) bitmapWidth / (mAppIconSize + 2 * minOffset), 1f); } } preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888); if (cellHSpan != 1 || cellVSpan != 1) { renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, bitmapWidth, bitmapHeight); } // Draw the icon in the top left corner try { Drawable icon = null; int hoffset = (int) (bitmapWidth / 2 - mAppIconSize * iconScale / 2); int yoffset = (int) (bitmapHeight / 2 - mAppIconSize * iconScale / 2); if (info.icon > 0) icon = mIconCache.getFullResIcon(packageName, info.icon); + Resources resources = mLauncher.getResources(); if (icon == null) icon = resources.getDrawable(R.drawable.ic_launcher_application); renderDrawableToBitmap(icon, preview, hoffset, yoffset, (int) (mAppIconSize * iconScale), (int) (mAppIconSize * iconScale)); } catch (Resources.NotFoundException e) {} } return preview; } public void syncWidgetPageItems(int page, boolean immediate) { int numItemsPerPage = mWidgetCountX * mWidgetCountY; int contentWidth = mWidgetSpacingLayout.getContentWidth(); int contentHeight = mWidgetSpacingLayout.getContentHeight(); // Calculate the dimensions of each cell we are giving to each widget ArrayList<Object> items = new ArrayList<Object>(); int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX); int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY); // Prepare the set of widgets to load previews for in the background int offset = page * numItemsPerPage; for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) { items.add(mWidgets.get(i)); } // Prepopulate the pages with the other widget info, and fill in the previews later PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page + mNumAppsPages); layout.setColumnCount(layout.getCellCountX()); for (int i = 0; i < items.size(); ++i) { Object rawInfo = items.get(i); PendingAddItemInfo createItemInfo = null; PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate( R.layout.apps_customize_widget, layout, false); if (rawInfo instanceof AppWidgetProviderInfo) { // Fill in the widget information AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo; createItemInfo = new PendingAddWidgetInfo(info, null, null); int[] cellSpans = mLauncher.getSpanForWidget(info, null); widget.applyFromAppWidgetProviderInfo(info, -1, cellSpans, mHolographicOutlineHelper); widget.setTag(createItemInfo); } else if (rawInfo instanceof ResolveInfo) { // Fill in the shortcuts information ResolveInfo info = (ResolveInfo) rawInfo; createItemInfo = new PendingAddItemInfo(); createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; createItemInfo.componentName = new ComponentName(info.activityInfo.packageName, info.activityInfo.name); widget.applyFromResolveInfo(mPackageManager, info, mHolographicOutlineHelper); widget.setTag(createItemInfo); } widget.setOnClickListener(this); widget.setOnLongClickListener(this); widget.setOnTouchListener(this); // Layout each widget int ix = i % mWidgetCountX; int iy = i / mWidgetCountX; GridLayout.LayoutParams lp = new GridLayout.LayoutParams( GridLayout.spec(iy, GridLayout.LEFT), GridLayout.spec(ix, GridLayout.TOP)); lp.width = cellWidth; lp.height = cellHeight; lp.setGravity(Gravity.TOP | Gravity.LEFT); if (ix > 0) lp.leftMargin = mWidgetWidthGap; if (iy > 0) lp.topMargin = mWidgetHeightGap; layout.addView(widget, lp); } // Load the widget previews if (immediate) { AsyncTaskPageData data = new AsyncTaskPageData(page, items, cellWidth, cellHeight, mWidgetCountX, null, null); loadWidgetPreviewsInBackground(null, data); onSyncWidgetPageItems(data); } else { prepareLoadWidgetPreviewsTask(page, items, cellWidth, cellHeight, mWidgetCountX); } } private void loadWidgetPreviewsInBackground(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { if (task != null) { // Ensure that this task starts running at the correct priority task.syncThreadPriority(); } // Load each of the widget/shortcut previews ArrayList<Object> items = data.items; ArrayList<Bitmap> images = data.generatedImages; int count = items.size(); int cellWidth = data.cellWidth; int cellHeight = data.cellHeight; for (int i = 0; i < count; ++i) { if (task != null) { // Ensure we haven't been cancelled yet if (task.isCancelled()) break; // Before work on each item, ensure that this task is running at the correct // priority task.syncThreadPriority(); } Object rawInfo = items.get(i); if (rawInfo instanceof AppWidgetProviderInfo) { AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo; int[] cellSpans = mLauncher.getSpanForWidget(info, null); images.add(getWidgetPreview(info, cellSpans[0],cellSpans[1], cellWidth, cellHeight)); } else if (rawInfo instanceof ResolveInfo) { // Fill in the shortcuts information ResolveInfo info = (ResolveInfo) rawInfo; images.add(getShortcutPreview(info, cellWidth, cellHeight)); } } } private void onSyncWidgetPageItems(AsyncTaskPageData data) { int page = data.page; PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page + mNumAppsPages); ArrayList<Object> items = data.items; int count = items.size(); for (int i = 0; i < count; ++i) { PagedViewWidget widget = (PagedViewWidget) layout.getChildAt(i); if (widget != null) { Bitmap preview = data.generatedImages.get(i); boolean scale = (preview.getWidth() >= data.cellWidth || preview.getHeight() >= data.cellHeight); widget.applyPreview(new FastBitmapDrawable(preview), i, scale); } } layout.createHardwareLayer(); invalidate(); /* TEMPORARILY DISABLE HOLOGRAPHIC ICONS if (mFadeInAdjacentScreens) { prepareGenerateHoloOutlinesTask(data.page, data.items, data.generatedImages); } */ } private void onHolographicPageItemsLoaded(AsyncTaskPageData data) { // Invalidate early to short-circuit children invalidates invalidate(); int page = data.page; ViewGroup layout = (ViewGroup) getPageAt(page); if (layout instanceof PagedViewCellLayout) { PagedViewCellLayout cl = (PagedViewCellLayout) layout; int count = cl.getPageChildCount(); if (count != data.generatedImages.size()) return; for (int i = 0; i < count; ++i) { PagedViewIcon icon = (PagedViewIcon) cl.getChildOnPageAt(i); icon.setHolographicOutline(data.generatedImages.get(i)); } } else { int count = layout.getChildCount(); if (count != data.generatedImages.size()) return; for (int i = 0; i < count; ++i) { View v = layout.getChildAt(i); ((PagedViewWidget) v).setHolographicOutline(data.generatedImages.get(i)); } } } @Override public void syncPages() { removeAllViews(); cancelAllTasks(); Context context = getContext(); for (int j = 0; j < mNumWidgetPages; ++j) { PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX, mWidgetCountY); setupPage(layout); addView(layout, new PagedViewGridLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } for (int i = 0; i < mNumAppsPages; ++i) { PagedViewCellLayout layout = new PagedViewCellLayout(context); setupPage(layout); addView(layout); } } @Override public void syncPageItems(int page, boolean immediate) { if (page < mNumAppsPages) { syncAppsPageItems(page, immediate); } else { syncWidgetPageItems(page - mNumAppsPages, immediate); } } // We want our pages to be z-ordered such that the further a page is to the left, the higher // it is in the z-order. This is important to insure touch events are handled correctly. View getPageAt(int index) { return getChildAt(getChildCount() - index - 1); } @Override protected int indexToPage(int index) { return getChildCount() - index - 1; } // In apps customize, we have a scrolling effect which emulates pulling cards off of a stack. @Override protected void screenScrolled(int screenCenter) { super.screenScrolled(screenCenter); for (int i = 0; i < getChildCount(); i++) { View v = getPageAt(i); if (v != null) { float scrollProgress = getScrollProgress(screenCenter, v, i); float interpolatedProgress = mZInterpolator.getInterpolation(Math.abs(Math.min(scrollProgress, 0))); float scale = (1 - interpolatedProgress) + interpolatedProgress * TRANSITION_SCALE_FACTOR; float translationX = Math.min(0, scrollProgress) * v.getMeasuredWidth(); float alpha; if (!LauncherApplication.isScreenLarge() || scrollProgress < 0) { alpha = scrollProgress < 0 ? mAlphaInterpolator.getInterpolation( 1 - Math.abs(scrollProgress)) : 1.0f; } else { // On large screens we need to fade the page as it nears its leftmost position alpha = mLeftScreenAlphaInterpolator.getInterpolation(1 - scrollProgress); } v.setCameraDistance(mDensity * CAMERA_DISTANCE); int pageWidth = v.getMeasuredWidth(); int pageHeight = v.getMeasuredHeight(); if (PERFORM_OVERSCROLL_ROTATION) { if (i == 0 && scrollProgress < 0) { // Overscroll to the left v.setPivotX(TRANSITION_PIVOT * pageWidth); v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress); scale = 1.0f; alpha = 1.0f; // On the first page, we don't want the page to have any lateral motion translationX = getScrollX(); } else if (i == getChildCount() - 1 && scrollProgress > 0) { // Overscroll to the right v.setPivotX((1 - TRANSITION_PIVOT) * pageWidth); v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress); scale = 1.0f; alpha = 1.0f; // On the last page, we don't want the page to have any lateral motion. translationX = getScrollX() - mMaxScrollX; } else { v.setPivotY(pageHeight / 2.0f); v.setPivotX(pageWidth / 2.0f); v.setRotationY(0f); } } v.setTranslationX(translationX); v.setScaleX(scale); v.setScaleY(scale); v.setAlpha(alpha); // If the view has 0 alpha, we set it to be invisible so as to prevent // it from accepting touches if (alpha < ViewConfiguration.ALPHA_THRESHOLD) { v.setVisibility(INVISIBLE); } else if (v.getVisibility() != VISIBLE) { v.setVisibility(VISIBLE); } } } } protected void overScroll(float amount) { acceleratedOverScroll(amount); } /** * Used by the parent to get the content width to set the tab bar to * @return */ public int getPageContentWidth() { return mContentWidth; } @Override protected void onPageEndMoving() { super.onPageEndMoving(); // We reset the save index when we change pages so that it will be recalculated on next // rotation mSaveInstanceStateItemIndex = -1; } /* * AllAppsView implementation */ @Override public void setup(Launcher launcher, DragController dragController) { mLauncher = launcher; mDragController = dragController; } @Override public void zoom(float zoom, boolean animate) { // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed() } @Override public boolean isVisible() { return (getVisibility() == VISIBLE); } @Override public boolean isAnimating() { return false; } @Override public void setApps(ArrayList<ApplicationInfo> list) { mApps = list; Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR); updatePageCounts(); // The next layout pass will trigger data-ready if both widgets and apps are set, so // request a layout to do this test and invalidate the page data when ready. if (testDataReady()) requestLayout(); } private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) { // We add it in place, in alphabetical order int count = list.size(); for (int i = 0; i < count; ++i) { ApplicationInfo info = list.get(i); int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR); if (index < 0) { mApps.add(-(index + 1), info); } } } @Override public void addApps(ArrayList<ApplicationInfo> list) { addAppsWithoutInvalidate(list); updatePageCounts(); invalidatePageData(); } private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) { ComponentName removeComponent = item.intent.getComponent(); int length = list.size(); for (int i = 0; i < length; ++i) { ApplicationInfo info = list.get(i); if (info.intent.getComponent().equals(removeComponent)) { return i; } } return -1; } private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) { // loop through all the apps and remove apps that have the same component int length = list.size(); for (int i = 0; i < length; ++i) { ApplicationInfo info = list.get(i); int removeIndex = findAppByComponent(mApps, info); if (removeIndex > -1) { mApps.remove(removeIndex); } } } @Override public void removeApps(ArrayList<ApplicationInfo> list) { removeAppsWithoutInvalidate(list); updatePageCounts(); invalidatePageData(); } @Override public void updateApps(ArrayList<ApplicationInfo> list) { // We remove and re-add the updated applications list because it's properties may have // changed (ie. the title), and this will ensure that the items will be in their proper // place in the list. removeAppsWithoutInvalidate(list); addAppsWithoutInvalidate(list); updatePageCounts(); invalidatePageData(); } @Override public void reset() { AppsCustomizeTabHost tabHost = getTabHost(); String tag = tabHost.getCurrentTabTag(); if (tag != null) { if (!tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) { tabHost.setCurrentTabFromContent(ContentType.Applications); } } if (mCurrentPage != 0) { invalidatePageData(0); } } private AppsCustomizeTabHost getTabHost() { return (AppsCustomizeTabHost) mLauncher.findViewById(R.id.apps_customize_pane); } @Override public void dumpState() { // TODO: Dump information related to current list of Applications, Widgets, etc. ApplicationInfo.dumpApplicationInfoList(LOG_TAG, "mApps", mApps); dumpAppWidgetProviderInfoList(LOG_TAG, "mWidgets", mWidgets); } private void dumpAppWidgetProviderInfoList(String tag, String label, ArrayList<Object> list) { Log.d(tag, label + " size=" + list.size()); for (Object i: list) { if (i instanceof AppWidgetProviderInfo) { AppWidgetProviderInfo info = (AppWidgetProviderInfo) i; Log.d(tag, " label=\"" + info.label + "\" previewImage=" + info.previewImage + " resizeMode=" + info.resizeMode + " configure=" + info.configure + " initialLayout=" + info.initialLayout + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight); } else if (i instanceof ResolveInfo) { ResolveInfo info = (ResolveInfo) i; Log.d(tag, " label=\"" + info.loadLabel(mPackageManager) + "\" icon=" + info.icon); } } } @Override public void surrender() { // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we // should stop this now. // Stop all background tasks cancelAllTasks(); } /* * We load an extra page on each side to prevent flashes from scrolling and loading of the * widget previews in the background with the AsyncTasks. */ protected int getAssociatedLowerPageBound(int page) { return Math.max(0, page - 2); } protected int getAssociatedUpperPageBound(int page) { final int count = getChildCount(); return Math.min(page + 2, count - 1); } @Override protected String getCurrentPageDescription() { int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; int stringId = R.string.default_scroll_format; int count = 0; if (page < mNumAppsPages) { stringId = R.string.apps_customize_apps_scroll_format; count = mNumAppsPages; } else { page -= mNumAppsPages; stringId = R.string.apps_customize_widgets_scroll_format; count = mNumWidgetPages; } return String.format(mContext.getString(stringId), page + 1, count); } }
true
true
private Bitmap getWidgetPreview(AppWidgetProviderInfo info, int cellHSpan, int cellVSpan, int cellWidth, int cellHeight) { // Load the preview image if possible String packageName = info.provider.getPackageName(); Drawable drawable = null; Bitmap preview = null; if (info.previewImage != 0) { drawable = mPackageManager.getDrawable(packageName, info.previewImage, null); if (drawable == null) { Log.w(LOG_TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon) + " for provider: " + info.provider); } else { // Map the target width/height to the cell dimensions int targetWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan); int targetHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan); int targetCellWidth; int targetCellHeight; if (targetWidth >= targetHeight) { targetCellWidth = Math.min(targetWidth, cellWidth); targetCellHeight = (int) (cellHeight * ((float) targetCellWidth / cellWidth)); } else { targetCellHeight = Math.min(targetHeight, cellHeight); targetCellWidth = (int) (cellWidth * ((float) targetCellHeight / cellHeight)); } // Map the preview to the target cell dimensions int bitmapWidth = Math.min(targetCellWidth, drawable.getIntrinsicWidth()); int bitmapHeight = (int) (drawable.getIntrinsicHeight() * ((float) bitmapWidth / drawable.getIntrinsicWidth())); preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888); renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth, bitmapHeight); } } // Generate a preview image if we couldn't load one if (drawable == null) { // TODO: This actually uses the apps customize cell layout params, where as we make want // the Workspace params for more accuracy. int targetWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan); int targetHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan); int bitmapWidth = targetWidth; int bitmapHeight = targetHeight; int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage); float iconScale = 1f; // Determine the size of the bitmap we want to draw if (cellHSpan == cellVSpan) { // For square widgets, we just have a fixed size for 1x1 and larger-than-1x1 if (cellHSpan <= 1) { bitmapWidth = bitmapHeight = mAppIconSize + 2 * minOffset; } else { bitmapWidth = bitmapHeight = mAppIconSize + 4 * minOffset; } } else { // Otherwise, ensure that we are properly sized within the cellWidth/Height if (targetWidth >= targetHeight) { bitmapWidth = Math.min(targetWidth, cellWidth); bitmapHeight = (int) (targetHeight * ((float) bitmapWidth / targetWidth)); iconScale = Math.min((float) bitmapHeight / (mAppIconSize + 2 * minOffset), 1f); } else { bitmapHeight = Math.min(targetHeight, cellHeight); bitmapWidth = (int) (targetWidth * ((float) bitmapHeight / targetHeight)); iconScale = Math.min((float) bitmapWidth / (mAppIconSize + 2 * minOffset), 1f); } } preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888); if (cellHSpan != 1 || cellVSpan != 1) { renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, bitmapWidth, bitmapHeight); } // Draw the icon in the top left corner try { Drawable icon = null; int hoffset = (int) (bitmapWidth / 2 - mAppIconSize * iconScale / 2); int yoffset = (int) (bitmapHeight / 2 - mAppIconSize * iconScale / 2); if (info.icon > 0) icon = mIconCache.getFullResIcon(packageName, info.icon); if (icon == null) icon = resources.getDrawable(R.drawable.ic_launcher_application); renderDrawableToBitmap(icon, preview, hoffset, yoffset, (int) (mAppIconSize * iconScale), (int) (mAppIconSize * iconScale)); } catch (Resources.NotFoundException e) {} } return preview; }
private Bitmap getWidgetPreview(AppWidgetProviderInfo info, int cellHSpan, int cellVSpan, int cellWidth, int cellHeight) { // Load the preview image if possible String packageName = info.provider.getPackageName(); Drawable drawable = null; Bitmap preview = null; if (info.previewImage != 0) { drawable = mPackageManager.getDrawable(packageName, info.previewImage, null); if (drawable == null) { Log.w(LOG_TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon) + " for provider: " + info.provider); } else { // Map the target width/height to the cell dimensions int targetWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan); int targetHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan); int targetCellWidth; int targetCellHeight; if (targetWidth >= targetHeight) { targetCellWidth = Math.min(targetWidth, cellWidth); targetCellHeight = (int) (cellHeight * ((float) targetCellWidth / cellWidth)); } else { targetCellHeight = Math.min(targetHeight, cellHeight); targetCellWidth = (int) (cellWidth * ((float) targetCellHeight / cellHeight)); } // Map the preview to the target cell dimensions int bitmapWidth = Math.min(targetCellWidth, drawable.getIntrinsicWidth()); int bitmapHeight = (int) (drawable.getIntrinsicHeight() * ((float) bitmapWidth / drawable.getIntrinsicWidth())); preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888); renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth, bitmapHeight); } } // Generate a preview image if we couldn't load one if (drawable == null) { // TODO: This actually uses the apps customize cell layout params, where as we make want // the Workspace params for more accuracy. int targetWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan); int targetHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan); int bitmapWidth = targetWidth; int bitmapHeight = targetHeight; int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage); float iconScale = 1f; // Determine the size of the bitmap we want to draw if (cellHSpan == cellVSpan) { // For square widgets, we just have a fixed size for 1x1 and larger-than-1x1 if (cellHSpan <= 1) { bitmapWidth = bitmapHeight = mAppIconSize + 2 * minOffset; } else { bitmapWidth = bitmapHeight = mAppIconSize + 4 * minOffset; } } else { // Otherwise, ensure that we are properly sized within the cellWidth/Height if (targetWidth >= targetHeight) { bitmapWidth = Math.min(targetWidth, cellWidth); bitmapHeight = (int) (targetHeight * ((float) bitmapWidth / targetWidth)); iconScale = Math.min((float) bitmapHeight / (mAppIconSize + 2 * minOffset), 1f); } else { bitmapHeight = Math.min(targetHeight, cellHeight); bitmapWidth = (int) (targetWidth * ((float) bitmapHeight / targetHeight)); iconScale = Math.min((float) bitmapWidth / (mAppIconSize + 2 * minOffset), 1f); } } preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888); if (cellHSpan != 1 || cellVSpan != 1) { renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, bitmapWidth, bitmapHeight); } // Draw the icon in the top left corner try { Drawable icon = null; int hoffset = (int) (bitmapWidth / 2 - mAppIconSize * iconScale / 2); int yoffset = (int) (bitmapHeight / 2 - mAppIconSize * iconScale / 2); if (info.icon > 0) icon = mIconCache.getFullResIcon(packageName, info.icon); Resources resources = mLauncher.getResources(); if (icon == null) icon = resources.getDrawable(R.drawable.ic_launcher_application); renderDrawableToBitmap(icon, preview, hoffset, yoffset, (int) (mAppIconSize * iconScale), (int) (mAppIconSize * iconScale)); } catch (Resources.NotFoundException e) {} } return preview; }
diff --git a/zazl/maqetta.zazl/src/maqetta/zazl/HTMLParser.java b/zazl/maqetta.zazl/src/maqetta/zazl/HTMLParser.java index 4fa5bb9a8..ba2104f6f 100644 --- a/zazl/maqetta.zazl/src/maqetta/zazl/HTMLParser.java +++ b/zazl/maqetta.zazl/src/maqetta/zazl/HTMLParser.java @@ -1,122 +1,125 @@ package maqetta.zazl; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLAttributes; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.parser.XMLDocumentFilter; import org.apache.xerces.xni.parser.XMLInputSource; import org.cyberneko.html.HTMLConfiguration; import org.cyberneko.html.filters.DefaultFilter; import org.cyberneko.html.filters.Identity; import org.cyberneko.html.filters.Writer; import org.davinci.ajaxLibrary.Library; public class HTMLParser extends DefaultFilter { private static final String AUGMENTATIONS = "http://cyberneko.org/html/features/augmentations"; private static final String FILTERS = "http://cyberneko.org/html/properties/filters"; private static final String SCRIPT_TYPE = "text/javascript"; private HTMLConfiguration parser = null; private String encoding = null; private String scriptURLPrefix = null; private String scriptURL = null; private String dojoDefaultRoot = null; private String configScriptTag = null; public HTMLParser(java.io.Writer out, String encoding, Library dojoLib, String configScriptTag) { this.encoding = encoding; this.configScriptTag = configScriptTag; dojoDefaultRoot = dojoLib.getDefaultRoot().substring(1); parser = new HTMLConfiguration(); parser.setFeature(AUGMENTATIONS, true); XMLDocumentFilter[] filters = { this, new Identity(), new HTMLWriter(out, this.encoding) }; parser.setProperty(FILTERS, filters); } public void parse(String html) throws IOException { parser.parse(new XMLInputSource(null, "", null, new StringReader(html), encoding)); } public void startDocument(XMLLocator locator, String encoding, Augmentations augs) throws XNIException { super.startDocument(locator, encoding, augs); } public void startElement(QName element, XMLAttributes attrs, Augmentations augs) throws XNIException { if (element.rawname.equalsIgnoreCase("script") && attrs != null) { String value = attrs.getValue("type"); if (value != null && value.equalsIgnoreCase(SCRIPT_TYPE)) { String src = attrs.getValue("src"); if (src != null && src.indexOf(dojoDefaultRoot+"/dojo/dojo.js") != -1) { scriptURL = src; scriptURLPrefix = scriptURL.substring(0, scriptURL.indexOf(dojoDefaultRoot+"/dojo/dojo.js")); configScriptTag = configScriptTag.replace("__URLPREFIX__", scriptURLPrefix); } } } super.startElement(element, attrs, augs); } public class HTMLWriter extends Writer { PrintWriter pw = null; public HTMLWriter(java.io.Writer out, String encoding) { super(out, encoding); } protected void printStartElement(QName element, XMLAttributes attrs) throws XNIException { if (element.rawname.equalsIgnoreCase("script") && attrs != null) { String value = attrs.getValue("type"); if (value != null && value.equalsIgnoreCase(SCRIPT_TYPE)) { String src = attrs.getValue("src"); if (src != null && src.equals(scriptURL)) { attrs.setValue(attrs.getIndex("src"), scriptURLPrefix+"lib/zazl/zazl.js"); attrs.removeAttributeAt(attrs.getIndex("data-dojo-config")); } super.printStartElement(element, attrs); } else { super.printStartElement(element, attrs); } } else { super.printStartElement(element, attrs); } } protected void printEndElement(QName element) throws XNIException { super.printEndElement(element); if (element.rawname.equalsIgnoreCase("script")) { if (scriptURL != null && scriptURL.indexOf(dojoDefaultRoot+"/dojo/dojo.js") != -1) { fPrinter.println(); fPrinter.println(configScriptTag); scriptURL = null; } } } protected void printAttributeValue(String text) { int length = text.length(); for (int j = 0; j < length; j++) { char c = text.charAt(j); switch (c) { case '"': fPrinter.print("&quot;"); break; case '<': fPrinter.print("&lt;"); break; case '>': fPrinter.print("&gt;"); break; + case '&': + fPrinter.print("&amp;"); + break; default: fPrinter.print(c); } } fPrinter.flush(); } } }
true
true
protected void printAttributeValue(String text) { int length = text.length(); for (int j = 0; j < length; j++) { char c = text.charAt(j); switch (c) { case '"': fPrinter.print("&quot;"); break; case '<': fPrinter.print("&lt;"); break; case '>': fPrinter.print("&gt;"); break; default: fPrinter.print(c); } } fPrinter.flush(); }
protected void printAttributeValue(String text) { int length = text.length(); for (int j = 0; j < length; j++) { char c = text.charAt(j); switch (c) { case '"': fPrinter.print("&quot;"); break; case '<': fPrinter.print("&lt;"); break; case '>': fPrinter.print("&gt;"); break; case '&': fPrinter.print("&amp;"); break; default: fPrinter.print(c); } } fPrinter.flush(); }
diff --git a/client/src/main/java/hudson/plugins/swarm/Client.java b/client/src/main/java/hudson/plugins/swarm/Client.java index 85cfa2a..1abae19 100644 --- a/client/src/main/java/hudson/plugins/swarm/Client.java +++ b/client/src/main/java/hudson/plugins/swarm/Client.java @@ -1,264 +1,264 @@ package hudson.plugins.swarm; import hudson.remoting.Launcher; import hudson.remoting.jnlp.Main; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; import org.xml.sax.SAXException; import org.kohsuke.args4j.Option; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.CmdLineException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLEncoder; import java.util.List; import java.util.ArrayList; import java.util.Random; /** * Swarm client. * * <p> * Discovers nearby Hudson via UDP broadcast, and pick eligible one randomly and joins it. * * @author Kohsuke Kawaguchi */ public class Client { /** * Used to discover the server. */ protected final DatagramSocket socket; /** * The Hudson that we are trying to connect to. */ protected Candidate target; @Option(name="-name",usage="Name of the slave") public String name; @Option(name="-description",usage="Description to be put on the slave") public String description; @Option(name="-labels",usage="Whitespace-separated list of labels to be assigned for this slave") public String labels; @Option(name="-fsroot",usage="Directory where Hudson places files") public File remoteFsRoot = new File("."); @Option(name="-executors",usage="Number of executors") public int executors = Runtime.getRuntime().availableProcessors(); public static void main(String... args) throws InterruptedException, IOException { Client client = new Client(); CmdLineParser p = new CmdLineParser(client); try { p.parseArgument(args); } catch (CmdLineException e) { System.out.println(e.getMessage()); p.printUsage(System.out); System.exit(-1); } client.run(); } public Client() throws IOException { socket = new DatagramSocket(); socket.setBroadcast(true); name = InetAddress.getLocalHost().getCanonicalHostName(); } class Candidate { final String url; final String secret; Candidate(String url, String secret) { this.url = url; this.secret = secret; } } /** * Finds a Hudson master that supports swarming, and join it. * * This method never returns. */ public void run() throws InterruptedException { System.out.println("Discovering Hudson master"); // wait until we get the ACK back while(true) { try { List<Candidate> candidates = new ArrayList<Candidate>(); for (DatagramPacket recv : discover()) { String responseXml = new String(recv.getData(), 0, recv.getLength()); Document xml; try { xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( new ByteArrayInputStream(recv.getData(), 0, recv.getLength())); } catch (SAXException e) { System.out.println("Invalid response XML from "+recv.getAddress()+": "+ responseXml); continue; } String swarm = getChildElementString(xml.getDocumentElement(), "swarm"); if(swarm==null) { System.out.println(recv.getAddress()+" doesn't support swarm"); continue; } String url = getChildElementString(xml.getDocumentElement(), "url"); if(url==null) { - System.out.println("No <url> in XML from "+recv.getAddress()+": "+ responseXml); + System.out.println(recv.getAddress()+" doesn't have the URL configuration yet. "+ responseXml); continue; } candidates.add(new Candidate(url,swarm)); } if(candidates.size()==0) throw new RetryException("No nearby Hudson supports swarming"); System.out.println("Found "+candidates.size()+" eligible Hudson."); // randomly pick up the Hudson to connect to target = candidates.get(new Random().nextInt(candidates.size())); verifyThatUrlIsHudson(); // create a new swarm slave createSwarmSlave(); connect(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (RetryException e) { System.out.println(e.getMessage()); if(e.getCause()!=null) e.getCause().printStackTrace(); } // retry System.out.println("Retrying in 10 seconds"); Thread.sleep(10*1000); } } /** * Discovers Hudson running nearby. * * To give every nearby Hudson a fair chance, wait for some time until we hear all the responses. */ protected List<DatagramPacket> discover() throws IOException, InterruptedException, RetryException { sendBroadcast(); List<DatagramPacket> responses = new ArrayList<DatagramPacket>(); // wait for 5 secs to gather up all the replies long limit = System.currentTimeMillis()+5*1000; while(true) { try { socket.setSoTimeout(Math.max(1,(int)(limit-System.currentTimeMillis()))); DatagramPacket recv = new DatagramPacket(new byte[2048], 2048); socket.receive(recv); responses.add(recv); } catch (SocketTimeoutException e) { // timed out if(responses.isEmpty()) throw new RetryException("Failed to receive a reply to broadcast."); return responses; } } } protected void sendBroadcast() throws IOException { DatagramPacket packet = new DatagramPacket(new byte[0], 0); packet.setAddress(InetAddress.getByName("255.255.255.255")); packet.setPort(Integer.getInteger("hudson.udp",33848)); socket.send(packet); } protected void connect() throws InterruptedException { try { Launcher launcher = new Launcher(); launcher.slaveJnlpURL = new URL(target.url+"/computer/"+name+"/slave-agent.jnlp"); List<String> jnlpArgs = launcher.parseJnlpArguments(); jnlpArgs.add("-noreconnect"); Main.main(jnlpArgs.toArray(new String[jnlpArgs.size()])); } catch (Exception e) { System.out.println("Failed to establish JNLP connection to "+target.url); Thread.sleep(10*1000); } } protected void createSwarmSlave() throws IOException, InterruptedException, RetryException { HttpURLConnection con = (HttpURLConnection)new URL(target.url + "/plugin/swarm/createSlave?name=" + name + "&executors=" + executors + param("remoteFsRoot",remoteFsRoot.getAbsolutePath()) + param("description",description)+ param("labels", labels)+ "&secret=" + target.secret).openConnection(); if(con.getResponseCode()!=200) { copy(con.getErrorStream(),System.out); throw new RetryException("Failed to create a slave on Hudson: "+con.getResponseCode()+" "+con.getResponseMessage()); } } private String param(String name, String value) throws UnsupportedEncodingException { if(value==null) return ""; return "&"+name+"="+ URLEncoder.encode(value,"UTF-8"); } protected void verifyThatUrlIsHudson() throws InterruptedException, RetryException { try { System.out.println("Connecting to "+target.url); HttpURLConnection con = (HttpURLConnection)new URL(target.url).openConnection(); con.connect(); String v = con.getHeaderField("X-Hudson"); if(v==null) throw new RetryException("This URL doesn't look like Hudson."); } catch (IOException e) { throw new RetryException("Failed to connect to "+target.url,e); } } private static void copy(InputStream in, OutputStream out) throws IOException { byte[] buf = new byte[8192]; int len; while ((len = in.read(buf)) >= 0) out.write(buf, 0, len); } private static String getChildElementString(Element parent, String tagName) { for (Node n=parent.getFirstChild(); n!=null; n=n.getNextSibling()) { if (n instanceof Element) { Element e = (Element) n; if(e.getTagName().equals(tagName)) { StringBuilder buf = new StringBuilder(); for (n=e.getFirstChild(); n!=null; n=n.getNextSibling()) { if(n instanceof Text) buf.append(n.getTextContent()); } return buf.toString(); } } } return null; } }
true
true
public void run() throws InterruptedException { System.out.println("Discovering Hudson master"); // wait until we get the ACK back while(true) { try { List<Candidate> candidates = new ArrayList<Candidate>(); for (DatagramPacket recv : discover()) { String responseXml = new String(recv.getData(), 0, recv.getLength()); Document xml; try { xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( new ByteArrayInputStream(recv.getData(), 0, recv.getLength())); } catch (SAXException e) { System.out.println("Invalid response XML from "+recv.getAddress()+": "+ responseXml); continue; } String swarm = getChildElementString(xml.getDocumentElement(), "swarm"); if(swarm==null) { System.out.println(recv.getAddress()+" doesn't support swarm"); continue; } String url = getChildElementString(xml.getDocumentElement(), "url"); if(url==null) { System.out.println("No <url> in XML from "+recv.getAddress()+": "+ responseXml); continue; } candidates.add(new Candidate(url,swarm)); } if(candidates.size()==0) throw new RetryException("No nearby Hudson supports swarming"); System.out.println("Found "+candidates.size()+" eligible Hudson."); // randomly pick up the Hudson to connect to target = candidates.get(new Random().nextInt(candidates.size())); verifyThatUrlIsHudson(); // create a new swarm slave createSwarmSlave(); connect(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (RetryException e) { System.out.println(e.getMessage()); if(e.getCause()!=null) e.getCause().printStackTrace(); } // retry System.out.println("Retrying in 10 seconds"); Thread.sleep(10*1000); } }
public void run() throws InterruptedException { System.out.println("Discovering Hudson master"); // wait until we get the ACK back while(true) { try { List<Candidate> candidates = new ArrayList<Candidate>(); for (DatagramPacket recv : discover()) { String responseXml = new String(recv.getData(), 0, recv.getLength()); Document xml; try { xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( new ByteArrayInputStream(recv.getData(), 0, recv.getLength())); } catch (SAXException e) { System.out.println("Invalid response XML from "+recv.getAddress()+": "+ responseXml); continue; } String swarm = getChildElementString(xml.getDocumentElement(), "swarm"); if(swarm==null) { System.out.println(recv.getAddress()+" doesn't support swarm"); continue; } String url = getChildElementString(xml.getDocumentElement(), "url"); if(url==null) { System.out.println(recv.getAddress()+" doesn't have the URL configuration yet. "+ responseXml); continue; } candidates.add(new Candidate(url,swarm)); } if(candidates.size()==0) throw new RetryException("No nearby Hudson supports swarming"); System.out.println("Found "+candidates.size()+" eligible Hudson."); // randomly pick up the Hudson to connect to target = candidates.get(new Random().nextInt(candidates.size())); verifyThatUrlIsHudson(); // create a new swarm slave createSwarmSlave(); connect(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (RetryException e) { System.out.println(e.getMessage()); if(e.getCause()!=null) e.getCause().printStackTrace(); } // retry System.out.println("Retrying in 10 seconds"); Thread.sleep(10*1000); } }
diff --git a/src/de/mud/terminal/VDUBuffer.java b/src/de/mud/terminal/VDUBuffer.java index d766bfe..60c73f4 100644 --- a/src/de/mud/terminal/VDUBuffer.java +++ b/src/de/mud/terminal/VDUBuffer.java @@ -1,836 +1,836 @@ /* * This file is part of "JTA - Telnet/SSH for the JAVA(tm) platform". * * (c) Matthias L. Jugel, Marcus Mei�ner 1996-2005. All Rights Reserved. * * Please visit http://javatelnet.org/ for updates and contact. * * --LICENSE NOTICE-- * 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 program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * --LICENSE NOTICE-- * */ package de.mud.terminal; import java.util.Arrays; /** * Implementation of a Video Display Unit (VDU) buffer. This class contains * all methods to manipulate the buffer that stores characters and their * attributes as well as the regions displayed. * * @author Matthias L. Jugel, Marcus Meißner * @version $Id: VDUBuffer.java 503 2005-10-24 07:34:13Z marcus $ */ public class VDUBuffer { /** The current version id tag */ public final static String ID = "$Id: VDUBuffer.java 503 2005-10-24 07:34:13Z marcus $"; /** Enable debug messages. */ public final static int debug = 0; public int height, width; /* rows and columns */ public boolean[] update; /* contains the lines that need update */ public char[][] charArray; /* contains the characters */ public int[][] charAttributes; /* contains character attrs */ public int bufSize; public int maxBufSize; /* buffer sizes */ public int screenBase; /* the actual screen start */ public int windowBase; /* where the start displaying */ public int scrollMarker; /* marks the last line inserted */ private int topMargin; /* top scroll margin */ private int bottomMargin; /* bottom scroll margin */ // cursor variables protected boolean showcursor = true; protected int cursorX, cursorY; /** Scroll up when inserting a line. */ public final static boolean SCROLL_UP = false; /** Scroll down when inserting a line. */ public final static boolean SCROLL_DOWN = true; /** Make character normal. */ public final static int NORMAL = 0x00; /** Make character bold. */ public final static int BOLD = 0x01; /** Underline character. */ public final static int UNDERLINE = 0x02; /** Invert character. */ public final static int INVERT = 0x04; /** Lower intensity character. */ public final static int LOW = 0x08; /** Invisible character. */ public final static int INVISIBLE = 0x10; /** how much to left shift the foreground color */ public final static int COLOR_FG_SHIFT = 5; /** how much to left shift the background color */ public final static int COLOR_BG_SHIFT = 14; /** color mask */ public final static int COLOR = 0x7fffe0; /* 0000 0000 0111 1111 1111 1111 1110 0000 */ /** foreground color mask */ public final static int COLOR_FG = 0x3fe0; /* 0000 0000 0000 0000 0011 1111 1110 0000 */ /** background color mask */ public final static int COLOR_BG = 0x7fc000; /* 0000 0000 0111 1111 1100 0000 0000 0000 */ /** * Create a new video display buffer with the passed width and height in * characters. * @param width the length of the character lines * @param height the amount of lines on the screen */ public VDUBuffer(int width, int height) { // set the display screen size setScreenSize(width, height, false); } /** * Create a standard video display buffer with 80 columns and 24 lines. */ public VDUBuffer() { this(80, 24); } /** * Put a character on the screen with normal font and outline. * The character previously on that position will be overwritten. * You need to call redraw() to update the screen. * @param c x-coordinate (column) * @param l y-coordinate (line) * @param ch the character to show on the screen * @see #insertChar * @see #deleteChar * @see #redraw */ public void putChar(int c, int l, char ch) { putChar(c, l, ch, NORMAL); } /** * Put a character on the screen with specific font and outline. * The character previously on that position will be overwritten. * You need to call redraw() to update the screen. * @param c x-coordinate (column) * @param l y-coordinate (line) * @param ch the character to show on the screen * @param attributes the character attributes * @see #BOLD * @see #UNDERLINE * @see #INVERT * @see #INVISIBLE * @see #NORMAL * @see #LOW * @see #insertChar * @see #deleteChar * @see #redraw */ public void putChar(int c, int l, char ch, int attributes) { c = checkBounds(c, 0, width - 1); l = checkBounds(l, 0, height - 1); charArray[screenBase + l][c] = ch; charAttributes[screenBase + l][c] = attributes; markLine(l, 1); } /** * Get the character at the specified position. * @param c x-coordinate (column) * @param l y-coordinate (line) * @see #putChar */ public char getChar(int c, int l) { c = checkBounds(c, 0, width - 1); l = checkBounds(l, 0, height - 1); return charArray[screenBase + l][c]; } /** * Get the attributes for the specified position. * @param c x-coordinate (column) * @param l y-coordinate (line) * @see #putChar */ public int getAttributes(int c, int l) { c = checkBounds(c, 0, width - 1); l = checkBounds(l, 0, height - 1); return charAttributes[screenBase + l][c]; } /** * Insert a character at a specific position on the screen. * All character right to from this position will be moved one to the right. * You need to call redraw() to update the screen. * @param c x-coordinate (column) * @param l y-coordinate (line) * @param ch the character to insert * @param attributes the character attributes * @see #BOLD * @see #UNDERLINE * @see #INVERT * @see #INVISIBLE * @see #NORMAL * @see #LOW * @see #putChar * @see #deleteChar * @see #redraw */ public void insertChar(int c, int l, char ch, int attributes) { c = checkBounds(c, 0, width - 1); l = checkBounds(l, 0, height - 1); System.arraycopy(charArray[screenBase + l], c, charArray[screenBase + l], c + 1, width - c - 1); System.arraycopy(charAttributes[screenBase + l], c, charAttributes[screenBase + l], c + 1, width - c - 1); putChar(c, l, ch, attributes); } /** * Delete a character at a given position on the screen. * All characters right to the position will be moved one to the left. * You need to call redraw() to update the screen. * @param c x-coordinate (column) * @param l y-coordinate (line) * @see #putChar * @see #insertChar * @see #redraw */ public void deleteChar(int c, int l) { c = checkBounds(c, 0, width - 1); l = checkBounds(l, 0, height - 1); if (c < width - 1) { System.arraycopy(charArray[screenBase + l], c + 1, charArray[screenBase + l], c, width - c - 1); System.arraycopy(charAttributes[screenBase + l], c + 1, charAttributes[screenBase + l], c, width - c - 1); } putChar(width - 1, l, (char) 0); } /** * Put a String at a specific position. Any characters previously on that * position will be overwritten. You need to call redraw() for screen update. * @param c x-coordinate (column) * @param l y-coordinate (line) * @param s the string to be shown on the screen * @see #BOLD * @see #UNDERLINE * @see #INVERT * @see #INVISIBLE * @see #NORMAL * @see #LOW * @see #putChar * @see #insertLine * @see #deleteLine * @see #redraw */ public void putString(int c, int l, String s) { putString(c, l, s, NORMAL); } /** * Put a String at a specific position giving all characters the same * attributes. Any characters previously on that position will be * overwritten. You need to call redraw() to update the screen. * @param c x-coordinate (column) * @param l y-coordinate (line) * @param s the string to be shown on the screen * @param attributes character attributes * @see #BOLD * @see #UNDERLINE * @see #INVERT * @see #INVISIBLE * @see #NORMAL * @see #LOW * @see #putChar * @see #insertLine * @see #deleteLine * @see #redraw */ public void putString(int c, int l, String s, int attributes) { for (int i = 0; i < s.length() && c + i < width; i++) putChar(c + i, l, s.charAt(i), attributes); } /** * Insert a blank line at a specific position. * The current line and all previous lines are scrolled one line up. The * top line is lost. You need to call redraw() to update the screen. * @param l the y-coordinate to insert the line * @see #deleteLine * @see #redraw */ public void insertLine(int l) { insertLine(l, 1, SCROLL_UP); } /** * Insert blank lines at a specific position. * You need to call redraw() to update the screen * @param l the y-coordinate to insert the line * @param n amount of lines to be inserted * @see #deleteLine * @see #redraw */ public void insertLine(int l, int n) { insertLine(l, n, SCROLL_UP); } /** * Insert a blank line at a specific position. Scroll text according to * the argument. * You need to call redraw() to update the screen * @param l the y-coordinate to insert the line * @param scrollDown scroll down * @see #deleteLine * @see #SCROLL_UP * @see #SCROLL_DOWN * @see #redraw */ public void insertLine(int l, boolean scrollDown) { insertLine(l, 1, scrollDown); } /** * Insert blank lines at a specific position. * The current line and all previous lines are scrolled one line up. The * top line is lost. You need to call redraw() to update the screen. * @param l the y-coordinate to insert the line * @param n number of lines to be inserted * @param scrollDown scroll down * @see #deleteLine * @see #SCROLL_UP * @see #SCROLL_DOWN * @see #redraw */ public synchronized void insertLine(int l, int n, boolean scrollDown) { l = checkBounds(l, 0, height - 1); char cbuf[][] = null; int abuf[][] = null; int offset = 0; int oldBase = screenBase; int newScreenBase = screenBase; int newWindowBase = windowBase; int newBufSize = bufSize; if (l > bottomMargin) /* We do not scroll below bottom margin (below the scrolling region). */ return; int top = (l < topMargin ? 0 : (l > bottomMargin ? (bottomMargin + 1 < height ? bottomMargin + 1 : height - 1) : topMargin)); int bottom = (l > bottomMargin ? height - 1 : (l < topMargin ? (topMargin > 0 ? topMargin - 1 : 0) : bottomMargin)); // System.out.println("l is "+l+", top is "+top+", bottom is "+bottom+", bottomargin is "+bottomMargin+", topMargin is "+topMargin); if (scrollDown) { if (n > (bottom - top)) n = (bottom - top); int size = bottom - l - (n - 1); if(size < 0) size = 0; cbuf = new char[size][]; abuf = new int[size][]; System.arraycopy(charArray, oldBase + l, cbuf, 0, bottom - l - (n - 1)); System.arraycopy(charAttributes, oldBase + l, abuf, 0, bottom - l - (n - 1)); System.arraycopy(cbuf, 0, charArray, oldBase + l + n, bottom - l - (n - 1)); System.arraycopy(abuf, 0, charAttributes, oldBase + l + n, bottom - l - (n - 1)); cbuf = charArray; abuf = charAttributes; } else { try { if (n > (bottom - top) + 1) n = (bottom - top) + 1; if (bufSize < maxBufSize) { if (bufSize + n > maxBufSize) { offset = n - (maxBufSize - bufSize); scrollMarker += offset; newBufSize = maxBufSize; newScreenBase = maxBufSize - height - 1; newWindowBase = screenBase; } else { scrollMarker += n; newScreenBase += n; newWindowBase += n; newBufSize += n; } - cbuf = new char[bufSize][]; - abuf = new int[bufSize][]; + cbuf = new char[newBufSize][]; + abuf = new int[newBufSize][]; } else { offset = n; cbuf = charArray; abuf = charAttributes; } // copy anything from the top of the buffer (+offset) to the new top // up to the screenBase. if (oldBase > 0) { System.arraycopy(charArray, offset, cbuf, 0, oldBase - offset); System.arraycopy(charAttributes, offset, abuf, 0, oldBase - offset); } // copy anything from the top of the screen (screenBase) up to the // topMargin to the new screen if (top > 0) { System.arraycopy(charArray, oldBase, cbuf, newScreenBase, top); System.arraycopy(charAttributes, oldBase, abuf, newScreenBase, top); } // copy anything from the topMargin up to the amount of lines inserted // to the gap left over between scrollback buffer and screenBase - if (oldBase > 0) { + if (oldBase >= 0) { System.arraycopy(charArray, oldBase + top, cbuf, oldBase - offset, n); System.arraycopy(charAttributes, oldBase + top, abuf, oldBase - offset, n); } // copy anything from topMargin + n up to the line linserted to the // topMargin System.arraycopy(charArray, oldBase + top + n, cbuf, newScreenBase + top, l - top - (n - 1)); System.arraycopy(charAttributes, oldBase + top + n, abuf, newScreenBase + top, l - top - (n - 1)); // // copy the all lines next to the inserted to the new buffer if (l < height - 1) { System.arraycopy(charArray, oldBase + l + 1, cbuf, newScreenBase + l + 1, (height - 1) - l); System.arraycopy(charAttributes, oldBase + l + 1, abuf, newScreenBase + l + 1, (height - 1) - l); } } catch (ArrayIndexOutOfBoundsException e) { // this should not happen anymore, but I will leave the code // here in case something happens anyway. That code above is // so complex I always have a hard time understanding what // I did, even though there are comments System.err.println("*** Error while scrolling up:"); System.err.println("--- BEGIN STACK TRACE ---"); e.printStackTrace(); System.err.println("--- END STACK TRACE ---"); System.err.println("bufSize=" + bufSize + ", maxBufSize=" + maxBufSize); System.err.println("top=" + top + ", bottom=" + bottom); System.err.println("n=" + n + ", l=" + l); System.err.println("screenBase=" + screenBase + ", windowBase=" + windowBase); System.err.println("newScreenBase=" + newScreenBase + ", newWindowBase=" + newWindowBase); System.err.println("oldBase=" + oldBase); System.err.println("size.width=" + width + ", size.height=" + height); System.err.println("abuf.length=" + abuf.length + ", cbuf.length=" + cbuf.length); System.err.println("*** done dumping debug information"); } } // this is a little helper to mark the scrolling scrollMarker -= n; for (int i = 0; i < n; i++) { cbuf[(newScreenBase + l) + (scrollDown ? i : -i)] = new char[width]; Arrays.fill(cbuf[(newScreenBase + l) + (scrollDown ? i : -i)], ' '); abuf[(newScreenBase + l) + (scrollDown ? i : -i)] = new int[width]; } charArray = cbuf; charAttributes = abuf; screenBase = newScreenBase; windowBase = newWindowBase; bufSize = newBufSize; if (scrollDown) markLine(l, bottom - l + 1); else markLine(top, l - top + 1); display.updateScrollBar(); } /** * Delete a line at a specific position. Subsequent lines will be scrolled * up to fill the space and a blank line is inserted at the end of the * screen. * @param l the y-coordinate to insert the line * @see #deleteLine */ public void deleteLine(int l) { l = checkBounds(l, 0, height - 1); int bottom = (l > bottomMargin ? height - 1: (l < topMargin?topMargin:bottomMargin + 1)); int numRows = bottom - l - 1; char[] discardedChars = charArray[screenBase + l]; int[] discardedAttributes = charAttributes[screenBase + l]; if (numRows > 0) { System.arraycopy(charArray, screenBase + l + 1, charArray, screenBase + l, numRows); System.arraycopy(charAttributes, screenBase + l + 1, charAttributes, screenBase + l, numRows); } int newBottomRow = screenBase + bottom - 1; charArray[newBottomRow] = discardedChars; charAttributes[newBottomRow] = discardedAttributes; Arrays.fill(charArray[newBottomRow], ' '); Arrays.fill(charAttributes[newBottomRow], 0); markLine(l, bottom - l); } /** * Delete a rectangular portion of the screen. * You need to call redraw() to update the screen. * @param c x-coordinate (column) * @param l y-coordinate (row) * @param w with of the area in characters * @param h height of the area in characters * @param curAttr attribute to fill * @see #deleteChar * @see #deleteLine * @see #redraw */ public void deleteArea(int c, int l, int w, int h, int curAttr) { c = checkBounds(c, 0, width - 1); l = checkBounds(l, 0, height - 1); int endColumn = c + w; int targetRow = screenBase + l; for (int i = 0; i < h && l + i < height; i++) { Arrays.fill(charAttributes[targetRow], c, endColumn, curAttr); Arrays.fill(charArray[targetRow], c, endColumn, ' '); targetRow++; } markLine(l, h); } /** * Delete a rectangular portion of the screen. * You need to call redraw() to update the screen. * @param c x-coordinate (column) * @param l y-coordinate (row) * @param w with of the area in characters * @param h height of the area in characters * @see #deleteChar * @see #deleteLine * @see #redraw */ public void deleteArea(int c, int l, int w, int h) { deleteArea(c, l, w, h, 0); } /** * Sets whether the cursor is visible or not. * @param doshow */ public void showCursor(boolean doshow) { if (doshow != showcursor) markLine(cursorY, 1); showcursor = doshow; } /** * Check whether the cursor is currently visible. * @return visibility */ public boolean isCursorVisible() { return showcursor; } /** * Puts the cursor at the specified position. * @param c column * @param l line */ public void setCursorPosition(int c, int l) { cursorX = checkBounds(c, 0, width - 1); cursorY = checkBounds(l, 0, height - 1); markLine(cursorY, 1); } /** * Get the current column of the cursor position. */ public int getCursorColumn() { return cursorX; } /** * Get the current line of the cursor position. */ public int getCursorRow() { return cursorY; } /** * Set the current window base. This allows to view the scrollback buffer. * @param line the line where the screen window starts * @see #setBufferSize * @see #getBufferSize */ public void setWindowBase(int line) { if (line > screenBase) line = screenBase; else if (line < 0) line = 0; windowBase = line; update[0] = true; redraw(); } /** * Get the current window base. * @see #setWindowBase */ public int getWindowBase() { return windowBase; } /** * Set the scroll margins simultaneously. If they're out of bounds, trim them. * @param l1 line that is the top * @param l2 line that is the bottom */ public void setMargins(int l1, int l2) { if (l1 > l2) return; if (l1 < 0) l1 = 0; if (l2 > height - 1) l2 = height - 1; topMargin = l1; bottomMargin = l2; } /** * Set the top scroll margin for the screen. If the current bottom margin * is smaller it will become the top margin and the line will become the * bottom margin. * @param l line that is the margin */ public void setTopMargin(int l) { if (l > bottomMargin) { topMargin = bottomMargin; bottomMargin = l; } else topMargin = l; if (topMargin < 0) topMargin = 0; if (bottomMargin > height - 1) bottomMargin = height - 1; } /** * Get the top scroll margin. */ public int getTopMargin() { return topMargin; } /** * Set the bottom scroll margin for the screen. If the current top margin * is bigger it will become the bottom margin and the line will become the * top margin. * @param l line that is the margin */ public void setBottomMargin(int l) { if (l < topMargin) { bottomMargin = topMargin; topMargin = l; } else bottomMargin = l; if (topMargin < 0) topMargin = 0; if (bottomMargin > height - 1) bottomMargin = height - 1; } /** * Get the bottom scroll margin. */ public int getBottomMargin() { return bottomMargin; } /** * Set scrollback buffer size. * @param amount new size of the buffer */ public void setBufferSize(int amount) { if (amount < height) amount = height; if (amount < maxBufSize) { char cbuf[][] = new char[amount][width]; int abuf[][] = new int[amount][width]; int copyStart = bufSize - amount < 0 ? 0 : bufSize - amount; int copyCount = bufSize - amount < 0 ? bufSize : amount; if (charArray != null) System.arraycopy(charArray, copyStart, cbuf, 0, copyCount); if (charAttributes != null) System.arraycopy(charAttributes, copyStart, abuf, 0, copyCount); charArray = cbuf; charAttributes = abuf; bufSize = copyCount; screenBase = bufSize - height; windowBase = screenBase; } maxBufSize = amount; update[0] = true; redraw(); } /** * Retrieve current scrollback buffer size. * @see #setBufferSize */ public int getBufferSize() { return bufSize; } /** * Retrieve maximum buffer Size. * @see #getBufferSize */ public int getMaxBufferSize() { return maxBufSize; } /** * Change the size of the screen. This will include adjustment of the * scrollback buffer. * @param w of the screen * @param h of the screen */ public void setScreenSize(int w, int h, boolean broadcast) { char cbuf[][]; int abuf[][]; int bsize = bufSize; if (w < 1 || h < 1) return; if (debug > 0) System.err.println("VDU: screen size [" + w + "," + h + "]"); if (h > maxBufSize) maxBufSize = h; if (h > bufSize) { bufSize = h; screenBase = 0; windowBase = 0; } if (windowBase + h >= bufSize) windowBase = bufSize - h; if (screenBase + h >= bufSize) screenBase = bufSize - h; cbuf = new char[bufSize][w]; abuf = new int[bufSize][w]; for (int i = 0; i < bufSize; i++) { Arrays.fill(cbuf[i], ' '); } if (charArray != null && charAttributes != null) { for (int i = 0; i < bsize && i < bufSize; i++) { System.arraycopy(charArray[i], 0, cbuf[i], 0, w < width ? w : width); System.arraycopy(charAttributes[i], 0, abuf[i], 0, w < width ? w : width); } } charArray = cbuf; charAttributes = abuf; width = w; height = h; topMargin = 0; bottomMargin = h - 1; update = new boolean[h + 1]; update[0] = true; /* FIXME: ??? if(resizeStrategy == RESIZE_FONT) setBounds(getBounds()); */ } /** * Get amount of rows on the screen. */ public int getRows() { return height; } /** * Get amount of columns on the screen. */ public int getColumns() { return width; } /** * Mark lines to be updated with redraw(). * @param l starting line * @param n amount of lines to be updated * @see #redraw */ public void markLine(int l, int n) { l = checkBounds(l, 0, height - 1); for (int i = 0; (i < n) && (l + i < height); i++) update[l + i + 1] = true; } private int checkBounds(int value, int lower, int upper) { if (value < lower) return lower; if (value > upper) return upper; return value; } /** a generic display that should redraw on demand */ protected VDUDisplay display; public void setDisplay(VDUDisplay display) { this.display = display; } /** * Trigger a redraw on the display. */ protected void redraw() { if (display != null) display.redraw(); } }
false
true
public synchronized void insertLine(int l, int n, boolean scrollDown) { l = checkBounds(l, 0, height - 1); char cbuf[][] = null; int abuf[][] = null; int offset = 0; int oldBase = screenBase; int newScreenBase = screenBase; int newWindowBase = windowBase; int newBufSize = bufSize; if (l > bottomMargin) /* We do not scroll below bottom margin (below the scrolling region). */ return; int top = (l < topMargin ? 0 : (l > bottomMargin ? (bottomMargin + 1 < height ? bottomMargin + 1 : height - 1) : topMargin)); int bottom = (l > bottomMargin ? height - 1 : (l < topMargin ? (topMargin > 0 ? topMargin - 1 : 0) : bottomMargin)); // System.out.println("l is "+l+", top is "+top+", bottom is "+bottom+", bottomargin is "+bottomMargin+", topMargin is "+topMargin); if (scrollDown) { if (n > (bottom - top)) n = (bottom - top); int size = bottom - l - (n - 1); if(size < 0) size = 0; cbuf = new char[size][]; abuf = new int[size][]; System.arraycopy(charArray, oldBase + l, cbuf, 0, bottom - l - (n - 1)); System.arraycopy(charAttributes, oldBase + l, abuf, 0, bottom - l - (n - 1)); System.arraycopy(cbuf, 0, charArray, oldBase + l + n, bottom - l - (n - 1)); System.arraycopy(abuf, 0, charAttributes, oldBase + l + n, bottom - l - (n - 1)); cbuf = charArray; abuf = charAttributes; } else { try { if (n > (bottom - top) + 1) n = (bottom - top) + 1; if (bufSize < maxBufSize) { if (bufSize + n > maxBufSize) { offset = n - (maxBufSize - bufSize); scrollMarker += offset; newBufSize = maxBufSize; newScreenBase = maxBufSize - height - 1; newWindowBase = screenBase; } else { scrollMarker += n; newScreenBase += n; newWindowBase += n; newBufSize += n; } cbuf = new char[bufSize][]; abuf = new int[bufSize][]; } else { offset = n; cbuf = charArray; abuf = charAttributes; } // copy anything from the top of the buffer (+offset) to the new top // up to the screenBase. if (oldBase > 0) { System.arraycopy(charArray, offset, cbuf, 0, oldBase - offset); System.arraycopy(charAttributes, offset, abuf, 0, oldBase - offset); } // copy anything from the top of the screen (screenBase) up to the // topMargin to the new screen if (top > 0) { System.arraycopy(charArray, oldBase, cbuf, newScreenBase, top); System.arraycopy(charAttributes, oldBase, abuf, newScreenBase, top); } // copy anything from the topMargin up to the amount of lines inserted // to the gap left over between scrollback buffer and screenBase if (oldBase > 0) { System.arraycopy(charArray, oldBase + top, cbuf, oldBase - offset, n); System.arraycopy(charAttributes, oldBase + top, abuf, oldBase - offset, n); } // copy anything from topMargin + n up to the line linserted to the // topMargin System.arraycopy(charArray, oldBase + top + n, cbuf, newScreenBase + top, l - top - (n - 1)); System.arraycopy(charAttributes, oldBase + top + n, abuf, newScreenBase + top, l - top - (n - 1)); // // copy the all lines next to the inserted to the new buffer if (l < height - 1) { System.arraycopy(charArray, oldBase + l + 1, cbuf, newScreenBase + l + 1, (height - 1) - l); System.arraycopy(charAttributes, oldBase + l + 1, abuf, newScreenBase + l + 1, (height - 1) - l); } } catch (ArrayIndexOutOfBoundsException e) { // this should not happen anymore, but I will leave the code // here in case something happens anyway. That code above is // so complex I always have a hard time understanding what // I did, even though there are comments System.err.println("*** Error while scrolling up:"); System.err.println("--- BEGIN STACK TRACE ---"); e.printStackTrace(); System.err.println("--- END STACK TRACE ---"); System.err.println("bufSize=" + bufSize + ", maxBufSize=" + maxBufSize); System.err.println("top=" + top + ", bottom=" + bottom); System.err.println("n=" + n + ", l=" + l); System.err.println("screenBase=" + screenBase + ", windowBase=" + windowBase); System.err.println("newScreenBase=" + newScreenBase + ", newWindowBase=" + newWindowBase); System.err.println("oldBase=" + oldBase); System.err.println("size.width=" + width + ", size.height=" + height); System.err.println("abuf.length=" + abuf.length + ", cbuf.length=" + cbuf.length); System.err.println("*** done dumping debug information"); } } // this is a little helper to mark the scrolling scrollMarker -= n; for (int i = 0; i < n; i++) { cbuf[(newScreenBase + l) + (scrollDown ? i : -i)] = new char[width]; Arrays.fill(cbuf[(newScreenBase + l) + (scrollDown ? i : -i)], ' '); abuf[(newScreenBase + l) + (scrollDown ? i : -i)] = new int[width]; } charArray = cbuf; charAttributes = abuf; screenBase = newScreenBase; windowBase = newWindowBase; bufSize = newBufSize; if (scrollDown) markLine(l, bottom - l + 1); else markLine(top, l - top + 1); display.updateScrollBar(); }
public synchronized void insertLine(int l, int n, boolean scrollDown) { l = checkBounds(l, 0, height - 1); char cbuf[][] = null; int abuf[][] = null; int offset = 0; int oldBase = screenBase; int newScreenBase = screenBase; int newWindowBase = windowBase; int newBufSize = bufSize; if (l > bottomMargin) /* We do not scroll below bottom margin (below the scrolling region). */ return; int top = (l < topMargin ? 0 : (l > bottomMargin ? (bottomMargin + 1 < height ? bottomMargin + 1 : height - 1) : topMargin)); int bottom = (l > bottomMargin ? height - 1 : (l < topMargin ? (topMargin > 0 ? topMargin - 1 : 0) : bottomMargin)); // System.out.println("l is "+l+", top is "+top+", bottom is "+bottom+", bottomargin is "+bottomMargin+", topMargin is "+topMargin); if (scrollDown) { if (n > (bottom - top)) n = (bottom - top); int size = bottom - l - (n - 1); if(size < 0) size = 0; cbuf = new char[size][]; abuf = new int[size][]; System.arraycopy(charArray, oldBase + l, cbuf, 0, bottom - l - (n - 1)); System.arraycopy(charAttributes, oldBase + l, abuf, 0, bottom - l - (n - 1)); System.arraycopy(cbuf, 0, charArray, oldBase + l + n, bottom - l - (n - 1)); System.arraycopy(abuf, 0, charAttributes, oldBase + l + n, bottom - l - (n - 1)); cbuf = charArray; abuf = charAttributes; } else { try { if (n > (bottom - top) + 1) n = (bottom - top) + 1; if (bufSize < maxBufSize) { if (bufSize + n > maxBufSize) { offset = n - (maxBufSize - bufSize); scrollMarker += offset; newBufSize = maxBufSize; newScreenBase = maxBufSize - height - 1; newWindowBase = screenBase; } else { scrollMarker += n; newScreenBase += n; newWindowBase += n; newBufSize += n; } cbuf = new char[newBufSize][]; abuf = new int[newBufSize][]; } else { offset = n; cbuf = charArray; abuf = charAttributes; } // copy anything from the top of the buffer (+offset) to the new top // up to the screenBase. if (oldBase > 0) { System.arraycopy(charArray, offset, cbuf, 0, oldBase - offset); System.arraycopy(charAttributes, offset, abuf, 0, oldBase - offset); } // copy anything from the top of the screen (screenBase) up to the // topMargin to the new screen if (top > 0) { System.arraycopy(charArray, oldBase, cbuf, newScreenBase, top); System.arraycopy(charAttributes, oldBase, abuf, newScreenBase, top); } // copy anything from the topMargin up to the amount of lines inserted // to the gap left over between scrollback buffer and screenBase if (oldBase >= 0) { System.arraycopy(charArray, oldBase + top, cbuf, oldBase - offset, n); System.arraycopy(charAttributes, oldBase + top, abuf, oldBase - offset, n); } // copy anything from topMargin + n up to the line linserted to the // topMargin System.arraycopy(charArray, oldBase + top + n, cbuf, newScreenBase + top, l - top - (n - 1)); System.arraycopy(charAttributes, oldBase + top + n, abuf, newScreenBase + top, l - top - (n - 1)); // // copy the all lines next to the inserted to the new buffer if (l < height - 1) { System.arraycopy(charArray, oldBase + l + 1, cbuf, newScreenBase + l + 1, (height - 1) - l); System.arraycopy(charAttributes, oldBase + l + 1, abuf, newScreenBase + l + 1, (height - 1) - l); } } catch (ArrayIndexOutOfBoundsException e) { // this should not happen anymore, but I will leave the code // here in case something happens anyway. That code above is // so complex I always have a hard time understanding what // I did, even though there are comments System.err.println("*** Error while scrolling up:"); System.err.println("--- BEGIN STACK TRACE ---"); e.printStackTrace(); System.err.println("--- END STACK TRACE ---"); System.err.println("bufSize=" + bufSize + ", maxBufSize=" + maxBufSize); System.err.println("top=" + top + ", bottom=" + bottom); System.err.println("n=" + n + ", l=" + l); System.err.println("screenBase=" + screenBase + ", windowBase=" + windowBase); System.err.println("newScreenBase=" + newScreenBase + ", newWindowBase=" + newWindowBase); System.err.println("oldBase=" + oldBase); System.err.println("size.width=" + width + ", size.height=" + height); System.err.println("abuf.length=" + abuf.length + ", cbuf.length=" + cbuf.length); System.err.println("*** done dumping debug information"); } } // this is a little helper to mark the scrolling scrollMarker -= n; for (int i = 0; i < n; i++) { cbuf[(newScreenBase + l) + (scrollDown ? i : -i)] = new char[width]; Arrays.fill(cbuf[(newScreenBase + l) + (scrollDown ? i : -i)], ' '); abuf[(newScreenBase + l) + (scrollDown ? i : -i)] = new int[width]; } charArray = cbuf; charAttributes = abuf; screenBase = newScreenBase; windowBase = newWindowBase; bufSize = newBufSize; if (scrollDown) markLine(l, bottom - l + 1); else markLine(top, l - top + 1); display.updateScrollBar(); }
diff --git a/src/main/java/fr/univnantes/atal/web/trashnao/security/TokenVerifier.java b/src/main/java/fr/univnantes/atal/web/trashnao/security/TokenVerifier.java index 184d8f5..621c52b 100644 --- a/src/main/java/fr/univnantes/atal/web/trashnao/security/TokenVerifier.java +++ b/src/main/java/fr/univnantes/atal/web/trashnao/security/TokenVerifier.java @@ -1,58 +1,58 @@ package fr.univnantes.atal.web.trashnao.security; import fr.univnantes.atal.web.trashnao.app.Constants; import fr.univnantes.atal.web.trashnao.model.User; import fr.univnantes.atal.web.trashnao.persistence.PMF; import java.io.InputStreamReader; import java.net.URL; import java.util.Map; import javax.jdo.JDOObjectNotFoundException; import javax.jdo.PersistenceManager; import javax.servlet.http.HttpServletRequest; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; public class TokenVerifier { static private ObjectMapper mapper = new ObjectMapper(); static public User getUser(HttpServletRequest request) { String accessToken = request.getParameter("access_token"); if (accessToken == null) { return null; } else { try { URL url = new URL( "https://www.googleapis.com/oauth2/v1/tokeninfo" + "?access_token=" + accessToken); Map<String, String> userData = mapper.readValue( new InputStreamReader(url.openStream(), "UTF-8"), new TypeReference<Map<String, String>>() { }); if (userData.get("audience") == null || userData.containsKey("error") || !userData.get("audience") .equals(Constants.CLIENT_ID)) { return null; } else { String email = userData.get("email"), userId = userData.get("user_id"); User user; PersistenceManager pm = PMF.get().getPersistenceManager(); try { user = pm.getObjectById(User.class, email); } catch (JDOObjectNotFoundException ex) { - user = new User(email, userId); + user = new User(userId, email); pm.makePersistent(user); } finally { pm.close(); } return user; } } catch (Exception ex) { return null; } } } }
true
true
static public User getUser(HttpServletRequest request) { String accessToken = request.getParameter("access_token"); if (accessToken == null) { return null; } else { try { URL url = new URL( "https://www.googleapis.com/oauth2/v1/tokeninfo" + "?access_token=" + accessToken); Map<String, String> userData = mapper.readValue( new InputStreamReader(url.openStream(), "UTF-8"), new TypeReference<Map<String, String>>() { }); if (userData.get("audience") == null || userData.containsKey("error") || !userData.get("audience") .equals(Constants.CLIENT_ID)) { return null; } else { String email = userData.get("email"), userId = userData.get("user_id"); User user; PersistenceManager pm = PMF.get().getPersistenceManager(); try { user = pm.getObjectById(User.class, email); } catch (JDOObjectNotFoundException ex) { user = new User(email, userId); pm.makePersistent(user); } finally { pm.close(); } return user; } } catch (Exception ex) { return null; } } }
static public User getUser(HttpServletRequest request) { String accessToken = request.getParameter("access_token"); if (accessToken == null) { return null; } else { try { URL url = new URL( "https://www.googleapis.com/oauth2/v1/tokeninfo" + "?access_token=" + accessToken); Map<String, String> userData = mapper.readValue( new InputStreamReader(url.openStream(), "UTF-8"), new TypeReference<Map<String, String>>() { }); if (userData.get("audience") == null || userData.containsKey("error") || !userData.get("audience") .equals(Constants.CLIENT_ID)) { return null; } else { String email = userData.get("email"), userId = userData.get("user_id"); User user; PersistenceManager pm = PMF.get().getPersistenceManager(); try { user = pm.getObjectById(User.class, email); } catch (JDOObjectNotFoundException ex) { user = new User(userId, email); pm.makePersistent(user); } finally { pm.close(); } return user; } } catch (Exception ex) { return null; } } }
diff --git a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallApplication.java b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallApplication.java index 24a184e16..084d89d89 100644 --- a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallApplication.java +++ b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallApplication.java @@ -1,230 +1,231 @@ /******************************************************************************* * Copyright (c) 2007, 2008 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 * Code 9 - ongoing development *******************************************************************************/ package org.eclipse.equinox.internal.p2.installer; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.net.proxy.IProxyService; import org.eclipse.core.runtime.*; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.installer.ui.SWTInstallAdvisor; import org.eclipse.equinox.internal.provisional.p2.installer.InstallAdvisor; import org.eclipse.equinox.internal.provisional.p2.installer.InstallDescription; import org.osgi.framework.*; /** * This is a simple installer application built using P2. The application must be given * an "install description" as a command line argument or system property * ({@link #SYS_PROP_INSTALL_DESCRIPTION}). The application reads this * install description, and looks for an existing profile in the local install registry that * matches it. If no profile is found, it creates a new profile, and installs the root * IU in the install description into the profile. It may then launch the installed application, * depending on the specification in the install description. If an existing profile is found, * the application instead performs an update on the existing profile with the new root * IU in the install description. Thus, an installed application can be updated by dropping * in a new install description file, and re-running this installer application. */ public class InstallApplication implements IApplication { /** * A property whose value is the URL of an install description. An install description is a file * that contains all the information required to complete the install. */ private static final String SYS_PROP_INSTALL_DESCRIPTION = "org.eclipse.equinox.p2.installDescription"; //$NON-NLS-1$ /** * The install advisor. This field is non null while the install application is running. */ private InstallAdvisor advisor; /** * Throws an exception of severity error with the given error message. */ private static CoreException fail(String message, Throwable throwable) { return new CoreException(new Status(IStatus.ERROR, InstallerActivator.PI_INSTALLER, message, throwable)); } /** * Copied from ServiceHelper because we need to obtain services * before p2 has been started. */ public static Object getService(BundleContext context, String name) { if (context == null) return null; ServiceReference reference = context.getServiceReference(name); if (reference == null) return null; Object result = context.getService(reference); context.ungetService(reference); return result; } /** * Loads the install description, filling in any missing data if needed. */ private InstallDescription computeInstallDescription() throws CoreException { InstallDescription description = fetchInstallDescription(SubMonitor.convert(null)); return advisor.prepareInstallDescription(description); } private InstallAdvisor createInstallContext() { //TODO create an appropriate advisor depending on whether headless or GUI install is desired. InstallAdvisor result = new SWTInstallAdvisor(); result.start(); return result; } /** * Fetch and return the install description to be installed. */ private InstallDescription fetchInstallDescription(SubMonitor monitor) throws CoreException { String site = System.getProperty(SYS_PROP_INSTALL_DESCRIPTION); try { return InstallDescriptionParser.createDescription(site, monitor); } catch (IOException e) { throw fail(Messages.App_InvalidSite + site, e); } } private IStatus getStatus(final Exception failure) { Throwable cause = failure; //unwrap target exception if applicable if (failure instanceof InvocationTargetException) { cause = ((InvocationTargetException) failure).getTargetException(); if (cause == null) cause = failure; } if (cause instanceof CoreException) return ((CoreException) cause).getStatus(); return new Status(IStatus.ERROR, InstallerActivator.PI_INSTALLER, Messages.App_Error, cause); } private void launchProduct(InstallDescription description) throws CoreException { IPath installLocation = description.getInstallLocation(); IPath toRun = installLocation.append(description.getLauncherName()); try { Runtime.getRuntime().exec(toRun.toString(), null, installLocation.toFile()); } catch (IOException e) { throw fail(Messages.App_LaunchFailed + toRun, e); } //wait a few seconds to give the user a chance to read the message try { Thread.sleep(3000); } catch (InterruptedException e) { //ignore } } /* (non-Javadoc) * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext) */ public Object start(IApplicationContext appContext) { try { appContext.applicationRunning(); initializeProxySupport(); advisor = createInstallContext(); //fetch description of what to install InstallDescription description = null; try { description = computeInstallDescription(); startRequiredBundles(description); //perform long running install operation InstallUpdateProductOperation operation = new InstallUpdateProductOperation(InstallerActivator.getDefault().getContext(), description); IStatus result = advisor.performInstall(operation); if (!result.isOK()) { LogHelper.log(result); advisor.setResult(result); return IApplication.EXIT_OK; } //just exit after a successful update if (!operation.isFirstInstall()) return IApplication.EXIT_OK; if (canAutoStart(description)) launchProduct(description); else { //notify user that the product was installed //TODO present the user an option to immediately start the product advisor.setResult(result); } } catch (OperationCanceledException e) { advisor.setResult(Status.CANCEL_STATUS); } catch (Exception e) { IStatus error = getStatus(e); advisor.setResult(error); LogHelper.log(error); } return IApplication.EXIT_OK; } finally { - advisor.stop(); + if (advisor != null) + advisor.stop(); } } private void initializeProxySupport() { IProxyService proxies = (IProxyService) getService(InstallerActivator.getDefault().getContext(), IProxyService.class.getName()); if (proxies == null) return; proxies.setProxiesEnabled(true); proxies.setSystemProxiesEnabled(true); } /** * Returns whether the configuration described by the given install * description can be started automatically. */ private boolean canAutoStart(InstallDescription description) { if (!description.isAutoStart()) return false; //can't start if we don't know launcher name and path if (description.getLauncherName() == null || description.getInstallLocation() == null) return false; return advisor.promptForLaunch(description); } /** * Starts the p2 bundles needed to continue with the install. */ private void startRequiredBundles(InstallDescription description) throws CoreException { IPath installLocation = description.getInstallLocation(); if (installLocation == null) throw fail(Messages.App_NoInstallLocation, null); //set agent location if specified IPath agentLocation = description.getAgentLocation(); if (agentLocation != null) { String agentArea = System.getProperty("eclipse.p2.data.area"); //$NON-NLS-1$ // TODO a bit of a hack here. If the value is already set and it is set to @config/p2 then // it may well be the default value put in by PDE. Overwrite it. // Its kind of unclear why we would NOT overwrite. At this point the user set their choice // of shared or standalone and those dicate where the agent should put its info... if (agentArea == null || agentArea.length() == 0 || agentArea.startsWith("@config")) //$NON-NLS-1$ System.setProperty("eclipse.p2.data.area", agentLocation.toOSString()); //$NON-NLS-1$ } //start up p2 try { InstallerActivator.getDefault().getBundle("org.eclipse.equinox.p2.exemplarysetup").start(Bundle.START_TRANSIENT); //$NON-NLS-1$ } catch (BundleException e) { throw fail(Messages.App_FailedStart, e); } } /* (non-Javadoc) * @see org.eclipse.equinox.app.IApplication#stop() */ public void stop() { //note this method can be called from another thread InstallAdvisor tempContext = advisor; if (tempContext != null) { tempContext.stop(); advisor = null; } } }
true
true
public Object start(IApplicationContext appContext) { try { appContext.applicationRunning(); initializeProxySupport(); advisor = createInstallContext(); //fetch description of what to install InstallDescription description = null; try { description = computeInstallDescription(); startRequiredBundles(description); //perform long running install operation InstallUpdateProductOperation operation = new InstallUpdateProductOperation(InstallerActivator.getDefault().getContext(), description); IStatus result = advisor.performInstall(operation); if (!result.isOK()) { LogHelper.log(result); advisor.setResult(result); return IApplication.EXIT_OK; } //just exit after a successful update if (!operation.isFirstInstall()) return IApplication.EXIT_OK; if (canAutoStart(description)) launchProduct(description); else { //notify user that the product was installed //TODO present the user an option to immediately start the product advisor.setResult(result); } } catch (OperationCanceledException e) { advisor.setResult(Status.CANCEL_STATUS); } catch (Exception e) { IStatus error = getStatus(e); advisor.setResult(error); LogHelper.log(error); } return IApplication.EXIT_OK; } finally { advisor.stop(); } }
public Object start(IApplicationContext appContext) { try { appContext.applicationRunning(); initializeProxySupport(); advisor = createInstallContext(); //fetch description of what to install InstallDescription description = null; try { description = computeInstallDescription(); startRequiredBundles(description); //perform long running install operation InstallUpdateProductOperation operation = new InstallUpdateProductOperation(InstallerActivator.getDefault().getContext(), description); IStatus result = advisor.performInstall(operation); if (!result.isOK()) { LogHelper.log(result); advisor.setResult(result); return IApplication.EXIT_OK; } //just exit after a successful update if (!operation.isFirstInstall()) return IApplication.EXIT_OK; if (canAutoStart(description)) launchProduct(description); else { //notify user that the product was installed //TODO present the user an option to immediately start the product advisor.setResult(result); } } catch (OperationCanceledException e) { advisor.setResult(Status.CANCEL_STATUS); } catch (Exception e) { IStatus error = getStatus(e); advisor.setResult(error); LogHelper.log(error); } return IApplication.EXIT_OK; } finally { if (advisor != null) advisor.stop(); } }
diff --git a/src/GridShape/Sphere.java b/src/GridShape/Sphere.java index 278f38b..edfc9dc 100644 --- a/src/GridShape/Sphere.java +++ b/src/GridShape/Sphere.java @@ -1,59 +1,63 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GridShape; import gameoflife.Grid; import java.awt.Point; import java.util.ArrayList; import java.util.List; /** * * @author Christiaan */ public class Sphere implements Profile { public List<Point> GetNeighbours(Grid grid, GridCell.Profile cellProfile, Point position) { List<Point> potentialNeighbours = cellProfile.GetNeighbours(position); List<Point> neighbours = new ArrayList<Point>(); for(Point p : potentialNeighbours) { int x = position.x + p.x; int y = position.y + p.y; if(x < 0) { x += grid.maxWidth(); y *= 2; } else if(x >= grid.maxWidth()) { x -= grid.maxWidth(); y *= -2; } if(y < 0) { x *= 2; y += grid.maxHeight(); } else if(y >= grid.maxHeight()) { x *= -2; y -= grid.maxHeight(); } - if(x < 0) - x += grid.maxWidth(); - else if(x >= grid.maxWidth()) - x -= grid.maxWidth(); + while(x < 0 || x >= grid.maxWidth()) { + if(x < 0) + x += grid.maxWidth(); + else if(x >= grid.maxWidth()) + x -= grid.maxWidth(); + } - if(y < 0) - y += grid.maxHeight(); - else if(y >= grid.maxHeight()) - y -= grid.maxHeight(); + while(y < 0 || y >= grid.maxHeight()) { + if(y < 0) + y += grid.maxHeight(); + else if(y >= grid.maxHeight()) + y -= grid.maxHeight(); + } neighbours.add(new Point(x,y)); } return neighbours; } }
false
true
public List<Point> GetNeighbours(Grid grid, GridCell.Profile cellProfile, Point position) { List<Point> potentialNeighbours = cellProfile.GetNeighbours(position); List<Point> neighbours = new ArrayList<Point>(); for(Point p : potentialNeighbours) { int x = position.x + p.x; int y = position.y + p.y; if(x < 0) { x += grid.maxWidth(); y *= 2; } else if(x >= grid.maxWidth()) { x -= grid.maxWidth(); y *= -2; } if(y < 0) { x *= 2; y += grid.maxHeight(); } else if(y >= grid.maxHeight()) { x *= -2; y -= grid.maxHeight(); } if(x < 0) x += grid.maxWidth(); else if(x >= grid.maxWidth()) x -= grid.maxWidth(); if(y < 0) y += grid.maxHeight(); else if(y >= grid.maxHeight()) y -= grid.maxHeight(); neighbours.add(new Point(x,y)); } return neighbours; }
public List<Point> GetNeighbours(Grid grid, GridCell.Profile cellProfile, Point position) { List<Point> potentialNeighbours = cellProfile.GetNeighbours(position); List<Point> neighbours = new ArrayList<Point>(); for(Point p : potentialNeighbours) { int x = position.x + p.x; int y = position.y + p.y; if(x < 0) { x += grid.maxWidth(); y *= 2; } else if(x >= grid.maxWidth()) { x -= grid.maxWidth(); y *= -2; } if(y < 0) { x *= 2; y += grid.maxHeight(); } else if(y >= grid.maxHeight()) { x *= -2; y -= grid.maxHeight(); } while(x < 0 || x >= grid.maxWidth()) { if(x < 0) x += grid.maxWidth(); else if(x >= grid.maxWidth()) x -= grid.maxWidth(); } while(y < 0 || y >= grid.maxHeight()) { if(y < 0) y += grid.maxHeight(); else if(y >= grid.maxHeight()) y -= grid.maxHeight(); } neighbours.add(new Point(x,y)); } return neighbours; }
diff --git a/src/main/java/it/restrung/rest/marshalling/response/AbstractJSONResponse.java b/src/main/java/it/restrung/rest/marshalling/response/AbstractJSONResponse.java index 624af38..db87cb2 100644 --- a/src/main/java/it/restrung/rest/marshalling/response/AbstractJSONResponse.java +++ b/src/main/java/it/restrung/rest/marshalling/response/AbstractJSONResponse.java @@ -1,344 +1,344 @@ /* * Copyright (C) 2012 47 Degrees, LLC * http://47deg.com * [email protected] * * 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 it.restrung.rest.marshalling.response; import it.restrung.rest.annotations.JsonProperty; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.util.*; /** * Convenience abstract class to be implemented by objects that can be deserialized from remote response * This class ues reflection to invoke setter from json properties */ public abstract class AbstractJSONResponse implements JSONResponse { /** * The json delegate constructed out of the response */ protected transient JSONObject delegate; /** * A cache map of already serialized object properties */ protected transient Map<String, Object> propertyMap = new HashMap<String, Object>(); /** * @see JSONResponse#fromJSON(org.json.JSONObject) */ @Override @SuppressWarnings("unchecked") public void fromJSON(JSONObject jsonObject) throws JSONException { if (jsonObject != null) { this.delegate = jsonObject; Method[] methods = getClass().getDeclaredMethods(); for (Method method : methods) { if (method.getParameterTypes().length == 1 && method.getName().startsWith("set") && method.getName().length() > 3) { Class argType = method.getParameterTypes()[0]; String propertyName = method.getName().substring(3); propertyName = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1); try { - Field foundField = getClass().getDeclaredField(propertyName); + Field foundField = getClass().getField(propertyName); if (foundField.isAnnotationPresent(JsonProperty.class)) { propertyName = foundField.getAnnotation(JsonProperty.class).value(); } } catch (NoSuchFieldException e) { //todo log errors when field names mismatch their setter } Object result = null; if (String.class.isAssignableFrom(argType)) { result = getString(propertyName); } else if (Boolean.class.isAssignableFrom(argType) || boolean.class.isAssignableFrom(argType)) { result = getBoolean(propertyName); } else if (Double.class.isAssignableFrom(argType) || double.class.isAssignableFrom(argType)) { result = getDouble(propertyName); } else if (Long.class.isAssignableFrom(argType) || long.class.isAssignableFrom(argType)) { result = getLong(propertyName); } else if (Integer.class.isAssignableFrom(argType) || int.class.isAssignableFrom(argType)) { result = getInt(propertyName); } else if (Date.class.isAssignableFrom(argType)) { result = getDate(propertyName); } else if (JSONResponse.class.isAssignableFrom(argType)) { result = getObject(propertyName, argType); } else if (Enum.class.isAssignableFrom(argType)) { String value = getString(propertyName); if (value != null) { result = Enum.valueOf((Class<Enum>) argType, getString(propertyName)); } } else if (List.class.isAssignableFrom(argType)) { Class typeArg = (Class) ((ParameterizedType) method.getGenericParameterTypes()[0]).getActualTypeArguments()[0]; if (JSONResponse.class.isAssignableFrom(typeArg)) { result = getList(propertyName, typeArg); } else { result = getElementCollection(propertyName); } } else if (Map.class.isAssignableFrom(argType)) { Class typeArg = (Class) ((ParameterizedType) method.getGenericParameterTypes()[0]).getActualTypeArguments()[0]; if (JSONResponse.class.isAssignableFrom(typeArg)) { result = getMap(propertyName, typeArg); } else { result = getElementMap(propertyName); } } else { throw new UnsupportedOperationException(String.format("%s is of type: %s which is not yet supported by the AbstractJSONResponse serialization", propertyName, argType)); } try { method.invoke(this, result); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } } } /** * Gets a list property deserialized values from the cache or from the underlying JSONObject * * @param property the property name * @param typeClass the type of JSONResponse contained in the array * @return the list of objects associated to this property in the JSON response */ @SuppressWarnings("unchecked") private List<?> getList(String property, Class<?> typeClass) { List<Object> list = null; if (!propertyMap.containsKey(property)) { JSONArray array = delegate.optJSONArray(property); if (array != null) { list = new ArrayList<Object>(array.length()); for (int i = 0; i < array.length(); i++) { JSONObject jsonObject = array.optJSONObject(i); try { Object response = typeClass.newInstance(); ((JSONResponse) response).fromJSON(jsonObject); list.add(response); } catch (JSONException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } propertyMap.put(property, list); } } else { list = (List<Object>) propertyMap.get(property); } return list; } /** * Gets a map property deserialized values from the cache or from the underlying JSONObject * * @param property the property name * @param typeClass the type of JSONResponse contained in the property * @return the map of json response style objects associated to this property in the JSON response */ @SuppressWarnings("unchecked") private Map<String, ?> getMap(String property, Class<?> typeClass) { Map<String, Object> map = null; if (!propertyMap.containsKey(property)) { JSONObject jsonMap = delegate.optJSONObject(property); if (jsonMap != null) { map = new LinkedHashMap<String, Object>(jsonMap.length()); while (jsonMap.keys().hasNext()) { String key = (String) jsonMap.keys().next(); JSONObject jsonObject = jsonMap.optJSONObject(key); try { Object response = typeClass.newInstance(); ((JSONResponse) response).fromJSON(jsonObject); map.put(key, response); } catch (JSONException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } propertyMap.put(property, map); } } else { map = (Map<String, Object>) propertyMap.get(property); } return map; } /** * Gets a list property deserialized values from the cache or from the underlying JSONObject * * @param property the property name * @return the list of primitive or simple supported objects associated to this property in the JSON response */ @SuppressWarnings("unchecked") private <T> List<T> getElementCollection(String property) { List<T> list = null; if (!propertyMap.containsKey(property)) { JSONArray jsonArray = delegate.optJSONArray(property); if (jsonArray != null) { list = new ArrayList<T>(jsonArray.length()); for (int i = 0; i < jsonArray.length(); i++) { T item = (T) jsonArray.opt(i); list.add(item); } } propertyMap.put(property, list); } else { list = (List<T>) propertyMap.get(property); } return list; } /** * Gets a map property deserialized values from the cache or from the underlying JSONObject * * @param property the property name * @return the map containining the keys as string and as values the primitive or simple supported objects associated to this property in the JSON response */ @SuppressWarnings("unchecked") private Map<String, Object> getElementMap(String property) { Map<String, Object> map = null; if (!propertyMap.containsKey(property)) { JSONObject jsonObject = delegate.optJSONObject(property); if (jsonObject != null) { map = new LinkedHashMap<String, Object>(jsonObject.length()); while (jsonObject.keys().hasNext()) { String key = (String) jsonObject.keys().next(); map.put(key, jsonObject.opt(key)); } } propertyMap.put(property, map); } else { map = (Map<String, Object>) propertyMap.get(property); } return map; } /** * Gets a property deserialized value from the cache or from the underlying JSONObject * * @param property the property name * @param typeClass the type of JSONResponse contained in the property */ @SuppressWarnings("unchecked") private Object getObject(String property, Class<?> typeClass) { Object object = null; if (!propertyMap.containsKey(property)) { JSONObject jsonObject = delegate.optJSONObject(property); if (jsonObject != null) { try { object = typeClass.newInstance(); ((JSONResponse) object).fromJSON(jsonObject); } catch (JSONException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } propertyMap.put(property, object); } else { object = propertyMap.get(property); } return object; } /** * Gets a date property deserialized value from the cache or from the underlying JSONObject * This method assumes the property is in a timestamp long format with seconds precision * * @param property the property name */ private Date getDate(String property) { Long timestamp = delegate.optLong(property); return timestamp != null ? new Date(timestamp * 1000) : null; } /** * Gets a string property deserialized value from the cache or from the underlying JSONObject * This method assumes that "null" actually means null * * @param property the property name */ private String getString(String property) { String value = delegate.optString(property, null); return "null".equals(value) ? null : value; } /** * Gets a double property deserialized value from the cache or from the underlying JSONObject * This method defaults to 0.0 if the property is null * * @param property the property name */ private double getDouble(String property) { return delegate.optDouble(property, 0.0); } /** * Gets a long property deserialized value from the cache or from the underlying JSONObject * This method defaults to 0 if the property is null * * @param property the property name */ private long getLong(String property) { return delegate.optLong(property, 0); } /** * Gets an int property deserialized value from the cache or from the underlying JSONObject * This method defaults to 0 if the property is null * * @param property the property name */ private int getInt(String property) { return delegate.optInt(property, 0); } /** * Gets a boolean property deserialized value from the cache or from the underlying JSONObject * This method defaults to false if the property is null * * @param property the property name */ private boolean getBoolean(String property) { return delegate.optBoolean(property, false); } }
true
true
public void fromJSON(JSONObject jsonObject) throws JSONException { if (jsonObject != null) { this.delegate = jsonObject; Method[] methods = getClass().getDeclaredMethods(); for (Method method : methods) { if (method.getParameterTypes().length == 1 && method.getName().startsWith("set") && method.getName().length() > 3) { Class argType = method.getParameterTypes()[0]; String propertyName = method.getName().substring(3); propertyName = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1); try { Field foundField = getClass().getDeclaredField(propertyName); if (foundField.isAnnotationPresent(JsonProperty.class)) { propertyName = foundField.getAnnotation(JsonProperty.class).value(); } } catch (NoSuchFieldException e) { //todo log errors when field names mismatch their setter } Object result = null; if (String.class.isAssignableFrom(argType)) { result = getString(propertyName); } else if (Boolean.class.isAssignableFrom(argType) || boolean.class.isAssignableFrom(argType)) { result = getBoolean(propertyName); } else if (Double.class.isAssignableFrom(argType) || double.class.isAssignableFrom(argType)) { result = getDouble(propertyName); } else if (Long.class.isAssignableFrom(argType) || long.class.isAssignableFrom(argType)) { result = getLong(propertyName); } else if (Integer.class.isAssignableFrom(argType) || int.class.isAssignableFrom(argType)) { result = getInt(propertyName); } else if (Date.class.isAssignableFrom(argType)) { result = getDate(propertyName); } else if (JSONResponse.class.isAssignableFrom(argType)) { result = getObject(propertyName, argType); } else if (Enum.class.isAssignableFrom(argType)) { String value = getString(propertyName); if (value != null) { result = Enum.valueOf((Class<Enum>) argType, getString(propertyName)); } } else if (List.class.isAssignableFrom(argType)) { Class typeArg = (Class) ((ParameterizedType) method.getGenericParameterTypes()[0]).getActualTypeArguments()[0]; if (JSONResponse.class.isAssignableFrom(typeArg)) { result = getList(propertyName, typeArg); } else { result = getElementCollection(propertyName); } } else if (Map.class.isAssignableFrom(argType)) { Class typeArg = (Class) ((ParameterizedType) method.getGenericParameterTypes()[0]).getActualTypeArguments()[0]; if (JSONResponse.class.isAssignableFrom(typeArg)) { result = getMap(propertyName, typeArg); } else { result = getElementMap(propertyName); } } else { throw new UnsupportedOperationException(String.format("%s is of type: %s which is not yet supported by the AbstractJSONResponse serialization", propertyName, argType)); } try { method.invoke(this, result); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } } }
public void fromJSON(JSONObject jsonObject) throws JSONException { if (jsonObject != null) { this.delegate = jsonObject; Method[] methods = getClass().getDeclaredMethods(); for (Method method : methods) { if (method.getParameterTypes().length == 1 && method.getName().startsWith("set") && method.getName().length() > 3) { Class argType = method.getParameterTypes()[0]; String propertyName = method.getName().substring(3); propertyName = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1); try { Field foundField = getClass().getField(propertyName); if (foundField.isAnnotationPresent(JsonProperty.class)) { propertyName = foundField.getAnnotation(JsonProperty.class).value(); } } catch (NoSuchFieldException e) { //todo log errors when field names mismatch their setter } Object result = null; if (String.class.isAssignableFrom(argType)) { result = getString(propertyName); } else if (Boolean.class.isAssignableFrom(argType) || boolean.class.isAssignableFrom(argType)) { result = getBoolean(propertyName); } else if (Double.class.isAssignableFrom(argType) || double.class.isAssignableFrom(argType)) { result = getDouble(propertyName); } else if (Long.class.isAssignableFrom(argType) || long.class.isAssignableFrom(argType)) { result = getLong(propertyName); } else if (Integer.class.isAssignableFrom(argType) || int.class.isAssignableFrom(argType)) { result = getInt(propertyName); } else if (Date.class.isAssignableFrom(argType)) { result = getDate(propertyName); } else if (JSONResponse.class.isAssignableFrom(argType)) { result = getObject(propertyName, argType); } else if (Enum.class.isAssignableFrom(argType)) { String value = getString(propertyName); if (value != null) { result = Enum.valueOf((Class<Enum>) argType, getString(propertyName)); } } else if (List.class.isAssignableFrom(argType)) { Class typeArg = (Class) ((ParameterizedType) method.getGenericParameterTypes()[0]).getActualTypeArguments()[0]; if (JSONResponse.class.isAssignableFrom(typeArg)) { result = getList(propertyName, typeArg); } else { result = getElementCollection(propertyName); } } else if (Map.class.isAssignableFrom(argType)) { Class typeArg = (Class) ((ParameterizedType) method.getGenericParameterTypes()[0]).getActualTypeArguments()[0]; if (JSONResponse.class.isAssignableFrom(typeArg)) { result = getMap(propertyName, typeArg); } else { result = getElementMap(propertyName); } } else { throw new UnsupportedOperationException(String.format("%s is of type: %s which is not yet supported by the AbstractJSONResponse serialization", propertyName, argType)); } try { method.invoke(this, result); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } } }
diff --git a/src/javatests/com/google/caja/opensocial/GadgetsTestMain.java b/src/javatests/com/google/caja/opensocial/GadgetsTestMain.java index 3b724de9..23c3c5ce 100644 --- a/src/javatests/com/google/caja/opensocial/GadgetsTestMain.java +++ b/src/javatests/com/google/caja/opensocial/GadgetsTestMain.java @@ -1,386 +1,385 @@ // Copyright 2007 Google Inc. All Rights Reserved. // 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.caja.opensocial; import com.google.caja.lexer.CharProducer; import com.google.caja.lexer.ExternalReference; import com.google.caja.lexer.FilePosition; import com.google.caja.lexer.InputSource; import com.google.caja.plugin.Config; import com.google.caja.reporting.BuildInfo; import com.google.caja.reporting.HtmlSnippetProducer; import com.google.caja.reporting.Message; import com.google.caja.reporting.MessageContext; import com.google.caja.reporting.MessageLevel; import com.google.caja.reporting.MessagePart; import com.google.caja.reporting.MessageQueue; import com.google.caja.reporting.MessageType; import com.google.caja.reporting.MessageTypeInt; import com.google.caja.reporting.SimpleMessageQueue; import com.google.caja.reporting.SnippetProducer; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * @author [email protected] (Jasvir Nagra) */ public class GadgetsTestMain { private MessageContext mc = new MessageContext(); private Map<InputSource, CharSequence> originalSources = new HashMap<InputSource, CharSequence>(); private ArrayList<URI> gadgetList; private JSONObject resultDoc; private BufferedWriter jsonOutput; private GadgetsTestMain() { resultDoc = new JSONObject(); mc.inputSources = new ArrayList<InputSource>(); } public static void main(String[] argv) throws UriCallbackException { System.exit(new GadgetsTestMain().run(argv)); } public boolean processArguments(String[] argv) { gadgetList = new ArrayList<URI>(); if (argv.length == 0) { usage("GadgetsTestMain urls-of-gadgets.txt [outputfile]"); return false; } try { String uri; BufferedReader ur = new BufferedReader(new FileReader(argv[0])); // Skip blank lines or comments while (null != (uri = ur.readLine())) { if (uri.matches("^[ \t]*$")) continue; if (uri.matches("^[ \t]*#")) continue; URI inputUri; try { if (uri.indexOf(':') >= 0) { inputUri = new URI(uri); } else { File inputFile = new File(uri); if (!inputFile.exists()) { System.err.println("WARNING: File \"" + uri + "\" does not exist"); return false; } if (!inputFile.isFile()) { usage("File \"" + uri + "\" is not a regular file"); return false; } inputUri = inputFile.getAbsoluteFile().toURI(); } gadgetList.add(inputUri); } catch (URISyntaxException e) { System.err.println("WARNING: URI \"" + uri + "\" malformed"); } } } catch (FileNotFoundException e) { usage("ERROR: Could not find file of urls:" + e.toString()); return false; } catch (IOException e) { usage("ERROR: Could not read urls:" + e.toString()); return false; } try { if (argv.length > 1) { jsonOutput = new BufferedWriter(new FileWriter(new File(argv[1]))); } else { jsonOutput = new BufferedWriter(new OutputStreamWriter(System.out)); } } catch (IOException e) { e.printStackTrace(); } return true; } private void writeResults(Writer w) { try { String json = resultDoc.toString(); w.write(json); } catch (IOException e) { e.printStackTrace(); } } private String getExceptionTrace(Exception e) { StringBuffer result = new StringBuffer(); for (StackTraceElement st : e.getStackTrace()) { result.append(st.toString()); result.append("\n"); } return result.toString(); } private void testGadget(URI gadget, JSONArray testResults, Map<MessageTypeInt, Integer> errorCount) throws IOException, UriCallbackException { String[] argv = { "-o", "/tmp/xx", - "-p", "xx", "--css_prop_schema", "resource:///com/google/caja/lang/css/css-extensions.json", "-i", gadget.toASCIIString() }; GadgetRewriterMain grm = new GadgetRewriterMain(); grm.init(argv); Config config = grm.getConfig(); MessageQueue mq = new SimpleMessageQueue(); DefaultGadgetRewriter rewriter = new DefaultGadgetRewriter(mq); rewriter.setCssSchema(config.getCssSchema(mq)); rewriter.setHtmlSchema(config.getHtmlSchema(mq)); JSONArray messages = new JSONArray(); JSONObject gadgetElement = json("url", gadget.toString(), "title", "TODO", "messages", messages); pushJson(testResults, gadgetElement); Writer w = new BufferedWriter(new FileWriter(config.getOutputBase())); MessageLevel worstErrorLevel = MessageLevel.LOG; MessageTypeInt worstErrorType = null; try { Callback cb = new Callback(config, mc, originalSources); URI baseUri = config.getBaseUri(); for (URI input : config.getInputUris()) { System.err.println(input); Reader r = cb.retrieve( new ExternalReference(input, FilePosition.UNKNOWN), null); CharProducer cp = CharProducer.Factory.create( r, new InputSource(input)); try { rewriter.rewrite(baseUri, cp, cb, "canvas", w); } catch (Exception e) { addMessageNode(messages,"Compiler threw uncaught exception: " + e, MessageLevel.FATAL_ERROR.toString(), MessageType.INTERNAL_ERROR.toString(), getExceptionTrace(e)); worstErrorType = MessageType.INTERNAL_ERROR; worstErrorLevel = MessageLevel.FATAL_ERROR; int count = errorCount.containsKey(MessageType.INTERNAL_ERROR) ? errorCount.get(MessageType.INTERNAL_ERROR) : 0; errorCount.put(MessageType.INTERNAL_ERROR, count + 1); } finally { SnippetProducer sp = new HtmlSnippetProducer(originalSources, mc); for (Message msg : mq.getMessages()) { MessageTypeInt type = msg.getMessageType(); if (type == MessageType.SEMICOLON_INSERTED) { continue; } addMessageNode(messages, msg, mc, sp); int count = errorCount.containsKey(type) ? errorCount.get(type) : 0; errorCount.put(type, count + 1); if (msg.getMessageLevel().compareTo(worstErrorLevel) > 0) { worstErrorType = msg.getMessageType(); worstErrorLevel = msg.getMessageLevel(); } } r.close(); } } } catch (RuntimeException e) { addMessageNode(messages,"Compiler threw uncaught runtime exception: " + e, MessageLevel.FATAL_ERROR.toString(), MessageType.INTERNAL_ERROR.toString(), getExceptionTrace(e)); worstErrorType = MessageType.INTERNAL_ERROR; worstErrorLevel = MessageLevel.FATAL_ERROR; } finally { addWorstErrorNode(gadgetElement, worstErrorLevel, worstErrorType); w.close(); } } private void addSummaryResults( JSONArray summary, Map<MessageTypeInt, Integer> errorCount) { List<Map.Entry<MessageTypeInt, Integer>> entries = new ArrayList<Map.Entry<MessageTypeInt, Integer>>( errorCount.entrySet()); Collections.sort( entries, new Comparator<Map.Entry<MessageTypeInt, Integer>>() { public int compare(Map.Entry<MessageTypeInt, Integer> a, Map.Entry<MessageTypeInt, Integer> b) { return b.getValue() - a.getValue(); } }); for (Map.Entry<MessageTypeInt, Integer> e : entries) { pushJson( summary, json("type", e.getKey(), "value", e.getValue(), "errorLevel", e.getKey().getLevel())); } } private int run(String[] argv) throws UriCallbackException { if (!processArguments(argv)) { return -1; } String timestamp = (new Date()).toString(); System.out.println(timestamp); Map<MessageTypeInt, Integer> errorCount = new LinkedHashMap<MessageTypeInt, Integer>(); JSONArray testResults = new JSONArray(); JSONArray summary = new JSONArray(); putJson( resultDoc, "buildInfo", JSONObject.escape(BuildInfo.getInstance().getBuildInfo()), "timestamp", JSONObject.escape(timestamp), "gadgets", testResults, "summary", summary); try { for (URI gadgetUri : gadgetList) { try { testGadget(gadgetUri, testResults, errorCount); } catch (RuntimeException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } finally { addSummaryResults(summary,errorCount); writeResults(jsonOutput); try { jsonOutput.close(); } catch (IOException e) { e.printStackTrace(); } } return 0; } private void addMessageNode(JSONArray messages, String position, String level, String type, String text) { pushJson(messages, json("position", position, "level", level, "type", type, "text", text)); } private void addWorstErrorNode(JSONObject gadget, MessageLevel mLevel, MessageTypeInt mType) { String levelOrdinal = mLevel == null ? "UNKNOWN" : "" + mLevel.ordinal(); String level = mLevel == null ? "UNKNOWN" : mLevel.toString(); String type = mType == null ? "UNKNOWN" : mType.toString(); putJson(gadget, "worstError", json("type", type, "level", level, "levelOrdinal", levelOrdinal)); } private void addMessageNode( JSONArray messages, Message msg, MessageContext mc, SnippetProducer sp) { MessageLevel messageLevel = msg.getMessageLevel(); MessagePart topMessage = msg.getMessageParts().get(0); StringBuffer position = new StringBuffer(); String snippet = null; String type = msg.getMessageType().toString(); if (topMessage instanceof FilePosition) { FilePosition filePosition = (FilePosition) topMessage; try { filePosition.format(mc, position); } catch (IOException e) { e.printStackTrace(); } } else { position = new StringBuffer("Unknown"); } snippet = sp.getSnippet(msg); addMessageNode( messages, msg.format(mc), messageLevel.name(), type, snippet); } public void usage(String msg) { System.err.println(BuildInfo.getInstance().getBuildInfo()); System.err.println(); if (msg != null && !"".equals(msg)) { System.err.println(msg); System.err.println(); } System.err.println("usage: GadgetsTestMain listofurls.txt output.json"); } private static JSONObject json(Object... members) { JSONObject o = new JSONObject(); putJson(o, members); return o; } @SuppressWarnings("unchecked") private static void putJson(JSONObject o, Object... members) { for (int i = 0, n = members.length; i < n; i += 2) { String name = (String) members[i]; Object value = toJsonValue(members[i + 1]); o.put(name, value); } } @SuppressWarnings("unchecked") private static void pushJson(JSONArray a, Object... members) { for (Object member : members) { a.add(toJsonValue(member)); } } private static Object toJsonValue(Object value) { if (value == null || value instanceof Boolean || value instanceof Number || value instanceof JSONObject || value instanceof JSONArray) { return value; } return value.toString(); } }
true
true
private void testGadget(URI gadget, JSONArray testResults, Map<MessageTypeInt, Integer> errorCount) throws IOException, UriCallbackException { String[] argv = { "-o", "/tmp/xx", "-p", "xx", "--css_prop_schema", "resource:///com/google/caja/lang/css/css-extensions.json", "-i", gadget.toASCIIString() }; GadgetRewriterMain grm = new GadgetRewriterMain(); grm.init(argv); Config config = grm.getConfig(); MessageQueue mq = new SimpleMessageQueue(); DefaultGadgetRewriter rewriter = new DefaultGadgetRewriter(mq); rewriter.setCssSchema(config.getCssSchema(mq)); rewriter.setHtmlSchema(config.getHtmlSchema(mq)); JSONArray messages = new JSONArray(); JSONObject gadgetElement = json("url", gadget.toString(), "title", "TODO", "messages", messages); pushJson(testResults, gadgetElement); Writer w = new BufferedWriter(new FileWriter(config.getOutputBase())); MessageLevel worstErrorLevel = MessageLevel.LOG; MessageTypeInt worstErrorType = null; try { Callback cb = new Callback(config, mc, originalSources); URI baseUri = config.getBaseUri(); for (URI input : config.getInputUris()) { System.err.println(input); Reader r = cb.retrieve( new ExternalReference(input, FilePosition.UNKNOWN), null); CharProducer cp = CharProducer.Factory.create( r, new InputSource(input)); try { rewriter.rewrite(baseUri, cp, cb, "canvas", w); } catch (Exception e) { addMessageNode(messages,"Compiler threw uncaught exception: " + e, MessageLevel.FATAL_ERROR.toString(), MessageType.INTERNAL_ERROR.toString(), getExceptionTrace(e)); worstErrorType = MessageType.INTERNAL_ERROR; worstErrorLevel = MessageLevel.FATAL_ERROR; int count = errorCount.containsKey(MessageType.INTERNAL_ERROR) ? errorCount.get(MessageType.INTERNAL_ERROR) : 0; errorCount.put(MessageType.INTERNAL_ERROR, count + 1); } finally { SnippetProducer sp = new HtmlSnippetProducer(originalSources, mc); for (Message msg : mq.getMessages()) { MessageTypeInt type = msg.getMessageType(); if (type == MessageType.SEMICOLON_INSERTED) { continue; } addMessageNode(messages, msg, mc, sp); int count = errorCount.containsKey(type) ? errorCount.get(type) : 0; errorCount.put(type, count + 1); if (msg.getMessageLevel().compareTo(worstErrorLevel) > 0) { worstErrorType = msg.getMessageType(); worstErrorLevel = msg.getMessageLevel(); } } r.close(); } } } catch (RuntimeException e) { addMessageNode(messages,"Compiler threw uncaught runtime exception: " + e, MessageLevel.FATAL_ERROR.toString(), MessageType.INTERNAL_ERROR.toString(), getExceptionTrace(e)); worstErrorType = MessageType.INTERNAL_ERROR; worstErrorLevel = MessageLevel.FATAL_ERROR; } finally { addWorstErrorNode(gadgetElement, worstErrorLevel, worstErrorType); w.close(); } }
private void testGadget(URI gadget, JSONArray testResults, Map<MessageTypeInt, Integer> errorCount) throws IOException, UriCallbackException { String[] argv = { "-o", "/tmp/xx", "--css_prop_schema", "resource:///com/google/caja/lang/css/css-extensions.json", "-i", gadget.toASCIIString() }; GadgetRewriterMain grm = new GadgetRewriterMain(); grm.init(argv); Config config = grm.getConfig(); MessageQueue mq = new SimpleMessageQueue(); DefaultGadgetRewriter rewriter = new DefaultGadgetRewriter(mq); rewriter.setCssSchema(config.getCssSchema(mq)); rewriter.setHtmlSchema(config.getHtmlSchema(mq)); JSONArray messages = new JSONArray(); JSONObject gadgetElement = json("url", gadget.toString(), "title", "TODO", "messages", messages); pushJson(testResults, gadgetElement); Writer w = new BufferedWriter(new FileWriter(config.getOutputBase())); MessageLevel worstErrorLevel = MessageLevel.LOG; MessageTypeInt worstErrorType = null; try { Callback cb = new Callback(config, mc, originalSources); URI baseUri = config.getBaseUri(); for (URI input : config.getInputUris()) { System.err.println(input); Reader r = cb.retrieve( new ExternalReference(input, FilePosition.UNKNOWN), null); CharProducer cp = CharProducer.Factory.create( r, new InputSource(input)); try { rewriter.rewrite(baseUri, cp, cb, "canvas", w); } catch (Exception e) { addMessageNode(messages,"Compiler threw uncaught exception: " + e, MessageLevel.FATAL_ERROR.toString(), MessageType.INTERNAL_ERROR.toString(), getExceptionTrace(e)); worstErrorType = MessageType.INTERNAL_ERROR; worstErrorLevel = MessageLevel.FATAL_ERROR; int count = errorCount.containsKey(MessageType.INTERNAL_ERROR) ? errorCount.get(MessageType.INTERNAL_ERROR) : 0; errorCount.put(MessageType.INTERNAL_ERROR, count + 1); } finally { SnippetProducer sp = new HtmlSnippetProducer(originalSources, mc); for (Message msg : mq.getMessages()) { MessageTypeInt type = msg.getMessageType(); if (type == MessageType.SEMICOLON_INSERTED) { continue; } addMessageNode(messages, msg, mc, sp); int count = errorCount.containsKey(type) ? errorCount.get(type) : 0; errorCount.put(type, count + 1); if (msg.getMessageLevel().compareTo(worstErrorLevel) > 0) { worstErrorType = msg.getMessageType(); worstErrorLevel = msg.getMessageLevel(); } } r.close(); } } } catch (RuntimeException e) { addMessageNode(messages,"Compiler threw uncaught runtime exception: " + e, MessageLevel.FATAL_ERROR.toString(), MessageType.INTERNAL_ERROR.toString(), getExceptionTrace(e)); worstErrorType = MessageType.INTERNAL_ERROR; worstErrorLevel = MessageLevel.FATAL_ERROR; } finally { addWorstErrorNode(gadgetElement, worstErrorLevel, worstErrorType); w.close(); } }
diff --git a/src/org/geworkbench/builtin/projects/ProjectSelection.java b/src/org/geworkbench/builtin/projects/ProjectSelection.java index 082e1a74..261cfcca 100755 --- a/src/org/geworkbench/builtin/projects/ProjectSelection.java +++ b/src/org/geworkbench/builtin/projects/ProjectSelection.java @@ -1,211 +1,212 @@ package org.geworkbench.builtin.projects; import org.geworkbench.bison.datastructure.biocollections.DSAncillaryDataSet; import org.geworkbench.bison.datastructure.biocollections.DSDataSet; import org.geworkbench.bison.datastructure.biocollections.microarrays.DSMicroarraySet; import org.geworkbench.bison.datastructure.bioobjects.markers.annotationparser.AnnotationParser; import org.geworkbench.engine.config.rules.GeawConfigObject; import org.geworkbench.events.ProjectEvent; /** * <p>Title: Sequence and Pattern Plugin</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2003</p> * <p>Company: </p> * * @author not attributable * @version 1.0 */ public class ProjectSelection { private ProjectNode selectedProjectNode = null; private DataSetNode selectedDataSetNode = null; private DataSetSubNode selectedDataSetSubNode = null; private ProjectTreeNode selectedNode = null; private ProjectTreeNode menuNode = null; // The node that a popup menu is invoked on private ProjectPanel panel; public ProjectSelection(ProjectPanel panel) { this.panel = panel; } /** * Returns whether the selections have all been cleared * * @return */ public boolean areNodeSelectionsCleared() { return (selectedProjectNode == null); } /** * Clears the selections and broadcasts the event */ public void clearNodeSelections() { selectedProjectNode = null; selectedDataSetNode = null; selectedDataSetSubNode = null; selectedNode = null; menuNode = null; throwEvent("receiveProjectSelection", "Project Cleared"); } // Access to various selection variables public ProjectNode getSelectedProjectNode() { return selectedProjectNode; } public DataSetNode getSelectedDataSetNode() { return selectedDataSetNode; } public DataSetSubNode getSelectedDataSetSubNode() { return selectedDataSetSubNode; } public ProjectTreeNode getSelectedNode() { return selectedNode; } public ProjectTreeNode getMenuNode() { return menuNode; } public void setMenuNode(ProjectTreeNode node) { menuNode = node; } public DSDataSet getDataSet() { if (selectedDataSetNode != null) { return selectedDataSetNode.dataFile; } else { return null; } } public DSAncillaryDataSet getDataSubSet() { if (selectedDataSetSubNode != null) { return selectedDataSetSubNode._aDataSet; } else { return null; } } /** * Finds the project node associated with this node of the given class * * @param parentPath * @return */ public ProjectTreeNode getNodeOfClass(ProjectTreeNode node, Class aClass) { while (!(aClass.isInstance(node))) { node = (ProjectTreeNode) node.getParent(); if (node == null) { return null; } } return (ProjectTreeNode) node; } /** * Assigns a new selection node * * @param pNode * @param node */ public void setNodeSelection(ProjectTreeNode node) { if (selectedNode != node) { selectedNode = node; menuNode = node; selectedProjectNode = (ProjectNode) getNodeOfClass(node, ProjectNode.class); boolean subNode = false; if (node instanceof DataSetNode) { selectedDataSetNode = (DataSetNode) node; AnnotationParser.setCurrentDataSet(selectedDataSetNode.dataFile); GeawConfigObject.getGuiWindow().setVisualizationType(selectedDataSetNode.dataFile); } else if (node instanceof DataSetSubNode) { selectedDataSetSubNode = (DataSetSubNode) node; selectedDataSetNode = (DataSetNode) getNodeOfClass(node, DataSetNode.class); + AnnotationParser.setCurrentDataSet(selectedDataSetNode.dataFile);//Fix bug 1471 GeawConfigObject.getGuiWindow().setVisualizationType(selectedDataSetSubNode._aDataSet); subNode = true; } else if (node instanceof ProjectNode && node.getChildCount() == 0) { selectedDataSetNode = null; selectedDataSetSubNode = null; GeawConfigObject.getGuiWindow().setVisualizationType(null); throwEvent("receiveProjectSelection", ProjectEvent.CLEARED); } checkProjectNode(); if (subNode) { throwSubNodeEvent("receiveProjectSelection"); } else { throwEvent("receiveProjectSelection", ProjectEvent.SELECTED); } } } /** * Checks that the selections are correctly assigned at the project level */ private void checkProjectNode() { if (selectedProjectNode == null) { selectedDataSetNode = null; selectedDataSetSubNode = null; } else { checkDataSetNode(); } } /** * Checks that the selections are correctly assigned at the DataSet level */ private void checkDataSetNode() { if (selectedDataSetNode == null) { selectedDataSetSubNode = null; } else { if (selectedDataSetNode.getParent() != selectedProjectNode) { selectedDataSetNode = null; selectedDataSetSubNode = null; } else { checkDataSetSubNode(); } } } /** * Checks that the selections are correctly assigned at the DataSetSub level */ private void checkDataSetSubNode() { if (selectedDataSetSubNode != null) { if (selectedDataSetSubNode.getParent() != selectedDataSetNode) { selectedDataSetSubNode = null; } } } /** * Throws the corresponding message event * * @param message */ public void throwEvent(String method, String message) { // Notify all listeners of the change in selection DSMicroarraySet maSet = null; if (selectedDataSetNode != null) { if (selectedDataSetNode.dataFile instanceof DSMicroarraySet) { maSet = (DSMicroarraySet) selectedDataSetNode.dataFile; panel.publishProjectEvent(new ProjectEvent(message, maSet, selectedDataSetNode)); } else { panel.publishProjectEvent(new ProjectEvent(message, selectedDataSetNode.dataFile, selectedDataSetNode)); } panel.sendCommentsEvent(selectedDataSetNode); } } public void throwSubNodeEvent(String message) { if ((selectedDataSetSubNode != null) && (selectedDataSetSubNode._aDataSet != null)) { panel.publishProjectEvent(new ProjectEvent(message, selectedDataSetSubNode._aDataSet, selectedDataSetSubNode)); } } }
true
true
public void setNodeSelection(ProjectTreeNode node) { if (selectedNode != node) { selectedNode = node; menuNode = node; selectedProjectNode = (ProjectNode) getNodeOfClass(node, ProjectNode.class); boolean subNode = false; if (node instanceof DataSetNode) { selectedDataSetNode = (DataSetNode) node; AnnotationParser.setCurrentDataSet(selectedDataSetNode.dataFile); GeawConfigObject.getGuiWindow().setVisualizationType(selectedDataSetNode.dataFile); } else if (node instanceof DataSetSubNode) { selectedDataSetSubNode = (DataSetSubNode) node; selectedDataSetNode = (DataSetNode) getNodeOfClass(node, DataSetNode.class); GeawConfigObject.getGuiWindow().setVisualizationType(selectedDataSetSubNode._aDataSet); subNode = true; } else if (node instanceof ProjectNode && node.getChildCount() == 0) { selectedDataSetNode = null; selectedDataSetSubNode = null; GeawConfigObject.getGuiWindow().setVisualizationType(null); throwEvent("receiveProjectSelection", ProjectEvent.CLEARED); } checkProjectNode(); if (subNode) { throwSubNodeEvent("receiveProjectSelection"); } else { throwEvent("receiveProjectSelection", ProjectEvent.SELECTED); } } }
public void setNodeSelection(ProjectTreeNode node) { if (selectedNode != node) { selectedNode = node; menuNode = node; selectedProjectNode = (ProjectNode) getNodeOfClass(node, ProjectNode.class); boolean subNode = false; if (node instanceof DataSetNode) { selectedDataSetNode = (DataSetNode) node; AnnotationParser.setCurrentDataSet(selectedDataSetNode.dataFile); GeawConfigObject.getGuiWindow().setVisualizationType(selectedDataSetNode.dataFile); } else if (node instanceof DataSetSubNode) { selectedDataSetSubNode = (DataSetSubNode) node; selectedDataSetNode = (DataSetNode) getNodeOfClass(node, DataSetNode.class); AnnotationParser.setCurrentDataSet(selectedDataSetNode.dataFile);//Fix bug 1471 GeawConfigObject.getGuiWindow().setVisualizationType(selectedDataSetSubNode._aDataSet); subNode = true; } else if (node instanceof ProjectNode && node.getChildCount() == 0) { selectedDataSetNode = null; selectedDataSetSubNode = null; GeawConfigObject.getGuiWindow().setVisualizationType(null); throwEvent("receiveProjectSelection", ProjectEvent.CLEARED); } checkProjectNode(); if (subNode) { throwSubNodeEvent("receiveProjectSelection"); } else { throwEvent("receiveProjectSelection", ProjectEvent.SELECTED); } } }
diff --git a/guice/modules/src/main/java/org/atmosphere/guice/AtmosphereGuiceServlet.java b/guice/modules/src/main/java/org/atmosphere/guice/AtmosphereGuiceServlet.java index c1c9a5ad..4034cca8 100644 --- a/guice/modules/src/main/java/org/atmosphere/guice/AtmosphereGuiceServlet.java +++ b/guice/modules/src/main/java/org/atmosphere/guice/AtmosphereGuiceServlet.java @@ -1,171 +1,170 @@ /* * Copyright 2013 Jeanfrancois Arcand * * 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.atmosphere.guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.inject.name.Names; import org.atmosphere.cpr.ApplicationConfig; import org.atmosphere.cpr.AtmosphereFramework; import org.atmosphere.cpr.AtmosphereServlet; import org.atmosphere.cpr.DefaultBroadcasterFactory; import org.atmosphere.cpr.FrameworkConfig; import org.atmosphere.handler.ReflectorServletProcessor; import org.atmosphere.jersey.JerseyBroadcaster; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import java.util.Map; import static org.atmosphere.cpr.FrameworkConfig.JERSEY_CONTAINER; /** * Google Guice Integration. To use it, just do in web.xml: * <p/> * <blockquote><code> * &lt;web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" * xmlns:j2ee = "http://java.sun.com/xml/ns/j2ee" * xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" * xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&gt; * &lt;listener&gt; * &lt;listener-class&gt;org.atmosphere.samples.guice.GuiceChatConfig&lt;/listener-class&gt; * &lt;/listener&gt; * &lt;description&gt;Atmosphere Chat&lt;/description&gt; * &lt;display-name&gt;Atmosphere Chat&lt;/display-name&gt; * &lt;servlet&gt; * &lt;description&gt;AtmosphereServlet&lt;/description&gt; * &lt;servlet-name&gt;AtmosphereServlet&lt;/servlet-name&gt; * &lt;servlet-class&gt;org.atmosphere.guice.AtmosphereGuiceServlet&lt;/servlet-class&gt; * &lt;load-on-startup&gt;0&lt;/load-on-startup&gt; * &lt;/servlet&gt; * &lt;servlet-mapping&gt; * &lt;servlet-name&gt;AtmosphereServlet&lt;/servlet-name&gt; * &lt;url-pattern&gt;/chat/*&lt;/url-pattern&gt; * &lt;/servlet-mapping&gt; * &lt;/web-app&gt; * <p/> * and then * <p/> * public class GuiceConfig extends GuiceServletContextListener { * * @author Jeanfrancois Arcand * @author Richard Wallace * @Override protected Injector getInjector() { * return Guice.createInjector(new ServletModule() { * @Override protected void configureServlets() { * bind(PubSubTest.class); * bind(new TypeLiteral&lt;Map&lt;String, String&gt;&gt;() { * }).annotatedWith(Names.named(AtmosphereGuiceServlet.JERSEY_PROPERTIES)).toInstance( * Collections.&lt;String, String>emptyMap()); * } * }); * } * } * </code></blockquote> */ public class AtmosphereGuiceServlet extends AtmosphereServlet { private static final Logger logger = LoggerFactory.getLogger(AtmosphereGuiceServlet.class); public static final String JERSEY_PROPERTIES = AtmosphereGuiceServlet.class.getName() + ".properties"; private static final String GUICE_FILTER = "com.google.inject.servlet.GuiceFilter"; private boolean guiceInstalled = false; public AtmosphereGuiceServlet() { this(false,true); } /** * Create an Atmosphere Servlet. * * @param isFilter true if this instance is used as an {@link org.atmosphere.cpr.AtmosphereFilter} */ public AtmosphereGuiceServlet(boolean isFilter, boolean autoDetectHandlers) { framework = new AtmosphereFramework(isFilter, autoDetectHandlers) { /** * Install Guice event if other extension has been already installed. * * @param sc {@link javax.servlet.ServletConfig} * @throws ServletException */ public void loadConfiguration(ServletConfig sc) throws ServletException { super.loadConfiguration(sc); if (!guiceInstalled) { detectSupportedFramework(sc); } } /** * Auto-detect Jersey when no atmosphere.xml file are specified. * * @param sc {@link javax.servlet.ServletConfig} * @return true if Jersey classes are detected */ protected boolean detectSupportedFramework(ServletConfig sc) { Injector injector = (Injector) framework().getAtmosphereConfig().getServletContext().getAttribute(Injector.class.getName()); GuiceContainer guiceServlet = injector.getInstance(GuiceContainer.class); setUseStreamForFlushingComments(false); ReflectorServletProcessor rsp = new ReflectorServletProcessor(); boolean isJersey = false; try { Thread.currentThread().getContextClassLoader().loadClass(JERSEY_CONTAINER); - setDefaultBroadcasterClassName(FrameworkConfig.JERSEY_BROADCASTER) + setDefaultBroadcasterClassName(broadcasterClassName) .setUseStreamForFlushingComments(true) .getAtmosphereConfig().setSupportSession(false); - DefaultBroadcasterFactory.buildAndReplaceDefaultfactory(JerseyBroadcaster.class, getAtmosphereConfig()); isJersey = true; } catch (Throwable t) { } rsp.setServlet(guiceServlet); String mapping = sc.getInitParameter(ApplicationConfig.PROPERTY_SERVLET_MAPPING); if (mapping == null) { mapping = "/*"; } if (isJersey) { try { Map<String, String> props = injector.getInstance( Key.get(new TypeLiteral<Map<String, String>>() { }, Names.named(JERSEY_PROPERTIES))); if (props != null) { for (String p : props.keySet()) { framework().addInitParameter(p, props.get(p)); } } } catch (Exception ex) { // Do not fail logger.debug("failed to add Jersey init parameters to Atmosphere servlet", ex); } } addAtmosphereHandler(mapping, rsp); guiceInstalled = true; return true; } }; } }
false
true
public AtmosphereGuiceServlet(boolean isFilter, boolean autoDetectHandlers) { framework = new AtmosphereFramework(isFilter, autoDetectHandlers) { /** * Install Guice event if other extension has been already installed. * * @param sc {@link javax.servlet.ServletConfig} * @throws ServletException */ public void loadConfiguration(ServletConfig sc) throws ServletException { super.loadConfiguration(sc); if (!guiceInstalled) { detectSupportedFramework(sc); } } /** * Auto-detect Jersey when no atmosphere.xml file are specified. * * @param sc {@link javax.servlet.ServletConfig} * @return true if Jersey classes are detected */ protected boolean detectSupportedFramework(ServletConfig sc) { Injector injector = (Injector) framework().getAtmosphereConfig().getServletContext().getAttribute(Injector.class.getName()); GuiceContainer guiceServlet = injector.getInstance(GuiceContainer.class); setUseStreamForFlushingComments(false); ReflectorServletProcessor rsp = new ReflectorServletProcessor(); boolean isJersey = false; try { Thread.currentThread().getContextClassLoader().loadClass(JERSEY_CONTAINER); setDefaultBroadcasterClassName(FrameworkConfig.JERSEY_BROADCASTER) .setUseStreamForFlushingComments(true) .getAtmosphereConfig().setSupportSession(false); DefaultBroadcasterFactory.buildAndReplaceDefaultfactory(JerseyBroadcaster.class, getAtmosphereConfig()); isJersey = true; } catch (Throwable t) { } rsp.setServlet(guiceServlet); String mapping = sc.getInitParameter(ApplicationConfig.PROPERTY_SERVLET_MAPPING); if (mapping == null) { mapping = "/*"; } if (isJersey) { try { Map<String, String> props = injector.getInstance( Key.get(new TypeLiteral<Map<String, String>>() { }, Names.named(JERSEY_PROPERTIES))); if (props != null) { for (String p : props.keySet()) { framework().addInitParameter(p, props.get(p)); } } } catch (Exception ex) { // Do not fail logger.debug("failed to add Jersey init parameters to Atmosphere servlet", ex); } } addAtmosphereHandler(mapping, rsp); guiceInstalled = true; return true; } }; }
public AtmosphereGuiceServlet(boolean isFilter, boolean autoDetectHandlers) { framework = new AtmosphereFramework(isFilter, autoDetectHandlers) { /** * Install Guice event if other extension has been already installed. * * @param sc {@link javax.servlet.ServletConfig} * @throws ServletException */ public void loadConfiguration(ServletConfig sc) throws ServletException { super.loadConfiguration(sc); if (!guiceInstalled) { detectSupportedFramework(sc); } } /** * Auto-detect Jersey when no atmosphere.xml file are specified. * * @param sc {@link javax.servlet.ServletConfig} * @return true if Jersey classes are detected */ protected boolean detectSupportedFramework(ServletConfig sc) { Injector injector = (Injector) framework().getAtmosphereConfig().getServletContext().getAttribute(Injector.class.getName()); GuiceContainer guiceServlet = injector.getInstance(GuiceContainer.class); setUseStreamForFlushingComments(false); ReflectorServletProcessor rsp = new ReflectorServletProcessor(); boolean isJersey = false; try { Thread.currentThread().getContextClassLoader().loadClass(JERSEY_CONTAINER); setDefaultBroadcasterClassName(broadcasterClassName) .setUseStreamForFlushingComments(true) .getAtmosphereConfig().setSupportSession(false); isJersey = true; } catch (Throwable t) { } rsp.setServlet(guiceServlet); String mapping = sc.getInitParameter(ApplicationConfig.PROPERTY_SERVLET_MAPPING); if (mapping == null) { mapping = "/*"; } if (isJersey) { try { Map<String, String> props = injector.getInstance( Key.get(new TypeLiteral<Map<String, String>>() { }, Names.named(JERSEY_PROPERTIES))); if (props != null) { for (String p : props.keySet()) { framework().addInitParameter(p, props.get(p)); } } } catch (Exception ex) { // Do not fail logger.debug("failed to add Jersey init parameters to Atmosphere servlet", ex); } } addAtmosphereHandler(mapping, rsp); guiceInstalled = true; return true; } }; }
diff --git a/src/fr/esieaprojet/dao/DataBaseDal.java b/src/fr/esieaprojet/dao/DataBaseDal.java index bbe20b4..4cf61ed 100644 --- a/src/fr/esieaprojet/dao/DataBaseDal.java +++ b/src/fr/esieaprojet/dao/DataBaseDal.java @@ -1,415 +1,415 @@ package fr.esieaprojet.dao; import java.text.Normalizer; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.regex.Pattern; import fr.esieaprojet.business.Adress; import fr.esieaprojet.business.BillingAdress; import fr.esieaprojet.business.Contact; import fr.esieaprojet.business.DeliveryAdress; import fr.esieaprojet.service.IContactDao; public class DataBaseDal implements IContactDao { private HashMap<String, ArrayList<Contact>> db = new HashMap<String, ArrayList<Contact>>(); private ArrayList<Contact> users = new ArrayList<Contact>(); int count = 0; private static final Pattern ACCENTS_PATTERN = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); //first element of arraylist in db is the user contact himself public DataBaseDal() { Contact mainUser = new Contact(); mainUser.setActive(true); mainUser.setBirthday("22/07/1991"); mainUser.setMail("[email protected]"); mainUser.setPassword("Password0"); mainUser.setFirstName("Jean"); mainUser.setLastName("Paul"); Contact user1 = new Contact(); user1.setActive(true); user1.setBirthday("22/07/1991"); user1.setMail("[email protected]"); user1.setPassword("Password1"); user1.setFirstName("Patrick"); user1.setLastName("Ping"); Contact user2 = new Contact(); user2.setActive(true); user2.setBirthday("22/07/1991"); user2.setMail("[email protected]"); user2.setPassword("Password2"); user2.setFirstName("Fred"); user2.setLastName("Duval"); createContact(mainUser, "0"); createContact(user1, mainUser.getId()); createContact(user2, mainUser.getId()); } @Override public boolean createContact(Contact contact, String userId) { // TODO Auto-generated method stub if(userId.equals("0")) { ArrayList<Contact> contacts = new ArrayList<Contact>(); //contacts.add(contact); db.put(contact.getId(), contacts); users.add(contact); count++; System.out.println("create contact "+contact.getId()+" count = "+count); } else { ArrayList<Contact> values = db.get(userId); for(int i=0; i<values.size(); i++) { if( values.get(i).getId().equals(contact.getId()) ) return false; } values.add(contact); if(db.put(userId, values) == null) return false; System.out.println("num = "+db.keySet().size()); } return true; } @Override public boolean deleteContact(Contact contact, String userId) { // TODO Auto-generated method stub ArrayList<Contact> values = db.get(userId); for(int i=0; i<values.size(); i++) { if( values.get(i).getId().equals(contact.getId()) ) { values.remove(i); break; } if(i == values.size()-1) return false; } if(db.put(userId, values) == null) return false; return true; } @Override public Contact getContactByName(String firstName, String lastName, String userId) { // TODO Auto-generated method stub ArrayList<Contact> values = db.get(userId); for(int i=0; i<values.size(); i++) { if(values.get(i).getFirstName().equals(firstName) && values.get(i).getLastName().equals(lastName)) return values.get(i); } return null; } @Override public Contact getContactById(String id, String userId) { // TODO Auto-generated method stub ArrayList<Contact> values = db.get(userId); for(int i=0; i<values.size(); i++) { if(values.get(i).getId().equals(id)) return values.get(i); } return null; } @Override public Contact getContactByMail(String mail, String userId) { // TODO Auto-generated method stub ArrayList<Contact> values = db.get(userId); for(int i=0; i<values.size(); i++) { if(values.get(i).getMail().equals(mail)) return values.get(i); } return null; } @Override public List<Contact> getAllContactByString(String string, String userId) { // TODO Auto-generated method stub - System.out.println("search contact "+userId+" count = "+count+" string = "+string); + //System.out.println("search contact "+userId+" count = "+count+" string = "+string); ArrayList<Contact> values = db.get(userId); ArrayList<Contact> result = new ArrayList<Contact>(); boolean flag; if(values == null) System.out.println("search contact null "+userId+" count = "+count); for(int i=0; i<values.size(); i++) { Contact c = values.get(i); ArrayList<DeliveryAdress> list1 = c.getDeliveryAdresses(); BillingAdress bAdr = c.getBillingAdress(); flag = false; - System.out.println("last= "+c.getLastName()+" test = "+string); - if(search(c.getFirstName(), string) || search(c.getFirstName(), string) || search(c.getBirthday(), string) + //System.out.println("last= "+c.getLastName()+" test = "+string); + if(search(c.getFirstName(), string) || search(c.getLastName(), string) || search(c.getBirthday(), string) || (search(c.getActiveMessage(), string) && c.getActiveMessage().length() == string.length()) || search(c.getMail(), string)) { result.add(c); continue; } else if((list1 != null) && (bAdr != null) &&( search(bAdr.getCityName(), string) || search(bAdr.getPostalCode(), string) || search(bAdr.getStreetName(), string) || search(bAdr.getStreetNumber(), string))) { result.add(c); System.out.println("reussi2"); continue; } else if(list1 != null) { for(int j=0; j<list1.size() && !flag; j++) { DeliveryAdress da = list1.get(j); if(search(da.getCityName(), string) || search(da.getPostalCode(), string) || search(da.getStreetName(), string) || search(da.getStreetNumber(), string)) { result.add(c); System.out.println("reussi3"); flag = true; } } } } if(result.isEmpty()) return null; else return result; } /* @Override public List<Contact> getAllContactByString(String string, String userId) { // TODO Auto-generated method stub System.out.println("search contact "+userId+" count = "+count+" string = "+string); ArrayList<Contact> values = db.get(userId); ArrayList<Contact> result = new ArrayList<Contact>(); boolean flag; if(values == null) System.out.println("search contact null "+userId+" count = "+count); for(int i=0; i<values.size(); i++) { Contact c = values.get(i); ArrayList<DeliveryAdress> list1 = c.getDeliveryAdresses(); BillingAdress bAdr = c.getBillingAdress(); flag = false; System.out.println("last= "+c.getLastName()+" test = "+string); if((c.getFirstName()+" ").contains(string) || (c.getLastName()+" ").contains(string)) { result.add(c); continue; } else if((list1 != null) && (bAdr != null) &&((bAdr.getCityName()+" ").contains(string) || (bAdr.getPostalCode()+" ").contains(string) || (bAdr.getStreetName()+" ").contains(string) || (bAdr.getStreetNumber()+" ").contains(string))) { result.add(c); System.out.println("reussi2"); continue; } else if(list1 != null) { for(int j=0; j<list1.size() && !flag; j++) { DeliveryAdress da = list1.get(j); if((da.getCityName()+" ").contains(string) || (da.getPostalCode()+" ").contains(string) || (da.getStreetName()+" ").contains(string) || (da.getStreetNumber()+" ").contains(string)) { result.add(c); System.out.println("reussi3"); flag = true; } } } } if(result.isEmpty()) return null; else return result; } */ @Override public List<Contact> getAllContactByDate(String date, String userId) { // TODO Auto-generated method stub ArrayList<Contact> values = db.get(userId); ArrayList<Contact> result = new ArrayList<Contact>(); for(int i=0; i<values.size(); i++) { Contact c = values.get(i); if(new String(c.getBirthday()).equals(date)) result.add(c); } if(result.isEmpty()) return null; else return result; } @Override public boolean updateContact(Contact contact, String userId) { // TODO Auto-generated method stub if(userId.equals(contact.getId())) { System.out.println("test reussi"); for(int i=0; i<users.size(); i++) { if( users.get(i).getId().equals(contact.getId()) ) { users.remove(i); users.add(contact); return true; } if(i == users.size()-1) return false; } } else { ArrayList<Contact> values = db.get(userId); for(int i=0; i<values.size(); i++) { if( values.get(i).getId().equals(contact.getId()) ) { values.remove(i); break; } if(i == values.size()-1) return false; } values.add(contact); if(db.put(userId, values) == null) return false; } return true; } @Override public Contact getContact(String mail, String password) { // TODO Auto-generated method stub for(int i=0; i<users.size(); i++) { if( users.get(i).getMail().equals(mail) && users.get(i).getPassword().equals(password) ) return users.get(i); } return null; } @Override public Contact getContact(String id) { // TODO Auto-generated method stub for(int i=0; i<users.size(); i++) { if( users.get(i).getId().equals(id) ) return users.get(i); } return null; } @Override public List<Contact> getAllContact(String userId) { // TODO Auto-generated method stub System.out.println("get contact "+userId); ArrayList<Contact> values = db.get(userId); if(values == null) { System.out.println("null"); } ArrayList<Contact> result = new ArrayList<Contact>(); for(int i=0; i<values.size(); i++) { Contact c = values.get(i); result.add(c); } if(result.isEmpty()) return null; else return result; } public static boolean search(String haystack, String needle) { final String hsToCompare = removeAccents(haystack+" ").toLowerCase(); final String nToCompare = removeAccents(needle).toLowerCase(); return hsToCompare.contains(nToCompare); } public static String removeAccents(String string) { return ACCENTS_PATTERN.matcher(Normalizer.normalize(string, Normalizer.Form.NFD)).replaceAll(""); } }
false
true
public List<Contact> getAllContactByString(String string, String userId) { // TODO Auto-generated method stub System.out.println("search contact "+userId+" count = "+count+" string = "+string); ArrayList<Contact> values = db.get(userId); ArrayList<Contact> result = new ArrayList<Contact>(); boolean flag; if(values == null) System.out.println("search contact null "+userId+" count = "+count); for(int i=0; i<values.size(); i++) { Contact c = values.get(i); ArrayList<DeliveryAdress> list1 = c.getDeliveryAdresses(); BillingAdress bAdr = c.getBillingAdress(); flag = false; System.out.println("last= "+c.getLastName()+" test = "+string); if(search(c.getFirstName(), string) || search(c.getFirstName(), string) || search(c.getBirthday(), string) || (search(c.getActiveMessage(), string) && c.getActiveMessage().length() == string.length()) || search(c.getMail(), string)) { result.add(c); continue; } else if((list1 != null) && (bAdr != null) &&( search(bAdr.getCityName(), string) || search(bAdr.getPostalCode(), string) || search(bAdr.getStreetName(), string) || search(bAdr.getStreetNumber(), string))) { result.add(c); System.out.println("reussi2"); continue; } else if(list1 != null) { for(int j=0; j<list1.size() && !flag; j++) { DeliveryAdress da = list1.get(j); if(search(da.getCityName(), string) || search(da.getPostalCode(), string) || search(da.getStreetName(), string) || search(da.getStreetNumber(), string)) { result.add(c); System.out.println("reussi3"); flag = true; } } } } if(result.isEmpty()) return null; else return result; }
public List<Contact> getAllContactByString(String string, String userId) { // TODO Auto-generated method stub //System.out.println("search contact "+userId+" count = "+count+" string = "+string); ArrayList<Contact> values = db.get(userId); ArrayList<Contact> result = new ArrayList<Contact>(); boolean flag; if(values == null) System.out.println("search contact null "+userId+" count = "+count); for(int i=0; i<values.size(); i++) { Contact c = values.get(i); ArrayList<DeliveryAdress> list1 = c.getDeliveryAdresses(); BillingAdress bAdr = c.getBillingAdress(); flag = false; //System.out.println("last= "+c.getLastName()+" test = "+string); if(search(c.getFirstName(), string) || search(c.getLastName(), string) || search(c.getBirthday(), string) || (search(c.getActiveMessage(), string) && c.getActiveMessage().length() == string.length()) || search(c.getMail(), string)) { result.add(c); continue; } else if((list1 != null) && (bAdr != null) &&( search(bAdr.getCityName(), string) || search(bAdr.getPostalCode(), string) || search(bAdr.getStreetName(), string) || search(bAdr.getStreetNumber(), string))) { result.add(c); System.out.println("reussi2"); continue; } else if(list1 != null) { for(int j=0; j<list1.size() && !flag; j++) { DeliveryAdress da = list1.get(j); if(search(da.getCityName(), string) || search(da.getPostalCode(), string) || search(da.getStreetName(), string) || search(da.getStreetNumber(), string)) { result.add(c); System.out.println("reussi3"); flag = true; } } } } if(result.isEmpty()) return null; else return result; }
diff --git a/src/main/java/com/j256/ormlite/android/AndroidDatabaseConnection.java b/src/main/java/com/j256/ormlite/android/AndroidDatabaseConnection.java index b7dbf7a..b6a0e0d 100644 --- a/src/main/java/com/j256/ormlite/android/AndroidDatabaseConnection.java +++ b/src/main/java/com/j256/ormlite/android/AndroidDatabaseConnection.java @@ -1,251 +1,251 @@ package com.j256.ormlite.android; import java.sql.SQLException; import java.sql.Savepoint; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import com.j256.ormlite.field.FieldType; import com.j256.ormlite.misc.SqlExceptionUtil; import com.j256.ormlite.stmt.GenericRowMapper; import com.j256.ormlite.stmt.StatementBuilder.StatementType; import com.j256.ormlite.support.CompiledStatement; import com.j256.ormlite.support.DatabaseConnection; import com.j256.ormlite.support.GeneratedKeyHolder; /** * Database connection for Android. * * @author kevingalligan, graywatson */ public class AndroidDatabaseConnection implements DatabaseConnection { private final SQLiteDatabase db; private final boolean readWrite; public AndroidDatabaseConnection(SQLiteDatabase db, boolean readWrite) { this.db = db; this.readWrite = readWrite; } public boolean isAutoCommitSupported() { return false; } public boolean getAutoCommit() throws SQLException { try { // You have to explicitly commit your transactions, so this is sort of correct return !db.inTransaction(); } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems getting auto-commit from database", e); } } public void setAutoCommit(boolean autoCommit) { // always in auto-commit mode } public Savepoint setSavePoint(String name) throws SQLException { try { db.beginTransaction(); return null; } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems beginning transaction", e); } } /** * Return whether this connection is read-write or not (real-only). */ public boolean isReadWrite() { return readWrite; } public void commit(Savepoint savepoint) throws SQLException { try { db.setTransactionSuccessful(); db.endTransaction(); } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems commiting transaction", e); } } public void rollback(Savepoint savepoint) throws SQLException { try { // no setTransactionSuccessful() means it is a rollback db.endTransaction(); } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems rolling back transaction", e); } } public CompiledStatement compileStatement(String statement, StatementType type, FieldType[] argFieldTypes, FieldType[] resultFieldTypes) { CompiledStatement stmt = new AndroidCompiledStatement(statement, db, type); return stmt; } /** * Android doesn't return the number of rows inserted. */ public int insert(String statement, Object[] args, FieldType[] argFieldTypes) throws SQLException { return insert(statement, args, argFieldTypes, null); } public int insert(String statement, Object[] args, FieldType[] argFieldTypes, GeneratedKeyHolder keyHolder) throws SQLException { SQLiteStatement stmt = null; try { stmt = db.compileStatement(statement); bindArgs(stmt, args, argFieldTypes); long rowId = stmt.executeInsert(); if (keyHolder != null) { keyHolder.addKey(rowId); } return 1; } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("inserting to database failed: " + statement, e); } finally { if (stmt != null) { stmt.close(); } } } public int update(String statement, Object[] args, FieldType[] argFieldTypes) throws SQLException { SQLiteStatement stmt = null; try { stmt = db.compileStatement(statement); bindArgs(stmt, args, argFieldTypes); stmt.execute(); return 1; } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("updating database failed: " + statement, e); } finally { if (stmt != null) { stmt.close(); } } } public int delete(String statement, Object[] args, FieldType[] argFieldTypes) throws SQLException { // delete is the same as update return update(statement, args, argFieldTypes); } public <T> Object queryForOne(String statement, Object[] args, FieldType[] argFieldTypes, GenericRowMapper<T> rowMapper) throws SQLException { Cursor cursor = null; try { cursor = db.rawQuery(statement, toStrings(args)); AndroidDatabaseResults results = new AndroidDatabaseResults(cursor); if (!results.next()) { return null; } else { T first = rowMapper.mapRow(results); if (results.next()) { return MORE_THAN_ONE; } else { return first; } } } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("queryForOne from database failed: " + statement, e); } finally { if (cursor != null) { cursor.close(); } } } public long queryForLong(String statement) throws SQLException { SQLiteStatement stmt = null; try { stmt = db.compileStatement(statement); return stmt.simpleQueryForLong(); } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("queryForLong from database failed: " + statement, e); } finally { if (stmt != null) { stmt.close(); } } } public void close() throws SQLException { try { db.close(); } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems closing the database connection", e); } } public boolean isClosed() throws SQLException { try { return !db.isOpen(); } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems detecting if the database is closed", e); } } public boolean isTableExists(String tableName) throws SQLException { // NOTE: it is non trivial to do this check since the helper will auto-create if it doesn't exist return true; } private void bindArgs(SQLiteStatement stmt, Object[] args, FieldType[] argFieldTypes) throws SQLException { if (args == null) { return; } for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg == null) { - stmt.bindNull(i); + stmt.bindNull(i + 1); } else { switch (argFieldTypes[i].getSqlType()) { case STRING : case LONG_STRING : - stmt.bindString(i, arg.toString()); + stmt.bindString(i + 1, arg.toString()); break; case BOOLEAN : case BYTE : case SHORT : case INTEGER : case LONG : - stmt.bindLong(i, ((Number) arg).longValue()); + stmt.bindLong(i + 1, ((Number) arg).longValue()); break; case FLOAT : case DOUBLE : - stmt.bindDouble(i, ((Number) arg).doubleValue()); + stmt.bindDouble(i + 1, ((Number) arg).doubleValue()); break; case BYTE_ARRAY : case SERIALIZABLE : - stmt.bindBlob(i, (byte[]) arg); + stmt.bindBlob(i + 1, (byte[]) arg); break; default : throw new SQLException("Unknown sql argument type " + argFieldTypes[i].getSqlType()); } } } } private String[] toStrings(Object[] args) { if (args == null) { return null; } String[] strings = new String[args.length]; for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg == null) { strings[i] = null; } else { strings[i] = arg.toString(); } } return strings; } }
false
true
private void bindArgs(SQLiteStatement stmt, Object[] args, FieldType[] argFieldTypes) throws SQLException { if (args == null) { return; } for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg == null) { stmt.bindNull(i); } else { switch (argFieldTypes[i].getSqlType()) { case STRING : case LONG_STRING : stmt.bindString(i, arg.toString()); break; case BOOLEAN : case BYTE : case SHORT : case INTEGER : case LONG : stmt.bindLong(i, ((Number) arg).longValue()); break; case FLOAT : case DOUBLE : stmt.bindDouble(i, ((Number) arg).doubleValue()); break; case BYTE_ARRAY : case SERIALIZABLE : stmt.bindBlob(i, (byte[]) arg); break; default : throw new SQLException("Unknown sql argument type " + argFieldTypes[i].getSqlType()); } } } }
private void bindArgs(SQLiteStatement stmt, Object[] args, FieldType[] argFieldTypes) throws SQLException { if (args == null) { return; } for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg == null) { stmt.bindNull(i + 1); } else { switch (argFieldTypes[i].getSqlType()) { case STRING : case LONG_STRING : stmt.bindString(i + 1, arg.toString()); break; case BOOLEAN : case BYTE : case SHORT : case INTEGER : case LONG : stmt.bindLong(i + 1, ((Number) arg).longValue()); break; case FLOAT : case DOUBLE : stmt.bindDouble(i + 1, ((Number) arg).doubleValue()); break; case BYTE_ARRAY : case SERIALIZABLE : stmt.bindBlob(i + 1, (byte[]) arg); break; default : throw new SQLException("Unknown sql argument type " + argFieldTypes[i].getSqlType()); } } } }
diff --git a/thud/btthud/data/MUUnitInfo.java b/thud/btthud/data/MUUnitInfo.java index aef4668..6bddf1d 100644 --- a/thud/btthud/data/MUUnitInfo.java +++ b/thud/btthud/data/MUUnitInfo.java @@ -1,811 +1,811 @@ // // MUUnitInfo.java // Thud // // Created by asp on Tue Nov 20 2001. // Copyright (c) 2001-2002 Anthony Parker. All rights reserved. // Please see LICENSE.TXT for more information. // // package btthud.data; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.font.*; import java.awt.image.*; import javax.swing.*; import javax.swing.text.*; import java.lang.*; import java.util.*; import java.awt.geom.*; import java.awt.image.*; /** * This class is for storing all the information about a single unit (typically a contact, enemy or friendly). * * @author Anthony Parker * @version 1.0, 11.20.01 */ public class MUUnitInfo extends Object implements Comparable { public boolean friend = false; public boolean target = false; public String type = null; public String team = null; public String id = null; public String name = " "; public String arc = null; public String status = " "; public float range, speed, verticalSpeed; public int x, y, z; public int heading, bearing, jumpHeading; public float rangeToCenter; public int bearingToCenter; public int weight; public int apparentHeat; public boolean jumping = false; public boolean primarySensor = false, secondarySensor = false; int expired = 5; static final int oldThreshold = 3; static public MUWeapon weapons[] = new MUWeapon[200]; // data that stores info on /all/ weapons ... assume 200 of them for now Font font = new Font("Monospaced", Font.BOLD, 10); // used for drawing armor FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true); // ------------------ static final int NO_SECTION = 0; static final int A = 1; static final int AS = 2; static final int C = 3; static final int CT = 4; static final int CTr = 5; static final int E = 6; static final int F = 7; static final int FLLr = 8; static final int FLS = 9; static final int FRLr = 10; static final int FRS = 11; static final int FS = 12; static final int H = 13; static final int Hr = 14; static final int LA = 15; static final int LAr = 16; static final int LL = 17; static final int LLr = 18; static final int LRW = 19; static final int LS = 20; static final int LT = 21; static final int LTr = 22; static final int LW = 23; static final int N = 24; static final int R = 25; static final int RA = 26; static final int RAr = 27; static final int RL = 28; static final int RLr = 29; static final int RLS = 30; static final int RRS = 31; static final int RRW = 32; static final int RS = 33; static final int RT = 34; static final int RTr = 35; static final int RW = 36; static final int S1 = 37; static final int S2 = 38; static final int S3 = 39; static final int S4 = 40; static final int S5 = 41; static final int S6 = 42; static final int S7 = 43; static final int S8 = 44; static final int T = 45; static final int TOTAL_SECTIONS = 46; static final int TYPE_UNKNOWN = 0; static final int BIPED = 1; static final int HOVER = 2; static final int TRACKED = 3; static final int WHEELED = 4; static final int NAVAL_SURFACE = 5; static final int NAVAL_HYDROFOIL = 6; static final int NAVAL_SUBMARINE = 7; static final int VTOL = 8; static final int AEROFIGHTER = 9; static final int AERODYNE_DS = 10; static final int SPHEROID_DS = 11; static final int BATTLESUIT = 12; static final int INFANTRY = 13; static final int INSTALLATION = 14; static final int TOTAL_MOVETYPES = 15; // -------------------------- public MUUnitInfo() { } public String toString() { String out = new String("\nMUUnitInfo: "); return (out + "ID:" + id + " Team:" + team + " Type:" + type + " Name:" + name + " Range:" + String.valueOf(range) + " Speed:" + String.valueOf(speed) + " XYZ:" + String.valueOf(x) + "," + String.valueOf(y) + "," + String.valueOf(z) + " Heading:" + String.valueOf(heading) + " Bearing:" + String.valueOf(bearing) + " RTC:" + String.valueOf(rangeToCenter) + " BTC:" + String.valueOf(bearingToCenter) + " Friend:" + String.valueOf(friend)); } public boolean isExpired() { if (expired <= 0) return true; else return false; } public boolean isOld() { if (expired <= oldThreshold) return true; else return false; } public boolean isFriend() { return friend; } public boolean isTarget() { return target; } public void expireMore() { expired--; } /** * Make a human-readable contact string, similar to standard .c for display */ public String makeContactString() { /* Example: PSl[cm]B Mi Swayback x: 40 y: 38 z: 0 r: 6.3 b:169 s: 0.0 h:180 S:F */ StringBuffer sb = new StringBuffer(); sb.append(primarySensor ? "P" : " "); sb.append(secondarySensor ? "S" : " "); sb.append(arc); sb.append("[" + id + "]"); sb.append(type); sb.append(" "); sb.append(leftJust(name, 12, true)); sb.append(" "); sb.append("x:" + rightJust(String.valueOf(x), 3, false) + " "); sb.append("y:" + rightJust(String.valueOf(y), 3, false) + " "); sb.append("z:" + rightJust(String.valueOf(z), 3, false) + " "); sb.append("r:" + rightJust(String.valueOf(range), 4, true) + " "); sb.append("b:" + rightJust(String.valueOf(bearing), 3, false) + " "); sb.append("s:" + rightJust(String.valueOf(speed), 5, true) + " "); sb.append("h:" + rightJust(String.valueOf(heading), 3, false) + " "); sb.append("S:" + status); return sb.toString(); /* return (primarySensor ? "P" : " ") + (secondarySensor ? "S" : " ") + arc + "[" + id + "]" + type + " " + team + " " + name + " " + "x: " + x + " y: " + y + " z: " + z + " r: " + range + " b: " + bearing + " s: " + speed + " h:" + heading + " S:" + flags; */ } public String leftJust(String l, int w, boolean trunc) { if (l.length() < w) { // Need to add spaces to the end StringBuffer sb = new StringBuffer(l); for (int i = 0; i < w - l.length(); i++) sb.append(" "); return sb.toString(); } else if (l.length() == w) { // Leave it the way it is return l; } else { // Choice here: truncate the string or leave the way it is if (trunc) { return l.substring(0, w); } else { return l; } } } public String rightJust(String l, int w, boolean trunc) { if (l.length() < w) { // Need to add spaces to the beginning StringBuffer sb = new StringBuffer(l); for (int i = 0; i < w - l.length(); i++) sb.insert(0, " "); return sb.toString(); } else if (l.length() == w) { // Leave it the way it is return l; } else { // Choice here: truncate the string or leave the way it is if (trunc) { return l.substring(0, w); } else { return l; } } } /** This implements Comparable * Right now we sort based on range, for easy contact lists. * Destroyed units should come last. */ public int compareTo(Object o2) { //if (isDestroyed()) // return -1; if (range < ((MUUnitInfo) o2).range) return 1; else if (range > ((MUUnitInfo) o2).range) return -1; else { // We don't want to return 0 unless they are exactly the same unit. Otherwise, it doesn't matter which is first return id.compareTo(((MUUnitInfo) o2).id); } } /** * Determine if the unit is destroyed or not */ public boolean isDestroyed() { return stringHasCharacter(status, 'D'); } /** * Determine if the unit is fallen or not */ public boolean isFallen() { return (stringHasCharacter(status, 'F') || stringHasCharacter(status, 'f')); } /** * Determine if a specific character is in this string */ public boolean stringHasCharacter(String s, char c) { if (s == null) return false; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == c) return true; } return false; } /** * Return an efficient hash code */ public int hashCode() { // Use the hash code for the id // This uses exponents and is probably grossly inefficient, but it'll do for now return id.hashCode(); } /*********************************************************************/ /** * Returns a BufferedImage which represents this particular unit. * @param h The height of the icon (not neccesarily the height of a hex) * @param drawArmor If true, draw any known armor information for this unit * @param color What color to draw this unit */ public GeneralPath icon(int h, boolean drawArmor, Color color) { // We do everything on a scale of 20 pixels. We scale up the path later if the height is > 20. //BufferedImage unitImage = new BufferedImage(h, h, BufferedImage.TYPE_INT_ARGB); GeneralPath unitOutline = new GeneralPath(); AffineTransform xform = new AffineTransform(); /* Graphics2D g = (Graphics2D) unitImage.getGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fill(new Rectangle(0, 0, h, h)); */ switch (type.charAt(0)) { case 'B': // Biped unitOutline.moveTo(8, 0); unitOutline.lineTo(8, 3); unitOutline.lineTo(5, 3); unitOutline.lineTo(1, 8); unitOutline.lineTo(4, 10); unitOutline.lineTo(6, 7); unitOutline.lineTo(7, 12); unitOutline.lineTo(4, 20); unitOutline.lineTo(8, 20); unitOutline.lineTo(10, 13); unitOutline.lineTo(12, 20); unitOutline.lineTo(16, 20); unitOutline.lineTo(13, 12); unitOutline.lineTo(14, 7); unitOutline.lineTo(16, 10); unitOutline.lineTo(19, 8); unitOutline.lineTo(15, 3); unitOutline.lineTo(12, 3); unitOutline.lineTo(12, 0); unitOutline.lineTo(8, 0); break; case 'Q': unitOutline.moveTo(8, 7); unitOutline.lineTo(8, 10); unitOutline.lineTo(5, 10); unitOutline.lineTo(3, 8); unitOutline.lineTo(1, 8); unitOutline.lineTo(2, 20); unitOutline.lineTo(4, 20); unitOutline.lineTo(3, 12); unitOutline.moveTo(4, 13); unitOutline.lineTo(6, 20); unitOutline.lineTo(8, 20); unitOutline.lineTo(6, 13); unitOutline.moveTo(7, 14); unitOutline.lineTo(13, 14); unitOutline.moveTo(14, 13); unitOutline.lineTo(12, 20); unitOutline.lineTo(14, 20); unitOutline.lineTo(16, 13); unitOutline.moveTo(17, 12); unitOutline.lineTo(16, 20); unitOutline.lineTo(18, 20); unitOutline.lineTo(19, 8); unitOutline.lineTo(17, 8); unitOutline.lineTo(15, 10); unitOutline.lineTo(12, 10); unitOutline.lineTo(12, 7); unitOutline.lineTo(8, 7); break; case 'H': case 'T': case 'W': unitOutline.moveTo(5, 2); unitOutline.lineTo(3, 5); unitOutline.lineTo(3, 15); unitOutline.lineTo(5, 18); unitOutline.lineTo(15, 18); unitOutline.lineTo(17, 15); unitOutline.lineTo(17, 5); unitOutline.lineTo(15, 2); unitOutline.lineTo(5, 2); // Should check to see if there is a turret here before we go around drawing it unitOutline.moveTo(8, 10); unitOutline.lineTo(8, 14); unitOutline.lineTo(12, 14); unitOutline.lineTo(12, 10); unitOutline.lineTo(8, 10); // Maybe rotate this according to turret heading? unitOutline.moveTo((float) 9.5, 10); unitOutline.lineTo((float) 9.5, 6); unitOutline.lineTo((float) 10.5, 6); unitOutline.lineTo((float) 10.5, 10); break; case 'N': - break;; + break; case 'Y': break; case 'U': break; case 'V': unitOutline.moveTo(8, 2); unitOutline.lineTo(7, 3); unitOutline.lineTo(7, 10); unitOutline.lineTo(9, 13); unitOutline.lineTo(9, 18); unitOutline.lineTo(8, 18); unitOutline.lineTo(8, 19); unitOutline.lineTo(12, 19); unitOutline.lineTo(12, 18); unitOutline.lineTo(11, 18); unitOutline.lineTo(11, 13); unitOutline.lineTo(13, 10); unitOutline.lineTo(13, 3); unitOutline.lineTo(12, 2); unitOutline.lineTo(8, 2); unitOutline.moveTo(2, 6); unitOutline.lineTo(2, 7); unitOutline.lineTo(9, 7); unitOutline.lineTo(9, 8); unitOutline.lineTo(11, 8); unitOutline.lineTo(11, 7); unitOutline.lineTo(18, 7); unitOutline.lineTo(18, 6); unitOutline.lineTo(11, 6); unitOutline.lineTo(11, 5); unitOutline.lineTo(9, 5); unitOutline.lineTo(9, 6); unitOutline.lineTo(2, 6); break; case 'F': break; case 'A': break; case 'D': unitOutline.moveTo(5, 1); unitOutline.lineTo(1, 5); unitOutline.lineTo(1, 15); unitOutline.lineTo(5, 19); unitOutline.lineTo(15, 19); unitOutline.lineTo(19, 15); unitOutline.lineTo(19, 5); unitOutline.lineTo(15, 1); unitOutline.lineTo(5, 1); // We scale because dropships are big. :) if (!drawArmor) xform.scale(h / 4.0, h / 4.0); break; case 'S': break; case 'I': break; case 'i': unitOutline.moveTo(4, 4); unitOutline.lineTo(2, 19); unitOutline.lineTo(18, 19); unitOutline.lineTo(16, 4); unitOutline.lineTo(4, 4); unitOutline.moveTo(5, 6); unitOutline.lineTo(5, 8); unitOutline.lineTo(15, 8); unitOutline.lineTo(15, 6); unitOutline.lineTo(5, 6); break; default: unitOutline.moveTo(7, 7); unitOutline.lineTo(7, 13); unitOutline.lineTo(13, 13); unitOutline.lineTo(13, 7); unitOutline.lineTo(7, 7); break; } // Draw the unit // only rotate if it's a 'Mech, fallen, and not for the status display if (type.charAt(0) == 'B' && isFallen() && !drawArmor) xform.rotate(Math.PI / 2, 10, 10); xform.scale((float) h / 20.0, (float) h / 20.0); //xform.translate(-10, -10); unitOutline.transform(xform); /* g.setColor(color); g.setTransform(new AffineTransform()); // reset the transform g.draw(unitOutline); return unitImage; */ return unitOutline; } /** * Returns true if this unit has the possibility of having a turret (note: doesnt' check to see if it actually does have one) */ public boolean canHaveTurret() { int mType = movementForType(type); if (mType == HOVER || mType == TRACKED || mType == WHEELED || mType == NAVAL_SURFACE) return true; else return false; } /***************************************************************************/ // Static methods /** * Return a color for displaying an armor percentage (green is minty, etc). */ static public Color colorForPercent(float p) { if (p >= 99) return new Color(0, 200, 0); // Bright green else if (p > 60) return new Color(0, 150, 0); // Darker green else if (p > 40) return new Color(150, 150, 0); // Darker yellow else if (p > 20) return new Color(200, 200, 0); // Bright yellow else return new Color(200, 0, 0); // Bright red } /** * Return a constant representing our movement type */ static public int movementForType(String s) { if (s.equals("B")) return BIPED; if (s.equals("H")) return HOVER; if (s.equals("T")) return TRACKED; if (s.equals("W")) return WHEELED; if (s.equals("N")) return NAVAL_SURFACE; if (s.equals("Y")) return NAVAL_HYDROFOIL; if (s.equals("U")) return NAVAL_SUBMARINE; if (s.equals("F")) return AEROFIGHTER; if (s.equals("A")) return AERODYNE_DS; if (s.equals("D")) return SPHEROID_DS; if (s.equals("S")) return SPHEROID_DS; if (s.equals("I")) return INFANTRY; if (s.equals("i")) return INSTALLATION; return TYPE_UNKNOWN; } /** * Return the index in an array for a specific section. * @param s A string representation of the section we're looking for. */ static public int indexForSection(String s) { // TODO: Rearrange so most commonly used are at top if (s.equals("A")) return A; if (s.equals("AS")) return AS; if (s.equals("C")) return C; if (s.equals("CT")) return CT; if (s.equals("CTr")) return CTr; if (s.equals("E")) return E; if (s.equals("F")) return F; if (s.equals("FLLr")) return FLLr; if (s.equals("FLS")) return FLS; if (s.equals("FRLr")) return FRLr; if (s.equals("FRS")) return FRS; if (s.equals("FS")) return FS; if (s.equals("H")) return H; if (s.equals("Hr")) return Hr; if (s.equals("LA")) return LA; if (s.equals("LAr")) return LAr; if (s.equals("LL")) return LL; if (s.equals("LLr")) return LLr; if (s.equals("LRW")) return LRW; if (s.equals("LS")) return LS; if (s.equals("LT")) return LT; if (s.equals("LTr")) return LTr; if (s.equals("LW")) return LW; if (s.equals("N")) return N; if (s.equals("R")) return R; if (s.equals("RA")) return RA; if (s.equals("RAr")) return RAr; if (s.equals("RL")) return RL; if (s.equals("RLr")) return RLr; if (s.equals("RLS")) return RLS; if (s.equals("RRS")) return RRS; if (s.equals("RRW")) return RRW; if (s.equals("RS")) return RS; if (s.equals("RT")) return RT; if (s.equals("RTr")) return RTr; if (s.equals("RW")) return RW; if (s.equals("S1")) return S1; if (s.equals("S2")) return S2; if (s.equals("S3")) return S3; if (s.equals("S4")) return S4; if (s.equals("S5")) return S5; if (s.equals("S6")) return S6; if (s.equals("S7")) return S7; if (s.equals("S8")) return S8; if (s.equals("T")) return T; // Default return NO_SECTION; } /** * Returns true if the weapon can be considered in the 'front' Arc * Only good for 'Mechs and Tanks at the moment */ static public boolean isInFrontArc(int sNum) { if (sNum == H || sNum == LA || sNum == LT || sNum == CT || sNum == RT || sNum == RA || sNum == LL || sNum == RL || sNum == FS) return true; else return false; } /** * Returns true if the weapon can be considered in the 'front' Arc * Only good for Tanks at the moment */ static public boolean isInTurretArc(int sNum) { if (sNum == T) return true; else return false; } /** * Returns true if the weapon can be considered in the left Arc * Only good for 'Mechs and Tanks at the moment */ static public boolean isInLeftArc(int sNum) { if (sNum == LA || sNum == LS) return true; else return false; } /** * Returns true if the weapon can be considered in the right Arc * Only good for 'Mechs and Tanks at the moment */ static public boolean isInRightArc(int sNum) { if (sNum == RA || sNum == RS) return true; else return false; } /** * Returns true if the weapon can be considered in the rear or aft Arc * Only good for 'Mechs and Tanks at the moment */ static public boolean isInRearArc(int sNum) { if (sNum == Hr || sNum == LAr || sNum == LTr || sNum == CTr || sNum == RTr || sNum == RAr || sNum == LLr || sNum == RLr || sNum == AS) return true; else return false; } /** * Adds a new weapon to our list of weapons, or updates an existing one */ static public void newWeapon(MUWeapon w) { try { weapons[w.typeNumber] = w; } catch (Exception e) { System.out.println("Error: newWeapon: " + e); } } /** * Gets a weapon based on its weapon number */ static public MUWeapon getWeapon(int number) { try { return weapons[number]; } catch (Exception e) { System.out.println("Error: getWeapon: " + e); return null; } } }
true
true
public GeneralPath icon(int h, boolean drawArmor, Color color) { // We do everything on a scale of 20 pixels. We scale up the path later if the height is > 20. //BufferedImage unitImage = new BufferedImage(h, h, BufferedImage.TYPE_INT_ARGB); GeneralPath unitOutline = new GeneralPath(); AffineTransform xform = new AffineTransform(); /* Graphics2D g = (Graphics2D) unitImage.getGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fill(new Rectangle(0, 0, h, h)); */ switch (type.charAt(0)) { case 'B': // Biped unitOutline.moveTo(8, 0); unitOutline.lineTo(8, 3); unitOutline.lineTo(5, 3); unitOutline.lineTo(1, 8); unitOutline.lineTo(4, 10); unitOutline.lineTo(6, 7); unitOutline.lineTo(7, 12); unitOutline.lineTo(4, 20); unitOutline.lineTo(8, 20); unitOutline.lineTo(10, 13); unitOutline.lineTo(12, 20); unitOutline.lineTo(16, 20); unitOutline.lineTo(13, 12); unitOutline.lineTo(14, 7); unitOutline.lineTo(16, 10); unitOutline.lineTo(19, 8); unitOutline.lineTo(15, 3); unitOutline.lineTo(12, 3); unitOutline.lineTo(12, 0); unitOutline.lineTo(8, 0); break; case 'Q': unitOutline.moveTo(8, 7); unitOutline.lineTo(8, 10); unitOutline.lineTo(5, 10); unitOutline.lineTo(3, 8); unitOutline.lineTo(1, 8); unitOutline.lineTo(2, 20); unitOutline.lineTo(4, 20); unitOutline.lineTo(3, 12); unitOutline.moveTo(4, 13); unitOutline.lineTo(6, 20); unitOutline.lineTo(8, 20); unitOutline.lineTo(6, 13); unitOutline.moveTo(7, 14); unitOutline.lineTo(13, 14); unitOutline.moveTo(14, 13); unitOutline.lineTo(12, 20); unitOutline.lineTo(14, 20); unitOutline.lineTo(16, 13); unitOutline.moveTo(17, 12); unitOutline.lineTo(16, 20); unitOutline.lineTo(18, 20); unitOutline.lineTo(19, 8); unitOutline.lineTo(17, 8); unitOutline.lineTo(15, 10); unitOutline.lineTo(12, 10); unitOutline.lineTo(12, 7); unitOutline.lineTo(8, 7); break; case 'H': case 'T': case 'W': unitOutline.moveTo(5, 2); unitOutline.lineTo(3, 5); unitOutline.lineTo(3, 15); unitOutline.lineTo(5, 18); unitOutline.lineTo(15, 18); unitOutline.lineTo(17, 15); unitOutline.lineTo(17, 5); unitOutline.lineTo(15, 2); unitOutline.lineTo(5, 2); // Should check to see if there is a turret here before we go around drawing it unitOutline.moveTo(8, 10); unitOutline.lineTo(8, 14); unitOutline.lineTo(12, 14); unitOutline.lineTo(12, 10); unitOutline.lineTo(8, 10); // Maybe rotate this according to turret heading? unitOutline.moveTo((float) 9.5, 10); unitOutline.lineTo((float) 9.5, 6); unitOutline.lineTo((float) 10.5, 6); unitOutline.lineTo((float) 10.5, 10); break; case 'N': break;; case 'Y': break; case 'U': break; case 'V': unitOutline.moveTo(8, 2); unitOutline.lineTo(7, 3); unitOutline.lineTo(7, 10); unitOutline.lineTo(9, 13); unitOutline.lineTo(9, 18); unitOutline.lineTo(8, 18); unitOutline.lineTo(8, 19); unitOutline.lineTo(12, 19); unitOutline.lineTo(12, 18); unitOutline.lineTo(11, 18); unitOutline.lineTo(11, 13); unitOutline.lineTo(13, 10); unitOutline.lineTo(13, 3); unitOutline.lineTo(12, 2); unitOutline.lineTo(8, 2); unitOutline.moveTo(2, 6); unitOutline.lineTo(2, 7); unitOutline.lineTo(9, 7); unitOutline.lineTo(9, 8); unitOutline.lineTo(11, 8); unitOutline.lineTo(11, 7); unitOutline.lineTo(18, 7); unitOutline.lineTo(18, 6); unitOutline.lineTo(11, 6); unitOutline.lineTo(11, 5); unitOutline.lineTo(9, 5); unitOutline.lineTo(9, 6); unitOutline.lineTo(2, 6); break; case 'F': break; case 'A': break; case 'D': unitOutline.moveTo(5, 1); unitOutline.lineTo(1, 5); unitOutline.lineTo(1, 15); unitOutline.lineTo(5, 19); unitOutline.lineTo(15, 19); unitOutline.lineTo(19, 15); unitOutline.lineTo(19, 5); unitOutline.lineTo(15, 1); unitOutline.lineTo(5, 1); // We scale because dropships are big. :) if (!drawArmor) xform.scale(h / 4.0, h / 4.0); break; case 'S': break; case 'I': break; case 'i': unitOutline.moveTo(4, 4); unitOutline.lineTo(2, 19); unitOutline.lineTo(18, 19); unitOutline.lineTo(16, 4); unitOutline.lineTo(4, 4); unitOutline.moveTo(5, 6); unitOutline.lineTo(5, 8); unitOutline.lineTo(15, 8); unitOutline.lineTo(15, 6); unitOutline.lineTo(5, 6); break; default: unitOutline.moveTo(7, 7); unitOutline.lineTo(7, 13); unitOutline.lineTo(13, 13); unitOutline.lineTo(13, 7); unitOutline.lineTo(7, 7); break; } // Draw the unit // only rotate if it's a 'Mech, fallen, and not for the status display if (type.charAt(0) == 'B' && isFallen() && !drawArmor) xform.rotate(Math.PI / 2, 10, 10); xform.scale((float) h / 20.0, (float) h / 20.0); //xform.translate(-10, -10); unitOutline.transform(xform); /* g.setColor(color); g.setTransform(new AffineTransform()); // reset the transform g.draw(unitOutline); return unitImage; */ return unitOutline; }
public GeneralPath icon(int h, boolean drawArmor, Color color) { // We do everything on a scale of 20 pixels. We scale up the path later if the height is > 20. //BufferedImage unitImage = new BufferedImage(h, h, BufferedImage.TYPE_INT_ARGB); GeneralPath unitOutline = new GeneralPath(); AffineTransform xform = new AffineTransform(); /* Graphics2D g = (Graphics2D) unitImage.getGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fill(new Rectangle(0, 0, h, h)); */ switch (type.charAt(0)) { case 'B': // Biped unitOutline.moveTo(8, 0); unitOutline.lineTo(8, 3); unitOutline.lineTo(5, 3); unitOutline.lineTo(1, 8); unitOutline.lineTo(4, 10); unitOutline.lineTo(6, 7); unitOutline.lineTo(7, 12); unitOutline.lineTo(4, 20); unitOutline.lineTo(8, 20); unitOutline.lineTo(10, 13); unitOutline.lineTo(12, 20); unitOutline.lineTo(16, 20); unitOutline.lineTo(13, 12); unitOutline.lineTo(14, 7); unitOutline.lineTo(16, 10); unitOutline.lineTo(19, 8); unitOutline.lineTo(15, 3); unitOutline.lineTo(12, 3); unitOutline.lineTo(12, 0); unitOutline.lineTo(8, 0); break; case 'Q': unitOutline.moveTo(8, 7); unitOutline.lineTo(8, 10); unitOutline.lineTo(5, 10); unitOutline.lineTo(3, 8); unitOutline.lineTo(1, 8); unitOutline.lineTo(2, 20); unitOutline.lineTo(4, 20); unitOutline.lineTo(3, 12); unitOutline.moveTo(4, 13); unitOutline.lineTo(6, 20); unitOutline.lineTo(8, 20); unitOutline.lineTo(6, 13); unitOutline.moveTo(7, 14); unitOutline.lineTo(13, 14); unitOutline.moveTo(14, 13); unitOutline.lineTo(12, 20); unitOutline.lineTo(14, 20); unitOutline.lineTo(16, 13); unitOutline.moveTo(17, 12); unitOutline.lineTo(16, 20); unitOutline.lineTo(18, 20); unitOutline.lineTo(19, 8); unitOutline.lineTo(17, 8); unitOutline.lineTo(15, 10); unitOutline.lineTo(12, 10); unitOutline.lineTo(12, 7); unitOutline.lineTo(8, 7); break; case 'H': case 'T': case 'W': unitOutline.moveTo(5, 2); unitOutline.lineTo(3, 5); unitOutline.lineTo(3, 15); unitOutline.lineTo(5, 18); unitOutline.lineTo(15, 18); unitOutline.lineTo(17, 15); unitOutline.lineTo(17, 5); unitOutline.lineTo(15, 2); unitOutline.lineTo(5, 2); // Should check to see if there is a turret here before we go around drawing it unitOutline.moveTo(8, 10); unitOutline.lineTo(8, 14); unitOutline.lineTo(12, 14); unitOutline.lineTo(12, 10); unitOutline.lineTo(8, 10); // Maybe rotate this according to turret heading? unitOutline.moveTo((float) 9.5, 10); unitOutline.lineTo((float) 9.5, 6); unitOutline.lineTo((float) 10.5, 6); unitOutline.lineTo((float) 10.5, 10); break; case 'N': break; case 'Y': break; case 'U': break; case 'V': unitOutline.moveTo(8, 2); unitOutline.lineTo(7, 3); unitOutline.lineTo(7, 10); unitOutline.lineTo(9, 13); unitOutline.lineTo(9, 18); unitOutline.lineTo(8, 18); unitOutline.lineTo(8, 19); unitOutline.lineTo(12, 19); unitOutline.lineTo(12, 18); unitOutline.lineTo(11, 18); unitOutline.lineTo(11, 13); unitOutline.lineTo(13, 10); unitOutline.lineTo(13, 3); unitOutline.lineTo(12, 2); unitOutline.lineTo(8, 2); unitOutline.moveTo(2, 6); unitOutline.lineTo(2, 7); unitOutline.lineTo(9, 7); unitOutline.lineTo(9, 8); unitOutline.lineTo(11, 8); unitOutline.lineTo(11, 7); unitOutline.lineTo(18, 7); unitOutline.lineTo(18, 6); unitOutline.lineTo(11, 6); unitOutline.lineTo(11, 5); unitOutline.lineTo(9, 5); unitOutline.lineTo(9, 6); unitOutline.lineTo(2, 6); break; case 'F': break; case 'A': break; case 'D': unitOutline.moveTo(5, 1); unitOutline.lineTo(1, 5); unitOutline.lineTo(1, 15); unitOutline.lineTo(5, 19); unitOutline.lineTo(15, 19); unitOutline.lineTo(19, 15); unitOutline.lineTo(19, 5); unitOutline.lineTo(15, 1); unitOutline.lineTo(5, 1); // We scale because dropships are big. :) if (!drawArmor) xform.scale(h / 4.0, h / 4.0); break; case 'S': break; case 'I': break; case 'i': unitOutline.moveTo(4, 4); unitOutline.lineTo(2, 19); unitOutline.lineTo(18, 19); unitOutline.lineTo(16, 4); unitOutline.lineTo(4, 4); unitOutline.moveTo(5, 6); unitOutline.lineTo(5, 8); unitOutline.lineTo(15, 8); unitOutline.lineTo(15, 6); unitOutline.lineTo(5, 6); break; default: unitOutline.moveTo(7, 7); unitOutline.lineTo(7, 13); unitOutline.lineTo(13, 13); unitOutline.lineTo(13, 7); unitOutline.lineTo(7, 7); break; } // Draw the unit // only rotate if it's a 'Mech, fallen, and not for the status display if (type.charAt(0) == 'B' && isFallen() && !drawArmor) xform.rotate(Math.PI / 2, 10, 10); xform.scale((float) h / 20.0, (float) h / 20.0); //xform.translate(-10, -10); unitOutline.transform(xform); /* g.setColor(color); g.setTransform(new AffineTransform()); // reset the transform g.draw(unitOutline); return unitImage; */ return unitOutline; }
diff --git a/perpus-app-ui/src/main/java/perpus/service/ReportServiceImpl.java b/perpus-app-ui/src/main/java/perpus/service/ReportServiceImpl.java index 1a2213b..e8b595a 100644 --- a/perpus-app-ui/src/main/java/perpus/service/ReportServiceImpl.java +++ b/perpus-app-ui/src/main/java/perpus/service/ReportServiceImpl.java @@ -1,113 +1,113 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package perpus.service; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import org.hibernate.SessionFactory; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import perpus.domain.LaporanPeminjamanDto; import perpus.domain.PeminjamanDetail; import perpus.domain.PengembalianDetail; /** * * @author adi */ @Service("reportService") public class ReportServiceImpl implements ReportService{ @Autowired private SessionFactory sessionFactory; @Autowired private TransaksiService transaksiService; public List<LaporanPeminjamanDto> dataLaporanPeminjaman(String mode, Date mulai, Date sampai){ List<LaporanPeminjamanDto> result = new ArrayList<LaporanPeminjamanDto>(); if(mode.equalsIgnoreCase("PEMINJAMAN")){ List<PeminjamanDetail> detailPeminjamans = transaksiService.getTransaksiBelumKembali(mulai, sampai); for(PeminjamanDetail p : detailPeminjamans){ PengembalianDetail kembali = transaksiService.getPengembalianByIdPinjamAndKodeBuku( p.getHeader().getId(), p.getBuku().getId()); LaporanPeminjamanDto lpd = new LaporanPeminjamanDto(); - lpd.setId(p.getId().toString()); + lpd.setId(p.getHeader().getId().toString()); lpd.setKodeAnggota(p.getHeader().getAnggota().getKodeAnggota()); lpd.setNamaAnggota(p.getHeader().getAnggota().getNamaAnggota()); lpd.setTglPinjam(p.getHeader().getTglPinjam()); lpd.setTglKembali(p.getHeader().getTglKembali()); lpd.setKodeBuku(p.getBuku().getKodeBuku()); lpd.setJudul(p.getBuku().getJudulBuku()); if(kembali != null){ lpd.setTglKembaliSebenarnya(new DateTime(lpd.getTglKembali()) .plusDays(kembali.getTelat()).toDate()); lpd.setTelat(kembali.getTelat()); lpd.setDenda(kembali.getDenda()); lpd.setStatus("Sudah Kembali"); } else { lpd.setStatus("Belum Kembali"); } result.add(lpd); } } else { List<PengembalianDetail> detailpengembalians = transaksiService.getTransaksiPengembalian(mulai, sampai); for (PengembalianDetail p : detailpengembalians) { LaporanPeminjamanDto lpd = new LaporanPeminjamanDto(); - lpd.setId(p.getId().toString()); + lpd.setId(p.getHeader().getId().toString()); lpd.setKodeAnggota(p.getHeader().getTransaksiPeminjaman().getAnggota().getKodeAnggota()); lpd.setNamaAnggota(p.getHeader().getTransaksiPeminjaman().getAnggota().getNamaAnggota()); lpd.setTglPinjam(p.getHeader().getTransaksiPeminjaman().getTglPinjam()); lpd.setTglKembali(p.getHeader().getTransaksiPeminjaman().getTglKembali()); lpd.setKodeBuku(p.getBuku().getKodeBuku()); lpd.setJudul(p.getBuku().getJudulBuku()); lpd.setTglKembaliSebenarnya(p.getCreatedDate()); lpd.setTelat(p.getTelat()); lpd.setDenda(p.getDenda()); lpd.setStatus("Sudah Kembali"); result.add(lpd); } } return result; } @Override public JasperPrint printLaporanPeminjaman(String mode, Date mulai, Date sampai){ try { InputStream inputStream = getClass().getResourceAsStream("/perpus/jrxml/LaporanPeminjaman.jasper"); List<LaporanPeminjamanDto> listWrappers = dataLaporanPeminjaman(mode, mulai, sampai); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("tglMulai", mulai); parameters.put("tglSampai", sampai); if(mode.equalsIgnoreCase("PEMINJAMAN")){ parameters.put("title", "LAPORAN PEMINJAMAN BUKU"); } else { parameters.put("title", "LAPORAN PENGEMBALIAN BUKU"); } JasperPrint j = JasperFillManager.fillReport( inputStream, parameters, new JRBeanCollectionDataSource(listWrappers)); return j; } catch (JRException ex) { ex.printStackTrace(); } return null; } }
false
true
public List<LaporanPeminjamanDto> dataLaporanPeminjaman(String mode, Date mulai, Date sampai){ List<LaporanPeminjamanDto> result = new ArrayList<LaporanPeminjamanDto>(); if(mode.equalsIgnoreCase("PEMINJAMAN")){ List<PeminjamanDetail> detailPeminjamans = transaksiService.getTransaksiBelumKembali(mulai, sampai); for(PeminjamanDetail p : detailPeminjamans){ PengembalianDetail kembali = transaksiService.getPengembalianByIdPinjamAndKodeBuku( p.getHeader().getId(), p.getBuku().getId()); LaporanPeminjamanDto lpd = new LaporanPeminjamanDto(); lpd.setId(p.getId().toString()); lpd.setKodeAnggota(p.getHeader().getAnggota().getKodeAnggota()); lpd.setNamaAnggota(p.getHeader().getAnggota().getNamaAnggota()); lpd.setTglPinjam(p.getHeader().getTglPinjam()); lpd.setTglKembali(p.getHeader().getTglKembali()); lpd.setKodeBuku(p.getBuku().getKodeBuku()); lpd.setJudul(p.getBuku().getJudulBuku()); if(kembali != null){ lpd.setTglKembaliSebenarnya(new DateTime(lpd.getTglKembali()) .plusDays(kembali.getTelat()).toDate()); lpd.setTelat(kembali.getTelat()); lpd.setDenda(kembali.getDenda()); lpd.setStatus("Sudah Kembali"); } else { lpd.setStatus("Belum Kembali"); } result.add(lpd); } } else { List<PengembalianDetail> detailpengembalians = transaksiService.getTransaksiPengembalian(mulai, sampai); for (PengembalianDetail p : detailpengembalians) { LaporanPeminjamanDto lpd = new LaporanPeminjamanDto(); lpd.setId(p.getId().toString()); lpd.setKodeAnggota(p.getHeader().getTransaksiPeminjaman().getAnggota().getKodeAnggota()); lpd.setNamaAnggota(p.getHeader().getTransaksiPeminjaman().getAnggota().getNamaAnggota()); lpd.setTglPinjam(p.getHeader().getTransaksiPeminjaman().getTglPinjam()); lpd.setTglKembali(p.getHeader().getTransaksiPeminjaman().getTglKembali()); lpd.setKodeBuku(p.getBuku().getKodeBuku()); lpd.setJudul(p.getBuku().getJudulBuku()); lpd.setTglKembaliSebenarnya(p.getCreatedDate()); lpd.setTelat(p.getTelat()); lpd.setDenda(p.getDenda()); lpd.setStatus("Sudah Kembali"); result.add(lpd); } } return result; }
public List<LaporanPeminjamanDto> dataLaporanPeminjaman(String mode, Date mulai, Date sampai){ List<LaporanPeminjamanDto> result = new ArrayList<LaporanPeminjamanDto>(); if(mode.equalsIgnoreCase("PEMINJAMAN")){ List<PeminjamanDetail> detailPeminjamans = transaksiService.getTransaksiBelumKembali(mulai, sampai); for(PeminjamanDetail p : detailPeminjamans){ PengembalianDetail kembali = transaksiService.getPengembalianByIdPinjamAndKodeBuku( p.getHeader().getId(), p.getBuku().getId()); LaporanPeminjamanDto lpd = new LaporanPeminjamanDto(); lpd.setId(p.getHeader().getId().toString()); lpd.setKodeAnggota(p.getHeader().getAnggota().getKodeAnggota()); lpd.setNamaAnggota(p.getHeader().getAnggota().getNamaAnggota()); lpd.setTglPinjam(p.getHeader().getTglPinjam()); lpd.setTglKembali(p.getHeader().getTglKembali()); lpd.setKodeBuku(p.getBuku().getKodeBuku()); lpd.setJudul(p.getBuku().getJudulBuku()); if(kembali != null){ lpd.setTglKembaliSebenarnya(new DateTime(lpd.getTglKembali()) .plusDays(kembali.getTelat()).toDate()); lpd.setTelat(kembali.getTelat()); lpd.setDenda(kembali.getDenda()); lpd.setStatus("Sudah Kembali"); } else { lpd.setStatus("Belum Kembali"); } result.add(lpd); } } else { List<PengembalianDetail> detailpengembalians = transaksiService.getTransaksiPengembalian(mulai, sampai); for (PengembalianDetail p : detailpengembalians) { LaporanPeminjamanDto lpd = new LaporanPeminjamanDto(); lpd.setId(p.getHeader().getId().toString()); lpd.setKodeAnggota(p.getHeader().getTransaksiPeminjaman().getAnggota().getKodeAnggota()); lpd.setNamaAnggota(p.getHeader().getTransaksiPeminjaman().getAnggota().getNamaAnggota()); lpd.setTglPinjam(p.getHeader().getTransaksiPeminjaman().getTglPinjam()); lpd.setTglKembali(p.getHeader().getTransaksiPeminjaman().getTglKembali()); lpd.setKodeBuku(p.getBuku().getKodeBuku()); lpd.setJudul(p.getBuku().getJudulBuku()); lpd.setTglKembaliSebenarnya(p.getCreatedDate()); lpd.setTelat(p.getTelat()); lpd.setDenda(p.getDenda()); lpd.setStatus("Sudah Kembali"); result.add(lpd); } } return result; }
diff --git a/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/util/PersonMainAttributes.java b/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/util/PersonMainAttributes.java index eee5f647..94f4a6fb 100644 --- a/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/util/PersonMainAttributes.java +++ b/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/util/PersonMainAttributes.java @@ -1,71 +1,70 @@ /* * Copyright 2012 SURFnet bv, The Netherlands * * 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 nl.surfnet.coin.selfservice.util; import java.util.List; import java.util.Map; /** * Simple pojo containing the main attributes of a person. These main attributes * will be displayed to the normal user by default. * */ public class PersonMainAttributes { public static final String USER_ATTRIBUTE_DISPLAY_NAME = "urn:mace:dir:attribute-def:displayName"; public static final String USER_ATTRIBUTE_MAIL = "urn:mace:dir:attribute-def:mail"; public static final String USER_ATTRIBUTE_SCHAC_HOME_ORGANISATIONS = "urn:mace:terena.org:attribute-def:schacHomeOrganization"; String mail; String displayName; String schacHomeOrganization ; /** * Constructor that initializes the object with fields from the given attributeMap * @param attributeMap the map with attributes */ public PersonMainAttributes(Map<String, List<String>> attributeMap) { mail = attributeMap.get(USER_ATTRIBUTE_MAIL) == null ? null : attributeMap.get(USER_ATTRIBUTE_MAIL).get(0); displayName = attributeMap.get(USER_ATTRIBUTE_DISPLAY_NAME) == null ? null : attributeMap.get(USER_ATTRIBUTE_DISPLAY_NAME).get(0); schacHomeOrganization = attributeMap.get(USER_ATTRIBUTE_SCHAC_HOME_ORGANISATIONS) == null ? null : attributeMap.get(USER_ATTRIBUTE_SCHAC_HOME_ORGANISATIONS).get(0); - mail = mail + "XXXX"; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getSchacHomeOrganization() { return schacHomeOrganization; } public void setSchacHomeOrganization(String schacHomeOrganization) { this.schacHomeOrganization = schacHomeOrganization; } }
true
true
public PersonMainAttributes(Map<String, List<String>> attributeMap) { mail = attributeMap.get(USER_ATTRIBUTE_MAIL) == null ? null : attributeMap.get(USER_ATTRIBUTE_MAIL).get(0); displayName = attributeMap.get(USER_ATTRIBUTE_DISPLAY_NAME) == null ? null : attributeMap.get(USER_ATTRIBUTE_DISPLAY_NAME).get(0); schacHomeOrganization = attributeMap.get(USER_ATTRIBUTE_SCHAC_HOME_ORGANISATIONS) == null ? null : attributeMap.get(USER_ATTRIBUTE_SCHAC_HOME_ORGANISATIONS).get(0); mail = mail + "XXXX"; }
public PersonMainAttributes(Map<String, List<String>> attributeMap) { mail = attributeMap.get(USER_ATTRIBUTE_MAIL) == null ? null : attributeMap.get(USER_ATTRIBUTE_MAIL).get(0); displayName = attributeMap.get(USER_ATTRIBUTE_DISPLAY_NAME) == null ? null : attributeMap.get(USER_ATTRIBUTE_DISPLAY_NAME).get(0); schacHomeOrganization = attributeMap.get(USER_ATTRIBUTE_SCHAC_HOME_ORGANISATIONS) == null ? null : attributeMap.get(USER_ATTRIBUTE_SCHAC_HOME_ORGANISATIONS).get(0); }
diff --git a/src/plugins/WebOfTrust/WebOfTrust.java b/src/plugins/WebOfTrust/WebOfTrust.java index 85d80730..488b528c 100644 --- a/src/plugins/WebOfTrust/WebOfTrust.java +++ b/src/plugins/WebOfTrust/WebOfTrust.java @@ -1,3588 +1,3590 @@ /* This code is part of WoT, a plugin for Freenet. It is distributed * under the GNU General Public License, version 2 (or at your option * any later version). See http://www.gnu.org/ for details of the GPL. */ package plugins.WebOfTrust; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Random; import plugins.WebOfTrust.Identity.FetchState; import plugins.WebOfTrust.Identity.IdentityID; import plugins.WebOfTrust.Score.ScoreID; import plugins.WebOfTrust.Trust.TrustID; import plugins.WebOfTrust.exceptions.DuplicateIdentityException; import plugins.WebOfTrust.exceptions.DuplicateScoreException; import plugins.WebOfTrust.exceptions.DuplicateTrustException; import plugins.WebOfTrust.exceptions.InvalidParameterException; import plugins.WebOfTrust.exceptions.NotInTrustTreeException; import plugins.WebOfTrust.exceptions.NotTrustedException; import plugins.WebOfTrust.exceptions.UnknownIdentityException; import plugins.WebOfTrust.introduction.IntroductionClient; import plugins.WebOfTrust.introduction.IntroductionPuzzle; import plugins.WebOfTrust.introduction.IntroductionPuzzleStore; import plugins.WebOfTrust.introduction.IntroductionServer; import plugins.WebOfTrust.introduction.OwnIntroductionPuzzle; import plugins.WebOfTrust.ui.fcp.FCPInterface; import plugins.WebOfTrust.ui.web.WebInterface; import com.db4o.Db4o; import com.db4o.ObjectContainer; import com.db4o.ObjectSet; import com.db4o.defragment.Defragment; import com.db4o.defragment.DefragmentConfig; import com.db4o.ext.ExtObjectContainer; import com.db4o.query.Query; import com.db4o.reflect.jdk.JdkReflector; import freenet.keys.FreenetURI; import freenet.keys.USK; import freenet.l10n.BaseL10n; import freenet.l10n.BaseL10n.LANGUAGE; import freenet.l10n.PluginL10n; import freenet.node.RequestClient; import freenet.pluginmanager.FredPlugin; import freenet.pluginmanager.FredPluginBaseL10n; import freenet.pluginmanager.FredPluginFCP; import freenet.pluginmanager.FredPluginL10n; import freenet.pluginmanager.FredPluginRealVersioned; import freenet.pluginmanager.FredPluginThreadless; import freenet.pluginmanager.FredPluginVersioned; import freenet.pluginmanager.PluginReplySender; import freenet.pluginmanager.PluginRespirator; import freenet.support.CurrentTimeUTC; import freenet.support.Logger; import freenet.support.Logger.LogLevel; import freenet.support.SimpleFieldSet; import freenet.support.SizeUtil; import freenet.support.api.Bucket; import freenet.support.io.FileUtil; /** * A web of trust plugin based on Freenet. * * @author xor ([email protected]), Julien Cornuwel ([email protected]) */ public class WebOfTrust implements FredPlugin, FredPluginThreadless, FredPluginFCP, FredPluginVersioned, FredPluginRealVersioned, FredPluginL10n, FredPluginBaseL10n { /* Constants */ public static final boolean FAST_DEBUG_MODE = false; /** The relative path of the plugin on Freenet's web interface */ public static final String SELF_URI = "/WebOfTrust"; /** Package-private method to allow unit tests to bypass some assert()s */ /** * The "name" of this web of trust. It is included in the document name of identity URIs. For an example, see the SEED_IDENTITIES * constant below. The purpose of this constant is to allow anyone to create his own custom web of trust which is completely disconnected * from the "official" web of trust of the Freenet project. It is also used as the session cookie namespace. */ public static final String WOT_NAME = "WebOfTrust"; public static final String DATABASE_FILENAME = WOT_NAME + ".db4o"; public static final int DATABASE_FORMAT_VERSION = 2; /** * The official seed identities of the WoT plugin: If a newbie wants to download the whole offficial web of trust, he needs at least one * trust list from an identity which is well-connected to the web of trust. To prevent newbies from having to add this identity manually, * the Freenet development team provides a list of seed identities - each of them is one of the developers. */ private static final String[] SEED_IDENTITIES = new String[] { "USK@QeTBVWTwBldfI-lrF~xf0nqFVDdQoSUghT~PvhyJ1NE,OjEywGD063La2H-IihD7iYtZm3rC0BP6UTvvwyF5Zh4,AQACAAE/WebOfTrust/1344", // xor "USK@z9dv7wqsxIBCiFLW7VijMGXD9Gl-EXAqBAwzQ4aq26s,4Uvc~Fjw3i9toGeQuBkDARUV5mF7OTKoAhqOA9LpNdo,AQACAAE/WebOfTrust/1270", // Toad "USK@o2~q8EMoBkCNEgzLUL97hLPdddco9ix1oAnEa~VzZtg,X~vTpL2LSyKvwQoYBx~eleI2RF6QzYJpzuenfcKDKBM,AQACAAE/WebOfTrust/9379", // Bombe // "USK@cI~w2hrvvyUa1E6PhJ9j5cCoG1xmxSooi7Nez4V2Gd4,A3ArC3rrJBHgAJV~LlwY9kgxM8kUR2pVYXbhGFtid78,AQACAAE/WebOfTrust/19", // TheSeeker. Disabled because he is using LCWoT and it does not support identity introduction ATM. "USK@D3MrAR-AVMqKJRjXnpKW2guW9z1mw5GZ9BB15mYVkVc,xgddjFHx2S~5U6PeFkwqO5V~1gZngFLoM-xaoMKSBI8,AQACAAE/WebOfTrust/4959", // zidel }; /* References from the node */ /** The node's interface to connect the plugin with the node, needed for retrieval of all other interfaces */ private PluginRespirator mPR; private static PluginL10n l10n; /* References from the plugin itself */ /* Database & configuration of the plugin */ private ExtObjectContainer mDB; private Configuration mConfig; private IntroductionPuzzleStore mPuzzleStore; /** Used for exporting identities, identity introductions and introduction puzzles to XML and importing them from XML. */ private XMLTransformer mXMLTransformer; private RequestClient mRequestClient; /* Worker objects which actually run the plugin */ /** * Clients can subscribe to certain events such as identity creation, trust changes, etc. with the {@link SubscriptionManager} */ private SubscriptionManager mSubscriptionManager; /** * Periodically wakes up and inserts any OwnIdentity which needs to be inserted. */ private IdentityInserter mInserter; /** * Fetches identities when it is told to do so by the plugin: * - At startup, all known identities are fetched * - When a new identity is received from a trust list it is fetched * - When a new identity is received by the IntrouductionServer it is fetched * - When an identity is manually added it is also fetched. * - ... */ private IdentityFetcher mFetcher; /** * Uploads captchas belonging to our own identities which others can solve to get on the trust list of them. Checks whether someone * uploaded solutions for them periodically and adds the new identities if a solution is received. */ private IntroductionServer mIntroductionServer; /** * Downloads captchas which the user can solve to announce his identities on other people's trust lists, provides the interface for * the UI to obtain the captchas and enter solutions. Uploads the solutions if the UI enters them. */ private IntroductionClient mIntroductionClient; /* Actual data of the WoT */ private boolean mFullScoreComputationNeeded = false; private boolean mTrustListImportInProgress = false; /* User interfaces */ private WebInterface mWebInterface; private FCPInterface mFCPInterface; /* Statistics */ private int mFullScoreRecomputationCount = 0; private long mFullScoreRecomputationMilliseconds = 0; private int mIncrementalScoreRecomputationCount = 0; private long mIncrementalScoreRecomputationMilliseconds = 0; /* These booleans are used for preventing the construction of log-strings if logging is disabled (for saving some cpu cycles) */ private static transient volatile boolean logDEBUG = false; private static transient volatile boolean logMINOR = false; static { Logger.registerClass(WebOfTrust.class); } public void runPlugin(PluginRespirator myPR) { try { Logger.normal(this, "Web Of Trust plugin version " + Version.getMarketingVersion() + " starting up..."); /* Catpcha generation needs headless mode on linux */ System.setProperty("java.awt.headless", "true"); mPR = myPR; /* TODO: This can be used for clean copies of the database to get rid of corrupted internal db4o structures. /* We should provide an option on the web interface to run this once during next startup and switch to the cloned database */ // cloneDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME), new File(getUserDataDirectory(), DATABASE_FILENAME + ".clone")); mDB = openDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME)); mConfig = getOrCreateConfig(); if(mConfig.getDatabaseFormatVersion() > WebOfTrust.DATABASE_FORMAT_VERSION) throw new RuntimeException("The WoT plugin's database format is newer than the WoT plugin which is being used."); mSubscriptionManager = new SubscriptionManager(this); mPuzzleStore = new IntroductionPuzzleStore(this); // Please ensure that no threads are using the IntroductionPuzzleStore / IdentityFetcher / SubscriptionManager while this is executing. upgradeDB(); mXMLTransformer = new XMLTransformer(this); mRequestClient = new RequestClient() { public boolean persistent() { return false; } public void removeFrom(ObjectContainer container) { throw new UnsupportedOperationException(); } public boolean realTimeFlag() { return false; } }; mInserter = new IdentityInserter(this); mFetcher = new IdentityFetcher(this, getPluginRespirator()); // We only do this if debug logging is enabled since the integrity verification cannot repair anything anyway, // if the user does not read his logs there is no need to check the integrity. // TODO: Do this once every few startups and notify the user in the web ui if errors are found. if(logDEBUG) verifyDatabaseIntegrity(); // TODO: Only do this once every few startups once we are certain that score computation does not have any serious bugs. verifyAndCorrectStoredScores(); // Database is up now, integrity is checked. We can start to actually do stuff // TODO: This can be used for doing backups. Implement auto backup, maybe once a week or month //backupDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME + ".backup")); mSubscriptionManager.start(); createSeedIdentities(); Logger.normal(this, "Starting fetches of all identities..."); synchronized(this) { synchronized(mFetcher) { for(Identity identity : getAllIdentities()) { if(shouldFetchIdentity(identity)) { try { mFetcher.fetch(identity.getID()); } catch(Exception e) { Logger.error(this, "Fetching identity failed!", e); } } } } } mInserter.start(); mIntroductionServer = new IntroductionServer(this, mFetcher); mIntroductionServer.start(); mIntroductionClient = new IntroductionClient(this); mIntroductionClient.start(); mWebInterface = new WebInterface(this, SELF_URI); mFCPInterface = new FCPInterface(this); Logger.normal(this, "Web Of Trust plugin starting up completed."); } catch(RuntimeException e){ Logger.error(this, "Error during startup", e); /* We call it so the database is properly closed */ terminate(); throw e; } } /** * Constructor for being used by the node and unit tests. Does not do anything. */ public WebOfTrust() { } /** * Constructor which does not generate an IdentityFetcher, IdentityInster, IntroductionPuzzleStore, user interface, etc. * For use by the unit tests to be able to run WoT without a node. * @param databaseFilename The filename of the database. */ public WebOfTrust(String databaseFilename) { mDB = openDatabase(new File(databaseFilename)); mConfig = getOrCreateConfig(); if(mConfig.getDatabaseFormatVersion() != WebOfTrust.DATABASE_FORMAT_VERSION) throw new RuntimeException("Database format version mismatch. Found: " + mConfig.getDatabaseFormatVersion() + "; expected: " + WebOfTrust.DATABASE_FORMAT_VERSION); mPuzzleStore = new IntroductionPuzzleStore(this); mSubscriptionManager = new SubscriptionManager(this); mFetcher = new IdentityFetcher(this, null); } private File getUserDataDirectory() { final File wotDirectory = new File(mPR.getNode().getUserDir(), WOT_NAME); if(!wotDirectory.exists() && !wotDirectory.mkdir()) throw new RuntimeException("Unable to create directory " + wotDirectory); return wotDirectory; } private com.db4o.config.Configuration getNewDatabaseConfiguration() { com.db4o.config.Configuration cfg = Db4o.newConfiguration(); // Required config options: cfg.reflectWith(new JdkReflector(getPluginClassLoader())); // TODO: Optimization: We do explicit activation everywhere. We could change this to 0 and test whether everything still works. // Ideally, we would benchmark both 0 and 1 and make it configurable. cfg.activationDepth(1); cfg.updateDepth(1); // This must not be changed: We only activate(this, 1) before store(this). Logger.normal(this, "Default activation depth: " + cfg.activationDepth()); cfg.exceptionsOnNotStorable(true); // The shutdown hook does auto-commit. We do NOT want auto-commit: if a transaction hasn't commit()ed, it's not safe to commit it. cfg.automaticShutDown(false); // Performance config options: cfg.callbacks(false); // We don't use callbacks yet. TODO: Investigate whether we might want to use them cfg.classActivationDepthConfigurable(false); // Registration of indices (also performance) // ATTENTION: Also update cloneDatabase() when adding new classes! @SuppressWarnings("unchecked") final Class<? extends Persistent>[] persistentClasses = new Class[] { Configuration.class, Identity.class, OwnIdentity.class, Trust.class, Score.class, IdentityFetcher.IdentityFetcherCommand.class, IdentityFetcher.AbortFetchCommand.class, IdentityFetcher.StartFetchCommand.class, IdentityFetcher.UpdateEditionHintCommand.class, SubscriptionManager.Subscription.class, SubscriptionManager.IdentitiesSubscription.class, SubscriptionManager.ScoresSubscription.class, SubscriptionManager.TrustsSubscription.class, SubscriptionManager.Notification.class, SubscriptionManager.InitialSynchronizationNotification.class, SubscriptionManager.IdentityChangedNotification.class, SubscriptionManager.ScoreChangedNotification.class, SubscriptionManager.TrustChangedNotification.class, IntroductionPuzzle.class, OwnIntroductionPuzzle.class }; for(Class<? extends Persistent> clazz : persistentClasses) { boolean classHasIndex = clazz.getAnnotation(Persistent.IndexedClass.class) != null; // TODO: We enable class indexes for all classes to make sure nothing breaks because it is the db4o default, check whether enabling // them only for the classes where we need them does not cause any harm. classHasIndex = true; if(logDEBUG) Logger.debug(this, "Persistent class: " + clazz.getCanonicalName() + "; hasIndex==" + classHasIndex); // TODO: Make very sure that it has no negative side effects if we disable class indices for some classes // Maybe benchmark in comparison to a database which has class indices enabled for ALL classes. cfg.objectClass(clazz).indexed(classHasIndex); // Check the class' fields for @IndexedField annotations for(Field field : clazz.getDeclaredFields()) { if(field.getAnnotation(Persistent.IndexedField.class) != null) { if(logDEBUG) Logger.debug(this, "Registering indexed field " + clazz.getCanonicalName() + '.' + field.getName()); cfg.objectClass(clazz).objectField(field.getName()).indexed(true); } } // Check whether the class itself has an @IndexedField annotation final Persistent.IndexedField annotation = clazz.getAnnotation(Persistent.IndexedField.class); if(annotation != null) { for(String fieldName : annotation.names()) { if(logDEBUG) Logger.debug(this, "Registering indexed field " + clazz.getCanonicalName() + '.' + fieldName); cfg.objectClass(clazz).objectField(fieldName).indexed(true); } } } // TODO: We should check whether db4o inherits the indexed attribute to child classes, for example for this one: // Unforunately, db4o does not provide any way to query the indexed() property of fields, you can only set it // We might figure out whether inheritance works by writing a benchmark. return cfg; } private synchronized void restoreDatabaseBackup(File databaseFile, File backupFile) throws IOException { Logger.warning(this, "Trying to restore database backup: " + backupFile.getAbsolutePath()); if(mDB != null) throw new RuntimeException("Database is opened already!"); if(backupFile.exists()) { try { FileUtil.secureDelete(databaseFile, mPR.getNode().fastWeakRandom); } catch(IOException e) { Logger.warning(this, "Deleting of the database failed: " + databaseFile.getAbsolutePath()); } if(backupFile.renameTo(databaseFile)) { Logger.warning(this, "Backup restored!"); } else { throw new IOException("Unable to rename backup file back to database file: " + databaseFile.getAbsolutePath()); } } else { throw new IOException("Cannot restore backup, it does not exist!"); } } private synchronized void defragmentDatabase(File databaseFile) throws IOException { Logger.normal(this, "Defragmenting database ..."); if(mDB != null) throw new RuntimeException("Database is opened already!"); if(mPR == null) { Logger.normal(this, "No PluginRespirator found, probably running as unit test, not defragmenting."); return; } final Random random = mPR.getNode().fastWeakRandom; // Open it first, because defrag will throw if it needs to upgrade the file. { final ObjectContainer database = Db4o.openFile(getNewDatabaseConfiguration(), databaseFile.getAbsolutePath()); // Db4o will throw during defragmentation if new fields were added to classes and we didn't initialize their values on existing // objects before defragmenting. So we just don't defragment if the database format version has changed. final boolean canDefragment = peekDatabaseFormatVersion(this, database.ext()) == WebOfTrust.DATABASE_FORMAT_VERSION; while(!database.close()); if(!canDefragment) { Logger.normal(this, "Not defragmenting, database format version changed!"); return; } if(!databaseFile.exists()) { Logger.error(this, "Database file does not exist after openFile: " + databaseFile.getAbsolutePath()); return; } } final File backupFile = new File(databaseFile.getAbsolutePath() + ".backup"); if(backupFile.exists()) { Logger.error(this, "Not defragmenting database: Backup file exists, maybe the node was shot during defrag: " + backupFile.getAbsolutePath()); return; } final File tmpFile = new File(databaseFile.getAbsolutePath() + ".temp"); FileUtil.secureDelete(tmpFile, random); /* As opposed to the default, BTreeIDMapping uses an on-disk file instead of in-memory for mapping IDs. /* Reduces memory usage during defragmentation while being slower. /* However as of db4o 7.4.63.11890, it is bugged and prevents defragmentation from succeeding for my database, so we don't use it for now. */ final DefragmentConfig config = new DefragmentConfig(databaseFile.getAbsolutePath(), backupFile.getAbsolutePath() // ,new BTreeIDMapping(tmpFile.getAbsolutePath()) ); /* Delete classes which are not known to the classloader anymore - We do NOT do this because: /* - It is buggy and causes exceptions often as of db4o 7.4.63.11890 /* - WOT has always had proper database upgrade code (function upgradeDB()) and does not rely on automatic schema evolution. /* If we need to get rid of certain objects we should do it in the database upgrade code, */ // config.storedClassFilter(new AvailableClassFilter()); config.db4oConfig(getNewDatabaseConfiguration()); try { Defragment.defrag(config); } catch (Exception e) { Logger.error(this, "Defragment failed", e); try { restoreDatabaseBackup(databaseFile, backupFile); return; } catch(IOException e2) { Logger.error(this, "Unable to restore backup", e2); throw new IOException(e); } } final long oldSize = backupFile.length(); final long newSize = databaseFile.length(); if(newSize <= 0) { Logger.error(this, "Defrag produced an empty file! Trying to restore old database file..."); databaseFile.delete(); try { restoreDatabaseBackup(databaseFile, backupFile); } catch(IOException e2) { Logger.error(this, "Unable to restore backup", e2); throw new IOException(e2); } } else { final double change = 100.0 * (((double)(oldSize - newSize)) / ((double)oldSize)); FileUtil.secureDelete(tmpFile, random); FileUtil.secureDelete(backupFile, random); Logger.normal(this, "Defragment completed. "+SizeUtil.formatSize(oldSize)+" ("+oldSize+") -> " +SizeUtil.formatSize(newSize)+" ("+newSize+") ("+(int)change+"% shrink)"); } } /** * ATTENTION: This function is duplicated in the Freetalk plugin, please backport any changes. * * Initializes the plugin's db4o database. */ private synchronized ExtObjectContainer openDatabase(File file) { Logger.normal(this, "Opening database using db4o " + Db4o.version()); if(mDB != null) throw new RuntimeException("Database is opened already!"); try { defragmentDatabase(file); } catch (IOException e) { throw new RuntimeException(e); } return Db4o.openFile(getNewDatabaseConfiguration(), file.getAbsolutePath()).ext(); } /** * ATTENTION: Please ensure that no threads are using the IntroductionPuzzleStore / IdentityFetcher / SubscriptionManager while this is executing. * It doesn't synchronize on the IntroductionPuzzleStore / IdentityFetcher / SubscriptionManager because it assumes that they are not being used yet. * (I didn't upgrade this function to do the locking because it would be much work to test the changes for little benefit) */ @SuppressWarnings("deprecation") private synchronized void upgradeDB() { int databaseVersion = mConfig.getDatabaseFormatVersion(); if(databaseVersion == WebOfTrust.DATABASE_FORMAT_VERSION) return; // Insert upgrade code here. See Freetalk.java for a skeleton. if(databaseVersion == 1) { Logger.normal(this, "Upgrading database version " + databaseVersion); //synchronized(this) { // Already done at function level //synchronized(mPuzzleStore) { // Normally would be needed for deleteWithoutCommit(Identity) but IntroductionClient/Server are not running yet //synchronized(mFetcher) { // Normally would be needed for deleteWithoutCommit(Identity) but the IdentityFetcher is not running yet //synchronized(mSubscriptionManager) { // Normally would be needed for deleteWithoutCommit(Identity) but the SubscriptionManager is not running yet synchronized(Persistent.transactionLock(mDB)) { try { Logger.normal(this, "Generating Score IDs..."); for(Score score : getAllScores()) { score.generateID(); score.storeWithoutCommit(); } Logger.normal(this, "Generating Trust IDs..."); for(Trust trust : getAllTrusts()) { trust.generateID(); trust.storeWithoutCommit(); } Logger.normal(this, "Searching for identities with mixed up insert/request URIs..."); for(Identity identity : getAllIdentities()) { try { USK.create(identity.getRequestURI()); } catch (MalformedURLException e) { if(identity instanceof OwnIdentity) { Logger.error(this, "Insert URI specified as request URI for OwnIdentity, not correcting the URIs as the insert URI" + "might have been published by solving captchas - the identity could be compromised: " + identity); } else { Logger.error(this, "Insert URI specified as request URI for non-own Identity, deleting: " + identity); deleteWithoutCommit(identity); } } } mConfig.setDatabaseFormatVersion(++databaseVersion); mConfig.storeAndCommit(); Logger.normal(this, "Upgraded database to version " + databaseVersion); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } //} } if(databaseVersion != WebOfTrust.DATABASE_FORMAT_VERSION) throw new RuntimeException("Your database is too outdated to be upgraded automatically, please create a new one by deleting " + DATABASE_FILENAME + ". Contact the developers if you really need your old data."); } /** * DO NOT USE THIS FUNCTION ON A DATABASE WHICH YOU WANT TO CONTINUE TO USE! * * Debug function for finding object leaks in the database. * * - Deletes all identities in the database - This should delete ALL objects in the database. * - Then it checks for whether any objects still exist - those are leaks. */ private synchronized void checkForDatabaseLeaks() { Logger.normal(this, "Checking for database leaks... This will delete all identities!"); { Logger.debug(this, "Checking FetchState leakage..."); final Query query = mDB.query(); query.constrain(FetchState.class); @SuppressWarnings("unchecked") ObjectSet<FetchState> result = (ObjectSet<FetchState>)query.execute(); for(FetchState state : result) { Logger.debug(this, "Checking " + state); final Query query2 = mDB.query(); query2.constrain(Identity.class); query.descend("mCurrentEditionFetchState").constrain(state).identity(); @SuppressWarnings("unchecked") ObjectSet<FetchState> result2 = (ObjectSet<FetchState>)query.execute(); switch(result2.size()) { case 0: Logger.error(this, "Found leaked FetchState!"); break; case 1: break; default: Logger.error(this, "Found re-used FetchState, count: " + result2.size()); break; } } Logger.debug(this, "Finished checking FetchState leakage, amount:" + result.size()); } Logger.normal(this, "Deleting ALL identities..."); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { beginTrustListImport(); for(Identity identity : getAllIdentities()) { deleteWithoutCommit(identity); } finishTrustListImport(); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { abortTrustListImport(e); // abortTrustListImport() does rollback already // Persistent.checkedRollbackAndThrow(mDB, this, e); throw e; } } } } } Logger.normal(this, "Deleting ALL identities finished."); Query query = mDB.query(); query.constrain(Object.class); @SuppressWarnings("unchecked") ObjectSet<Object> result = query.execute(); for(Object leak : result) { Logger.error(this, "Found leaked object: " + leak); } Logger.warning(this, "Finished checking for database leaks. This database is empty now, delete it."); } private synchronized boolean verifyDatabaseIntegrity() { // Take locks of all objects which deal with persistent stuff because we act upon ALL persistent objects. synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { deleteDuplicateObjects(); deleteOrphanObjects(); Logger.debug(this, "Testing database integrity..."); final Query q = mDB.query(); q.constrain(Persistent.class); boolean result = true; for(final Persistent p : new Persistent.InitializingObjectSet<Persistent>(this, q)) { try { p.startupDatabaseIntegrityTest(); } catch(Exception e) { result = false; try { Logger.error(this, "Integrity test failed for " + p, e); } catch(Exception e2) { Logger.error(this, "Integrity test failed for Persistent of class " + p.getClass(), e); Logger.error(this, "Exception thrown by toString() was:", e2); } } } Logger.debug(this, "Database integrity test finished."); return result; } } } } /** * Does not do proper synchronization! Only use it in single-thread-mode during startup. * * Does a backup of the database using db4o's backup mechanism. * * This will NOT fix corrupted internal structures of databases - use cloneDatabase if you need to fix your database. */ private synchronized void backupDatabase(File newDatabase) { Logger.normal(this, "Backing up database to " + newDatabase.getAbsolutePath()); if(newDatabase.exists()) throw new RuntimeException("Target exists already: " + newDatabase.getAbsolutePath()); WebOfTrust backup = null; boolean success = false; try { mDB.backup(newDatabase.getAbsolutePath()); if(logDEBUG) { backup = new WebOfTrust(newDatabase.getAbsolutePath()); // We do not throw to make the clone mechanism more robust in case it is being used for creating backups Logger.debug(this, "Checking database integrity of clone..."); if(backup.verifyDatabaseIntegrity()) Logger.debug(this, "Checking database integrity of clone finished."); else Logger.error(this, "Database integrity check of clone failed!"); Logger.debug(this, "Checking this.equals(clone)..."); if(equals(backup)) Logger.normal(this, "Clone is equal!"); else Logger.error(this, "Clone is not equal!"); } success = true; } finally { if(backup != null) backup.terminate(); if(!success) newDatabase.delete(); } Logger.normal(this, "Backing up database finished."); } /** * Does not do proper synchronization! Only use it in single-thread-mode during startup. * * Creates a clone of the source database by reading all objects of it into memory and then writing them out to the target database. * Does NOT copy the Configuration, the IntroductionPuzzles or the IdentityFetcher command queue. * * The difference to backupDatabase is that it does NOT use db4o's backup mechanism, instead it creates the whole database from scratch. * This is useful because the backup mechanism of db4o does nothing but copying the raw file: * It wouldn't fix databases which cannot be defragmented anymore due to internal corruption. * - Databases which were cloned by this function CAN be defragmented even if the original database couldn't. * * HOWEVER this function uses lots of memory as the whole database is copied into memory. */ private synchronized void cloneDatabase(File sourceDatabase, File targetDatabase) { Logger.normal(this, "Cloning " + sourceDatabase.getAbsolutePath() + " to " + targetDatabase.getAbsolutePath()); if(targetDatabase.exists()) throw new RuntimeException("Target exists already: " + targetDatabase.getAbsolutePath()); WebOfTrust original = null; WebOfTrust clone = null; boolean success = false; try { original = new WebOfTrust(sourceDatabase.getAbsolutePath()); // We need to copy all objects into memory and then close & unload the source database before writing the objects to the target one. // - I tried implementing this function in a way where it directly takes the objects from the source database and stores them // in the target database while the source is still open. This did not work: Identity objects disappeared magically, resulting // in Trust objects .storeWithoutCommit throwing "Mandatory object not found" on their associated identities. // FIXME: Clone the Configuration object final HashSet<Identity> allIdentities = new HashSet<Identity>(original.getAllIdentities()); final HashSet<Trust> allTrusts = new HashSet<Trust>(original.getAllTrusts()); final HashSet<Score> allScores = new HashSet<Score>(original.getAllScores()); for(Identity identity : allIdentities) { identity.checkedActivate(16); identity.mWebOfTrust = null; identity.mDB = null; } for(Trust trust : allTrusts) { trust.checkedActivate(16); trust.mWebOfTrust = null; trust.mDB = null; } for(Score score : allScores) { score.checkedActivate(16); score.mWebOfTrust = null; score.mDB = null; } // We don't clone: // - Introduction puzzles because we can just download new ones // - IdentityFetcher commands because they aren't persistent across startups anyway // - Subscription and Notification objects because subscriptions are also not persistent across startups. original.terminate(); original = null; System.gc(); // Now we write out the in-memory copies ... clone = new WebOfTrust(targetDatabase.getAbsolutePath()); for(Identity identity : allIdentities) { identity.initializeTransient(clone); identity.storeWithoutCommit(); } Persistent.checkedCommit(clone.getDatabase(), clone); for(Trust trust : allTrusts) { trust.initializeTransient(clone); trust.storeWithoutCommit(); } Persistent.checkedCommit(clone.getDatabase(), clone); for(Score score : allScores) { score.initializeTransient(clone); score.storeWithoutCommit(); } Persistent.checkedCommit(clone.getDatabase(), clone); // And because cloning is a complex operation we do a mandatory database integrity check Logger.normal(this, "Checking database integrity of clone..."); if(clone.verifyDatabaseIntegrity()) Logger.normal(this, "Checking database integrity of clone finished."); else throw new RuntimeException("Database integrity check of clone failed!"); // ... and also test whether the Web Of Trust is equals() to the clone. This does a deep check of all identities, scores & trusts! original = new WebOfTrust(sourceDatabase.getAbsolutePath()); Logger.normal(this, "Checking original.equals(clone)..."); if(original.equals(clone)) Logger.normal(this, "Clone is equal!"); else throw new RuntimeException("Clone is not equal!"); success = true; } finally { if(original != null) original.terminate(); if(clone != null) clone.terminate(); if(!success) targetDatabase.delete(); } Logger.normal(this, "Cloning database finished."); } /** * Recomputes the {@link Score} of all identities and checks whether the score which is stored in the database is correct. * Incorrect scores are corrected & stored. * * The function is synchronized and does a transaction, no outer synchronization is needed. */ protected synchronized void verifyAndCorrectStoredScores() { Logger.normal(this, "Veriying all stored scores ..."); synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } Logger.normal(this, "Veriying all stored scores finished."); } /** * Debug function for deleting duplicate identities etc. which might have been created due to bugs :) */ private synchronized void deleteDuplicateObjects() { synchronized(mPuzzleStore) { // Needed for deleteWithoutCommit(Identity) synchronized(mFetcher) { // Needed for deleteWithoutCommit(Identity) synchronized(mSubscriptionManager) { // Needed for deleteWithoutCommit(Identity) synchronized(Persistent.transactionLock(mDB)) { try { HashSet<String> deleted = new HashSet<String>(); if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ..."); for(Identity identity : getAllIdentities()) { Query q = mDB.query(); q.constrain(Identity.class); q.descend("mID").constrain(identity.getID()); q.constrain(identity).identity().not(); ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q); for(Identity duplicate : duplicates) { if(deleted.contains(duplicate.getID()) == false) { Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI()); deleteWithoutCommit(duplicate); Persistent.checkedCommit(mDB, this); } } deleted.add(identity.getID()); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { } // synchronized(mPuzzleStore) { // synchronized(this) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ..."); boolean duplicateTrustFound = false; for(OwnIdentity truster : getAllOwnIdentities()) { HashSet<String> givenTo = new HashSet<String>(); for(Trust trust : getGivenTrusts(truster)) { if(givenTo.contains(trust.getTrustee().getID()) == false) givenTo.add(trust.getTrustee().getID()); else { Logger.error(this, "Deleting duplicate given trust:" + trust); removeTrustWithoutCommit(trust); duplicateTrustFound = true; } } } if(duplicateTrustFound) { computeAllScoresWithoutCommit(); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { /* TODO: Also delete duplicate score */ } /** * Debug function for deleting trusts or scores of which one of the involved partners is missing. */ private synchronized void deleteOrphanObjects() { // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanTrustFound = false; Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q); for(Trust trust : orphanTrusts) { if(trust.getTruster() != null && trust.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust); continue; } Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee()); orphanTrustFound = true; trust.deleteWithoutCommit(); // No need to update subscriptions as the trust is broken anyway. } if(orphanTrustFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanScoresFound = false; Query q = mDB.query(); q.constrain(Score.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q); for(Score score : orphanScores) { if(score.getTruster() != null && score.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score); continue; } Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee()); orphanScoresFound = true; score.deleteWithoutCommit(); // No need to update subscriptions as the score is broken anyway. } if(orphanScoresFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } /** * Warning: This function is not synchronized, use it only in single threaded mode. * @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist. */ @SuppressWarnings("deprecation") private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) { final Query query = database.query(); query.constrain(Configuration.class); @SuppressWarnings("unchecked") ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute(); switch(result.size()) { case 1: { final Configuration config = (Configuration)result.next(); config.initializeTransient(wot, database); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); return config.getDatabaseFormatVersion(); } default: return -1; } } /** * Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists. * @return The config object. */ private synchronized Configuration getOrCreateConfig() { final Query query = mDB.query(); query.constrain(Configuration.class); final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query); switch(result.size()) { case 1: { final Configuration config = result.next(); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); config.setDefaultValues(false); config.storeAndCommit(); return config; } case 0: { final Configuration config = new Configuration(this); config.initializeTransient(this); config.storeAndCommit(); return config; } default: throw new RuntimeException("Multiple config objects found: " + result.size()); } } /** Capacity is the maximum amount of points an identity can give to an other by trusting it. * * Values choice : * Advogato Trust metric recommends that values decrease by rounded 2.5 times. * This makes sense, making the need of 3 N+1 ranked people to overpower * the trust given by a N ranked identity. * * Number of ranks choice : * When someone creates a fresh identity, he gets the seed identity at * rank 1 and freenet developpers at rank 2. That means that * he will see people that were : * - given 7 trust by freenet devs (rank 2) * - given 17 trust by rank 3 * - given 50 trust by rank 4 * - given 100 trust by rank 5 and above. * This makes the range small enough to avoid a newbie * to even see spam, and large enough to make him see a reasonnable part * of the community right out-of-the-box. * Of course, as soon as he will start to give trust, he will put more * people at rank 1 and enlarge his WoT. */ protected static final int capacities[] = { 100,// Rank 0 : Own identities 40, // Rank 1 : Identities directly trusted by ownIdenties 16, // Rank 2 : Identities trusted by rank 1 identities 6, // So on... 2, 1 // Every identity above rank 5 can give 1 point }; // Identities with negative score have zero capacity /** * Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much * trust points an identity can add to the score of identities which it has assigned trust values to. * The higher the rank of an identity, the less is it's capacity. * * If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less * than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0. * * If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value: * The decision of the truster should always overpower the view of remote identities. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed * @param trustee The {@link Identity} of which the capacity shall be computed. * @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust, * - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view. */ private int computeCapacity(OwnIdentity truster, Identity trustee, int rank) { if(truster == trustee) return 100; try { // FIXME: The comment "Security check, if rank computation breaks this will hit." below sounds like we don't actually // need to execute this because the callers probably do it implicitly. Check if this is true and if yes, convert it to an assert. if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit. assert(rank == Integer.MAX_VALUE); return 0; } } catch(NotTrustedException e) { } if(rank == -1 || rank == Integer.MAX_VALUE) return 0; return (rank < capacities.length) ? capacities[rank] : 1; } /** * Reference-implementation of score computation. This means:<br /> * - It is not used by the real WoT code because its slow<br /> * - It is used by unit tests (and WoT) to check whether the real implementation works<br /> * - It is the function which you should read if you want to understand how WoT works.<br /> * * Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br /> * * There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br /> * * Further, rank values are shortest paths and the path-finding algorithm is not executed from the source * to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path. * Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database * and affect many others. So it is useful to have this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * </code> * * @return True if all stored scores were correct. False if there were any errors in stored scores. */ protected boolean computeAllScoresWithoutCommit() { if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); boolean returnValue = true; final ObjectSet<Identity> allIdentities = getAllIdentities(); // Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity. for(OwnIdentity treeOwner : getAllOwnIdentities()) { // At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner. // An identity is visible if there is a trust chain from the owner to it. // The rank is the distance in trust steps from the treeOwner. // So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on. final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2); // Compute the rank values { // For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters. // The inner loop then pulls out one unprocessed identity and computes the rank of its trustees: // All trustees which have received positive (> 0) trust will get his rank + 1 // Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE. // Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all. // Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none. // // Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value: // The decision of the own identity shall not be overpowered by the view of the remote identities. // // The purpose of differentiation between Integer.MAX_VALUE and -1 is: // Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing // them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and // have a way of telling the user "this identity is not trusted" by keeping a score object of them. // Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where // we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank // - and we never import their trust lists. // We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved // introduction puzzles cannot inherit their rank to their trustees. final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>(); // The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE try { Score selfScore = getScore(treeOwner, treeOwner); if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one rankValues.put(treeOwner, selfScore.getRank()); unprocessedTrusters.addLast(treeOwner); } else { rankValues.put(treeOwner, null); } } catch(NotInTrustTreeException e) { // This only happens in unit tests. } while(!unprocessedTrusters.isEmpty()) { final Identity truster = unprocessedTrusters.removeFirst(); final Integer trusterRank = rankValues.get(truster); // The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all. if(trusterRank == null || trusterRank == Integer.MAX_VALUE) { // (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security) continue; } final int trusteeRank = trusterRank + 1; for(Trust trust : getGivenTrusts(truster)) { final Identity trustee = trust.getTrustee(); final Integer oldTrusteeRank = rankValues.get(trustee); if(oldTrusteeRank == null) { // The trustee was not processed yet if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } else rankValues.put(trustee, Integer.MAX_VALUE); } else { // Breadth first search will process all rank one identities are processed before any rank two identities, etc. assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank); if(oldTrusteeRank == Integer.MAX_VALUE) { // If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not // given by the tree owner. try { final Trust treeOwnerTrust = getTrust(treeOwner, trustee); assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct? } catch(NotTrustedException e) { if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } } } } } } } // Rank values of all visible identities are computed now. // Next step is to compute the scores of all identities for(Identity target : allIdentities) { // The score of an identity is the sum of all weighted trust values it has received. // Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank. Integer targetScore; final Integer targetRank = rankValues.get(target); if(targetRank == null) { targetScore = null; } else { // The treeOwner trusts himself. if(targetRank == 0) { targetScore = Integer.MAX_VALUE; } else { // If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score. try { targetScore = (int)getTrust(treeOwner, target).getValue(); } catch(NotTrustedException e) { targetScore = 0; for(Trust receivedTrust : getReceivedTrusts(target)) { final Identity truster = receivedTrust.getTruster(); final Integer trusterRank = rankValues.get(truster); // The capacity is a weight function for trust values which are given from an identity: // The higher the rank, the less the capacity. // If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0. final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1); targetScore += (receivedTrust.getValue() * capacity) / 100; } } } } Score newScore = null; if(targetScore != null) { newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank)); } boolean needToCheckFetchStatus = false; boolean oldShouldFetch = false; int oldCapacity = 0; // Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct. try { Score currentStoredScore = getScore(treeOwner, target); oldCapacity = currentStoredScore.getCapacity(); if(newScore == null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(currentStoredScore, null); } else { if(!newScore.equals(currentStoredScore)) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); final Score oldScore = currentStoredScore.clone(); currentStoredScore.setRank(newScore.getRank()); currentStoredScore.setCapacity(newScore.getCapacity()); currentStoredScore.setValue(newScore.getScore()); currentStoredScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, currentStoredScore); } } } catch(NotInTrustTreeException e) { oldCapacity = 0; if(newScore != null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); newScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, newScore); } } if(needToCheckFetchStatus) { // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target); target.markForRefetch(); target.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(target); mFetcher.storeStartFetchCommandWithoutCommit(target); } else if(oldShouldFetch && !shouldFetchIdentity(target)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target); mFetcher.storeAbortFetchCommandWithoutCommit(target); } } } } mFullScoreComputationNeeded = false; ++mFullScoreRecomputationCount; mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; if(logMINOR) { Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s"); } return returnValue; } private synchronized void createSeedIdentities() { synchronized(mSubscriptionManager) { for(String seedURI : SEED_IDENTITIES) { synchronized(Persistent.transactionLock(mDB)) { try { final Identity existingSeed = getIdentityByURI(seedURI); final Identity oldExistingSeed = existingSeed.clone(); // For the SubscriptionManager if(existingSeed instanceof OwnIdentity) { final OwnIdentity ownExistingSeed = (OwnIdentity)existingSeed; ownExistingSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); ownExistingSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT)); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, ownExistingSeed); ownExistingSeed.storeAndCommit(); } else { try { existingSeed.setEdition(new FreenetURI(seedURI).getEdition()); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, existingSeed); existingSeed.storeAndCommit(); } catch(InvalidParameterException e) { /* We already have the latest edition stored */ } } } catch (UnknownIdentityException uie) { try { final Identity newSeed = new Identity(this, seedURI, null, true); // We have to explicitly set the edition number because the constructor only considers the given edition as a hint. newSeed.setEdition(new FreenetURI(seedURI).getEdition()); newSeed.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, newSeed); Persistent.checkedCommit(mDB, this); } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } public void terminate() { Logger.normal(this, "Web Of Trust plugin terminating ..."); /* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */ try { if(mWebInterface != null) this.mWebInterface.unload(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionClient != null) mIntroductionClient.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionServer != null) mIntroductionServer.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mInserter != null) mInserter.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mFetcher != null) mFetcher.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mSubscriptionManager != null) mSubscriptionManager.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mDB != null) { /* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending. * If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction. * - All transactions should be committed after obtaining the lock() on the database. */ synchronized(Persistent.transactionLock(mDB)) { System.gc(); mDB.rollback(); System.gc(); mDB.close(); } } } catch(Exception e) { Logger.error(this, "Error during termination.", e); } Logger.normal(this, "Web Of Trust plugin terminated."); } /** * Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>. */ public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { mFCPInterface.handle(replysender, params, data, accesstype); } /** * Loads an own or normal identity from the database, querying on its ID. * * @param id The ID of the identity to load * @return The identity matching the supplied ID. * @throws DuplicateIdentityException if there are more than one identity with this id in the database * @throws UnknownIdentityException if there is no identity with this id in the database */ public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(Identity.class); query.descend("mID").constrain(id); final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Gets an OwnIdentity by its ID. * * @param id The unique identifier to query an OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if there is now OwnIdentity with that id */ public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(OwnIdentity.class); query.descend("mID").constrain(id); final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI}) * * @param uri The requestURI of the identity * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database */ public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Loads an identity from the database, querying on its requestURI (as String) * * @param uri The requestURI of the identity which will be converted to {@link FreenetURI} * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database * @throws MalformedURLException if the requestURI isn't a valid FreenetURI */ public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getIdentityByURI(new FreenetURI(uri)); } /** * Gets an OwnIdentity by its requestURI (a {@link FreenetURI}). * The OwnIdentity's unique identifier is extracted from the supplied requestURI. * * @param uri The requestURI of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database */ public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Gets an OwnIdentity by its requestURI (as String). * The given String is converted to {@link FreenetURI} in order to extract a unique id. * * @param uri The requestURI (as String) of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database * @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI */ public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getOwnIdentityByURI(new FreenetURI(uri)); } /** * Returns all identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database */ public ObjectSet<Identity> getAllIdentities() { final Query query = mDB.query(); query.constrain(Identity.class); return new Persistent.InitializingObjectSet<Identity>(this, query); } public static enum SortOrder { ByNicknameAscending, ByNicknameDescending, ByScoreAscending, ByScoreDescending, ByLocalTrustAscending, ByLocalTrustDescending } /** * Get a filtered and sorted list of identities. * You have to synchronize on this WoT when calling the function and processing the returned list. */ public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) { Query q = mDB.query(); switch(sortInstruction) { case ByNicknameAscending: q.constrain(Identity.class); q.descend("mNickname").orderAscending(); break; case ByNicknameDescending: q.constrain(Identity.class); q.descend("mNickname").orderDescending(); break; case ByScoreAscending: q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByScoreDescending: // TODO: This excludes identities which have no score q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; case ByLocalTrustAscending: q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByLocalTrustDescending: // TODO: This excludes untrusted identities. q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; } if(nickFilter != null) { nickFilter = nickFilter.trim(); if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like(); } return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database. * * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Identity> getAllNonOwnIdentities() { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently * modified identities will be at the beginning of the list. * * You have to synchronize on this WoT when calling the function and processing the returned list! * * Used by the IntroductionClient for fetching puzzles from recently modified identities. */ public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); /* TODO: As soon as identities announce that they were online every day, uncomment the following line */ /* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */ q.descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all own identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database. */ public ObjectSet<OwnIdentity> getAllOwnIdentities() { final Query q = mDB.query(); q.constrain(OwnIdentity.class); return new Persistent.InitializingObjectSet<OwnIdentity>(this, q); } /** * DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST! * IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS: * - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will. * - Especially it might be an information leak if the trust values of other OwnIdentities are deleted! * - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption. * * The intended purpose of this function is: * - To specify which objects have to be dealt with when messing with storage of an identity. * - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them. * However, the implementations of those functions might cause leaks by forgetting to delete certain object members. * If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty. * You then can check whether the database actually IS empty to test for leakage. * * You have to lock the WebOfTrust, the IntroductionPuzzleStore, the IdentityFetcher and the SubscriptionManager before calling this function. */ private void deleteWithoutCommit(Identity identity) { // We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport. // If the caller already handles that for us though, we should not call those function again. // So we check whether the caller already started an import. boolean trustListImportWasInProgress = mTrustListImportInProgress; try { if(!trustListImportWasInProgress) beginTrustListImport(); if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ..."); if(logDEBUG) Logger.debug(this, "Deleting received scores..."); for(Score score : getScores(identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } if(identity instanceof OwnIdentity) { if(logDEBUG) Logger.debug(this, "Deleting given scores..."); for(Score score : getGivenScores((OwnIdentity)identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } } if(logDEBUG) Logger.debug(this, "Deleting received trusts..."); for(Trust trust : getReceivedTrusts(identity)) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); } if(logDEBUG) Logger.debug(this, "Deleting given trusts..."); for(Trust givenTrust : getGivenTrusts(identity)) { givenTrust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(givenTrust, null); // We call computeAllScores anyway so we do not use removeTrustWithoutCommit() } mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us. if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ..."); mPuzzleStore.onIdentityDeletion(identity); if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command..."); if(mFetcher != null) { // Can be null if we use this function in upgradeDB() mFetcher.storeAbortFetchCommandWithoutCommit(identity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. } if(logDEBUG) Logger.debug(this, "Deleting the identity..."); identity.deleteWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(identity, null); if(!trustListImportWasInProgress) finishTrustListImport(); } catch(RuntimeException e) { if(!trustListImportWasInProgress) abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * Gets the score of this identity in a trust tree. * Each {@link OwnIdentity} has its own trust tree. * * @param truster The owner of the trust tree * @return The {@link Score} of this Identity in the required trust tree * @throws NotInTrustTreeException if this identity is not in the required trust tree */ public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mID").constrain(new ScoreID(truster, trustee).toString()); final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query); switch(result.size()) { case 1: final Score score = result.next(); assert(score.getTruster() == truster); assert(score.getTrustee() == trustee); return score; case 0: throw new NotInTrustTreeException(truster, trustee); default: throw new DuplicateScoreException(truster, trustee, result.size()); } } /** * Gets a list of all this Identity's Scores. * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * * @return An {@link ObjectSet} containing all {@link Score} this Identity has. */ public ObjectSet<Score> getScores(final Identity identity) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTrustee").constrain(identity).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Get a list of all scores which the passed own identity has assigned to other identities. * * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * @return An {@link ObjectSet} containing all {@link Score} this Identity has given. */ public ObjectSet<Score> getGivenScores(final OwnIdentity truster) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets the best score this Identity has in existing trust trees. * * @return the best score this Identity has * @throws NotInTrustTreeException If the identity has no score in any trusttree. */ public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException { int bestScore = Integer.MIN_VALUE; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestScore = Math.max(score.getScore(), bestScore); return bestScore; } /** * Gets the best capacity this identity has in any trust tree. * @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0. */ public synchronized int getBestCapacity(final Identity identity) throws NotInTrustTreeException { int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestCapacity = Math.max(score.getCapacity(), bestCapacity); return bestCapacity; } /** * Get all scores in the database. * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Score> getAllScores() { final Query query = mDB.query(); query.constrain(Score.class); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Checks whether the given identity should be downloaded. * * Synchronization: You must synchronize on this WebOfTrust when using this function. * * @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity. */ private boolean shouldFetchIdentity(final Identity identity) { if(identity instanceof OwnIdentity) return true; int bestScore = Integer.MIN_VALUE; int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) return false; // TODO: Cache the best score of an identity as a member variable. for(Score score : scores) { bestCapacity = Math.max(score.getCapacity(), bestCapacity); bestScore = Math.max(score.getScore(), bestScore); if(bestCapacity > 0 || bestScore >= 0) return true; } return false; } /** * Gets non-own Identities matching a specified score criteria. * TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The owner of the trust tree, null if you want the trusted identities of all owners. * @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0 * and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0. * @return an {@link ObjectSet} containing Scores of the identities that match the criteria */ public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) { final Query query = mDB.query(); query.constrain(Score.class); if(truster != null) query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").constrain(OwnIdentity.class).not(); /* We include 0 in the list of identities with positive score because solving captchas gives no points to score */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets {@link Trust} from a specified truster to a specified trustee. * * @param truster The identity that gives trust to this Identity * @param trustee The identity which receives the trust * @return The trust given to the trustee by the specified truster * @throws NotTrustedException if the truster doesn't trust the trustee */ public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mID").constrain(new TrustID(truster, trustee).toString()); final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query); switch(result.size()) { case 1: final Trust trust = result.next(); assert(trust.getTruster() == truster); assert(trust.getTrustee() == trustee); return trust; case 0: throw new NotTrustedException(truster, trustee); default: throw new DuplicateTrustException(truster, trustee, result.size()); } } /** * Gets all trusts given by the given truster. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster. * The result is sorted descending by the time we last fetched the trusted identity. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets given trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The identity which given the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster in a trust list with a different edition than the passed in one. * You have to synchronize on this WoT when calling the function and processing the returned list! */ protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) { final Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mTrusterTrustListEdition").constrain(edition).not(); return new Persistent.InitializingObjectSet<Trust>(this, q); } /** * Gets all trusts received by the given trustee. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets received trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param trustee The identity which has received the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getAllTrusts() { final Query query = mDB.query(); query.constrain(Trust.class); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gives some {@link Trust} to another Identity. * It creates or updates an existing Trust object and make the trustee compute its {@link Score}. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * * @param truster The Identity that gives the trust * @param trustee The Identity that receives the trust * @param newValue Numeric value of the trust * @param newComment A comment to explain the given value * @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values. */ protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { try { // Check if we are updating an existing trust value final Trust trust = getTrust(truster, trustee); final Trust oldTrust = trust.clone(); trust.trusterEditionUpdated(); trust.setComment(newComment); trust.storeWithoutCommit(); if(trust.getValue() != newValue) { trust.setValue(newValue); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(oldTrust, trust); if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(oldTrust, trust); } } catch (NotTrustedException e) { final Trust trust = new Trust(this, truster, trustee, newValue, newComment); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(null, trust); if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(null, trust); } truster.updated(); truster.storeWithoutCommit(); // TODO: Mabye notify clients about this. IMHO it would create too much notifications on trust list import so we don't. // As soon as we have notification-coalescing we might do it. // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(truster); } /** * Only for being used by WoT internally and by unit tests! * * You have to synchronize on this WebOfTrust while querying the parameter identities and calling this function. */ void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { setTrustWithoutCommit(truster, trustee, newValue, newComment); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } /** * Deletes a trust object. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * * @param truster * @param trustee */ protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) { try { try { removeTrustWithoutCommit(getTrust(truster, trustee)); } catch (NotTrustedException e) { Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname()); } } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * */ protected void removeTrustWithoutCommit(Trust trust) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); updateScoresWithoutCommit(trust, null); } /** * Initializes this OwnIdentity's trust tree without commiting the transaction. * Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities. * * The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }} * * @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen) */ private void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException { try { getScore(identity, identity); Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity); return; } catch (NotInTrustTreeException e) { final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100); score.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, score); } } /** * Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified * trust tree. * * Synchronization: * You have to synchronize on this WebOfTrust object when using this function. * * @param truster The OwnIdentity that owns the trust tree * @param trustee The identity for which the score shall be computed. * @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster. * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return Integer.MAX_VALUE; int value = 0; try { return getTrust(truster, trustee).getValue(); } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { final Score trusterScore = getScore(truster, trust.getTruster()); value += ( trust.getValue() * trusterScore.getCapacity() ) / 100; } catch (NotInTrustTreeException e) {} } return value; } /** * Computes the trustees's rank in the trust tree of the truster. * It gets its best ranked non-zero-capacity truster's rank, plus one. * If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite). * If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1. * * If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the * tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision). * * The purpose of differentiation between Integer.MAX_VALUE and -1 is: * Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them * in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the * user "this identity is not trusted" by keeping a score object of them. * Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we * hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and * we never download their trust lists. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * Synchronization: * You have to synchronize on this WebOfTrust object when using this function. * * @param truster The OwnIdentity that owns the trust tree * @return The new Rank if this Identity * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return 0; int rank = -1; try { Trust treeOwnerTrust = getTrust(truster, trustee); if(treeOwnerTrust.getValue() > 0) return 1; else return Integer.MAX_VALUE; } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { Score score = getScore(truster, trust.getTruster()); if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank // A truster only gives his rank to a trustee if he has assigned a strictly positive trust value if(trust.getValue() > 0 ) { // We give the rank to the trustee if it is better than its current rank or he has no rank yet. if(rank == -1 || score.getRank() < rank) rank = score.getRank(); } else { // If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster. if(rank == -1) rank = Integer.MAX_VALUE; } } } catch (NotInTrustTreeException e) {} } if(rank == -1) return -1; else if(rank == Integer.MAX_VALUE) return Integer.MAX_VALUE; else return rank+1; } /** * Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress. * This speeds up setTrust/removeTrust as the score calculation is only performed when {@link #finishTrustListImport()} is called. * * ATTENTION: Always take care to call one of {@link #finishTrustListImport()} / {@link #abortTrustListImport(Exception)} / {@link #abortTrustListImport(Exception, LogLevel)} * for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> */ protected void beginTrustListImport() { if(logMINOR) Logger.minor(this, "beginTrustListImport()"); if(mTrustListImportInProgress) { abortTrustListImport(new RuntimeException("There was already a trust list import in progress!")); mFullScoreComputationNeeded = true; computeAllScoresWithoutCommit(); assert(mFullScoreComputationNeeded == false); } mTrustListImportInProgress = true; assert(!mFullScoreComputationNeeded); assert(computeAllScoresWithoutCommit()); // The database is intact before the import } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e, Logger.LogLevel.ERROR); // Does checkedRollback() for you already } * }}}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file. * @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file. */ protected void abortTrustListImport(Exception e, LogLevel logLevel) { if(logMINOR) Logger.minor(this, "abortTrustListImport()"); assert(mTrustListImportInProgress); mTrustListImportInProgress = false; mFullScoreComputationNeeded = false; Persistent.checkedRollback(mDB, this, e, logLevel); assert(computeAllScoresWithoutCommit()); // Test rollback. } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR} */ protected void abortTrustListImport(Exception e) { abortTrustListImport(e, Logger.LogLevel.ERROR); } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Finishes the import of the current trust list and performs score computation. * * ATTENTION: In opposite to abortTrustListImport(), which rolls back the transaction, this does NOT commit the transaction. You have to do it! * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> */ protected void finishTrustListImport() { if(logMINOR) Logger.minor(this, "finishTrustListImport()"); if(!mTrustListImportInProgress) { Logger.error(this, "There was no trust list import in progress!"); return; } if(mFullScoreComputationNeeded) { computeAllScoresWithoutCommit(); assert(!mFullScoreComputationNeeded); // It properly clears the flag assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable } else assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked. mTrustListImportInProgress = false; } /** * Updates all trust trees which are affected by the given modified score. * For understanding how score calculation works you should first read {@link #computeAllScoresWithoutCommit()} * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; } * }}}} */ private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) { if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); // We only include the time measurement if we actually do something. // If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included. boolean includeMeasurement = false; final boolean trustWasCreated = (oldTrust == null); final boolean trustWasDeleted = (newTrust == null); final boolean trustWasModified = !trustWasCreated && !trustWasDeleted; if(trustWasCreated && trustWasDeleted) throw new NullPointerException("No old/new trust specified."); if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster()) throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust); if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee()) throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust); // We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values // which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best // rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity // then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because // the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank. if(trustWasDeleted) { mFullScoreComputationNeeded = true; } if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) { includeMeasurement = true; for(OwnIdentity treeOwner : getAllOwnIdentities()) { try { // Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score. if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0) continue; } catch(NotInTrustTreeException e) { continue; } // See explanation above "We cannot iteratively REMOVE an inherited rank..." if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) { mFullScoreComputationNeeded = true; break; } final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>(); unprocessedEdges.add(newTrust); while(!unprocessedEdges.isEmpty()) { final Trust trust = unprocessedEdges.removeFirst(); final Identity trustee = trust.getTrustee(); if(trustee == treeOwner) continue; Score currentStoredTrusteeScore; boolean scoreExistedBefore; try { currentStoredTrusteeScore = getScore(treeOwner, trustee); scoreExistedBefore = true; } catch(NotInTrustTreeException e) { scoreExistedBefore = false; currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0); } final Score oldScore = currentStoredTrusteeScore.clone(); boolean oldShouldFetch = shouldFetchIdentity(trustee); final int newScoreValue = computeScoreValue(treeOwner, trustee); final int newRank = computeRank(treeOwner, trustee); final int newCapacity = computeCapacity(treeOwner, trustee, newRank); final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity); // Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value, // the rank and capacity are always computed based on the trust value of the own identity so we must also check this here: if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank && (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore mFullScoreComputationNeeded = true; break; } if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) { mFullScoreComputationNeeded = true; break; } // We are OK to update it now. We must not update the values of the stored score object before determining whether we need // a full score computation - the full computation needs the old values of the object. currentStoredTrusteeScore.setValue(newScore.getScore()); currentStoredTrusteeScore.setRank(newScore.getRank()); currentStoredTrusteeScore.setCapacity(newScore.getCapacity()); // Identities should not get into the queue if they have no rank, see the large if() about 20 lines below assert(currentStoredTrusteeScore.getRank() >= 0); if(currentStoredTrusteeScore.getRank() >= 0) { currentStoredTrusteeScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(scoreExistedBefore ? oldScore : null, currentStoredTrusteeScore); } // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee); trustee.markForRefetch(); trustee.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(trustee); mFetcher.storeStartFetchCommandWithoutCommit(trustee); } else if(oldShouldFetch && !shouldFetchIdentity(trustee)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee); mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } // If the rank or capacity changed then the trustees might be affected because the could have inherited theirs if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) { // If this identity has no capacity or no rank then it cannot affect its trustees: // (- If it had none and it has none now then there is none which can be inherited, this is obvious) // - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) { // We need to update the trustees of trustee for(Trust givenTrust : getGivenTrusts(trustee)) { unprocessedEdges.add(givenTrust); } } } } if(mFullScoreComputationNeeded) break; } } if(includeMeasurement) { ++mIncrementalScoreRecomputationCount; mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; } if(logMINOR) { final String time = includeMeasurement ? ("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s") : ("Time not measured: Computation was aborted before doing anything."); if(!mFullScoreComputationNeeded) Logger.minor(this, "Incremental computation of all Scores finished. " + time); else Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time); } if(!mTrustListImportInProgress) { if(mFullScoreComputationNeeded) { // TODO: Optimization: This uses very much CPU and memory. Write a partial computation function... // TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT // keep all objects in memory etc. computeAllScoresWithoutCommit(); assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable } else { assert(computeAllScoresWithoutCommit()); // This function worked correctly. } } else { // a trust list import is in progress // We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore // updateScoresWithoutCommit is called often during import of a single trust list // assert(computeAllScoresWithoutCommit()); } } /* Client interface functions */ public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException { try { getIdentityByURI(requestURI); throw new InvalidParameterException("We already have this identity"); } catch(UnknownIdentityException e) { final Identity identity = new Identity(this, requestURI, null, false); + synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e2) { Persistent.checkedRollbackAndThrow(mDB, this, e2); } } + } // The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher. // TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust. Logger.normal(this, "addIdentity(): " + identity); return identity; } } public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME); return createOwnIdentity(keypair[0], nickName, publishTrustList, context); } /** * @param context A context with which you want to use the identity. Null if you want to add it later. */ public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { synchronized(mFetcher) { // For beginTrustListImport()/setTrustWithoutCommit() synchronized(mSubscriptionManager) { // For beginTrustListImport()/setTrustWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { OwnIdentity identity; try { identity = getOwnIdentityByURI(insertURI); throw new InvalidParameterException("The URI you specified is already used by the own identity " + identity.getNickname() + "."); } catch(UnknownIdentityException uie) { identity = new OwnIdentity(this, insertURI, nickName, publishTrustList); if(context != null) identity.addContext(context); if(publishTrustList) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */ identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); initTrustTreeWithoutCommit(identity); beginTrustListImport(); // Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation. mFullScoreComputationNeeded = true; for(String seedURI : SEED_IDENTITIES) { try { setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity."); } catch(UnknownIdentityException e) { Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e); } } finishTrustListImport(); Persistent.checkedCommit(mDB, this); if(mIntroductionClient != null) mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles. if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")"); return identity; } catch(RuntimeException e) { abortTrustListImport(e); // Rolls back for us throw e; // Satisfy the compiler } } } } } } /** * This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}. * * The {@link OwnIdentity} is not deleted because this would be a security issue: * If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target * * @param id The {@link Identity.IdentityID} of the identity. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID. */ public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException { Logger.normal(this, "deleteOwnIdentity(): Starting... "); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { final OwnIdentity oldIdentity = getOwnIdentityByID(id); try { Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity); // We don't need any score computations to happen (explanation will follow below) so we don't need the following: /* beginTrustListImport(); */ // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); final Identity newIdentity; try { newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); } catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } newIdentity.setContexts(oldIdentity.getContexts()); newIdentity.setProperties(oldIdentity.getProperties()); try { newIdentity.setEdition(oldIdentity.getEdition()); } catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen throw new RuntimeException(e); } // In theory we do not need to re-fetch the current trust list edition: // The trust list of an own identity is always stored completely in the database, i.e. all trustees exist. // HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that // the current edition of the old OwndIdentity was not fetched yet. // So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well. if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) { newIdentity.onFetched(oldIdentity.getLastFetchedDate()); } // An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already. newIdentity.storeWithoutCommit(); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust; try { newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // Delete all given scores: // Non-own identities do not assign scores to other identities so we can just delete them. for(Score oldScore : getGivenScores(oldIdentity)) { final Identity trustee = oldScore.getTrustee(); final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee); oldScore.deleteWithoutCommit(); // If the OwnIdentity which we are converting was the only source of trust to the trustee // of this Score value, the should-fetch state of the trustee might change to false. if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) { mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } } assert(getGivenScores(oldIdentity).size() == 0); // Copy all given trusts: // We don't have to use the removeTrust/setTrust functions because the score graph does not need updating: // - To the rating of the converted identity in the score graphs of other own identities it is irrelevant // whether it is an own identity or not. The rating should never depend on whether it is an own identity! // - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted // completely and therefore it does not need to be updated. for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) { Trust newGivenTrust; try { newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(), oldGivenTrust.getValue(), oldGivenTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newGivenTrust.equals(oldGivenTrust)); */ oldGivenTrust.deleteWithoutCommit(); newGivenTrust.storeWithoutCommit(); } mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(newIdentity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, newIdentity); // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } Logger.normal(this, "deleteOwnIdentity(): Finished."); } /** * NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()} */ public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException { Logger.normal(this, "restoreOwnIdentity(): Starting... "); OwnIdentity identity; synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { long edition = 0; try { edition = Math.max(edition, insertFreenetURI.getEdition()); } catch(IllegalStateException e) { // The user supplied URI did not have an edition specified } try { // Try replacing an existing non-own version of the identity with an OwnIdentity Identity oldIdentity = getIdentityByURI(insertFreenetURI); if(oldIdentity instanceof OwnIdentity) throw new InvalidParameterException("There is already an own identity with the given URI pair."); Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity); // Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function. // But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference // implementation will fail if two identities with the same ID exist. // This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph // but we must also store the own version to be able to modify the trust graph. beginTrustListImport(); // We already have fetched this identity as a stranger's one. We need to update the database. identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); /* We re-fetch the most recent edition to make sure all trustees are imported */ edition = Math.max(edition, oldIdentity.getEdition()); identity.restoreEdition(edition, oldIdentity.getLastFetchedDate()); identity.setContexts(oldIdentity.getContexts()); identity.setProperties(oldIdentity.getProperties()); identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); // Nothing has changed about the actual score so we do not notify. // mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, newScore); } assert(getScores(oldIdentity).size() == 0); // What we do NOT have to deal with is the given scores of the old identity: // Given scores do NOT exist for non-own identities, so there are no old ones to update. // Of cause there WILL be scores because it is an own identity now. // They will be created automatically when updating the given trusts // - so thats what we will do now. // Update all given trusts for(Trust givenTrust : getGivenTrusts(oldIdentity)) { // TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could: // - manually delete the old Trust objects from the database // - manually store the new trust objects // - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version // of setTrustWithoutCommit which deals with that. // But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit: // To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make // it only update the parts of the trust graph which are affected. // Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests. removeTrustWithoutCommit(givenTrust); setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); } // We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit // which would re-create scores of the old identity. We later call it AFTER deleting the old identity. /* finishTrustListImport(); */ mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); finishTrustListImport(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); } catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it. identity = new OwnIdentity(this, insertFreenetURI, null, false); Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity); identity.restoreEdition(edition, null); // Store the new identity identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); } mFetcher.storeStartFetchCommandWithoutCommit(identity); // This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { if(mTrustListImportInProgress) { // We don't execute beginTrustListImport() in all code paths of this function abortTrustListImport(e); // Does rollback for us throw e; } else { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } } Logger.normal(this, "restoreOwnIdentity(): Finished."); } public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment) throws UnknownIdentityException, NumberFormatException, InvalidParameterException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); Identity trustee = getIdentityByID(trusteeID); setTrust(truster, trustee, value, comment); } public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); final Identity trustee = getIdentityByID(trusteeID); synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { removeTrustWithoutCommit(truster, trustee); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } /** * Enables or disables the publishing of the trust list of an {@link OwnIdentity}. * The trust list contains all trust values which the OwnIdentity has assigned to other identities. * * @see OwnIdentity#setPublishTrustList(boolean) * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishTrustList Whether to publish the trust list. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given {@link Identity.IdentityID}. */ public synchronized void setPublishTrustList(final String ownIdentityID, final boolean publishTrustList) throws UnknownIdentityException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setPublishTrustList(publishTrustList); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "setPublishTrustList to " + publishTrustList + " for " + identity); } /** * Enables or disables the publishing of {@link IntroductionPuzzle}s for an {@link OwnIdentity}. * * If publishIntroductionPuzzles==true adds, if false removes: * - the context {@link IntroductionPuzzle.INTRODUCTION_CONTEXT} * - the property {@link IntroductionServer.PUZZLE_COUNT_PROPERTY} with the value {@link IntroductionServer.DEFAULT_PUZZLE_COUNT} * * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishIntroductionPuzzles Whether to publish introduction puzzles. * @throws UnknownIdentityException If there is no identity with the given ownIdentityID * @throws InvalidParameterException If {@link OwnIdentity#doesPublishTrustList()} returns false on the selected identity: It doesn't make sense for an identity to allow introduction if it doesn't publish a trust list - the purpose of introduction is to add other identities to your trust list. */ public synchronized void setPublishIntroductionPuzzles(final String ownIdentityID, final boolean publishIntroductionPuzzles) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager if(!identity.doesPublishTrustList()) throw new InvalidParameterException("An identity must publish its trust list if it wants to publish introduction puzzles!"); synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { if(publishIntroductionPuzzles) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } else { identity.removeContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.removeProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY); } mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "Set publishIntroductionPuzzles to " + true + " for " + identity); } public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.addContext(newContext); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeContext(context); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'"); } public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException { return getIdentityByID(identityID).getProperty(property); } public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setProperty(property, value); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeProperty(property); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'"); } public String getVersion() { return Version.getMarketingVersion(); } public long getRealVersion() { return Version.getRealVersion(); } public String getString(String key) { return getBaseL10n().getString(key); } public void setLanguage(LANGUAGE newLanguage) { WebOfTrust.l10n = new PluginL10n(this, newLanguage); if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode); } public PluginRespirator getPluginRespirator() { return mPR; } public ExtObjectContainer getDatabase() { return mDB; } public Configuration getConfig() { return mConfig; } public SubscriptionManager getSubscriptionManager() { return mSubscriptionManager; } public IdentityFetcher getIdentityFetcher() { return mFetcher; } public XMLTransformer getXMLTransformer() { return mXMLTransformer; } public IntroductionPuzzleStore getIntroductionPuzzleStore() { return mPuzzleStore; } public IntroductionClient getIntroductionClient() { return mIntroductionClient; } protected FCPInterface getFCPInterface() { return mFCPInterface; } public RequestClient getRequestClient() { return mRequestClient; } /** * This is where our L10n files are stored. * @return Path of our L10n files. */ public String getL10nFilesBasePath() { return "plugins/WebOfTrust/l10n/"; } /** * This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ... * @return Mask of the L10n files. */ public String getL10nFilesMask() { return "lang_${lang}.l10n"; } /** * Override L10n files are stored on the disk, their names should be explicit * we put here the plugin name, and the "override" indication. Plugin L10n * override is not implemented in the node yet. * @return Mask of the override L10n files. */ public String getL10nOverrideFilesMask() { return "WebOfTrust_lang_${lang}.override.l10n"; } /** * Get the ClassLoader of this plugin. This is necessary when getting * resources inside the plugin's Jar, for example L10n files. * @return ClassLoader object */ public ClassLoader getPluginClassLoader() { return WebOfTrust.class.getClassLoader(); } /** * Access to the current L10n data. * * @return L10n object. */ public BaseL10n getBaseL10n() { return WebOfTrust.l10n.getBase(); } public int getNumberOfFullScoreRecomputations() { return mFullScoreRecomputationCount; } public synchronized double getAverageFullScoreRecomputationTime() { return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000); } public int getNumberOfIncrementalScoreRecomputations() { return mIncrementalScoreRecomputationCount; } public synchronized double getAverageIncrementalScoreRecomputationTime() { return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000); } /** * Tests whether two WoT are equal. * This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests. */ public synchronized boolean equals(Object obj) { if(obj == this) return true; if(!(obj instanceof WebOfTrust)) return false; WebOfTrust other = (WebOfTrust)obj; synchronized(other) { { // Compare own identities final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities(); if(allIdentities.size() != other.getAllOwnIdentities().size()) return false; for(OwnIdentity identity : allIdentities) { try { if(!identity.equals(other.getOwnIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare identities final ObjectSet<Identity> allIdentities = getAllIdentities(); if(allIdentities.size() != other.getAllIdentities().size()) return false; for(Identity identity : allIdentities) { try { if(!identity.equals(other.getIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare trusts final ObjectSet<Trust> allTrusts = getAllTrusts(); if(allTrusts.size() != other.getAllTrusts().size()) return false; for(Trust trust : allTrusts) { try { Identity otherTruster = other.getIdentityByID(trust.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID()); if(!trust.equals(other.getTrust(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotTrustedException e) { return false; } } } { // Compare scores final ObjectSet<Score> allScores = getAllScores(); if(allScores.size() != other.getAllScores().size()) return false; for(Score score : allScores) { try { OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID()); if(!score.equals(other.getScore(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotInTrustTreeException e) { return false; } } } } return true; } }
false
true
private synchronized void deleteDuplicateObjects() { synchronized(mPuzzleStore) { // Needed for deleteWithoutCommit(Identity) synchronized(mFetcher) { // Needed for deleteWithoutCommit(Identity) synchronized(mSubscriptionManager) { // Needed for deleteWithoutCommit(Identity) synchronized(Persistent.transactionLock(mDB)) { try { HashSet<String> deleted = new HashSet<String>(); if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ..."); for(Identity identity : getAllIdentities()) { Query q = mDB.query(); q.constrain(Identity.class); q.descend("mID").constrain(identity.getID()); q.constrain(identity).identity().not(); ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q); for(Identity duplicate : duplicates) { if(deleted.contains(duplicate.getID()) == false) { Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI()); deleteWithoutCommit(duplicate); Persistent.checkedCommit(mDB, this); } } deleted.add(identity.getID()); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { } // synchronized(mPuzzleStore) { // synchronized(this) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ..."); boolean duplicateTrustFound = false; for(OwnIdentity truster : getAllOwnIdentities()) { HashSet<String> givenTo = new HashSet<String>(); for(Trust trust : getGivenTrusts(truster)) { if(givenTo.contains(trust.getTrustee().getID()) == false) givenTo.add(trust.getTrustee().getID()); else { Logger.error(this, "Deleting duplicate given trust:" + trust); removeTrustWithoutCommit(trust); duplicateTrustFound = true; } } } if(duplicateTrustFound) { computeAllScoresWithoutCommit(); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { /* TODO: Also delete duplicate score */ } /** * Debug function for deleting trusts or scores of which one of the involved partners is missing. */ private synchronized void deleteOrphanObjects() { // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanTrustFound = false; Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q); for(Trust trust : orphanTrusts) { if(trust.getTruster() != null && trust.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust); continue; } Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee()); orphanTrustFound = true; trust.deleteWithoutCommit(); // No need to update subscriptions as the trust is broken anyway. } if(orphanTrustFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanScoresFound = false; Query q = mDB.query(); q.constrain(Score.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q); for(Score score : orphanScores) { if(score.getTruster() != null && score.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score); continue; } Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee()); orphanScoresFound = true; score.deleteWithoutCommit(); // No need to update subscriptions as the score is broken anyway. } if(orphanScoresFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } /** * Warning: This function is not synchronized, use it only in single threaded mode. * @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist. */ @SuppressWarnings("deprecation") private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) { final Query query = database.query(); query.constrain(Configuration.class); @SuppressWarnings("unchecked") ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute(); switch(result.size()) { case 1: { final Configuration config = (Configuration)result.next(); config.initializeTransient(wot, database); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); return config.getDatabaseFormatVersion(); } default: return -1; } } /** * Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists. * @return The config object. */ private synchronized Configuration getOrCreateConfig() { final Query query = mDB.query(); query.constrain(Configuration.class); final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query); switch(result.size()) { case 1: { final Configuration config = result.next(); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); config.setDefaultValues(false); config.storeAndCommit(); return config; } case 0: { final Configuration config = new Configuration(this); config.initializeTransient(this); config.storeAndCommit(); return config; } default: throw new RuntimeException("Multiple config objects found: " + result.size()); } } /** Capacity is the maximum amount of points an identity can give to an other by trusting it. * * Values choice : * Advogato Trust metric recommends that values decrease by rounded 2.5 times. * This makes sense, making the need of 3 N+1 ranked people to overpower * the trust given by a N ranked identity. * * Number of ranks choice : * When someone creates a fresh identity, he gets the seed identity at * rank 1 and freenet developpers at rank 2. That means that * he will see people that were : * - given 7 trust by freenet devs (rank 2) * - given 17 trust by rank 3 * - given 50 trust by rank 4 * - given 100 trust by rank 5 and above. * This makes the range small enough to avoid a newbie * to even see spam, and large enough to make him see a reasonnable part * of the community right out-of-the-box. * Of course, as soon as he will start to give trust, he will put more * people at rank 1 and enlarge his WoT. */ protected static final int capacities[] = { 100,// Rank 0 : Own identities 40, // Rank 1 : Identities directly trusted by ownIdenties 16, // Rank 2 : Identities trusted by rank 1 identities 6, // So on... 2, 1 // Every identity above rank 5 can give 1 point }; // Identities with negative score have zero capacity /** * Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much * trust points an identity can add to the score of identities which it has assigned trust values to. * The higher the rank of an identity, the less is it's capacity. * * If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less * than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0. * * If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value: * The decision of the truster should always overpower the view of remote identities. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed * @param trustee The {@link Identity} of which the capacity shall be computed. * @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust, * - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view. */ private int computeCapacity(OwnIdentity truster, Identity trustee, int rank) { if(truster == trustee) return 100; try { // FIXME: The comment "Security check, if rank computation breaks this will hit." below sounds like we don't actually // need to execute this because the callers probably do it implicitly. Check if this is true and if yes, convert it to an assert. if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit. assert(rank == Integer.MAX_VALUE); return 0; } } catch(NotTrustedException e) { } if(rank == -1 || rank == Integer.MAX_VALUE) return 0; return (rank < capacities.length) ? capacities[rank] : 1; } /** * Reference-implementation of score computation. This means:<br /> * - It is not used by the real WoT code because its slow<br /> * - It is used by unit tests (and WoT) to check whether the real implementation works<br /> * - It is the function which you should read if you want to understand how WoT works.<br /> * * Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br /> * * There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br /> * * Further, rank values are shortest paths and the path-finding algorithm is not executed from the source * to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path. * Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database * and affect many others. So it is useful to have this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * </code> * * @return True if all stored scores were correct. False if there were any errors in stored scores. */ protected boolean computeAllScoresWithoutCommit() { if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); boolean returnValue = true; final ObjectSet<Identity> allIdentities = getAllIdentities(); // Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity. for(OwnIdentity treeOwner : getAllOwnIdentities()) { // At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner. // An identity is visible if there is a trust chain from the owner to it. // The rank is the distance in trust steps from the treeOwner. // So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on. final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2); // Compute the rank values { // For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters. // The inner loop then pulls out one unprocessed identity and computes the rank of its trustees: // All trustees which have received positive (> 0) trust will get his rank + 1 // Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE. // Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all. // Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none. // // Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value: // The decision of the own identity shall not be overpowered by the view of the remote identities. // // The purpose of differentiation between Integer.MAX_VALUE and -1 is: // Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing // them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and // have a way of telling the user "this identity is not trusted" by keeping a score object of them. // Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where // we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank // - and we never import their trust lists. // We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved // introduction puzzles cannot inherit their rank to their trustees. final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>(); // The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE try { Score selfScore = getScore(treeOwner, treeOwner); if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one rankValues.put(treeOwner, selfScore.getRank()); unprocessedTrusters.addLast(treeOwner); } else { rankValues.put(treeOwner, null); } } catch(NotInTrustTreeException e) { // This only happens in unit tests. } while(!unprocessedTrusters.isEmpty()) { final Identity truster = unprocessedTrusters.removeFirst(); final Integer trusterRank = rankValues.get(truster); // The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all. if(trusterRank == null || trusterRank == Integer.MAX_VALUE) { // (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security) continue; } final int trusteeRank = trusterRank + 1; for(Trust trust : getGivenTrusts(truster)) { final Identity trustee = trust.getTrustee(); final Integer oldTrusteeRank = rankValues.get(trustee); if(oldTrusteeRank == null) { // The trustee was not processed yet if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } else rankValues.put(trustee, Integer.MAX_VALUE); } else { // Breadth first search will process all rank one identities are processed before any rank two identities, etc. assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank); if(oldTrusteeRank == Integer.MAX_VALUE) { // If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not // given by the tree owner. try { final Trust treeOwnerTrust = getTrust(treeOwner, trustee); assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct? } catch(NotTrustedException e) { if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } } } } } } } // Rank values of all visible identities are computed now. // Next step is to compute the scores of all identities for(Identity target : allIdentities) { // The score of an identity is the sum of all weighted trust values it has received. // Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank. Integer targetScore; final Integer targetRank = rankValues.get(target); if(targetRank == null) { targetScore = null; } else { // The treeOwner trusts himself. if(targetRank == 0) { targetScore = Integer.MAX_VALUE; } else { // If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score. try { targetScore = (int)getTrust(treeOwner, target).getValue(); } catch(NotTrustedException e) { targetScore = 0; for(Trust receivedTrust : getReceivedTrusts(target)) { final Identity truster = receivedTrust.getTruster(); final Integer trusterRank = rankValues.get(truster); // The capacity is a weight function for trust values which are given from an identity: // The higher the rank, the less the capacity. // If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0. final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1); targetScore += (receivedTrust.getValue() * capacity) / 100; } } } } Score newScore = null; if(targetScore != null) { newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank)); } boolean needToCheckFetchStatus = false; boolean oldShouldFetch = false; int oldCapacity = 0; // Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct. try { Score currentStoredScore = getScore(treeOwner, target); oldCapacity = currentStoredScore.getCapacity(); if(newScore == null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(currentStoredScore, null); } else { if(!newScore.equals(currentStoredScore)) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); final Score oldScore = currentStoredScore.clone(); currentStoredScore.setRank(newScore.getRank()); currentStoredScore.setCapacity(newScore.getCapacity()); currentStoredScore.setValue(newScore.getScore()); currentStoredScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, currentStoredScore); } } } catch(NotInTrustTreeException e) { oldCapacity = 0; if(newScore != null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); newScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, newScore); } } if(needToCheckFetchStatus) { // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target); target.markForRefetch(); target.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(target); mFetcher.storeStartFetchCommandWithoutCommit(target); } else if(oldShouldFetch && !shouldFetchIdentity(target)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target); mFetcher.storeAbortFetchCommandWithoutCommit(target); } } } } mFullScoreComputationNeeded = false; ++mFullScoreRecomputationCount; mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; if(logMINOR) { Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s"); } return returnValue; } private synchronized void createSeedIdentities() { synchronized(mSubscriptionManager) { for(String seedURI : SEED_IDENTITIES) { synchronized(Persistent.transactionLock(mDB)) { try { final Identity existingSeed = getIdentityByURI(seedURI); final Identity oldExistingSeed = existingSeed.clone(); // For the SubscriptionManager if(existingSeed instanceof OwnIdentity) { final OwnIdentity ownExistingSeed = (OwnIdentity)existingSeed; ownExistingSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); ownExistingSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT)); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, ownExistingSeed); ownExistingSeed.storeAndCommit(); } else { try { existingSeed.setEdition(new FreenetURI(seedURI).getEdition()); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, existingSeed); existingSeed.storeAndCommit(); } catch(InvalidParameterException e) { /* We already have the latest edition stored */ } } } catch (UnknownIdentityException uie) { try { final Identity newSeed = new Identity(this, seedURI, null, true); // We have to explicitly set the edition number because the constructor only considers the given edition as a hint. newSeed.setEdition(new FreenetURI(seedURI).getEdition()); newSeed.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, newSeed); Persistent.checkedCommit(mDB, this); } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } public void terminate() { Logger.normal(this, "Web Of Trust plugin terminating ..."); /* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */ try { if(mWebInterface != null) this.mWebInterface.unload(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionClient != null) mIntroductionClient.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionServer != null) mIntroductionServer.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mInserter != null) mInserter.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mFetcher != null) mFetcher.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mSubscriptionManager != null) mSubscriptionManager.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mDB != null) { /* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending. * If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction. * - All transactions should be committed after obtaining the lock() on the database. */ synchronized(Persistent.transactionLock(mDB)) { System.gc(); mDB.rollback(); System.gc(); mDB.close(); } } } catch(Exception e) { Logger.error(this, "Error during termination.", e); } Logger.normal(this, "Web Of Trust plugin terminated."); } /** * Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>. */ public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { mFCPInterface.handle(replysender, params, data, accesstype); } /** * Loads an own or normal identity from the database, querying on its ID. * * @param id The ID of the identity to load * @return The identity matching the supplied ID. * @throws DuplicateIdentityException if there are more than one identity with this id in the database * @throws UnknownIdentityException if there is no identity with this id in the database */ public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(Identity.class); query.descend("mID").constrain(id); final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Gets an OwnIdentity by its ID. * * @param id The unique identifier to query an OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if there is now OwnIdentity with that id */ public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(OwnIdentity.class); query.descend("mID").constrain(id); final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI}) * * @param uri The requestURI of the identity * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database */ public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Loads an identity from the database, querying on its requestURI (as String) * * @param uri The requestURI of the identity which will be converted to {@link FreenetURI} * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database * @throws MalformedURLException if the requestURI isn't a valid FreenetURI */ public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getIdentityByURI(new FreenetURI(uri)); } /** * Gets an OwnIdentity by its requestURI (a {@link FreenetURI}). * The OwnIdentity's unique identifier is extracted from the supplied requestURI. * * @param uri The requestURI of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database */ public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Gets an OwnIdentity by its requestURI (as String). * The given String is converted to {@link FreenetURI} in order to extract a unique id. * * @param uri The requestURI (as String) of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database * @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI */ public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getOwnIdentityByURI(new FreenetURI(uri)); } /** * Returns all identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database */ public ObjectSet<Identity> getAllIdentities() { final Query query = mDB.query(); query.constrain(Identity.class); return new Persistent.InitializingObjectSet<Identity>(this, query); } public static enum SortOrder { ByNicknameAscending, ByNicknameDescending, ByScoreAscending, ByScoreDescending, ByLocalTrustAscending, ByLocalTrustDescending } /** * Get a filtered and sorted list of identities. * You have to synchronize on this WoT when calling the function and processing the returned list. */ public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) { Query q = mDB.query(); switch(sortInstruction) { case ByNicknameAscending: q.constrain(Identity.class); q.descend("mNickname").orderAscending(); break; case ByNicknameDescending: q.constrain(Identity.class); q.descend("mNickname").orderDescending(); break; case ByScoreAscending: q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByScoreDescending: // TODO: This excludes identities which have no score q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; case ByLocalTrustAscending: q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByLocalTrustDescending: // TODO: This excludes untrusted identities. q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; } if(nickFilter != null) { nickFilter = nickFilter.trim(); if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like(); } return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database. * * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Identity> getAllNonOwnIdentities() { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently * modified identities will be at the beginning of the list. * * You have to synchronize on this WoT when calling the function and processing the returned list! * * Used by the IntroductionClient for fetching puzzles from recently modified identities. */ public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); /* TODO: As soon as identities announce that they were online every day, uncomment the following line */ /* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */ q.descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all own identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database. */ public ObjectSet<OwnIdentity> getAllOwnIdentities() { final Query q = mDB.query(); q.constrain(OwnIdentity.class); return new Persistent.InitializingObjectSet<OwnIdentity>(this, q); } /** * DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST! * IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS: * - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will. * - Especially it might be an information leak if the trust values of other OwnIdentities are deleted! * - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption. * * The intended purpose of this function is: * - To specify which objects have to be dealt with when messing with storage of an identity. * - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them. * However, the implementations of those functions might cause leaks by forgetting to delete certain object members. * If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty. * You then can check whether the database actually IS empty to test for leakage. * * You have to lock the WebOfTrust, the IntroductionPuzzleStore, the IdentityFetcher and the SubscriptionManager before calling this function. */ private void deleteWithoutCommit(Identity identity) { // We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport. // If the caller already handles that for us though, we should not call those function again. // So we check whether the caller already started an import. boolean trustListImportWasInProgress = mTrustListImportInProgress; try { if(!trustListImportWasInProgress) beginTrustListImport(); if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ..."); if(logDEBUG) Logger.debug(this, "Deleting received scores..."); for(Score score : getScores(identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } if(identity instanceof OwnIdentity) { if(logDEBUG) Logger.debug(this, "Deleting given scores..."); for(Score score : getGivenScores((OwnIdentity)identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } } if(logDEBUG) Logger.debug(this, "Deleting received trusts..."); for(Trust trust : getReceivedTrusts(identity)) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); } if(logDEBUG) Logger.debug(this, "Deleting given trusts..."); for(Trust givenTrust : getGivenTrusts(identity)) { givenTrust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(givenTrust, null); // We call computeAllScores anyway so we do not use removeTrustWithoutCommit() } mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us. if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ..."); mPuzzleStore.onIdentityDeletion(identity); if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command..."); if(mFetcher != null) { // Can be null if we use this function in upgradeDB() mFetcher.storeAbortFetchCommandWithoutCommit(identity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. } if(logDEBUG) Logger.debug(this, "Deleting the identity..."); identity.deleteWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(identity, null); if(!trustListImportWasInProgress) finishTrustListImport(); } catch(RuntimeException e) { if(!trustListImportWasInProgress) abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * Gets the score of this identity in a trust tree. * Each {@link OwnIdentity} has its own trust tree. * * @param truster The owner of the trust tree * @return The {@link Score} of this Identity in the required trust tree * @throws NotInTrustTreeException if this identity is not in the required trust tree */ public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mID").constrain(new ScoreID(truster, trustee).toString()); final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query); switch(result.size()) { case 1: final Score score = result.next(); assert(score.getTruster() == truster); assert(score.getTrustee() == trustee); return score; case 0: throw new NotInTrustTreeException(truster, trustee); default: throw new DuplicateScoreException(truster, trustee, result.size()); } } /** * Gets a list of all this Identity's Scores. * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * * @return An {@link ObjectSet} containing all {@link Score} this Identity has. */ public ObjectSet<Score> getScores(final Identity identity) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTrustee").constrain(identity).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Get a list of all scores which the passed own identity has assigned to other identities. * * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * @return An {@link ObjectSet} containing all {@link Score} this Identity has given. */ public ObjectSet<Score> getGivenScores(final OwnIdentity truster) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets the best score this Identity has in existing trust trees. * * @return the best score this Identity has * @throws NotInTrustTreeException If the identity has no score in any trusttree. */ public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException { int bestScore = Integer.MIN_VALUE; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestScore = Math.max(score.getScore(), bestScore); return bestScore; } /** * Gets the best capacity this identity has in any trust tree. * @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0. */ public synchronized int getBestCapacity(final Identity identity) throws NotInTrustTreeException { int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestCapacity = Math.max(score.getCapacity(), bestCapacity); return bestCapacity; } /** * Get all scores in the database. * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Score> getAllScores() { final Query query = mDB.query(); query.constrain(Score.class); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Checks whether the given identity should be downloaded. * * Synchronization: You must synchronize on this WebOfTrust when using this function. * * @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity. */ private boolean shouldFetchIdentity(final Identity identity) { if(identity instanceof OwnIdentity) return true; int bestScore = Integer.MIN_VALUE; int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) return false; // TODO: Cache the best score of an identity as a member variable. for(Score score : scores) { bestCapacity = Math.max(score.getCapacity(), bestCapacity); bestScore = Math.max(score.getScore(), bestScore); if(bestCapacity > 0 || bestScore >= 0) return true; } return false; } /** * Gets non-own Identities matching a specified score criteria. * TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The owner of the trust tree, null if you want the trusted identities of all owners. * @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0 * and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0. * @return an {@link ObjectSet} containing Scores of the identities that match the criteria */ public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) { final Query query = mDB.query(); query.constrain(Score.class); if(truster != null) query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").constrain(OwnIdentity.class).not(); /* We include 0 in the list of identities with positive score because solving captchas gives no points to score */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets {@link Trust} from a specified truster to a specified trustee. * * @param truster The identity that gives trust to this Identity * @param trustee The identity which receives the trust * @return The trust given to the trustee by the specified truster * @throws NotTrustedException if the truster doesn't trust the trustee */ public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mID").constrain(new TrustID(truster, trustee).toString()); final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query); switch(result.size()) { case 1: final Trust trust = result.next(); assert(trust.getTruster() == truster); assert(trust.getTrustee() == trustee); return trust; case 0: throw new NotTrustedException(truster, trustee); default: throw new DuplicateTrustException(truster, trustee, result.size()); } } /** * Gets all trusts given by the given truster. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster. * The result is sorted descending by the time we last fetched the trusted identity. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets given trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The identity which given the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster in a trust list with a different edition than the passed in one. * You have to synchronize on this WoT when calling the function and processing the returned list! */ protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) { final Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mTrusterTrustListEdition").constrain(edition).not(); return new Persistent.InitializingObjectSet<Trust>(this, q); } /** * Gets all trusts received by the given trustee. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets received trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param trustee The identity which has received the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getAllTrusts() { final Query query = mDB.query(); query.constrain(Trust.class); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gives some {@link Trust} to another Identity. * It creates or updates an existing Trust object and make the trustee compute its {@link Score}. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * * @param truster The Identity that gives the trust * @param trustee The Identity that receives the trust * @param newValue Numeric value of the trust * @param newComment A comment to explain the given value * @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values. */ protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { try { // Check if we are updating an existing trust value final Trust trust = getTrust(truster, trustee); final Trust oldTrust = trust.clone(); trust.trusterEditionUpdated(); trust.setComment(newComment); trust.storeWithoutCommit(); if(trust.getValue() != newValue) { trust.setValue(newValue); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(oldTrust, trust); if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(oldTrust, trust); } } catch (NotTrustedException e) { final Trust trust = new Trust(this, truster, trustee, newValue, newComment); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(null, trust); if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(null, trust); } truster.updated(); truster.storeWithoutCommit(); // TODO: Mabye notify clients about this. IMHO it would create too much notifications on trust list import so we don't. // As soon as we have notification-coalescing we might do it. // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(truster); } /** * Only for being used by WoT internally and by unit tests! * * You have to synchronize on this WebOfTrust while querying the parameter identities and calling this function. */ void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { setTrustWithoutCommit(truster, trustee, newValue, newComment); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } /** * Deletes a trust object. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * * @param truster * @param trustee */ protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) { try { try { removeTrustWithoutCommit(getTrust(truster, trustee)); } catch (NotTrustedException e) { Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname()); } } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * */ protected void removeTrustWithoutCommit(Trust trust) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); updateScoresWithoutCommit(trust, null); } /** * Initializes this OwnIdentity's trust tree without commiting the transaction. * Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities. * * The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }} * * @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen) */ private void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException { try { getScore(identity, identity); Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity); return; } catch (NotInTrustTreeException e) { final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100); score.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, score); } } /** * Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified * trust tree. * * Synchronization: * You have to synchronize on this WebOfTrust object when using this function. * * @param truster The OwnIdentity that owns the trust tree * @param trustee The identity for which the score shall be computed. * @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster. * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return Integer.MAX_VALUE; int value = 0; try { return getTrust(truster, trustee).getValue(); } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { final Score trusterScore = getScore(truster, trust.getTruster()); value += ( trust.getValue() * trusterScore.getCapacity() ) / 100; } catch (NotInTrustTreeException e) {} } return value; } /** * Computes the trustees's rank in the trust tree of the truster. * It gets its best ranked non-zero-capacity truster's rank, plus one. * If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite). * If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1. * * If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the * tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision). * * The purpose of differentiation between Integer.MAX_VALUE and -1 is: * Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them * in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the * user "this identity is not trusted" by keeping a score object of them. * Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we * hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and * we never download their trust lists. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * Synchronization: * You have to synchronize on this WebOfTrust object when using this function. * * @param truster The OwnIdentity that owns the trust tree * @return The new Rank if this Identity * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return 0; int rank = -1; try { Trust treeOwnerTrust = getTrust(truster, trustee); if(treeOwnerTrust.getValue() > 0) return 1; else return Integer.MAX_VALUE; } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { Score score = getScore(truster, trust.getTruster()); if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank // A truster only gives his rank to a trustee if he has assigned a strictly positive trust value if(trust.getValue() > 0 ) { // We give the rank to the trustee if it is better than its current rank or he has no rank yet. if(rank == -1 || score.getRank() < rank) rank = score.getRank(); } else { // If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster. if(rank == -1) rank = Integer.MAX_VALUE; } } } catch (NotInTrustTreeException e) {} } if(rank == -1) return -1; else if(rank == Integer.MAX_VALUE) return Integer.MAX_VALUE; else return rank+1; } /** * Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress. * This speeds up setTrust/removeTrust as the score calculation is only performed when {@link #finishTrustListImport()} is called. * * ATTENTION: Always take care to call one of {@link #finishTrustListImport()} / {@link #abortTrustListImport(Exception)} / {@link #abortTrustListImport(Exception, LogLevel)} * for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> */ protected void beginTrustListImport() { if(logMINOR) Logger.minor(this, "beginTrustListImport()"); if(mTrustListImportInProgress) { abortTrustListImport(new RuntimeException("There was already a trust list import in progress!")); mFullScoreComputationNeeded = true; computeAllScoresWithoutCommit(); assert(mFullScoreComputationNeeded == false); } mTrustListImportInProgress = true; assert(!mFullScoreComputationNeeded); assert(computeAllScoresWithoutCommit()); // The database is intact before the import } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e, Logger.LogLevel.ERROR); // Does checkedRollback() for you already } * }}}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file. * @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file. */ protected void abortTrustListImport(Exception e, LogLevel logLevel) { if(logMINOR) Logger.minor(this, "abortTrustListImport()"); assert(mTrustListImportInProgress); mTrustListImportInProgress = false; mFullScoreComputationNeeded = false; Persistent.checkedRollback(mDB, this, e, logLevel); assert(computeAllScoresWithoutCommit()); // Test rollback. } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR} */ protected void abortTrustListImport(Exception e) { abortTrustListImport(e, Logger.LogLevel.ERROR); } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Finishes the import of the current trust list and performs score computation. * * ATTENTION: In opposite to abortTrustListImport(), which rolls back the transaction, this does NOT commit the transaction. You have to do it! * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> */ protected void finishTrustListImport() { if(logMINOR) Logger.minor(this, "finishTrustListImport()"); if(!mTrustListImportInProgress) { Logger.error(this, "There was no trust list import in progress!"); return; } if(mFullScoreComputationNeeded) { computeAllScoresWithoutCommit(); assert(!mFullScoreComputationNeeded); // It properly clears the flag assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable } else assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked. mTrustListImportInProgress = false; } /** * Updates all trust trees which are affected by the given modified score. * For understanding how score calculation works you should first read {@link #computeAllScoresWithoutCommit()} * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; } * }}}} */ private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) { if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); // We only include the time measurement if we actually do something. // If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included. boolean includeMeasurement = false; final boolean trustWasCreated = (oldTrust == null); final boolean trustWasDeleted = (newTrust == null); final boolean trustWasModified = !trustWasCreated && !trustWasDeleted; if(trustWasCreated && trustWasDeleted) throw new NullPointerException("No old/new trust specified."); if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster()) throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust); if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee()) throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust); // We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values // which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best // rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity // then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because // the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank. if(trustWasDeleted) { mFullScoreComputationNeeded = true; } if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) { includeMeasurement = true; for(OwnIdentity treeOwner : getAllOwnIdentities()) { try { // Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score. if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0) continue; } catch(NotInTrustTreeException e) { continue; } // See explanation above "We cannot iteratively REMOVE an inherited rank..." if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) { mFullScoreComputationNeeded = true; break; } final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>(); unprocessedEdges.add(newTrust); while(!unprocessedEdges.isEmpty()) { final Trust trust = unprocessedEdges.removeFirst(); final Identity trustee = trust.getTrustee(); if(trustee == treeOwner) continue; Score currentStoredTrusteeScore; boolean scoreExistedBefore; try { currentStoredTrusteeScore = getScore(treeOwner, trustee); scoreExistedBefore = true; } catch(NotInTrustTreeException e) { scoreExistedBefore = false; currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0); } final Score oldScore = currentStoredTrusteeScore.clone(); boolean oldShouldFetch = shouldFetchIdentity(trustee); final int newScoreValue = computeScoreValue(treeOwner, trustee); final int newRank = computeRank(treeOwner, trustee); final int newCapacity = computeCapacity(treeOwner, trustee, newRank); final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity); // Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value, // the rank and capacity are always computed based on the trust value of the own identity so we must also check this here: if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank && (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore mFullScoreComputationNeeded = true; break; } if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) { mFullScoreComputationNeeded = true; break; } // We are OK to update it now. We must not update the values of the stored score object before determining whether we need // a full score computation - the full computation needs the old values of the object. currentStoredTrusteeScore.setValue(newScore.getScore()); currentStoredTrusteeScore.setRank(newScore.getRank()); currentStoredTrusteeScore.setCapacity(newScore.getCapacity()); // Identities should not get into the queue if they have no rank, see the large if() about 20 lines below assert(currentStoredTrusteeScore.getRank() >= 0); if(currentStoredTrusteeScore.getRank() >= 0) { currentStoredTrusteeScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(scoreExistedBefore ? oldScore : null, currentStoredTrusteeScore); } // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee); trustee.markForRefetch(); trustee.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(trustee); mFetcher.storeStartFetchCommandWithoutCommit(trustee); } else if(oldShouldFetch && !shouldFetchIdentity(trustee)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee); mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } // If the rank or capacity changed then the trustees might be affected because the could have inherited theirs if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) { // If this identity has no capacity or no rank then it cannot affect its trustees: // (- If it had none and it has none now then there is none which can be inherited, this is obvious) // - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) { // We need to update the trustees of trustee for(Trust givenTrust : getGivenTrusts(trustee)) { unprocessedEdges.add(givenTrust); } } } } if(mFullScoreComputationNeeded) break; } } if(includeMeasurement) { ++mIncrementalScoreRecomputationCount; mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; } if(logMINOR) { final String time = includeMeasurement ? ("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s") : ("Time not measured: Computation was aborted before doing anything."); if(!mFullScoreComputationNeeded) Logger.minor(this, "Incremental computation of all Scores finished. " + time); else Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time); } if(!mTrustListImportInProgress) { if(mFullScoreComputationNeeded) { // TODO: Optimization: This uses very much CPU and memory. Write a partial computation function... // TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT // keep all objects in memory etc. computeAllScoresWithoutCommit(); assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable } else { assert(computeAllScoresWithoutCommit()); // This function worked correctly. } } else { // a trust list import is in progress // We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore // updateScoresWithoutCommit is called often during import of a single trust list // assert(computeAllScoresWithoutCommit()); } } /* Client interface functions */ public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException { try { getIdentityByURI(requestURI); throw new InvalidParameterException("We already have this identity"); } catch(UnknownIdentityException e) { final Identity identity = new Identity(this, requestURI, null, false); synchronized(Persistent.transactionLock(mDB)) { try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e2) { Persistent.checkedRollbackAndThrow(mDB, this, e2); } } // The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher. // TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust. Logger.normal(this, "addIdentity(): " + identity); return identity; } } public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME); return createOwnIdentity(keypair[0], nickName, publishTrustList, context); } /** * @param context A context with which you want to use the identity. Null if you want to add it later. */ public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { synchronized(mFetcher) { // For beginTrustListImport()/setTrustWithoutCommit() synchronized(mSubscriptionManager) { // For beginTrustListImport()/setTrustWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { OwnIdentity identity; try { identity = getOwnIdentityByURI(insertURI); throw new InvalidParameterException("The URI you specified is already used by the own identity " + identity.getNickname() + "."); } catch(UnknownIdentityException uie) { identity = new OwnIdentity(this, insertURI, nickName, publishTrustList); if(context != null) identity.addContext(context); if(publishTrustList) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */ identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); initTrustTreeWithoutCommit(identity); beginTrustListImport(); // Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation. mFullScoreComputationNeeded = true; for(String seedURI : SEED_IDENTITIES) { try { setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity."); } catch(UnknownIdentityException e) { Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e); } } finishTrustListImport(); Persistent.checkedCommit(mDB, this); if(mIntroductionClient != null) mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles. if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")"); return identity; } catch(RuntimeException e) { abortTrustListImport(e); // Rolls back for us throw e; // Satisfy the compiler } } } } } } /** * This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}. * * The {@link OwnIdentity} is not deleted because this would be a security issue: * If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target * * @param id The {@link Identity.IdentityID} of the identity. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID. */ public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException { Logger.normal(this, "deleteOwnIdentity(): Starting... "); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { final OwnIdentity oldIdentity = getOwnIdentityByID(id); try { Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity); // We don't need any score computations to happen (explanation will follow below) so we don't need the following: /* beginTrustListImport(); */ // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); final Identity newIdentity; try { newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); } catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } newIdentity.setContexts(oldIdentity.getContexts()); newIdentity.setProperties(oldIdentity.getProperties()); try { newIdentity.setEdition(oldIdentity.getEdition()); } catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen throw new RuntimeException(e); } // In theory we do not need to re-fetch the current trust list edition: // The trust list of an own identity is always stored completely in the database, i.e. all trustees exist. // HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that // the current edition of the old OwndIdentity was not fetched yet. // So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well. if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) { newIdentity.onFetched(oldIdentity.getLastFetchedDate()); } // An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already. newIdentity.storeWithoutCommit(); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust; try { newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // Delete all given scores: // Non-own identities do not assign scores to other identities so we can just delete them. for(Score oldScore : getGivenScores(oldIdentity)) { final Identity trustee = oldScore.getTrustee(); final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee); oldScore.deleteWithoutCommit(); // If the OwnIdentity which we are converting was the only source of trust to the trustee // of this Score value, the should-fetch state of the trustee might change to false. if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) { mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } } assert(getGivenScores(oldIdentity).size() == 0); // Copy all given trusts: // We don't have to use the removeTrust/setTrust functions because the score graph does not need updating: // - To the rating of the converted identity in the score graphs of other own identities it is irrelevant // whether it is an own identity or not. The rating should never depend on whether it is an own identity! // - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted // completely and therefore it does not need to be updated. for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) { Trust newGivenTrust; try { newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(), oldGivenTrust.getValue(), oldGivenTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newGivenTrust.equals(oldGivenTrust)); */ oldGivenTrust.deleteWithoutCommit(); newGivenTrust.storeWithoutCommit(); } mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(newIdentity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, newIdentity); // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } Logger.normal(this, "deleteOwnIdentity(): Finished."); } /** * NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()} */ public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException { Logger.normal(this, "restoreOwnIdentity(): Starting... "); OwnIdentity identity; synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { long edition = 0; try { edition = Math.max(edition, insertFreenetURI.getEdition()); } catch(IllegalStateException e) { // The user supplied URI did not have an edition specified } try { // Try replacing an existing non-own version of the identity with an OwnIdentity Identity oldIdentity = getIdentityByURI(insertFreenetURI); if(oldIdentity instanceof OwnIdentity) throw new InvalidParameterException("There is already an own identity with the given URI pair."); Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity); // Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function. // But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference // implementation will fail if two identities with the same ID exist. // This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph // but we must also store the own version to be able to modify the trust graph. beginTrustListImport(); // We already have fetched this identity as a stranger's one. We need to update the database. identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); /* We re-fetch the most recent edition to make sure all trustees are imported */ edition = Math.max(edition, oldIdentity.getEdition()); identity.restoreEdition(edition, oldIdentity.getLastFetchedDate()); identity.setContexts(oldIdentity.getContexts()); identity.setProperties(oldIdentity.getProperties()); identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); // Nothing has changed about the actual score so we do not notify. // mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, newScore); } assert(getScores(oldIdentity).size() == 0); // What we do NOT have to deal with is the given scores of the old identity: // Given scores do NOT exist for non-own identities, so there are no old ones to update. // Of cause there WILL be scores because it is an own identity now. // They will be created automatically when updating the given trusts // - so thats what we will do now. // Update all given trusts for(Trust givenTrust : getGivenTrusts(oldIdentity)) { // TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could: // - manually delete the old Trust objects from the database // - manually store the new trust objects // - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version // of setTrustWithoutCommit which deals with that. // But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit: // To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make // it only update the parts of the trust graph which are affected. // Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests. removeTrustWithoutCommit(givenTrust); setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); } // We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit // which would re-create scores of the old identity. We later call it AFTER deleting the old identity. /* finishTrustListImport(); */ mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); finishTrustListImport(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); } catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it. identity = new OwnIdentity(this, insertFreenetURI, null, false); Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity); identity.restoreEdition(edition, null); // Store the new identity identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); } mFetcher.storeStartFetchCommandWithoutCommit(identity); // This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { if(mTrustListImportInProgress) { // We don't execute beginTrustListImport() in all code paths of this function abortTrustListImport(e); // Does rollback for us throw e; } else { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } } Logger.normal(this, "restoreOwnIdentity(): Finished."); } public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment) throws UnknownIdentityException, NumberFormatException, InvalidParameterException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); Identity trustee = getIdentityByID(trusteeID); setTrust(truster, trustee, value, comment); } public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); final Identity trustee = getIdentityByID(trusteeID); synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { removeTrustWithoutCommit(truster, trustee); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } /** * Enables or disables the publishing of the trust list of an {@link OwnIdentity}. * The trust list contains all trust values which the OwnIdentity has assigned to other identities. * * @see OwnIdentity#setPublishTrustList(boolean) * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishTrustList Whether to publish the trust list. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given {@link Identity.IdentityID}. */ public synchronized void setPublishTrustList(final String ownIdentityID, final boolean publishTrustList) throws UnknownIdentityException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setPublishTrustList(publishTrustList); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "setPublishTrustList to " + publishTrustList + " for " + identity); } /** * Enables or disables the publishing of {@link IntroductionPuzzle}s for an {@link OwnIdentity}. * * If publishIntroductionPuzzles==true adds, if false removes: * - the context {@link IntroductionPuzzle.INTRODUCTION_CONTEXT} * - the property {@link IntroductionServer.PUZZLE_COUNT_PROPERTY} with the value {@link IntroductionServer.DEFAULT_PUZZLE_COUNT} * * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishIntroductionPuzzles Whether to publish introduction puzzles. * @throws UnknownIdentityException If there is no identity with the given ownIdentityID * @throws InvalidParameterException If {@link OwnIdentity#doesPublishTrustList()} returns false on the selected identity: It doesn't make sense for an identity to allow introduction if it doesn't publish a trust list - the purpose of introduction is to add other identities to your trust list. */ public synchronized void setPublishIntroductionPuzzles(final String ownIdentityID, final boolean publishIntroductionPuzzles) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager if(!identity.doesPublishTrustList()) throw new InvalidParameterException("An identity must publish its trust list if it wants to publish introduction puzzles!"); synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { if(publishIntroductionPuzzles) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } else { identity.removeContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.removeProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY); } mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "Set publishIntroductionPuzzles to " + true + " for " + identity); } public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.addContext(newContext); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeContext(context); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'"); } public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException { return getIdentityByID(identityID).getProperty(property); } public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setProperty(property, value); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeProperty(property); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'"); } public String getVersion() { return Version.getMarketingVersion(); } public long getRealVersion() { return Version.getRealVersion(); } public String getString(String key) { return getBaseL10n().getString(key); } public void setLanguage(LANGUAGE newLanguage) { WebOfTrust.l10n = new PluginL10n(this, newLanguage); if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode); } public PluginRespirator getPluginRespirator() { return mPR; } public ExtObjectContainer getDatabase() { return mDB; } public Configuration getConfig() { return mConfig; } public SubscriptionManager getSubscriptionManager() { return mSubscriptionManager; } public IdentityFetcher getIdentityFetcher() { return mFetcher; } public XMLTransformer getXMLTransformer() { return mXMLTransformer; } public IntroductionPuzzleStore getIntroductionPuzzleStore() { return mPuzzleStore; } public IntroductionClient getIntroductionClient() { return mIntroductionClient; } protected FCPInterface getFCPInterface() { return mFCPInterface; } public RequestClient getRequestClient() { return mRequestClient; } /** * This is where our L10n files are stored. * @return Path of our L10n files. */ public String getL10nFilesBasePath() { return "plugins/WebOfTrust/l10n/"; } /** * This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ... * @return Mask of the L10n files. */ public String getL10nFilesMask() { return "lang_${lang}.l10n"; } /** * Override L10n files are stored on the disk, their names should be explicit * we put here the plugin name, and the "override" indication. Plugin L10n * override is not implemented in the node yet. * @return Mask of the override L10n files. */ public String getL10nOverrideFilesMask() { return "WebOfTrust_lang_${lang}.override.l10n"; } /** * Get the ClassLoader of this plugin. This is necessary when getting * resources inside the plugin's Jar, for example L10n files. * @return ClassLoader object */ public ClassLoader getPluginClassLoader() { return WebOfTrust.class.getClassLoader(); } /** * Access to the current L10n data. * * @return L10n object. */ public BaseL10n getBaseL10n() { return WebOfTrust.l10n.getBase(); } public int getNumberOfFullScoreRecomputations() { return mFullScoreRecomputationCount; } public synchronized double getAverageFullScoreRecomputationTime() { return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000); } public int getNumberOfIncrementalScoreRecomputations() { return mIncrementalScoreRecomputationCount; } public synchronized double getAverageIncrementalScoreRecomputationTime() { return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000); } /** * Tests whether two WoT are equal. * This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests. */ public synchronized boolean equals(Object obj) { if(obj == this) return true; if(!(obj instanceof WebOfTrust)) return false; WebOfTrust other = (WebOfTrust)obj; synchronized(other) { { // Compare own identities final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities(); if(allIdentities.size() != other.getAllOwnIdentities().size()) return false; for(OwnIdentity identity : allIdentities) { try { if(!identity.equals(other.getOwnIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare identities final ObjectSet<Identity> allIdentities = getAllIdentities(); if(allIdentities.size() != other.getAllIdentities().size()) return false; for(Identity identity : allIdentities) { try { if(!identity.equals(other.getIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare trusts final ObjectSet<Trust> allTrusts = getAllTrusts(); if(allTrusts.size() != other.getAllTrusts().size()) return false; for(Trust trust : allTrusts) { try { Identity otherTruster = other.getIdentityByID(trust.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID()); if(!trust.equals(other.getTrust(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotTrustedException e) { return false; } } } { // Compare scores final ObjectSet<Score> allScores = getAllScores(); if(allScores.size() != other.getAllScores().size()) return false; for(Score score : allScores) { try { OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID()); if(!score.equals(other.getScore(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotInTrustTreeException e) { return false; } } } } return true; } }
private synchronized void deleteDuplicateObjects() { synchronized(mPuzzleStore) { // Needed for deleteWithoutCommit(Identity) synchronized(mFetcher) { // Needed for deleteWithoutCommit(Identity) synchronized(mSubscriptionManager) { // Needed for deleteWithoutCommit(Identity) synchronized(Persistent.transactionLock(mDB)) { try { HashSet<String> deleted = new HashSet<String>(); if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ..."); for(Identity identity : getAllIdentities()) { Query q = mDB.query(); q.constrain(Identity.class); q.descend("mID").constrain(identity.getID()); q.constrain(identity).identity().not(); ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q); for(Identity duplicate : duplicates) { if(deleted.contains(duplicate.getID()) == false) { Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI()); deleteWithoutCommit(duplicate); Persistent.checkedCommit(mDB, this); } } deleted.add(identity.getID()); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { } // synchronized(mPuzzleStore) { // synchronized(this) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ..."); boolean duplicateTrustFound = false; for(OwnIdentity truster : getAllOwnIdentities()) { HashSet<String> givenTo = new HashSet<String>(); for(Trust trust : getGivenTrusts(truster)) { if(givenTo.contains(trust.getTrustee().getID()) == false) givenTo.add(trust.getTrustee().getID()); else { Logger.error(this, "Deleting duplicate given trust:" + trust); removeTrustWithoutCommit(trust); duplicateTrustFound = true; } } } if(duplicateTrustFound) { computeAllScoresWithoutCommit(); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { /* TODO: Also delete duplicate score */ } /** * Debug function for deleting trusts or scores of which one of the involved partners is missing. */ private synchronized void deleteOrphanObjects() { // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanTrustFound = false; Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q); for(Trust trust : orphanTrusts) { if(trust.getTruster() != null && trust.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust); continue; } Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee()); orphanTrustFound = true; trust.deleteWithoutCommit(); // No need to update subscriptions as the trust is broken anyway. } if(orphanTrustFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanScoresFound = false; Query q = mDB.query(); q.constrain(Score.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q); for(Score score : orphanScores) { if(score.getTruster() != null && score.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score); continue; } Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee()); orphanScoresFound = true; score.deleteWithoutCommit(); // No need to update subscriptions as the score is broken anyway. } if(orphanScoresFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } /** * Warning: This function is not synchronized, use it only in single threaded mode. * @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist. */ @SuppressWarnings("deprecation") private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) { final Query query = database.query(); query.constrain(Configuration.class); @SuppressWarnings("unchecked") ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute(); switch(result.size()) { case 1: { final Configuration config = (Configuration)result.next(); config.initializeTransient(wot, database); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); return config.getDatabaseFormatVersion(); } default: return -1; } } /** * Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists. * @return The config object. */ private synchronized Configuration getOrCreateConfig() { final Query query = mDB.query(); query.constrain(Configuration.class); final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query); switch(result.size()) { case 1: { final Configuration config = result.next(); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); config.setDefaultValues(false); config.storeAndCommit(); return config; } case 0: { final Configuration config = new Configuration(this); config.initializeTransient(this); config.storeAndCommit(); return config; } default: throw new RuntimeException("Multiple config objects found: " + result.size()); } } /** Capacity is the maximum amount of points an identity can give to an other by trusting it. * * Values choice : * Advogato Trust metric recommends that values decrease by rounded 2.5 times. * This makes sense, making the need of 3 N+1 ranked people to overpower * the trust given by a N ranked identity. * * Number of ranks choice : * When someone creates a fresh identity, he gets the seed identity at * rank 1 and freenet developpers at rank 2. That means that * he will see people that were : * - given 7 trust by freenet devs (rank 2) * - given 17 trust by rank 3 * - given 50 trust by rank 4 * - given 100 trust by rank 5 and above. * This makes the range small enough to avoid a newbie * to even see spam, and large enough to make him see a reasonnable part * of the community right out-of-the-box. * Of course, as soon as he will start to give trust, he will put more * people at rank 1 and enlarge his WoT. */ protected static final int capacities[] = { 100,// Rank 0 : Own identities 40, // Rank 1 : Identities directly trusted by ownIdenties 16, // Rank 2 : Identities trusted by rank 1 identities 6, // So on... 2, 1 // Every identity above rank 5 can give 1 point }; // Identities with negative score have zero capacity /** * Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much * trust points an identity can add to the score of identities which it has assigned trust values to. * The higher the rank of an identity, the less is it's capacity. * * If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less * than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0. * * If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value: * The decision of the truster should always overpower the view of remote identities. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed * @param trustee The {@link Identity} of which the capacity shall be computed. * @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust, * - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view. */ private int computeCapacity(OwnIdentity truster, Identity trustee, int rank) { if(truster == trustee) return 100; try { // FIXME: The comment "Security check, if rank computation breaks this will hit." below sounds like we don't actually // need to execute this because the callers probably do it implicitly. Check if this is true and if yes, convert it to an assert. if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit. assert(rank == Integer.MAX_VALUE); return 0; } } catch(NotTrustedException e) { } if(rank == -1 || rank == Integer.MAX_VALUE) return 0; return (rank < capacities.length) ? capacities[rank] : 1; } /** * Reference-implementation of score computation. This means:<br /> * - It is not used by the real WoT code because its slow<br /> * - It is used by unit tests (and WoT) to check whether the real implementation works<br /> * - It is the function which you should read if you want to understand how WoT works.<br /> * * Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br /> * * There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br /> * * Further, rank values are shortest paths and the path-finding algorithm is not executed from the source * to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path. * Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database * and affect many others. So it is useful to have this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * </code> * * @return True if all stored scores were correct. False if there were any errors in stored scores. */ protected boolean computeAllScoresWithoutCommit() { if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); boolean returnValue = true; final ObjectSet<Identity> allIdentities = getAllIdentities(); // Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity. for(OwnIdentity treeOwner : getAllOwnIdentities()) { // At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner. // An identity is visible if there is a trust chain from the owner to it. // The rank is the distance in trust steps from the treeOwner. // So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on. final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2); // Compute the rank values { // For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters. // The inner loop then pulls out one unprocessed identity and computes the rank of its trustees: // All trustees which have received positive (> 0) trust will get his rank + 1 // Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE. // Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all. // Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none. // // Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value: // The decision of the own identity shall not be overpowered by the view of the remote identities. // // The purpose of differentiation between Integer.MAX_VALUE and -1 is: // Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing // them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and // have a way of telling the user "this identity is not trusted" by keeping a score object of them. // Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where // we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank // - and we never import their trust lists. // We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved // introduction puzzles cannot inherit their rank to their trustees. final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>(); // The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE try { Score selfScore = getScore(treeOwner, treeOwner); if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one rankValues.put(treeOwner, selfScore.getRank()); unprocessedTrusters.addLast(treeOwner); } else { rankValues.put(treeOwner, null); } } catch(NotInTrustTreeException e) { // This only happens in unit tests. } while(!unprocessedTrusters.isEmpty()) { final Identity truster = unprocessedTrusters.removeFirst(); final Integer trusterRank = rankValues.get(truster); // The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all. if(trusterRank == null || trusterRank == Integer.MAX_VALUE) { // (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security) continue; } final int trusteeRank = trusterRank + 1; for(Trust trust : getGivenTrusts(truster)) { final Identity trustee = trust.getTrustee(); final Integer oldTrusteeRank = rankValues.get(trustee); if(oldTrusteeRank == null) { // The trustee was not processed yet if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } else rankValues.put(trustee, Integer.MAX_VALUE); } else { // Breadth first search will process all rank one identities are processed before any rank two identities, etc. assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank); if(oldTrusteeRank == Integer.MAX_VALUE) { // If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not // given by the tree owner. try { final Trust treeOwnerTrust = getTrust(treeOwner, trustee); assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct? } catch(NotTrustedException e) { if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } } } } } } } // Rank values of all visible identities are computed now. // Next step is to compute the scores of all identities for(Identity target : allIdentities) { // The score of an identity is the sum of all weighted trust values it has received. // Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank. Integer targetScore; final Integer targetRank = rankValues.get(target); if(targetRank == null) { targetScore = null; } else { // The treeOwner trusts himself. if(targetRank == 0) { targetScore = Integer.MAX_VALUE; } else { // If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score. try { targetScore = (int)getTrust(treeOwner, target).getValue(); } catch(NotTrustedException e) { targetScore = 0; for(Trust receivedTrust : getReceivedTrusts(target)) { final Identity truster = receivedTrust.getTruster(); final Integer trusterRank = rankValues.get(truster); // The capacity is a weight function for trust values which are given from an identity: // The higher the rank, the less the capacity. // If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0. final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1); targetScore += (receivedTrust.getValue() * capacity) / 100; } } } } Score newScore = null; if(targetScore != null) { newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank)); } boolean needToCheckFetchStatus = false; boolean oldShouldFetch = false; int oldCapacity = 0; // Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct. try { Score currentStoredScore = getScore(treeOwner, target); oldCapacity = currentStoredScore.getCapacity(); if(newScore == null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(currentStoredScore, null); } else { if(!newScore.equals(currentStoredScore)) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); final Score oldScore = currentStoredScore.clone(); currentStoredScore.setRank(newScore.getRank()); currentStoredScore.setCapacity(newScore.getCapacity()); currentStoredScore.setValue(newScore.getScore()); currentStoredScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, currentStoredScore); } } } catch(NotInTrustTreeException e) { oldCapacity = 0; if(newScore != null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); newScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, newScore); } } if(needToCheckFetchStatus) { // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target); target.markForRefetch(); target.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(target); mFetcher.storeStartFetchCommandWithoutCommit(target); } else if(oldShouldFetch && !shouldFetchIdentity(target)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target); mFetcher.storeAbortFetchCommandWithoutCommit(target); } } } } mFullScoreComputationNeeded = false; ++mFullScoreRecomputationCount; mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; if(logMINOR) { Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s"); } return returnValue; } private synchronized void createSeedIdentities() { synchronized(mSubscriptionManager) { for(String seedURI : SEED_IDENTITIES) { synchronized(Persistent.transactionLock(mDB)) { try { final Identity existingSeed = getIdentityByURI(seedURI); final Identity oldExistingSeed = existingSeed.clone(); // For the SubscriptionManager if(existingSeed instanceof OwnIdentity) { final OwnIdentity ownExistingSeed = (OwnIdentity)existingSeed; ownExistingSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); ownExistingSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT)); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, ownExistingSeed); ownExistingSeed.storeAndCommit(); } else { try { existingSeed.setEdition(new FreenetURI(seedURI).getEdition()); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, existingSeed); existingSeed.storeAndCommit(); } catch(InvalidParameterException e) { /* We already have the latest edition stored */ } } } catch (UnknownIdentityException uie) { try { final Identity newSeed = new Identity(this, seedURI, null, true); // We have to explicitly set the edition number because the constructor only considers the given edition as a hint. newSeed.setEdition(new FreenetURI(seedURI).getEdition()); newSeed.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, newSeed); Persistent.checkedCommit(mDB, this); } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } public void terminate() { Logger.normal(this, "Web Of Trust plugin terminating ..."); /* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */ try { if(mWebInterface != null) this.mWebInterface.unload(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionClient != null) mIntroductionClient.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionServer != null) mIntroductionServer.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mInserter != null) mInserter.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mFetcher != null) mFetcher.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mSubscriptionManager != null) mSubscriptionManager.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mDB != null) { /* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending. * If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction. * - All transactions should be committed after obtaining the lock() on the database. */ synchronized(Persistent.transactionLock(mDB)) { System.gc(); mDB.rollback(); System.gc(); mDB.close(); } } } catch(Exception e) { Logger.error(this, "Error during termination.", e); } Logger.normal(this, "Web Of Trust plugin terminated."); } /** * Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>. */ public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { mFCPInterface.handle(replysender, params, data, accesstype); } /** * Loads an own or normal identity from the database, querying on its ID. * * @param id The ID of the identity to load * @return The identity matching the supplied ID. * @throws DuplicateIdentityException if there are more than one identity with this id in the database * @throws UnknownIdentityException if there is no identity with this id in the database */ public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(Identity.class); query.descend("mID").constrain(id); final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Gets an OwnIdentity by its ID. * * @param id The unique identifier to query an OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if there is now OwnIdentity with that id */ public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(OwnIdentity.class); query.descend("mID").constrain(id); final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI}) * * @param uri The requestURI of the identity * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database */ public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Loads an identity from the database, querying on its requestURI (as String) * * @param uri The requestURI of the identity which will be converted to {@link FreenetURI} * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database * @throws MalformedURLException if the requestURI isn't a valid FreenetURI */ public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getIdentityByURI(new FreenetURI(uri)); } /** * Gets an OwnIdentity by its requestURI (a {@link FreenetURI}). * The OwnIdentity's unique identifier is extracted from the supplied requestURI. * * @param uri The requestURI of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database */ public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Gets an OwnIdentity by its requestURI (as String). * The given String is converted to {@link FreenetURI} in order to extract a unique id. * * @param uri The requestURI (as String) of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database * @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI */ public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getOwnIdentityByURI(new FreenetURI(uri)); } /** * Returns all identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database */ public ObjectSet<Identity> getAllIdentities() { final Query query = mDB.query(); query.constrain(Identity.class); return new Persistent.InitializingObjectSet<Identity>(this, query); } public static enum SortOrder { ByNicknameAscending, ByNicknameDescending, ByScoreAscending, ByScoreDescending, ByLocalTrustAscending, ByLocalTrustDescending } /** * Get a filtered and sorted list of identities. * You have to synchronize on this WoT when calling the function and processing the returned list. */ public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) { Query q = mDB.query(); switch(sortInstruction) { case ByNicknameAscending: q.constrain(Identity.class); q.descend("mNickname").orderAscending(); break; case ByNicknameDescending: q.constrain(Identity.class); q.descend("mNickname").orderDescending(); break; case ByScoreAscending: q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByScoreDescending: // TODO: This excludes identities which have no score q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; case ByLocalTrustAscending: q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByLocalTrustDescending: // TODO: This excludes untrusted identities. q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; } if(nickFilter != null) { nickFilter = nickFilter.trim(); if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like(); } return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database. * * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Identity> getAllNonOwnIdentities() { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently * modified identities will be at the beginning of the list. * * You have to synchronize on this WoT when calling the function and processing the returned list! * * Used by the IntroductionClient for fetching puzzles from recently modified identities. */ public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); /* TODO: As soon as identities announce that they were online every day, uncomment the following line */ /* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */ q.descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all own identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database. */ public ObjectSet<OwnIdentity> getAllOwnIdentities() { final Query q = mDB.query(); q.constrain(OwnIdentity.class); return new Persistent.InitializingObjectSet<OwnIdentity>(this, q); } /** * DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST! * IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS: * - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will. * - Especially it might be an information leak if the trust values of other OwnIdentities are deleted! * - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption. * * The intended purpose of this function is: * - To specify which objects have to be dealt with when messing with storage of an identity. * - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them. * However, the implementations of those functions might cause leaks by forgetting to delete certain object members. * If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty. * You then can check whether the database actually IS empty to test for leakage. * * You have to lock the WebOfTrust, the IntroductionPuzzleStore, the IdentityFetcher and the SubscriptionManager before calling this function. */ private void deleteWithoutCommit(Identity identity) { // We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport. // If the caller already handles that for us though, we should not call those function again. // So we check whether the caller already started an import. boolean trustListImportWasInProgress = mTrustListImportInProgress; try { if(!trustListImportWasInProgress) beginTrustListImport(); if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ..."); if(logDEBUG) Logger.debug(this, "Deleting received scores..."); for(Score score : getScores(identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } if(identity instanceof OwnIdentity) { if(logDEBUG) Logger.debug(this, "Deleting given scores..."); for(Score score : getGivenScores((OwnIdentity)identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } } if(logDEBUG) Logger.debug(this, "Deleting received trusts..."); for(Trust trust : getReceivedTrusts(identity)) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); } if(logDEBUG) Logger.debug(this, "Deleting given trusts..."); for(Trust givenTrust : getGivenTrusts(identity)) { givenTrust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(givenTrust, null); // We call computeAllScores anyway so we do not use removeTrustWithoutCommit() } mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us. if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ..."); mPuzzleStore.onIdentityDeletion(identity); if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command..."); if(mFetcher != null) { // Can be null if we use this function in upgradeDB() mFetcher.storeAbortFetchCommandWithoutCommit(identity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. } if(logDEBUG) Logger.debug(this, "Deleting the identity..."); identity.deleteWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(identity, null); if(!trustListImportWasInProgress) finishTrustListImport(); } catch(RuntimeException e) { if(!trustListImportWasInProgress) abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * Gets the score of this identity in a trust tree. * Each {@link OwnIdentity} has its own trust tree. * * @param truster The owner of the trust tree * @return The {@link Score} of this Identity in the required trust tree * @throws NotInTrustTreeException if this identity is not in the required trust tree */ public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mID").constrain(new ScoreID(truster, trustee).toString()); final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query); switch(result.size()) { case 1: final Score score = result.next(); assert(score.getTruster() == truster); assert(score.getTrustee() == trustee); return score; case 0: throw new NotInTrustTreeException(truster, trustee); default: throw new DuplicateScoreException(truster, trustee, result.size()); } } /** * Gets a list of all this Identity's Scores. * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * * @return An {@link ObjectSet} containing all {@link Score} this Identity has. */ public ObjectSet<Score> getScores(final Identity identity) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTrustee").constrain(identity).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Get a list of all scores which the passed own identity has assigned to other identities. * * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * @return An {@link ObjectSet} containing all {@link Score} this Identity has given. */ public ObjectSet<Score> getGivenScores(final OwnIdentity truster) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets the best score this Identity has in existing trust trees. * * @return the best score this Identity has * @throws NotInTrustTreeException If the identity has no score in any trusttree. */ public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException { int bestScore = Integer.MIN_VALUE; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestScore = Math.max(score.getScore(), bestScore); return bestScore; } /** * Gets the best capacity this identity has in any trust tree. * @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0. */ public synchronized int getBestCapacity(final Identity identity) throws NotInTrustTreeException { int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestCapacity = Math.max(score.getCapacity(), bestCapacity); return bestCapacity; } /** * Get all scores in the database. * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Score> getAllScores() { final Query query = mDB.query(); query.constrain(Score.class); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Checks whether the given identity should be downloaded. * * Synchronization: You must synchronize on this WebOfTrust when using this function. * * @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity. */ private boolean shouldFetchIdentity(final Identity identity) { if(identity instanceof OwnIdentity) return true; int bestScore = Integer.MIN_VALUE; int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) return false; // TODO: Cache the best score of an identity as a member variable. for(Score score : scores) { bestCapacity = Math.max(score.getCapacity(), bestCapacity); bestScore = Math.max(score.getScore(), bestScore); if(bestCapacity > 0 || bestScore >= 0) return true; } return false; } /** * Gets non-own Identities matching a specified score criteria. * TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The owner of the trust tree, null if you want the trusted identities of all owners. * @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0 * and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0. * @return an {@link ObjectSet} containing Scores of the identities that match the criteria */ public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) { final Query query = mDB.query(); query.constrain(Score.class); if(truster != null) query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").constrain(OwnIdentity.class).not(); /* We include 0 in the list of identities with positive score because solving captchas gives no points to score */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets {@link Trust} from a specified truster to a specified trustee. * * @param truster The identity that gives trust to this Identity * @param trustee The identity which receives the trust * @return The trust given to the trustee by the specified truster * @throws NotTrustedException if the truster doesn't trust the trustee */ public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mID").constrain(new TrustID(truster, trustee).toString()); final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query); switch(result.size()) { case 1: final Trust trust = result.next(); assert(trust.getTruster() == truster); assert(trust.getTrustee() == trustee); return trust; case 0: throw new NotTrustedException(truster, trustee); default: throw new DuplicateTrustException(truster, trustee, result.size()); } } /** * Gets all trusts given by the given truster. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster. * The result is sorted descending by the time we last fetched the trusted identity. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets given trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The identity which given the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster in a trust list with a different edition than the passed in one. * You have to synchronize on this WoT when calling the function and processing the returned list! */ protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) { final Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mTrusterTrustListEdition").constrain(edition).not(); return new Persistent.InitializingObjectSet<Trust>(this, q); } /** * Gets all trusts received by the given trustee. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets received trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param trustee The identity which has received the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getAllTrusts() { final Query query = mDB.query(); query.constrain(Trust.class); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gives some {@link Trust} to another Identity. * It creates or updates an existing Trust object and make the trustee compute its {@link Score}. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * * @param truster The Identity that gives the trust * @param trustee The Identity that receives the trust * @param newValue Numeric value of the trust * @param newComment A comment to explain the given value * @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values. */ protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { try { // Check if we are updating an existing trust value final Trust trust = getTrust(truster, trustee); final Trust oldTrust = trust.clone(); trust.trusterEditionUpdated(); trust.setComment(newComment); trust.storeWithoutCommit(); if(trust.getValue() != newValue) { trust.setValue(newValue); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(oldTrust, trust); if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(oldTrust, trust); } } catch (NotTrustedException e) { final Trust trust = new Trust(this, truster, trustee, newValue, newComment); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(null, trust); if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(null, trust); } truster.updated(); truster.storeWithoutCommit(); // TODO: Mabye notify clients about this. IMHO it would create too much notifications on trust list import so we don't. // As soon as we have notification-coalescing we might do it. // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(truster); } /** * Only for being used by WoT internally and by unit tests! * * You have to synchronize on this WebOfTrust while querying the parameter identities and calling this function. */ void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { setTrustWithoutCommit(truster, trustee, newValue, newComment); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } /** * Deletes a trust object. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * * @param truster * @param trustee */ protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) { try { try { removeTrustWithoutCommit(getTrust(truster, trustee)); } catch (NotTrustedException e) { Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname()); } } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * */ protected void removeTrustWithoutCommit(Trust trust) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); updateScoresWithoutCommit(trust, null); } /** * Initializes this OwnIdentity's trust tree without commiting the transaction. * Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities. * * The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }} * * @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen) */ private void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException { try { getScore(identity, identity); Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity); return; } catch (NotInTrustTreeException e) { final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100); score.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, score); } } /** * Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified * trust tree. * * Synchronization: * You have to synchronize on this WebOfTrust object when using this function. * * @param truster The OwnIdentity that owns the trust tree * @param trustee The identity for which the score shall be computed. * @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster. * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return Integer.MAX_VALUE; int value = 0; try { return getTrust(truster, trustee).getValue(); } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { final Score trusterScore = getScore(truster, trust.getTruster()); value += ( trust.getValue() * trusterScore.getCapacity() ) / 100; } catch (NotInTrustTreeException e) {} } return value; } /** * Computes the trustees's rank in the trust tree of the truster. * It gets its best ranked non-zero-capacity truster's rank, plus one. * If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite). * If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1. * * If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the * tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision). * * The purpose of differentiation between Integer.MAX_VALUE and -1 is: * Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them * in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the * user "this identity is not trusted" by keeping a score object of them. * Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we * hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and * we never download their trust lists. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * Synchronization: * You have to synchronize on this WebOfTrust object when using this function. * * @param truster The OwnIdentity that owns the trust tree * @return The new Rank if this Identity * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return 0; int rank = -1; try { Trust treeOwnerTrust = getTrust(truster, trustee); if(treeOwnerTrust.getValue() > 0) return 1; else return Integer.MAX_VALUE; } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { Score score = getScore(truster, trust.getTruster()); if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank // A truster only gives his rank to a trustee if he has assigned a strictly positive trust value if(trust.getValue() > 0 ) { // We give the rank to the trustee if it is better than its current rank or he has no rank yet. if(rank == -1 || score.getRank() < rank) rank = score.getRank(); } else { // If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster. if(rank == -1) rank = Integer.MAX_VALUE; } } } catch (NotInTrustTreeException e) {} } if(rank == -1) return -1; else if(rank == Integer.MAX_VALUE) return Integer.MAX_VALUE; else return rank+1; } /** * Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress. * This speeds up setTrust/removeTrust as the score calculation is only performed when {@link #finishTrustListImport()} is called. * * ATTENTION: Always take care to call one of {@link #finishTrustListImport()} / {@link #abortTrustListImport(Exception)} / {@link #abortTrustListImport(Exception, LogLevel)} * for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> */ protected void beginTrustListImport() { if(logMINOR) Logger.minor(this, "beginTrustListImport()"); if(mTrustListImportInProgress) { abortTrustListImport(new RuntimeException("There was already a trust list import in progress!")); mFullScoreComputationNeeded = true; computeAllScoresWithoutCommit(); assert(mFullScoreComputationNeeded == false); } mTrustListImportInProgress = true; assert(!mFullScoreComputationNeeded); assert(computeAllScoresWithoutCommit()); // The database is intact before the import } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e, Logger.LogLevel.ERROR); // Does checkedRollback() for you already } * }}}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file. * @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file. */ protected void abortTrustListImport(Exception e, LogLevel logLevel) { if(logMINOR) Logger.minor(this, "abortTrustListImport()"); assert(mTrustListImportInProgress); mTrustListImportInProgress = false; mFullScoreComputationNeeded = false; Persistent.checkedRollback(mDB, this, e, logLevel); assert(computeAllScoresWithoutCommit()); // Test rollback. } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR} */ protected void abortTrustListImport(Exception e) { abortTrustListImport(e, Logger.LogLevel.ERROR); } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Finishes the import of the current trust list and performs score computation. * * ATTENTION: In opposite to abortTrustListImport(), which rolls back the transaction, this does NOT commit the transaction. You have to do it! * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> */ protected void finishTrustListImport() { if(logMINOR) Logger.minor(this, "finishTrustListImport()"); if(!mTrustListImportInProgress) { Logger.error(this, "There was no trust list import in progress!"); return; } if(mFullScoreComputationNeeded) { computeAllScoresWithoutCommit(); assert(!mFullScoreComputationNeeded); // It properly clears the flag assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable } else assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked. mTrustListImportInProgress = false; } /** * Updates all trust trees which are affected by the given modified score. * For understanding how score calculation works you should first read {@link #computeAllScoresWithoutCommit()} * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; } * }}}} */ private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) { if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); // We only include the time measurement if we actually do something. // If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included. boolean includeMeasurement = false; final boolean trustWasCreated = (oldTrust == null); final boolean trustWasDeleted = (newTrust == null); final boolean trustWasModified = !trustWasCreated && !trustWasDeleted; if(trustWasCreated && trustWasDeleted) throw new NullPointerException("No old/new trust specified."); if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster()) throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust); if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee()) throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust); // We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values // which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best // rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity // then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because // the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank. if(trustWasDeleted) { mFullScoreComputationNeeded = true; } if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) { includeMeasurement = true; for(OwnIdentity treeOwner : getAllOwnIdentities()) { try { // Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score. if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0) continue; } catch(NotInTrustTreeException e) { continue; } // See explanation above "We cannot iteratively REMOVE an inherited rank..." if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) { mFullScoreComputationNeeded = true; break; } final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>(); unprocessedEdges.add(newTrust); while(!unprocessedEdges.isEmpty()) { final Trust trust = unprocessedEdges.removeFirst(); final Identity trustee = trust.getTrustee(); if(trustee == treeOwner) continue; Score currentStoredTrusteeScore; boolean scoreExistedBefore; try { currentStoredTrusteeScore = getScore(treeOwner, trustee); scoreExistedBefore = true; } catch(NotInTrustTreeException e) { scoreExistedBefore = false; currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0); } final Score oldScore = currentStoredTrusteeScore.clone(); boolean oldShouldFetch = shouldFetchIdentity(trustee); final int newScoreValue = computeScoreValue(treeOwner, trustee); final int newRank = computeRank(treeOwner, trustee); final int newCapacity = computeCapacity(treeOwner, trustee, newRank); final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity); // Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value, // the rank and capacity are always computed based on the trust value of the own identity so we must also check this here: if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank && (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore mFullScoreComputationNeeded = true; break; } if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) { mFullScoreComputationNeeded = true; break; } // We are OK to update it now. We must not update the values of the stored score object before determining whether we need // a full score computation - the full computation needs the old values of the object. currentStoredTrusteeScore.setValue(newScore.getScore()); currentStoredTrusteeScore.setRank(newScore.getRank()); currentStoredTrusteeScore.setCapacity(newScore.getCapacity()); // Identities should not get into the queue if they have no rank, see the large if() about 20 lines below assert(currentStoredTrusteeScore.getRank() >= 0); if(currentStoredTrusteeScore.getRank() >= 0) { currentStoredTrusteeScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(scoreExistedBefore ? oldScore : null, currentStoredTrusteeScore); } // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee); trustee.markForRefetch(); trustee.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(trustee); mFetcher.storeStartFetchCommandWithoutCommit(trustee); } else if(oldShouldFetch && !shouldFetchIdentity(trustee)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee); mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } // If the rank or capacity changed then the trustees might be affected because the could have inherited theirs if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) { // If this identity has no capacity or no rank then it cannot affect its trustees: // (- If it had none and it has none now then there is none which can be inherited, this is obvious) // - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) { // We need to update the trustees of trustee for(Trust givenTrust : getGivenTrusts(trustee)) { unprocessedEdges.add(givenTrust); } } } } if(mFullScoreComputationNeeded) break; } } if(includeMeasurement) { ++mIncrementalScoreRecomputationCount; mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; } if(logMINOR) { final String time = includeMeasurement ? ("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s") : ("Time not measured: Computation was aborted before doing anything."); if(!mFullScoreComputationNeeded) Logger.minor(this, "Incremental computation of all Scores finished. " + time); else Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time); } if(!mTrustListImportInProgress) { if(mFullScoreComputationNeeded) { // TODO: Optimization: This uses very much CPU and memory. Write a partial computation function... // TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT // keep all objects in memory etc. computeAllScoresWithoutCommit(); assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable } else { assert(computeAllScoresWithoutCommit()); // This function worked correctly. } } else { // a trust list import is in progress // We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore // updateScoresWithoutCommit is called often during import of a single trust list // assert(computeAllScoresWithoutCommit()); } } /* Client interface functions */ public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException { try { getIdentityByURI(requestURI); throw new InvalidParameterException("We already have this identity"); } catch(UnknownIdentityException e) { final Identity identity = new Identity(this, requestURI, null, false); synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e2) { Persistent.checkedRollbackAndThrow(mDB, this, e2); } } } // The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher. // TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust. Logger.normal(this, "addIdentity(): " + identity); return identity; } } public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME); return createOwnIdentity(keypair[0], nickName, publishTrustList, context); } /** * @param context A context with which you want to use the identity. Null if you want to add it later. */ public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { synchronized(mFetcher) { // For beginTrustListImport()/setTrustWithoutCommit() synchronized(mSubscriptionManager) { // For beginTrustListImport()/setTrustWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { OwnIdentity identity; try { identity = getOwnIdentityByURI(insertURI); throw new InvalidParameterException("The URI you specified is already used by the own identity " + identity.getNickname() + "."); } catch(UnknownIdentityException uie) { identity = new OwnIdentity(this, insertURI, nickName, publishTrustList); if(context != null) identity.addContext(context); if(publishTrustList) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */ identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); initTrustTreeWithoutCommit(identity); beginTrustListImport(); // Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation. mFullScoreComputationNeeded = true; for(String seedURI : SEED_IDENTITIES) { try { setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity."); } catch(UnknownIdentityException e) { Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e); } } finishTrustListImport(); Persistent.checkedCommit(mDB, this); if(mIntroductionClient != null) mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles. if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")"); return identity; } catch(RuntimeException e) { abortTrustListImport(e); // Rolls back for us throw e; // Satisfy the compiler } } } } } } /** * This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}. * * The {@link OwnIdentity} is not deleted because this would be a security issue: * If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target * * @param id The {@link Identity.IdentityID} of the identity. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID. */ public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException { Logger.normal(this, "deleteOwnIdentity(): Starting... "); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { final OwnIdentity oldIdentity = getOwnIdentityByID(id); try { Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity); // We don't need any score computations to happen (explanation will follow below) so we don't need the following: /* beginTrustListImport(); */ // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); final Identity newIdentity; try { newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); } catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } newIdentity.setContexts(oldIdentity.getContexts()); newIdentity.setProperties(oldIdentity.getProperties()); try { newIdentity.setEdition(oldIdentity.getEdition()); } catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen throw new RuntimeException(e); } // In theory we do not need to re-fetch the current trust list edition: // The trust list of an own identity is always stored completely in the database, i.e. all trustees exist. // HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that // the current edition of the old OwndIdentity was not fetched yet. // So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well. if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) { newIdentity.onFetched(oldIdentity.getLastFetchedDate()); } // An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already. newIdentity.storeWithoutCommit(); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust; try { newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // Delete all given scores: // Non-own identities do not assign scores to other identities so we can just delete them. for(Score oldScore : getGivenScores(oldIdentity)) { final Identity trustee = oldScore.getTrustee(); final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee); oldScore.deleteWithoutCommit(); // If the OwnIdentity which we are converting was the only source of trust to the trustee // of this Score value, the should-fetch state of the trustee might change to false. if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) { mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } } assert(getGivenScores(oldIdentity).size() == 0); // Copy all given trusts: // We don't have to use the removeTrust/setTrust functions because the score graph does not need updating: // - To the rating of the converted identity in the score graphs of other own identities it is irrelevant // whether it is an own identity or not. The rating should never depend on whether it is an own identity! // - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted // completely and therefore it does not need to be updated. for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) { Trust newGivenTrust; try { newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(), oldGivenTrust.getValue(), oldGivenTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newGivenTrust.equals(oldGivenTrust)); */ oldGivenTrust.deleteWithoutCommit(); newGivenTrust.storeWithoutCommit(); } mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(newIdentity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, newIdentity); // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } Logger.normal(this, "deleteOwnIdentity(): Finished."); } /** * NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()} */ public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException { Logger.normal(this, "restoreOwnIdentity(): Starting... "); OwnIdentity identity; synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { long edition = 0; try { edition = Math.max(edition, insertFreenetURI.getEdition()); } catch(IllegalStateException e) { // The user supplied URI did not have an edition specified } try { // Try replacing an existing non-own version of the identity with an OwnIdentity Identity oldIdentity = getIdentityByURI(insertFreenetURI); if(oldIdentity instanceof OwnIdentity) throw new InvalidParameterException("There is already an own identity with the given URI pair."); Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity); // Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function. // But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference // implementation will fail if two identities with the same ID exist. // This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph // but we must also store the own version to be able to modify the trust graph. beginTrustListImport(); // We already have fetched this identity as a stranger's one. We need to update the database. identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); /* We re-fetch the most recent edition to make sure all trustees are imported */ edition = Math.max(edition, oldIdentity.getEdition()); identity.restoreEdition(edition, oldIdentity.getLastFetchedDate()); identity.setContexts(oldIdentity.getContexts()); identity.setProperties(oldIdentity.getProperties()); identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); // Nothing has changed about the actual score so we do not notify. // mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, newScore); } assert(getScores(oldIdentity).size() == 0); // What we do NOT have to deal with is the given scores of the old identity: // Given scores do NOT exist for non-own identities, so there are no old ones to update. // Of cause there WILL be scores because it is an own identity now. // They will be created automatically when updating the given trusts // - so thats what we will do now. // Update all given trusts for(Trust givenTrust : getGivenTrusts(oldIdentity)) { // TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could: // - manually delete the old Trust objects from the database // - manually store the new trust objects // - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version // of setTrustWithoutCommit which deals with that. // But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit: // To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make // it only update the parts of the trust graph which are affected. // Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests. removeTrustWithoutCommit(givenTrust); setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); } // We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit // which would re-create scores of the old identity. We later call it AFTER deleting the old identity. /* finishTrustListImport(); */ mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); finishTrustListImport(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); } catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it. identity = new OwnIdentity(this, insertFreenetURI, null, false); Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity); identity.restoreEdition(edition, null); // Store the new identity identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); } mFetcher.storeStartFetchCommandWithoutCommit(identity); // This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { if(mTrustListImportInProgress) { // We don't execute beginTrustListImport() in all code paths of this function abortTrustListImport(e); // Does rollback for us throw e; } else { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } } Logger.normal(this, "restoreOwnIdentity(): Finished."); } public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment) throws UnknownIdentityException, NumberFormatException, InvalidParameterException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); Identity trustee = getIdentityByID(trusteeID); setTrust(truster, trustee, value, comment); } public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); final Identity trustee = getIdentityByID(trusteeID); synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { removeTrustWithoutCommit(truster, trustee); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } /** * Enables or disables the publishing of the trust list of an {@link OwnIdentity}. * The trust list contains all trust values which the OwnIdentity has assigned to other identities. * * @see OwnIdentity#setPublishTrustList(boolean) * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishTrustList Whether to publish the trust list. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given {@link Identity.IdentityID}. */ public synchronized void setPublishTrustList(final String ownIdentityID, final boolean publishTrustList) throws UnknownIdentityException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setPublishTrustList(publishTrustList); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "setPublishTrustList to " + publishTrustList + " for " + identity); } /** * Enables or disables the publishing of {@link IntroductionPuzzle}s for an {@link OwnIdentity}. * * If publishIntroductionPuzzles==true adds, if false removes: * - the context {@link IntroductionPuzzle.INTRODUCTION_CONTEXT} * - the property {@link IntroductionServer.PUZZLE_COUNT_PROPERTY} with the value {@link IntroductionServer.DEFAULT_PUZZLE_COUNT} * * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishIntroductionPuzzles Whether to publish introduction puzzles. * @throws UnknownIdentityException If there is no identity with the given ownIdentityID * @throws InvalidParameterException If {@link OwnIdentity#doesPublishTrustList()} returns false on the selected identity: It doesn't make sense for an identity to allow introduction if it doesn't publish a trust list - the purpose of introduction is to add other identities to your trust list. */ public synchronized void setPublishIntroductionPuzzles(final String ownIdentityID, final boolean publishIntroductionPuzzles) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager if(!identity.doesPublishTrustList()) throw new InvalidParameterException("An identity must publish its trust list if it wants to publish introduction puzzles!"); synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { if(publishIntroductionPuzzles) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } else { identity.removeContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.removeProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY); } mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "Set publishIntroductionPuzzles to " + true + " for " + identity); } public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.addContext(newContext); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeContext(context); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'"); } public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException { return getIdentityByID(identityID).getProperty(property); } public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setProperty(property, value); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeProperty(property); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'"); } public String getVersion() { return Version.getMarketingVersion(); } public long getRealVersion() { return Version.getRealVersion(); } public String getString(String key) { return getBaseL10n().getString(key); } public void setLanguage(LANGUAGE newLanguage) { WebOfTrust.l10n = new PluginL10n(this, newLanguage); if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode); } public PluginRespirator getPluginRespirator() { return mPR; } public ExtObjectContainer getDatabase() { return mDB; } public Configuration getConfig() { return mConfig; } public SubscriptionManager getSubscriptionManager() { return mSubscriptionManager; } public IdentityFetcher getIdentityFetcher() { return mFetcher; } public XMLTransformer getXMLTransformer() { return mXMLTransformer; } public IntroductionPuzzleStore getIntroductionPuzzleStore() { return mPuzzleStore; } public IntroductionClient getIntroductionClient() { return mIntroductionClient; } protected FCPInterface getFCPInterface() { return mFCPInterface; } public RequestClient getRequestClient() { return mRequestClient; } /** * This is where our L10n files are stored. * @return Path of our L10n files. */ public String getL10nFilesBasePath() { return "plugins/WebOfTrust/l10n/"; } /** * This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ... * @return Mask of the L10n files. */ public String getL10nFilesMask() { return "lang_${lang}.l10n"; } /** * Override L10n files are stored on the disk, their names should be explicit * we put here the plugin name, and the "override" indication. Plugin L10n * override is not implemented in the node yet. * @return Mask of the override L10n files. */ public String getL10nOverrideFilesMask() { return "WebOfTrust_lang_${lang}.override.l10n"; } /** * Get the ClassLoader of this plugin. This is necessary when getting * resources inside the plugin's Jar, for example L10n files. * @return ClassLoader object */ public ClassLoader getPluginClassLoader() { return WebOfTrust.class.getClassLoader(); } /** * Access to the current L10n data. * * @return L10n object. */ public BaseL10n getBaseL10n() { return WebOfTrust.l10n.getBase(); } public int getNumberOfFullScoreRecomputations() { return mFullScoreRecomputationCount; } public synchronized double getAverageFullScoreRecomputationTime() { return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000); } public int getNumberOfIncrementalScoreRecomputations() { return mIncrementalScoreRecomputationCount; } public synchronized double getAverageIncrementalScoreRecomputationTime() { return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000); } /** * Tests whether two WoT are equal. * This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests. */ public synchronized boolean equals(Object obj) { if(obj == this) return true; if(!(obj instanceof WebOfTrust)) return false; WebOfTrust other = (WebOfTrust)obj; synchronized(other) { { // Compare own identities final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities(); if(allIdentities.size() != other.getAllOwnIdentities().size()) return false; for(OwnIdentity identity : allIdentities) { try { if(!identity.equals(other.getOwnIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare identities final ObjectSet<Identity> allIdentities = getAllIdentities(); if(allIdentities.size() != other.getAllIdentities().size()) return false; for(Identity identity : allIdentities) { try { if(!identity.equals(other.getIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare trusts final ObjectSet<Trust> allTrusts = getAllTrusts(); if(allTrusts.size() != other.getAllTrusts().size()) return false; for(Trust trust : allTrusts) { try { Identity otherTruster = other.getIdentityByID(trust.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID()); if(!trust.equals(other.getTrust(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotTrustedException e) { return false; } } } { // Compare scores final ObjectSet<Score> allScores = getAllScores(); if(allScores.size() != other.getAllScores().size()) return false; for(Score score : allScores) { try { OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID()); if(!score.equals(other.getScore(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotInTrustTreeException e) { return false; } } } } return true; } }
diff --git a/bcel-additions/org/apache/bcel/verifier/statics/Pass3aVerifier.java b/bcel-additions/org/apache/bcel/verifier/statics/Pass3aVerifier.java index 3b2c7f2d..4c3b8a4d 100644 --- a/bcel-additions/org/apache/bcel/verifier/statics/Pass3aVerifier.java +++ b/bcel-additions/org/apache/bcel/verifier/statics/Pass3aVerifier.java @@ -1,1125 +1,1126 @@ package org.apache.bcel.verifier.statics; /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache BCEL" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * "Apache BCEL", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``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 THE APACHE SOFTWARE FOUNDATION 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ import org.apache.bcel.*; import org.apache.bcel.generic.*; import org.apache.bcel.classfile.*; import org.apache.bcel.verifier.*; import org.apache.bcel.verifier.exc.*; /** * This PassVerifier verifies a class file according to * pass 3, static part as described in The Java Virtual * Machine Specification, 2nd edition. * More detailed information is to be found at the do_verify() * method's documentation. * * @version $Id$ * @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A> * @see #do_verify() */ public final class Pass3aVerifier extends PassVerifier{ /** The Verifier that created this. */ private Verifier myOwner; /** * The method number to verify. * This is the index in the array returned * by JavaClass.getMethods(). */ private int method_no; /** The one and only InstructionList object used by an instance of this class. It's here for performance reasons by do_verify() and its callees. */ InstructionList instructionList; /** The one and only Code object used by an instance of this class. It's here for performance reasons by do_verify() and its callees. */ Code code; /** Should only be instantiated by a Verifier. */ public Pass3aVerifier(Verifier owner, int method_no){ myOwner = owner; this.method_no = method_no; } /** * Pass 3a is the verification of static constraints of * JVM code (such as legal targets of branch instructions). * This is the part of pass 3 where you do not need data * flow analysis. * JustIce also delays the checks for a correct exception * table of a Code attribute and correct line number entries * in a LineNumberTable attribute of a Code attribute (which * conceptually belong to pass 2) to this pass. Also, most * of the check for valid local variable entries in a * LocalVariableTable attribute of a Code attribute is * delayed until this pass. * All these checks need access to the code array of the * Code attribute. * * @throws InvalidMethodException if the method to verify does not exist. */ public VerificationResult do_verify(){ if (myOwner.doPass2().equals(VerificationResult.VR_OK)){ // Okay, class file was loaded correctly by Pass 1 // and satisfies static constraints of Pass 2. JavaClass jc = Repository.lookupClass(myOwner.getClassName()); Method[] methods = jc.getMethods(); if (method_no >= methods.length){ throw new InvalidMethodException("METHOD DOES NOT EXIST!"); } Method method = methods[method_no]; code = method.getCode(); // No Code? Nothing to verify! if ( method.isAbstract() || method.isNative() ){ // IF mg HAS NO CODE (static constraint of Pass 2) return VerificationResult.VR_OK; } // TODO: // We want a very sophisticated code examination here with good explanations // on where to look for an illegal instruction or such. // Only after that we should try to build an InstructionList and throw an // AssertionViolatedException if after our examination InstructionList building // still fails. // That examination should be implemented in a byte-oriented way, i.e. look for // an instruction, make sure its validity, count its length, find the next // instruction and so on. try{ instructionList = new InstructionList(method.getCode().getCode()); } catch(RuntimeException re){ return new VerificationResult(VerificationResult.VERIFIED_REJECTED, "Bad bytecode in the code array of the Code attribute of method '"+method+"'."); } instructionList.setPositions(true); // Start verification. VerificationResult vr = VerificationResult.VR_OK; //default try{ delayedPass2Checks(); } catch(ClassConstraintException cce){ vr = new VerificationResult(VerificationResult.VERIFIED_REJECTED, cce.getMessage()); return vr; } try{ pass3StaticInstructionChecks(); pass3StaticInstructionOperandsChecks(); } catch(StaticCodeConstraintException scce){ vr = new VerificationResult(VerificationResult.VERIFIED_REJECTED, scce.getMessage()); } return vr; } else{ //did not pass Pass 2. return VerificationResult.VR_NOTYET; } } /** * These are the checks that could be done in pass 2 but are delayed to pass 3 * for performance reasons. Also, these checks need access to the code array * of the Code attribute of a Method so it's okay to perform them here. * Also see the description of the do_verify() method. * * @throws ClassConstraintException if the verification fails. * @see #do_verify() */ private void delayedPass2Checks(){ int[] instructionPositions = instructionList.getInstructionPositions(); int codeLength = code.getCode().length; ///////////////////// // LineNumberTable // ///////////////////// LineNumberTable lnt = code.getLineNumberTable(); if (lnt != null){ LineNumber[] lineNumbers = lnt.getLineNumberTable(); IntList offsets = new IntList(); lineNumber_loop: for (int i=0; i < lineNumbers.length; i++){ // may appear in any order. for (int j=0; j < instructionPositions.length; j++){ // TODO: Make this a binary search! The instructionPositions array is naturally ordered! int offset = lineNumbers[i].getStartPC(); if (instructionPositions[j] == offset){ if (offsets.contains(offset)){ addMessage("LineNumberTable attribute '"+code.getLineNumberTable()+"' refers to the same code offset ('"+offset+"') more than once which is violating the semantics [but is sometimes produced by IBM's 'jikes' compiler]."); } else{ offsets.add(offset); } continue lineNumber_loop; } } throw new ClassConstraintException("Code attribute '"+code+"' has a LineNumberTable attribute '"+code.getLineNumberTable()+"' referring to a code offset ('"+lineNumbers[i].getStartPC()+"') that does not exist."); } } /////////////////////////// // LocalVariableTable(s) // /////////////////////////// /* We cannot use code.getLocalVariableTable() because there could be more than only one. This is a bug in BCEL. */ Attribute[] atts = code.getAttributes(); for (int a=0; a<atts.length; a++){ if (atts[a] instanceof LocalVariableTable){ LocalVariableTable lvt = (LocalVariableTable) atts[a]; if (lvt != null){ LocalVariable[] localVariables = lvt.getLocalVariableTable(); for (int i=0; i<localVariables.length; i++){ int startpc = localVariables[i].getStartPC(); int length = localVariables[i].getLength(); if (!contains(instructionPositions, startpc)){ throw new ClassConstraintException("Code attribute '"+code+"' has a LocalVariableTable attribute '"+code.getLocalVariableTable()+"' referring to a code offset ('"+startpc+"') that does not exist."); } if ( (!contains(instructionPositions, startpc+length)) && (startpc+length != codeLength) ){ throw new ClassConstraintException("Code attribute '"+code+"' has a LocalVariableTable attribute '"+code.getLocalVariableTable()+"' referring to a code offset start_pc+length ('"+(startpc+length)+"') that does not exist."); } } } } } //////////////////// // ExceptionTable // //////////////////// // In BCEL's "classfile" API, the startPC/endPC-notation is // inclusive/exclusive as in the Java Virtual Machine Specification. // WARNING: This is not true for BCEL's "generic" API. CodeException[] exceptionTable = code.getExceptionTable(); for (int i=0; i<exceptionTable.length; i++){ int startpc = exceptionTable[i].getStartPC(); int endpc = exceptionTable[i].getEndPC(); int handlerpc = exceptionTable[i].getHandlerPC(); if (startpc >= endpc){ throw new ClassConstraintException("Code attribute '"+code+"' has an exception_table entry '"+exceptionTable[i]+"' that has its start_pc ('"+startpc+"') not smaller than its end_pc ('"+endpc+"')."); } if (!contains(instructionPositions, startpc)){ throw new ClassConstraintException("Code attribute '"+code+"' has an exception_table entry '"+exceptionTable[i]+"' that has a non-existant bytecode offset as its start_pc ('"+startpc+"')."); } if ( (!contains(instructionPositions, endpc)) && (endpc != codeLength)){ throw new ClassConstraintException("Code attribute '"+code+"' has an exception_table entry '"+exceptionTable[i]+"' that has a non-existant bytecode offset as its end_pc ('"+startpc+"') [that is also not equal to code_length ('"+codeLength+"')]."); } if (!contains(instructionPositions, handlerpc)){ throw new ClassConstraintException("Code attribute '"+code+"' has an exception_table entry '"+exceptionTable[i]+"' that has a non-existant bytecode offset as its handler_pc ('"+handlerpc+"')."); } } } /** * These are the checks if constraints are satisfied which are described in the * Java Virtual Machine Specification, Second Edition as Static Constraints on * the instructions of Java Virtual Machine Code (chapter 4.8.1). * * @throws StaticCodeConstraintException if the verification fails. */ private void pass3StaticInstructionChecks(){ // Code array must not be empty: // Enforced in pass 2 (also stated in the static constraints of the Code // array in vmspec2), together with pass 1 (reading code_length bytes and // interpreting them as code[]). So this must not be checked again here. if (! (code.getCode().length < 65536)){// contradicts vmspec2 page 152 ("Limitations"), but is on page 134. throw new StaticCodeInstructionConstraintException("Code array in code attribute '"+code+"' too big: must be smaller than 65536 bytes."); } // First opcode at offset 0: okay, that's clear. Nothing to do. // Only instances of the instructions documented in Section 6.4 may appear in // the code array. // For BCEL's sake, we cannot handle WIDE stuff, but hopefully BCEL does its job right :) // The last byte of the last instruction in the code array must be the byte at index // code_length-1 : See the do_verify() comments. We actually don't iterate through the // byte array, but use an InstructionList so we cannot check for this. But BCEL does // things right, so it's implicitly okay. // TODO: Check how BCEL handles (and will handle) instructions like IMPDEP1, IMPDEP2, // BREAKPOINT... that BCEL knows about but which are illegal anyway. // We currently go the safe way here. InstructionHandle ih = instructionList.getStart(); while (ih != null){ Instruction i = ih.getInstruction(); if (i instanceof IMPDEP1){ throw new StaticCodeInstructionConstraintException("IMPDEP1 must not be in the code, it is an illegal instruction for _internal_ JVM use!"); } if (i instanceof IMPDEP2){ throw new StaticCodeInstructionConstraintException("IMPDEP2 must not be in the code, it is an illegal instruction for _internal_ JVM use!"); } if (i instanceof BREAKPOINT){ throw new StaticCodeInstructionConstraintException("BREAKPOINT must not be in the code, it is an illegal instruction for _internal_ JVM use!"); } ih = ih.getNext(); } // The original verifier seems to do this check here, too. // An unreachable last instruction may also not fall through the // end of the code, which is stupid -- but with the original // verifier's subroutine semantics one cannot predict reachability. Instruction last = instructionList.getEnd().getInstruction(); if (! ((last instanceof ReturnInstruction) || (last instanceof RET) || (last instanceof GotoInstruction) || (last instanceof ATHROW) )) // JSR / JSR_W would possibly RETurn and then fall off the code! throw new StaticCodeInstructionConstraintException("Execution must not fall off the bottom of the code array. This constraint is enforced statically as some existing verifiers do - so it may be a false alarm if the last instruction is not reachable."); } /** * These are the checks for the satisfaction of constraints which are described in the * Java Virtual Machine Specification, Second Edition as Static Constraints on * the operands of instructions of Java Virtual Machine Code (chapter 4.8.1). * BCEL parses the code array to create an InstructionList and therefore has to check * some of these constraints. Additional checks are also implemented here. * * @throws StaticCodeConstraintException if the verification fails. */ private void pass3StaticInstructionOperandsChecks(){ // When building up the InstructionList, BCEL has already done all those checks // mentioned in The Java Virtual Machine Specification, Second Edition, as // "static constraints on the operands of instructions in the code array". // TODO: see the do_verify() comments. Maybe we should really work on the // byte array first to give more comprehensive messages. // TODO: Review Exception API, possibly build in some "offending instruction" thing // when we're ready to insulate the offending instruction by doing the // above thing. // TODO: Implement as much as possible here. BCEL does _not_ check everything. ConstantPoolGen cpg = new ConstantPoolGen(Repository.lookupClass(myOwner.getClassName()).getConstantPool()); InstOperandConstraintVisitor v = new InstOperandConstraintVisitor(cpg); // Checks for the things BCEL does _not_ handle itself. InstructionHandle ih = instructionList.getStart(); while (ih != null){ Instruction i = ih.getInstruction(); // An "own" constraint, due to JustIce's new definition of what "subroutine" means. if (i instanceof JsrInstruction){ InstructionHandle target = ((JsrInstruction) i).getTarget(); if (target == instructionList.getStart()){ throw new StaticCodeInstructionOperandConstraintException("Due to JustIce's clear definition of subroutines, no JSR or JSR_W may have a top-level instruction (such as the very first instruction, which is targeted by instruction '"+ih+"' as its target."); } if (!(target.getInstruction() instanceof ASTORE)){ throw new StaticCodeInstructionOperandConstraintException("Due to JustIce's clear definition of subroutines, no JSR or JSR_W may target anything else than an ASTORE instruction. Instruction '"+ih+"' targets '"+target+"'."); } } // vmspec2, page 134-137 ih.accept(v); ih = ih.getNext(); } } /** A small utility method returning if a given int i is in the given int[] ints. */ private static boolean contains(int[] ints, int i){ for (int j=0; j<ints.length; j++){ if (ints[j]==i) return true; } return false; } /** Returns the method number as supplied when instantiating. */ public int getMethodNo(){ return method_no; } /** * This visitor class does the actual checking for the instruction * operand's constraints. */ private class InstOperandConstraintVisitor extends org.apache.bcel.generic.EmptyVisitor{ /** The ConstantPoolGen instance this Visitor operates on. */ private ConstantPoolGen cpg; /** The only Constructor. */ InstOperandConstraintVisitor(ConstantPoolGen cpg){ this.cpg = cpg; } /** * Utility method to return the max_locals value of the method verified * by the surrounding Pass3aVerifier instance. */ private int max_locals(){ return Repository.lookupClass(myOwner.getClassName()).getMethods()[method_no].getCode().getMaxLocals(); } /** * A utility method to always raise an exeption. */ private void constraintViolated(Instruction i, String message) { throw new StaticCodeInstructionOperandConstraintException("Instruction "+i+" constraint violated: "+message); } /** * A utility method to raise an exception if the index is not * a valid constant pool index. */ private void indexValid(Instruction i, int idx){ if (idx < 0 || idx >= cpg.getSize()){ constraintViolated(i, "Illegal constant pool index '"+idx+"'."); } } /////////////////////////////////////////////////////////// // The Java Virtual Machine Specification, pages 134-137 // /////////////////////////////////////////////////////////// /** * Assures the generic preconditions of a LoadClass instance. * The referenced class is loaded and pass2-verified. */ public void visitLoadClass(LoadClass o){ ObjectType t = o.getLoadClassType(cpg); if (t != null){// null means "no class is loaded" Verifier v = VerifierFactory.getVerifier(t.getClassName()); VerificationResult vr = v.doPass1(); if (vr.getStatus() != VerificationResult.VERIFIED_OK){ constraintViolated((Instruction) o, "Class '"+o.getLoadClassType(cpg).getClassName()+"' is referenced, but cannot be loaded: '"+vr+"'."); } } } // The target of each jump and branch instruction [...] must be the opcode [...] // BCEL _DOES_ handle this. // tableswitch: BCEL will do it, supposedly. // lookupswitch: BCEL will do it, supposedly. /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ // LDC and LDC_W (LDC_W is a subclass of LDC in BCEL's model) public void visitLDC(LDC o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! ( (c instanceof ConstantInteger) || (c instanceof ConstantFloat) || (c instanceof ConstantString) ) ){ constraintViolated(o, "Operand of LDC or LDC_W must be one of CONSTANT_Integer, CONSTANT_Float or CONSTANT_String, but is '"+c+"'."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ // LDC2_W public void visitLDC2_W(LDC2_W o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! ( (c instanceof ConstantLong) || (c instanceof ConstantDouble) ) ){ constraintViolated(o, "Operand of LDC2_W must be CONSTANT_Long or CONSTANT_Double, but is '"+c+"'."); } try{ indexValid(o, o.getIndex()+1); } catch(StaticCodeInstructionOperandConstraintException e){ throw new AssertionViolatedException("OOPS: Does not BCEL handle that? LDC2_W operand has a problem."); } } private Field findFieldinClass(String fieldname, Type fieldtype, JavaClass jc) { Field f = null; Field[] fields = jc.getFields(); for (int i=0; i<fields.length; i++){ if (fields[i].getName().equals(fieldname) && fields[i].getSignature().equals(fieldtype.getSignature())) { f = fields[i]; break; } } return f; } private Field findField(String fieldname, Type fieldtype, JavaClass jc) { Field f = findFieldinClass(fieldname, fieldtype, jc); if (f != null) return f; String[] interface_names = jc.getInterfaceNames(); for (int i = 0; i < interface_names.length; i++) { f = findField(fieldname, fieldtype, Repository.lookupClass(interface_names[i])); if (f != null) return f; } String superclass = jc.getSuperclassName(); if (superclass != null && ! superclass.equals(jc.getClassName())) { f = findField(fieldname, fieldtype, Repository.lookupClass(superclass)); } return f; } private Field findField(FieldInstruction o) { JavaClass jc = Repository.lookupClass(o.getClassType(cpg).getClassName()); Field f = findField(o.getFieldName(cpg), o.getFieldType(cpg), jc); if (f == null){ constraintViolated(o, "Referenced field '"+o.getFieldName(cpg)+"' does not exist in class '"+jc.getClassName()+"'."); } return f; } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ //getfield, putfield, getstatic, putstatic public void visitFieldInstruction(FieldInstruction o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantFieldref)){ constraintViolated(o, "Indexing a constant that's not a CONSTANT_Fieldref but a '"+c+"'."); } Field f = findField(o); if (f == null){ } else{ /* TODO: Check if assignment compatibility is sufficient. What does Sun do? */ Type f_type = Type.getType(f.getSignature()); Type o_type = o.getType(cpg); /* TODO: Is there a way to make BCEL tell us if a field has a void method's signature, i.e. "()I" instead of "I"? */ if (! f_type.equals(o_type)){ constraintViolated(o, "Referenced field '"+o.getFieldName(cpg)+"' has type '"+f_type+"' instead of '"+o_type+"' as expected."); } /* TODO: Check for access modifiers here. */ } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitInvokeInstruction(InvokeInstruction o){ indexValid(o, o.getIndex()); if ( (o instanceof INVOKEVIRTUAL) || (o instanceof INVOKESPECIAL) || (o instanceof INVOKESTATIC) ){ Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantMethodref)){ constraintViolated(o, "Indexing a constant that's not a CONSTANT_Methodref but a '"+c+"'."); } else{ // Constants are okay due to pass2. ConstantNameAndType cnat = (ConstantNameAndType) (cpg.getConstant(((ConstantMethodref) c).getNameAndTypeIndex())); ConstantUtf8 cutf8 = (ConstantUtf8) (cpg.getConstant(cnat.getNameIndex())); if (cutf8.getBytes().equals(Constants.CONSTRUCTOR_NAME) && (!(o instanceof INVOKESPECIAL)) ){ constraintViolated(o, "Only INVOKESPECIAL is allowed to invoke instance initialization methods."); } if ( (! (cutf8.getBytes().equals(Constants.CONSTRUCTOR_NAME)) ) && (cutf8.getBytes().startsWith("<")) ){ constraintViolated(o, "No method with a name beginning with '<' other than the instance initialization methods may be called by the method invocation instructions."); } } } else{ //if (o instanceof INVOKEINTERFACE){ Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantInterfaceMethodref)){ constraintViolated(o, "Indexing a constant that's not a CONSTANT_InterfaceMethodref but a '"+c+"'."); } // TODO: From time to time check if BCEL allows to detect if the // 'count' operand is consistent with the information in the // CONSTANT_InterfaceMethodref and if the last operand is zero. // By now, BCEL hides those two operands because they're superfluous. // Invoked method must not be <init> or <clinit> ConstantNameAndType cnat = (ConstantNameAndType) (cpg.getConstant(((ConstantInterfaceMethodref)c).getNameAndTypeIndex())); String name = ((ConstantUtf8) (cpg.getConstant(cnat.getNameIndex()))).getBytes(); if (name.equals(Constants.CONSTRUCTOR_NAME)){ constraintViolated(o, "Method to invoke must not be '"+Constants.CONSTRUCTOR_NAME+"'."); } if (name.equals(Constants.STATIC_INITIALIZER_NAME)){ constraintViolated(o, "Method to invoke must not be '"+Constants.STATIC_INITIALIZER_NAME+"'."); } } // The LoadClassType is the method-declaring class, so we have to check the other types. Type t = o.getReturnType(cpg); if (t instanceof ArrayType){ t = ((ArrayType) t).getBasicType(); } if (t instanceof ObjectType){ Verifier v = VerifierFactory.getVerifier(((ObjectType) t).getClassName()); VerificationResult vr = v.doPass2(); if (vr.getStatus() != VerificationResult.VERIFIED_OK){ constraintViolated(o, "Return type class/interface could not be verified successfully: '"+vr.getMessage()+"'."); } } Type[] ts = o.getArgumentTypes(cpg); for (int i=0; i<ts.length; i++){ t = ts[i]; if (t instanceof ArrayType){ t = ((ArrayType) t).getBasicType(); } if (t instanceof ObjectType){ Verifier v = VerifierFactory.getVerifier(((ObjectType) t).getClassName()); VerificationResult vr = v.doPass2(); if (vr.getStatus() != VerificationResult.VERIFIED_OK){ constraintViolated(o, "Argument type class/interface could not be verified successfully: '"+vr.getMessage()+"'."); } } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitINSTANCEOF(INSTANCEOF o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)){ constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitCHECKCAST(CHECKCAST o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)){ constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitNEW(NEW o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)){ constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } else{ ConstantUtf8 cutf8 = (ConstantUtf8) (cpg.getConstant( ((ConstantClass) c).getNameIndex() )); Type t = Type.getType("L"+cutf8.getBytes()+";"); if (t instanceof ArrayType){ constraintViolated(o, "NEW must not be used to create an array."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitMULTIANEWARRAY(MULTIANEWARRAY o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)){ constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } int dimensions2create = o.getDimensions(); if (dimensions2create < 1){ constraintViolated(o, "Number of dimensions to create must be greater than zero."); } Type t = o.getType(cpg); if (t instanceof ArrayType){ int dimensions = ((ArrayType) t).getDimensions(); if (dimensions < dimensions2create){ constraintViolated(o, "Not allowed to create array with more dimensions ('+dimensions2create+') than the one referenced by the CONSTANT_Class '"+t+"'."); } } else{ constraintViolated(o, "Expecting a CONSTANT_Class referencing an array type. [Constraint not found in The Java Virtual Machine Specification, Second Edition, 4.8.1]"); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitANEWARRAY(ANEWARRAY o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)){ constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } Type t = o.getType(cpg); if (t instanceof ArrayType){ int dimensions = ((ArrayType) t).getDimensions(); if (dimensions >= 255){ constraintViolated(o, "Not allowed to create an array with more than 255 dimensions."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitNEWARRAY(NEWARRAY o){ byte t = o.getTypecode(); if (! ( (t == Constants.T_BOOLEAN) || (t == Constants.T_CHAR) || (t == Constants.T_FLOAT) || (t == Constants.T_DOUBLE) || (t == Constants.T_BYTE) || (t == Constants.T_SHORT) || (t == Constants.T_INT) || (t == Constants.T_LONG) ) ){ constraintViolated(o, "Illegal type code '+t+' for 'atype' operand."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitILOAD(ILOAD o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitFLOAD(FLOAD o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitALOAD(ALOAD o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitISTORE(ISTORE o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitFSTORE(FSTORE o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitASTORE(ASTORE o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitIINC(IINC o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitRET(RET o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitLLOAD(LLOAD o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative. [Constraint by JustIce as an analogon to the single-slot xLOAD/xSTORE instructions; may not happen anyway.]"); } else{ int maxminus2 = max_locals()-2; if (idx > maxminus2){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-2 '"+maxminus2+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitDLOAD(DLOAD o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative. [Constraint by JustIce as an analogon to the single-slot xLOAD/xSTORE instructions; may not happen anyway.]"); } else{ int maxminus2 = max_locals()-2; if (idx > maxminus2){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-2 '"+maxminus2+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitLSTORE(LSTORE o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative. [Constraint by JustIce as an analogon to the single-slot xLOAD/xSTORE instructions; may not happen anyway.]"); } else{ int maxminus2 = max_locals()-2; if (idx > maxminus2){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-2 '"+maxminus2+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitDSTORE(DSTORE o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative. [Constraint by JustIce as an analogon to the single-slot xLOAD/xSTORE instructions; may not happen anyway.]"); } else{ int maxminus2 = max_locals()-2; if (idx > maxminus2){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-2 '"+maxminus2+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitLOOKUPSWITCH(LOOKUPSWITCH o){ int[] matchs = o.getMatchs(); int max = Integer.MIN_VALUE; for (int i=0; i<matchs.length; i++){ if (matchs[i] == max && i != 0){ constraintViolated(o, "Match '"+matchs[i]+"' occurs more than once."); } if (matchs[i] < max){ constraintViolated(o, "Lookup table must be sorted but isn't."); } else{ max = matchs[i]; } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitTABLESWITCH(TABLESWITCH o){ // "high" must be >= "low". We cannot check this, as BCEL hides // it from us. } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitPUTSTATIC(PUTSTATIC o){ String field_name = o.getFieldName(cpg); JavaClass jc = Repository.lookupClass(o.getClassType(cpg).getClassName()); Field[] fields = jc.getFields(); Field f = null; for (int i=0; i<fields.length; i++){ if (fields[i].getName().equals(field_name)){ f = fields[i]; break; } } if (f == null){ throw new AssertionViolatedException("Field not found?!?"); } if (f.isFinal()){ if (!(myOwner.getClassName().equals(o.getClassType(cpg).getClassName()))){ constraintViolated(o, "Referenced field '"+f+"' is final and must therefore be declared in the current class '"+myOwner.getClassName()+"' which is not the case: it is declared in '"+o.getClassType(cpg).getClassName()+"'."); } } if (! (f.isStatic())){ constraintViolated(o, "Referenced field '"+f+"' is not static which it should be."); } String meth_name = Repository.lookupClass(myOwner.getClassName()).getMethods()[method_no].getName(); // If it's an interface, it can be set only in <clinit>. if ((!(jc.isClass())) && (!(meth_name.equals(Constants.STATIC_INITIALIZER_NAME)))){ constraintViolated(o, "Interface field '"+f+"' must be set in a '"+Constants.STATIC_INITIALIZER_NAME+"' method."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitGETSTATIC(GETSTATIC o){ String field_name = o.getFieldName(cpg); JavaClass jc = Repository.lookupClass(o.getClassType(cpg).getClassName()); Field[] fields = jc.getFields(); Field f = null; for (int i=0; i<fields.length; i++){ if (fields[i].getName().equals(field_name)){ f = fields[i]; break; } } if (f == null){ throw new AssertionViolatedException("Field not found?!?"); } if (! (f.isStatic())){ constraintViolated(o, "Referenced field '"+f+"' is not static which it should be."); } } /* Checks if the constraints of operands of the said instruction(s) are satisfied. */ //public void visitPUTFIELD(PUTFIELD o){ // for performance reasons done in Pass 3b //} /* Checks if the constraints of operands of the said instruction(s) are satisfied. */ //public void visitGETFIELD(GETFIELD o){ // for performance reasons done in Pass 3b //} private Method findMethodinClass(String name, Type ret, Type[] args, JavaClass jc) { Method[] ms = jc.getMethods(); Method m = null; for (int i=0; i<ms.length; i++){ if ( (ms[i].getName().equals(name)) && (Type.getReturnType(ms[i].getSignature()).equals(ret)) && (objarrayequals(Type.getArgumentTypes(ms[i].getSignature()), args)) ){ m = ms[i]; break; } } return m; } private Method findMethod(String name, Type ret, Type[] args, JavaClass jc) { Method m = findMethodinClass(name, ret, args, jc); if (m != null) return m; String supername = jc.getSuperclassName(); - while (supername != null && ! supername.equals(jc.getClassName())) { - JavaClass j = Repository.lookupClass(supername); + JavaClass j = jc; + while (supername != null && ! supername.equals(j.getClassName())) { + j = Repository.lookupClass(supername); m = findMethodinClass(name, ret, args, j); if (m != null) return m; supername = j.getSuperclassName(); } String[] intfs = jc.getInterfaceNames(); for (int i = 0; i < intfs.length; i++) { m = findMethodinClass(name, ret, args, Repository.lookupClass(intfs[i])); if (m != null) return m; } return m; } private Method findMethod(InvokeInstruction o) { String classname = o.getClassName(cpg); JavaClass jc = Repository.lookupClass(classname); String methodname = o.getMethodName(cpg); Type returntype = o.getReturnType(cpg); Type[] argumenttypes = o.getArgumentTypes(cpg); Method m = findMethod(methodname, returntype, argumenttypes, jc); if (m == null){ constraintViolated(o, "Referenced method '"+o.getMethodName(cpg)+"' with expected signature not found in class '"+jc.getClassName()+"'."); } return m; } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitINVOKEINTERFACE(INVOKEINTERFACE o){ // INVOKEINTERFACE is a LoadClass; the Class where the referenced method is declared in, // is therefore resolved/verified. // INVOKEINTERFACE is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. Method m = findMethod(o); String classname = o.getClassName(cpg); JavaClass jc = Repository.lookupClass(classname); if (jc.isClass()){ constraintViolated(o, "Referenced class '"+jc.getClassName()+"' is a class, but not an interface as expected."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitINVOKESPECIAL(INVOKESPECIAL o){ // INVOKESPECIAL is a LoadClass; the Class where the referenced method is declared in, // is therefore resolved/verified. // INVOKESPECIAL is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. Method m = findMethod(o); String classname = o.getClassName(cpg); JavaClass jc = Repository.lookupClass(classname); JavaClass current = Repository.lookupClass(myOwner.getClassName()); if (current.isSuper()){ if ((Repository.instanceOf( current, jc )) && (!current.equals(jc))){ if (! (o.getMethodName(cpg).equals(Constants.CONSTRUCTOR_NAME) )){ // Special lookup procedure for ACC_SUPER classes. int supidx = -1; Method meth = null; while (supidx != 0){ supidx = current.getSuperclassNameIndex(); current = Repository.lookupClass(current.getSuperclassName()); Method[] meths = current.getMethods(); for (int i=0; i<meths.length; i++){ if ( (meths[i].getName().equals(o.getMethodName(cpg))) && (Type.getReturnType(meths[i].getSignature()).equals(o.getReturnType(cpg))) && (objarrayequals(Type.getArgumentTypes(meths[i].getSignature()), o.getArgumentTypes(cpg))) ){ meth = meths[i]; break; } } if (meth != null) break; } if (meth == null){ constraintViolated(o, "ACC_SUPER special lookup procedure not successful: method '"+o.getMethodName(cpg)+"' with proper signature not declared in superclass hierarchy."); } } } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitINVOKESTATIC(INVOKESTATIC o){ // INVOKESTATIC is a LoadClass; the Class where the referenced method is declared in, // is therefore resolved/verified. // INVOKESTATIC is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. Method m = findMethod(o); if (! (m.isStatic())){ // implies it's not abstract, verified in pass 2. constraintViolated(o, "Referenced method '"+o.getMethodName(cpg)+"' has ACC_STATIC unset."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitINVOKEVIRTUAL(INVOKEVIRTUAL o){ // INVOKEVIRTUAL is a LoadClass; the Class where the referenced method is declared in, // is therefore resolved/verified. // INVOKEVIRTUAL is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. String classname = o.getClassName(cpg); JavaClass jc = Repository.lookupClass(classname); Method m = findMethod(o); if (! (jc.isClass())){ constraintViolated(o, "Referenced class '"+jc.getClassName()+"' is an interface, but not a class as expected."); } } // WIDE stuff is BCEL-internal and cannot be checked here. /** * A utility method like equals(Object) for arrays. * The equality of the elements is based on their equals(Object) * method instead of their object identity. */ private boolean objarrayequals(Object[] o, Object[] p){ if (o.length != p.length){ return false; } for (int i=0; i<o.length; i++){ if (! (o[i].equals(p[i])) ){ return false; } } return true; } } }
true
true
public void visitInvokeInstruction(InvokeInstruction o){ indexValid(o, o.getIndex()); if ( (o instanceof INVOKEVIRTUAL) || (o instanceof INVOKESPECIAL) || (o instanceof INVOKESTATIC) ){ Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantMethodref)){ constraintViolated(o, "Indexing a constant that's not a CONSTANT_Methodref but a '"+c+"'."); } else{ // Constants are okay due to pass2. ConstantNameAndType cnat = (ConstantNameAndType) (cpg.getConstant(((ConstantMethodref) c).getNameAndTypeIndex())); ConstantUtf8 cutf8 = (ConstantUtf8) (cpg.getConstant(cnat.getNameIndex())); if (cutf8.getBytes().equals(Constants.CONSTRUCTOR_NAME) && (!(o instanceof INVOKESPECIAL)) ){ constraintViolated(o, "Only INVOKESPECIAL is allowed to invoke instance initialization methods."); } if ( (! (cutf8.getBytes().equals(Constants.CONSTRUCTOR_NAME)) ) && (cutf8.getBytes().startsWith("<")) ){ constraintViolated(o, "No method with a name beginning with '<' other than the instance initialization methods may be called by the method invocation instructions."); } } } else{ //if (o instanceof INVOKEINTERFACE){ Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantInterfaceMethodref)){ constraintViolated(o, "Indexing a constant that's not a CONSTANT_InterfaceMethodref but a '"+c+"'."); } // TODO: From time to time check if BCEL allows to detect if the // 'count' operand is consistent with the information in the // CONSTANT_InterfaceMethodref and if the last operand is zero. // By now, BCEL hides those two operands because they're superfluous. // Invoked method must not be <init> or <clinit> ConstantNameAndType cnat = (ConstantNameAndType) (cpg.getConstant(((ConstantInterfaceMethodref)c).getNameAndTypeIndex())); String name = ((ConstantUtf8) (cpg.getConstant(cnat.getNameIndex()))).getBytes(); if (name.equals(Constants.CONSTRUCTOR_NAME)){ constraintViolated(o, "Method to invoke must not be '"+Constants.CONSTRUCTOR_NAME+"'."); } if (name.equals(Constants.STATIC_INITIALIZER_NAME)){ constraintViolated(o, "Method to invoke must not be '"+Constants.STATIC_INITIALIZER_NAME+"'."); } } // The LoadClassType is the method-declaring class, so we have to check the other types. Type t = o.getReturnType(cpg); if (t instanceof ArrayType){ t = ((ArrayType) t).getBasicType(); } if (t instanceof ObjectType){ Verifier v = VerifierFactory.getVerifier(((ObjectType) t).getClassName()); VerificationResult vr = v.doPass2(); if (vr.getStatus() != VerificationResult.VERIFIED_OK){ constraintViolated(o, "Return type class/interface could not be verified successfully: '"+vr.getMessage()+"'."); } } Type[] ts = o.getArgumentTypes(cpg); for (int i=0; i<ts.length; i++){ t = ts[i]; if (t instanceof ArrayType){ t = ((ArrayType) t).getBasicType(); } if (t instanceof ObjectType){ Verifier v = VerifierFactory.getVerifier(((ObjectType) t).getClassName()); VerificationResult vr = v.doPass2(); if (vr.getStatus() != VerificationResult.VERIFIED_OK){ constraintViolated(o, "Argument type class/interface could not be verified successfully: '"+vr.getMessage()+"'."); } } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitINSTANCEOF(INSTANCEOF o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)){ constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitCHECKCAST(CHECKCAST o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)){ constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitNEW(NEW o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)){ constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } else{ ConstantUtf8 cutf8 = (ConstantUtf8) (cpg.getConstant( ((ConstantClass) c).getNameIndex() )); Type t = Type.getType("L"+cutf8.getBytes()+";"); if (t instanceof ArrayType){ constraintViolated(o, "NEW must not be used to create an array."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitMULTIANEWARRAY(MULTIANEWARRAY o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)){ constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } int dimensions2create = o.getDimensions(); if (dimensions2create < 1){ constraintViolated(o, "Number of dimensions to create must be greater than zero."); } Type t = o.getType(cpg); if (t instanceof ArrayType){ int dimensions = ((ArrayType) t).getDimensions(); if (dimensions < dimensions2create){ constraintViolated(o, "Not allowed to create array with more dimensions ('+dimensions2create+') than the one referenced by the CONSTANT_Class '"+t+"'."); } } else{ constraintViolated(o, "Expecting a CONSTANT_Class referencing an array type. [Constraint not found in The Java Virtual Machine Specification, Second Edition, 4.8.1]"); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitANEWARRAY(ANEWARRAY o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)){ constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } Type t = o.getType(cpg); if (t instanceof ArrayType){ int dimensions = ((ArrayType) t).getDimensions(); if (dimensions >= 255){ constraintViolated(o, "Not allowed to create an array with more than 255 dimensions."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitNEWARRAY(NEWARRAY o){ byte t = o.getTypecode(); if (! ( (t == Constants.T_BOOLEAN) || (t == Constants.T_CHAR) || (t == Constants.T_FLOAT) || (t == Constants.T_DOUBLE) || (t == Constants.T_BYTE) || (t == Constants.T_SHORT) || (t == Constants.T_INT) || (t == Constants.T_LONG) ) ){ constraintViolated(o, "Illegal type code '+t+' for 'atype' operand."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitILOAD(ILOAD o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitFLOAD(FLOAD o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitALOAD(ALOAD o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitISTORE(ISTORE o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitFSTORE(FSTORE o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitASTORE(ASTORE o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitIINC(IINC o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitRET(RET o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitLLOAD(LLOAD o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative. [Constraint by JustIce as an analogon to the single-slot xLOAD/xSTORE instructions; may not happen anyway.]"); } else{ int maxminus2 = max_locals()-2; if (idx > maxminus2){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-2 '"+maxminus2+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitDLOAD(DLOAD o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative. [Constraint by JustIce as an analogon to the single-slot xLOAD/xSTORE instructions; may not happen anyway.]"); } else{ int maxminus2 = max_locals()-2; if (idx > maxminus2){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-2 '"+maxminus2+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitLSTORE(LSTORE o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative. [Constraint by JustIce as an analogon to the single-slot xLOAD/xSTORE instructions; may not happen anyway.]"); } else{ int maxminus2 = max_locals()-2; if (idx > maxminus2){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-2 '"+maxminus2+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitDSTORE(DSTORE o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative. [Constraint by JustIce as an analogon to the single-slot xLOAD/xSTORE instructions; may not happen anyway.]"); } else{ int maxminus2 = max_locals()-2; if (idx > maxminus2){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-2 '"+maxminus2+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitLOOKUPSWITCH(LOOKUPSWITCH o){ int[] matchs = o.getMatchs(); int max = Integer.MIN_VALUE; for (int i=0; i<matchs.length; i++){ if (matchs[i] == max && i != 0){ constraintViolated(o, "Match '"+matchs[i]+"' occurs more than once."); } if (matchs[i] < max){ constraintViolated(o, "Lookup table must be sorted but isn't."); } else{ max = matchs[i]; } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitTABLESWITCH(TABLESWITCH o){ // "high" must be >= "low". We cannot check this, as BCEL hides // it from us. } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitPUTSTATIC(PUTSTATIC o){ String field_name = o.getFieldName(cpg); JavaClass jc = Repository.lookupClass(o.getClassType(cpg).getClassName()); Field[] fields = jc.getFields(); Field f = null; for (int i=0; i<fields.length; i++){ if (fields[i].getName().equals(field_name)){ f = fields[i]; break; } } if (f == null){ throw new AssertionViolatedException("Field not found?!?"); } if (f.isFinal()){ if (!(myOwner.getClassName().equals(o.getClassType(cpg).getClassName()))){ constraintViolated(o, "Referenced field '"+f+"' is final and must therefore be declared in the current class '"+myOwner.getClassName()+"' which is not the case: it is declared in '"+o.getClassType(cpg).getClassName()+"'."); } } if (! (f.isStatic())){ constraintViolated(o, "Referenced field '"+f+"' is not static which it should be."); } String meth_name = Repository.lookupClass(myOwner.getClassName()).getMethods()[method_no].getName(); // If it's an interface, it can be set only in <clinit>. if ((!(jc.isClass())) && (!(meth_name.equals(Constants.STATIC_INITIALIZER_NAME)))){ constraintViolated(o, "Interface field '"+f+"' must be set in a '"+Constants.STATIC_INITIALIZER_NAME+"' method."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitGETSTATIC(GETSTATIC o){ String field_name = o.getFieldName(cpg); JavaClass jc = Repository.lookupClass(o.getClassType(cpg).getClassName()); Field[] fields = jc.getFields(); Field f = null; for (int i=0; i<fields.length; i++){ if (fields[i].getName().equals(field_name)){ f = fields[i]; break; } } if (f == null){ throw new AssertionViolatedException("Field not found?!?"); } if (! (f.isStatic())){ constraintViolated(o, "Referenced field '"+f+"' is not static which it should be."); } } /* Checks if the constraints of operands of the said instruction(s) are satisfied. */ //public void visitPUTFIELD(PUTFIELD o){ // for performance reasons done in Pass 3b //} /* Checks if the constraints of operands of the said instruction(s) are satisfied. */ //public void visitGETFIELD(GETFIELD o){ // for performance reasons done in Pass 3b //} private Method findMethodinClass(String name, Type ret, Type[] args, JavaClass jc) { Method[] ms = jc.getMethods(); Method m = null; for (int i=0; i<ms.length; i++){ if ( (ms[i].getName().equals(name)) && (Type.getReturnType(ms[i].getSignature()).equals(ret)) && (objarrayequals(Type.getArgumentTypes(ms[i].getSignature()), args)) ){ m = ms[i]; break; } } return m; } private Method findMethod(String name, Type ret, Type[] args, JavaClass jc) { Method m = findMethodinClass(name, ret, args, jc); if (m != null) return m; String supername = jc.getSuperclassName(); while (supername != null && ! supername.equals(jc.getClassName())) { JavaClass j = Repository.lookupClass(supername); m = findMethodinClass(name, ret, args, j); if (m != null) return m; supername = j.getSuperclassName(); } String[] intfs = jc.getInterfaceNames(); for (int i = 0; i < intfs.length; i++) { m = findMethodinClass(name, ret, args, Repository.lookupClass(intfs[i])); if (m != null) return m; } return m; } private Method findMethod(InvokeInstruction o) { String classname = o.getClassName(cpg); JavaClass jc = Repository.lookupClass(classname); String methodname = o.getMethodName(cpg); Type returntype = o.getReturnType(cpg); Type[] argumenttypes = o.getArgumentTypes(cpg); Method m = findMethod(methodname, returntype, argumenttypes, jc); if (m == null){ constraintViolated(o, "Referenced method '"+o.getMethodName(cpg)+"' with expected signature not found in class '"+jc.getClassName()+"'."); } return m; } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitINVOKEINTERFACE(INVOKEINTERFACE o){ // INVOKEINTERFACE is a LoadClass; the Class where the referenced method is declared in, // is therefore resolved/verified. // INVOKEINTERFACE is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. Method m = findMethod(o); String classname = o.getClassName(cpg); JavaClass jc = Repository.lookupClass(classname); if (jc.isClass()){ constraintViolated(o, "Referenced class '"+jc.getClassName()+"' is a class, but not an interface as expected."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitINVOKESPECIAL(INVOKESPECIAL o){ // INVOKESPECIAL is a LoadClass; the Class where the referenced method is declared in, // is therefore resolved/verified. // INVOKESPECIAL is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. Method m = findMethod(o); String classname = o.getClassName(cpg); JavaClass jc = Repository.lookupClass(classname); JavaClass current = Repository.lookupClass(myOwner.getClassName()); if (current.isSuper()){ if ((Repository.instanceOf( current, jc )) && (!current.equals(jc))){ if (! (o.getMethodName(cpg).equals(Constants.CONSTRUCTOR_NAME) )){ // Special lookup procedure for ACC_SUPER classes. int supidx = -1; Method meth = null; while (supidx != 0){ supidx = current.getSuperclassNameIndex(); current = Repository.lookupClass(current.getSuperclassName()); Method[] meths = current.getMethods(); for (int i=0; i<meths.length; i++){ if ( (meths[i].getName().equals(o.getMethodName(cpg))) && (Type.getReturnType(meths[i].getSignature()).equals(o.getReturnType(cpg))) && (objarrayequals(Type.getArgumentTypes(meths[i].getSignature()), o.getArgumentTypes(cpg))) ){ meth = meths[i]; break; } } if (meth != null) break; } if (meth == null){ constraintViolated(o, "ACC_SUPER special lookup procedure not successful: method '"+o.getMethodName(cpg)+"' with proper signature not declared in superclass hierarchy."); } } } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitINVOKESTATIC(INVOKESTATIC o){ // INVOKESTATIC is a LoadClass; the Class where the referenced method is declared in, // is therefore resolved/verified. // INVOKESTATIC is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. Method m = findMethod(o); if (! (m.isStatic())){ // implies it's not abstract, verified in pass 2. constraintViolated(o, "Referenced method '"+o.getMethodName(cpg)+"' has ACC_STATIC unset."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitINVOKEVIRTUAL(INVOKEVIRTUAL o){ // INVOKEVIRTUAL is a LoadClass; the Class where the referenced method is declared in, // is therefore resolved/verified. // INVOKEVIRTUAL is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. String classname = o.getClassName(cpg); JavaClass jc = Repository.lookupClass(classname); Method m = findMethod(o); if (! (jc.isClass())){ constraintViolated(o, "Referenced class '"+jc.getClassName()+"' is an interface, but not a class as expected."); } } // WIDE stuff is BCEL-internal and cannot be checked here. /** * A utility method like equals(Object) for arrays. * The equality of the elements is based on their equals(Object) * method instead of their object identity. */ private boolean objarrayequals(Object[] o, Object[] p){ if (o.length != p.length){ return false; } for (int i=0; i<o.length; i++){ if (! (o[i].equals(p[i])) ){ return false; } } return true; } }
public void visitInvokeInstruction(InvokeInstruction o){ indexValid(o, o.getIndex()); if ( (o instanceof INVOKEVIRTUAL) || (o instanceof INVOKESPECIAL) || (o instanceof INVOKESTATIC) ){ Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantMethodref)){ constraintViolated(o, "Indexing a constant that's not a CONSTANT_Methodref but a '"+c+"'."); } else{ // Constants are okay due to pass2. ConstantNameAndType cnat = (ConstantNameAndType) (cpg.getConstant(((ConstantMethodref) c).getNameAndTypeIndex())); ConstantUtf8 cutf8 = (ConstantUtf8) (cpg.getConstant(cnat.getNameIndex())); if (cutf8.getBytes().equals(Constants.CONSTRUCTOR_NAME) && (!(o instanceof INVOKESPECIAL)) ){ constraintViolated(o, "Only INVOKESPECIAL is allowed to invoke instance initialization methods."); } if ( (! (cutf8.getBytes().equals(Constants.CONSTRUCTOR_NAME)) ) && (cutf8.getBytes().startsWith("<")) ){ constraintViolated(o, "No method with a name beginning with '<' other than the instance initialization methods may be called by the method invocation instructions."); } } } else{ //if (o instanceof INVOKEINTERFACE){ Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantInterfaceMethodref)){ constraintViolated(o, "Indexing a constant that's not a CONSTANT_InterfaceMethodref but a '"+c+"'."); } // TODO: From time to time check if BCEL allows to detect if the // 'count' operand is consistent with the information in the // CONSTANT_InterfaceMethodref and if the last operand is zero. // By now, BCEL hides those two operands because they're superfluous. // Invoked method must not be <init> or <clinit> ConstantNameAndType cnat = (ConstantNameAndType) (cpg.getConstant(((ConstantInterfaceMethodref)c).getNameAndTypeIndex())); String name = ((ConstantUtf8) (cpg.getConstant(cnat.getNameIndex()))).getBytes(); if (name.equals(Constants.CONSTRUCTOR_NAME)){ constraintViolated(o, "Method to invoke must not be '"+Constants.CONSTRUCTOR_NAME+"'."); } if (name.equals(Constants.STATIC_INITIALIZER_NAME)){ constraintViolated(o, "Method to invoke must not be '"+Constants.STATIC_INITIALIZER_NAME+"'."); } } // The LoadClassType is the method-declaring class, so we have to check the other types. Type t = o.getReturnType(cpg); if (t instanceof ArrayType){ t = ((ArrayType) t).getBasicType(); } if (t instanceof ObjectType){ Verifier v = VerifierFactory.getVerifier(((ObjectType) t).getClassName()); VerificationResult vr = v.doPass2(); if (vr.getStatus() != VerificationResult.VERIFIED_OK){ constraintViolated(o, "Return type class/interface could not be verified successfully: '"+vr.getMessage()+"'."); } } Type[] ts = o.getArgumentTypes(cpg); for (int i=0; i<ts.length; i++){ t = ts[i]; if (t instanceof ArrayType){ t = ((ArrayType) t).getBasicType(); } if (t instanceof ObjectType){ Verifier v = VerifierFactory.getVerifier(((ObjectType) t).getClassName()); VerificationResult vr = v.doPass2(); if (vr.getStatus() != VerificationResult.VERIFIED_OK){ constraintViolated(o, "Argument type class/interface could not be verified successfully: '"+vr.getMessage()+"'."); } } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitINSTANCEOF(INSTANCEOF o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)){ constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitCHECKCAST(CHECKCAST o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)){ constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitNEW(NEW o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)){ constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } else{ ConstantUtf8 cutf8 = (ConstantUtf8) (cpg.getConstant( ((ConstantClass) c).getNameIndex() )); Type t = Type.getType("L"+cutf8.getBytes()+";"); if (t instanceof ArrayType){ constraintViolated(o, "NEW must not be used to create an array."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitMULTIANEWARRAY(MULTIANEWARRAY o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)){ constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } int dimensions2create = o.getDimensions(); if (dimensions2create < 1){ constraintViolated(o, "Number of dimensions to create must be greater than zero."); } Type t = o.getType(cpg); if (t instanceof ArrayType){ int dimensions = ((ArrayType) t).getDimensions(); if (dimensions < dimensions2create){ constraintViolated(o, "Not allowed to create array with more dimensions ('+dimensions2create+') than the one referenced by the CONSTANT_Class '"+t+"'."); } } else{ constraintViolated(o, "Expecting a CONSTANT_Class referencing an array type. [Constraint not found in The Java Virtual Machine Specification, Second Edition, 4.8.1]"); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitANEWARRAY(ANEWARRAY o){ indexValid(o, o.getIndex()); Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)){ constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } Type t = o.getType(cpg); if (t instanceof ArrayType){ int dimensions = ((ArrayType) t).getDimensions(); if (dimensions >= 255){ constraintViolated(o, "Not allowed to create an array with more than 255 dimensions."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitNEWARRAY(NEWARRAY o){ byte t = o.getTypecode(); if (! ( (t == Constants.T_BOOLEAN) || (t == Constants.T_CHAR) || (t == Constants.T_FLOAT) || (t == Constants.T_DOUBLE) || (t == Constants.T_BYTE) || (t == Constants.T_SHORT) || (t == Constants.T_INT) || (t == Constants.T_LONG) ) ){ constraintViolated(o, "Illegal type code '+t+' for 'atype' operand."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitILOAD(ILOAD o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitFLOAD(FLOAD o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitALOAD(ALOAD o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitISTORE(ISTORE o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitFSTORE(FSTORE o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitASTORE(ASTORE o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitIINC(IINC o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitRET(RET o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ int maxminus1 = max_locals()-1; if (idx > maxminus1){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitLLOAD(LLOAD o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative. [Constraint by JustIce as an analogon to the single-slot xLOAD/xSTORE instructions; may not happen anyway.]"); } else{ int maxminus2 = max_locals()-2; if (idx > maxminus2){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-2 '"+maxminus2+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitDLOAD(DLOAD o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative. [Constraint by JustIce as an analogon to the single-slot xLOAD/xSTORE instructions; may not happen anyway.]"); } else{ int maxminus2 = max_locals()-2; if (idx > maxminus2){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-2 '"+maxminus2+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitLSTORE(LSTORE o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative. [Constraint by JustIce as an analogon to the single-slot xLOAD/xSTORE instructions; may not happen anyway.]"); } else{ int maxminus2 = max_locals()-2; if (idx > maxminus2){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-2 '"+maxminus2+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitDSTORE(DSTORE o){ int idx = o.getIndex(); if (idx < 0){ constraintViolated(o, "Index '"+idx+"' must be non-negative. [Constraint by JustIce as an analogon to the single-slot xLOAD/xSTORE instructions; may not happen anyway.]"); } else{ int maxminus2 = max_locals()-2; if (idx > maxminus2){ constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-2 '"+maxminus2+"'."); } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitLOOKUPSWITCH(LOOKUPSWITCH o){ int[] matchs = o.getMatchs(); int max = Integer.MIN_VALUE; for (int i=0; i<matchs.length; i++){ if (matchs[i] == max && i != 0){ constraintViolated(o, "Match '"+matchs[i]+"' occurs more than once."); } if (matchs[i] < max){ constraintViolated(o, "Lookup table must be sorted but isn't."); } else{ max = matchs[i]; } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitTABLESWITCH(TABLESWITCH o){ // "high" must be >= "low". We cannot check this, as BCEL hides // it from us. } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitPUTSTATIC(PUTSTATIC o){ String field_name = o.getFieldName(cpg); JavaClass jc = Repository.lookupClass(o.getClassType(cpg).getClassName()); Field[] fields = jc.getFields(); Field f = null; for (int i=0; i<fields.length; i++){ if (fields[i].getName().equals(field_name)){ f = fields[i]; break; } } if (f == null){ throw new AssertionViolatedException("Field not found?!?"); } if (f.isFinal()){ if (!(myOwner.getClassName().equals(o.getClassType(cpg).getClassName()))){ constraintViolated(o, "Referenced field '"+f+"' is final and must therefore be declared in the current class '"+myOwner.getClassName()+"' which is not the case: it is declared in '"+o.getClassType(cpg).getClassName()+"'."); } } if (! (f.isStatic())){ constraintViolated(o, "Referenced field '"+f+"' is not static which it should be."); } String meth_name = Repository.lookupClass(myOwner.getClassName()).getMethods()[method_no].getName(); // If it's an interface, it can be set only in <clinit>. if ((!(jc.isClass())) && (!(meth_name.equals(Constants.STATIC_INITIALIZER_NAME)))){ constraintViolated(o, "Interface field '"+f+"' must be set in a '"+Constants.STATIC_INITIALIZER_NAME+"' method."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitGETSTATIC(GETSTATIC o){ String field_name = o.getFieldName(cpg); JavaClass jc = Repository.lookupClass(o.getClassType(cpg).getClassName()); Field[] fields = jc.getFields(); Field f = null; for (int i=0; i<fields.length; i++){ if (fields[i].getName().equals(field_name)){ f = fields[i]; break; } } if (f == null){ throw new AssertionViolatedException("Field not found?!?"); } if (! (f.isStatic())){ constraintViolated(o, "Referenced field '"+f+"' is not static which it should be."); } } /* Checks if the constraints of operands of the said instruction(s) are satisfied. */ //public void visitPUTFIELD(PUTFIELD o){ // for performance reasons done in Pass 3b //} /* Checks if the constraints of operands of the said instruction(s) are satisfied. */ //public void visitGETFIELD(GETFIELD o){ // for performance reasons done in Pass 3b //} private Method findMethodinClass(String name, Type ret, Type[] args, JavaClass jc) { Method[] ms = jc.getMethods(); Method m = null; for (int i=0; i<ms.length; i++){ if ( (ms[i].getName().equals(name)) && (Type.getReturnType(ms[i].getSignature()).equals(ret)) && (objarrayequals(Type.getArgumentTypes(ms[i].getSignature()), args)) ){ m = ms[i]; break; } } return m; } private Method findMethod(String name, Type ret, Type[] args, JavaClass jc) { Method m = findMethodinClass(name, ret, args, jc); if (m != null) return m; String supername = jc.getSuperclassName(); JavaClass j = jc; while (supername != null && ! supername.equals(j.getClassName())) { j = Repository.lookupClass(supername); m = findMethodinClass(name, ret, args, j); if (m != null) return m; supername = j.getSuperclassName(); } String[] intfs = jc.getInterfaceNames(); for (int i = 0; i < intfs.length; i++) { m = findMethodinClass(name, ret, args, Repository.lookupClass(intfs[i])); if (m != null) return m; } return m; } private Method findMethod(InvokeInstruction o) { String classname = o.getClassName(cpg); JavaClass jc = Repository.lookupClass(classname); String methodname = o.getMethodName(cpg); Type returntype = o.getReturnType(cpg); Type[] argumenttypes = o.getArgumentTypes(cpg); Method m = findMethod(methodname, returntype, argumenttypes, jc); if (m == null){ constraintViolated(o, "Referenced method '"+o.getMethodName(cpg)+"' with expected signature not found in class '"+jc.getClassName()+"'."); } return m; } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitINVOKEINTERFACE(INVOKEINTERFACE o){ // INVOKEINTERFACE is a LoadClass; the Class where the referenced method is declared in, // is therefore resolved/verified. // INVOKEINTERFACE is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. Method m = findMethod(o); String classname = o.getClassName(cpg); JavaClass jc = Repository.lookupClass(classname); if (jc.isClass()){ constraintViolated(o, "Referenced class '"+jc.getClassName()+"' is a class, but not an interface as expected."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitINVOKESPECIAL(INVOKESPECIAL o){ // INVOKESPECIAL is a LoadClass; the Class where the referenced method is declared in, // is therefore resolved/verified. // INVOKESPECIAL is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. Method m = findMethod(o); String classname = o.getClassName(cpg); JavaClass jc = Repository.lookupClass(classname); JavaClass current = Repository.lookupClass(myOwner.getClassName()); if (current.isSuper()){ if ((Repository.instanceOf( current, jc )) && (!current.equals(jc))){ if (! (o.getMethodName(cpg).equals(Constants.CONSTRUCTOR_NAME) )){ // Special lookup procedure for ACC_SUPER classes. int supidx = -1; Method meth = null; while (supidx != 0){ supidx = current.getSuperclassNameIndex(); current = Repository.lookupClass(current.getSuperclassName()); Method[] meths = current.getMethods(); for (int i=0; i<meths.length; i++){ if ( (meths[i].getName().equals(o.getMethodName(cpg))) && (Type.getReturnType(meths[i].getSignature()).equals(o.getReturnType(cpg))) && (objarrayequals(Type.getArgumentTypes(meths[i].getSignature()), o.getArgumentTypes(cpg))) ){ meth = meths[i]; break; } } if (meth != null) break; } if (meth == null){ constraintViolated(o, "ACC_SUPER special lookup procedure not successful: method '"+o.getMethodName(cpg)+"' with proper signature not declared in superclass hierarchy."); } } } } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitINVOKESTATIC(INVOKESTATIC o){ // INVOKESTATIC is a LoadClass; the Class where the referenced method is declared in, // is therefore resolved/verified. // INVOKESTATIC is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. Method m = findMethod(o); if (! (m.isStatic())){ // implies it's not abstract, verified in pass 2. constraintViolated(o, "Referenced method '"+o.getMethodName(cpg)+"' has ACC_STATIC unset."); } } /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ public void visitINVOKEVIRTUAL(INVOKEVIRTUAL o){ // INVOKEVIRTUAL is a LoadClass; the Class where the referenced method is declared in, // is therefore resolved/verified. // INVOKEVIRTUAL is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. String classname = o.getClassName(cpg); JavaClass jc = Repository.lookupClass(classname); Method m = findMethod(o); if (! (jc.isClass())){ constraintViolated(o, "Referenced class '"+jc.getClassName()+"' is an interface, but not a class as expected."); } } // WIDE stuff is BCEL-internal and cannot be checked here. /** * A utility method like equals(Object) for arrays. * The equality of the elements is based on their equals(Object) * method instead of their object identity. */ private boolean objarrayequals(Object[] o, Object[] p){ if (o.length != p.length){ return false; } for (int i=0; i<o.length; i++){ if (! (o[i].equals(p[i])) ){ return false; } } return true; } }
diff --git a/com.uwusoft.timesheet/src/com/uwusoft/timesheet/util/AutomaticCheckoutCheckinUtil.java b/com.uwusoft.timesheet/src/com/uwusoft/timesheet/util/AutomaticCheckoutCheckinUtil.java index d30d3bb..b104bfa 100644 --- a/com.uwusoft.timesheet/src/com/uwusoft/timesheet/util/AutomaticCheckoutCheckinUtil.java +++ b/com.uwusoft.timesheet/src/com/uwusoft/timesheet/util/AutomaticCheckoutCheckinUtil.java @@ -1,118 +1,118 @@ package com.uwusoft.timesheet.util; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; import org.eclipse.core.commands.ParameterizedCommand; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.commands.ICommandService; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.services.ISourceProviderService; import com.uwusoft.timesheet.Activator; import com.uwusoft.timesheet.TimesheetApp; import com.uwusoft.timesheet.commands.SessionSourceProvider; import com.uwusoft.timesheet.dialog.AllDayTaskDateDialog; import com.uwusoft.timesheet.extensionpoint.LocalStorageService; import com.uwusoft.timesheet.extensionpoint.StorageService; import com.uwusoft.timesheet.model.AllDayTasks; import com.uwusoft.timesheet.model.TaskEntry; public class AutomaticCheckoutCheckinUtil { public static void execute() { LocalStorageService storageService = LocalStorageService.getInstance(); Date startDate = TimesheetApp.startDate; Date shutdownDate = TimesheetApp.shutDownDate; Date lastDate = storageService.getLastTaskEntryDate(); if (lastDate == null) lastDate = BusinessDayUtil.getPreviousBusinessDay(new Date()); if (shutdownDate.before(lastDate)) shutdownDate = lastDate; int startDay = getDay(startDate); final int startWeek = getWeek(startDate); int shutdownDay = getDay(shutdownDate); final int shutdownWeek = getWeek(shutdownDate); final IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); final ICommandService commandService = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class); ISourceProviderService sourceProviderService = (ISourceProviderService) PlatformUI.getWorkbench().getService(ISourceProviderService.class); SessionSourceProvider commandStateService = (SessionSourceProvider) sourceProviderService.getSourceProvider(SessionSourceProvider.SESSION_STATE); if (startDay != shutdownDay && storageService.getLastTask() != null) { // don't automatically check in/out if program is restarted Map<String, String> parameters = new HashMap<String, String>(); parameters.put("Timesheet.commands.shutdownTime", StorageService.formatter.format(shutdownDate)); try { // automatic check out handlerService.executeCommand(ParameterizedCommand.generateCommand(commandService.getCommand("Timesheet.checkout"), parameters), null); } catch (Exception ex) { MessageBox.setError("Automatic check out", ex.getMessage() + "\n(" + parameters + ")"); } } if (storageService.getLastTask() == null) { // automatic check in commandStateService.setEnabled(false); Date end = BusinessDayUtil.getNextBusinessDay(shutdownDate, true); // create missing holidays and handle week change Date start = BusinessDayUtil.getPreviousBusinessDay(startDate); - while (end.before(start)) { // create missing whole day tasks until last business day + while (!end.after(start)) { // create missing whole day tasks until last business day AllDayTaskDateDialog dateDialog = new AllDayTaskDateDialog(Display.getDefault(), "Select missing all day task", Activator.getDefault().getPreferenceStore().getString(AllDayTasks.allDayTasks[0]), end); if (dateDialog.open() == Dialog.OK) { do { storageService.createTaskEntry(new TaskEntry(end, TimesheetApp.createTask(dateDialog.getTask()), AllDayTasks.getInstance().getTotal(), true)); } while (!(end = BusinessDayUtil.getNextBusinessDay(end, true)).after(dateDialog.getTo())); } } final Map<String, String> parameters = new HashMap<String, String>(); parameters.put("Timesheet.commands.startTime", StorageService.formatter.format(startDate)); PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { try { handlerService.executeCommand(ParameterizedCommand.generateCommand(commandService.getCommand("Timesheet.checkin"), parameters), null); for (int week = shutdownWeek; week < startWeek; week++) { parameters.clear(); parameters.put("Timesheet.commands.weekNum", Integer.toString(week)); handlerService.executeCommand(ParameterizedCommand.generateCommand(commandService.getCommand("Timesheet.submit"), parameters), null); } } catch (Exception ex) { MessageBox.setError("Automatic check in", ex.getMessage() + "\n(" + parameters + ")"); } } }); } else { commandStateService.setEnabled(true); final Map<String, String> parameters = new HashMap<String, String>(); parameters.put("Timesheet.commands.changeTime", StorageService.formatter.format(startDate)); PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { try { handlerService.executeCommand(ParameterizedCommand.generateCommand(commandService.getCommand("Timesheet.changeTask"), parameters), null); } catch (Exception e) { MessageBox.setError("Automatic change task", e.getMessage() + "\n(" + parameters + ")"); } } }); } commandStateService.setBreak(false); } private static int getDay(Date date) { Calendar calDay = Calendar.getInstance(); calDay.setTime(date); return calDay.get(Calendar.DAY_OF_YEAR); } private static int getWeek(Date date) { Calendar calWeek = new GregorianCalendar(); calWeek.setTime(date); return calWeek.get(Calendar.WEEK_OF_YEAR); } }
true
true
public static void execute() { LocalStorageService storageService = LocalStorageService.getInstance(); Date startDate = TimesheetApp.startDate; Date shutdownDate = TimesheetApp.shutDownDate; Date lastDate = storageService.getLastTaskEntryDate(); if (lastDate == null) lastDate = BusinessDayUtil.getPreviousBusinessDay(new Date()); if (shutdownDate.before(lastDate)) shutdownDate = lastDate; int startDay = getDay(startDate); final int startWeek = getWeek(startDate); int shutdownDay = getDay(shutdownDate); final int shutdownWeek = getWeek(shutdownDate); final IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); final ICommandService commandService = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class); ISourceProviderService sourceProviderService = (ISourceProviderService) PlatformUI.getWorkbench().getService(ISourceProviderService.class); SessionSourceProvider commandStateService = (SessionSourceProvider) sourceProviderService.getSourceProvider(SessionSourceProvider.SESSION_STATE); if (startDay != shutdownDay && storageService.getLastTask() != null) { // don't automatically check in/out if program is restarted Map<String, String> parameters = new HashMap<String, String>(); parameters.put("Timesheet.commands.shutdownTime", StorageService.formatter.format(shutdownDate)); try { // automatic check out handlerService.executeCommand(ParameterizedCommand.generateCommand(commandService.getCommand("Timesheet.checkout"), parameters), null); } catch (Exception ex) { MessageBox.setError("Automatic check out", ex.getMessage() + "\n(" + parameters + ")"); } } if (storageService.getLastTask() == null) { // automatic check in commandStateService.setEnabled(false); Date end = BusinessDayUtil.getNextBusinessDay(shutdownDate, true); // create missing holidays and handle week change Date start = BusinessDayUtil.getPreviousBusinessDay(startDate); while (end.before(start)) { // create missing whole day tasks until last business day AllDayTaskDateDialog dateDialog = new AllDayTaskDateDialog(Display.getDefault(), "Select missing all day task", Activator.getDefault().getPreferenceStore().getString(AllDayTasks.allDayTasks[0]), end); if (dateDialog.open() == Dialog.OK) { do { storageService.createTaskEntry(new TaskEntry(end, TimesheetApp.createTask(dateDialog.getTask()), AllDayTasks.getInstance().getTotal(), true)); } while (!(end = BusinessDayUtil.getNextBusinessDay(end, true)).after(dateDialog.getTo())); } } final Map<String, String> parameters = new HashMap<String, String>(); parameters.put("Timesheet.commands.startTime", StorageService.formatter.format(startDate)); PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { try { handlerService.executeCommand(ParameterizedCommand.generateCommand(commandService.getCommand("Timesheet.checkin"), parameters), null); for (int week = shutdownWeek; week < startWeek; week++) { parameters.clear(); parameters.put("Timesheet.commands.weekNum", Integer.toString(week)); handlerService.executeCommand(ParameterizedCommand.generateCommand(commandService.getCommand("Timesheet.submit"), parameters), null); } } catch (Exception ex) { MessageBox.setError("Automatic check in", ex.getMessage() + "\n(" + parameters + ")"); } } }); } else { commandStateService.setEnabled(true); final Map<String, String> parameters = new HashMap<String, String>(); parameters.put("Timesheet.commands.changeTime", StorageService.formatter.format(startDate)); PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { try { handlerService.executeCommand(ParameterizedCommand.generateCommand(commandService.getCommand("Timesheet.changeTask"), parameters), null); } catch (Exception e) { MessageBox.setError("Automatic change task", e.getMessage() + "\n(" + parameters + ")"); } } }); } commandStateService.setBreak(false); }
public static void execute() { LocalStorageService storageService = LocalStorageService.getInstance(); Date startDate = TimesheetApp.startDate; Date shutdownDate = TimesheetApp.shutDownDate; Date lastDate = storageService.getLastTaskEntryDate(); if (lastDate == null) lastDate = BusinessDayUtil.getPreviousBusinessDay(new Date()); if (shutdownDate.before(lastDate)) shutdownDate = lastDate; int startDay = getDay(startDate); final int startWeek = getWeek(startDate); int shutdownDay = getDay(shutdownDate); final int shutdownWeek = getWeek(shutdownDate); final IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); final ICommandService commandService = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class); ISourceProviderService sourceProviderService = (ISourceProviderService) PlatformUI.getWorkbench().getService(ISourceProviderService.class); SessionSourceProvider commandStateService = (SessionSourceProvider) sourceProviderService.getSourceProvider(SessionSourceProvider.SESSION_STATE); if (startDay != shutdownDay && storageService.getLastTask() != null) { // don't automatically check in/out if program is restarted Map<String, String> parameters = new HashMap<String, String>(); parameters.put("Timesheet.commands.shutdownTime", StorageService.formatter.format(shutdownDate)); try { // automatic check out handlerService.executeCommand(ParameterizedCommand.generateCommand(commandService.getCommand("Timesheet.checkout"), parameters), null); } catch (Exception ex) { MessageBox.setError("Automatic check out", ex.getMessage() + "\n(" + parameters + ")"); } } if (storageService.getLastTask() == null) { // automatic check in commandStateService.setEnabled(false); Date end = BusinessDayUtil.getNextBusinessDay(shutdownDate, true); // create missing holidays and handle week change Date start = BusinessDayUtil.getPreviousBusinessDay(startDate); while (!end.after(start)) { // create missing whole day tasks until last business day AllDayTaskDateDialog dateDialog = new AllDayTaskDateDialog(Display.getDefault(), "Select missing all day task", Activator.getDefault().getPreferenceStore().getString(AllDayTasks.allDayTasks[0]), end); if (dateDialog.open() == Dialog.OK) { do { storageService.createTaskEntry(new TaskEntry(end, TimesheetApp.createTask(dateDialog.getTask()), AllDayTasks.getInstance().getTotal(), true)); } while (!(end = BusinessDayUtil.getNextBusinessDay(end, true)).after(dateDialog.getTo())); } } final Map<String, String> parameters = new HashMap<String, String>(); parameters.put("Timesheet.commands.startTime", StorageService.formatter.format(startDate)); PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { try { handlerService.executeCommand(ParameterizedCommand.generateCommand(commandService.getCommand("Timesheet.checkin"), parameters), null); for (int week = shutdownWeek; week < startWeek; week++) { parameters.clear(); parameters.put("Timesheet.commands.weekNum", Integer.toString(week)); handlerService.executeCommand(ParameterizedCommand.generateCommand(commandService.getCommand("Timesheet.submit"), parameters), null); } } catch (Exception ex) { MessageBox.setError("Automatic check in", ex.getMessage() + "\n(" + parameters + ")"); } } }); } else { commandStateService.setEnabled(true); final Map<String, String> parameters = new HashMap<String, String>(); parameters.put("Timesheet.commands.changeTime", StorageService.formatter.format(startDate)); PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { try { handlerService.executeCommand(ParameterizedCommand.generateCommand(commandService.getCommand("Timesheet.changeTask"), parameters), null); } catch (Exception e) { MessageBox.setError("Automatic change task", e.getMessage() + "\n(" + parameters + ")"); } } }); } commandStateService.setBreak(false); }
diff --git a/src/java/main/org/jaxen/jdom/DocumentNavigator.java b/src/java/main/org/jaxen/jdom/DocumentNavigator.java index f15792e..d9d195f 100644 --- a/src/java/main/org/jaxen/jdom/DocumentNavigator.java +++ b/src/java/main/org/jaxen/jdom/DocumentNavigator.java @@ -1,435 +1,435 @@ package org.jaxen.jdom; import org.jaxen.BaseXPath; import org.jaxen.DefaultNavigator; import org.jaxen.FunctionCallException; import org.jaxen.util.SingleObjectIterator; import org.saxpath.SAXPathException; import org.jdom.Document; import org.jdom.Element; import org.jdom.Comment; import org.jdom.Attribute; import org.jdom.Text; import org.jdom.CDATA; import org.jdom.ProcessingInstruction; import org.jdom.Namespace; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class DocumentNavigator extends DefaultNavigator { private static class Singleton { private static DocumentNavigator instance = new DocumentNavigator(); } public static DocumentNavigator getInstance() { return Singleton.instance; } public boolean isElement(Object obj) { return obj instanceof Element; } public boolean isComment(Object obj) { return obj instanceof Comment; } public boolean isText(Object obj) { return ( obj instanceof String || obj instanceof Text || obj instanceof CDATA ); } public boolean isAttribute(Object obj) { return obj instanceof Attribute; } public boolean isProcessingInstruction(Object obj) { return obj instanceof ProcessingInstruction; } public boolean isDocument(Object obj) { return obj instanceof Document; } public boolean isNamespace(Object obj) { return obj instanceof Namespace || obj instanceof XPathNamespace; } public String getElementName(Object obj) { Element elem = (Element) obj; return elem.getName(); } public String getElementNamespaceUri(Object obj) { Element elem = (Element) obj; String uri = elem.getNamespaceURI(); if ( uri != null && uri.length() == 0 ) return null; else return uri; } public String getAttributeName(Object obj) { Attribute attr = (Attribute) obj; return attr.getName(); } public String getAttributeNamespaceUri(Object obj) { Attribute attr = (Attribute) obj; String uri = attr.getNamespaceURI(); if ( uri != null && uri.length() == 0 ) return null; else return uri; } public Iterator getChildAxisIterator(Object contextNode) { if ( contextNode instanceof Element ) { return ((Element)contextNode).getContent().iterator(); } else if ( contextNode instanceof Document ) { return ((Document)contextNode).getContent().iterator(); } return null; } public Iterator getNamespaceAxisIterator(Object contextNode) { if ( ! ( contextNode instanceof Element ) ) { return null; } Element elem = (Element) contextNode; Map nsMap = new HashMap(); Element current = elem; while ( current != null ) { Namespace ns = current.getNamespace(); if ( ns != Namespace.NO_NAMESPACE ) { if ( !nsMap.containsKey(ns.getPrefix()) ) nsMap.put( ns.getPrefix(), new XPathNamespace(elem, ns) ); } Iterator additional = current.getAdditionalNamespaces().iterator(); while ( additional.hasNext() ) { ns = (Namespace)additional.next(); if ( !nsMap.containsKey(ns.getPrefix()) ) nsMap.put( ns.getPrefix(), new XPathNamespace(elem, ns) ); } current = current.getParent(); } nsMap.put( "xml", new XPathNamespace(elem, Namespace.XML_NAMESPACE) ); return nsMap.values().iterator(); } public Iterator getParentAxisIterator(Object contextNode) { Object parent = null; if ( contextNode instanceof Document ) { parent = contextNode; } else if ( contextNode instanceof Element ) { parent = ((Element)contextNode).getParent(); if ( parent == null ) { if ( ((Element)contextNode).isRootElement() ) { parent = ((Element)contextNode).getDocument(); } } } else if ( contextNode instanceof Attribute ) { parent = ((Attribute)contextNode).getParent(); } else if ( contextNode instanceof XPathNamespace ) { parent = ((XPathNamespace)contextNode).getJDOMElement(); } else if ( contextNode instanceof ProcessingInstruction ) { parent = ((ProcessingInstruction)contextNode).getParent(); } else if ( contextNode instanceof Text ) { parent = ((Text)contextNode).getParent(); } else if ( contextNode instanceof Comment ) { - parent = ((Text)contextNode).getParent(); + parent = ((Comment)contextNode).getParent(); } if ( parent != null ) { return new SingleObjectIterator( parent ); } return null; } public Iterator getAttributeAxisIterator(Object contextNode) { if ( ! ( contextNode instanceof Element ) ) { return null; } Element elem = (Element) contextNode; return elem.getAttributes().iterator(); } /** Returns a parsed form of the given xpath string, which will be suitable * for queries on JDOM documents. */ public BaseXPath parseXPath (String xpath) throws SAXPathException { return new XPath(xpath); } public Object getDocumentNode(Object contextNode) { if ( contextNode instanceof Document ) { return contextNode; } Element elem = (Element) contextNode; return elem.getDocument(); } public String getElementQName(Object obj) { Element elem = (Element) obj; String prefix = elem.getNamespacePrefix(); if ( "".equals( prefix ) ) { return elem.getName(); } return prefix + ":" + elem.getName(); } public String getAttributeQName(Object obj) { Attribute attr = (Attribute) obj; String prefix = attr.getNamespacePrefix(); if ( "".equals( prefix ) ) { return attr.getName(); } return prefix + ":" + attr.getName(); } public String getNamespaceStringValue(Object obj) { if (obj instanceof Namespace) { Namespace ns = (Namespace) obj; return ns.getURI(); } else { XPathNamespace ns = (XPathNamespace) obj; return ns.getJDOMNamespace().getURI(); } } public String getNamespacePrefix(Object obj) { if (obj instanceof Namespace) { Namespace ns = (Namespace) obj; return ns.getPrefix(); } else { XPathNamespace ns = (XPathNamespace) obj; return ns.getJDOMNamespace().getPrefix(); } } public String getTextStringValue(Object obj) { if ( obj instanceof Text ) { return ((Text)obj).getValue(); } if ( obj instanceof CDATA ) { return ((CDATA)obj).getText(); } return ""; } public String getAttributeStringValue(Object obj) { Attribute attr = (Attribute) obj; return attr.getValue(); } public String getElementStringValue(Object obj) { Element elem = (Element) obj; StringBuffer buf = new StringBuffer(); List content = elem.getContent(); Iterator contentIter = content.iterator(); Object each = null; while ( contentIter.hasNext() ) { each = contentIter.next(); if ( each instanceof String ) { buf.append( each ); } else if ( each instanceof Text ) { buf.append( ((Text)each).getValue() ); } else if ( each instanceof CDATA ) { buf.append( ((CDATA)each).getText() ); } else if ( each instanceof Element ) { buf.append( getElementStringValue( each ) ); } } return buf.toString(); } public String getProcessingInstructionTarget(Object obj) { ProcessingInstruction pi = (ProcessingInstruction) obj; return pi.getTarget(); } public String getProcessingInstructionData(Object obj) { ProcessingInstruction pi = (ProcessingInstruction) obj; return pi.getData(); } public String getCommentStringValue(Object obj) { Comment cmt = (Comment) obj; return cmt.getText(); } public String translateNamespacePrefixToUri(String prefix, Object context) { Element element = null; if ( context instanceof Element ) { element = (Element) context; } else if ( context instanceof Attribute ) { element = ((Attribute)context).getParent(); } else if ( context instanceof XPathNamespace ) { element = ((XPathNamespace)context).getJDOMElement(); } else if ( context instanceof Text ) { element = ((Text)context).getParent(); } else if ( context instanceof Comment ) { element = ((Comment)context).getParent(); } else if ( context instanceof ProcessingInstruction ) { element = ((ProcessingInstruction)context).getParent(); } if ( element != null ) { Namespace namespace = element.getNamespace( prefix ); if ( namespace != null ) { return namespace.getURI(); } } return null; } public Object getDocument(String url) throws FunctionCallException { try { SAXBuilder builder = new SAXBuilder(); return builder.build( url ); } catch (JDOMException e) { throw new FunctionCallException( e.getMessage() ); } } }
true
true
public Iterator getParentAxisIterator(Object contextNode) { Object parent = null; if ( contextNode instanceof Document ) { parent = contextNode; } else if ( contextNode instanceof Element ) { parent = ((Element)contextNode).getParent(); if ( parent == null ) { if ( ((Element)contextNode).isRootElement() ) { parent = ((Element)contextNode).getDocument(); } } } else if ( contextNode instanceof Attribute ) { parent = ((Attribute)contextNode).getParent(); } else if ( contextNode instanceof XPathNamespace ) { parent = ((XPathNamespace)contextNode).getJDOMElement(); } else if ( contextNode instanceof ProcessingInstruction ) { parent = ((ProcessingInstruction)contextNode).getParent(); } else if ( contextNode instanceof Text ) { parent = ((Text)contextNode).getParent(); } else if ( contextNode instanceof Comment ) { parent = ((Text)contextNode).getParent(); } if ( parent != null ) { return new SingleObjectIterator( parent ); } return null; }
public Iterator getParentAxisIterator(Object contextNode) { Object parent = null; if ( contextNode instanceof Document ) { parent = contextNode; } else if ( contextNode instanceof Element ) { parent = ((Element)contextNode).getParent(); if ( parent == null ) { if ( ((Element)contextNode).isRootElement() ) { parent = ((Element)contextNode).getDocument(); } } } else if ( contextNode instanceof Attribute ) { parent = ((Attribute)contextNode).getParent(); } else if ( contextNode instanceof XPathNamespace ) { parent = ((XPathNamespace)contextNode).getJDOMElement(); } else if ( contextNode instanceof ProcessingInstruction ) { parent = ((ProcessingInstruction)contextNode).getParent(); } else if ( contextNode instanceof Text ) { parent = ((Text)contextNode).getParent(); } else if ( contextNode instanceof Comment ) { parent = ((Comment)contextNode).getParent(); } if ( parent != null ) { return new SingleObjectIterator( parent ); } return null; }
diff --git a/deegree-client/deegree-jsf-core/src/main/java/org/deegree/client/core/renderer/OutputXMLRenderer.java b/deegree-client/deegree-jsf-core/src/main/java/org/deegree/client/core/renderer/OutputXMLRenderer.java index 79fe31420b..a3009be518 100644 --- a/deegree-client/deegree-jsf-core/src/main/java/org/deegree/client/core/renderer/OutputXMLRenderer.java +++ b/deegree-client/deegree-jsf-core/src/main/java/org/deegree/client/core/renderer/OutputXMLRenderer.java @@ -1,353 +1,353 @@ //$HeadURL: svn+ssh://[email protected]/deegree/base/trunk/resources/eclipse/files_template.xml $ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2010 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library 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 library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.client.core.renderer; import static org.slf4j.LoggerFactory.getLogger; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.StringReader; import java.net.URL; import java.util.UUID; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.render.FacesRenderer; import javax.faces.render.Renderer; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.apache.commons.io.IOUtils; import org.deegree.client.core.component.HtmlOutputXML; import org.deegree.client.core.utils.FacesUtils; import org.slf4j.Logger; /** * Renderer for {@link HtmlOutputXML}. Renders the value xml indentent and colored, if possible, otherwise as simple * String. If the value should be downloadable, a file will be created and a download linked rendered. * * @author <a href="mailto:[email protected]">Lyn Buesching</a> * @author last edited by: $Author: lyn $ * * @version $Revision: $, $Date: $ */ @FacesRenderer(componentFamily = "javax.faces.Output", rendererType = "org.deegree.OutputXML") public class OutputXMLRenderer extends Renderer { private static final Logger LOG = getLogger( OutputXMLRenderer.class ); @Override public void encodeBegin( FacesContext context, UIComponent component ) throws IOException { HtmlOutputXML xmlComponent = (HtmlOutputXML) component; if ( xmlComponent.getValue() != null ) { String clientId = xmlComponent.getClientId(); ResponseWriter writer = context.getResponseWriter(); writer.startElement( "div", xmlComponent ); writer.writeAttribute( "id", clientId, "clientId" ); writer.writeAttribute( "name", clientId, "clientId" ); writer.writeAttribute( "class", xmlComponent.getStyleClass(), "styleClass" ); if ( xmlComponent.isDownloadable() ) { writer.startElement( "div", null ); writer.writeAttribute( "class", "downloadArea", null ); encodeDownload( writer, xmlComponent ); writer.endElement( "div" ); } writer.startElement( "div", xmlComponent ); writer.writeAttribute( "class", "xmlArea", null ); encodeXML( writer, xmlComponent.getValue() ); writer.endElement( "div" ); writer.endElement( "div" ); } } private void encodeDownload( ResponseWriter writer, HtmlOutputXML xmlComponent ) throws IOException { File dir = new File( "downloads" ); new File( FacesUtils.getAbsolutePath( "downloads", null ) ).mkdirs(); String src = xmlComponent.getDownloadFile(); String fileName = "file_" + UUID.randomUUID() + ".xml"; URL webAccessibleUrl = FacesUtils.getWebAccessibleUrl( dir.toString(), fileName ); try { File f = new File( FacesUtils.getAbsolutePath( dir.toString(), fileName ) ); FileInputStream is = new FileInputStream( src ); FileOutputStream os = new FileOutputStream( f ); try { IOUtils.copy( is, os ); } finally { IOUtils.closeQuietly( is ); IOUtils.closeQuietly( os ); new File( src ).delete(); } DeleteThread thread = new DeleteThread( f, xmlComponent.getMinutesUntilDelete() * 3600 ); thread.start(); } catch ( Exception e ) { LOG.warn( "Could not write file for download: " + e.getMessage() ); return; } writer.write( xmlComponent.getDownloadLabel() ); writer.startElement( "a", null ); writer.writeAttribute( "href", webAccessibleUrl.toExternalForm(), null ); writer.writeAttribute( "target", "_blank", null ); writer.write( fileName ); writer.endElement( "a" ); } private void encodeXML( ResponseWriter writer, String value ) throws IOException { int depth = 0; try { XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader( new StringReader( value ) ); boolean lastWasEndElement = false; boolean lastWasComment = false; while ( reader.hasNext() ) { switch ( reader.getEventType() ) { case XMLStreamConstants.START_ELEMENT: if ( !lastWasComment ) { writer.startElement( "br", null ); writer.endElement( "br" ); } writer.write( getSpaces( depth ) ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "&lt;" ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "tag", null ); String prefix = reader.getPrefix(); writer.write( ( prefix != null && prefix.length() > 0 ? prefix + ":" : "" ) + reader.getLocalName() ); writer.endElement( "span" ); for ( int i = 0; i < reader.getAttributeCount(); i++ ) { writer.startElement( "span", null ); writer.writeAttribute( "class", "attributeName", null ); writer.write( "&#160;" ); String attributePrefix = reader.getAttributePrefix( i ); writer.write( ( attributePrefix != null && attributePrefix.length() > 0 ? attributePrefix + ":" : "" ) + reader.getAttributeLocalName( i ) ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "=\"" ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "text", null ); writer.write( encodeString( reader.getAttributeValue( i ) ) ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "\"" ); writer.endElement( "span" ); } for ( int i = 0; i < reader.getNamespaceCount(); i++ ) { writer.startElement( "span", null ); writer.writeAttribute( "class", "attributeName", null ); writer.write( "&#160;" ); String nsPrefix = reader.getNamespacePrefix( i ); writer.write( "xmlns" ); - if ( nsPrefix != null ) { + if ( nsPrefix != null && !nsPrefix.isEmpty() ) { writer.write( ":" + nsPrefix ); } writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "=\"" ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "text", null ); writer.write( reader.getNamespaceURI( i ) ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "\"" ); writer.endElement( "span" ); } writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "&gt;" ); writer.endElement( "span" ); depth++; lastWasEndElement = false; lastWasComment = false; break; case XMLStreamConstants.CHARACTERS: String text = reader.getText(); if ( text.trim().length() > 0 ) { writer.startElement( "span", null ); writer.writeAttribute( "class", "text", null ); writer.write( encodeString( text ) ); writer.endElement( "span" ); lastWasEndElement = false; lastWasComment = false; } break; case XMLStreamConstants.END_ELEMENT: depth--; if ( lastWasEndElement ) { writer.startElement( "br", null ); writer.endElement( "br" ); writer.write( getSpaces( depth ) ); } writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "&lt;/" ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "tag", null ); prefix = reader.getPrefix(); writer.write( ( prefix != null && prefix.length() > 0 ? prefix + ":" : "" ) + reader.getLocalName() ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "&gt;" ); writer.endElement( "span" ); lastWasEndElement = true; lastWasComment = false; break; case XMLStreamConstants.COMMENT: writer.startElement( "div", null ); writer.writeAttribute( "class", "comment", null ); writer.write( "&lt;/!--" + reader.getText() + "--&gt;" ); writer.endElement( "div" ); lastWasEndElement = false; lastWasComment = true; break; default: break; } reader.next(); } reader.close(); } catch ( Throwable e ) { if ( depth == 0 ) { writer.writeText( "Response could not parsed as XML.", null ); } else { writer.writeText( "... (if you want the complete document, please click the download button)", null ); } } } private static final char c[] = { '<', '>', '&', '\"' }; private static final String expansion[] = { "&lt;amp;", "&gt;amp;", "&amp;amp;", "&quot;amp;" }; private String encodeString( String s ) { StringBuffer st = new StringBuffer(); for ( int i = 0; i < s.length(); i++ ) { boolean copy = true; char ch = s.charAt( i ); for ( int j = 0; j < c.length; j++ ) { if ( c[j] == ch ) { st.append( expansion[j] ); copy = false; break; } } if ( copy ) { st.append( ch ); } } return st.toString(); } private String getSpaces( int depth ) { int indent = 4; int n = depth * indent; char[] chars = new char[n]; StringBuffer sb = new StringBuffer(); for ( int i = 0; i < chars.length; i++ ) { sb.append( "&#160;" ); } return sb.toString(); } private class DeleteThread extends Thread { private final File fileToDelete; private final int secondesUntilDelete; public DeleteThread( File fileToDelete, int secondesUntilDelete ) { this.fileToDelete = fileToDelete; this.secondesUntilDelete = secondesUntilDelete; } @Override public void run() { if ( secondesUntilDelete > 0 ) try { DeleteThread.sleep( secondesUntilDelete ); } catch ( InterruptedException e ) { LOG.debug( "Could not sleep delete thread: " + e.getMessage() ); } if ( fileToDelete != null ) { try { if ( fileToDelete.delete() ) { LOG.debug( "Successfully deleted file " + fileToDelete.getName() ); } else { LOG.debug( "Could not delete file " + fileToDelete.getName() ); } } catch ( Exception e ) { LOG.error( "Could not delete file " + fileToDelete.getName() + ": " + e.getMessage() ); } } } } }
true
true
private void encodeXML( ResponseWriter writer, String value ) throws IOException { int depth = 0; try { XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader( new StringReader( value ) ); boolean lastWasEndElement = false; boolean lastWasComment = false; while ( reader.hasNext() ) { switch ( reader.getEventType() ) { case XMLStreamConstants.START_ELEMENT: if ( !lastWasComment ) { writer.startElement( "br", null ); writer.endElement( "br" ); } writer.write( getSpaces( depth ) ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "&lt;" ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "tag", null ); String prefix = reader.getPrefix(); writer.write( ( prefix != null && prefix.length() > 0 ? prefix + ":" : "" ) + reader.getLocalName() ); writer.endElement( "span" ); for ( int i = 0; i < reader.getAttributeCount(); i++ ) { writer.startElement( "span", null ); writer.writeAttribute( "class", "attributeName", null ); writer.write( "&#160;" ); String attributePrefix = reader.getAttributePrefix( i ); writer.write( ( attributePrefix != null && attributePrefix.length() > 0 ? attributePrefix + ":" : "" ) + reader.getAttributeLocalName( i ) ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "=\"" ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "text", null ); writer.write( encodeString( reader.getAttributeValue( i ) ) ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "\"" ); writer.endElement( "span" ); } for ( int i = 0; i < reader.getNamespaceCount(); i++ ) { writer.startElement( "span", null ); writer.writeAttribute( "class", "attributeName", null ); writer.write( "&#160;" ); String nsPrefix = reader.getNamespacePrefix( i ); writer.write( "xmlns" ); if ( nsPrefix != null ) { writer.write( ":" + nsPrefix ); } writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "=\"" ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "text", null ); writer.write( reader.getNamespaceURI( i ) ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "\"" ); writer.endElement( "span" ); } writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "&gt;" ); writer.endElement( "span" ); depth++; lastWasEndElement = false; lastWasComment = false; break; case XMLStreamConstants.CHARACTERS: String text = reader.getText(); if ( text.trim().length() > 0 ) { writer.startElement( "span", null ); writer.writeAttribute( "class", "text", null ); writer.write( encodeString( text ) ); writer.endElement( "span" ); lastWasEndElement = false; lastWasComment = false; } break; case XMLStreamConstants.END_ELEMENT: depth--; if ( lastWasEndElement ) { writer.startElement( "br", null ); writer.endElement( "br" ); writer.write( getSpaces( depth ) ); } writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "&lt;/" ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "tag", null ); prefix = reader.getPrefix(); writer.write( ( prefix != null && prefix.length() > 0 ? prefix + ":" : "" ) + reader.getLocalName() ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "&gt;" ); writer.endElement( "span" ); lastWasEndElement = true; lastWasComment = false; break; case XMLStreamConstants.COMMENT: writer.startElement( "div", null ); writer.writeAttribute( "class", "comment", null ); writer.write( "&lt;/!--" + reader.getText() + "--&gt;" ); writer.endElement( "div" ); lastWasEndElement = false; lastWasComment = true; break; default: break; } reader.next(); } reader.close(); } catch ( Throwable e ) { if ( depth == 0 ) { writer.writeText( "Response could not parsed as XML.", null ); } else { writer.writeText( "... (if you want the complete document, please click the download button)", null ); } } }
private void encodeXML( ResponseWriter writer, String value ) throws IOException { int depth = 0; try { XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader( new StringReader( value ) ); boolean lastWasEndElement = false; boolean lastWasComment = false; while ( reader.hasNext() ) { switch ( reader.getEventType() ) { case XMLStreamConstants.START_ELEMENT: if ( !lastWasComment ) { writer.startElement( "br", null ); writer.endElement( "br" ); } writer.write( getSpaces( depth ) ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "&lt;" ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "tag", null ); String prefix = reader.getPrefix(); writer.write( ( prefix != null && prefix.length() > 0 ? prefix + ":" : "" ) + reader.getLocalName() ); writer.endElement( "span" ); for ( int i = 0; i < reader.getAttributeCount(); i++ ) { writer.startElement( "span", null ); writer.writeAttribute( "class", "attributeName", null ); writer.write( "&#160;" ); String attributePrefix = reader.getAttributePrefix( i ); writer.write( ( attributePrefix != null && attributePrefix.length() > 0 ? attributePrefix + ":" : "" ) + reader.getAttributeLocalName( i ) ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "=\"" ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "text", null ); writer.write( encodeString( reader.getAttributeValue( i ) ) ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "\"" ); writer.endElement( "span" ); } for ( int i = 0; i < reader.getNamespaceCount(); i++ ) { writer.startElement( "span", null ); writer.writeAttribute( "class", "attributeName", null ); writer.write( "&#160;" ); String nsPrefix = reader.getNamespacePrefix( i ); writer.write( "xmlns" ); if ( nsPrefix != null && !nsPrefix.isEmpty() ) { writer.write( ":" + nsPrefix ); } writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "=\"" ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "text", null ); writer.write( reader.getNamespaceURI( i ) ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "\"" ); writer.endElement( "span" ); } writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "&gt;" ); writer.endElement( "span" ); depth++; lastWasEndElement = false; lastWasComment = false; break; case XMLStreamConstants.CHARACTERS: String text = reader.getText(); if ( text.trim().length() > 0 ) { writer.startElement( "span", null ); writer.writeAttribute( "class", "text", null ); writer.write( encodeString( text ) ); writer.endElement( "span" ); lastWasEndElement = false; lastWasComment = false; } break; case XMLStreamConstants.END_ELEMENT: depth--; if ( lastWasEndElement ) { writer.startElement( "br", null ); writer.endElement( "br" ); writer.write( getSpaces( depth ) ); } writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "&lt;/" ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "tag", null ); prefix = reader.getPrefix(); writer.write( ( prefix != null && prefix.length() > 0 ? prefix + ":" : "" ) + reader.getLocalName() ); writer.endElement( "span" ); writer.startElement( "span", null ); writer.writeAttribute( "class", "sign", null ); writer.write( "&gt;" ); writer.endElement( "span" ); lastWasEndElement = true; lastWasComment = false; break; case XMLStreamConstants.COMMENT: writer.startElement( "div", null ); writer.writeAttribute( "class", "comment", null ); writer.write( "&lt;/!--" + reader.getText() + "--&gt;" ); writer.endElement( "div" ); lastWasEndElement = false; lastWasComment = true; break; default: break; } reader.next(); } reader.close(); } catch ( Throwable e ) { if ( depth == 0 ) { writer.writeText( "Response could not parsed as XML.", null ); } else { writer.writeText( "... (if you want the complete document, please click the download button)", null ); } } }
diff --git a/src/plovr/io/Responses.java b/src/plovr/io/Responses.java index b5789a2cb..175a0c3a3 100644 --- a/src/plovr/io/Responses.java +++ b/src/plovr/io/Responses.java @@ -1,38 +1,38 @@ package plovr.io; import java.io.IOException; import java.io.Writer; import org.plovr.Config; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; public final class Responses { /** Utility class: do not instantiate. */ private Responses() {} /** * Writes a 200 response with the specified JavaScript content using the * appropriate headers and character encoding. * Once this method is called, nothing else may be written as it closes the * response. * @param js The JavaScript code to write to the response. * @param exchange to which the response will be written -- no content may * have been written to its response yet as this method sets headers */ public static void writeJs( String js, Config config, HttpExchange exchange) throws IOException { Headers responseHeaders = exchange.getResponseHeaders(); responseHeaders.set("Content-Type", config.getJsContentType()); - int responseLength = js.getBytes(Settings.CHARSET).length; + int responseLength = js.getBytes(config.getOutputCharset()).length; exchange.sendResponseHeaders(200, responseLength); Writer responseBody = Streams.createOutputStreamWriter( exchange.getResponseBody(), config); responseBody.write(js); responseBody.close(); } }
true
true
public static void writeJs( String js, Config config, HttpExchange exchange) throws IOException { Headers responseHeaders = exchange.getResponseHeaders(); responseHeaders.set("Content-Type", config.getJsContentType()); int responseLength = js.getBytes(Settings.CHARSET).length; exchange.sendResponseHeaders(200, responseLength); Writer responseBody = Streams.createOutputStreamWriter( exchange.getResponseBody(), config); responseBody.write(js); responseBody.close(); }
public static void writeJs( String js, Config config, HttpExchange exchange) throws IOException { Headers responseHeaders = exchange.getResponseHeaders(); responseHeaders.set("Content-Type", config.getJsContentType()); int responseLength = js.getBytes(config.getOutputCharset()).length; exchange.sendResponseHeaders(200, responseLength); Writer responseBody = Streams.createOutputStreamWriter( exchange.getResponseBody(), config); responseBody.write(js); responseBody.close(); }
diff --git a/src/simciv/builds/ProblemsReport.java b/src/simciv/builds/ProblemsReport.java index 1792fe1..7ee070e 100644 --- a/src/simciv/builds/ProblemsReport.java +++ b/src/simciv/builds/ProblemsReport.java @@ -1,45 +1,45 @@ package simciv.builds; import java.util.ArrayList; public class ProblemsReport { // Problem severity public static final byte MINOR = 0; public static final byte SEVERE = 1; private static final byte COUNT = 2; private ArrayList<String> problems[]; @SuppressWarnings("unchecked") public ProblemsReport() { problems = new ArrayList[COUNT]; for(int i = 0; i < problems.length; i++) problems[i] = new ArrayList<String>(); } public void add(byte severity, String message) { problems[severity].add(message); } public ArrayList<String> getList(byte severity) { return problems[severity]; } public boolean isEmpty() { for(int i = 0; i < problems.length; i++) { if(!problems[i].isEmpty()) return false; } - return false; + return true; } }
true
true
public boolean isEmpty() { for(int i = 0; i < problems.length; i++) { if(!problems[i].isEmpty()) return false; } return false; }
public boolean isEmpty() { for(int i = 0; i < problems.length; i++) { if(!problems[i].isEmpty()) return false; } return true; }
diff --git a/demos/symbol/TestGappedSymbolList.java b/demos/symbol/TestGappedSymbolList.java index 52f7ff1c3..4a2487c81 100755 --- a/demos/symbol/TestGappedSymbolList.java +++ b/demos/symbol/TestGappedSymbolList.java @@ -1,76 +1,76 @@ /* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package symbol; import java.util.*; import java.io.*; import org.biojava.bio.*; import org.biojava.bio.symbol.*; /** * This demonstrates gapped sequences as a view onto an ungapped sequence. * * @author Matthew Pocock */ public class TestGappedSymbolList { public static void main(String [] args) { try { SymbolList res = Tools.createSymbolList(10); final int trials = 10; System.out.println("Starting with:\n" + res.seqString()); - GappedSymbolList gl = new GappedSymbolList(res); + SimpleGappedSymbolList gl = new SimpleGappedSymbolList(res); System.out.println("Gapped version:\n" + gl.seqString()); gl.dumpBlocks(); for(int i = 0; i < trials; i++) { int pos = (int) (Math.random() * (double) gl.length() + 1.0); // System.out.println("Inserting gap at " + pos); gl.addGapInView(pos); // gl.dumpBlocks(); System.out.println(gl.seqString()); } for(int i = 0; i < trials; i++) { int pos; do { pos = (int) (Math.random() * (double) gl.length()) + 1; } while(gl.symbolAt(pos) != gl.getAlphabet().getGapSymbol()); // System.out.println("Removing gap at " + pos); gl.removeGap(pos); // gl.dumpBlocks(); System.out.println(gl.seqString()); } for(int i = 0; i < trials; i++) { int pos = (int) (Math.random() * ((double) res.length() + 1.0)) + 1; // System.out.println("Inserting gap at " + pos); gl.addGapInSource(pos); // gl.dumpBlocks(); System.out.println(gl.seqString()); } for(int i = 1; i <= gl.length(); i++) { System.out.println(gl.viewToSource(i)); } } catch (Throwable t) { t.printStackTrace(); System.exit(1); } } }
true
true
public static void main(String [] args) { try { SymbolList res = Tools.createSymbolList(10); final int trials = 10; System.out.println("Starting with:\n" + res.seqString()); GappedSymbolList gl = new GappedSymbolList(res); System.out.println("Gapped version:\n" + gl.seqString()); gl.dumpBlocks(); for(int i = 0; i < trials; i++) { int pos = (int) (Math.random() * (double) gl.length() + 1.0); // System.out.println("Inserting gap at " + pos); gl.addGapInView(pos); // gl.dumpBlocks(); System.out.println(gl.seqString()); } for(int i = 0; i < trials; i++) { int pos; do { pos = (int) (Math.random() * (double) gl.length()) + 1; } while(gl.symbolAt(pos) != gl.getAlphabet().getGapSymbol()); // System.out.println("Removing gap at " + pos); gl.removeGap(pos); // gl.dumpBlocks(); System.out.println(gl.seqString()); } for(int i = 0; i < trials; i++) { int pos = (int) (Math.random() * ((double) res.length() + 1.0)) + 1; // System.out.println("Inserting gap at " + pos); gl.addGapInSource(pos); // gl.dumpBlocks(); System.out.println(gl.seqString()); } for(int i = 1; i <= gl.length(); i++) { System.out.println(gl.viewToSource(i)); } } catch (Throwable t) { t.printStackTrace(); System.exit(1); } }
public static void main(String [] args) { try { SymbolList res = Tools.createSymbolList(10); final int trials = 10; System.out.println("Starting with:\n" + res.seqString()); SimpleGappedSymbolList gl = new SimpleGappedSymbolList(res); System.out.println("Gapped version:\n" + gl.seqString()); gl.dumpBlocks(); for(int i = 0; i < trials; i++) { int pos = (int) (Math.random() * (double) gl.length() + 1.0); // System.out.println("Inserting gap at " + pos); gl.addGapInView(pos); // gl.dumpBlocks(); System.out.println(gl.seqString()); } for(int i = 0; i < trials; i++) { int pos; do { pos = (int) (Math.random() * (double) gl.length()) + 1; } while(gl.symbolAt(pos) != gl.getAlphabet().getGapSymbol()); // System.out.println("Removing gap at " + pos); gl.removeGap(pos); // gl.dumpBlocks(); System.out.println(gl.seqString()); } for(int i = 0; i < trials; i++) { int pos = (int) (Math.random() * ((double) res.length() + 1.0)) + 1; // System.out.println("Inserting gap at " + pos); gl.addGapInSource(pos); // gl.dumpBlocks(); System.out.println(gl.seqString()); } for(int i = 1; i <= gl.length(); i++) { System.out.println(gl.viewToSource(i)); } } catch (Throwable t) { t.printStackTrace(); System.exit(1); } }
diff --git a/master/src/com/indago/helpme/gui/dashboard/HelpERCallDetailsActivity.java b/master/src/com/indago/helpme/gui/dashboard/HelpERCallDetailsActivity.java index c383b27..3f900d4 100644 --- a/master/src/com/indago/helpme/gui/dashboard/HelpERCallDetailsActivity.java +++ b/master/src/com/indago/helpme/gui/dashboard/HelpERCallDetailsActivity.java @@ -1,343 +1,343 @@ package com.indago.helpme.gui.dashboard; import java.util.HashMap; import java.util.List; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.os.Bundle; import android.os.Handler; import android.text.Html; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.android.helpme.demo.interfaces.DrawManagerInterface; import com.android.helpme.demo.interfaces.UserInterface; import com.android.helpme.demo.manager.HistoryManager; import com.android.helpme.demo.manager.MessageOrchestrator; import com.android.helpme.demo.manager.UserManager; import com.android.helpme.demo.overlay.MapItemnizedOverlay; import com.android.helpme.demo.overlay.MapOverlayItem; import com.android.helpme.demo.utils.Task; import com.android.helpme.demo.utils.User; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import com.google.android.maps.OverlayItem; import com.indago.helpme.R; import com.indago.helpme.gui.util.ImageUtility; public class HelpERCallDetailsActivity extends MapActivity implements DrawManagerInterface { private static final String LOGTAG = HelpERCallDetailsActivity.class.getSimpleName(); protected static DisplayMetrics metrics = new DisplayMetrics(); private Handler mHandler; private List<Overlay> mapOverlays; private MapItemnizedOverlay overlay; private MapController mapController; private HashMap<String, MapOverlayItem> hashMapOverlayItem; private Drawable mMapsPinGreen; private Drawable mMapsPinOrange; private boolean show = false; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); getWindowManager().getDefaultDisplay().getMetrics(metrics); super.onCreate(savedInstanceState); setContentView(R.layout.activity_help_er_call_details); Bundle extras = getIntent().getExtras(); String userID = extras.getString("USER_ID"); UserInterface mUser = UserManager.getInstance().getUserById(userID); if(mUser == null) { throw new NullPointerException(LOGTAG + ": User with ID " + userID + " could not be retrieved from Extras-Bundle at onCreate()"); } TextView name = (TextView) findViewById(R.id.tv_help_ee_name); name.setText(Html.fromHtml(name.getText() + " " + mUser.getName())); TextView age = (TextView) findViewById(R.id.tv_help_ee_age); age.setText(Html.fromHtml(age.getText() + " " + mUser.getAge())); TextView gender = (TextView) findViewById(R.id.tv_help_ee_gender); gender.setText(Html.fromHtml(gender.getText() + " " + mUser.getGender())); ImageView picture = (ImageView) findViewById(R.id.iv_help_ee_picture); picture.setImageDrawable(new LayerDrawable(ImageUtility.retrieveDrawables(getApplicationContext(), mUser.getPicture()))); picture.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setZoomLevel(); } }); mHandler = new Handler(); initMaps(mUser); MessageOrchestrator.getInstance().addDrawManager(DRAWMANAGER_TYPE.MAP, this); } @Override protected void onResume() { super.onResume(); setDefaulAppearance(); } protected void setDefaulAppearance() { getWindow().getDecorView().getRootView() .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); } private void initMaps(UserInterface userInterface) { MapView mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); mapOverlays = mapView.getOverlays(); hashMapOverlayItem = new HashMap<String, MapOverlayItem>(); mMapsPinOrange = this.getResources().getDrawable(R.drawable.maps_pin_orange); int w = mMapsPinOrange.getIntrinsicWidth(); int h = mMapsPinOrange.getIntrinsicHeight(); mMapsPinOrange.setBounds(-w / 2, -h, w / 2, 0); mMapsPinGreen = this.getResources().getDrawable(R.drawable.maps_pin_green); mMapsPinGreen.setBounds(0, 0, mMapsPinGreen.getIntrinsicWidth(), mMapsPinGreen.getIntrinsicHeight()); overlay = new MapItemnizedOverlay(mMapsPinGreen, this); mapController = mapView.getController(); mapOverlays.add(overlay); mHandler.postDelayed(addMarker(userInterface), 200); if(UserManager.getInstance().thisUser().getGeoPoint() != null) { mHandler.postDelayed(addMarker(UserManager.getInstance().getThisUser()), 200); } } @Override public void onBackPressed() { if (show) { return; } AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); // set title alertDialogBuilder.setTitle("Warning!\nCanceling Support Offer!"); // set dialog message alertDialogBuilder.setMessage("Do you really want to cancel your current support offer?").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { MessageOrchestrator.getInstance().removeDrawManager(DRAWMANAGER_TYPE.MAP); HistoryManager.getInstance().getTask().setFailed(); HistoryManager.getInstance().stopTask(); startActivity(new Intent(getApplicationContext(), com.indago.helpme.gui.dashboard.HelpERControlcenterActivity.class)); finish(); } }).setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // if this button is clicked, just close // the dialog box and do nothing dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); //startActivity(new Intent(getApplicationContext(), com.indago.helpme.gui.HelpERControlcenterActivity.class), null); //super.onBackPressed(); //finish(); } private Runnable addMarker(final UserInterface userInterface) { return new Runnable() { @Override public void run() { MapOverlayItem overlayitem = hashMapOverlayItem.get(userInterface.getId()); boolean zoom = false; if(overlayitem != null) { overlay.removeItem(overlayitem); } if (hashMapOverlayItem.size() <= 1 && overlayitem == null) zoom = true; if(userInterface.getId().equalsIgnoreCase(UserManager.getInstance().thisUser().getId())) { overlayitem = new MapOverlayItem(userInterface.getGeoPoint(), userInterface.getId(), null, userInterface.getJsonObject() , ImageUtility.retrieveDrawables(getApplicationContext(), userInterface.getPicture())); overlayitem.setMarker(mMapsPinGreen); } else {// a help seeker overlayitem = new MapOverlayItem(userInterface.getGeoPoint(), userInterface.getId(), null,userInterface.getJsonObject(), ImageUtility.retrieveDrawables(getApplicationContext(), userInterface.getPicture())); overlayitem.setMarker(mMapsPinOrange); } hashMapOverlayItem.put(userInterface.getId(), overlayitem); overlay.addOverlay(overlayitem); if (zoom) { setZoomLevel(); } // setZoomLevel(); } }; } private Runnable showInRangeMessageBox(final Context context, final Task task) { show = true; return new Runnable() { @Override public void run() { MessageOrchestrator.getInstance().removeDrawManager(DRAWMANAGER_TYPE.MAP); HistoryManager.getInstance().stopTask(); mHandler.post(HistoryManager.getInstance().saveHistory(getApplicationContext())); Dialog dialog = buildDialog(context, task); try { dialog.show(); } catch(Exception exception) { Log.e(LOGTAG, exception.toString()); } } }; } @Override public void drawThis(Object object) { if(object instanceof User) { User user = (User) object; mHandler.post(addMarker(user)); } else if(object instanceof Task) { Task task = (Task) object; if(!show) { mHandler.post(showInRangeMessageBox(this, task)); } } } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } /* * */ private void setZoomLevel() { Object[] keys = hashMapOverlayItem.keySet().toArray(); OverlayItem item; if(keys.length > 1) { int minLatitude = Integer.MAX_VALUE; int maxLatitude = Integer.MIN_VALUE; int minLongitude = Integer.MAX_VALUE; int maxLongitude = Integer.MIN_VALUE; for(Object key : keys) { item = hashMapOverlayItem.get((String) key); GeoPoint p = item.getPoint(); int lati = p.getLatitudeE6(); int lon = p.getLongitudeE6(); maxLatitude = Math.max(lati, maxLatitude); minLatitude = Math.min(lati, minLatitude); maxLongitude = Math.max(lon, maxLongitude); minLongitude = Math.min(lon, minLongitude); } mapController.zoomToSpan(Math.abs(maxLatitude - minLatitude), Math.abs(maxLongitude - minLongitude)); mapController.animateTo(new GeoPoint((maxLatitude + minLatitude) / 2, (maxLongitude + minLongitude) / 2)); } else { String key = (String) keys[0]; item = hashMapOverlayItem.get(key); mapController.animateTo(item.getPoint()); while(mapController.zoomIn()) { } mapController.zoomOut(); } } private Dialog buildDialog(Context context, Task task) { UserInterface userInterface = task.getUser(); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context); Dialog dialog = dialogBuilder.show(); dialog.setContentView(R.layout.dialog_help_er_in_range); -// dialog.setCanceledOnTouchOutside(false); + dialog.setCanceledOnTouchOutside(false); ImageView imageView; TextView text; String string;Button button; Drawable[] drawables = new Drawable[4]; imageView = (ImageView) dialog.findViewById(R.id.dialog_helper_in_range_picture); imageView.setImageDrawable(new LayerDrawable(ImageUtility.retrieveDrawables(context, userInterface.getPicture()))); text = (TextView) dialog.findViewById(R.id.dialog_helper_in_range_title); string = context.getString(R.string.helper_in_range_title); string = string.replace("[Name]", userInterface.getName()); text.setText(Html.fromHtml(string)); text = (TextView) dialog.findViewById(R.id.dialog_helper_in_range_text); string = context.getString(R.string.helper_in_range_text); if (userInterface.getGender().equalsIgnoreCase("female")) { string = string.replace("[gender]", "her"); }else { string = string.replace("[gender]", "him"); } text.setText(Html.fromHtml(string)); button = (Button) dialog.findViewById(R.id.dialog_helper_in_range_button); button.setText("OK"); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), HelpERControlcenterActivity.class); startActivity(intent); finish(); } }); return dialog; } }
true
true
private Dialog buildDialog(Context context, Task task) { UserInterface userInterface = task.getUser(); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context); Dialog dialog = dialogBuilder.show(); dialog.setContentView(R.layout.dialog_help_er_in_range); // dialog.setCanceledOnTouchOutside(false); ImageView imageView; TextView text; String string;Button button; Drawable[] drawables = new Drawable[4]; imageView = (ImageView) dialog.findViewById(R.id.dialog_helper_in_range_picture); imageView.setImageDrawable(new LayerDrawable(ImageUtility.retrieveDrawables(context, userInterface.getPicture()))); text = (TextView) dialog.findViewById(R.id.dialog_helper_in_range_title); string = context.getString(R.string.helper_in_range_title); string = string.replace("[Name]", userInterface.getName()); text.setText(Html.fromHtml(string)); text = (TextView) dialog.findViewById(R.id.dialog_helper_in_range_text); string = context.getString(R.string.helper_in_range_text); if (userInterface.getGender().equalsIgnoreCase("female")) { string = string.replace("[gender]", "her"); }else { string = string.replace("[gender]", "him"); } text.setText(Html.fromHtml(string)); button = (Button) dialog.findViewById(R.id.dialog_helper_in_range_button); button.setText("OK"); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), HelpERControlcenterActivity.class); startActivity(intent); finish(); } }); return dialog; }
private Dialog buildDialog(Context context, Task task) { UserInterface userInterface = task.getUser(); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context); Dialog dialog = dialogBuilder.show(); dialog.setContentView(R.layout.dialog_help_er_in_range); dialog.setCanceledOnTouchOutside(false); ImageView imageView; TextView text; String string;Button button; Drawable[] drawables = new Drawable[4]; imageView = (ImageView) dialog.findViewById(R.id.dialog_helper_in_range_picture); imageView.setImageDrawable(new LayerDrawable(ImageUtility.retrieveDrawables(context, userInterface.getPicture()))); text = (TextView) dialog.findViewById(R.id.dialog_helper_in_range_title); string = context.getString(R.string.helper_in_range_title); string = string.replace("[Name]", userInterface.getName()); text.setText(Html.fromHtml(string)); text = (TextView) dialog.findViewById(R.id.dialog_helper_in_range_text); string = context.getString(R.string.helper_in_range_text); if (userInterface.getGender().equalsIgnoreCase("female")) { string = string.replace("[gender]", "her"); }else { string = string.replace("[gender]", "him"); } text.setText(Html.fromHtml(string)); button = (Button) dialog.findViewById(R.id.dialog_helper_in_range_button); button.setText("OK"); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), HelpERControlcenterActivity.class); startActivity(intent); finish(); } }); return dialog; }
diff --git a/desktop/src/net/mms_projects/copy_it/ui/swt/forms/PreferencesDialog.java b/desktop/src/net/mms_projects/copy_it/ui/swt/forms/PreferencesDialog.java index 60d1e3e..5eab6db 100644 --- a/desktop/src/net/mms_projects/copy_it/ui/swt/forms/PreferencesDialog.java +++ b/desktop/src/net/mms_projects/copy_it/ui/swt/forms/PreferencesDialog.java @@ -1,325 +1,324 @@ package net.mms_projects.copy_it.ui.swt.forms; import net.mms_projects.copy_it.LoginResponse; import net.mms_projects.copy_it.Messages; import net.mms_projects.copy_it.Settings; import net.mms_projects.copy_it.api.ServerApi; import net.mms_projects.copy_it.api.endpoints.DeviceEndpoint; import net.mms_projects.copy_it.ui.swt.forms.login_dialogs.AbstractLoginDialog; import net.mms_projects.copy_it.ui.swt.forms.login_dialogs.AutoLoginDialog; import net.mms_projects.copy_it.ui.swt.forms.login_dialogs.LoginDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PreferencesDialog extends GeneralDialog { protected Shell shell; private Settings settings; private Text textEncryptionPassphrase; private Label lblDeviceIdHere; private Button btnLogin; private Button btnManualLogin; private Button btnEnablePolling; private Button btnEnableQueue; private final Logger log = LoggerFactory.getLogger(this.getClass()); /** * Create the dialog. * * @param parent * @param Settings * the settings */ public PreferencesDialog(Shell parent, Settings settings) { super(parent, SWT.DIALOG_TRIM); this.settings = settings; setText(Messages.getString("title_activity_settings")); } @Override public void open() { this.createContents(); this.updateForm(); this.shell.open(); this.shell.layout(); Display display = getParent().getDisplay(); while (!this.shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } this.settings.saveProperties(); } /** * Create contents of the dialog. */ protected void createContents() { /* * Definitions */ // Shell this.shell = new Shell(this.getParent(), SWT.DIALOG_TRIM); shell.setLayout(new FormLayout()); // Elements TabFolder tabFolder = new TabFolder(shell, SWT.NONE); FormData fd_tabFolder = new FormData(); fd_tabFolder.left = new FormAttachment(0, 10); fd_tabFolder.right = new FormAttachment(100, -6); fd_tabFolder.top = new FormAttachment(0, 10); fd_tabFolder.bottom = new FormAttachment(0, 358); tabFolder.setLayoutData(fd_tabFolder); Button btnClose = new Button(shell, SWT.NONE); FormData fd_btnClose = new FormData(); fd_btnClose.top = new FormAttachment(tabFolder, 6); fd_btnClose.right = new FormAttachment(tabFolder, 0, SWT.RIGHT); fd_btnClose.left = new FormAttachment(0, 457); btnClose.setLayoutData(fd_btnClose); // Account tab TabItem tbtmAccount = new TabItem(tabFolder, SWT.NONE); Composite compositeAccount = new Composite(tabFolder, SWT.NONE); compositeAccount.setLayout(new FormLayout()); Label lblAccountName = new Label(compositeAccount, SWT.NONE); FormData fd_lblAccountName = new FormData(); fd_lblAccountName.right = new FormAttachment(0, 170); fd_lblAccountName.top = new FormAttachment(0, 10); fd_lblAccountName.left = new FormAttachment(0, 10); lblAccountName.setLayoutData(fd_lblAccountName); Label lblAccountNameHere = new Label(compositeAccount, SWT.NONE); FormData fd_lblAccountNameHere = new FormData(); fd_lblAccountNameHere.right = new FormAttachment(0, 380); fd_lblAccountNameHere.top = new FormAttachment(0, 10); fd_lblAccountNameHere.left = new FormAttachment(0, 200); lblAccountNameHere.setLayoutData(fd_lblAccountNameHere); Label lblDeviceId = new Label(compositeAccount, SWT.NONE); FormData fd_lblDeviceId = new FormData(); fd_lblDeviceId.right = new FormAttachment(0, 80); fd_lblDeviceId.top = new FormAttachment(0, 33); fd_lblDeviceId.left = new FormAttachment(0, 10); lblDeviceId.setLayoutData(fd_lblDeviceId); this.lblDeviceIdHere = new Label(compositeAccount, SWT.NONE); FormData fd_lblDeviceIdHere = new FormData(); fd_lblDeviceIdHere.right = new FormAttachment(0, 380); fd_lblDeviceIdHere.top = new FormAttachment(0, 33); fd_lblDeviceIdHere.left = new FormAttachment(0, 200); lblDeviceIdHere.setLayoutData(fd_lblDeviceIdHere); this.btnLogin = new Button(compositeAccount, SWT.NONE); FormData fd_btnLogin = new FormData(); fd_btnLogin.left = new FormAttachment(0, 200); fd_btnLogin.top = new FormAttachment(lblDeviceIdHere, 6); fd_btnLogin.bottom = new FormAttachment(0, 85); btnLogin.setLayoutData(fd_btnLogin); this.btnManualLogin = new Button(compositeAccount, SWT.NONE); fd_btnLogin.right = new FormAttachment(btnManualLogin, -6); FormData fd_btnManualLogin = new FormData(); fd_btnManualLogin.bottom = new FormAttachment(btnLogin, 0, SWT.BOTTOM); fd_btnManualLogin.left = new FormAttachment(0, 364); fd_btnManualLogin.right = new FormAttachment(100, -10); fd_btnManualLogin.top = new FormAttachment(lblDeviceIdHere, 6); btnManualLogin.setLayoutData(fd_btnManualLogin); // Security tab TabItem tbtmSecurity = new TabItem(tabFolder, SWT.NONE); Composite compositeSecurity = new Composite(tabFolder, SWT.NONE); compositeSecurity.setLayout(new FormLayout()); final Button btnEnableLocalEncryption = new Button(compositeSecurity, SWT.CHECK); FormData fd_btnEnableLocalEncryption = new FormData(); fd_btnEnableLocalEncryption.right = new FormAttachment(0, 194); fd_btnEnableLocalEncryption.top = new FormAttachment(0, 10); fd_btnEnableLocalEncryption.left = new FormAttachment(0, 10); btnEnableLocalEncryption.setLayoutData(fd_btnEnableLocalEncryption); Label lblEncryptionPassphrase = new Label(compositeSecurity, SWT.NONE); FormData fd_lblEncryptionPassphrase = new FormData(); fd_lblEncryptionPassphrase.right = new FormAttachment(0, 194); fd_lblEncryptionPassphrase.top = new FormAttachment(0, 44); fd_lblEncryptionPassphrase.left = new FormAttachment(0, 10); lblEncryptionPassphrase.setLayoutData(fd_lblEncryptionPassphrase); this.textEncryptionPassphrase = new Text(compositeSecurity, SWT.BORDER); FormData fd_textEncryptionPassphrase = new FormData(); fd_textEncryptionPassphrase.right = new FormAttachment(0, 400); fd_textEncryptionPassphrase.top = new FormAttachment(0, 40); fd_textEncryptionPassphrase.left = new FormAttachment(0, 200); textEncryptionPassphrase.setLayoutData(fd_textEncryptionPassphrase); // Sync tab TabItem tbtmSync = new TabItem(tabFolder, SWT.NONE); Composite compositeSync = new Composite(tabFolder, SWT.NONE); compositeSync.setLayout(new FormLayout()); btnEnablePolling = new Button(compositeSync, SWT.CHECK); FormData fd_btnEnablePolling = new FormData(); - fd_btnEnablePolling.right = new FormAttachment(0, 178); fd_btnEnablePolling.top = new FormAttachment(0, 10); fd_btnEnablePolling.left = new FormAttachment(0, 10); btnEnablePolling.setLayoutData(fd_btnEnablePolling); btnEnableQueue = new Button(compositeSync, SWT.CHECK); FormData fd_btnEnableQueue = new FormData(); fd_btnEnableQueue.top = new FormAttachment(0, 40); fd_btnEnableQueue.left = new FormAttachment(0, 10); btnEnableQueue.setLayoutData(fd_btnEnableQueue); /* * Layout and settings */ // Shell this.shell.setSize(552, 434); this.shell.setText(getText()); btnClose.setText("Close"); // Account tab tbtmAccount.setText("Account"); tbtmAccount.setControl(compositeAccount); lblAccountName.setText("Account name:"); lblAccountNameHere.setText("Account name here..."); lblDeviceId.setText("Device id:"); this.lblDeviceIdHere.setText("Device id here..."); this.btnLogin.setText(Messages.getString("button_login")); this.btnManualLogin.setText("Manual login "); // Security tab tbtmSecurity.setText("Security"); tbtmSecurity.setControl(compositeSecurity); btnEnableLocalEncryption.setText("Enable local encryption"); lblEncryptionPassphrase.setText("Encryption passphrase:"); // Sync tab tbtmSync.setText("Sync"); tbtmSync.setControl(compositeSync); btnEnablePolling.setText(Messages .getString("PreferencesDialog.btnEnablePolling.text")); btnEnableQueue.setText(Messages .getString("PreferencesDialog.btnEnableQueue.text")); //$NON-NLS-1$ /* * Listeners */ // Automatic login button this.btnLogin.addSelectionListener(new LoginSectionAdapter() { @Override public AbstractLoginDialog getLoginDialog() { return new AutoLoginDialog(shell, PreferencesDialog.this.settings); } }); // Manual login this.btnManualLogin.addSelectionListener(new LoginSectionAdapter() { @Override public AbstractLoginDialog getLoginDialog() { return new LoginDialog(shell); } }); // Encryption enable checkbox btnEnableLocalEncryption.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { textEncryptionPassphrase.setEnabled(btnEnableLocalEncryption .getSelection()); PreferencesDialog.this.updateForm(); } }); // Close button btnClose.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { PreferencesDialog.this.shell.close(); } }); // Sync tab btnEnablePolling.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { PreferencesDialog.this.settings.set("sync.polling.enabled", btnEnablePolling.getSelection()); PreferencesDialog.this.updateForm(); } }); btnEnableQueue.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { PreferencesDialog.this.settings.set("sync.queue.enabled", btnEnableQueue.getSelection()); PreferencesDialog.this.updateForm(); } }); } protected void updateForm() { if (this.settings.get("device.id") != null) { this.lblDeviceIdHere.setText(this.settings.get("device.id")); } else { this.lblDeviceIdHere.setText("None"); } if (this.settings.get("device.id") != null) { this.btnLogin.setText("Relogin"); } if (this.settings.get("device.id") != null) { this.btnManualLogin.setText("Relogin (manual)"); } btnEnablePolling.setSelection(this.settings .getBoolean("sync.polling.enabled")); btnEnableQueue.setSelection(this.settings .getBoolean("sync.queue.enabled")); btnEnableQueue.setEnabled(this.settings .getBoolean("sync.polling.enabled")); } private abstract class LoginSectionAdapter extends SelectionAdapter { abstract public AbstractLoginDialog getLoginDialog(); @Override final public void widgetSelected(SelectionEvent event) { AbstractLoginDialog dialog = this.getLoginDialog(); dialog.open(); LoginResponse response = dialog.getResponse(); if (response == null) { log.debug("No login response returned."); return; } ServerApi api = new ServerApi(); api.deviceId = response.deviceId; api.devicePassword = response.devicePassword; try { new DeviceEndpoint(api).create("Interwebz Paste client"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } PreferencesDialog.this.settings.set("device.id", response.deviceId.toString()); PreferencesDialog.this.settings.set("device.password", response.devicePassword); PreferencesDialog.this.updateForm(); } } }
true
true
protected void createContents() { /* * Definitions */ // Shell this.shell = new Shell(this.getParent(), SWT.DIALOG_TRIM); shell.setLayout(new FormLayout()); // Elements TabFolder tabFolder = new TabFolder(shell, SWT.NONE); FormData fd_tabFolder = new FormData(); fd_tabFolder.left = new FormAttachment(0, 10); fd_tabFolder.right = new FormAttachment(100, -6); fd_tabFolder.top = new FormAttachment(0, 10); fd_tabFolder.bottom = new FormAttachment(0, 358); tabFolder.setLayoutData(fd_tabFolder); Button btnClose = new Button(shell, SWT.NONE); FormData fd_btnClose = new FormData(); fd_btnClose.top = new FormAttachment(tabFolder, 6); fd_btnClose.right = new FormAttachment(tabFolder, 0, SWT.RIGHT); fd_btnClose.left = new FormAttachment(0, 457); btnClose.setLayoutData(fd_btnClose); // Account tab TabItem tbtmAccount = new TabItem(tabFolder, SWT.NONE); Composite compositeAccount = new Composite(tabFolder, SWT.NONE); compositeAccount.setLayout(new FormLayout()); Label lblAccountName = new Label(compositeAccount, SWT.NONE); FormData fd_lblAccountName = new FormData(); fd_lblAccountName.right = new FormAttachment(0, 170); fd_lblAccountName.top = new FormAttachment(0, 10); fd_lblAccountName.left = new FormAttachment(0, 10); lblAccountName.setLayoutData(fd_lblAccountName); Label lblAccountNameHere = new Label(compositeAccount, SWT.NONE); FormData fd_lblAccountNameHere = new FormData(); fd_lblAccountNameHere.right = new FormAttachment(0, 380); fd_lblAccountNameHere.top = new FormAttachment(0, 10); fd_lblAccountNameHere.left = new FormAttachment(0, 200); lblAccountNameHere.setLayoutData(fd_lblAccountNameHere); Label lblDeviceId = new Label(compositeAccount, SWT.NONE); FormData fd_lblDeviceId = new FormData(); fd_lblDeviceId.right = new FormAttachment(0, 80); fd_lblDeviceId.top = new FormAttachment(0, 33); fd_lblDeviceId.left = new FormAttachment(0, 10); lblDeviceId.setLayoutData(fd_lblDeviceId); this.lblDeviceIdHere = new Label(compositeAccount, SWT.NONE); FormData fd_lblDeviceIdHere = new FormData(); fd_lblDeviceIdHere.right = new FormAttachment(0, 380); fd_lblDeviceIdHere.top = new FormAttachment(0, 33); fd_lblDeviceIdHere.left = new FormAttachment(0, 200); lblDeviceIdHere.setLayoutData(fd_lblDeviceIdHere); this.btnLogin = new Button(compositeAccount, SWT.NONE); FormData fd_btnLogin = new FormData(); fd_btnLogin.left = new FormAttachment(0, 200); fd_btnLogin.top = new FormAttachment(lblDeviceIdHere, 6); fd_btnLogin.bottom = new FormAttachment(0, 85); btnLogin.setLayoutData(fd_btnLogin); this.btnManualLogin = new Button(compositeAccount, SWT.NONE); fd_btnLogin.right = new FormAttachment(btnManualLogin, -6); FormData fd_btnManualLogin = new FormData(); fd_btnManualLogin.bottom = new FormAttachment(btnLogin, 0, SWT.BOTTOM); fd_btnManualLogin.left = new FormAttachment(0, 364); fd_btnManualLogin.right = new FormAttachment(100, -10); fd_btnManualLogin.top = new FormAttachment(lblDeviceIdHere, 6); btnManualLogin.setLayoutData(fd_btnManualLogin); // Security tab TabItem tbtmSecurity = new TabItem(tabFolder, SWT.NONE); Composite compositeSecurity = new Composite(tabFolder, SWT.NONE); compositeSecurity.setLayout(new FormLayout()); final Button btnEnableLocalEncryption = new Button(compositeSecurity, SWT.CHECK); FormData fd_btnEnableLocalEncryption = new FormData(); fd_btnEnableLocalEncryption.right = new FormAttachment(0, 194); fd_btnEnableLocalEncryption.top = new FormAttachment(0, 10); fd_btnEnableLocalEncryption.left = new FormAttachment(0, 10); btnEnableLocalEncryption.setLayoutData(fd_btnEnableLocalEncryption); Label lblEncryptionPassphrase = new Label(compositeSecurity, SWT.NONE); FormData fd_lblEncryptionPassphrase = new FormData(); fd_lblEncryptionPassphrase.right = new FormAttachment(0, 194); fd_lblEncryptionPassphrase.top = new FormAttachment(0, 44); fd_lblEncryptionPassphrase.left = new FormAttachment(0, 10); lblEncryptionPassphrase.setLayoutData(fd_lblEncryptionPassphrase); this.textEncryptionPassphrase = new Text(compositeSecurity, SWT.BORDER); FormData fd_textEncryptionPassphrase = new FormData(); fd_textEncryptionPassphrase.right = new FormAttachment(0, 400); fd_textEncryptionPassphrase.top = new FormAttachment(0, 40); fd_textEncryptionPassphrase.left = new FormAttachment(0, 200); textEncryptionPassphrase.setLayoutData(fd_textEncryptionPassphrase); // Sync tab TabItem tbtmSync = new TabItem(tabFolder, SWT.NONE); Composite compositeSync = new Composite(tabFolder, SWT.NONE); compositeSync.setLayout(new FormLayout()); btnEnablePolling = new Button(compositeSync, SWT.CHECK); FormData fd_btnEnablePolling = new FormData(); fd_btnEnablePolling.right = new FormAttachment(0, 178); fd_btnEnablePolling.top = new FormAttachment(0, 10); fd_btnEnablePolling.left = new FormAttachment(0, 10); btnEnablePolling.setLayoutData(fd_btnEnablePolling); btnEnableQueue = new Button(compositeSync, SWT.CHECK); FormData fd_btnEnableQueue = new FormData(); fd_btnEnableQueue.top = new FormAttachment(0, 40); fd_btnEnableQueue.left = new FormAttachment(0, 10); btnEnableQueue.setLayoutData(fd_btnEnableQueue); /* * Layout and settings */ // Shell this.shell.setSize(552, 434); this.shell.setText(getText()); btnClose.setText("Close"); // Account tab tbtmAccount.setText("Account"); tbtmAccount.setControl(compositeAccount); lblAccountName.setText("Account name:"); lblAccountNameHere.setText("Account name here..."); lblDeviceId.setText("Device id:"); this.lblDeviceIdHere.setText("Device id here..."); this.btnLogin.setText(Messages.getString("button_login")); this.btnManualLogin.setText("Manual login "); // Security tab tbtmSecurity.setText("Security"); tbtmSecurity.setControl(compositeSecurity); btnEnableLocalEncryption.setText("Enable local encryption"); lblEncryptionPassphrase.setText("Encryption passphrase:"); // Sync tab tbtmSync.setText("Sync"); tbtmSync.setControl(compositeSync); btnEnablePolling.setText(Messages .getString("PreferencesDialog.btnEnablePolling.text")); btnEnableQueue.setText(Messages .getString("PreferencesDialog.btnEnableQueue.text")); //$NON-NLS-1$ /* * Listeners */ // Automatic login button this.btnLogin.addSelectionListener(new LoginSectionAdapter() { @Override public AbstractLoginDialog getLoginDialog() { return new AutoLoginDialog(shell, PreferencesDialog.this.settings); } }); // Manual login this.btnManualLogin.addSelectionListener(new LoginSectionAdapter() { @Override public AbstractLoginDialog getLoginDialog() { return new LoginDialog(shell); } }); // Encryption enable checkbox btnEnableLocalEncryption.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { textEncryptionPassphrase.setEnabled(btnEnableLocalEncryption .getSelection()); PreferencesDialog.this.updateForm(); } }); // Close button btnClose.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { PreferencesDialog.this.shell.close(); } }); // Sync tab btnEnablePolling.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { PreferencesDialog.this.settings.set("sync.polling.enabled", btnEnablePolling.getSelection()); PreferencesDialog.this.updateForm(); } }); btnEnableQueue.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { PreferencesDialog.this.settings.set("sync.queue.enabled", btnEnableQueue.getSelection()); PreferencesDialog.this.updateForm(); } }); }
protected void createContents() { /* * Definitions */ // Shell this.shell = new Shell(this.getParent(), SWT.DIALOG_TRIM); shell.setLayout(new FormLayout()); // Elements TabFolder tabFolder = new TabFolder(shell, SWT.NONE); FormData fd_tabFolder = new FormData(); fd_tabFolder.left = new FormAttachment(0, 10); fd_tabFolder.right = new FormAttachment(100, -6); fd_tabFolder.top = new FormAttachment(0, 10); fd_tabFolder.bottom = new FormAttachment(0, 358); tabFolder.setLayoutData(fd_tabFolder); Button btnClose = new Button(shell, SWT.NONE); FormData fd_btnClose = new FormData(); fd_btnClose.top = new FormAttachment(tabFolder, 6); fd_btnClose.right = new FormAttachment(tabFolder, 0, SWT.RIGHT); fd_btnClose.left = new FormAttachment(0, 457); btnClose.setLayoutData(fd_btnClose); // Account tab TabItem tbtmAccount = new TabItem(tabFolder, SWT.NONE); Composite compositeAccount = new Composite(tabFolder, SWT.NONE); compositeAccount.setLayout(new FormLayout()); Label lblAccountName = new Label(compositeAccount, SWT.NONE); FormData fd_lblAccountName = new FormData(); fd_lblAccountName.right = new FormAttachment(0, 170); fd_lblAccountName.top = new FormAttachment(0, 10); fd_lblAccountName.left = new FormAttachment(0, 10); lblAccountName.setLayoutData(fd_lblAccountName); Label lblAccountNameHere = new Label(compositeAccount, SWT.NONE); FormData fd_lblAccountNameHere = new FormData(); fd_lblAccountNameHere.right = new FormAttachment(0, 380); fd_lblAccountNameHere.top = new FormAttachment(0, 10); fd_lblAccountNameHere.left = new FormAttachment(0, 200); lblAccountNameHere.setLayoutData(fd_lblAccountNameHere); Label lblDeviceId = new Label(compositeAccount, SWT.NONE); FormData fd_lblDeviceId = new FormData(); fd_lblDeviceId.right = new FormAttachment(0, 80); fd_lblDeviceId.top = new FormAttachment(0, 33); fd_lblDeviceId.left = new FormAttachment(0, 10); lblDeviceId.setLayoutData(fd_lblDeviceId); this.lblDeviceIdHere = new Label(compositeAccount, SWT.NONE); FormData fd_lblDeviceIdHere = new FormData(); fd_lblDeviceIdHere.right = new FormAttachment(0, 380); fd_lblDeviceIdHere.top = new FormAttachment(0, 33); fd_lblDeviceIdHere.left = new FormAttachment(0, 200); lblDeviceIdHere.setLayoutData(fd_lblDeviceIdHere); this.btnLogin = new Button(compositeAccount, SWT.NONE); FormData fd_btnLogin = new FormData(); fd_btnLogin.left = new FormAttachment(0, 200); fd_btnLogin.top = new FormAttachment(lblDeviceIdHere, 6); fd_btnLogin.bottom = new FormAttachment(0, 85); btnLogin.setLayoutData(fd_btnLogin); this.btnManualLogin = new Button(compositeAccount, SWT.NONE); fd_btnLogin.right = new FormAttachment(btnManualLogin, -6); FormData fd_btnManualLogin = new FormData(); fd_btnManualLogin.bottom = new FormAttachment(btnLogin, 0, SWT.BOTTOM); fd_btnManualLogin.left = new FormAttachment(0, 364); fd_btnManualLogin.right = new FormAttachment(100, -10); fd_btnManualLogin.top = new FormAttachment(lblDeviceIdHere, 6); btnManualLogin.setLayoutData(fd_btnManualLogin); // Security tab TabItem tbtmSecurity = new TabItem(tabFolder, SWT.NONE); Composite compositeSecurity = new Composite(tabFolder, SWT.NONE); compositeSecurity.setLayout(new FormLayout()); final Button btnEnableLocalEncryption = new Button(compositeSecurity, SWT.CHECK); FormData fd_btnEnableLocalEncryption = new FormData(); fd_btnEnableLocalEncryption.right = new FormAttachment(0, 194); fd_btnEnableLocalEncryption.top = new FormAttachment(0, 10); fd_btnEnableLocalEncryption.left = new FormAttachment(0, 10); btnEnableLocalEncryption.setLayoutData(fd_btnEnableLocalEncryption); Label lblEncryptionPassphrase = new Label(compositeSecurity, SWT.NONE); FormData fd_lblEncryptionPassphrase = new FormData(); fd_lblEncryptionPassphrase.right = new FormAttachment(0, 194); fd_lblEncryptionPassphrase.top = new FormAttachment(0, 44); fd_lblEncryptionPassphrase.left = new FormAttachment(0, 10); lblEncryptionPassphrase.setLayoutData(fd_lblEncryptionPassphrase); this.textEncryptionPassphrase = new Text(compositeSecurity, SWT.BORDER); FormData fd_textEncryptionPassphrase = new FormData(); fd_textEncryptionPassphrase.right = new FormAttachment(0, 400); fd_textEncryptionPassphrase.top = new FormAttachment(0, 40); fd_textEncryptionPassphrase.left = new FormAttachment(0, 200); textEncryptionPassphrase.setLayoutData(fd_textEncryptionPassphrase); // Sync tab TabItem tbtmSync = new TabItem(tabFolder, SWT.NONE); Composite compositeSync = new Composite(tabFolder, SWT.NONE); compositeSync.setLayout(new FormLayout()); btnEnablePolling = new Button(compositeSync, SWT.CHECK); FormData fd_btnEnablePolling = new FormData(); fd_btnEnablePolling.top = new FormAttachment(0, 10); fd_btnEnablePolling.left = new FormAttachment(0, 10); btnEnablePolling.setLayoutData(fd_btnEnablePolling); btnEnableQueue = new Button(compositeSync, SWT.CHECK); FormData fd_btnEnableQueue = new FormData(); fd_btnEnableQueue.top = new FormAttachment(0, 40); fd_btnEnableQueue.left = new FormAttachment(0, 10); btnEnableQueue.setLayoutData(fd_btnEnableQueue); /* * Layout and settings */ // Shell this.shell.setSize(552, 434); this.shell.setText(getText()); btnClose.setText("Close"); // Account tab tbtmAccount.setText("Account"); tbtmAccount.setControl(compositeAccount); lblAccountName.setText("Account name:"); lblAccountNameHere.setText("Account name here..."); lblDeviceId.setText("Device id:"); this.lblDeviceIdHere.setText("Device id here..."); this.btnLogin.setText(Messages.getString("button_login")); this.btnManualLogin.setText("Manual login "); // Security tab tbtmSecurity.setText("Security"); tbtmSecurity.setControl(compositeSecurity); btnEnableLocalEncryption.setText("Enable local encryption"); lblEncryptionPassphrase.setText("Encryption passphrase:"); // Sync tab tbtmSync.setText("Sync"); tbtmSync.setControl(compositeSync); btnEnablePolling.setText(Messages .getString("PreferencesDialog.btnEnablePolling.text")); btnEnableQueue.setText(Messages .getString("PreferencesDialog.btnEnableQueue.text")); //$NON-NLS-1$ /* * Listeners */ // Automatic login button this.btnLogin.addSelectionListener(new LoginSectionAdapter() { @Override public AbstractLoginDialog getLoginDialog() { return new AutoLoginDialog(shell, PreferencesDialog.this.settings); } }); // Manual login this.btnManualLogin.addSelectionListener(new LoginSectionAdapter() { @Override public AbstractLoginDialog getLoginDialog() { return new LoginDialog(shell); } }); // Encryption enable checkbox btnEnableLocalEncryption.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { textEncryptionPassphrase.setEnabled(btnEnableLocalEncryption .getSelection()); PreferencesDialog.this.updateForm(); } }); // Close button btnClose.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { PreferencesDialog.this.shell.close(); } }); // Sync tab btnEnablePolling.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { PreferencesDialog.this.settings.set("sync.polling.enabled", btnEnablePolling.getSelection()); PreferencesDialog.this.updateForm(); } }); btnEnableQueue.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { PreferencesDialog.this.settings.set("sync.queue.enabled", btnEnableQueue.getSelection()); PreferencesDialog.this.updateForm(); } }); }
diff --git a/src/share/classes/com/sun/tools/javafx/comp/JavafxResolve.java b/src/share/classes/com/sun/tools/javafx/comp/JavafxResolve.java index d6475c32d..656e66629 100644 --- a/src/share/classes/com/sun/tools/javafx/comp/JavafxResolve.java +++ b/src/share/classes/com/sun/tools/javafx/comp/JavafxResolve.java @@ -1,2172 +1,2180 @@ /* * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.tools.javafx.comp; import com.sun.tools.javac.comp.*; import com.sun.tools.javac.util.*; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javac.code.*; import com.sun.tools.javac.jvm.*; import com.sun.tools.javac.tree.*; import com.sun.tools.javac.code.Type.*; import com.sun.tools.javac.code.Symbol.*; import static com.sun.tools.javac.code.Flags.*; import static com.sun.tools.javac.code.Kinds.*; import static com.sun.tools.javac.code.TypeTags.*; import javax.lang.model.element.ElementVisitor; import com.sun.tools.javafx.code.*; import com.sun.tools.javafx.tree.*; import com.sun.tools.javafx.util.MsgSym; import java.util.HashSet; import java.util.Set; /** Helper class for name resolution, used mostly by the attribution phase. * * <p><b>This is NOT part of any API supported by Sun Microsystems. If * you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice.</b> */ public class JavafxResolve { protected static final Context.Key<JavafxResolve> javafxResolveKey = new Context.Key<JavafxResolve>(); Name.Table names; Log log; JavafxSymtab syms; JavafxCheck chk; Infer infer; JavafxClassReader reader; JavafxTreeInfo treeinfo; JavafxTypes types; public final boolean boxingEnabled; // = source.allowBoxing(); public final boolean varargsEnabled; // = source.allowVarargs(); private final boolean debugResolve; public static JavafxResolve instance(Context context) { JavafxResolve instance = context.get(javafxResolveKey); if (instance == null) instance = new JavafxResolve(context); return instance; } protected JavafxResolve(Context context) { context.put(javafxResolveKey, this); syms = (JavafxSymtab)JavafxSymtab.instance(context); varNotFound = new ResolveError(ABSENT_VAR, syms.errSymbol, "variable not found"); wrongMethod = new ResolveError(WRONG_MTH, syms.errSymbol, "method not found"); wrongMethods = new ResolveError(WRONG_MTHS, syms.errSymbol, "wrong methods"); methodNotFound = new ResolveError(ABSENT_MTH, syms.errSymbol, "method not found"); typeNotFound = new ResolveError(ABSENT_TYP, syms.errSymbol, "type not found"); names = Name.Table.instance(context); log = Log.instance(context); chk = (JavafxCheck)JavafxCheck.instance(context); infer = Infer.instance(context); reader = JavafxClassReader.instance(context); treeinfo = JavafxTreeInfo.instance(context); types = JavafxTypes.instance(context); Source source = Source.instance(context); boxingEnabled = source.allowBoxing(); varargsEnabled = source.allowVarargs(); Options options = Options.instance(context); debugResolve = options.get("debugresolve") != null; } /** error symbols, which are returned when resolution fails */ final ResolveError varNotFound; final ResolveError wrongMethod; final ResolveError wrongMethods; final ResolveError methodNotFound; final ResolveError typeNotFound; /* ************************************************************************ * Identifier resolution *************************************************************************/ /** An environment is "static" if its static level is greater than * the one of its outer environment */ // JavaFX change public // JavaFX change static boolean isStatic(JavafxEnv<JavafxAttrContext> env) { return env.info.staticLevel > env.outer.info.staticLevel; } /** An environment is an "initializer" if it is a constructor or * an instance initializer. */ static boolean isInitializer(JavafxEnv<JavafxAttrContext> env) { Symbol owner = env.info.scope.owner; return owner.isConstructor() || owner.owner.kind == TYP && (owner.kind == VAR || owner.kind == MTH && (owner.flags() & BLOCK) != 0) && (owner.flags() & STATIC) == 0; } /** Is class accessible in given evironment? * @param env The current environment. * @param c The class whose accessibility is checked. */ public boolean isAccessible(JavafxEnv<JavafxAttrContext> env, TypeSymbol c) { // because the SCRIPT_PRIVATE bit is too high for the switch, test it later switch ((short)(c.flags() & Flags.AccessFlags)) { case PRIVATE: return env.enclClass.sym.outermostClass() == c.owner.outermostClass(); case 0: if ((c.flags() & JavafxFlags.SCRIPT_PRIVATE) != 0) { // script-private //System.err.println("isAccessible " + c + " = " + (env.enclClass.sym.outermostClass() == // c.outermostClass()) + ", enclClass " + env.enclClass.getName()); //System.err.println(" encl outer: " + env.enclClass.sym.outermostClass() + ", c outer: " + c.outermostClass()); return env.enclClass.sym.outermostClass() == c.outermostClass(); }; // 'package' access return env.toplevel.packge == c.owner // fast special case || env.toplevel.packge == c.packge() || // Hack: this case is added since synthesized default constructors // of anonymous classes should be allowed to access // classes which would be inaccessible otherwise. env.enclFunction != null && (env.enclFunction.mods.flags & ANONCONSTR) != 0; default: // error recovery case PUBLIC: return true; case PROTECTED: return env.toplevel.packge == c.owner // fast special case || env.toplevel.packge == c.packge() || isInnerSubClass(env.enclClass.sym, c.owner); } } //where /** Is given class a subclass of given base class, or an inner class * of a subclass? * Return null if no such class exists. * @param c The class which is the subclass or is contained in it. * @param base The base class */ private boolean isInnerSubClass(ClassSymbol c, Symbol base) { while (c != null && !c.isSubClass(base, types)) { c = c.owner.enclClass(); } return c != null; } boolean isAccessible(JavafxEnv<JavafxAttrContext> env, Type t) { return (t.tag == ARRAY) ? isAccessible(env, types.elemtype(t)) : isAccessible(env, t.tsym); } /** Is symbol accessible as a member of given type in given evironment? * @param env The current environment. * @param site The type of which the tested symbol is regarded * as a member. * @param sym The symbol. */ public boolean isAccessible(JavafxEnv<JavafxAttrContext> env, Type site, Symbol sym) { if (sym.name == names.init && sym.owner != site.tsym) return false; if ((sym.flags() & (JavafxFlags.PUBLIC_READ | JavafxFlags.PUBLIC_INIT)) != 0) { // assignment access handled elsewhere -- treat like return isAccessible(env, site); } // if the READABLE flag isn't set, then access for read is the same as for write return isAccessibleForWrite(env, site, sym); } /** Is symbol accessible for write as a member of given type in given evironment? * @param env The current environment. * @param site The type of which the tested symbol is regarded * as a member. * @param sym The symbol. */ public boolean isAccessibleForWrite(JavafxEnv<JavafxAttrContext> env, Type site, Symbol sym) { if (sym.name == names.init && sym.owner != site.tsym) return false; // because the SCRIPT_PRIVATE bit is too high for the switch, test it later switch ((short)(sym.flags() & Flags.AccessFlags)) { case PRIVATE: return (env.enclClass.sym == sym.owner // fast special case || env.enclClass.sym.outermostClass() == sym.owner.outermostClass()) && isInheritedIn(sym, site.tsym, types); case 0: if ((sym.flags() & JavafxFlags.SCRIPT_PRIVATE) != 0) { // script-private //TODO: don't know what is right if (env.enclClass.sym == sym.owner) { return true; // fast special case -- in this class } Symbol enclOuter = env.enclClass.sym.outermostClass(); Symbol ownerOuter = sym.owner.outermostClass(); return enclOuter == ownerOuter; }; // 'package' access PackageSymbol pkg = env.toplevel.packge; boolean samePkg = (pkg == sym.owner.owner // fast special case || pkg == sym.packge()); boolean typeAccessible = isAccessible(env, site); // TODO: javac logic is to also 'and'-in inheritedIn. // Based possibly on bugs in what is passed in, // this doesn't work when accessing static variables in an outer class. // When called from findVar this works because the site in the actual // owner of the sym, but when coming from an ident and checkAssignable // this isn't true. //boolean inheritedIn = isInheritedIn(sym, site.tsym, types); return samePkg && typeAccessible; case PROTECTED: return (env.toplevel.packge == sym.owner.owner // fast special case || env.toplevel.packge == sym.packge() || isProtectedAccessible(sym, env.enclClass.sym, site) || // OK to select instance method or field from 'super' or type name // (but type names should be disallowed elsewhere!) env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP) && isAccessible(env, site) && // `sym' is accessible only if not overridden by // another symbol which is a member of `site' // (because, if it is overridden, `sym' is not strictly // speaking a member of `site'.) (sym.kind != MTH || sym.isConstructor() || types.implementation((MethodSymbol)sym, site.tsym, true) == sym); default: // this case includes erroneous combinations as well return isAccessible(env, site); } } //where /** Is given protected symbol accessible if it is selected from given site * and the selection takes place in given class? * @param sym The symbol with protected access * @param c The class where the access takes place * @site The type of the qualifier */ private boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) { while (c != null && !(types.isSuperType(types.erasure(sym.owner.type), c) && (c.flags() & INTERFACE) == 0 && // In JLS 2e 6.6.2.1, the subclass restriction applies // only to instance fields and methods -- types are excluded // regardless of whether they are declared 'static' or not. ((sym.flags() & STATIC) != 0 || sym.kind == TYP || types.isSuperType(site, c)))) c = c.owner.enclClass(); return c != null; } /** Try to instantiate the type of a method so that it fits * given type arguments and argument types. If succesful, return * the method's instantiated type, else return null. * The instantiation will take into account an additional leading * formal parameter if the method is an instance method seen as a member * of un underdetermined site In this case, we treat site as an additional * parameter and the parameters of the class containing the method as * additional type variables that get instantiated. * * @param env The current environment * @param m The method symbol. * @param mt The expected type. * @param argtypes The invocation's given value arguments. * @param typeargtypes The invocation's given type arguments. * @param allowBoxing Allow boxing conversions of arguments. * @param useVarargs Box trailing arguments into an array for varargs. */ Type rawInstantiate(JavafxEnv<JavafxAttrContext> env, Symbol m, Type mt, List<Type> argtypes, List<Type> typeargtypes, boolean allowBoxing, boolean useVarargs, Warner warn) throws Infer.NoInstanceException { if (useVarargs && (m.flags() & VARARGS) == 0) return null; m.complete(); // tvars is the list of formal type variables for which type arguments // need to inferred. List<Type> tvars = env.info.tvars; if (typeargtypes == null) typeargtypes = List.nil(); if (mt.tag != FORALL && typeargtypes.nonEmpty()) { // This is not a polymorphic method, but typeargs are supplied // which is fine, see JLS3 15.12.2.1 } else if (mt.tag == FORALL && typeargtypes.nonEmpty()) { ForAll pmt = (ForAll) mt; if (typeargtypes.length() != pmt.tvars.length()) return null; // Check type arguments are within bounds List<Type> formals = pmt.tvars; List<Type> actuals = typeargtypes; while (formals.nonEmpty() && actuals.nonEmpty()) { List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head), pmt.tvars, typeargtypes); for (; bounds.nonEmpty(); bounds = bounds.tail) if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn)) return null; formals = formals.tail; actuals = actuals.tail; } mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes); } else if (mt.tag == FORALL) { ForAll pmt = (ForAll) mt; List<Type> tvars1 = types.newInstances(pmt.tvars); tvars = tvars.appendList(tvars1); mt = types.subst(pmt.qtype, pmt.tvars, tvars1); } // find out whether we need to go the slow route via infer boolean instNeeded = tvars.tail != null/*inlined: tvars.nonEmpty()*/; for (List<Type> l = argtypes; l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded; l = l.tail) { if (l.head.tag == FORALL) instNeeded = true; } if (instNeeded) return infer.instantiateMethod(tvars, (MethodType)mt, argtypes, allowBoxing, useVarargs, warn); return argumentsAcceptable(argtypes, mt.getParameterTypes(), allowBoxing, useVarargs, warn) ? mt : null; } /** Same but returns null instead throwing a NoInstanceException */ Type instantiate(JavafxEnv<JavafxAttrContext> env, Type site, Symbol m, List<Type> argtypes, List<Type> typeargtypes, boolean allowBoxing, boolean useVarargs, Warner warn) { try { return rawInstantiate(env, m, types.memberType(site, m), argtypes, typeargtypes, allowBoxing, useVarargs, warn); } catch (Infer.NoInstanceException ex) { return null; } } /** Check if a parameter list accepts a list of args. */ boolean argumentsAcceptable(List<Type> argtypes, List<Type> formals, boolean allowBoxing, boolean useVarargs, Warner warn) { Type varargsFormal = useVarargs ? formals.last() : null; while (argtypes.nonEmpty() && formals.head != varargsFormal) { boolean works = allowBoxing ? types.isConvertible(argtypes.head, formals.head, warn) : types.isSubtypeUnchecked(argtypes.head, formals.head, warn); if (!works) return false; argtypes = argtypes.tail; formals = formals.tail; } if (formals.head != varargsFormal) return false; // not enough args if (!useVarargs) return argtypes.isEmpty(); Type elt = types.elemtype(varargsFormal); while (argtypes.nonEmpty()) { if (!types.isConvertible(argtypes.head, elt, warn)) return false; argtypes = argtypes.tail; } return true; } /* *************************************************************************** * Symbol lookup * the following naming conventions for arguments are used * * env is the environment where the symbol was mentioned * site is the type of which the symbol is a member * name is the symbol's name * if no arguments are given * argtypes are the value arguments, if we search for a method * * If no symbol was found, a ResolveError detailing the problem is returned. ****************************************************************************/ /** Find field. Synthetic fields are always skipped. * @param env The current environment. * @param site The original type from where the selection takes place. * @param name The name of the field. * @param c The class to search for the field. This is always * a superclass or implemented interface of site's class. */ // Javafx change public // javafx change Symbol findField(JavafxEnv<JavafxAttrContext> env, Type site, Name name, TypeSymbol c) { Symbol bestSoFar = varNotFound; Symbol sym; Scope.Entry e = c.members().lookup(name); while (e.scope != null) { if ((e.sym.kind & (VAR|MTH)) != 0 && (e.sym.flags_field & SYNTHETIC) == 0) { sym = isAccessible(env, site, e.sym) ? e.sym : new AccessError(env, site, e.sym); if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS && sym.owner != bestSoFar.owner) bestSoFar = new AmbiguityError(bestSoFar, sym); else if (sym.kind < bestSoFar.kind) bestSoFar = sym; } e = e.next(); } if (bestSoFar != varNotFound) return bestSoFar; Type st = types.supertype(c.type); if (st != null && st.tag == CLASS) { sym = findField(env, site, name, st.tsym); if (sym.kind < bestSoFar.kind) bestSoFar = sym; } // We failed to find the field in the single Java class supertype of the // Javafx class. // Now try to find the filed in all of the Javafx supertypes. if (bestSoFar.kind > AMBIGUOUS && c instanceof JavafxClassSymbol) { List<Type> supertypes = ((JavafxClassSymbol)c).getSuperTypes(); for (Type tp : supertypes) { if (tp != null && tp.tag == CLASS) { sym = findField(env, site, name, tp.tsym); if (sym.kind < bestSoFar.kind) bestSoFar = sym; if (bestSoFar.kind < AMBIGUOUS) { break; } } } } for (List<Type> l = types.interfaces(c.type); bestSoFar.kind != AMBIGUOUS && l.nonEmpty(); l = l.tail) { sym = findField(env, site, name, l.head.tsym); if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS && sym.owner != bestSoFar.owner) bestSoFar = new AmbiguityError(bestSoFar, sym); else if (sym.kind < bestSoFar.kind) bestSoFar = sym; } return bestSoFar; } /** Resolve a field identifier, throw a fatal error if not found. * @param pos The position to use for error reporting. * @param env The environment current at the method invocation. * @param site The type of the qualifying expression, in which * identifier is searched. * @param name The identifier's name. */ public VarSymbol resolveInternalField(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env, Type site, Name name) { Symbol sym = findField(env, site, name, site.tsym); if (sym.kind == VAR) return (VarSymbol)sym; else throw new FatalError( JCDiagnostic.fragment(MsgSym.MESSAGE_FATAL_ERR_CANNOT_LOCATE_FIELD, name)); } /** Find unqualified variable or field with given name. * Synthetic fields always skipped. * @param env The current environment. * @param name The name of the variable or field. */ Symbol findVar(JavafxEnv<JavafxAttrContext> env, Name name, int kind, Type expected) { Symbol bestSoFar = varNotFound; Symbol sym; JavafxEnv<JavafxAttrContext> env1 = env; boolean staticOnly = false; boolean innerAccess = false; Type mtype = expected; if (mtype instanceof FunctionType) mtype = mtype.asMethodType(); boolean checkArgs = mtype instanceof MethodType || mtype instanceof ForAll; while (env1 != null) { Scope sc = env1.info.scope; Type envClass; if (env1.tree instanceof JFXClassDeclaration) { JFXClassDeclaration cdecl = (JFXClassDeclaration) env1.tree; if (cdecl.runMethod != null && name != names._this && name != names._super) { envClass = null; sc = cdecl.runBodyScope; innerAccess = true; } envClass = cdecl.sym.type; } else envClass = null; if (envClass != null) { sym = findMember(env1, envClass, name, expected, true, false, false); if (sym.exists()) { if (staticOnly) { // Note: can't call isStatic with null owner if (sym.owner != null) { if (!sym.isStatic()) { return new StaticError(sym); } } } return sym; } } if (sc != null) { for (Scope.Entry e = sc.lookup(name); e.scope != null; e = e.next()) { if ((e.sym.flags_field & SYNTHETIC) != 0) continue; if ((e.sym.kind & (MTH|VAR)) != 0) { if (innerAccess) { e.sym.flags_field |= JavafxFlags.VARUSE_INNER_ACCESS; } if (checkArgs) { return checkArgs(e.sym, mtype); } return e.sym; } } } if (env1.tree instanceof JFXFunctionDefinition) innerAccess = true; if (env1.outer != null && isStatic(env1)) staticOnly = true; env1 = env1.outer; } Scope.Entry e = env.toplevel.namedImportScope.lookup(name); for (; e.scope != null; e = e.next()) { sym = e.sym; Type origin = e.getOrigin().owner.type; if ((sym.kind & (MTH|VAR)) != 0) { if (e.sym.owner.type != origin) sym = sym.clone(e.getOrigin().owner); - return selectBest(env, origin, mtype, + if (sym.kind == VAR) + return isAccessible(env, origin, sym) + ? sym : new AccessError(env, origin, sym); + else //method + return selectBest(env, origin, mtype, e.sym, bestSoFar, true, false, false); } } Symbol origin = null; e = env.toplevel.starImportScope.lookup(name); for (; e.scope != null; e = e.next()) { sym = e.sym; if ((sym.kind & (MTH|VAR)) == 0) continue; // invariant: sym.kind == VAR if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner) return new AmbiguityError(bestSoFar, sym); else if (bestSoFar.kind >= VAR) { origin = e.getOrigin().owner; - bestSoFar = selectBest(env, origin.type, mtype, + if (sym.kind == VAR) + bestSoFar = isAccessible(env, origin.type, sym) + ? sym : new AccessError(env, origin.type, sym); + else //method + bestSoFar = selectBest(env, origin.type, mtype, e.sym, bestSoFar, true, false, false); } } if (name == names.fromString("__DIR__") || name == names.fromString("__FILE__") || name == names.fromString("__PROFILE__")) { Type type = syms.stringType; return new VarSymbol(Flags.PUBLIC, name, type, env.enclClass.sym); } if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type) return bestSoFar.clone(origin); else return bestSoFar; } //where private Symbol checkArgs(Symbol sym, Type mtype) { Type mt = sym.type; if (mt instanceof FunctionType) { mt = mt.asMethodType(); } // Better to use selectBest, but that requires some // changes. FIXME if (!(mt instanceof MethodType) || !argumentsAcceptable(mtype.getParameterTypes(), mt.getParameterTypes(), true, false, Warner.noWarnings)) { return wrongMethod.setWrongSym(sym); } return sym; } Warner noteWarner = new Warner(); /** Select the best method for a call site among two choices. * @param env The current environment. * @param site The original type from where the * selection takes place. * @param argtypes The invocation's value arguments, * @param typeargtypes The invocation's type arguments, * @param sym Proposed new best match. * @param bestSoFar Previously found best match. * @param allowBoxing Allow boxing conversions of arguments. * @param useVarargs Box trailing arguments into an array for varargs. */ Symbol selectBest(JavafxEnv<JavafxAttrContext> env, Type site, Type expected, Symbol sym, Symbol bestSoFar, boolean allowBoxing, boolean useVarargs, boolean operator) { if (sym.kind == ERR) return bestSoFar; if (!isInheritedIn(sym, site.tsym, types)) return bestSoFar; assert sym.kind < AMBIGUOUS; List<Type> argtypes = expected.getParameterTypes(); List<Type> typeargtypes = expected.getTypeArguments(); try { if (rawInstantiate(env, sym, types.memberType(site, sym), argtypes, typeargtypes, allowBoxing, useVarargs, Warner.noWarnings) == null) { // inapplicable switch (bestSoFar.kind) { case ABSENT_MTH: return wrongMethod.setWrongSym(sym); case WRONG_MTH: return wrongMethods; default: return bestSoFar; } } } catch (Infer.NoInstanceException ex) { switch (bestSoFar.kind) { case ABSENT_MTH: return wrongMethod.setWrongSym(sym, ex.getDiagnostic()); case WRONG_MTH: return wrongMethods; default: return bestSoFar; } } if (!isAccessible(env, site, sym)) { return (bestSoFar.kind == ABSENT_MTH) ? new AccessError(env, site, sym) : bestSoFar; } return (bestSoFar.kind > AMBIGUOUS) ? sym : mostSpecific(sym, bestSoFar, env, site, allowBoxing && operator, useVarargs); } /* Return the most specific of the two methods for a call, * given that both are accessible and applicable. * @param m1 A new candidate for most specific. * @param m2 The previous most specific candidate. * @param env The current environment. * @param site The original type from where the selection * takes place. * @param allowBoxing Allow boxing conversions of arguments. * @param useVarargs Box trailing arguments into an array for varargs. */ Symbol mostSpecific(Symbol m1, Symbol m2, JavafxEnv<JavafxAttrContext> env, Type site, boolean allowBoxing, boolean useVarargs) { switch (m2.kind) { case MTH: if (m1 == m2) return m1; Type mt1 = types.memberType(site, m1); noteWarner.unchecked = false; boolean m1SignatureMoreSpecific = (instantiate(env, site, m2, types.lowerBoundArgtypes(mt1), null, allowBoxing, false, noteWarner) != null || useVarargs && instantiate(env, site, m2, types.lowerBoundArgtypes(mt1), null, allowBoxing, true, noteWarner) != null) && !noteWarner.unchecked; Type mt2 = types.memberType(site, m2); noteWarner.unchecked = false; boolean m2SignatureMoreSpecific = (instantiate(env, site, m1, types.lowerBoundArgtypes(mt2), null, allowBoxing, false, noteWarner) != null || useVarargs && instantiate(env, site, m1, types.lowerBoundArgtypes(mt2), null, allowBoxing, true, noteWarner) != null) && !noteWarner.unchecked; if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) { if (!types.overrideEquivalent(mt1, mt2)) return new AmbiguityError(m1, m2); // same signature; select (a) the non-bridge method, or // (b) the one that overrides the other, or (c) the concrete // one, or (d) merge both abstract signatures if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE)) { return ((m1.flags() & BRIDGE) != 0) ? m2 : m1; } // if one overrides or hides the other, use it TypeSymbol m1Owner = (TypeSymbol)m1.owner; TypeSymbol m2Owner = (TypeSymbol)m2.owner; if (types.asSuper(m1Owner.type, m2Owner) != null && ((m1.owner.flags_field & INTERFACE) == 0 || (m2.owner.flags_field & INTERFACE) != 0) && m1.overrides(m2, m1Owner, types, false)) return m1; if (types.asSuper(m2Owner.type, m1Owner) != null && ((m2.owner.flags_field & INTERFACE) == 0 || (m1.owner.flags_field & INTERFACE) != 0) && m2.overrides(m1, m2Owner, types, false)) return m2; boolean m1Abstract = (m1.flags() & ABSTRACT) != 0; boolean m2Abstract = (m2.flags() & ABSTRACT) != 0; if (m1Abstract && !m2Abstract) return m2; if (m2Abstract && !m1Abstract) return m1; // both abstract or both concrete if (!m1Abstract && !m2Abstract) return new AmbiguityError(m1, m2); // check for same erasure if (!types.isSameType(m1.erasure(types), m2.erasure(types))) return new AmbiguityError(m1, m2); // both abstract, neither overridden; merge throws clause and result type Symbol result; Type result2 = mt2.getReturnType(); if (mt2.tag == FORALL) result2 = types.subst(result2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars); if (types.isSubtype(mt1.getReturnType(), result2)) { result = m1; } else if (types.isSubtype(result2, mt1.getReturnType())) { result = m2; } else { // Theoretically, this can't happen, but it is possible // due to error recovery or mixing incompatible class files return new AmbiguityError(m1, m2); } result = result.clone(result.owner); result.type = (Type)result.type.clone(); result.type.setThrown(chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes())); return result; } if (m1SignatureMoreSpecific) return m1; if (m2SignatureMoreSpecific) return m2; return new AmbiguityError(m1, m2); case AMBIGUOUS: AmbiguityError e = (AmbiguityError)m2; Symbol err1 = mostSpecific(m1, e.sym1, env, site, allowBoxing, useVarargs); Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs); if (err1 == err2) return err1; if (err1 == e.sym1 && err2 == e.sym2) return m2; if (err1 instanceof AmbiguityError && err2 instanceof AmbiguityError && ((AmbiguityError)err1).sym1 == ((AmbiguityError)err2).sym1) return new AmbiguityError(m1, m2); else return new AmbiguityError(err1, err2); default: throw new AssertionError(); } } /** Find best qualified method matching given name, type and value * arguments. * @param env The current environment. * @param site The original type from where the selection * takes place. * @param name The method's name. * @param argtypes The method's value arguments. * @param typeargtypes The method's type arguments * @param allowBoxing Allow boxing conversions of arguments. * @param useVarargs Box trailing arguments into an array for varargs. */ Symbol findMethod(JavafxEnv<JavafxAttrContext> env, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes, boolean allowBoxing, boolean useVarargs, boolean operator) { return findMember(env, site, name, newMethTemplate(argtypes, typeargtypes), site.tsym.type, methodNotFound, allowBoxing, useVarargs, operator); } Symbol findMember(JavafxEnv<JavafxAttrContext> env, Type site, Name name, Type expected, boolean allowBoxing, boolean useVarargs, boolean operator) { return findMember(env, site, name, expected, site.tsym.type, methodNotFound, allowBoxing, useVarargs, operator); } // where private Symbol findMember(JavafxEnv<JavafxAttrContext> env, Type site, Name name, Type expected, Type intype, Symbol bestSoFar, boolean allowBoxing, boolean useVarargs, boolean operator) { Symbol best = findMemberWithoutAccessChecks(env, site, name, expected, intype, bestSoFar, allowBoxing, useVarargs, operator); if (!(best instanceof ResolveError) && !isAccessible(env, site, best)) { // it is not accessible, return an error instead best = new AccessError(env, site, best); } return best; } // where private Symbol findMemberWithoutAccessChecks(JavafxEnv<JavafxAttrContext> env, Type site, Name name, Type expected, Type intype, Symbol bestSoFar, boolean allowBoxing, boolean useVarargs, boolean operator) { Type mtype = expected; if (mtype instanceof FunctionType) mtype = mtype.asMethodType(); boolean checkArgs = mtype instanceof MethodType || mtype instanceof ForAll; for (Type ct = intype; ct.tag == CLASS; ct = types.supertype(ct)) { ClassSymbol c = (ClassSymbol)ct.tsym; for (Scope.Entry e = c.members().lookup(name); e.scope != null; e = e.next()) { if ((e.sym.kind & (VAR|MTH)) == 0 || (e.sym.flags_field & SYNTHETIC) != 0) continue; e.sym.complete(); if (! checkArgs) { // No argument list to disambiguate. if (bestSoFar.kind == ABSENT_VAR || bestSoFar.kind == ABSENT_MTH) bestSoFar = e.sym; else if (e.sym != bestSoFar) bestSoFar = new AmbiguityError(bestSoFar, e.sym); } else if (e.sym.kind == MTH) { if (isExactMatch(mtype, e.sym)) return e.sym; bestSoFar = selectBest(env, site, mtype, e.sym, bestSoFar, allowBoxing, useVarargs, operator); } else if ((e.sym.kind & (VAR|MTH)) != 0 && bestSoFar == methodNotFound) { // FIXME duplicates logic in findVar. Type mt = e.sym.type; if (mt instanceof FunctionType) mt = mt.asMethodType(); if (! (mt instanceof MethodType) || ! argumentsAcceptable(mtype.getParameterTypes(), mt.getParameterTypes(), true, false, Warner.noWarnings)) return wrongMethod.setWrongSym(e.sym); return e.sym; } } if (! checkArgs && bestSoFar.kind != ABSENT_VAR && bestSoFar.kind != ABSENT_MTH) { return bestSoFar; } Symbol concrete = methodNotFound; if ((bestSoFar.flags() & ABSTRACT) == 0) concrete = bestSoFar; for (List<Type> l = types.interfaces(c.type); l.nonEmpty(); l = l.tail) { bestSoFar = findMemberWithoutAccessChecks(env, site, name, expected, l.head, bestSoFar, allowBoxing, useVarargs, operator); } if (concrete != bestSoFar && concrete.kind < ERR && bestSoFar.kind < ERR && types.isSubSignature(concrete.type, bestSoFar.type)) bestSoFar = concrete; if (name == names.init) return bestSoFar; } // We failed to find the field in the single Java class supertype of the // Javafx class. // Now try to find the filed in all of the Javafx supertypes. if (bestSoFar.kind > AMBIGUOUS && intype.tsym instanceof JavafxClassSymbol) { List<Type> supertypes = ((JavafxClassSymbol)intype.tsym).getSuperTypes(); for (Type tp : supertypes) { bestSoFar = findMemberWithoutAccessChecks(env, site, name, expected, tp, bestSoFar, allowBoxing, useVarargs, operator); if (bestSoFar.kind < AMBIGUOUS) { break; } } } return bestSoFar; } private boolean isExactMatch(Type mtype, Symbol bestSoFar) { if (bestSoFar.kind == MTH && (bestSoFar.type instanceof MethodType) && mtype.tag == TypeTags.METHOD ) { List<Type> actuals = ((MethodType)mtype).getParameterTypes(); List<Type> formals = ((MethodType)bestSoFar.type).getParameterTypes(); if (actuals != null && formals != null) { if (actuals.size() == formals.size()) { for (Type actual : actuals) { if (! types.isSameType(actual, formals.head)) { return false; } formals = formals.tail; } return true; } } } return false; } Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) { MethodType mt = new MethodType(argtypes, null, null, syms.methodClass); return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt); } /** Load toplevel or member class with given fully qualified name and * verify that it is accessible. * @param env The current environment. * @param name The fully qualified name of the class to be loaded. */ Symbol loadClass(JavafxEnv<JavafxAttrContext> env, Name name) { try { ClassSymbol c = reader.loadClass(name); return isAccessible(env, c) ? c : new AccessError(c); } catch (ClassReader.BadClassFile err) { throw err; } catch (CompletionFailure ex) { return typeNotFound; } } /** Find qualified member type. * @param env The current environment. * @param site The original type from where the selection takes * place. * @param name The type's name. * @param c The class to search for the member type. This is * always a superclass or implemented interface of * site's class. */ // Javafx change public // Javafx change Symbol findMemberType(JavafxEnv<JavafxAttrContext> env, Type site, Name name, TypeSymbol c) { Symbol bestSoFar = typeNotFound; Symbol sym; Scope.Entry e = c.members().lookup(name); while (e.scope != null) { if (e.sym.kind == TYP) { return isAccessible(env, site, e.sym) ? e.sym : new AccessError(env, site, e.sym); } e = e.next(); } Type st = types.supertype(c.type); if (st != null && st.tag == CLASS) { sym = findMemberType(env, site, name, st.tsym); if (sym.kind < bestSoFar.kind) bestSoFar = sym; } // We failed to find the field in the single Java class supertype of the // Javafx class. // Now try to find the filed in all of the Javafx supertypes. if (bestSoFar.kind > AMBIGUOUS && c instanceof JavafxClassSymbol) { List<Type> supertypes = ((JavafxClassSymbol)c).getSuperTypes(); for (Type tp : supertypes) { if (tp != null && tp.tag == CLASS) { sym = findField(env, site, name, tp.tsym); if (sym.kind < bestSoFar.kind) bestSoFar = sym; if (bestSoFar.kind < AMBIGUOUS) { break; } } } } for (List<Type> l = types.interfaces(c.type); bestSoFar.kind != AMBIGUOUS && l.nonEmpty(); l = l.tail) { sym = findMemberType(env, site, name, l.head.tsym); if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS && sym.owner != bestSoFar.owner) bestSoFar = new AmbiguityError(bestSoFar, sym); else if (sym.kind < bestSoFar.kind) bestSoFar = sym; } return bestSoFar; } /** Find a global type in given scope and load corresponding class. * @param env The current environment. * @param scope The scope in which to look for the type. * @param name The type's name. */ Symbol findGlobalType(JavafxEnv<JavafxAttrContext> env, Scope scope, Name name) { Symbol bestSoFar = typeNotFound; for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) { Symbol sym = loadClass(env, e.sym.flatName()); if (bestSoFar.kind == TYP && sym.kind == TYP && bestSoFar != sym) return new AmbiguityError(bestSoFar, sym); else if (sym.kind < bestSoFar.kind) bestSoFar = sym; } return bestSoFar; } Type findBuiltinType (Name typeName) { if (typeName == syms.booleanTypeName) return syms.javafx_BooleanType; if (typeName == syms.charTypeName) return syms.javafx_CharacterType; if (typeName == syms.byteTypeName) return syms.javafx_ByteType; if (typeName == syms.shortTypeName) return syms.javafx_ShortType; if (typeName == syms.integerTypeName) return syms.javafx_IntegerType; if (typeName == syms.longTypeName) return syms.javafx_LongType; if (typeName == syms.floatTypeName) return syms.javafx_FloatType; if (typeName == syms.doubleTypeName) return syms.javafx_DoubleType; if (typeName == syms.numberTypeName) return syms.javafx_NumberType; if (typeName == syms.stringTypeName) return syms.javafx_StringType; if (typeName == syms.voidTypeName) return syms.javafx_VoidType; return null; } /** Find an unqualified type symbol. * @param env The current environment. * @param name The type's name. */ Symbol findType(JavafxEnv<JavafxAttrContext> env, Name name) { Symbol bestSoFar = typeNotFound; Symbol sym; boolean staticOnly = false; for (JavafxEnv<JavafxAttrContext> env1 = env; env1.outer != null; env1 = env1.outer) { if (isStatic(env1)) staticOnly = true; for (Scope.Entry e = env1.info.scope.lookup(name); e.scope != null; e = e.next()) { if (e.sym.kind == TYP) { if (staticOnly && e.sym.type.tag == TYPEVAR && e.sym.owner.kind == TYP) return new StaticError(e.sym); return e.sym; } } sym = findMemberType(env1, env1.enclClass.sym.type, name, env1.enclClass.sym); if (staticOnly && sym.kind == TYP && sym.type.tag == CLASS && sym.type.getEnclosingType().tag == CLASS && env1.enclClass.sym.type.isParameterized() && sym.type.getEnclosingType().isParameterized()) return new StaticError(sym); else if (sym.exists()) return sym; else if (sym.kind < bestSoFar.kind) bestSoFar = sym; JFXClassDeclaration encl = env1.baseClause ? (JFXClassDeclaration)env1.tree : env1.enclClass; if ((encl.sym.flags() & STATIC) != 0) staticOnly = true; } if (env.tree.getFXTag() != JavafxTag.IMPORT) { sym = findGlobalType(env, env.toplevel.namedImportScope, name); if (sym.exists()) return sym; else if (sym.kind < bestSoFar.kind) bestSoFar = sym; } sym = findGlobalType(env, env.toplevel.packge.members(), name); if (sym.exists()) return sym; else if (sym.kind < bestSoFar.kind) bestSoFar = sym; Type type = findBuiltinType(name); if (type != null) return type.tsym; if (env.tree.getFXTag() != JavafxTag.IMPORT) { sym = findGlobalType(env, env.toplevel.starImportScope, name); if (sym.exists()) return sym; else if (sym.kind < bestSoFar.kind) bestSoFar = sym; } return bestSoFar; } /** Find an unqualified identifier which matches a specified kind set. * @param env The current environment. * @param name The indentifier's name. * @param kind Indicates the possible symbol kinds * (a subset of VAL, TYP, PCK). */ Symbol findIdent(JavafxEnv<JavafxAttrContext> env, Name name, int kind, Type expected) { Symbol bestSoFar = typeNotFound; Symbol sym; if ((kind & (VAR|MTH)) != 0) { sym = findVar(env, name, kind, expected); if (sym.exists()) return sym; else if (sym.kind < bestSoFar.kind) bestSoFar = sym; } if ((kind & TYP) != 0) { sym = findType(env, name); if (sym.exists()) return sym; else if (sym.kind < bestSoFar.kind) bestSoFar = sym; } if ((kind & PCK) != 0) return reader.enterPackage(name); else return bestSoFar; } /** Find an identifier in a package which matches a specified kind set. * @param env The current environment. * @param name The identifier's name. * @param kind Indicates the possible symbol kinds * (a nonempty subset of TYP, PCK). */ Symbol findIdentInPackage(JavafxEnv<JavafxAttrContext> env, TypeSymbol pck, Name name, int kind) { Name fullname = TypeSymbol.formFullName(name, pck); Symbol bestSoFar = typeNotFound; PackageSymbol pack = null; if ((kind & PCK) != 0) { pack = reader.enterPackage(fullname); if (pack.exists()) return pack; } if ((kind & TYP) != 0) { Symbol sym = loadClass(env, fullname); if (sym.exists()) { // don't allow programs to use flatnames if (name == sym.name) return sym; } else if (sym.kind < bestSoFar.kind) bestSoFar = sym; } return (pack != null) ? pack : bestSoFar; } /** Find an identifier among the members of a given type `site'. * @param env The current environment. * @param site The type containing the symbol to be found. * @param name The identifier's name. * @param kind Indicates the possible symbol kinds * (a subset of VAL, TYP). */ Symbol findIdentInType(JavafxEnv<JavafxAttrContext> env, Type site, Name name, int kind) { Symbol bestSoFar = typeNotFound; Symbol sym; if ((kind & (VAR|MTH)) != 0) { sym = findField(env, site, name, site.tsym); if (sym.exists()) return sym; else if (sym.kind < bestSoFar.kind) bestSoFar = sym; } if ((kind & TYP) != 0) { sym = findMemberType(env, site, name, site.tsym); if (sym.exists()) return sym; else if (sym.kind < bestSoFar.kind) bestSoFar = sym; } return bestSoFar; } /* *************************************************************************** * Access checking * The following methods convert ResolveErrors to ErrorSymbols, issuing * an error message in the process ****************************************************************************/ /** If `sym' is a bad symbol: report error and return errSymbol * else pass through unchanged, * additional arguments duplicate what has been used in trying to find the * symbol (--> flyweight pattern). This improves performance since we * expect misses to happen frequently. * * @param sym The symbol that was found, or a ResolveError. * @param pos The position to use for error reporting. * @param site The original type from where the selection took place. * @param name The symbol's name. * @param argtypes The invocation's value arguments, * if we looked for a method. * @param typeargtypes The invocation's type arguments, * if we looked for a method. */ Symbol access(Symbol sym, DiagnosticPosition pos, Type site, Name name, boolean qualified, List<Type> argtypes, List<Type> typeargtypes) { if (sym.kind >= AMBIGUOUS) { // printscopes(site.tsym.members());//DEBUG if (!site.isErroneous() && !Type.isErroneous(argtypes) && (typeargtypes==null || !Type.isErroneous(typeargtypes))) { ((ResolveError)sym).report(log, pos, site, name, argtypes, typeargtypes); } do { sym = ((ResolveError)sym).sym; } while (sym.kind >= AMBIGUOUS); if (sym == syms.errSymbol // preserve the symbol name through errors || ((sym.kind & ERRONEOUS) == 0 // make sure an error symbol is returned && (sym.kind & TYP) != 0)) sym = new ErrorType(name, qualified?site.tsym:syms.noSymbol).tsym; } return sym; } Symbol access(Symbol sym, DiagnosticPosition pos, Type site, Name name, boolean qualified, Type expected) { return access(sym, pos, site, name, qualified, expected.getParameterTypes(), expected.getTypeArguments()); } /** Same as above, but without type arguments and arguments. */ // Javafx change public // Javafx change Symbol access(Symbol sym, DiagnosticPosition pos, Type site, Name name, boolean qualified) { if (sym.kind >= AMBIGUOUS) return access(sym, pos, site, name, qualified, List.<Type>nil(), null); else return sym; } /** Check that sym is not an abstract method. */ void checkNonAbstract(DiagnosticPosition pos, Symbol sym) { if ((sym.flags() & ABSTRACT) != 0) log.error(pos, MsgSym.MESSAGE_ABSTRACT_CANNOT_BE_ACCESSED_DIRECTLY, kindName(sym), sym, sym.location()); } /* *************************************************************************** * Debugging ****************************************************************************/ /** print all scopes starting with scope s and proceeding outwards. * used for debugging. */ public void printscopes(Scope s) { while (s != null) { if (s.owner != null) System.err.print(s.owner + ": "); for (Scope.Entry e = s.elems; e != null; e = e.sibling) { if ((e.sym.flags() & ABSTRACT) != 0) System.err.print("abstract "); System.err.print(e.sym + " "); } System.err.println(); s = s.next; } } void printscopes(JavafxEnv<JavafxAttrContext> env) { while (env.outer != null) { System.err.println("------------------------------"); printscopes(env.info.scope); env = env.outer; } } public void printscopes(Type t) { while (t.tag == CLASS) { printscopes(t.tsym.members()); t = types.supertype(t); } } /* *************************************************************************** * Name resolution * Naming conventions are as for symbol lookup * Unlike the find... methods these methods will report access errors ****************************************************************************/ /** Resolve an unqualified (non-method) identifier. * @param pos The position to use for error reporting. * @param env The environment current at the identifier use. * @param name The identifier's name. * @param kind The set of admissible symbol kinds for the identifier. * @param pt The expected type. */ Symbol resolveIdent(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env, Name name, int kind, Type pt) { Symbol sym = findIdent(env, name, kind, pt); if (sym.kind >= AMBIGUOUS) return access(sym, pos, env.enclClass.sym.type, name, false, pt); else return sym; } /** Resolve a qualified method identifier * @param pos The position to use for error reporting. * @param env The environment current at the method invocation. * @param site The type of the qualifying expression, in which * identifier is searched. * @param name The identifier's name. * @param argtypes The types of the invocation's value arguments. * @param typeargtypes The types of the invocation's type arguments. */ Symbol resolveQualifiedMethod(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env, Type site, Name name, Type expected) { Symbol sym = findMember(env, site, name, expected, false, env.info.varArgs=false, false); if (varargsEnabled && sym.kind >= WRONG_MTHS) { sym = findMember(env, site, name, expected, true, false, false); if (sym.kind >= WRONG_MTHS) sym = findMember(env, site, name, expected, true, env.info.varArgs=true, false); } if (sym.kind >= AMBIGUOUS) { sym = access(sym, pos, site, name, true, expected); } return sym; } /** Resolve a qualified method identifier, throw a fatal error if not * found. * @param pos The position to use for error reporting. * @param env The environment current at the method invocation. * @param site The type of the qualifying expression, in which * identifier is searched. * @param name The identifier's name. * @param argtypes The types of the invocation's value arguments. * @param typeargtypes The types of the invocation's type arguments. */ public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) { Symbol sym = resolveQualifiedMethod( pos, env, site, name, newMethTemplate(argtypes, typeargtypes)); if (sym.kind == MTH) return (MethodSymbol)sym; else throw new FatalError( JCDiagnostic.fragment(MsgSym.MESSAGE_FATAL_ERR_CANNOT_LOCATE_METH, name)); } /** Resolve constructor. * @param pos The position to use for error reporting. * @param env The environment current at the constructor invocation. * @param site The type of class for which a constructor is searched. * @param argtypes The types of the constructor invocation's value * arguments. * @param typeargtypes The types of the constructor invocation's type * arguments. */ public // Javafx change Symbol resolveConstructor(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env, Type site, List<Type> argtypes, List<Type> typeargtypes) { Symbol sym = resolveConstructor(pos, env, site, argtypes, typeargtypes, false, env.info.varArgs=false); if (varargsEnabled && sym.kind >= WRONG_MTHS) { sym = resolveConstructor(pos, env, site, argtypes, typeargtypes, true, false); if (sym.kind >= WRONG_MTHS) sym = resolveConstructor(pos, env, site, argtypes, typeargtypes, true, env.info.varArgs=true); } if (sym.kind >= AMBIGUOUS) { sym = access(sym, pos, site, names.init, true, argtypes, typeargtypes); } return sym; } /** Resolve constructor. * @param pos The position to use for error reporting. * @param env The environment current at the constructor invocation. * @param site The type of class for which a constructor is searched. * @param argtypes The types of the constructor invocation's value * arguments. * @param typeargtypes The types of the constructor invocation's type * arguments. * @param allowBoxing Allow boxing and varargs conversions. * @param useVarargs Box trailing arguments into an array for varargs. */ public // Javafx change Symbol resolveConstructor(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env, Type site, List<Type> argtypes, List<Type> typeargtypes, boolean allowBoxing, boolean useVarargs) { Symbol sym = findMethod(env, site, names.init, argtypes, typeargtypes, allowBoxing, useVarargs, false); if ((sym.flags() & DEPRECATED) != 0 && (env.info.scope.owner.flags() & DEPRECATED) == 0 && env.info.scope.owner.outermostClass() != sym.outermostClass()) chk.warnDeprecated(pos, sym); return sym; } /** Resolve a constructor, throw a fatal error if not found. * @param pos The position to use for error reporting. * @param env The environment current at the method invocation. * @param site The type to be constructed. * @param argtypes The types of the invocation's value arguments. * @param typeargtypes The types of the invocation's type arguments. */ public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env, Type site, List<Type> argtypes, List<Type> typeargtypes) { Symbol sym = resolveConstructor( pos, env, site, argtypes, typeargtypes); if (sym.kind == MTH) return (MethodSymbol)sym; else throw new FatalError( JCDiagnostic.fragment(MsgSym.MESSAGE_FATAL_ERR_CANNOT_LOCATE_CTOR, site)); } /** Resolve operator. * @param pos The position to use for error reporting. * @param optag The tag of the operation tree. * @param env The environment current at the operation. * @param argtypes The types of the operands. */ Symbol resolveOperator(DiagnosticPosition pos, JavafxTag optag, JavafxEnv<JavafxAttrContext> env, List<Type> argtypes) { Name name = treeinfo.operatorName(optag); Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes, null, false, false, true); if (boxingEnabled && sym.kind >= WRONG_MTHS) sym = findMethod(env, syms.predefClass.type, name, argtypes, null, true, false, true); return access(sym, pos, env.enclClass.sym.type, name, false, argtypes, null); } /** Resolve operator. * @param pos The position to use for error reporting. * @param optag The tag of the operation tree. * @param env The environment current at the operation. * @param arg The type of the operand. */ Symbol resolveUnaryOperator(DiagnosticPosition pos, JavafxTag optag, JavafxEnv<JavafxAttrContext> env, Type arg) { // check for Duration unary minus if (types.isSameType(arg, ((JavafxSymtab)syms).javafx_DurationType)) { Symbol res = null; switch (optag) { case NEG: res = resolveMethod(pos, env, names.fromString("negate"), arg, List.<Type>nil()); break; } if (res != null && res.kind == MTH) { return res; } } return resolveOperator(pos, optag, env, List.of(arg)); } /** Resolve binary operator. * @param pos The position to use for error reporting. * @param optag The tag of the operation tree. * @param env The environment current at the operation. * @param left The types of the left operand. * @param right The types of the right operand. */ Symbol resolveBinaryOperator(DiagnosticPosition pos, JavafxTag optag, JavafxEnv<JavafxAttrContext> env, Type left, Type right) { // Duration operator overloading if (types.isSameType(left, ((JavafxSymtab)syms).javafx_DurationType) || types.isSameType(right, ((JavafxSymtab)syms).javafx_DurationType)) { Type dur = left; Symbol res = null; switch (optag) { case PLUS: res = resolveMethod(pos, env, names.fromString("add"), dur, List.of(right)); break; case MINUS: res = resolveMethod(pos, env, names.fromString("sub"), dur, List.of(right)); break; case MUL: if (!types.isSameType(left, ((JavafxSymtab)syms).javafx_DurationType)) { left = right; right = dur; dur = left; } res = resolveMethod(pos, env, names.fromString("mul"), dur, List.of(right)); break; case DIV: res = resolveMethod(pos, env, names.fromString("div"), dur, List.of(right)); break; //fix me...inline or move to static helper? case LT: res = resolveMethod(pos, env, names.fromString("lt"), dur, List.of(right)); break; case LE: res = resolveMethod(pos, env, names.fromString("le"), dur, List.of(right)); break; case GT: res = resolveMethod(pos, env, names.fromString("gt"), dur, List.of(right)); break; case GE: res = resolveMethod(pos, env, names.fromString("ge"), dur, List.of(right)); break; } if (res != null && res.kind == MTH) { return res; } // else fall through } return resolveOperator(pos, optag, env, List.of(left, right)); } Symbol resolveMethod(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env, Name name, Type type, List<Type> argtypes) { Symbol sym = findMethod(env, type, name, argtypes, null, true, false, false); if (sym.kind == MTH) { // skip access if method wasn't found return access(sym, pos, env.enclClass.sym.type, name, false, argtypes, null); } return sym; } /** * Resolve `c.name' where name == this or name == super. * @param pos The position to use for error reporting. * @param env The environment current at the expression. * @param c The qualifier. * @param name The identifier's name. */ public // Javafx change Symbol resolveSelf(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env, TypeSymbol c, Name name) { JavafxEnv<JavafxAttrContext> env1 = env; boolean staticOnly = false; while (env1.outer != null) { if (isStatic(env1)) staticOnly = true; if (env1.enclClass.sym == c) { Symbol sym = env1.info.scope.lookup(name).sym; if (sym != null) { if (staticOnly) sym = new StaticError(sym); return access(sym, pos, env.enclClass.sym.type, name, true); } } if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true; env1 = env1.outer; } log.error(pos, MsgSym.MESSAGE_NOT_ENCL_CLASS, c); return syms.errSymbol; } /** * Resolve `c.this' for an enclosing class c that contains the * named member. * @param pos The position to use for error reporting. * @param env The environment current at the expression. * @param member The member that must be contained in the result. */ Symbol resolveSelfContaining(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env, Symbol member) { Name name = names._this; JavafxEnv<JavafxAttrContext> env1 = env; boolean staticOnly = false; while (env1.outer != null) { if (isStatic(env1)) staticOnly = true; if (env1.enclClass.sym.isSubClass(member.owner, types) && isAccessible(env, env1.enclClass.sym.type, member)) { Symbol sym = env1.info.scope.lookup(name).sym; if (sym != null) { if (staticOnly) sym = new StaticError(sym); return access(sym, pos, env.enclClass.sym.type, name, true); } } if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true; env1 = env1.outer; } log.error(pos, MsgSym.MESSAGE_ENCL_CLASS_REQUIRED, member); return syms.errSymbol; } /** * Resolve an appropriate implicit this instance for t's container. * JLS2 8.8.5.1 and 15.9.2 */ public // Javafx change Type resolveImplicitThis(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env, Type t) { Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0) ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this) : resolveSelfContaining(pos, env, t.tsym)).type; if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym) log.error(pos, MsgSym.MESSAGE_CANNOT_REF_BEFORE_CTOR_CALLED, "this"); return thisType; } /* *************************************************************************** * Methods related to kinds ****************************************************************************/ /** A localized string describing a given kind. */ public // Javafx change static JCDiagnostic kindName(int kind) { switch (kind) { case PCK: return JCDiagnostic.fragment(MsgSym.KINDNAME_PACKAGE); case TYP: return JCDiagnostic.fragment(MsgSym.KINDNAME_CLASS); case VAR: return JCDiagnostic.fragment(MsgSym.KINDNAME_VARIABLE); case VAL: return JCDiagnostic.fragment(MsgSym.KINDNAME_VALUE); case MTH: return JCDiagnostic.fragment(MsgSym.KINDNAME_METHOD); default : return JCDiagnostic.fragment(MsgSym.KINDNAME, Integer.toString(kind)); //debug } } static JCDiagnostic kindName(Symbol sym) { switch (sym.getKind()) { case PACKAGE: return JCDiagnostic.fragment(MsgSym.KINDNAME_PACKAGE); case ENUM: case ANNOTATION_TYPE: case INTERFACE: case CLASS: return JCDiagnostic.fragment(MsgSym.KINDNAME_CLASS); case TYPE_PARAMETER: return JCDiagnostic.fragment(MsgSym.KINDNAME_TYPE_VARIABLE); case ENUM_CONSTANT: case FIELD: case PARAMETER: case LOCAL_VARIABLE: case EXCEPTION_PARAMETER: return JCDiagnostic.fragment(MsgSym.KINDNAME_VARIABLE); case METHOD: case CONSTRUCTOR: case STATIC_INIT: case INSTANCE_INIT: return JCDiagnostic.fragment(MsgSym.KINDNAME_METHOD); default: if (sym.kind == VAL) // I don't think this can happen but it can't harm // playing it safe --ahe return JCDiagnostic.fragment(MsgSym.KINDNAME_VALUE); else return JCDiagnostic.fragment(MsgSym.KINDNAME, sym.getKind()); // debug } } /** A localized string describing a given set of kinds. */ public // Javafx change static JCDiagnostic kindNames(int kind) { StringBuffer key = new StringBuffer(); key.append(MsgSym.KINDNAME); if ((kind & VAL) != 0) key.append(((kind & VAL) == VAR) ? MsgSym.KINDNAME_KEY_VARIABLE : MsgSym.KINDNAME_KEY_VALUE); if ((kind & MTH) != 0) key.append(MsgSym.KINDNAME_KEY_METHOD); if ((kind & TYP) != 0) key.append(MsgSym.KINDNAME_KEY_CLASS); if ((kind & PCK) != 0) key.append(MsgSym.KINDNAME_KEY_PACKAGE); return JCDiagnostic.fragment(key.toString(), kind); } /** A localized string describing the kind -- either class or interface -- * of a given type. */ static JCDiagnostic typeKindName(Type t) { if (t.tag == TYPEVAR || t.tag == CLASS && (t.tsym.flags() & COMPOUND) != 0) return JCDiagnostic.fragment(MsgSym.KINDNAME_TYPE_VARIABLE_BOUND); else if (t.tag == PACKAGE) return JCDiagnostic.fragment(MsgSym.KINDNAME_PACKAGE); else if ((t.tsym.flags_field & ANNOTATION) != 0) return JCDiagnostic.fragment(MsgSym.KINDNAME_ANNOTATION); else if ((t.tsym.flags_field & INTERFACE) != 0) return JCDiagnostic.fragment(MsgSym.KINDNAME_INTERFACE); else return JCDiagnostic.fragment(MsgSym.KINDNAME_CLASS); } /** A localized string describing the kind of a missing symbol, given an * error kind. */ static JCDiagnostic absentKindName(int kind) { switch (kind) { case ABSENT_VAR: return JCDiagnostic.fragment(MsgSym.KINDNAME_VARIABLE); case WRONG_MTHS: case WRONG_MTH: case ABSENT_MTH: return JCDiagnostic.fragment(MsgSym.KINDNAME_METHOD); case ABSENT_TYP: return JCDiagnostic.fragment(MsgSym.KINDNAME_CLASS); default: return JCDiagnostic.fragment(MsgSym.KINDNAME, kind); } } /* *************************************************************************** * ResolveError classes, indicating error situations when accessing symbols ****************************************************************************/ public void logAccessError(JavafxEnv<JavafxAttrContext> env, JCTree tree, Type type) { AccessError error = new AccessError(env, type.getEnclosingType(), type.tsym); error.report(log, tree.pos(), type.getEnclosingType(), null, null, null); } /** Root class for resolve errors. * Instances of this class indicate "Symbol not found". * Instances of subclass indicate other errors. */ private class ResolveError extends Symbol { ResolveError(int kind, Symbol sym, String debugName) { super(kind, 0, null, null, null); this.debugName = debugName; this.sym = sym; } /** The name of the kind of error, for debugging only. */ final String debugName; /** The symbol that was determined by resolution, or errSymbol if none * was found. */ final Symbol sym; /** The symbol that was a close mismatch, or null if none was found. * wrongSym is currently set if a simgle method with the correct name, but * the wrong parameters was found. */ Symbol wrongSym; /** An auxiliary explanation set in case of instantiation errors. */ JCDiagnostic explanation; public <R, P> R accept(ElementVisitor<R, P> v, P p) { throw new AssertionError(); } /** Print the (debug only) name of the kind of error. */ @Override public String toString() { return debugName + " wrongSym=" + wrongSym + " explanation=" + explanation; } /** Update wrongSym and explanation and return this. */ ResolveError setWrongSym(Symbol sym, JCDiagnostic explanation) { this.wrongSym = sym; this.explanation = explanation; return this; } /** Update wrongSym and return this. */ ResolveError setWrongSym(Symbol sym) { this.wrongSym = sym; this.explanation = null; return this; } @Override public boolean exists() { switch (kind) { case HIDDEN: case ABSENT_VAR: case ABSENT_MTH: case ABSENT_TYP: return false; default: return true; } } /** Report error. * @param log The error log to be used for error reporting. * @param pos The position to be used for error reporting. * @param site The original type from where the selection took place. * @param name The name of the symbol to be resolved. * @param argtypes The invocation's value arguments, * if we looked for a method. * @param typeargtypes The invocation's type arguments, * if we looked for a method. */ void report(Log log, DiagnosticPosition pos, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) { if (name != name.table.error) { JCDiagnostic kindname = absentKindName(kind); String idname = name.toString(); String args = ""; String typeargs = ""; if (kind >= WRONG_MTHS && kind <= ABSENT_MTH) { if (isOperator(name)) { log.error(pos, MsgSym.MESSAGE_OPERATOR_CANNOT_BE_APPLIED, name, Type.toString(argtypes)); return; } if (name == name.table.init) { kindname = JCDiagnostic.fragment(MsgSym.KINDNAME_CONSTRUCTOR); idname = site.tsym.name.toString(); } args = "(" + Type.toString(argtypes) + ")"; if (typeargtypes != null && typeargtypes.nonEmpty()) typeargs = "<" + Type.toString(typeargtypes) + ">"; } if (kind == WRONG_MTH) { String wrongSymStr; if (wrongSym instanceof MethodSymbol) wrongSymStr = types.toJavaFXString((MethodSymbol) wrongSym.asMemberOf(site, types), ((MethodSymbol) wrongSym).params); else wrongSymStr = wrongSym.toString(); log.error(pos, MsgSym.MESSAGE_CANNOT_APPLY_SYMBOL + (explanation != null ? ".1" : ""), wrongSymStr, types.location(wrongSym, site), typeargs, types.toJavaFXString(argtypes), explanation); } else if (site.tsym.name.len != 0) { if (site.tsym.kind == PCK && !site.tsym.exists()) log.error(pos, MsgSym.MESSAGE_DOES_NOT_EXIST, site.tsym); else log.error(pos, MsgSym.MESSAGE_CANNOT_RESOLVE_LOCATION, kindname, idname, args, typeargs, typeKindName(site), site); } else { log.error(pos, MsgSym.MESSAGE_CANNOT_RESOLVE, kindname, idname, args, typeargs); } } } //where /** A name designates an operator if it consists * of a non-empty sequence of operator symbols +-~!/*%&|^<>= */ boolean isOperator(Name name) { int i = 0; while (i < name.len && "+-~!*/%&|^<>=".indexOf(name.byteAt(i)) >= 0) i++; return i > 0 && i == name.len; } } /** Resolve error class indicating that a symbol is not accessible. */ class AccessError extends ResolveError { AccessError(Symbol sym) { this(null, null, sym); } AccessError(JavafxEnv<JavafxAttrContext> env, Type site, Symbol sym) { super(HIDDEN, sym, "access error"); this.env = env; this.site = site; if (debugResolve) log.error(MsgSym.MESSAGE_PROC_MESSAGER, sym + " @ " + site + " is inaccessible."); } private JavafxEnv<JavafxAttrContext> env; private Type site; /** Report error. * @param log The error log to be used for error reporting. * @param pos The position to be used for error reporting. * @param site The original type from where the selection took place. * @param name The name of the symbol to be resolved. * @param argtypes The invocation's value arguments, * if we looked for a method. * @param typeargtypes The invocation's type arguments, * if we looked for a method. */ @Override void report(Log log, DiagnosticPosition pos, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) { if (sym.owner.type.tag != ERROR) { if (sym.name == sym.name.table.init && sym.owner != site.tsym) new ResolveError(ABSENT_MTH, sym.owner, "absent method " + sym).report( log, pos, site, name, argtypes, typeargtypes); if ((sym.flags() & PUBLIC) != 0 || (env != null && this.site != null && !isAccessible(env, this.site))) log.error(pos, MsgSym.MESSAGE_NOT_DEF_ACCESS_CLASS_INTF_CANNOT_ACCESS, sym, sym.location()); else if ((sym.flags() & JavafxFlags.JavafxAccessFlags) == 0L) // 'package' access log.error(pos, MsgSym.MESSAGE_NOT_DEF_PUBLIC_CANNOT_ACCESS, sym, sym.location()); else log.error(pos, MsgSym.MESSAGE_REPORT_ACCESS, sym, JavafxCheck.protectionString(sym.flags()), sym.location()); } } } /** Resolve error class indicating that an instance member was accessed * from a static context. */ class StaticError extends ResolveError { StaticError(Symbol sym) { super(STATICERR, sym, "static error"); } /** Report error. * @param log The error log to be used for error reporting. * @param pos The position to be used for error reporting. * @param site The original type from where the selection took place. * @param name The name of the symbol to be resolved. * @param argtypes The invocation's value arguments, * if we looked for a method. * @param typeargtypes The invocation's type arguments, * if we looked for a method. */ @Override void report(Log log, DiagnosticPosition pos, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) { String symstr = ((sym.kind == TYP && sym.type.tag == CLASS) ? types.erasure(sym.type) : sym).toString(); log.error(pos, MsgSym.MESSAGE_NON_STATIC_CANNOT_BE_REF, kindName(sym), symstr); } } /** Resolve error class indicating an ambiguous reference. */ class AmbiguityError extends ResolveError { Symbol sym1; Symbol sym2; AmbiguityError(Symbol sym1, Symbol sym2) { super(AMBIGUOUS, sym1, "ambiguity error"); this.sym1 = sym1; this.sym2 = sym2; } /** Report error. * @param log The error log to be used for error reporting. * @param pos The position to be used for error reporting. * @param site The original type from where the selection took place. * @param name The name of the symbol to be resolved. * @param argtypes The invocation's value arguments, * if we looked for a method. * @param typeargtypes The invocation's type arguments, * if we looked for a method. */ @Override void report(Log log, DiagnosticPosition pos, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) { AmbiguityError pair = this; while (true) { if (pair.sym1.kind == AMBIGUOUS) pair = (AmbiguityError)pair.sym1; else if (pair.sym2.kind == AMBIGUOUS) pair = (AmbiguityError)pair.sym2; else break; } Name sname = pair.sym1.name; if (sname == sname.table.init) sname = pair.sym1.owner.name; log.error(pos, MsgSym.MESSAGE_REF_AMBIGUOUS, sname, kindName(pair.sym1), pair.sym1, types.location(pair.sym1, site), kindName(pair.sym2), pair.sym2, types.location(pair.sym2, site)); } } /** * @param sym The symbol. * @param clazz The type symbol of which the tested symbol is regarded * as a member. * * From the javac code from which this was cloned -- * * Is this symbol inherited into a given class? * PRE: If symbol's owner is a interface, * it is already assumed that the interface is a superinterface * of given class. * @param clazz The class for which we want to establish membership. * This must be a subclass of the member's owner. */ public boolean isInheritedIn(Symbol sym, Symbol clazz, JavafxTypes types) { // because the SCRIPT_PRIVATE bit is too high for the switch, test it later switch ((short)(sym.flags_field & Flags.AccessFlags)) { default: // error recovery case PUBLIC: return true; case PRIVATE: return sym.owner == clazz; case PROTECTED: // we model interfaces as extending Object return (clazz.flags() & INTERFACE) == 0; case 0: if ((sym.flags() & JavafxFlags.SCRIPT_PRIVATE) != 0) { // script-private //TODO: this isn't right //return sym.owner == clazz; }; // 'package' access boolean foundInherited = false; for (Type supType : types.supertypes(clazz, clazz.type)) { if (supType.tsym == sym.owner) { foundInherited = true; break; } else if (supType.isErroneous()) { return true; // Error recovery } else if (supType.tsym != null && (supType.tsym.flags() & COMPOUND) != 0) { continue; } } return foundInherited && (clazz.flags() & INTERFACE) == 0; } } }
false
true
Symbol findVar(JavafxEnv<JavafxAttrContext> env, Name name, int kind, Type expected) { Symbol bestSoFar = varNotFound; Symbol sym; JavafxEnv<JavafxAttrContext> env1 = env; boolean staticOnly = false; boolean innerAccess = false; Type mtype = expected; if (mtype instanceof FunctionType) mtype = mtype.asMethodType(); boolean checkArgs = mtype instanceof MethodType || mtype instanceof ForAll; while (env1 != null) { Scope sc = env1.info.scope; Type envClass; if (env1.tree instanceof JFXClassDeclaration) { JFXClassDeclaration cdecl = (JFXClassDeclaration) env1.tree; if (cdecl.runMethod != null && name != names._this && name != names._super) { envClass = null; sc = cdecl.runBodyScope; innerAccess = true; } envClass = cdecl.sym.type; } else envClass = null; if (envClass != null) { sym = findMember(env1, envClass, name, expected, true, false, false); if (sym.exists()) { if (staticOnly) { // Note: can't call isStatic with null owner if (sym.owner != null) { if (!sym.isStatic()) { return new StaticError(sym); } } } return sym; } } if (sc != null) { for (Scope.Entry e = sc.lookup(name); e.scope != null; e = e.next()) { if ((e.sym.flags_field & SYNTHETIC) != 0) continue; if ((e.sym.kind & (MTH|VAR)) != 0) { if (innerAccess) { e.sym.flags_field |= JavafxFlags.VARUSE_INNER_ACCESS; } if (checkArgs) { return checkArgs(e.sym, mtype); } return e.sym; } } } if (env1.tree instanceof JFXFunctionDefinition) innerAccess = true; if (env1.outer != null && isStatic(env1)) staticOnly = true; env1 = env1.outer; } Scope.Entry e = env.toplevel.namedImportScope.lookup(name); for (; e.scope != null; e = e.next()) { sym = e.sym; Type origin = e.getOrigin().owner.type; if ((sym.kind & (MTH|VAR)) != 0) { if (e.sym.owner.type != origin) sym = sym.clone(e.getOrigin().owner); return selectBest(env, origin, mtype, e.sym, bestSoFar, true, false, false); } } Symbol origin = null; e = env.toplevel.starImportScope.lookup(name); for (; e.scope != null; e = e.next()) { sym = e.sym; if ((sym.kind & (MTH|VAR)) == 0) continue; // invariant: sym.kind == VAR if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner) return new AmbiguityError(bestSoFar, sym); else if (bestSoFar.kind >= VAR) { origin = e.getOrigin().owner; bestSoFar = selectBest(env, origin.type, mtype, e.sym, bestSoFar, true, false, false); } } if (name == names.fromString("__DIR__") || name == names.fromString("__FILE__") || name == names.fromString("__PROFILE__")) { Type type = syms.stringType; return new VarSymbol(Flags.PUBLIC, name, type, env.enclClass.sym); } if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type) return bestSoFar.clone(origin); else return bestSoFar; }
Symbol findVar(JavafxEnv<JavafxAttrContext> env, Name name, int kind, Type expected) { Symbol bestSoFar = varNotFound; Symbol sym; JavafxEnv<JavafxAttrContext> env1 = env; boolean staticOnly = false; boolean innerAccess = false; Type mtype = expected; if (mtype instanceof FunctionType) mtype = mtype.asMethodType(); boolean checkArgs = mtype instanceof MethodType || mtype instanceof ForAll; while (env1 != null) { Scope sc = env1.info.scope; Type envClass; if (env1.tree instanceof JFXClassDeclaration) { JFXClassDeclaration cdecl = (JFXClassDeclaration) env1.tree; if (cdecl.runMethod != null && name != names._this && name != names._super) { envClass = null; sc = cdecl.runBodyScope; innerAccess = true; } envClass = cdecl.sym.type; } else envClass = null; if (envClass != null) { sym = findMember(env1, envClass, name, expected, true, false, false); if (sym.exists()) { if (staticOnly) { // Note: can't call isStatic with null owner if (sym.owner != null) { if (!sym.isStatic()) { return new StaticError(sym); } } } return sym; } } if (sc != null) { for (Scope.Entry e = sc.lookup(name); e.scope != null; e = e.next()) { if ((e.sym.flags_field & SYNTHETIC) != 0) continue; if ((e.sym.kind & (MTH|VAR)) != 0) { if (innerAccess) { e.sym.flags_field |= JavafxFlags.VARUSE_INNER_ACCESS; } if (checkArgs) { return checkArgs(e.sym, mtype); } return e.sym; } } } if (env1.tree instanceof JFXFunctionDefinition) innerAccess = true; if (env1.outer != null && isStatic(env1)) staticOnly = true; env1 = env1.outer; } Scope.Entry e = env.toplevel.namedImportScope.lookup(name); for (; e.scope != null; e = e.next()) { sym = e.sym; Type origin = e.getOrigin().owner.type; if ((sym.kind & (MTH|VAR)) != 0) { if (e.sym.owner.type != origin) sym = sym.clone(e.getOrigin().owner); if (sym.kind == VAR) return isAccessible(env, origin, sym) ? sym : new AccessError(env, origin, sym); else //method return selectBest(env, origin, mtype, e.sym, bestSoFar, true, false, false); } } Symbol origin = null; e = env.toplevel.starImportScope.lookup(name); for (; e.scope != null; e = e.next()) { sym = e.sym; if ((sym.kind & (MTH|VAR)) == 0) continue; // invariant: sym.kind == VAR if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner) return new AmbiguityError(bestSoFar, sym); else if (bestSoFar.kind >= VAR) { origin = e.getOrigin().owner; if (sym.kind == VAR) bestSoFar = isAccessible(env, origin.type, sym) ? sym : new AccessError(env, origin.type, sym); else //method bestSoFar = selectBest(env, origin.type, mtype, e.sym, bestSoFar, true, false, false); } } if (name == names.fromString("__DIR__") || name == names.fromString("__FILE__") || name == names.fromString("__PROFILE__")) { Type type = syms.stringType; return new VarSymbol(Flags.PUBLIC, name, type, env.enclClass.sym); } if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type) return bestSoFar.clone(origin); else return bestSoFar; }
diff --git a/MELT/src/melt/Model/Student.java b/MELT/src/melt/Model/Student.java index 8b84567..3c14037 100644 --- a/MELT/src/melt/Model/Student.java +++ b/MELT/src/melt/Model/Student.java @@ -1,205 +1,206 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package melt.Model; import java.util.ArrayList; import javax.xml.bind.annotation.XmlElement; /** * * @author panos */ public class Student { private String name; private int id; @XmlElement(name="SelectedTest") private Test selectedTest; private String testName; private double mcqMark; private double fibqMark; private double essayMark; public double getMcqMark() { return mcqMark; } public double getFibqMark() { return fibqMark; } @XmlElement(name="FibqMarks") public void setFibqMark(double fibqMark) { this.fibqMark = fibqMark; } public double getEssayMark() { return essayMark; } @XmlElement(name="EssayMarks") public void setEssayMark(double essayMark) { this.essayMark = essayMark; } @XmlElement(name="McqMarks") public void setMcqMark(double studentMark) { this.mcqMark = studentMark; } public Student(String name,int id,Test studentSelectionTest){ this.name = name; this.id = id; mcqMark = 0; fibqMark = 0; essayMark = 0; this.createSelectedTest(studentSelectionTest); } public Student(){ } public String getName() { return name; } @XmlElement public void setName(String name) { this.name = name; } public int getId() { return id; } @XmlElement public void setId(int id) { this.id = id; } public Test getSelectedTest() { return selectedTest; } private void createSelectedTest(Test test) { this.selectedTest = new Test(); this.selectedTest.setCreator(test.getCreator()); this.selectedTest.setId(test.getId()); + this.selectedTest.setName(test.getName()); this.selectedTest.setInstructions(test.getInstructions()); //copy sections of the test to the student test along with their details for(Section currentSection : test.getSections()){ Section newSection = new Section(); newSection.setId(currentSection.getId()); newSection.setName(currentSection.getName()); newSection.setTime(currentSection.getTime()); newSection.setInstructions(currentSection.getInstructions()); this.selectedTest.addSection(newSection); for(Subsection currentSubsection : currentSection.getSubsections()){ Subsection newSubsection = new Subsection(); newSubsection.setId(currentSubsection.getId()); newSubsection.setName(currentSubsection.getName()); newSubsection.setType(currentSubsection.getType()); for(Question currentQuestion : currentSubsection.getQuestions()){ switch(newSubsection.getType()){ case "Mcq": Mcq currentMcq = (Mcq) currentQuestion; ArrayList<String> mcqanswers = currentMcq.getAnswers(); ArrayList<Integer> correctAnswers = currentMcq.getCorrectAnswers(); String mcqQuestionText = currentMcq.getQuestionText(); Mcq newMcqQuestion = new Mcq(); newMcqQuestion.setQuestionText(mcqQuestionText); newMcqQuestion.setAnswers(mcqanswers); newMcqQuestion.setCorrectAnswers(correctAnswers); newMcqQuestion.setId(currentMcq.getId()); newMcqQuestion.setMark(currentMcq.getMark()); newSubsection.addQuestion(currentQuestion); newSection.addSubsection(newSubsection); break; case "Fibq": Fibq currentFibq = (Fibq) currentQuestion; ArrayList<FibqBlankAnswers> fibqanswers = currentFibq.getCorrectAnswers(); String fibqQuestionText = currentFibq.getQuestionText(); Fibq newFibqQuestion = new Fibq(); newFibqQuestion.setQuestionText(fibqQuestionText); newFibqQuestion.setCorrectAnswers(fibqanswers); newFibqQuestion.setId(currentFibq.getId()); newFibqQuestion.setMark(currentFibq.getMark()); newFibqQuestion.setAutoMarked(currentFibq.isAutoMarked()); newSubsection.addQuestion(newFibqQuestion); newSection.addSubsection(newSubsection); break; case "Essay": Essay currentEssay = (Essay) currentQuestion; String essayText = currentEssay.getQuestionText(); int wordLimit = currentEssay.getWordLimit(); double mark = currentEssay.getMark(); int numOfLines = currentEssay.getNoOfLines(); Essay newEssay = new Essay(currentEssay.getId(), essayText, mark,numOfLines ); newEssay.setWordLimit(wordLimit); newSubsection.addQuestion(newEssay); newSection.addSubsection(newSubsection); break; } } } } this.testName = selectedTest.getName(); } public void markMcqQuestions(){ for(Section section : selectedTest.getSections()){ for(Subsection subsection : section.getSubsections()){ if(subsection.getType().equals("Mcq")){ for(Question question : subsection.getQuestions()){ if(question.checkAnswer()){ this.mcqMark+=question.getMark(); } } } } } } public void markFibqQuestions(){ for(Section section : selectedTest.getSections()){ for(Subsection subsection : section.getSubsections()){ if(subsection.getType().equals("Fibq")){ for(Question question : subsection.getQuestions()){ Fibq currentFibq = (Fibq) question; if(currentFibq.isAutoMarked()){ currentFibq.checkAnswer(); this.fibqMark+=currentFibq.getMark(); } } } } } } public void setAnswersForQuestion(String answer,Section section,Subsection subsection,Question question){ } public void setAnswersForQuestion(ArrayList<Integer> answers,Section section,Subsection subsection,Question question){ } public void setAnswerForQuestion(ArrayList<String> answers,Section section,Subsection subsection,Question question){ } @Override public String toString(){ return this.name; } }
true
true
private void createSelectedTest(Test test) { this.selectedTest = new Test(); this.selectedTest.setCreator(test.getCreator()); this.selectedTest.setId(test.getId()); this.selectedTest.setInstructions(test.getInstructions()); //copy sections of the test to the student test along with their details for(Section currentSection : test.getSections()){ Section newSection = new Section(); newSection.setId(currentSection.getId()); newSection.setName(currentSection.getName()); newSection.setTime(currentSection.getTime()); newSection.setInstructions(currentSection.getInstructions()); this.selectedTest.addSection(newSection); for(Subsection currentSubsection : currentSection.getSubsections()){ Subsection newSubsection = new Subsection(); newSubsection.setId(currentSubsection.getId()); newSubsection.setName(currentSubsection.getName()); newSubsection.setType(currentSubsection.getType()); for(Question currentQuestion : currentSubsection.getQuestions()){ switch(newSubsection.getType()){ case "Mcq": Mcq currentMcq = (Mcq) currentQuestion; ArrayList<String> mcqanswers = currentMcq.getAnswers(); ArrayList<Integer> correctAnswers = currentMcq.getCorrectAnswers(); String mcqQuestionText = currentMcq.getQuestionText(); Mcq newMcqQuestion = new Mcq(); newMcqQuestion.setQuestionText(mcqQuestionText); newMcqQuestion.setAnswers(mcqanswers); newMcqQuestion.setCorrectAnswers(correctAnswers); newMcqQuestion.setId(currentMcq.getId()); newMcqQuestion.setMark(currentMcq.getMark()); newSubsection.addQuestion(currentQuestion); newSection.addSubsection(newSubsection); break; case "Fibq": Fibq currentFibq = (Fibq) currentQuestion; ArrayList<FibqBlankAnswers> fibqanswers = currentFibq.getCorrectAnswers(); String fibqQuestionText = currentFibq.getQuestionText(); Fibq newFibqQuestion = new Fibq(); newFibqQuestion.setQuestionText(fibqQuestionText); newFibqQuestion.setCorrectAnswers(fibqanswers); newFibqQuestion.setId(currentFibq.getId()); newFibqQuestion.setMark(currentFibq.getMark()); newFibqQuestion.setAutoMarked(currentFibq.isAutoMarked()); newSubsection.addQuestion(newFibqQuestion); newSection.addSubsection(newSubsection); break; case "Essay": Essay currentEssay = (Essay) currentQuestion; String essayText = currentEssay.getQuestionText(); int wordLimit = currentEssay.getWordLimit(); double mark = currentEssay.getMark(); int numOfLines = currentEssay.getNoOfLines(); Essay newEssay = new Essay(currentEssay.getId(), essayText, mark,numOfLines ); newEssay.setWordLimit(wordLimit); newSubsection.addQuestion(newEssay); newSection.addSubsection(newSubsection); break; } } } } this.testName = selectedTest.getName(); }
private void createSelectedTest(Test test) { this.selectedTest = new Test(); this.selectedTest.setCreator(test.getCreator()); this.selectedTest.setId(test.getId()); this.selectedTest.setName(test.getName()); this.selectedTest.setInstructions(test.getInstructions()); //copy sections of the test to the student test along with their details for(Section currentSection : test.getSections()){ Section newSection = new Section(); newSection.setId(currentSection.getId()); newSection.setName(currentSection.getName()); newSection.setTime(currentSection.getTime()); newSection.setInstructions(currentSection.getInstructions()); this.selectedTest.addSection(newSection); for(Subsection currentSubsection : currentSection.getSubsections()){ Subsection newSubsection = new Subsection(); newSubsection.setId(currentSubsection.getId()); newSubsection.setName(currentSubsection.getName()); newSubsection.setType(currentSubsection.getType()); for(Question currentQuestion : currentSubsection.getQuestions()){ switch(newSubsection.getType()){ case "Mcq": Mcq currentMcq = (Mcq) currentQuestion; ArrayList<String> mcqanswers = currentMcq.getAnswers(); ArrayList<Integer> correctAnswers = currentMcq.getCorrectAnswers(); String mcqQuestionText = currentMcq.getQuestionText(); Mcq newMcqQuestion = new Mcq(); newMcqQuestion.setQuestionText(mcqQuestionText); newMcqQuestion.setAnswers(mcqanswers); newMcqQuestion.setCorrectAnswers(correctAnswers); newMcqQuestion.setId(currentMcq.getId()); newMcqQuestion.setMark(currentMcq.getMark()); newSubsection.addQuestion(currentQuestion); newSection.addSubsection(newSubsection); break; case "Fibq": Fibq currentFibq = (Fibq) currentQuestion; ArrayList<FibqBlankAnswers> fibqanswers = currentFibq.getCorrectAnswers(); String fibqQuestionText = currentFibq.getQuestionText(); Fibq newFibqQuestion = new Fibq(); newFibqQuestion.setQuestionText(fibqQuestionText); newFibqQuestion.setCorrectAnswers(fibqanswers); newFibqQuestion.setId(currentFibq.getId()); newFibqQuestion.setMark(currentFibq.getMark()); newFibqQuestion.setAutoMarked(currentFibq.isAutoMarked()); newSubsection.addQuestion(newFibqQuestion); newSection.addSubsection(newSubsection); break; case "Essay": Essay currentEssay = (Essay) currentQuestion; String essayText = currentEssay.getQuestionText(); int wordLimit = currentEssay.getWordLimit(); double mark = currentEssay.getMark(); int numOfLines = currentEssay.getNoOfLines(); Essay newEssay = new Essay(currentEssay.getId(), essayText, mark,numOfLines ); newEssay.setWordLimit(wordLimit); newSubsection.addQuestion(newEssay); newSection.addSubsection(newSubsection); break; } } } } this.testName = selectedTest.getName(); }
diff --git a/server/src/main/java/org/benjp/utils/PropertyManager.java b/server/src/main/java/org/benjp/utils/PropertyManager.java index bac09bcc..726def38 100644 --- a/server/src/main/java/org/benjp/utils/PropertyManager.java +++ b/server/src/main/java/org/benjp/utils/PropertyManager.java @@ -1,88 +1,88 @@ /* * Copyright (C) 2012 eXo Platform SAS. * * 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.benjp.utils; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; public class PropertyManager { private static Properties properties; private static final String PROPERTIES_PATH = System.getProperty("catalina.base")+"/conf/chat.properties"; public static final String PROPERTY_SERVER_HOST = "dbServerHost"; public static final String PROPERTY_SERVER_PORT = "dbServerPort"; public static final String PROPERTY_DB_NAME = "dbName"; public static final String PROPERTY_DB_AUTHENTICATION = "dbAuthentication"; public static final String PROPERTY_DB_USER = "dbUser"; public static final String PROPERTY_DB_PASSWORD = "dbPassword"; public static final String PROPERTY_CHAT_SERVER_URL = "chatServerUrl"; public static final String PROPERTY_CHAT_PORTAL_PAGE = "chatPortalPage"; public static final String PROPERTY_INTERVAL_CHAT = "chatIntervalChat"; public static final String PROPERTY_INTERVAL_SESSION = "chatIntervalSession"; public static final String PROPERTY_INTERVAL_STATUS = "chatIntervalStatus"; public static final String PROPERTY_INTERVAL_NOTIF = "chatIntervalNotif"; public static final String PROPERTY_INTERVAL_USERS = "chatIntervalUsers"; public static final String PROPERTY_PASSPHRASE = "chatPassPhrase"; public static final String PROPERTY_CRON_NOTIF_CLEANUP = "chatCronNotifCleanup"; public static String getProperty(String key) { String value = (String)properties().get(key); System.out.println("PROP:"+key+"="+value); return value; } private static Properties properties() { if (properties==null) { properties = new Properties(); InputStream stream = null; try { stream = new FileInputStream(PROPERTIES_PATH); properties.load(stream); stream.close(); } catch (Exception e) { properties.setProperty(PROPERTY_SERVER_HOST, "localhost"); properties.setProperty(PROPERTY_SERVER_PORT, "27017"); properties.setProperty(PROPERTY_DB_NAME, "chat"); properties.setProperty(PROPERTY_DB_AUTHENTICATION, "false"); properties.setProperty(PROPERTY_DB_USER, ""); properties.setProperty(PROPERTY_DB_PASSWORD, ""); properties.setProperty(PROPERTY_CHAT_SERVER_URL, "/chatServer"); properties.setProperty(PROPERTY_CHAT_PORTAL_PAGE, "/portal/intranet/chat"); properties.setProperty(PROPERTY_INTERVAL_CHAT, "3000"); properties.setProperty(PROPERTY_INTERVAL_SESSION, "60000"); properties.setProperty(PROPERTY_INTERVAL_STATUS, "15000"); properties.setProperty(PROPERTY_INTERVAL_NOTIF, "3000"); properties.setProperty(PROPERTY_INTERVAL_USERS, "5000"); properties.setProperty(PROPERTY_PASSPHRASE, "chat"); - properties.setProperty(PROPERTY_CRON_NOTIF_CLEANUP, "* 10 * * * ?"); + properties.setProperty(PROPERTY_CRON_NOTIF_CLEANUP, "0 0/60 * * * ?"); } } return properties; } }
true
true
private static Properties properties() { if (properties==null) { properties = new Properties(); InputStream stream = null; try { stream = new FileInputStream(PROPERTIES_PATH); properties.load(stream); stream.close(); } catch (Exception e) { properties.setProperty(PROPERTY_SERVER_HOST, "localhost"); properties.setProperty(PROPERTY_SERVER_PORT, "27017"); properties.setProperty(PROPERTY_DB_NAME, "chat"); properties.setProperty(PROPERTY_DB_AUTHENTICATION, "false"); properties.setProperty(PROPERTY_DB_USER, ""); properties.setProperty(PROPERTY_DB_PASSWORD, ""); properties.setProperty(PROPERTY_CHAT_SERVER_URL, "/chatServer"); properties.setProperty(PROPERTY_CHAT_PORTAL_PAGE, "/portal/intranet/chat"); properties.setProperty(PROPERTY_INTERVAL_CHAT, "3000"); properties.setProperty(PROPERTY_INTERVAL_SESSION, "60000"); properties.setProperty(PROPERTY_INTERVAL_STATUS, "15000"); properties.setProperty(PROPERTY_INTERVAL_NOTIF, "3000"); properties.setProperty(PROPERTY_INTERVAL_USERS, "5000"); properties.setProperty(PROPERTY_PASSPHRASE, "chat"); properties.setProperty(PROPERTY_CRON_NOTIF_CLEANUP, "* 10 * * * ?"); } } return properties; }
private static Properties properties() { if (properties==null) { properties = new Properties(); InputStream stream = null; try { stream = new FileInputStream(PROPERTIES_PATH); properties.load(stream); stream.close(); } catch (Exception e) { properties.setProperty(PROPERTY_SERVER_HOST, "localhost"); properties.setProperty(PROPERTY_SERVER_PORT, "27017"); properties.setProperty(PROPERTY_DB_NAME, "chat"); properties.setProperty(PROPERTY_DB_AUTHENTICATION, "false"); properties.setProperty(PROPERTY_DB_USER, ""); properties.setProperty(PROPERTY_DB_PASSWORD, ""); properties.setProperty(PROPERTY_CHAT_SERVER_URL, "/chatServer"); properties.setProperty(PROPERTY_CHAT_PORTAL_PAGE, "/portal/intranet/chat"); properties.setProperty(PROPERTY_INTERVAL_CHAT, "3000"); properties.setProperty(PROPERTY_INTERVAL_SESSION, "60000"); properties.setProperty(PROPERTY_INTERVAL_STATUS, "15000"); properties.setProperty(PROPERTY_INTERVAL_NOTIF, "3000"); properties.setProperty(PROPERTY_INTERVAL_USERS, "5000"); properties.setProperty(PROPERTY_PASSPHRASE, "chat"); properties.setProperty(PROPERTY_CRON_NOTIF_CLEANUP, "0 0/60 * * * ?"); } } return properties; }
diff --git a/test-project/src/main/java/Main.java b/test-project/src/main/java/Main.java index be95d05..fa3b74e 100644 --- a/test-project/src/main/java/Main.java +++ b/test-project/src/main/java/Main.java @@ -1,62 +1,61 @@ import org.hyperic.sigar.NetFlags; import org.hyperic.sigar.NetInterfaceConfig; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import java.io.*; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * @author Timophey.Kulishov * @version $Rev$ <br/> * $Author$ <br/> * $Date$ */ public class Main { public static void main(String[] args) throws SigarException, UnknownHostException { // try (FileOutputStream fileOutputStream = new FileOutputStream("d:\\workfolder\\TestCar.obj"); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) { // Car car = new Car(1, Color.BLACK, "BMV"); // objectOutputStream.writeObject(car); // } catch (IOException e) { // e.printStackTrace(); // } // try (FileInputStream fileInputStream = new FileInputStream("d:\\workfolder\\TestCar.obj"); // ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) { // Car car = (Car) objectInputStream.readObject(); // System.out.println(car.getModel()); // } catch (IOException e) { // e.printStackTrace(); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } // Super ssuper = new Super(); //// System.out.println(Color.values()[1]); // int i = 10; // Set<Object> set = new HashSet<>(); // set.add(i); // assert true; // System.out.println("hi"); -// Set<? extends RuntimeException> set = new HashSet<RuntimeException>(); -// Car car = new Car(2, Color.BLACK, "BMW"); -// car = null; -// System.gc(); + Set<? extends RuntimeException> set = new HashSet<RuntimeException>(); + Car car = new Car(2, Color.BLACK, "BMW"); + car = null; + System.gc(); // while (Car.getCarCount() > 0) { // // } - System.out.println(InetAddress.getLocalHost().getHostAddress()); } }
false
true
public static void main(String[] args) throws SigarException, UnknownHostException { // try (FileOutputStream fileOutputStream = new FileOutputStream("d:\\workfolder\\TestCar.obj"); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) { // Car car = new Car(1, Color.BLACK, "BMV"); // objectOutputStream.writeObject(car); // } catch (IOException e) { // e.printStackTrace(); // } // try (FileInputStream fileInputStream = new FileInputStream("d:\\workfolder\\TestCar.obj"); // ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) { // Car car = (Car) objectInputStream.readObject(); // System.out.println(car.getModel()); // } catch (IOException e) { // e.printStackTrace(); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } // Super ssuper = new Super(); //// System.out.println(Color.values()[1]); // int i = 10; // Set<Object> set = new HashSet<>(); // set.add(i); // assert true; // System.out.println("hi"); // Set<? extends RuntimeException> set = new HashSet<RuntimeException>(); // Car car = new Car(2, Color.BLACK, "BMW"); // car = null; // System.gc(); // while (Car.getCarCount() > 0) { // // } System.out.println(InetAddress.getLocalHost().getHostAddress()); }
public static void main(String[] args) throws SigarException, UnknownHostException { // try (FileOutputStream fileOutputStream = new FileOutputStream("d:\\workfolder\\TestCar.obj"); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) { // Car car = new Car(1, Color.BLACK, "BMV"); // objectOutputStream.writeObject(car); // } catch (IOException e) { // e.printStackTrace(); // } // try (FileInputStream fileInputStream = new FileInputStream("d:\\workfolder\\TestCar.obj"); // ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) { // Car car = (Car) objectInputStream.readObject(); // System.out.println(car.getModel()); // } catch (IOException e) { // e.printStackTrace(); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } // Super ssuper = new Super(); //// System.out.println(Color.values()[1]); // int i = 10; // Set<Object> set = new HashSet<>(); // set.add(i); // assert true; // System.out.println("hi"); Set<? extends RuntimeException> set = new HashSet<RuntimeException>(); Car car = new Car(2, Color.BLACK, "BMW"); car = null; System.gc(); // while (Car.getCarCount() > 0) { // // } }
diff --git a/src/main/java/hs/mediasystem/enrich/EnrichCache.java b/src/main/java/hs/mediasystem/enrich/EnrichCache.java index c6f04dab..55a8a199 100644 --- a/src/main/java/hs/mediasystem/enrich/EnrichCache.java +++ b/src/main/java/hs/mediasystem/enrich/EnrichCache.java @@ -1,515 +1,515 @@ package hs.mediasystem.enrich; import hs.mediasystem.util.OrderedExecutionQueue; import hs.mediasystem.util.OrderedExecutionQueueExecutor; import hs.mediasystem.util.TaskExecutor; import hs.mediasystem.util.TaskThreadPoolExecutor; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.concurrent.Task; import javafx.concurrent.Worker.State; import javax.inject.Inject; import javax.inject.Singleton; @Singleton public class EnrichCache { private final Comparator<CacheKey> taskPriorityComparator = new Comparator<CacheKey>() { @Override public int compare(CacheKey o1, CacheKey o2) { if(o1.getPriority() > o2.getPriority()) { return -1; } else if(o1.getPriority() < o2.getPriority()) { return 1; } return 0; } }; private final Map<Class<?>, Enricher<?>> ENRICHERS = new HashMap<>(); private final Map<CacheKey, Map<Class<?>, CacheValue>> cache = new WeakHashMap<>(); private final Map<CacheKey, Set<EnrichmentListener>> enrichmentListeners = new WeakHashMap<>(); private final Map<CacheKey, Set<PendingEnrichment<?>>> pendingEnrichmentMap = new WeakHashMap<>(); private final OrderedExecutionQueue<CacheKey> cacheQueue = new OrderedExecutionQueueExecutor<>(taskPriorityComparator, new TaskThreadPoolExecutor(new ThreadPoolExecutor(5, 5, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()))); private final OrderedExecutionQueue<CacheKey> normalQueue; public <T> void registerEnricher(Class<T> cls, Enricher<T> enricher) { ENRICHERS.put(cls, enricher); } @Inject public EnrichCache(TaskExecutor normalExecutor) { this.normalQueue = new OrderedExecutionQueueExecutor<>(taskPriorityComparator, normalExecutor); } public void addListener(CacheKey key, EnrichmentListener listener) { synchronized(cache) { Set<EnrichmentListener> listeners = enrichmentListeners.get(key); if(listeners == null) { listeners = new HashSet<>(); enrichmentListeners.put(key, listeners); } listeners.add(listener); Map<Class<?>, CacheValue> cacheValues = cache.get(key); if(cacheValues != null) { for(Map.Entry<Class<?>, CacheValue> entry : cacheValues.entrySet()) { listener.update(entry.getValue().state, entry.getKey(), entry.getValue().enrichable); } } } } public void removeListener(CacheKey key, EnrichmentListener listener) { synchronized(cache) { Set<EnrichmentListener> listeners = enrichmentListeners.get(key); if(listeners != null) { listeners.remove(listener); } } } public CacheValue getCacheValue(CacheKey key, Class<?> enrichableClass) { synchronized(cache) { Map<Class<?>, CacheValue> cacheValues = cache.get(key); if(cacheValues == null) { return null; } return cacheValues.get(enrichableClass); } } public CacheValue getDescendantCacheValue(CacheKey key, Class<?> enrichableClass) { synchronized(cache) { Map<Class<?>, CacheValue> cacheValues = cache.get(key); if(cacheValues == null) { return null; } for(Class<?> cls : cacheValues.keySet()) { if(enrichableClass.isAssignableFrom(cls)) { return cacheValues.get(cls); } } return null; } } public <T> void enrich(CacheKey key, Class<T> enrichableClass) { enrich(key, enrichableClass, false); } private <T> void enrich(CacheKey key, Class<T> enrichableClass, boolean bypassCache) { synchronized(cache) { @SuppressWarnings("unchecked") Enricher<T> enricher = (Enricher<T>)ENRICHERS.get(enrichableClass); if(enricher == null) { System.out.println("No suitable Enricher for " + enrichableClass); insertFailedEnrichment(key, enrichableClass); } else { PendingEnrichment<T> pendingEnrichment = new PendingEnrichment<>(enricher, enrichableClass, bypassCache); /* * First check if this Enrichment is not already pending. Although the system has no problem handling * multiple the same Pending Enrichments (as after the first one is being processed the others only * result in a promotion) it can be wasteful to have many of these queued up. */ Set<PendingEnrichment<?>> pendingEnrichments = pendingEnrichmentMap.get(key); if(pendingEnrichments != null && pendingEnrichments.contains(pendingEnrichment)) { /* * The Pending Enrichment already exists, promote the associated key (requeueing any tasks that might * use it) and then discard it. */ List<Task<?>> cacheTasks = cacheQueue.removeAll(key); List<Task<?>> normalTasks = normalQueue.removeAll(key); key.promote(); if(cacheTasks != null) { cacheQueue.submitAll(key, cacheTasks); } if(normalTasks != null) { normalQueue.submitAll(key, cacheTasks); } return; } /* * If this unique Enrichment fails immediately, we donot bother adding it to the PENDING_ENRICHMENTS map. */ pendingEnrichment.enrichIfConditionsMet(key); if(pendingEnrichment.getState() == PendingEnrichmentState.BROKEN_DEPENDENCY) { insertFailedEnrichment(key, pendingEnrichment.getEnrichableClass()); } else { pendingEnrichments = pendingEnrichmentMap.get(key); // get Set again as it can be non-null now after calling enrichIfConditionsMet above if(pendingEnrichments == null) { pendingEnrichments = new HashSet<>(); pendingEnrichmentMap.put(key, pendingEnrichments); } pendingEnrichments.add(pendingEnrichment); } } } } public void reload(CacheKey key) { synchronized(cache) { /* * Remove any queued tasks and any pending enrichments associated with this key, * cancel any pending enrichments to prevent them from adding old results to the * cache and gather a list of classes there were in the cache and were being * loaded. */ cacheQueue.removeAll(key); normalQueue.removeAll(key); Set<Class<?>> classesToReload = new HashSet<>(); Set<PendingEnrichment<?>> pendingEnrichments = pendingEnrichmentMap.remove(key); if(pendingEnrichments != null) { for(PendingEnrichment<?> pendingEnrichment : pendingEnrichments) { pendingEnrichment.cancel(); classesToReload.add(pendingEnrichment.enrichableClass); } } Map<Class<?>, CacheValue> cacheValues = cache.get(key); if(cacheValues != null) { for(Iterator<Entry<Class<?>, CacheValue>> iterator = cacheValues.entrySet().iterator(); iterator.hasNext();) { Map.Entry<Class<?>, CacheValue> entry = iterator.next(); if(entry.getValue().state != EnrichmentState.IMMUTABLE) { classesToReload.add(entry.getKey()); iterator.remove(); } } } /* * Re-enrich the classes we found, bypassing the cache */ for(Class<?> classToReload : classesToReload) { enrich(key, classToReload, true); } } } private void insertFailedEnrichment(CacheKey key, Class<?> enrichableClass) { insertInternal(key, EnrichmentState.FAILED, enrichableClass, null, false); } @SuppressWarnings("unchecked") public <E> void insertImmutableDataIfNotExists(CacheKey key, E enrichable) { if(enrichable == null) { throw new IllegalArgumentException("parameter 'enrichable' cannot be null"); } insertInternal(key, EnrichmentState.IMMUTABLE, (Class<E>)enrichable.getClass(), enrichable, true); } @SuppressWarnings("unchecked") public <E> void insert(CacheKey key, E enrichable) { if(enrichable == null) { throw new IllegalArgumentException("parameter 'enrichable' cannot be null"); } insertInternal(key, EnrichmentState.ENRICHED, (Class<E>)enrichable.getClass(), enrichable, false); } @SuppressWarnings("unchecked") public <E> void insertImmutable(CacheKey key, E enrichable) { if(enrichable == null) { throw new IllegalArgumentException("parameter 'enrichable' cannot be null"); } insertInternal(key, EnrichmentState.IMMUTABLE, (Class<E>)enrichable.getClass(), enrichable, false); } private <E> void insertInternal(CacheKey key, EnrichmentState state, Class<E> enrichableClass, E enrichable, boolean onlyIfNotExists) { synchronized(cache) { Map<Class<?>, CacheValue> cacheValues = cache.get(key); if(cacheValues == null) { cacheValues = new HashMap<>(); cache.put(key, cacheValues); } if(onlyIfNotExists && cacheValues.containsKey(enrichableClass)) { return; } cacheValues.put(enrichableClass, new CacheValue(state, enrichable)); Set<EnrichmentListener> listeners = enrichmentListeners.get(key); if(listeners != null) { for(EnrichmentListener listener : new HashSet<>(listeners)) { listener.update(state, enrichableClass, enrichable); } } /* * Notify any waiting PendingEnrichments of the newly inserted data */ Set<PendingEnrichment<?>> pendingEnrichments = pendingEnrichmentMap.get(key); if(pendingEnrichments != null) { for(PendingEnrichment<?> pendingEnrichment : new HashSet<>(pendingEnrichments)) { if(pendingEnrichment.getState() == PendingEnrichmentState.WAITING_FOR_DEPENDENCY) { pendingEnrichment.enrichIfConditionsMet(key); if(pendingEnrichment.getState() == PendingEnrichmentState.BROKEN_DEPENDENCY) { insertFailedEnrichment(key, pendingEnrichment.getEnrichableClass()); pendingEnrichments.remove(pendingEnrichment); if(pendingEnrichments.isEmpty()) { pendingEnrichmentMap.remove(key); } } } } } } } public <E> E getFromCache(CacheKey key, Class<E> enrichableClass) { synchronized(cache) { CacheValue cacheValue = getCacheValue(key, enrichableClass); @SuppressWarnings("unchecked") E e = (E)(cacheValue == null ? null : cacheValue.enrichable); return e; } } public static class CacheValue { private final EnrichmentState state; private final Object enrichable; public CacheValue(EnrichmentState state, Object enrichable) { this.state = state; this.enrichable = enrichable; } } private enum PendingEnrichmentState {NOT_INITIALIZED, WAITING_FOR_DEPENDENCY, BROKEN_DEPENDENCY, IN_PROGRESS} private class PendingEnrichment<T> { private final Enricher<T> enricher; private final Class<T> enrichableClass; private final boolean bypassCache; private PendingEnrichmentState state = PendingEnrichmentState.NOT_INITIALIZED; private volatile boolean cancelled; public PendingEnrichment(Enricher<T> enricher, Class<T> enrichableClass, boolean bypassCache) { assert enricher != null; assert enrichableClass != null; this.enricher = enricher; this.enrichableClass = enrichableClass; this.bypassCache = bypassCache; } public void cancel() { cancelled = true; } public PendingEnrichmentState getState() { return state; } /** * Returns <code>true</code> if this PendingEnrich was handled, otherwise <code>false</code> * * @param key a key * @return <code>true</code> if this PendingEnrich was handled, otherwise <code>false</code> */ public void enrichIfConditionsMet(final CacheKey key) { synchronized(cache) { if(state == PendingEnrichmentState.IN_PROGRESS || state == PendingEnrichmentState.BROKEN_DEPENDENCY) { throw new IllegalStateException("" + state); } if(cancelled) { return; } Map<Class<?>, Object> inputParameters = null; for(Class<?> parameterType : enricher.getInputTypes()) { CacheValue cacheValue = getDescendantCacheValue(key, parameterType); if(cacheValue == null) { state = PendingEnrichmentState.WAITING_FOR_DEPENDENCY; - enrich(key, parameterType); + enrich(key, parameterType, bypassCache); return; } if(cacheValue.state == EnrichmentState.FAILED) { state = PendingEnrichmentState.BROKEN_DEPENDENCY; return; } if(inputParameters == null) { inputParameters = new HashMap<>(); } inputParameters.put(parameterType, cacheValue.enrichable); } state = PendingEnrichmentState.IN_PROGRESS; final Parameters finalInputParameters = new Parameters(inputParameters); Platform.runLater(new Runnable() { @Override public void run() { synchronized(cache) { if(cancelled) { return; } List<EnrichTask<T>> enrichTasks = enricher.enrich(finalInputParameters, bypassCache); for(int i = 0; i < enrichTasks.size(); i++) { final EnrichTask<T> enrichTask = enrichTasks.get(i); final EnrichTask<T> nextEnrichTask = (i < enrichTasks.size() - 1) ? enrichTasks.get(i + 1) : null; enrichTask.stateProperty().addListener(new ChangeListener<State>() { @Override public void changed(ObservableValue<? extends State> observable, State oldState, State state) { synchronized(cache) { if(!cancelled && (state == State.FAILED || state == State.CANCELLED || state == State.SUCCEEDED)) { T taskResult = enrichTask.getValue(); System.out.println("[" + (state == State.FAILED ? "WARN" : "FINE") + "] EnrichCache [" + enricher.getClass().getSimpleName() + "->" + enrichableClass.getSimpleName() + "]: " + state + ": " + key + ": " + enrichTask.getTitle() + " -> " + taskResult); if(state == State.FAILED) { System.out.println("[WARN] EnrichCache [" + enricher.getClass().getSimpleName() + "->" + enrichableClass.getSimpleName() + "]: " + state + ": " + key + ": " + enrichTask.getTitle() + ": " + enrichTask.getException()); enrichTask.getException().printStackTrace(System.out); insertFailedEnrichment(key, enrichableClass); } if(state == State.SUCCEEDED) { if(taskResult != null || nextEnrichTask == null) { if(taskResult != null) { insert(key, taskResult); } else { insertFailedEnrichment(key, enrichableClass); } Set<PendingEnrichment<?>> set = pendingEnrichmentMap.get(key); set.remove(PendingEnrichment.this); if(set.isEmpty()) { pendingEnrichmentMap.remove(key); } } else { System.out.println("[FINE] EnrichCache [" + enricher.getClass().getSimpleName() + "->" + enrichableClass.getSimpleName() + "]: ENRICH_NEXT: " + key + ": " + nextEnrichTask.getTitle()); if(nextEnrichTask.isFast()) { cacheQueue.submit(key, nextEnrichTask); } else { normalQueue.submit(key, nextEnrichTask); } } } cacheQueue.submitPending(); normalQueue.submitPending(); } } } }); } EnrichTask<T> firstTask = enrichTasks.get(0); System.out.println("[FINE] EnrichCache [" + enricher.getClass().getSimpleName() + "->" + enrichableClass.getSimpleName() + "]: ENRICH: " + key + ": " + firstTask.getTitle()); if(firstTask.isFast()) { cacheQueue.submit(key, firstTask); } else { normalQueue.submit(key, firstTask); } } } }); } } public Class<?> getEnrichableClass() { return enrichableClass; } @Override public int hashCode() { return enricher.hashCode(); } @Override public boolean equals(Object obj) { if(this == obj) { return true; } if(obj == null || getClass() != obj.getClass()) { return false; } PendingEnrichment<?> other = (PendingEnrichment<?>)obj; return enricher.equals(other.enricher); } } }
true
true
public void enrichIfConditionsMet(final CacheKey key) { synchronized(cache) { if(state == PendingEnrichmentState.IN_PROGRESS || state == PendingEnrichmentState.BROKEN_DEPENDENCY) { throw new IllegalStateException("" + state); } if(cancelled) { return; } Map<Class<?>, Object> inputParameters = null; for(Class<?> parameterType : enricher.getInputTypes()) { CacheValue cacheValue = getDescendantCacheValue(key, parameterType); if(cacheValue == null) { state = PendingEnrichmentState.WAITING_FOR_DEPENDENCY; enrich(key, parameterType); return; } if(cacheValue.state == EnrichmentState.FAILED) { state = PendingEnrichmentState.BROKEN_DEPENDENCY; return; } if(inputParameters == null) { inputParameters = new HashMap<>(); } inputParameters.put(parameterType, cacheValue.enrichable); } state = PendingEnrichmentState.IN_PROGRESS; final Parameters finalInputParameters = new Parameters(inputParameters); Platform.runLater(new Runnable() { @Override public void run() { synchronized(cache) { if(cancelled) { return; } List<EnrichTask<T>> enrichTasks = enricher.enrich(finalInputParameters, bypassCache); for(int i = 0; i < enrichTasks.size(); i++) { final EnrichTask<T> enrichTask = enrichTasks.get(i); final EnrichTask<T> nextEnrichTask = (i < enrichTasks.size() - 1) ? enrichTasks.get(i + 1) : null; enrichTask.stateProperty().addListener(new ChangeListener<State>() { @Override public void changed(ObservableValue<? extends State> observable, State oldState, State state) { synchronized(cache) { if(!cancelled && (state == State.FAILED || state == State.CANCELLED || state == State.SUCCEEDED)) { T taskResult = enrichTask.getValue(); System.out.println("[" + (state == State.FAILED ? "WARN" : "FINE") + "] EnrichCache [" + enricher.getClass().getSimpleName() + "->" + enrichableClass.getSimpleName() + "]: " + state + ": " + key + ": " + enrichTask.getTitle() + " -> " + taskResult); if(state == State.FAILED) { System.out.println("[WARN] EnrichCache [" + enricher.getClass().getSimpleName() + "->" + enrichableClass.getSimpleName() + "]: " + state + ": " + key + ": " + enrichTask.getTitle() + ": " + enrichTask.getException()); enrichTask.getException().printStackTrace(System.out); insertFailedEnrichment(key, enrichableClass); } if(state == State.SUCCEEDED) { if(taskResult != null || nextEnrichTask == null) { if(taskResult != null) { insert(key, taskResult); } else { insertFailedEnrichment(key, enrichableClass); } Set<PendingEnrichment<?>> set = pendingEnrichmentMap.get(key); set.remove(PendingEnrichment.this); if(set.isEmpty()) { pendingEnrichmentMap.remove(key); } } else { System.out.println("[FINE] EnrichCache [" + enricher.getClass().getSimpleName() + "->" + enrichableClass.getSimpleName() + "]: ENRICH_NEXT: " + key + ": " + nextEnrichTask.getTitle()); if(nextEnrichTask.isFast()) { cacheQueue.submit(key, nextEnrichTask); } else { normalQueue.submit(key, nextEnrichTask); } } } cacheQueue.submitPending(); normalQueue.submitPending(); } } } }); } EnrichTask<T> firstTask = enrichTasks.get(0); System.out.println("[FINE] EnrichCache [" + enricher.getClass().getSimpleName() + "->" + enrichableClass.getSimpleName() + "]: ENRICH: " + key + ": " + firstTask.getTitle()); if(firstTask.isFast()) { cacheQueue.submit(key, firstTask); } else { normalQueue.submit(key, firstTask); } } } }); } }
public void enrichIfConditionsMet(final CacheKey key) { synchronized(cache) { if(state == PendingEnrichmentState.IN_PROGRESS || state == PendingEnrichmentState.BROKEN_DEPENDENCY) { throw new IllegalStateException("" + state); } if(cancelled) { return; } Map<Class<?>, Object> inputParameters = null; for(Class<?> parameterType : enricher.getInputTypes()) { CacheValue cacheValue = getDescendantCacheValue(key, parameterType); if(cacheValue == null) { state = PendingEnrichmentState.WAITING_FOR_DEPENDENCY; enrich(key, parameterType, bypassCache); return; } if(cacheValue.state == EnrichmentState.FAILED) { state = PendingEnrichmentState.BROKEN_DEPENDENCY; return; } if(inputParameters == null) { inputParameters = new HashMap<>(); } inputParameters.put(parameterType, cacheValue.enrichable); } state = PendingEnrichmentState.IN_PROGRESS; final Parameters finalInputParameters = new Parameters(inputParameters); Platform.runLater(new Runnable() { @Override public void run() { synchronized(cache) { if(cancelled) { return; } List<EnrichTask<T>> enrichTasks = enricher.enrich(finalInputParameters, bypassCache); for(int i = 0; i < enrichTasks.size(); i++) { final EnrichTask<T> enrichTask = enrichTasks.get(i); final EnrichTask<T> nextEnrichTask = (i < enrichTasks.size() - 1) ? enrichTasks.get(i + 1) : null; enrichTask.stateProperty().addListener(new ChangeListener<State>() { @Override public void changed(ObservableValue<? extends State> observable, State oldState, State state) { synchronized(cache) { if(!cancelled && (state == State.FAILED || state == State.CANCELLED || state == State.SUCCEEDED)) { T taskResult = enrichTask.getValue(); System.out.println("[" + (state == State.FAILED ? "WARN" : "FINE") + "] EnrichCache [" + enricher.getClass().getSimpleName() + "->" + enrichableClass.getSimpleName() + "]: " + state + ": " + key + ": " + enrichTask.getTitle() + " -> " + taskResult); if(state == State.FAILED) { System.out.println("[WARN] EnrichCache [" + enricher.getClass().getSimpleName() + "->" + enrichableClass.getSimpleName() + "]: " + state + ": " + key + ": " + enrichTask.getTitle() + ": " + enrichTask.getException()); enrichTask.getException().printStackTrace(System.out); insertFailedEnrichment(key, enrichableClass); } if(state == State.SUCCEEDED) { if(taskResult != null || nextEnrichTask == null) { if(taskResult != null) { insert(key, taskResult); } else { insertFailedEnrichment(key, enrichableClass); } Set<PendingEnrichment<?>> set = pendingEnrichmentMap.get(key); set.remove(PendingEnrichment.this); if(set.isEmpty()) { pendingEnrichmentMap.remove(key); } } else { System.out.println("[FINE] EnrichCache [" + enricher.getClass().getSimpleName() + "->" + enrichableClass.getSimpleName() + "]: ENRICH_NEXT: " + key + ": " + nextEnrichTask.getTitle()); if(nextEnrichTask.isFast()) { cacheQueue.submit(key, nextEnrichTask); } else { normalQueue.submit(key, nextEnrichTask); } } } cacheQueue.submitPending(); normalQueue.submitPending(); } } } }); } EnrichTask<T> firstTask = enrichTasks.get(0); System.out.println("[FINE] EnrichCache [" + enricher.getClass().getSimpleName() + "->" + enrichableClass.getSimpleName() + "]: ENRICH: " + key + ": " + firstTask.getTitle()); if(firstTask.isFast()) { cacheQueue.submit(key, firstTask); } else { normalQueue.submit(key, firstTask); } } } }); } }
diff --git a/src/gov/nih/ncgc/bard/capextract/handler/CapResourceHandler.java b/src/gov/nih/ncgc/bard/capextract/handler/CapResourceHandler.java index bee6a71..0522623 100644 --- a/src/gov/nih/ncgc/bard/capextract/handler/CapResourceHandler.java +++ b/src/gov/nih/ncgc/bard/capextract/handler/CapResourceHandler.java @@ -1,114 +1,115 @@ package gov.nih.ncgc.bard.capextract.handler; import gov.nih.ncgc.bard.capextract.CAPConstants; import gov.nih.ncgc.bard.capextract.SslHttpClient; import gov.nih.ncgc.bard.capextract.jaxb.Link; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.HttpHostConnectException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; //import java.io.BufferedReader; import java.io.IOException; //import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.reflect.Method; import java.util.List; import java.util.Vector; /** * A one line summary. * * @author Rajarshi Guha */ public abstract class CapResourceHandler { protected Logger log; private JAXBContext jc; private HttpClient httpClient; protected CapResourceHandler() { httpClient = SslHttpClient.getHttpClient(); log = LoggerFactory.getLogger(this.getClass()); try { jc = JAXBContext.newInstance("gov.nih.ncgc.bard.capextract.jaxb"); } catch (JAXBException e) { e.printStackTrace(); } } public <T> Vector<T> poll(String url, CAPConstants.CapResource resource) throws IOException { return poll(url, resource, false); } public <T> Vector<T> poll(String url, CAPConstants.CapResource resource, boolean skipPartial) throws IOException { Vector<T> vec = new Vector<T>(); while (url != null) { T t = getResponse(url, resource); vec.add(t); url = null; try { Method getLinkList = t.getClass().getMethod("getLink", (Class<?>[])null); @SuppressWarnings("unchecked") List<Link> links = (List<Link>)getLinkList.invoke(t, (Object[])null); for (Link link: links) if (link.getRel().equals("next") && !skipPartial) url = link.getHref(); } catch (Exception e) {;} } return vec; } protected <T> T getResponse(String url, CAPConstants.CapResource resource) throws IOException { HttpGet get = new HttpGet(url); get.setHeader("Accept", resource.getMimeType()); get.setHeader(CAPConstants.CAP_APIKEY_HEADER, CAPConstants.getApiKey()); HttpResponse response; try { response = httpClient.execute(get); } catch (HttpHostConnectException ex) { + ex.printStackTrace(); try { - wait(5000); - } catch (InterruptedException ie) {;} + Thread.sleep(5000); + } catch (InterruptedException ie) {ie.printStackTrace();} httpClient = SslHttpClient.getHttpClient(); response = httpClient.execute(get); } if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 206) throw new IOException("Got a HTTP " + response.getStatusLine().getStatusCode() + " for " + resource + ": " + url); if (response.getStatusLine().getStatusCode() == 206) log.info("Got a 206 (partial content) ... make sure this is handled appropriately for " + resource + ": " + url); Unmarshaller unmarshaller; try { unmarshaller = jc.createUnmarshaller(); Reader reader = new InputStreamReader(response.getEntity().getContent(), "UTF-8"); Object o = unmarshaller.unmarshal(reader); @SuppressWarnings("unchecked") T t = (T)o; return t; } catch (JAXBException e) { throw new IOException("Error unmarshalling document from " + url, e); } } // // for debug purposes // private String read(InputStream in) throws IOException { // StringBuilder sb = new StringBuilder(); // BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000); // int n = 0; // for (String line = r.readLine(); line != null; line = r.readLine()) { // n++; // sb.append(line); // } // in.close(); // return sb.toString(); // } }
false
true
protected <T> T getResponse(String url, CAPConstants.CapResource resource) throws IOException { HttpGet get = new HttpGet(url); get.setHeader("Accept", resource.getMimeType()); get.setHeader(CAPConstants.CAP_APIKEY_HEADER, CAPConstants.getApiKey()); HttpResponse response; try { response = httpClient.execute(get); } catch (HttpHostConnectException ex) { try { wait(5000); } catch (InterruptedException ie) {;} httpClient = SslHttpClient.getHttpClient(); response = httpClient.execute(get); } if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 206) throw new IOException("Got a HTTP " + response.getStatusLine().getStatusCode() + " for " + resource + ": " + url); if (response.getStatusLine().getStatusCode() == 206) log.info("Got a 206 (partial content) ... make sure this is handled appropriately for " + resource + ": " + url); Unmarshaller unmarshaller; try { unmarshaller = jc.createUnmarshaller(); Reader reader = new InputStreamReader(response.getEntity().getContent(), "UTF-8"); Object o = unmarshaller.unmarshal(reader); @SuppressWarnings("unchecked") T t = (T)o; return t; } catch (JAXBException e) { throw new IOException("Error unmarshalling document from " + url, e); } }
protected <T> T getResponse(String url, CAPConstants.CapResource resource) throws IOException { HttpGet get = new HttpGet(url); get.setHeader("Accept", resource.getMimeType()); get.setHeader(CAPConstants.CAP_APIKEY_HEADER, CAPConstants.getApiKey()); HttpResponse response; try { response = httpClient.execute(get); } catch (HttpHostConnectException ex) { ex.printStackTrace(); try { Thread.sleep(5000); } catch (InterruptedException ie) {ie.printStackTrace();} httpClient = SslHttpClient.getHttpClient(); response = httpClient.execute(get); } if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 206) throw new IOException("Got a HTTP " + response.getStatusLine().getStatusCode() + " for " + resource + ": " + url); if (response.getStatusLine().getStatusCode() == 206) log.info("Got a 206 (partial content) ... make sure this is handled appropriately for " + resource + ": " + url); Unmarshaller unmarshaller; try { unmarshaller = jc.createUnmarshaller(); Reader reader = new InputStreamReader(response.getEntity().getContent(), "UTF-8"); Object o = unmarshaller.unmarshal(reader); @SuppressWarnings("unchecked") T t = (T)o; return t; } catch (JAXBException e) { throw new IOException("Error unmarshalling document from " + url, e); } }
diff --git a/src/main/java/com/redhat/topicindex/extras/client/local/presenter/TopicImportPresenter.java b/src/main/java/com/redhat/topicindex/extras/client/local/presenter/TopicImportPresenter.java index 565872b..081909c 100644 --- a/src/main/java/com/redhat/topicindex/extras/client/local/presenter/TopicImportPresenter.java +++ b/src/main/java/com/redhat/topicindex/extras/client/local/presenter/TopicImportPresenter.java @@ -1,316 +1,316 @@ package com.redhat.topicindex.extras.client.local.presenter; import org.vectomatic.file.File; import org.vectomatic.file.FileReader; import org.vectomatic.file.FileUploadExt; import org.vectomatic.file.events.ErrorHandler; import org.vectomatic.file.events.LoadEndEvent; import org.vectomatic.file.events.LoadEndHandler; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.HasWidgets; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.xml.client.Document; import com.google.gwt.xml.client.Node; import com.google.gwt.xml.client.NodeList; import com.google.gwt.xml.client.XMLParser; import javax.enterprise.context.Dependent; import javax.inject.Inject; import com.redhat.topicindex.extras.client.local.Presenter; @Dependent public class TopicImportPresenter implements Presenter { public interface Display { Button getGoButton(); FileUploadExt getUpload(); Widget asWidget(); TextArea getFileList(); TextArea getLog(); } @Inject private HandlerManager eventBus; @Inject private Display display; public void bind() { display.getUpload().addChangeHandler(new ChangeHandler() { @Override public void onChange(final ChangeEvent event) { display.getFileList().setText(""); final StringBuilder fileNames = new StringBuilder(); for (final File file : display.getUpload().getFiles()) { fileNames.append(file.getName() + "\n"); } display.getFileList().setText(fileNames.toString()); } }); display.getGoButton().addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { /* Start processing the files. We create a chain of methods to simulate synchronous processing */ final StringBuilder log = new StringBuilder(); pocessFiles(0, log); } }); } /** * Called when all files have been processed * * @param log * The string holding the log */ private void processingDone(final StringBuilder log) { display.getLog().setText(log.toString()); } /** * Extract the file from the list of upload files and process it, or call processingDone if there are no more files to process. * * @param index * The index of the file to process * @param log * The string holding the log */ private void pocessFiles(final int index, final StringBuilder log) { if (index >= display.getUpload().getFiles().getLength()) { processingDone(log); } else { processFile(display.getUpload().getFiles().getItem(index), index, log); } } /** * Load a file and then pass it off to have the XML processed. Once the file is loaded and its contents processed, call pocessFiles to process the next * file. * * @param file * The file to read * @param index * The index off the file * @param log * The string holding the log */ private void processFile(final File file, final int index, final StringBuilder log) { final FileReader reader = new FileReader(); reader.addErrorHandler(new ErrorHandler() { @Override public void onError(final org.vectomatic.file.events.ErrorEvent event) { pocessFiles(index + 1, log); } }); reader.addLoadEndHandler(new LoadEndHandler() { @Override public void onLoadEnd(final LoadEndEvent event) { final String result = reader.getStringResult(); processXML(result, file, index, log); } }); reader.readAsBinaryString(file); } private void processXML(final String result, final File file, final int index, final StringBuilder log) { try { String fixedResult = result; - /* remove utf-8 BOM marker (if present) */ + /* remove utf-8 Byte Order Mark (BOM) if present */ if (fixedResult.startsWith("")) fixedResult = fixedResult.replaceFirst("", ""); /* parse the XML document into a DOM */ final Document doc = XMLParser.parse(fixedResult); /* what is the top level element */ Node toplevelNode = doc.getDocumentElement(); /* Get the node name */ final String toplevelNodeName = toplevelNode.getNodeName(); /* sections can be imported directly */ if (toplevelNodeName.equals("section")) { // no processing required } /* tasks are turned into sections */ else if (toplevelNodeName.equals("task")) { log.append(file.getName() + ": This topic has had its document element changed from <task> to <section>.\n"); toplevelNode = replaceNodeWithSection(toplevelNode); } /* variablelist are turned into sections */ else if (toplevelNodeName.equals("variablelist")) { log.append(file.getName() + ": This topic has had its document element changed from <variablelist> to <section>.\n"); toplevelNode = replaceNodeWithSection(toplevelNode); } /* Some unknown node type */ else { log.append(file.getName() + ": This topic uses an unrecognised parent node of <" + toplevelNodeName + ">. No processing has been done for this topic, and the XML has been included as is.\n"); uploadFile(result, file, index, log); return; } /* some additional validity checks */ final String errors = isNodeValid(toplevelNode); if (errors != null && !errors.isEmpty()) log.append(file.getName() + ":" + errors + "\n"); /* Upload the processed XML */ uploadFile(toplevelNode.getOwnerDocument().toString(), file, index, log); } catch (final Exception ex) { /* The xml is not valid, so upload as is */ log.append(file.getName() + ": This topic has invalid XML, and has been uploaded as is.\n"); uploadFile(result, file, index, log); } } private void uploadFile(final String topicXML, final File file, final int index, final StringBuilder log) { log.append("-------------------------------------\n"); log.append("Uploaded file " + file.getName() + "\n"); log.append("XML Contents is:\n"); log.append(topicXML + "\n"); log.append("-------------------------------------\n"); pocessFiles(index + 1, log); } /** * Create a new Document with a <section> document lement node. This is to work around the lack of a Document.renameNode() method. * * @param node * The node to be replaced * @return The new node in a new document */ private Node replaceNodeWithSection(final Node node) { final Document doc = XMLParser.createDocument(); final Node section = doc.createElement("section"); doc.appendChild(section); final NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); ++i) { final Node childNode = children.item(i); final Node importedNode = doc.importNode(childNode, true); section.appendChild(importedNode); } return section; } /** * Perform some validity checks on the topic * * @param node * The node that holds the topic * @return any errors that were found */ private String isNodeValid(final Node node) { final StringBuilder builder = new StringBuilder(); if (getFirstChild(node, "section", true) != null) builder.append(" This topic has illegal nested sections."); if (getFirstChild(node, "xref", true) != null) builder.append(" This topic has illegal xrefs."); if (getFirstChild(node, "xi:include", true) != null) builder.append(" This topic has illegal xi:includes."); if (getFirstChild(node, "title", false) == null) builder.append(" This topic has no title."); return builder.toString(); } /** * Scans a XML document for a node with the given name * * @param node * The node to search * @param nodeName * The name of the node to find * @param recursive true if a search is to be done on the children as well, false otherwise * @return null if no node is found, or the first node with the supplied name that was found */ private Node getFirstChild(final Node node, final String nodeName, final boolean recursive) { final NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); ++i) { final Node child = children.item(i); // TODO: check URI (e.g. for xi:include) if (child.getNodeName().equals(nodeName)) return child; } if (recursive) { for (int i = 0; i < children.getLength(); ++i) { final Node child = children.item(i); final Node namedChild = getFirstChild(child, nodeName, recursive); if (namedChild != null) return namedChild; } } return null; } @Override public void go(final HasWidgets container) { bind(); container.clear(); container.add(display.asWidget()); } }
true
true
private void processXML(final String result, final File file, final int index, final StringBuilder log) { try { String fixedResult = result; /* remove utf-8 BOM marker (if present) */ if (fixedResult.startsWith("")) fixedResult = fixedResult.replaceFirst("", ""); /* parse the XML document into a DOM */ final Document doc = XMLParser.parse(fixedResult); /* what is the top level element */ Node toplevelNode = doc.getDocumentElement(); /* Get the node name */ final String toplevelNodeName = toplevelNode.getNodeName(); /* sections can be imported directly */ if (toplevelNodeName.equals("section")) { // no processing required } /* tasks are turned into sections */ else if (toplevelNodeName.equals("task")) { log.append(file.getName() + ": This topic has had its document element changed from <task> to <section>.\n"); toplevelNode = replaceNodeWithSection(toplevelNode); } /* variablelist are turned into sections */ else if (toplevelNodeName.equals("variablelist")) { log.append(file.getName() + ": This topic has had its document element changed from <variablelist> to <section>.\n"); toplevelNode = replaceNodeWithSection(toplevelNode); } /* Some unknown node type */ else { log.append(file.getName() + ": This topic uses an unrecognised parent node of <" + toplevelNodeName + ">. No processing has been done for this topic, and the XML has been included as is.\n"); uploadFile(result, file, index, log); return; } /* some additional validity checks */ final String errors = isNodeValid(toplevelNode); if (errors != null && !errors.isEmpty()) log.append(file.getName() + ":" + errors + "\n"); /* Upload the processed XML */ uploadFile(toplevelNode.getOwnerDocument().toString(), file, index, log); } catch (final Exception ex) { /* The xml is not valid, so upload as is */ log.append(file.getName() + ": This topic has invalid XML, and has been uploaded as is.\n"); uploadFile(result, file, index, log); } }
private void processXML(final String result, final File file, final int index, final StringBuilder log) { try { String fixedResult = result; /* remove utf-8 Byte Order Mark (BOM) if present */ if (fixedResult.startsWith("")) fixedResult = fixedResult.replaceFirst("", ""); /* parse the XML document into a DOM */ final Document doc = XMLParser.parse(fixedResult); /* what is the top level element */ Node toplevelNode = doc.getDocumentElement(); /* Get the node name */ final String toplevelNodeName = toplevelNode.getNodeName(); /* sections can be imported directly */ if (toplevelNodeName.equals("section")) { // no processing required } /* tasks are turned into sections */ else if (toplevelNodeName.equals("task")) { log.append(file.getName() + ": This topic has had its document element changed from <task> to <section>.\n"); toplevelNode = replaceNodeWithSection(toplevelNode); } /* variablelist are turned into sections */ else if (toplevelNodeName.equals("variablelist")) { log.append(file.getName() + ": This topic has had its document element changed from <variablelist> to <section>.\n"); toplevelNode = replaceNodeWithSection(toplevelNode); } /* Some unknown node type */ else { log.append(file.getName() + ": This topic uses an unrecognised parent node of <" + toplevelNodeName + ">. No processing has been done for this topic, and the XML has been included as is.\n"); uploadFile(result, file, index, log); return; } /* some additional validity checks */ final String errors = isNodeValid(toplevelNode); if (errors != null && !errors.isEmpty()) log.append(file.getName() + ":" + errors + "\n"); /* Upload the processed XML */ uploadFile(toplevelNode.getOwnerDocument().toString(), file, index, log); } catch (final Exception ex) { /* The xml is not valid, so upload as is */ log.append(file.getName() + ": This topic has invalid XML, and has been uploaded as is.\n"); uploadFile(result, file, index, log); } }
diff --git a/uncoupled/deegree-maven-plugin/src/main/java/org/deegree/maven/ithelper/ServiceIntegrationTestHelper.java b/uncoupled/deegree-maven-plugin/src/main/java/org/deegree/maven/ithelper/ServiceIntegrationTestHelper.java index d17a75ec46..5cb12389ae 100644 --- a/uncoupled/deegree-maven-plugin/src/main/java/org/deegree/maven/ithelper/ServiceIntegrationTestHelper.java +++ b/uncoupled/deegree-maven-plugin/src/main/java/org/deegree/maven/ithelper/ServiceIntegrationTestHelper.java @@ -1,281 +1,281 @@ //$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2010 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library 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 library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.maven.ithelper; import static java.util.Collections.singletonList; import static org.apache.commons.io.FileUtils.readFileToString; import static org.apache.commons.io.IOUtils.closeQuietly; import static org.apache.commons.io.IOUtils.toByteArray; import static org.deegree.commons.utils.net.HttpUtils.STREAM; import static org.deegree.commons.utils.net.HttpUtils.post; import static org.deegree.protocol.wms.WMSConstants.WMSRequestType.GetMap; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.apache.commons.io.IOUtils; import org.apache.commons.io.filefilter.SuffixFileFilter; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.deegree.commons.utils.Pair; import org.deegree.cs.CRSUtils; import org.deegree.cs.exceptions.TransformationException; import org.deegree.cs.exceptions.UnknownCRSException; import org.deegree.cs.persistence.CRSManager; import org.deegree.geometry.Envelope; import org.deegree.geometry.GeometryFactory; import org.deegree.geometry.GeometryTransformer; import org.deegree.protocol.wms.client.WMSClient111; /** * * @author <a href="mailto:[email protected]">Andreas Schmitz</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public class ServiceIntegrationTestHelper { private Log log; private MavenProject project; public ServiceIntegrationTestHelper( MavenProject project, Log log ) { this.log = log; this.project = project; } public String getPort() { Object port = project.getProperties().get( "portnumber" ); return port.toString(); } public String createBaseURL() { Object port = project.getProperties().get( "portnumber" ); return "http://localhost:" + port + "/" + project.getArtifactId() + "/"; } public void testCapabilities( String service ) throws MojoFailureException { String address = createBaseURL() + "services/" + service.toLowerCase() + "?request=GetCapabilities&service=" + service; try { log.info( "Reading capabilities from " + address ); String input = IOUtils.toString( new URL( address ).openStream(), "UTF-8" ); XMLInputFactory fac = XMLInputFactory.newInstance(); XMLStreamReader in = fac.createXMLStreamReader( new StringReader( input ) ); in.next(); if ( in.getLocalName().toLowerCase().contains( "exception" ) ) { log.error( "Actual response was:" ); log.error( input ); throw new MojoFailureException( "Retrieving capabilities from " + address + " failed." ); } } catch ( MalformedURLException e ) { log.debug( e ); throw new MojoFailureException( "Retrieving capabilities for " + service + " failed: " + e.getLocalizedMessage() ); } catch ( XMLStreamException e ) { log.debug( e ); throw new MojoFailureException( "Retrieving capabilities for " + service + " failed: " + e.getLocalizedMessage() ); } catch ( FactoryConfigurationError e ) { log.debug( e ); throw new MojoFailureException( "Retrieving capabilities for " + service + " failed: " + e.getLocalizedMessage() ); } catch ( IOException e ) { log.debug( e ); throw new MojoFailureException( "Retrieving capabilities for " + service + " failed: " + e.getLocalizedMessage() ); } } public void testLayers( String service ) throws MojoFailureException { if ( !service.equals( "WMS" ) ) { return; } - String address = createBaseURL() + "services?request=GetCapabilities&version=1.1.1&service=" + service; + String address = createBaseURL() + "services/wms?request=GetCapabilities&version=1.1.1&service=" + service; String currentLayer = null; try { WMSClient111 client = new WMSClient111( new URL( address ), 360, 360 ); for ( String layer : client.getNamedLayers() ) { log.info( "Retrieving map for layer " + layer ); currentLayer = layer; List<String> layers = singletonList( layer ); String srs = client.getCoordinateSystems( layer ).getFirst(); Envelope bbox = client.getBoundingBox( srs, layer ); if ( bbox == null ) { bbox = client.getLatLonBoundingBox( layer ); if ( bbox == null ) { bbox = new GeometryFactory().createEnvelope( -180, -90, 180, 90, CRSUtils.EPSG_4326 ); } bbox = new GeometryTransformer( CRSManager.lookup( srs ) ).transform( bbox ); } Pair<BufferedImage, String> map = client.getMap( layers, 100, 100, bbox, CRSManager.lookup( srs ), client.getFormats( GetMap ).getFirst(), true, false, -1, false, null ); if ( map.first == null ) { throw new MojoFailureException( "Retrieving map for " + layer + " failed: " + map.second ); } } } catch ( MalformedURLException e ) { log.debug( e ); throw new MojoFailureException( "Retrieving capabilities for " + service + " failed: " + e.getLocalizedMessage() ); } catch ( IOException e ) { log.debug( e ); throw new MojoFailureException( "Retrieving map for " + currentLayer + " failed: " + e.getLocalizedMessage() ); } catch ( IllegalArgumentException e ) { log.debug( e ); throw new MojoFailureException( "Layer " + currentLayer + " had no bounding box." ); } catch ( TransformationException e ) { log.debug( e ); throw new MojoFailureException( "Layer " + currentLayer + " had no bounding box." ); } catch ( UnknownCRSException e ) { log.debug( e ); throw new MojoFailureException( "Layer " + currentLayer + " had no bounding box." ); } } public static double determineSimilarity( String name, InputStream in1, InputStream in2 ) throws IOException, MojoFailureException { try { byte[] buf1 = toByteArray( in1 ); byte[] buf2 = toByteArray( in2 ); long equal = 0; for ( int i = 0; i < buf1.length; ++i ) { if ( i < buf2.length && buf1[i] == buf2[i] ) { ++equal; } } double sim = (double) equal / (double) buf1.length; if ( sim < 0.99 ) { throw new MojoFailureException( "Request test " + name + " resulted in a similarity of only " + sim + "!" ); } return sim; } finally { closeQuietly( in1 ); closeQuietly( in2 ); } } public void testRequests() throws MojoFailureException { String address = createBaseURL() + "services"; File reqDir = new File( project.getBasedir(), "src/test/requests" ); log.info( "---- Searching main requests directory for requests." ); testRequestDirectories( address, reqDir ); } public void testRequestDirectories( String address, File dir ) throws MojoFailureException { testRequestDirectory( address, dir ); File[] listed = dir.listFiles(); if ( listed != null ) { for ( File f : listed ) { if ( f.isDirectory() && !f.getName().equalsIgnoreCase( ".svn" ) ) { log.info( "---- Searching request class " + f.getName() + " for requests." ); testRequestDirectories( address, f ); } } } } public void testRequestDirectory( String address, File dir ) throws MojoFailureException { File[] listed = dir.listFiles( (FileFilter) new SuffixFileFilter( "kvp" ) ); if ( listed != null ) { for ( File f : listed ) { String name = f.getName(); name = name.substring( 0, name.length() - 4 ); log.info( "KVP request testing " + name ); try { String req = readFileToString( f ).trim(); InputStream in1 = new URL( address + ( req.startsWith( "?" ) ? "" : "?" ) + req ).openStream(); File response = new File( f.getParentFile(), name + ".response" ); InputStream in2 = new FileInputStream( response ); double sim = determineSimilarity( name, in1, in2 ); if ( sim != 1 ) { log.info( "Request test " + name + " resulted in similarity of " + sim ); } } catch ( IOException e ) { throw new MojoFailureException( "KVP request checking of " + name + " failed: " + e.getLocalizedMessage() ); } } } listed = dir.listFiles( (FileFilter) new SuffixFileFilter( "xml" ) ); if ( listed != null ) { for ( File f : listed ) { String name = f.getName(); name = name.substring( 0, name.length() - 4 ); log.info( "XML request testing " + name ); FileInputStream reqIn = null; try { reqIn = new FileInputStream( f ); InputStream in1 = post( STREAM, address, reqIn, null ); File response = new File( f.getParentFile(), name + ".response" ); InputStream in2 = new FileInputStream( response ); double sim = determineSimilarity( name, in1, in2 ); log.info( "Request test " + name + " resulted in similarity of " + sim ); } catch ( IOException e ) { throw new MojoFailureException( "KVP request checking of " + name + " failed: " + e.getLocalizedMessage() ); } finally { closeQuietly( reqIn ); } } } } }
true
true
public void testLayers( String service ) throws MojoFailureException { if ( !service.equals( "WMS" ) ) { return; } String address = createBaseURL() + "services?request=GetCapabilities&version=1.1.1&service=" + service; String currentLayer = null; try { WMSClient111 client = new WMSClient111( new URL( address ), 360, 360 ); for ( String layer : client.getNamedLayers() ) { log.info( "Retrieving map for layer " + layer ); currentLayer = layer; List<String> layers = singletonList( layer ); String srs = client.getCoordinateSystems( layer ).getFirst(); Envelope bbox = client.getBoundingBox( srs, layer ); if ( bbox == null ) { bbox = client.getLatLonBoundingBox( layer ); if ( bbox == null ) { bbox = new GeometryFactory().createEnvelope( -180, -90, 180, 90, CRSUtils.EPSG_4326 ); } bbox = new GeometryTransformer( CRSManager.lookup( srs ) ).transform( bbox ); } Pair<BufferedImage, String> map = client.getMap( layers, 100, 100, bbox, CRSManager.lookup( srs ), client.getFormats( GetMap ).getFirst(), true, false, -1, false, null ); if ( map.first == null ) { throw new MojoFailureException( "Retrieving map for " + layer + " failed: " + map.second ); } } } catch ( MalformedURLException e ) { log.debug( e ); throw new MojoFailureException( "Retrieving capabilities for " + service + " failed: " + e.getLocalizedMessage() ); } catch ( IOException e ) { log.debug( e ); throw new MojoFailureException( "Retrieving map for " + currentLayer + " failed: " + e.getLocalizedMessage() ); } catch ( IllegalArgumentException e ) { log.debug( e ); throw new MojoFailureException( "Layer " + currentLayer + " had no bounding box." ); } catch ( TransformationException e ) { log.debug( e ); throw new MojoFailureException( "Layer " + currentLayer + " had no bounding box." ); } catch ( UnknownCRSException e ) { log.debug( e ); throw new MojoFailureException( "Layer " + currentLayer + " had no bounding box." ); } }
public void testLayers( String service ) throws MojoFailureException { if ( !service.equals( "WMS" ) ) { return; } String address = createBaseURL() + "services/wms?request=GetCapabilities&version=1.1.1&service=" + service; String currentLayer = null; try { WMSClient111 client = new WMSClient111( new URL( address ), 360, 360 ); for ( String layer : client.getNamedLayers() ) { log.info( "Retrieving map for layer " + layer ); currentLayer = layer; List<String> layers = singletonList( layer ); String srs = client.getCoordinateSystems( layer ).getFirst(); Envelope bbox = client.getBoundingBox( srs, layer ); if ( bbox == null ) { bbox = client.getLatLonBoundingBox( layer ); if ( bbox == null ) { bbox = new GeometryFactory().createEnvelope( -180, -90, 180, 90, CRSUtils.EPSG_4326 ); } bbox = new GeometryTransformer( CRSManager.lookup( srs ) ).transform( bbox ); } Pair<BufferedImage, String> map = client.getMap( layers, 100, 100, bbox, CRSManager.lookup( srs ), client.getFormats( GetMap ).getFirst(), true, false, -1, false, null ); if ( map.first == null ) { throw new MojoFailureException( "Retrieving map for " + layer + " failed: " + map.second ); } } } catch ( MalformedURLException e ) { log.debug( e ); throw new MojoFailureException( "Retrieving capabilities for " + service + " failed: " + e.getLocalizedMessage() ); } catch ( IOException e ) { log.debug( e ); throw new MojoFailureException( "Retrieving map for " + currentLayer + " failed: " + e.getLocalizedMessage() ); } catch ( IllegalArgumentException e ) { log.debug( e ); throw new MojoFailureException( "Layer " + currentLayer + " had no bounding box." ); } catch ( TransformationException e ) { log.debug( e ); throw new MojoFailureException( "Layer " + currentLayer + " had no bounding box." ); } catch ( UnknownCRSException e ) { log.debug( e ); throw new MojoFailureException( "Layer " + currentLayer + " had no bounding box." ); } }
diff --git a/com.ibm.wala.cast.java/src/com/ibm/wala/cast/java/ipa/callgraph/JavaSourceAnalysisScope.java b/com.ibm.wala.cast.java/src/com/ibm/wala/cast/java/ipa/callgraph/JavaSourceAnalysisScope.java index 1d4a7a5d1..274d7cd3c 100644 --- a/com.ibm.wala.cast.java/src/com/ibm/wala/cast/java/ipa/callgraph/JavaSourceAnalysisScope.java +++ b/com.ibm.wala.cast.java/src/com/ibm/wala/cast/java/ipa/callgraph/JavaSourceAnalysisScope.java @@ -1,35 +1,35 @@ /****************************************************************************** * Copyright (c) 2002 - 2006 IBM Corporation. * 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 *****************************************************************************/ /* * Created on Sep 27, 2005 */ package com.ibm.wala.cast.java.ipa.callgraph; import com.ibm.wala.eclipse.util.EclipseProjectPath; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.types.ClassLoaderReference; public class JavaSourceAnalysisScope extends AnalysisScope { public JavaSourceAnalysisScope() { EclipseProjectPath.SOURCE_REF.setParent(getLoader(APPLICATION)); getLoader(SYNTHETIC).setParent(EclipseProjectPath.SOURCE_REF); loadersByName.put(EclipseProjectPath.SOURCE, EclipseProjectPath.SOURCE_REF); setLoaderImpl(getLoader(SYNTHETIC), "com.ibm.wala.ipa.summaries.BypassSyntheticClassLoader"); - setLoaderImpl(EclipseProjectPath.SOURCE_REF, "com.ibm.domo.ast.java.translator.polyglot.PolyglotSourceLoaderImpl"); + setLoaderImpl(EclipseProjectPath.SOURCE_REF, "com.ibm.wala.cast.java.translator.polyglot.PolyglotSourceLoaderImpl"); } public ClassLoaderReference getSourceLoader() { return getLoader(EclipseProjectPath.SOURCE); } }
true
true
public JavaSourceAnalysisScope() { EclipseProjectPath.SOURCE_REF.setParent(getLoader(APPLICATION)); getLoader(SYNTHETIC).setParent(EclipseProjectPath.SOURCE_REF); loadersByName.put(EclipseProjectPath.SOURCE, EclipseProjectPath.SOURCE_REF); setLoaderImpl(getLoader(SYNTHETIC), "com.ibm.wala.ipa.summaries.BypassSyntheticClassLoader"); setLoaderImpl(EclipseProjectPath.SOURCE_REF, "com.ibm.domo.ast.java.translator.polyglot.PolyglotSourceLoaderImpl"); }
public JavaSourceAnalysisScope() { EclipseProjectPath.SOURCE_REF.setParent(getLoader(APPLICATION)); getLoader(SYNTHETIC).setParent(EclipseProjectPath.SOURCE_REF); loadersByName.put(EclipseProjectPath.SOURCE, EclipseProjectPath.SOURCE_REF); setLoaderImpl(getLoader(SYNTHETIC), "com.ibm.wala.ipa.summaries.BypassSyntheticClassLoader"); setLoaderImpl(EclipseProjectPath.SOURCE_REF, "com.ibm.wala.cast.java.translator.polyglot.PolyglotSourceLoaderImpl"); }
diff --git a/src/markehme/factionsplus/Cmds/CmdWarp.java b/src/markehme/factionsplus/Cmds/CmdWarp.java index 92a3e8b..6d87c25 100644 --- a/src/markehme/factionsplus/Cmds/CmdWarp.java +++ b/src/markehme/factionsplus/Cmds/CmdWarp.java @@ -1,230 +1,230 @@ package markehme.factionsplus.Cmds; import java.io.*; import java.util.ArrayList; import java.util.List; import markehme.factionsplus.FactionsPlus; import markehme.factionsplus.extras.*; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import com.massivecraft.factions.Board; import com.massivecraft.factions.FLocation; import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayers; import com.massivecraft.factions.Faction; import com.massivecraft.factions.cmd.FCommand; import com.massivecraft.factions.integration.EssentialsFeatures; import com.massivecraft.factions.struct.*; import com.massivecraft.factions.zcore.util.SmokeUtil; public class CmdWarp extends FCommand { public CmdWarp() { this.aliases.add("warp"); this.requiredArgs.add("name"); this.optionalArgs.put("password", "string"); this.optionalArgs.put("faction", "string"); this.permission = Permission.HELP.node; this.disableOnLock = false; this.errorOnToManyArgs = false; senderMustBePlayer = true; senderMustBeMember = false; this.setHelpShort("warps to a specific warp"); } @Override public void perform() { String warpname = this.argAsString(0); String setPassword = null; if(this.argAsString(1) != null) { setPassword = this.argAsString(1); } else { setPassword = "nullvalue"; } if(!FactionsPlus.permission.has(sender, "factionsplus.warp")) { sender.sendMessage(ChatColor.RED + "No permission!"); return; } Player player = (Player)sender; FPlayer fplayer = FPlayers.i.get(sender.getName()); Faction currentFaction = fplayer.getFaction(); File currentWarpFile = new File(FactionsPlus.folderWarps, currentFaction.getId()); World world; // Check if player can teleport from enemy territory if(!FactionsPlus.config.getBoolean(FactionsPlus.confStr_warpTeleportAllowedFromEnemyTerritory) && fplayer.isInEnemyTerritory() ){ fplayer.msg("<b>You cannot teleport to your faction warp while in the territory of an enemy faction."); return; } // Check if player can teleport from different world /* * Move inside the try catch * * if(!Conf.homesTeleportAllowedFromDifferentWorld && player.getWorld().getUID() != world){ * fme.msg("<b>You cannot teleport to your faction home while in a different world."); * return; * } */ // Check for enemies nearby // if player is not in a safe zone or their own faction territory, only allow teleport if no enemies are nearby Location loc = player.getLocation().clone(); if ( FactionsPlus.config.getInt(FactionsPlus.confStr_warpTeleportAllowedEnemyDistance) > 0 && ! Board.getFactionAt(new FLocation(loc)).isSafeZone() && ( ! fplayer.isInOwnTerritory() || ( fplayer.isInOwnTerritory() && ! FactionsPlus.config.getBoolean(FactionsPlus.confStr_warpTeleportIgnoreEnemiesIfInOwnTerritory)))){ World w = loc.getWorld(); double x = loc.getX(); double y = loc.getY(); double z = loc.getZ(); for (Player playa : me.getServer().getOnlinePlayers()) { if (playa == null || !playa.isOnline() || playa.isDead() || playa == fme || playa.getWorld() != w) continue; FPlayer fp = FPlayers.i.get(playa); if ( ! FactionsAny.Relation.ENEMY.equals( Bridge.factions.getRelationBetween( fplayer, fp ) )) { continue;//if not enemies, continue } Location l = playa.getLocation(); double dx = Math.abs(x - l.getX()); double dy = Math.abs(y - l.getY()); double dz = Math.abs(z - l.getZ()); double max = FactionsPlus.config.getInt(FactionsPlus.confStr_warpTeleportAllowedEnemyDistance); // box-shaped distance check if (dx > max || dy > max || dz > max) continue; - fplayer.msg("<b>You cannot teleport to your faction warp while an enemy is within " + FactionsPlus.config.getInt("warpTeleportAllowedEnemyDistance") + " blocks of you."); + fplayer.msg("<b>You cannot teleport to your faction warp while an enemy is within " + max+ " blocks of you."); return; } } if (!currentWarpFile.exists()) { sender.sendMessage(ChatColor.RED + "Your faction has no warps!"); return; } FileInputStream fstream=null; DataInputStream in=null; BufferedReader br=null; try { fstream = new FileInputStream(currentWarpFile); in = new DataInputStream(fstream); br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { //sender.sendMessage(strLine); String[] warp_data = strLine.split(":"); if(warp_data[0].equalsIgnoreCase(warpname)) { //sender.sendMessage("warp found: " + warp_data[0]); double x = Double.parseDouble(warp_data[1]); double y = Double.parseDouble(warp_data[2]); // y axis double z = Double.parseDouble(warp_data[3]); float Y = Float.parseFloat(warp_data[4]); // yaw float playa = Float.parseFloat(warp_data[5]); world = Bukkit.getServer().getWorld(warp_data[6]); if(warp_data.length == 8) { if(warp_data[7] != "nullvalue") { if(!setPassword.trim().equals(warp_data[7].trim())) { sender.sendMessage("Incorrect password, please use /f warp [warp] <password>"); return; } } } if(FactionsPlus.config.getInt(FactionsPlus.confStr_economyCostToWarp) > 0) { if (!payForCommand(FactionsPlus.config.getInt(FactionsPlus.confStr_economyCostToWarp), "to teleport to this warp", "for teleporting to your faction home")) { return; } } player.sendMessage(ChatColor.RED + "Warped to " + ChatColor.WHITE + warpname); Location newTel = new Location(world, x, y, z, Y, playa); if (EssentialsFeatures.handleTeleport(player, newTel)) return; // Create a smoke effect if (FactionsPlus.config.getBoolean(FactionsPlus.confStr_smokeEffectOnWarp)) { List<Location> smokeLocations = new ArrayList<Location>(); smokeLocations.add(player.getLocation()); smokeLocations.add(player.getLocation().add(0, 1, 0)); smokeLocations.add(newTel); smokeLocations.add(newTel.clone().add(0, 1, 0)); SmokeUtil.spawnCloudRandom(smokeLocations, 3f); } player.teleport(new Location(world, x, y, z, Y, playa)); // in.close(); return; } } player.sendMessage("Could not find the warp " + warpname); // in.close(); } catch (Exception e) { e.printStackTrace(); sender.sendMessage(ChatColor.RED + "An internal error occured (02)"); }finally{ if (null != br) { try { br.close(); } catch ( IOException e ) { e.printStackTrace(); } } if (null != in) { try { in.close(); } catch ( IOException e ) { e.printStackTrace(); } } if (null != fstream) { try { fstream.close(); } catch ( IOException e ) { e.printStackTrace(); } } } } }
true
true
public void perform() { String warpname = this.argAsString(0); String setPassword = null; if(this.argAsString(1) != null) { setPassword = this.argAsString(1); } else { setPassword = "nullvalue"; } if(!FactionsPlus.permission.has(sender, "factionsplus.warp")) { sender.sendMessage(ChatColor.RED + "No permission!"); return; } Player player = (Player)sender; FPlayer fplayer = FPlayers.i.get(sender.getName()); Faction currentFaction = fplayer.getFaction(); File currentWarpFile = new File(FactionsPlus.folderWarps, currentFaction.getId()); World world; // Check if player can teleport from enemy territory if(!FactionsPlus.config.getBoolean(FactionsPlus.confStr_warpTeleportAllowedFromEnemyTerritory) && fplayer.isInEnemyTerritory() ){ fplayer.msg("<b>You cannot teleport to your faction warp while in the territory of an enemy faction."); return; } // Check if player can teleport from different world /* * Move inside the try catch * * if(!Conf.homesTeleportAllowedFromDifferentWorld && player.getWorld().getUID() != world){ * fme.msg("<b>You cannot teleport to your faction home while in a different world."); * return; * } */ // Check for enemies nearby // if player is not in a safe zone or their own faction territory, only allow teleport if no enemies are nearby Location loc = player.getLocation().clone(); if ( FactionsPlus.config.getInt(FactionsPlus.confStr_warpTeleportAllowedEnemyDistance) > 0 && ! Board.getFactionAt(new FLocation(loc)).isSafeZone() && ( ! fplayer.isInOwnTerritory() || ( fplayer.isInOwnTerritory() && ! FactionsPlus.config.getBoolean(FactionsPlus.confStr_warpTeleportIgnoreEnemiesIfInOwnTerritory)))){ World w = loc.getWorld(); double x = loc.getX(); double y = loc.getY(); double z = loc.getZ(); for (Player playa : me.getServer().getOnlinePlayers()) { if (playa == null || !playa.isOnline() || playa.isDead() || playa == fme || playa.getWorld() != w) continue; FPlayer fp = FPlayers.i.get(playa); if ( ! FactionsAny.Relation.ENEMY.equals( Bridge.factions.getRelationBetween( fplayer, fp ) )) { continue;//if not enemies, continue } Location l = playa.getLocation(); double dx = Math.abs(x - l.getX()); double dy = Math.abs(y - l.getY()); double dz = Math.abs(z - l.getZ()); double max = FactionsPlus.config.getInt(FactionsPlus.confStr_warpTeleportAllowedEnemyDistance); // box-shaped distance check if (dx > max || dy > max || dz > max) continue; fplayer.msg("<b>You cannot teleport to your faction warp while an enemy is within " + FactionsPlus.config.getInt("warpTeleportAllowedEnemyDistance") + " blocks of you."); return; } } if (!currentWarpFile.exists()) { sender.sendMessage(ChatColor.RED + "Your faction has no warps!"); return; } FileInputStream fstream=null; DataInputStream in=null; BufferedReader br=null; try { fstream = new FileInputStream(currentWarpFile); in = new DataInputStream(fstream); br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { //sender.sendMessage(strLine); String[] warp_data = strLine.split(":"); if(warp_data[0].equalsIgnoreCase(warpname)) { //sender.sendMessage("warp found: " + warp_data[0]); double x = Double.parseDouble(warp_data[1]); double y = Double.parseDouble(warp_data[2]); // y axis double z = Double.parseDouble(warp_data[3]); float Y = Float.parseFloat(warp_data[4]); // yaw float playa = Float.parseFloat(warp_data[5]); world = Bukkit.getServer().getWorld(warp_data[6]); if(warp_data.length == 8) { if(warp_data[7] != "nullvalue") { if(!setPassword.trim().equals(warp_data[7].trim())) { sender.sendMessage("Incorrect password, please use /f warp [warp] <password>"); return; } } } if(FactionsPlus.config.getInt(FactionsPlus.confStr_economyCostToWarp) > 0) { if (!payForCommand(FactionsPlus.config.getInt(FactionsPlus.confStr_economyCostToWarp), "to teleport to this warp", "for teleporting to your faction home")) { return; } } player.sendMessage(ChatColor.RED + "Warped to " + ChatColor.WHITE + warpname); Location newTel = new Location(world, x, y, z, Y, playa); if (EssentialsFeatures.handleTeleport(player, newTel)) return; // Create a smoke effect if (FactionsPlus.config.getBoolean(FactionsPlus.confStr_smokeEffectOnWarp)) { List<Location> smokeLocations = new ArrayList<Location>(); smokeLocations.add(player.getLocation()); smokeLocations.add(player.getLocation().add(0, 1, 0)); smokeLocations.add(newTel); smokeLocations.add(newTel.clone().add(0, 1, 0)); SmokeUtil.spawnCloudRandom(smokeLocations, 3f); } player.teleport(new Location(world, x, y, z, Y, playa)); // in.close(); return; } } player.sendMessage("Could not find the warp " + warpname); // in.close(); } catch (Exception e) { e.printStackTrace(); sender.sendMessage(ChatColor.RED + "An internal error occured (02)"); }finally{ if (null != br) { try { br.close(); } catch ( IOException e ) { e.printStackTrace(); } } if (null != in) { try { in.close(); } catch ( IOException e ) { e.printStackTrace(); } } if (null != fstream) { try { fstream.close(); } catch ( IOException e ) { e.printStackTrace(); } } } }
public void perform() { String warpname = this.argAsString(0); String setPassword = null; if(this.argAsString(1) != null) { setPassword = this.argAsString(1); } else { setPassword = "nullvalue"; } if(!FactionsPlus.permission.has(sender, "factionsplus.warp")) { sender.sendMessage(ChatColor.RED + "No permission!"); return; } Player player = (Player)sender; FPlayer fplayer = FPlayers.i.get(sender.getName()); Faction currentFaction = fplayer.getFaction(); File currentWarpFile = new File(FactionsPlus.folderWarps, currentFaction.getId()); World world; // Check if player can teleport from enemy territory if(!FactionsPlus.config.getBoolean(FactionsPlus.confStr_warpTeleportAllowedFromEnemyTerritory) && fplayer.isInEnemyTerritory() ){ fplayer.msg("<b>You cannot teleport to your faction warp while in the territory of an enemy faction."); return; } // Check if player can teleport from different world /* * Move inside the try catch * * if(!Conf.homesTeleportAllowedFromDifferentWorld && player.getWorld().getUID() != world){ * fme.msg("<b>You cannot teleport to your faction home while in a different world."); * return; * } */ // Check for enemies nearby // if player is not in a safe zone or their own faction territory, only allow teleport if no enemies are nearby Location loc = player.getLocation().clone(); if ( FactionsPlus.config.getInt(FactionsPlus.confStr_warpTeleportAllowedEnemyDistance) > 0 && ! Board.getFactionAt(new FLocation(loc)).isSafeZone() && ( ! fplayer.isInOwnTerritory() || ( fplayer.isInOwnTerritory() && ! FactionsPlus.config.getBoolean(FactionsPlus.confStr_warpTeleportIgnoreEnemiesIfInOwnTerritory)))){ World w = loc.getWorld(); double x = loc.getX(); double y = loc.getY(); double z = loc.getZ(); for (Player playa : me.getServer().getOnlinePlayers()) { if (playa == null || !playa.isOnline() || playa.isDead() || playa == fme || playa.getWorld() != w) continue; FPlayer fp = FPlayers.i.get(playa); if ( ! FactionsAny.Relation.ENEMY.equals( Bridge.factions.getRelationBetween( fplayer, fp ) )) { continue;//if not enemies, continue } Location l = playa.getLocation(); double dx = Math.abs(x - l.getX()); double dy = Math.abs(y - l.getY()); double dz = Math.abs(z - l.getZ()); double max = FactionsPlus.config.getInt(FactionsPlus.confStr_warpTeleportAllowedEnemyDistance); // box-shaped distance check if (dx > max || dy > max || dz > max) continue; fplayer.msg("<b>You cannot teleport to your faction warp while an enemy is within " + max+ " blocks of you."); return; } } if (!currentWarpFile.exists()) { sender.sendMessage(ChatColor.RED + "Your faction has no warps!"); return; } FileInputStream fstream=null; DataInputStream in=null; BufferedReader br=null; try { fstream = new FileInputStream(currentWarpFile); in = new DataInputStream(fstream); br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { //sender.sendMessage(strLine); String[] warp_data = strLine.split(":"); if(warp_data[0].equalsIgnoreCase(warpname)) { //sender.sendMessage("warp found: " + warp_data[0]); double x = Double.parseDouble(warp_data[1]); double y = Double.parseDouble(warp_data[2]); // y axis double z = Double.parseDouble(warp_data[3]); float Y = Float.parseFloat(warp_data[4]); // yaw float playa = Float.parseFloat(warp_data[5]); world = Bukkit.getServer().getWorld(warp_data[6]); if(warp_data.length == 8) { if(warp_data[7] != "nullvalue") { if(!setPassword.trim().equals(warp_data[7].trim())) { sender.sendMessage("Incorrect password, please use /f warp [warp] <password>"); return; } } } if(FactionsPlus.config.getInt(FactionsPlus.confStr_economyCostToWarp) > 0) { if (!payForCommand(FactionsPlus.config.getInt(FactionsPlus.confStr_economyCostToWarp), "to teleport to this warp", "for teleporting to your faction home")) { return; } } player.sendMessage(ChatColor.RED + "Warped to " + ChatColor.WHITE + warpname); Location newTel = new Location(world, x, y, z, Y, playa); if (EssentialsFeatures.handleTeleport(player, newTel)) return; // Create a smoke effect if (FactionsPlus.config.getBoolean(FactionsPlus.confStr_smokeEffectOnWarp)) { List<Location> smokeLocations = new ArrayList<Location>(); smokeLocations.add(player.getLocation()); smokeLocations.add(player.getLocation().add(0, 1, 0)); smokeLocations.add(newTel); smokeLocations.add(newTel.clone().add(0, 1, 0)); SmokeUtil.spawnCloudRandom(smokeLocations, 3f); } player.teleport(new Location(world, x, y, z, Y, playa)); // in.close(); return; } } player.sendMessage("Could not find the warp " + warpname); // in.close(); } catch (Exception e) { e.printStackTrace(); sender.sendMessage(ChatColor.RED + "An internal error occured (02)"); }finally{ if (null != br) { try { br.close(); } catch ( IOException e ) { e.printStackTrace(); } } if (null != in) { try { in.close(); } catch ( IOException e ) { e.printStackTrace(); } } if (null != fstream) { try { fstream.close(); } catch ( IOException e ) { e.printStackTrace(); } } } }
diff --git a/src/com/android/email/activity/setup/AccountSetupOptions.java b/src/com/android/email/activity/setup/AccountSetupOptions.java index 1a246c9f..2822fd6c 100644 --- a/src/com/android/email/activity/setup/AccountSetupOptions.java +++ b/src/com/android/email/activity/setup/AccountSetupOptions.java @@ -1,430 +1,431 @@ /* * Copyright (C) 2008 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.email.activity.setup; import android.accounts.AccountAuthenticatorResponse; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.Spinner; import com.android.email.Email; import com.android.email.R; import com.android.email.activity.ActivityHelper; import com.android.email.activity.UiUtilities; import com.android.email.service.EmailServiceUtils; import com.android.email.service.MailService; import com.android.emailcommon.Logging; import com.android.emailcommon.provider.Account; import com.android.emailcommon.provider.HostAuth; import com.android.emailcommon.provider.Policy; import com.android.emailcommon.service.SyncWindow; import com.android.emailcommon.utility.Utility; import java.io.IOException; /** * TODO: Cleanup the manipulation of Account.FLAGS_INCOMPLETE and make sure it's never left set. */ public class AccountSetupOptions extends AccountSetupActivity implements OnClickListener { private Spinner mCheckFrequencyView; private Spinner mSyncWindowView; private CheckBox mDefaultView; private CheckBox mNotifyView; private CheckBox mSyncContactsView; private CheckBox mSyncCalendarView; private CheckBox mSyncEmailView; private CheckBox mBackgroundAttachmentsView; private View mAccountSyncWindowRow; private boolean mDonePressed = false; public static final int REQUEST_CODE_ACCEPT_POLICIES = 1; /** Default sync window for new EAS accounts */ private static final int SYNC_WINDOW_EAS_DEFAULT = SyncWindow.SYNC_WINDOW_AUTO; public static void actionOptions(Activity fromActivity) { fromActivity.startActivity(new Intent(fromActivity, AccountSetupOptions.class)); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityHelper.debugSetWindowFlags(this); setContentView(R.layout.account_setup_options); mCheckFrequencyView = (Spinner) UiUtilities.getView(this, R.id.account_check_frequency); mSyncWindowView = (Spinner) UiUtilities.getView(this, R.id.account_sync_window); mDefaultView = (CheckBox) UiUtilities.getView(this, R.id.account_default); mNotifyView = (CheckBox) UiUtilities.getView(this, R.id.account_notify); mSyncContactsView = (CheckBox) UiUtilities.getView(this, R.id.account_sync_contacts); mSyncCalendarView = (CheckBox) UiUtilities.getView(this, R.id.account_sync_calendar); mSyncEmailView = (CheckBox) UiUtilities.getView(this, R.id.account_sync_email); mSyncEmailView.setChecked(true); mBackgroundAttachmentsView = (CheckBox) UiUtilities.getView(this, R.id.account_background_attachments); mBackgroundAttachmentsView.setChecked(true); UiUtilities.getView(this, R.id.previous).setOnClickListener(this); UiUtilities.getView(this, R.id.next).setOnClickListener(this); mAccountSyncWindowRow = UiUtilities.getView(this, R.id.account_sync_window_row); // Generate spinner entries using XML arrays used by the preferences int frequencyValuesId; int frequencyEntriesId; Account account = SetupData.getAccount(); - String protocol = account.mHostAuthRecv.mProtocol; + HostAuth host = account.getOrCreateHostAuthRecv(this); + String protocol = host != null ? host.mProtocol : ""; boolean eas = HostAuth.SCHEME_EAS.equals(protocol); if (eas) { frequencyValuesId = R.array.account_settings_check_frequency_values_push; frequencyEntriesId = R.array.account_settings_check_frequency_entries_push; } else { frequencyValuesId = R.array.account_settings_check_frequency_values; frequencyEntriesId = R.array.account_settings_check_frequency_entries; } CharSequence[] frequencyValues = getResources().getTextArray(frequencyValuesId); CharSequence[] frequencyEntries = getResources().getTextArray(frequencyEntriesId); // Now create the array used by the Spinner SpinnerOption[] checkFrequencies = new SpinnerOption[frequencyEntries.length]; for (int i = 0; i < frequencyEntries.length; i++) { checkFrequencies[i] = new SpinnerOption( Integer.valueOf(frequencyValues[i].toString()), frequencyEntries[i].toString()); } ArrayAdapter<SpinnerOption> checkFrequenciesAdapter = new ArrayAdapter<SpinnerOption>(this, android.R.layout.simple_spinner_item, checkFrequencies); checkFrequenciesAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mCheckFrequencyView.setAdapter(checkFrequenciesAdapter); if (eas) { enableEASSyncWindowSpinner(); } // Note: It is OK to use mAccount.mIsDefault here *only* because the account // has not been written to the DB yet. Ordinarily, call Account.getDefaultAccountId(). if (account.mIsDefault || SetupData.isDefault()) { mDefaultView.setChecked(true); } mNotifyView.setChecked( (account.getFlags() & Account.FLAGS_NOTIFY_NEW_MAIL) != 0); SpinnerOption.setSpinnerOptionValue(mCheckFrequencyView, account.getSyncInterval()); // Setup any additional items to support EAS & EAS flow mode if (eas) { // "also sync contacts" == "true" mSyncContactsView.setVisibility(View.VISIBLE); mSyncContactsView.setChecked(true); mSyncCalendarView.setVisibility(View.VISIBLE); mSyncCalendarView.setChecked(true); // Show the associated dividers UiUtilities.setVisibilitySafe(this, R.id.account_sync_contacts_divider, View.VISIBLE); UiUtilities.setVisibilitySafe(this, R.id.account_sync_calendar_divider, View.VISIBLE); } // If we are in POP3, hide the "Background Attachments" mode if (HostAuth.SCHEME_POP3.equals(protocol)) { mBackgroundAttachmentsView.setVisibility(View.GONE); UiUtilities.setVisibilitySafe(this, R.id.account_background_attachments_divider, View.GONE); } // If we are just visiting here to fill in details, exit immediately if (SetupData.isAutoSetup() || SetupData.getFlowMode() == SetupData.FLOW_MODE_FORCE_CREATE) { onDone(); } } @Override public void finish() { // If the account manager initiated the creation, and success was not reported, // then we assume that we're giving up (for any reason) - report failure. AccountAuthenticatorResponse authenticatorResponse = SetupData.getAccountAuthenticatorResponse(); if (authenticatorResponse != null) { authenticatorResponse.onError(AccountManager.ERROR_CODE_CANCELED, "canceled"); SetupData.setAccountAuthenticatorResponse(null); } super.finish(); } /** * Respond to clicks in the "Next" or "Previous" buttons */ @Override public void onClick(View view) { switch (view.getId()) { case R.id.next: // Don't allow this more than once (Exchange accounts call an async method // before finish()'ing the Activity, which allows this code to potentially be // executed multiple times if (!mDonePressed) { onDone(); mDonePressed = true; } break; case R.id.previous: onBackPressed(); break; } } /** * Ths is called when the user clicks the "done" button. * It collects the data from the UI, updates the setup account record, and commits * the account to the database (making it real for the first time.) * Finally, we call setupAccountManagerAccount(), which will eventually complete via callback. */ private void onDone() { final Account account = SetupData.getAccount(); if (account.isSaved()) { // Disrupting the normal flow could get us here, but if the account is already // saved, we've done this work return; } account.setDisplayName(account.getEmailAddress()); int newFlags = account.getFlags() & ~(Account.FLAGS_NOTIFY_NEW_MAIL | Account.FLAGS_BACKGROUND_ATTACHMENTS); if (mNotifyView.isChecked()) { newFlags |= Account.FLAGS_NOTIFY_NEW_MAIL; } if (mBackgroundAttachmentsView.isChecked()) { newFlags |= Account.FLAGS_BACKGROUND_ATTACHMENTS; } account.setFlags(newFlags); account.setSyncInterval((Integer)((SpinnerOption)mCheckFrequencyView .getSelectedItem()).value); if (mAccountSyncWindowRow.getVisibility() == View.VISIBLE) { int window = (Integer)((SpinnerOption)mSyncWindowView.getSelectedItem()).value; account.setSyncLookback(window); } account.setDefaultAccount(mDefaultView.isChecked()); if (account.mHostAuthRecv == null) { throw new IllegalStateException("in AccountSetupOptions with null mHostAuthRecv"); } // Finish setting up the account, and commit it to the database // Set the incomplete flag here to avoid reconciliation issues in ExchangeService account.mFlags |= Account.FLAGS_INCOMPLETE; boolean calendar = false; boolean contacts = false; boolean email = mSyncEmailView.isChecked(); if (account.mHostAuthRecv.mProtocol.equals("eas")) { if (SetupData.getPolicy() != null) { account.mFlags |= Account.FLAGS_SECURITY_HOLD; account.mPolicy = SetupData.getPolicy(); } // Get flags for contacts/calendar sync contacts = mSyncContactsView.isChecked(); calendar = mSyncCalendarView.isChecked(); } // Finally, write the completed account (for the first time) and then // install it into the Account manager as well. These are done off-thread. // The account manager will report back via the callback, which will take us to // the next operations. final boolean email2 = email; final boolean calendar2 = calendar; final boolean contacts2 = contacts; Utility.runAsync(new Runnable() { @Override public void run() { Context context = AccountSetupOptions.this; AccountSettingsUtils.commitSettings(context, account); MailService.setupAccountManagerAccount(context, account, email2, calendar2, contacts2, mAccountManagerCallback); } }); } /** * This is called at the completion of MailService.setupAccountManagerAccount() */ AccountManagerCallback<Bundle> mAccountManagerCallback = new AccountManagerCallback<Bundle>() { public void run(AccountManagerFuture<Bundle> future) { try { Bundle bundle = future.getResult(); bundle.keySet(); AccountSetupOptions.this.runOnUiThread(new Runnable() { public void run() { optionsComplete(); } }); return; } catch (OperationCanceledException e) { Log.d(Logging.LOG_TAG, "addAccount was canceled"); } catch (IOException e) { Log.d(Logging.LOG_TAG, "addAccount failed: " + e); } catch (AuthenticatorException e) { Log.d(Logging.LOG_TAG, "addAccount failed: " + e); } showErrorDialog(R.string.account_setup_failed_dlg_auth_message, R.string.system_account_create_failed); } }; /** * This is called if MailService.setupAccountManagerAccount() fails for some reason */ private void showErrorDialog(final int msgResId, final Object... args) { runOnUiThread(new Runnable() { public void run() { new AlertDialog.Builder(AccountSetupOptions.this) .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle(getString(R.string.account_setup_failed_dlg_title)) .setMessage(getString(msgResId, args)) .setCancelable(true) .setPositiveButton( getString(R.string.account_setup_failed_dlg_edit_details_action), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }) .show(); } }); } /** * This is called after the account manager creates the new account. */ private void optionsComplete() { // If the account manager initiated the creation, report success at this point AccountAuthenticatorResponse authenticatorResponse = SetupData.getAccountAuthenticatorResponse(); if (authenticatorResponse != null) { authenticatorResponse.onResult(null); SetupData.setAccountAuthenticatorResponse(null); } // Now that AccountManager account creation is complete, clear the INCOMPLETE flag Account account = SetupData.getAccount(); account.mFlags &= ~Account.FLAGS_INCOMPLETE; AccountSettingsUtils.commitSettings(AccountSetupOptions.this, account); // If we've got policies for this account, ask the user to accept. if ((account.mFlags & Account.FLAGS_SECURITY_HOLD) != 0) { Intent intent = AccountSecurity.actionUpdateSecurityIntent(this, account.mId, false); startActivityForResult(intent, AccountSetupOptions.REQUEST_CODE_ACCEPT_POLICIES); return; } saveAccountAndFinish(); } /** * This is called after the AccountSecurity activity completes. */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { saveAccountAndFinish(); } /** * These are the final cleanup steps when creating an account: * Clear incomplete & security hold flags * Update account in DB * Enable email services * Enable exchange services * Move to final setup screen */ private void saveAccountAndFinish() { Utility.runAsync(new Runnable() { @Override public void run() { AccountSetupOptions context = AccountSetupOptions.this; // Clear the security hold flag now Account account = SetupData.getAccount(); account.mFlags &= ~Account.FLAGS_SECURITY_HOLD; AccountSettingsUtils.commitSettings(context, account); // Start up services based on new account(s) Email.setServicesEnabledSync(context); EmailServiceUtils.startExchangeService(context); // Move to final setup screen AccountSetupNames.actionSetNames(context); finish(); } }); } /** * Enable an additional spinner using the arrays normally handled by preferences */ private void enableEASSyncWindowSpinner() { // Show everything mAccountSyncWindowRow.setVisibility(View.VISIBLE); // Generate spinner entries using XML arrays used by the preferences CharSequence[] windowValues = getResources().getTextArray( R.array.account_settings_mail_window_values); CharSequence[] windowEntries = getResources().getTextArray( R.array.account_settings_mail_window_entries); // Find a proper maximum for email lookback, based on policy (if we have one) int maxEntry = windowEntries.length; Policy policy = SetupData.getAccount().mPolicy; if (policy != null) { int maxLookback = policy.mMaxEmailLookback; if (maxLookback != 0) { // Offset/Code 0 1 2 3 4 5 // Entries auto, 1 day, 3 day, 1 week, 2 week, 1 month // Lookback N/A 1 day, 3 day, 1 week, 2 week, 1 month // Since our test below is i < maxEntry, we must set maxEntry to maxLookback + 1 maxEntry = maxLookback + 1; } } // Now create the array used by the Spinner SpinnerOption[] windowOptions = new SpinnerOption[maxEntry]; int defaultIndex = -1; for (int i = 0; i < maxEntry; i++) { final int value = Integer.valueOf(windowValues[i].toString()); windowOptions[i] = new SpinnerOption(value, windowEntries[i].toString()); if (value == SYNC_WINDOW_EAS_DEFAULT) { defaultIndex = i; } } ArrayAdapter<SpinnerOption> windowOptionsAdapter = new ArrayAdapter<SpinnerOption>(this, android.R.layout.simple_spinner_item, windowOptions); windowOptionsAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSyncWindowView.setAdapter(windowOptionsAdapter); SpinnerOption.setSpinnerOptionValue(mSyncWindowView, SetupData.getAccount().getSyncLookback()); if (defaultIndex >= 0) { mSyncWindowView.setSelection(defaultIndex); } } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityHelper.debugSetWindowFlags(this); setContentView(R.layout.account_setup_options); mCheckFrequencyView = (Spinner) UiUtilities.getView(this, R.id.account_check_frequency); mSyncWindowView = (Spinner) UiUtilities.getView(this, R.id.account_sync_window); mDefaultView = (CheckBox) UiUtilities.getView(this, R.id.account_default); mNotifyView = (CheckBox) UiUtilities.getView(this, R.id.account_notify); mSyncContactsView = (CheckBox) UiUtilities.getView(this, R.id.account_sync_contacts); mSyncCalendarView = (CheckBox) UiUtilities.getView(this, R.id.account_sync_calendar); mSyncEmailView = (CheckBox) UiUtilities.getView(this, R.id.account_sync_email); mSyncEmailView.setChecked(true); mBackgroundAttachmentsView = (CheckBox) UiUtilities.getView(this, R.id.account_background_attachments); mBackgroundAttachmentsView.setChecked(true); UiUtilities.getView(this, R.id.previous).setOnClickListener(this); UiUtilities.getView(this, R.id.next).setOnClickListener(this); mAccountSyncWindowRow = UiUtilities.getView(this, R.id.account_sync_window_row); // Generate spinner entries using XML arrays used by the preferences int frequencyValuesId; int frequencyEntriesId; Account account = SetupData.getAccount(); String protocol = account.mHostAuthRecv.mProtocol; boolean eas = HostAuth.SCHEME_EAS.equals(protocol); if (eas) { frequencyValuesId = R.array.account_settings_check_frequency_values_push; frequencyEntriesId = R.array.account_settings_check_frequency_entries_push; } else { frequencyValuesId = R.array.account_settings_check_frequency_values; frequencyEntriesId = R.array.account_settings_check_frequency_entries; } CharSequence[] frequencyValues = getResources().getTextArray(frequencyValuesId); CharSequence[] frequencyEntries = getResources().getTextArray(frequencyEntriesId); // Now create the array used by the Spinner SpinnerOption[] checkFrequencies = new SpinnerOption[frequencyEntries.length]; for (int i = 0; i < frequencyEntries.length; i++) { checkFrequencies[i] = new SpinnerOption( Integer.valueOf(frequencyValues[i].toString()), frequencyEntries[i].toString()); } ArrayAdapter<SpinnerOption> checkFrequenciesAdapter = new ArrayAdapter<SpinnerOption>(this, android.R.layout.simple_spinner_item, checkFrequencies); checkFrequenciesAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mCheckFrequencyView.setAdapter(checkFrequenciesAdapter); if (eas) { enableEASSyncWindowSpinner(); } // Note: It is OK to use mAccount.mIsDefault here *only* because the account // has not been written to the DB yet. Ordinarily, call Account.getDefaultAccountId(). if (account.mIsDefault || SetupData.isDefault()) { mDefaultView.setChecked(true); } mNotifyView.setChecked( (account.getFlags() & Account.FLAGS_NOTIFY_NEW_MAIL) != 0); SpinnerOption.setSpinnerOptionValue(mCheckFrequencyView, account.getSyncInterval()); // Setup any additional items to support EAS & EAS flow mode if (eas) { // "also sync contacts" == "true" mSyncContactsView.setVisibility(View.VISIBLE); mSyncContactsView.setChecked(true); mSyncCalendarView.setVisibility(View.VISIBLE); mSyncCalendarView.setChecked(true); // Show the associated dividers UiUtilities.setVisibilitySafe(this, R.id.account_sync_contacts_divider, View.VISIBLE); UiUtilities.setVisibilitySafe(this, R.id.account_sync_calendar_divider, View.VISIBLE); } // If we are in POP3, hide the "Background Attachments" mode if (HostAuth.SCHEME_POP3.equals(protocol)) { mBackgroundAttachmentsView.setVisibility(View.GONE); UiUtilities.setVisibilitySafe(this, R.id.account_background_attachments_divider, View.GONE); } // If we are just visiting here to fill in details, exit immediately if (SetupData.isAutoSetup() || SetupData.getFlowMode() == SetupData.FLOW_MODE_FORCE_CREATE) { onDone(); } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityHelper.debugSetWindowFlags(this); setContentView(R.layout.account_setup_options); mCheckFrequencyView = (Spinner) UiUtilities.getView(this, R.id.account_check_frequency); mSyncWindowView = (Spinner) UiUtilities.getView(this, R.id.account_sync_window); mDefaultView = (CheckBox) UiUtilities.getView(this, R.id.account_default); mNotifyView = (CheckBox) UiUtilities.getView(this, R.id.account_notify); mSyncContactsView = (CheckBox) UiUtilities.getView(this, R.id.account_sync_contacts); mSyncCalendarView = (CheckBox) UiUtilities.getView(this, R.id.account_sync_calendar); mSyncEmailView = (CheckBox) UiUtilities.getView(this, R.id.account_sync_email); mSyncEmailView.setChecked(true); mBackgroundAttachmentsView = (CheckBox) UiUtilities.getView(this, R.id.account_background_attachments); mBackgroundAttachmentsView.setChecked(true); UiUtilities.getView(this, R.id.previous).setOnClickListener(this); UiUtilities.getView(this, R.id.next).setOnClickListener(this); mAccountSyncWindowRow = UiUtilities.getView(this, R.id.account_sync_window_row); // Generate spinner entries using XML arrays used by the preferences int frequencyValuesId; int frequencyEntriesId; Account account = SetupData.getAccount(); HostAuth host = account.getOrCreateHostAuthRecv(this); String protocol = host != null ? host.mProtocol : ""; boolean eas = HostAuth.SCHEME_EAS.equals(protocol); if (eas) { frequencyValuesId = R.array.account_settings_check_frequency_values_push; frequencyEntriesId = R.array.account_settings_check_frequency_entries_push; } else { frequencyValuesId = R.array.account_settings_check_frequency_values; frequencyEntriesId = R.array.account_settings_check_frequency_entries; } CharSequence[] frequencyValues = getResources().getTextArray(frequencyValuesId); CharSequence[] frequencyEntries = getResources().getTextArray(frequencyEntriesId); // Now create the array used by the Spinner SpinnerOption[] checkFrequencies = new SpinnerOption[frequencyEntries.length]; for (int i = 0; i < frequencyEntries.length; i++) { checkFrequencies[i] = new SpinnerOption( Integer.valueOf(frequencyValues[i].toString()), frequencyEntries[i].toString()); } ArrayAdapter<SpinnerOption> checkFrequenciesAdapter = new ArrayAdapter<SpinnerOption>(this, android.R.layout.simple_spinner_item, checkFrequencies); checkFrequenciesAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mCheckFrequencyView.setAdapter(checkFrequenciesAdapter); if (eas) { enableEASSyncWindowSpinner(); } // Note: It is OK to use mAccount.mIsDefault here *only* because the account // has not been written to the DB yet. Ordinarily, call Account.getDefaultAccountId(). if (account.mIsDefault || SetupData.isDefault()) { mDefaultView.setChecked(true); } mNotifyView.setChecked( (account.getFlags() & Account.FLAGS_NOTIFY_NEW_MAIL) != 0); SpinnerOption.setSpinnerOptionValue(mCheckFrequencyView, account.getSyncInterval()); // Setup any additional items to support EAS & EAS flow mode if (eas) { // "also sync contacts" == "true" mSyncContactsView.setVisibility(View.VISIBLE); mSyncContactsView.setChecked(true); mSyncCalendarView.setVisibility(View.VISIBLE); mSyncCalendarView.setChecked(true); // Show the associated dividers UiUtilities.setVisibilitySafe(this, R.id.account_sync_contacts_divider, View.VISIBLE); UiUtilities.setVisibilitySafe(this, R.id.account_sync_calendar_divider, View.VISIBLE); } // If we are in POP3, hide the "Background Attachments" mode if (HostAuth.SCHEME_POP3.equals(protocol)) { mBackgroundAttachmentsView.setVisibility(View.GONE); UiUtilities.setVisibilitySafe(this, R.id.account_background_attachments_divider, View.GONE); } // If we are just visiting here to fill in details, exit immediately if (SetupData.isAutoSetup() || SetupData.getFlowMode() == SetupData.FLOW_MODE_FORCE_CREATE) { onDone(); } }
diff --git a/src/com.gluster.storage.management.gui/src/com/gluster/storage/management/gui/views/pages/VolumeOptionsPage.java b/src/com.gluster.storage.management.gui/src/com/gluster/storage/management/gui/views/pages/VolumeOptionsPage.java index 69434e96..d8b8387e 100644 --- a/src/com.gluster.storage.management.gui/src/com/gluster/storage/management/gui/views/pages/VolumeOptionsPage.java +++ b/src/com.gluster.storage.management.gui/src/com/gluster/storage/management/gui/views/pages/VolumeOptionsPage.java @@ -1,359 +1,361 @@ /******************************************************************************* * Copyright (c) 2011 Gluster, Inc. <http://www.gluster.com> * This file is part of Gluster Management Console. * * Gluster Management Console is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Gluster Management Console 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 Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see * <http://www.gnu.org/licenses/>. *******************************************************************************/ package com.gluster.storage.management.gui.views.pages; import java.util.List; import org.apache.commons.lang.WordUtils; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.ColumnLayoutData; import org.eclipse.jface.viewers.ColumnViewerToolTipSupport; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.widgets.FormToolkit; import com.gluster.storage.management.core.constants.CoreConstants; import com.gluster.storage.management.core.model.DefaultClusterListener; import com.gluster.storage.management.core.model.Event; import com.gluster.storage.management.core.model.Event.EVENT_TYPE; import com.gluster.storage.management.core.model.Volume; import com.gluster.storage.management.core.model.VolumeOption; import com.gluster.storage.management.core.model.VolumeOptionInfo; import com.gluster.storage.management.gui.GlusterDataModelManager; import com.gluster.storage.management.gui.VolumeOptionsContentProvider; import com.gluster.storage.management.gui.VolumeOptionsTableLabelProvider; import com.gluster.storage.management.gui.utils.GUIHelper; public class VolumeOptionsPage extends Composite { private final FormToolkit toolkit = new FormToolkit(Display.getCurrent()); private TableViewer tableViewer; private GUIHelper guiHelper = GUIHelper.getInstance(); private Volume volume; private DefaultClusterListener clusterListener; private Text filterText; private List<VolumeOptionInfo> defaultVolumeOptions = GlusterDataModelManager.getInstance() .getVolumeOptionsDefaults(); public enum OPTIONS_TABLE_COLUMN_INDICES { OPTION_KEY, OPTION_VALUE }; private static final String[] OPTIONS_TABLE_COLUMN_NAMES = new String[] { "Option Key", "Option Value" }; private Button addTopButton; private Button addBottomButton; private TableViewerColumn keyColumn; private OptionKeyEditingSupport keyEditingSupport; public VolumeOptionsPage(final Composite parent, int style, Volume volume) { super(parent, style); this.volume = volume; toolkit.adapt(this); toolkit.paintBordersFor(this); setupPageLayout(); addTopButton = createAddButton(); filterText = guiHelper.createFilterText(toolkit, this); setupOptionsTableViewer(filterText); addBottomButton = createAddButton(); if (defaultVolumeOptions.size() == volume.getOptions().size()) { setAddButtonsEnabled(false); } tableViewer.setInput(volume.getOptions()); parent.layout(); // Important - this actually paints the table registerListeners(parent); } private void setAddButtonsEnabled(boolean enable) { addTopButton.setEnabled(enable); addBottomButton.setEnabled(enable); } private Button createAddButton() { return toolkit.createButton(this, "&Add", SWT.FLAT); } private void registerListeners(final Composite parent) { /** * Ideally not required. However the table viewer is not getting laid out properly on performing * "maximize + restore" So this is a hack to make sure that the table is laid out again on re-size of the window */ addPaintListener(new PaintListener() { @Override public void paintControl(PaintEvent e) { parent.layout(); } }); clusterListener = new DefaultClusterListener() { @Override public void volumeChanged(Volume volume, Event event) { super.volumeChanged(volume, event); switch (event.getEventType()) { case VOLUME_OPTIONS_RESET: if (!tableViewer.getControl().isDisposed()) { + //While reseting the options, clear the filter text before refreshing the tree + filterText.setText(""); tableViewer.refresh(); setAddButtonsEnabled(true); } break; case VOLUME_OPTION_SET: String key = (String)event.getEventData(); if (isNewOption(volume, key)) { // option has been set successfully by the user. re-enable the add button and search filter // textbox setAddButtonsEnabled(true); filterText.setEnabled(true); } if (defaultVolumeOptions.size() == volume.getOptions().size()) { setAddButtonsEnabled(false); } tableViewer.refresh(); break; case VOLUME_CHANGED: tableViewer.refresh(); if(volume.getOptions().size() == defaultVolumeOptions.size()) { setAddButtonsEnabled(false); } else { setAddButtonsEnabled(true); } default: break; } } private boolean isNewOption(Volume volume, String optionKey) { if (filterText.getText().length() > 0) { // user has been filtering the contents. adding new option is allowed only when contents are NOT // filtered. Thus it's impossible that this is a newly added option return false; } // if this is the last option in the volume options, it must be the new option return optionKey.equals(volume.getOptions().getOptions().get(volume.getOptions().size() - 1).getKey()); } }; SelectionListener addButtonSelectionListener = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // add an empty option to be filled up by user volume.setOption("", ""); tableViewer.refresh(); tableViewer.setSelection(new StructuredSelection(getEntry(""))); keyColumn.getViewer().editElement(getEntry(""), 0); // edit newly created entry // disable the add button AND search filter textbox till user fills up the new option setAddButtonsEnabled(false); filterText.setEnabled(false); } private VolumeOption getEntry(String key) { for (VolumeOption entry : volume.getOptions().getOptions()) { if (entry.getKey().equals(key)) { return entry; } } return null; } }; addTopButton.addSelectionListener(addButtonSelectionListener); addBottomButton.addSelectionListener(addButtonSelectionListener); // Make sure that add button is enabled only when search filter textbox is empty filterText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (filterText.getText().length() > 0) { setAddButtonsEnabled(false); } else { if (defaultVolumeOptions.size() == volume.getOptions().size()) { setAddButtonsEnabled(false); } else { setAddButtonsEnabled(true); } } } }); GlusterDataModelManager.getInstance().addClusterListener(clusterListener); addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { toolkit.dispose(); if (!(addTopButton.isEnabled() || addBottomButton.isEnabled())) { // user has selected key, but not added value. Since this is not a valid entry, // remove the last option (without value) from the volume volume.getOptions().remove(keyEditingSupport.getEntryBeingAdded().getKey()); } GlusterDataModelManager.getInstance().removeClusterListener(clusterListener); } }); } private void setupPageLayout() { final GridLayout layout = new GridLayout(2, false); layout.verticalSpacing = 10; layout.marginTop = 10; setLayout(layout); } private void setupOptionsTable(Composite parent) { Table table = tableViewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); TableColumnLayout tableColumnLayout = createTableColumnLayout(); parent.setLayout(tableColumnLayout); setColumnProperties(table, OPTIONS_TABLE_COLUMN_INDICES.OPTION_KEY, SWT.CENTER, 100); setColumnProperties(table, OPTIONS_TABLE_COLUMN_INDICES.OPTION_VALUE, SWT.CENTER, 100); } private TableColumnLayout createTableColumnLayout() { TableColumnLayout tableColumnLayout = new TableColumnLayout(); ColumnLayoutData defaultColumnLayoutData = new ColumnWeightData(100); tableColumnLayout.setColumnData(createKeyColumn(), defaultColumnLayoutData); tableColumnLayout.setColumnData(createValueColumn(), defaultColumnLayoutData); return tableColumnLayout; } private TableColumn createValueColumn() { TableViewerColumn valueColumn = new TableViewerColumn(tableViewer, SWT.NONE); valueColumn.getColumn() .setText(OPTIONS_TABLE_COLUMN_NAMES[OPTIONS_TABLE_COLUMN_INDICES.OPTION_VALUE.ordinal()]); valueColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { return ((VolumeOption) element).getValue(); } }); // User can edit value of a volume option valueColumn.setEditingSupport(new OptionValueEditingSupport(valueColumn.getViewer(), volume)); return valueColumn.getColumn(); } private TableColumn createKeyColumn() { keyColumn = new TableViewerColumn(tableViewer, SWT.NONE); keyColumn.getColumn().setText(OPTIONS_TABLE_COLUMN_NAMES[OPTIONS_TABLE_COLUMN_INDICES.OPTION_KEY.ordinal()]); keyColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { return ((VolumeOption) element).getKey(); } @Override public String getToolTipText(Object element) { String key = ((VolumeOption) element).getKey(); if (key.isEmpty()) { return "Click to select a volume option key"; } VolumeOptionInfo optionInfo = GlusterDataModelManager.getInstance().getVolumeOptionInfo(key); // Wrap the description before adding to tooltip so that long descriptions are displayed properly return WordUtils.wrap(optionInfo.getDescription(), 60) + CoreConstants.NEWLINE + "Default value: " + optionInfo.getDefaultValue(); } }); // Editing support required when adding new key keyEditingSupport = new OptionKeyEditingSupport(keyColumn.getViewer(), volume); keyColumn.setEditingSupport(keyEditingSupport); return keyColumn.getColumn(); } private void createOptionsTableViewer(Composite parent) { tableViewer = new TableViewer(parent, SWT.FLAT | SWT.FULL_SELECTION | SWT.SINGLE); tableViewer.setLabelProvider(new VolumeOptionsTableLabelProvider()); tableViewer.setContentProvider(new VolumeOptionsContentProvider()); tableViewer.getTable().setLinesVisible(true); setupOptionsTable(parent); } private Composite createTableViewerComposite() { Composite tableViewerComposite = new Composite(this, SWT.NO); tableViewerComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true); layoutData.horizontalSpan = 2; tableViewerComposite.setLayoutData(layoutData); return tableViewerComposite; } private void setupOptionsTableViewer(final Text filterText) { Composite tableViewerComposite = createTableViewerComposite(); createOptionsTableViewer(tableViewerComposite); ColumnViewerToolTipSupport.enableFor(tableViewer); // Create a case insensitive filter for the table viewer using the filter text field guiHelper.createFilter(tableViewer, filterText, false); } private void setColumnProperties(Table table, OPTIONS_TABLE_COLUMN_INDICES columnIndex, int alignment, int weight) { TableColumn column = table.getColumn(columnIndex.ordinal()); column.setAlignment(alignment); TableColumnLayout tableColumnLayout = (TableColumnLayout) table.getParent().getLayout(); tableColumnLayout.setColumnData(column, new ColumnWeightData(weight)); } }
true
true
private void registerListeners(final Composite parent) { /** * Ideally not required. However the table viewer is not getting laid out properly on performing * "maximize + restore" So this is a hack to make sure that the table is laid out again on re-size of the window */ addPaintListener(new PaintListener() { @Override public void paintControl(PaintEvent e) { parent.layout(); } }); clusterListener = new DefaultClusterListener() { @Override public void volumeChanged(Volume volume, Event event) { super.volumeChanged(volume, event); switch (event.getEventType()) { case VOLUME_OPTIONS_RESET: if (!tableViewer.getControl().isDisposed()) { tableViewer.refresh(); setAddButtonsEnabled(true); } break; case VOLUME_OPTION_SET: String key = (String)event.getEventData(); if (isNewOption(volume, key)) { // option has been set successfully by the user. re-enable the add button and search filter // textbox setAddButtonsEnabled(true); filterText.setEnabled(true); } if (defaultVolumeOptions.size() == volume.getOptions().size()) { setAddButtonsEnabled(false); } tableViewer.refresh(); break; case VOLUME_CHANGED: tableViewer.refresh(); if(volume.getOptions().size() == defaultVolumeOptions.size()) { setAddButtonsEnabled(false); } else { setAddButtonsEnabled(true); } default: break; } } private boolean isNewOption(Volume volume, String optionKey) { if (filterText.getText().length() > 0) { // user has been filtering the contents. adding new option is allowed only when contents are NOT // filtered. Thus it's impossible that this is a newly added option return false; } // if this is the last option in the volume options, it must be the new option return optionKey.equals(volume.getOptions().getOptions().get(volume.getOptions().size() - 1).getKey()); } }; SelectionListener addButtonSelectionListener = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // add an empty option to be filled up by user volume.setOption("", ""); tableViewer.refresh(); tableViewer.setSelection(new StructuredSelection(getEntry(""))); keyColumn.getViewer().editElement(getEntry(""), 0); // edit newly created entry // disable the add button AND search filter textbox till user fills up the new option setAddButtonsEnabled(false); filterText.setEnabled(false); } private VolumeOption getEntry(String key) { for (VolumeOption entry : volume.getOptions().getOptions()) { if (entry.getKey().equals(key)) { return entry; } } return null; } }; addTopButton.addSelectionListener(addButtonSelectionListener); addBottomButton.addSelectionListener(addButtonSelectionListener); // Make sure that add button is enabled only when search filter textbox is empty filterText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (filterText.getText().length() > 0) { setAddButtonsEnabled(false); } else { if (defaultVolumeOptions.size() == volume.getOptions().size()) { setAddButtonsEnabled(false); } else { setAddButtonsEnabled(true); } } } }); GlusterDataModelManager.getInstance().addClusterListener(clusterListener); addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { toolkit.dispose(); if (!(addTopButton.isEnabled() || addBottomButton.isEnabled())) { // user has selected key, but not added value. Since this is not a valid entry, // remove the last option (without value) from the volume volume.getOptions().remove(keyEditingSupport.getEntryBeingAdded().getKey()); } GlusterDataModelManager.getInstance().removeClusterListener(clusterListener); } }); }
private void registerListeners(final Composite parent) { /** * Ideally not required. However the table viewer is not getting laid out properly on performing * "maximize + restore" So this is a hack to make sure that the table is laid out again on re-size of the window */ addPaintListener(new PaintListener() { @Override public void paintControl(PaintEvent e) { parent.layout(); } }); clusterListener = new DefaultClusterListener() { @Override public void volumeChanged(Volume volume, Event event) { super.volumeChanged(volume, event); switch (event.getEventType()) { case VOLUME_OPTIONS_RESET: if (!tableViewer.getControl().isDisposed()) { //While reseting the options, clear the filter text before refreshing the tree filterText.setText(""); tableViewer.refresh(); setAddButtonsEnabled(true); } break; case VOLUME_OPTION_SET: String key = (String)event.getEventData(); if (isNewOption(volume, key)) { // option has been set successfully by the user. re-enable the add button and search filter // textbox setAddButtonsEnabled(true); filterText.setEnabled(true); } if (defaultVolumeOptions.size() == volume.getOptions().size()) { setAddButtonsEnabled(false); } tableViewer.refresh(); break; case VOLUME_CHANGED: tableViewer.refresh(); if(volume.getOptions().size() == defaultVolumeOptions.size()) { setAddButtonsEnabled(false); } else { setAddButtonsEnabled(true); } default: break; } } private boolean isNewOption(Volume volume, String optionKey) { if (filterText.getText().length() > 0) { // user has been filtering the contents. adding new option is allowed only when contents are NOT // filtered. Thus it's impossible that this is a newly added option return false; } // if this is the last option in the volume options, it must be the new option return optionKey.equals(volume.getOptions().getOptions().get(volume.getOptions().size() - 1).getKey()); } }; SelectionListener addButtonSelectionListener = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // add an empty option to be filled up by user volume.setOption("", ""); tableViewer.refresh(); tableViewer.setSelection(new StructuredSelection(getEntry(""))); keyColumn.getViewer().editElement(getEntry(""), 0); // edit newly created entry // disable the add button AND search filter textbox till user fills up the new option setAddButtonsEnabled(false); filterText.setEnabled(false); } private VolumeOption getEntry(String key) { for (VolumeOption entry : volume.getOptions().getOptions()) { if (entry.getKey().equals(key)) { return entry; } } return null; } }; addTopButton.addSelectionListener(addButtonSelectionListener); addBottomButton.addSelectionListener(addButtonSelectionListener); // Make sure that add button is enabled only when search filter textbox is empty filterText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (filterText.getText().length() > 0) { setAddButtonsEnabled(false); } else { if (defaultVolumeOptions.size() == volume.getOptions().size()) { setAddButtonsEnabled(false); } else { setAddButtonsEnabled(true); } } } }); GlusterDataModelManager.getInstance().addClusterListener(clusterListener); addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { toolkit.dispose(); if (!(addTopButton.isEnabled() || addBottomButton.isEnabled())) { // user has selected key, but not added value. Since this is not a valid entry, // remove the last option (without value) from the volume volume.getOptions().remove(keyEditingSupport.getEntryBeingAdded().getKey()); } GlusterDataModelManager.getInstance().removeClusterListener(clusterListener); } }); }
diff --git a/src/de/uni_koblenz/jgralab/impl/IncidentGraphElementIterable.java b/src/de/uni_koblenz/jgralab/impl/IncidentGraphElementIterable.java index 5bfe131b..a93162cc 100644 --- a/src/de/uni_koblenz/jgralab/impl/IncidentGraphElementIterable.java +++ b/src/de/uni_koblenz/jgralab/impl/IncidentGraphElementIterable.java @@ -1,159 +1,158 @@ /* * JGraLab - The Java Graph Laboratory * * Copyright (C) 2006-2010 Institute for Software Technology * University of Koblenz-Landau, Germany * [email protected] * * 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>. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining * it with Eclipse (or a modified version of that program or an Eclipse * plugin), containing parts covered by the terms of the Eclipse Public * License (EPL), the licensors of this Program grant you additional * permission to convey the resulting work. Corresponding Source for a * non-source form of such a combination shall include the source code for * the parts of JGraLab used as well as that of the covered work. */ package de.uni_koblenz.jgralab.impl; import java.util.ConcurrentModificationException; import java.util.Iterator; import de.uni_koblenz.jgralab.Direction; import de.uni_koblenz.jgralab.GraphElement; import de.uni_koblenz.jgralab.Incidence; import de.uni_koblenz.jgralab.schema.GraphElementClass; /** * This class provides an {@link Iterable} for the incident {@link GraphElement} * s at a given {@link GraphElement}. * * @author [email protected] */ public abstract class IncidentGraphElementIterable<G extends GraphElement<?, ?>> implements Iterable<G> { /** * This class provides an {@link Iterator} for the incident * {@link GraphElement}s at a given {@link GraphElement}. * * @author [email protected] * */ abstract class IncidentGraphElementIterator implements Iterator<G> { /** * The current {@link Incidence}. */ protected Incidence current = null; /** * {@link GraphElement} which incident {@link GraphElement}s are * iterated. */ protected GraphElement<?, ?> graphElement = null; /** * The {@link Class} of the desired incident {@link GraphElement}s. */ protected Class<? extends GraphElement<?, ?>> gc; /** * {@link Direction} of the desired incident {@link GraphElement}s. */ protected Direction dir; /** * The version of the incidence list of the {@link GraphElement} at the * beginning of the iteration. This information is used to check if the * incidence list has changed. The failfast-{@link Iterator} will throw * an {@link ConcurrentModificationException} if the {@link #hasNext()} * or {@link #next()} is called. */ protected long incidenceListVersion; /** * Creates an {@link Iterator} over the {@link Incidence}s of * <code>graphElement</code>. * * @param graphElement * {@link GraphElement} which {@link Incidence}s should be * iterated. * @param gc * {@link Class} only instances of this class are returned. * @param dir * {@link Direction} of the desired {@link Incidence}s. */ - public <G1, G2> IncidentGraphElementIterator( - GraphElement<G1, G2> graphElement, - Class<? extends GraphElement<G1, G2>> gc, Direction dir) { + public IncidentGraphElementIterator(GraphElement<?, ?> graphElement, + Class<? extends GraphElement<?, ?>> gc, Direction dir) { this.graphElement = graphElement; this.gc = gc; this.dir = dir; - incidenceListVersion = ((GraphElementImpl<G1, G2>) graphElement) + incidenceListVersion = ((GraphElementImpl<?, ?>) graphElement) .getIncidenceListVersion(); current = graphElement.getFirstIncidence(dir); } @Override public boolean hasNext() { checkConcurrentModification(); return current != null; } /** * Checks if the sequence of {@link Incidence}s was modified. In this * case a {@link ConcurrentModificationException} is thrown * * @throws ConcurrentModificationException */ protected void checkConcurrentModification() { if (((GraphElementImpl<?, ?>) graphElement) .isIncidenceListModified(incidenceListVersion)) { throw new ConcurrentModificationException( "The incidence list of the GraphElement has been modified - the iterator is not longer valid"); } } /** * Sets {@link #current} to the next {@link Incidence} which is * connected to an {@link GraphElement} different from * {@link #graphElement} and of {@link GraphElementClass} {@link #gc}. * If such an element does not exist {@link #current} is set to * <code>null</code>. */ protected abstract void setCurrentToNextIncidentGraphElement(); @Override public void remove() { throw new UnsupportedOperationException( "Cannot remove GraphElements using Iterator"); } } /** * The current {@link Iterator}. */ protected IncidentGraphElementIterator iter = null; @Override public Iterator<G> iterator() { return iter; } }
false
true
public <G1, G2> IncidentGraphElementIterator( GraphElement<G1, G2> graphElement, Class<? extends GraphElement<G1, G2>> gc, Direction dir) { this.graphElement = graphElement; this.gc = gc; this.dir = dir; incidenceListVersion = ((GraphElementImpl<G1, G2>) graphElement) .getIncidenceListVersion(); current = graphElement.getFirstIncidence(dir); }
public IncidentGraphElementIterator(GraphElement<?, ?> graphElement, Class<? extends GraphElement<?, ?>> gc, Direction dir) { this.graphElement = graphElement; this.gc = gc; this.dir = dir; incidenceListVersion = ((GraphElementImpl<?, ?>) graphElement) .getIncidenceListVersion(); current = graphElement.getFirstIncidence(dir); }
diff --git a/src/com/tulskiy/musique/audio/AudioFileReader.java b/src/com/tulskiy/musique/audio/AudioFileReader.java index 2055939..bcacab9 100755 --- a/src/com/tulskiy/musique/audio/AudioFileReader.java +++ b/src/com/tulskiy/musique/audio/AudioFileReader.java @@ -1,126 +1,130 @@ /* * Copyright (c) 2008, 2009, 2010, 2011 Denis Tulskiy * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * version 3 along with this work. If not, see <http://www.gnu.org/licenses/>. */ package com.tulskiy.musique.audio; import com.tulskiy.musique.audio.formats.cue.CUEParser; import com.tulskiy.musique.playlist.Track; import com.tulskiy.musique.playlist.TrackData; import org.jaudiotagger.audio.generic.GenericAudioHeader; import org.jaudiotagger.tag.KeyNotFoundException; import org.jaudiotagger.tag.Tag; import org.jaudiotagger.tag.TagField; import org.jaudiotagger.tag.TagFieldKey; import java.io.File; import java.io.IOException; import java.io.LineNumberReader; import java.io.StringReader; import java.nio.charset.Charset; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * @Author: Denis Tulskiy * @Date: 25.06.2009 */ public abstract class AudioFileReader { private static CUEParser cueParser; protected static Charset defaultCharset = Charset.forName("iso8859-1"); protected final Logger logger = Logger.getLogger("musique"); public void read(File file, List<Track> list) { logger.log(Level.FINEST, "Reading file : {0}", file); Track track = read(file); String cueSheet = track.getTrackData().getCueSheet(); if (cueSheet != null && cueSheet.length() > 0) { if (cueParser == null) cueParser = new CUEParser(); LineNumberReader reader = new LineNumberReader(new StringReader(cueSheet)); cueParser.parse(list, track, reader, true); } else { list.add(track); } } protected abstract Track readSingle(Track track); public Track reload(Track track) { Track res = readSingle(track); if (res.getTrackData().isFile()) res.getTrackData().setLastModified(res.getTrackData().getFile().lastModified()); return res; } public Track read(File file) { Track track = new Track(); track.getTrackData().setLocation(file.toURI().toString()); return reload(track); } public abstract boolean isFileSupported(String ext); protected void copyCommonTagFields(Tag tag, Track track) throws IOException { TrackData trackData = track.getTrackData(); if (tag != null && track != null) { for (TagFieldKey key : TagFieldKey.values()) { List<TagField> fields; try { fields = tag.get(key); } - catch (KeyNotFoundException e) { + catch (KeyNotFoundException knfe) { // TODO review continue; } + catch (NullPointerException npe) { + // TODO review workaround for mp4tag (throws nullpointer if no mapping found for generic key) + continue; + } for (TagField field : fields) { track.getTrackData().addTagFieldValues(key, field.toString()); } } // TODO think about the way trackData.setCueSheet(tag.getFirst("CUESHEET")); } } protected void copySpecificTagFields(Tag tag, Track track) { // Empty implementation, to be overridden } protected void copyHeaderFields(GenericAudioHeader header, Track track) { TrackData trackData = track.getTrackData(); if (header != null && track != null) { trackData.setChannels(header.getChannelNumber()); trackData.setTotalSamples(header.getTotalSamples()); // trackData.setTotalSamples((long) (header.getPreciseLength() * header.getSampleRateAsNumber())); trackData.setSampleRate(header.getSampleRateAsNumber()); trackData.setStartPosition(0); trackData.setCodec(header.getFormat()); trackData.setBitrate((int) header.getBitRateAsNumber()); } } public static void setDefaultCharset(Charset charset) { defaultCharset = charset; } public static Charset getDefaultCharset() { return defaultCharset; } }
false
true
protected void copyCommonTagFields(Tag tag, Track track) throws IOException { TrackData trackData = track.getTrackData(); if (tag != null && track != null) { for (TagFieldKey key : TagFieldKey.values()) { List<TagField> fields; try { fields = tag.get(key); } catch (KeyNotFoundException e) { // TODO review continue; } for (TagField field : fields) { track.getTrackData().addTagFieldValues(key, field.toString()); } } // TODO think about the way trackData.setCueSheet(tag.getFirst("CUESHEET")); } }
protected void copyCommonTagFields(Tag tag, Track track) throws IOException { TrackData trackData = track.getTrackData(); if (tag != null && track != null) { for (TagFieldKey key : TagFieldKey.values()) { List<TagField> fields; try { fields = tag.get(key); } catch (KeyNotFoundException knfe) { // TODO review continue; } catch (NullPointerException npe) { // TODO review workaround for mp4tag (throws nullpointer if no mapping found for generic key) continue; } for (TagField field : fields) { track.getTrackData().addTagFieldValues(key, field.toString()); } } // TODO think about the way trackData.setCueSheet(tag.getFirst("CUESHEET")); } }
diff --git a/src/main/java/org/maventest/App.java b/src/main/java/org/maventest/App.java index 8a316e0..e429d29 100644 --- a/src/main/java/org/maventest/App.java +++ b/src/main/java/org/maventest/App.java @@ -1,29 +1,29 @@ package org.maventest; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); } public static int largest(int[] list) { - int index, max=Integer.MAX_VALUE; + int index, max=0; if (list.length == 0) { throw new RuntimeException("Empty list"); } - for (index = 0; index < list.length-1; index++) { + for (index = 0; index < list.length; index++) { if (list[index] > max) { max = list[index]; } } return max; } }
false
true
public static int largest(int[] list) { int index, max=Integer.MAX_VALUE; if (list.length == 0) { throw new RuntimeException("Empty list"); } for (index = 0; index < list.length-1; index++) { if (list[index] > max) { max = list[index]; } } return max; }
public static int largest(int[] list) { int index, max=0; if (list.length == 0) { throw new RuntimeException("Empty list"); } for (index = 0; index < list.length; index++) { if (list[index] > max) { max = list[index]; } } return max; }
diff --git a/ProcessorCore/src/main/java/de/plushnikov/intellij/lombok/processor/clazz/log/AbstractLogProcessor.java b/ProcessorCore/src/main/java/de/plushnikov/intellij/lombok/processor/clazz/log/AbstractLogProcessor.java index 9243927..1ead23b 100644 --- a/ProcessorCore/src/main/java/de/plushnikov/intellij/lombok/processor/clazz/log/AbstractLogProcessor.java +++ b/ProcessorCore/src/main/java/de/plushnikov/intellij/lombok/processor/clazz/log/AbstractLogProcessor.java @@ -1,67 +1,72 @@ package de.plushnikov.intellij.lombok.processor.clazz.log; import com.intellij.openapi.project.Project; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiAnnotation; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiField; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiModifier; import com.intellij.psi.PsiType; import com.intellij.psi.impl.light.LightElement; import de.plushnikov.intellij.lombok.processor.clazz.AbstractLombokClassProcessor; import de.plushnikov.intellij.lombok.psi.MyLightFieldBuilder; import org.jetbrains.annotations.NotNull; import java.util.List; /** * Base lombok processor class for logger processing * * @author Plushnikov Michail */ public abstract class AbstractLogProcessor extends AbstractLombokClassProcessor { private final static String loggerName = "log"; private final String loggerType; private final String loggerInitializer;//TODO add Initializer support protected AbstractLogProcessor(@NotNull String supportedAnnotation, @NotNull String loggerType, @NotNull String loggerInitializer) { super(supportedAnnotation, PsiField.class); this.loggerType = loggerType; this.loggerInitializer = loggerInitializer; } public <Psi extends PsiElement> void process(@NotNull PsiClass psiClass, @NotNull PsiMethod[] classMethods, @NotNull PsiAnnotation psiAnnotation, @NotNull List<Psi> target) { + if (psiClass.isInterface() || psiClass.isAnnotationType()) { + //TODO create warning in code + //Logger Injection is not possible on interface or annotation types + return; + } if (!hasFieldByName(psiClass, loggerName)) { Project project = psiClass.getProject(); PsiManager manager = psiClass.getContainingFile().getManager(); PsiType psiLoggerType = JavaPsiFacade.getElementFactory(project).createTypeFromText(loggerType, psiClass); LightElement loggerField = new MyLightFieldBuilder(manager, loggerName, psiLoggerType) .setHasInitializer(true) .setContainingClass(psiClass) - .setModifiers(PsiModifier.FINAL, PsiModifier.STATIC, PsiModifier.PUBLIC) + .setModifiers(PsiModifier.FINAL, PsiModifier.STATIC, PsiModifier.PRIVATE) .setNavigationElement(psiAnnotation); target.add((Psi) loggerField); } else { //TODO create warning in code //Not generating fieldName(): A field with that name already exists } } protected boolean hasFieldByName(@NotNull PsiClass psiClass, String... fieldNames) { final PsiField[] psiFields = collectClassFieldsIntern(psiClass); for (PsiField psiField : psiFields) { for (String fieldName : fieldNames) { if (psiField.getName().equals(fieldName)) { return true; } } } return false; } }
false
true
public <Psi extends PsiElement> void process(@NotNull PsiClass psiClass, @NotNull PsiMethod[] classMethods, @NotNull PsiAnnotation psiAnnotation, @NotNull List<Psi> target) { if (!hasFieldByName(psiClass, loggerName)) { Project project = psiClass.getProject(); PsiManager manager = psiClass.getContainingFile().getManager(); PsiType psiLoggerType = JavaPsiFacade.getElementFactory(project).createTypeFromText(loggerType, psiClass); LightElement loggerField = new MyLightFieldBuilder(manager, loggerName, psiLoggerType) .setHasInitializer(true) .setContainingClass(psiClass) .setModifiers(PsiModifier.FINAL, PsiModifier.STATIC, PsiModifier.PUBLIC) .setNavigationElement(psiAnnotation); target.add((Psi) loggerField); } else { //TODO create warning in code //Not generating fieldName(): A field with that name already exists } }
public <Psi extends PsiElement> void process(@NotNull PsiClass psiClass, @NotNull PsiMethod[] classMethods, @NotNull PsiAnnotation psiAnnotation, @NotNull List<Psi> target) { if (psiClass.isInterface() || psiClass.isAnnotationType()) { //TODO create warning in code //Logger Injection is not possible on interface or annotation types return; } if (!hasFieldByName(psiClass, loggerName)) { Project project = psiClass.getProject(); PsiManager manager = psiClass.getContainingFile().getManager(); PsiType psiLoggerType = JavaPsiFacade.getElementFactory(project).createTypeFromText(loggerType, psiClass); LightElement loggerField = new MyLightFieldBuilder(manager, loggerName, psiLoggerType) .setHasInitializer(true) .setContainingClass(psiClass) .setModifiers(PsiModifier.FINAL, PsiModifier.STATIC, PsiModifier.PRIVATE) .setNavigationElement(psiAnnotation); target.add((Psi) loggerField); } else { //TODO create warning in code //Not generating fieldName(): A field with that name already exists } }
diff --git a/src/main/java/org/threeten/bp/format/DateTimePrintContext.java b/src/main/java/org/threeten/bp/format/DateTimePrintContext.java index e607b71a..12b746ac 100644 --- a/src/main/java/org/threeten/bp/format/DateTimePrintContext.java +++ b/src/main/java/org/threeten/bp/format/DateTimePrintContext.java @@ -1,288 +1,291 @@ /* * Copyright (c) 2007-2013, Stephen Colebourne & Michael Nascimento Santos * * 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 JSR-310 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 OWNER 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.threeten.bp.format; import static org.threeten.bp.temporal.ChronoField.EPOCH_DAY; import static org.threeten.bp.temporal.ChronoField.INSTANT_SECONDS; import java.util.Locale; import java.util.Objects; import org.threeten.bp.DateTimeException; import org.threeten.bp.Instant; import org.threeten.bp.ZoneId; import org.threeten.bp.chrono.Chronology; import org.threeten.bp.chrono.ChronoLocalDate; import org.threeten.bp.jdk8.DefaultInterfaceTemporalAccessor; import org.threeten.bp.temporal.ChronoField; import org.threeten.bp.temporal.TemporalAccessor; import org.threeten.bp.temporal.TemporalField; import org.threeten.bp.temporal.TemporalQueries; import org.threeten.bp.temporal.TemporalQuery; import org.threeten.bp.temporal.ValueRange; /** * Context object used during date and time printing. * <p> * This class provides a single wrapper to items used in the print. * * <h3>Specification for implementors</h3> * This class is a mutable context intended for use from a single thread. * Usage of the class is thread-safe within standard printing as the framework creates * a new instance of the class for each print and printing is single-threaded. */ final class DateTimePrintContext { /** * The temporal being output. */ private TemporalAccessor temporal; /** * The locale, not null. */ private Locale locale; /** * The symbols, not null. */ private DateTimeFormatSymbols symbols; /** * Whether the current formatter is optional. */ private int optional; /** * Creates a new instance of the context. * * @param temporal the temporal object being output, not null * @param formatter the formatter controlling the print, not null */ DateTimePrintContext(TemporalAccessor temporal, DateTimeFormatter formatter) { super(); this.temporal = adjust(temporal, formatter); this.locale = formatter.getLocale(); this.symbols = formatter.getSymbols(); } // for testing DateTimePrintContext(TemporalAccessor temporal, Locale locale, DateTimeFormatSymbols symbols) { this.temporal = temporal; this.locale = locale; this.symbols = symbols; } private static TemporalAccessor adjust(final TemporalAccessor temporal, DateTimeFormatter formatter) { // normal case first Chronology overrideChrono = formatter.getChronology(); ZoneId overrideZone = formatter.getZone(); if (overrideChrono == null && overrideZone == null) { return temporal; } // ensure minimal change Chronology temporalChrono = Chronology.from(temporal); // default to ISO, handles Instant ZoneId temporalZone = temporal.query(TemporalQueries.zone()); // zone then offset, handles OffsetDateTime if (temporal.isSupported(EPOCH_DAY) == false || Objects.equals(overrideChrono, temporalChrono)) { overrideChrono = null; } if (temporal.isSupported(INSTANT_SECONDS) == false || Objects.equals(overrideZone, temporalZone)) { overrideZone = null; } if (overrideChrono == null && overrideZone == null) { return temporal; } // make adjustment if (overrideChrono != null && overrideZone != null) { return overrideChrono.zonedDateTime(Instant.from(temporal), overrideZone); } else if (overrideZone != null) { return temporalChrono.zonedDateTime(Instant.from(temporal), overrideZone); } else { // overrideChrono != null // need class here to handle non-standard cases like OffsetDate final ChronoLocalDate<?> date = overrideChrono.date(temporal); return new DefaultInterfaceTemporalAccessor() { @Override public boolean isSupported(TemporalField field) { return temporal.isSupported(field); } @Override public ValueRange range(TemporalField field) { if (field instanceof ChronoField) { if (((ChronoField) field).isDateField()) { return date.range(field); } else { return temporal.range(field); } } return field.rangeRefinedBy(this); } @Override public long getLong(TemporalField field) { if (field instanceof ChronoField) { if (((ChronoField) field).isDateField()) { return date.getLong(field); } else { return temporal.getLong(field); } } return field.getFrom(this); } @Override public <R> R query(TemporalQuery<R> query) { - if (query == TemporalQueries.zoneId() || query == TemporalQueries.chronology() || query == TemporalQueries.precision()) { + if (query == TemporalQueries.chronology()) { + return (R) date.getChronology(); + } + if (query == TemporalQueries.zoneId() || query == TemporalQueries.precision()) { return temporal.query(query); } return query.queryFrom(this); } }; } } //----------------------------------------------------------------------- /** * Gets the temporal object being output. * * @return the temporal object, not null */ TemporalAccessor getTemporal() { return temporal; } /** * Gets the locale. * <p> * This locale is used to control localization in the print output except * where localization is controlled by the symbols. * * @return the locale, not null */ Locale getLocale() { return locale; } /** * Gets the formatting symbols. * <p> * The symbols control the localization of numeric output. * * @return the formatting symbols, not null */ DateTimeFormatSymbols getSymbols() { return symbols; } //----------------------------------------------------------------------- /** * Starts the printing of an optional segment of the input. */ void startOptional() { this.optional++; } /** * Ends the printing of an optional segment of the input. */ void endOptional() { this.optional--; } /** * Gets a value using a query. * * @param query the query to use, not null * @return the result, null if not found and optional is true * @throws DateTimeException if the type is not available and the section is not optional */ <R> R getValue(TemporalQuery<R> query) { R result = temporal.query(query); if (result == null && optional == 0) { throw new DateTimeException("Unable to extract value: " + temporal.getClass()); } return result; } /** * Gets the value of the specified field. * <p> * This will return the value for the specified field. * * @param field the field to find, not null * @return the value, null if not found and optional is true * @throws DateTimeException if the field is not available and the section is not optional */ Long getValue(TemporalField field) { try { return temporal.getLong(field); } catch (DateTimeException ex) { if (optional > 0) { return null; } throw ex; } } //----------------------------------------------------------------------- /** * Returns a string version of the context for debugging. * * @return a string representation of the context, not null */ @Override public String toString() { return temporal.toString(); } //------------------------------------------------------------------------- // for testing /** * Sets the date-time being output. * * @param temporal the date-time object, not null */ void setDateTime(TemporalAccessor temporal) { Objects.requireNonNull(temporal, "temporal"); this.temporal = temporal; } /** * Sets the locale. * <p> * This locale is used to control localization in the print output except * where localization is controlled by the symbols. * * @param locale the locale, not null */ void setLocale(Locale locale) { Objects.requireNonNull(locale, "locale"); this.locale = locale; } }
true
true
private static TemporalAccessor adjust(final TemporalAccessor temporal, DateTimeFormatter formatter) { // normal case first Chronology overrideChrono = formatter.getChronology(); ZoneId overrideZone = formatter.getZone(); if (overrideChrono == null && overrideZone == null) { return temporal; } // ensure minimal change Chronology temporalChrono = Chronology.from(temporal); // default to ISO, handles Instant ZoneId temporalZone = temporal.query(TemporalQueries.zone()); // zone then offset, handles OffsetDateTime if (temporal.isSupported(EPOCH_DAY) == false || Objects.equals(overrideChrono, temporalChrono)) { overrideChrono = null; } if (temporal.isSupported(INSTANT_SECONDS) == false || Objects.equals(overrideZone, temporalZone)) { overrideZone = null; } if (overrideChrono == null && overrideZone == null) { return temporal; } // make adjustment if (overrideChrono != null && overrideZone != null) { return overrideChrono.zonedDateTime(Instant.from(temporal), overrideZone); } else if (overrideZone != null) { return temporalChrono.zonedDateTime(Instant.from(temporal), overrideZone); } else { // overrideChrono != null // need class here to handle non-standard cases like OffsetDate final ChronoLocalDate<?> date = overrideChrono.date(temporal); return new DefaultInterfaceTemporalAccessor() { @Override public boolean isSupported(TemporalField field) { return temporal.isSupported(field); } @Override public ValueRange range(TemporalField field) { if (field instanceof ChronoField) { if (((ChronoField) field).isDateField()) { return date.range(field); } else { return temporal.range(field); } } return field.rangeRefinedBy(this); } @Override public long getLong(TemporalField field) { if (field instanceof ChronoField) { if (((ChronoField) field).isDateField()) { return date.getLong(field); } else { return temporal.getLong(field); } } return field.getFrom(this); } @Override public <R> R query(TemporalQuery<R> query) { if (query == TemporalQueries.zoneId() || query == TemporalQueries.chronology() || query == TemporalQueries.precision()) { return temporal.query(query); } return query.queryFrom(this); } }; } }
private static TemporalAccessor adjust(final TemporalAccessor temporal, DateTimeFormatter formatter) { // normal case first Chronology overrideChrono = formatter.getChronology(); ZoneId overrideZone = formatter.getZone(); if (overrideChrono == null && overrideZone == null) { return temporal; } // ensure minimal change Chronology temporalChrono = Chronology.from(temporal); // default to ISO, handles Instant ZoneId temporalZone = temporal.query(TemporalQueries.zone()); // zone then offset, handles OffsetDateTime if (temporal.isSupported(EPOCH_DAY) == false || Objects.equals(overrideChrono, temporalChrono)) { overrideChrono = null; } if (temporal.isSupported(INSTANT_SECONDS) == false || Objects.equals(overrideZone, temporalZone)) { overrideZone = null; } if (overrideChrono == null && overrideZone == null) { return temporal; } // make adjustment if (overrideChrono != null && overrideZone != null) { return overrideChrono.zonedDateTime(Instant.from(temporal), overrideZone); } else if (overrideZone != null) { return temporalChrono.zonedDateTime(Instant.from(temporal), overrideZone); } else { // overrideChrono != null // need class here to handle non-standard cases like OffsetDate final ChronoLocalDate<?> date = overrideChrono.date(temporal); return new DefaultInterfaceTemporalAccessor() { @Override public boolean isSupported(TemporalField field) { return temporal.isSupported(field); } @Override public ValueRange range(TemporalField field) { if (field instanceof ChronoField) { if (((ChronoField) field).isDateField()) { return date.range(field); } else { return temporal.range(field); } } return field.rangeRefinedBy(this); } @Override public long getLong(TemporalField field) { if (field instanceof ChronoField) { if (((ChronoField) field).isDateField()) { return date.getLong(field); } else { return temporal.getLong(field); } } return field.getFrom(this); } @Override public <R> R query(TemporalQuery<R> query) { if (query == TemporalQueries.chronology()) { return (R) date.getChronology(); } if (query == TemporalQueries.zoneId() || query == TemporalQueries.precision()) { return temporal.query(query); } return query.queryFrom(this); } }; } }
diff --git a/src/main/java/org/dynjs/runtime/modules/JavaClassModuleProvider.java b/src/main/java/org/dynjs/runtime/modules/JavaClassModuleProvider.java index bf32d227..f5cc1f00 100644 --- a/src/main/java/org/dynjs/runtime/modules/JavaClassModuleProvider.java +++ b/src/main/java/org/dynjs/runtime/modules/JavaClassModuleProvider.java @@ -1,90 +1,90 @@ package org.dynjs.runtime.modules; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.dynjs.exception.InvalidModuleException; import org.dynjs.runtime.DynJS; import org.dynjs.runtime.ExecutionContext; import org.dynjs.runtime.GlobalObject; import org.dynjs.runtime.JSFunction; import org.dynjs.runtime.JSObject; import org.dynjs.runtime.PropertyDescriptor; import org.dynjs.runtime.PropertyDescriptor.Names; public class JavaClassModuleProvider extends ModuleProvider { public void addModule(Object module) throws InvalidModuleException { Module moduleAnno = module.getClass().getAnnotation(Module.class); if (moduleAnno == null) { throw new InvalidModuleException(module, "No @Module annotation"); } String moduleName = moduleAnno.name(); if (moduleName == null) { throw new InvalidModuleException(module, "Name not specified in @Module"); } modules.put(moduleName, module); } @Override public boolean load(DynJS runtime, ExecutionContext context, String moduleName) { Object javaModule = modules.get(moduleName); if (javaModule == null) { return false; } try { buildExports(context, moduleName, javaModule); return true; } catch (IllegalAccessException e) { return false; } } private JSObject buildExports(ExecutionContext context, String moduleName, Object javaModule) throws IllegalAccessException { Method[] methods = javaModule.getClass().getMethods(); - JSObject module = (JSObject) context.getGlobalObject().get("module"); - JSObject exports = (JSObject) module.get(null, "exports"); + JSObject module = (JSObject) context.getVariableEnvironment().getRecord().getBindingValue(context, "module", true); + JSObject exports = (JSObject) module.get(context, "exports"); for (Method method : methods) { Export exportAnno = method.getAnnotation(Export.class); if (exportAnno == null) { continue; } String exportName = exportAnno.name(); if ("".equals(exportName)) { exportName = method.getName(); } final JSFunction function = buildFunction(context.getGlobalObject(), javaModule, method); PropertyDescriptor desc = new PropertyDescriptor(); desc.set(Names.VALUE, function); function.setDebugContext(moduleName + "." + exportName); exports.defineOwnProperty(context, exportName, desc, false); } return exports; } private JSFunction buildFunction(GlobalObject globalObject, Object module, Method method) throws IllegalAccessException { return new JavaFunction(globalObject, module, method); } private Map<String, Object> modules = new HashMap<>(); @Override public String generateModuleID(ExecutionContext context, String moduleName) { if (modules.get(moduleName) != null) return moduleName; return null; } }
true
true
private JSObject buildExports(ExecutionContext context, String moduleName, Object javaModule) throws IllegalAccessException { Method[] methods = javaModule.getClass().getMethods(); JSObject module = (JSObject) context.getGlobalObject().get("module"); JSObject exports = (JSObject) module.get(null, "exports"); for (Method method : methods) { Export exportAnno = method.getAnnotation(Export.class); if (exportAnno == null) { continue; } String exportName = exportAnno.name(); if ("".equals(exportName)) { exportName = method.getName(); } final JSFunction function = buildFunction(context.getGlobalObject(), javaModule, method); PropertyDescriptor desc = new PropertyDescriptor(); desc.set(Names.VALUE, function); function.setDebugContext(moduleName + "." + exportName); exports.defineOwnProperty(context, exportName, desc, false); } return exports; }
private JSObject buildExports(ExecutionContext context, String moduleName, Object javaModule) throws IllegalAccessException { Method[] methods = javaModule.getClass().getMethods(); JSObject module = (JSObject) context.getVariableEnvironment().getRecord().getBindingValue(context, "module", true); JSObject exports = (JSObject) module.get(context, "exports"); for (Method method : methods) { Export exportAnno = method.getAnnotation(Export.class); if (exportAnno == null) { continue; } String exportName = exportAnno.name(); if ("".equals(exportName)) { exportName = method.getName(); } final JSFunction function = buildFunction(context.getGlobalObject(), javaModule, method); PropertyDescriptor desc = new PropertyDescriptor(); desc.set(Names.VALUE, function); function.setDebugContext(moduleName + "." + exportName); exports.defineOwnProperty(context, exportName, desc, false); } return exports; }
diff --git a/src/com/minecarts/lockdown/Lockdown.java b/src/com/minecarts/lockdown/Lockdown.java index dae71ed..1becbaf 100644 --- a/src/com/minecarts/lockdown/Lockdown.java +++ b/src/com/minecarts/lockdown/Lockdown.java @@ -1,176 +1,176 @@ package com.minecarts.lockdown; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.event.Event; import org.bukkit.event.Listener; import static org.bukkit.event.Event.Type.*; import org.bukkit.event.Event.Type; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Date; import com.minecarts.lockdown.command.MainCommand; import com.minecarts.lockdown.listener.*; public class Lockdown extends JavaPlugin { public final Logger log = Logger.getLogger("Minecraft.Lockdown"); private PluginManager pluginManager; private boolean debug = false; private List<String> requiredPlugins; private ArrayList<String> lockedPlugins = new ArrayList<String>(); private HashMap<String, Date> msgThrottle = new HashMap<String, Date>(); private MainCommand command = new MainCommand(this); public void onEnable() { try { PluginDescriptionFile pdf = getDescription(); pluginManager = getServer().getPluginManager(); - requiredPlugins = getConfig().getList("required_plugins", new ArrayList<String>()); - debug = getConfig().getBoolean("debug", false); + requiredPlugins = getConfig().getStringList("required_plugins"); + debug = getConfig().getBoolean("debug"); HashMap<Listener, Type[]> listeners = new HashMap<Listener, Type[]>(); listeners.put(new PlayerListener(this), new Type[]{ PLAYER_INTERACT, PLAYER_LOGIN }); listeners.put(new BlockListener(this), new Type[]{ BLOCK_BREAK, BLOCK_PLACE, BLOCK_IGNITE, BLOCK_BURN, BLOCK_FROMTO, BLOCK_PISTON_EXTEND, BLOCK_PISTON_RETRACT }); listeners.put(new EntityListener(this), new Type[]{ ENTITY_DAMAGE, PAINTING_PLACE, PAINTING_BREAK, ENTITY_EXPLODE, EXPLOSION_PRIME, ENDERMAN_PICKUP, ENDERMAN_PLACE }); listeners.put(new VehicleListener(this), new Type[]{ VEHICLE_COLLISION_ENTITY, VEHICLE_DAMAGE, VEHICLE_DESTROY }); for(java.util.Map.Entry<Listener, Type[]> entry : listeners.entrySet()) { for(Type type : entry.getValue()) { pluginManager.registerEvent(type, entry.getKey(), Event.Priority.Normal, this); } } //Register our command to our commandHandler getCommand("lockdown").setExecutor(command); log.info("[" + pdf.getName() + "] version " + pdf.getVersion() + " enabled."); if(getConfig().getBoolean("start_locked", true)) { lockedPlugins = new ArrayList<String>(requiredPlugins); log("Starting locked, these plugins must unlock themselves manually: " + lockedPlugins, false); } // Start a task to monitor our required plugins // Check after one second, then every 10 seconds (200 ticks) getServer().getScheduler().scheduleSyncRepeatingTask(this, new checkLoadedPlugins(), 20, 200); } catch (Error e) { log.severe("**** CRITICAL ERROR, LOCKDOWN FAILED TO LOAD CORRECTLY *****"); e.printStackTrace(); getServer().shutdown(); } catch (Exception e) { log.severe("**** CRITICAL EXCEPTION, LOCKDOWN FAILED TO LOAD CORRECTLY *****"); e.printStackTrace(); getServer().shutdown(); } } public void onDisable(){} //Repeating plugin loaded checker public class checkLoadedPlugins implements Runnable { public void run() { for(String p : requiredPlugins) { if(!pluginManager.isPluginEnabled(p) && !isLocked(p)) { lock(p, "Required plugin is not loaded or disabled."); } } //Display some helpful logging if(!lockedPlugins.isEmpty()) { log(String.format("%d/%d plugins not enabled or still locked:", lockedPlugins.size(), requiredPlugins.size())); int i = 0; for(String p : lockedPlugins){ log(String.format("\t%d. %s", ++i, p)); } } } } //External API public boolean isLocked() { return command.isLocked() || !lockedPlugins.isEmpty(); } public boolean isLocked(Plugin p) { return isLocked(p.getDescription().getName()); } public boolean isLocked(String pluginName) { return lockedPlugins.contains(pluginName); } public ArrayList<String> getLockedPlugins() { return new ArrayList<String>(lockedPlugins); } public void lock(Plugin p, String reason) { lock(p.getDescription().getName(), reason); } public void lock(String pluginName, String reason) { if(!lockedPlugins.contains(pluginName)){ lockedPlugins.add(pluginName); log(pluginName + " PLUGIN LOCK: " + reason, false); } } public void unlock(Plugin p, String reason) { unlock(p.getDescription().getName(), reason); } public void unlock(String pluginName, String reason) { if(lockedPlugins.contains(pluginName)){ lockedPlugins.remove(pluginName); log(pluginName + " plugin lock lifted: " + reason, false); } } //Internal logging and messaging public void log(String msg) { log(msg, true); } public void log(String msg, boolean debug) { if(debug && !this.debug) return; log.info("Lockdown> " + msg); } public void informPlayer(Player player) { String playerName = player.getName(); long time = new Date().getTime(); if(!this.msgThrottle.containsKey(playerName)) { this.msgThrottle.put(playerName, new Date()); notify(player); } if((time - (this.msgThrottle.get(player.getName()).getTime())) > 1000 * 3) { //every 3 seconds notify(player); this.msgThrottle.put(player.getName(), new Date()); } } private void notify(Player player) { player.sendMessage(ChatColor.GRAY + "The world is in " + ChatColor.YELLOW + "temporary lockdown mode" + ChatColor.GRAY + " while all plugins are"); player.sendMessage(ChatColor.GRAY + " properly loaded. Please try again in a few seconds."); } }
true
true
public void onEnable() { try { PluginDescriptionFile pdf = getDescription(); pluginManager = getServer().getPluginManager(); requiredPlugins = getConfig().getList("required_plugins", new ArrayList<String>()); debug = getConfig().getBoolean("debug", false); HashMap<Listener, Type[]> listeners = new HashMap<Listener, Type[]>(); listeners.put(new PlayerListener(this), new Type[]{ PLAYER_INTERACT, PLAYER_LOGIN }); listeners.put(new BlockListener(this), new Type[]{ BLOCK_BREAK, BLOCK_PLACE, BLOCK_IGNITE, BLOCK_BURN, BLOCK_FROMTO, BLOCK_PISTON_EXTEND, BLOCK_PISTON_RETRACT }); listeners.put(new EntityListener(this), new Type[]{ ENTITY_DAMAGE, PAINTING_PLACE, PAINTING_BREAK, ENTITY_EXPLODE, EXPLOSION_PRIME, ENDERMAN_PICKUP, ENDERMAN_PLACE }); listeners.put(new VehicleListener(this), new Type[]{ VEHICLE_COLLISION_ENTITY, VEHICLE_DAMAGE, VEHICLE_DESTROY }); for(java.util.Map.Entry<Listener, Type[]> entry : listeners.entrySet()) { for(Type type : entry.getValue()) { pluginManager.registerEvent(type, entry.getKey(), Event.Priority.Normal, this); } } //Register our command to our commandHandler getCommand("lockdown").setExecutor(command); log.info("[" + pdf.getName() + "] version " + pdf.getVersion() + " enabled."); if(getConfig().getBoolean("start_locked", true)) { lockedPlugins = new ArrayList<String>(requiredPlugins); log("Starting locked, these plugins must unlock themselves manually: " + lockedPlugins, false); } // Start a task to monitor our required plugins // Check after one second, then every 10 seconds (200 ticks) getServer().getScheduler().scheduleSyncRepeatingTask(this, new checkLoadedPlugins(), 20, 200); } catch (Error e) { log.severe("**** CRITICAL ERROR, LOCKDOWN FAILED TO LOAD CORRECTLY *****"); e.printStackTrace(); getServer().shutdown(); } catch (Exception e) { log.severe("**** CRITICAL EXCEPTION, LOCKDOWN FAILED TO LOAD CORRECTLY *****"); e.printStackTrace(); getServer().shutdown(); } }
public void onEnable() { try { PluginDescriptionFile pdf = getDescription(); pluginManager = getServer().getPluginManager(); requiredPlugins = getConfig().getStringList("required_plugins"); debug = getConfig().getBoolean("debug"); HashMap<Listener, Type[]> listeners = new HashMap<Listener, Type[]>(); listeners.put(new PlayerListener(this), new Type[]{ PLAYER_INTERACT, PLAYER_LOGIN }); listeners.put(new BlockListener(this), new Type[]{ BLOCK_BREAK, BLOCK_PLACE, BLOCK_IGNITE, BLOCK_BURN, BLOCK_FROMTO, BLOCK_PISTON_EXTEND, BLOCK_PISTON_RETRACT }); listeners.put(new EntityListener(this), new Type[]{ ENTITY_DAMAGE, PAINTING_PLACE, PAINTING_BREAK, ENTITY_EXPLODE, EXPLOSION_PRIME, ENDERMAN_PICKUP, ENDERMAN_PLACE }); listeners.put(new VehicleListener(this), new Type[]{ VEHICLE_COLLISION_ENTITY, VEHICLE_DAMAGE, VEHICLE_DESTROY }); for(java.util.Map.Entry<Listener, Type[]> entry : listeners.entrySet()) { for(Type type : entry.getValue()) { pluginManager.registerEvent(type, entry.getKey(), Event.Priority.Normal, this); } } //Register our command to our commandHandler getCommand("lockdown").setExecutor(command); log.info("[" + pdf.getName() + "] version " + pdf.getVersion() + " enabled."); if(getConfig().getBoolean("start_locked", true)) { lockedPlugins = new ArrayList<String>(requiredPlugins); log("Starting locked, these plugins must unlock themselves manually: " + lockedPlugins, false); } // Start a task to monitor our required plugins // Check after one second, then every 10 seconds (200 ticks) getServer().getScheduler().scheduleSyncRepeatingTask(this, new checkLoadedPlugins(), 20, 200); } catch (Error e) { log.severe("**** CRITICAL ERROR, LOCKDOWN FAILED TO LOAD CORRECTLY *****"); e.printStackTrace(); getServer().shutdown(); } catch (Exception e) { log.severe("**** CRITICAL EXCEPTION, LOCKDOWN FAILED TO LOAD CORRECTLY *****"); e.printStackTrace(); getServer().shutdown(); } }
diff --git a/services/src/main/java/org/keycloak/services/managers/TokenManager.java b/services/src/main/java/org/keycloak/services/managers/TokenManager.java index 689139e525..61ebb23504 100755 --- a/services/src/main/java/org/keycloak/services/managers/TokenManager.java +++ b/services/src/main/java/org/keycloak/services/managers/TokenManager.java @@ -1,216 +1,218 @@ package org.keycloak.services.managers; import org.jboss.resteasy.jose.Base64Url; import org.jboss.resteasy.jose.jws.JWSBuilder; import org.jboss.resteasy.jwt.JsonSerialization; import org.jboss.resteasy.logging.Logger; import org.keycloak.models.ApplicationModel; import org.keycloak.models.Constants; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserModel; import org.keycloak.representations.SkeletonKeyScope; import org.keycloak.representations.SkeletonKeyToken; import javax.ws.rs.core.MultivaluedMap; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * Stateful object that creates tokens and manages oauth access codes * * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */ public class TokenManager { protected static final Logger logger = Logger.getLogger(TokenManager.class); protected Map<String, AccessCodeEntry> accessCodeMap = new ConcurrentHashMap<String, AccessCodeEntry>(); public void clearAccessCodes() { accessCodeMap.clear(); } public AccessCodeEntry getAccessCode(String key) { return accessCodeMap.get(key); } public AccessCodeEntry pullAccessCode(String key) { return accessCodeMap.remove(key); } public AccessCodeEntry createAccessCode(String scopeParam, String state, String redirect, RealmModel realm, UserModel client, UserModel user) { boolean applicationResource = realm.hasRole(client, realm.getRole(Constants.APPLICATION_ROLE)); AccessCodeEntry code = new AccessCodeEntry(); SkeletonKeyScope scopeMap = null; if (scopeParam != null) scopeMap = decodeScope(scopeParam); List<RoleModel> realmRolesRequested = code.getRealmRolesRequested(); MultivaluedMap<String, RoleModel> resourceRolesRequested = code.getResourceRolesRequested(); Set<String> realmMapping = realm.getRoleMappingValues(user); if (realmMapping != null && realmMapping.size() > 0 && (scopeMap == null || scopeMap.containsKey("realm"))) { Set<String> scope = realm.getScopeMappingValues(client); if (scope.size() > 0) { Set<String> scopeRequest = scopeMap != null ? new HashSet<String>(scopeMap.get("realm")) : null; for (String role : realmMapping) { if ((scopeRequest == null || scopeRequest.contains(role)) && scope.contains(role)) realmRolesRequested.add(realm.getRole(role)); } } } for (ApplicationModel resource : realm.getApplications()) { if (applicationResource && resource.getApplicationUser().getLoginName().equals(client.getLoginName())) { - resourceRolesRequested.addAll(resource.getName(), resource.getRoles()); + for (String role : resource.getRoleMappingValues(user)) { + resourceRolesRequested.addAll(resource.getName(), resource.getRole(role)); + } } else { Set<String> mapping = resource.getRoleMappingValues(user); if (mapping != null && mapping.size() > 0 && (scopeMap == null || scopeMap.containsKey(resource.getName()))) { Set<String> scope = resource.getScopeMappingValues(client); if (scope.size() > 0) { Set<String> scopeRequest = scopeMap != null ? new HashSet<String>(scopeMap.get(resource.getName())) : null; for (String role : mapping) { if ((scopeRequest == null || scopeRequest.contains(role)) && scope.contains(role)) resourceRolesRequested.add(resource.getName(), resource.getRole(role)); } } } } } createToken(code, realm, client, user); code.setRealm(realm); code.setExpiration((System.currentTimeMillis() / 1000) + realm.getAccessCodeLifespan()); code.setClient(client); code.setUser(user); code.setState(state); code.setRedirectUri(redirect); accessCodeMap.put(code.getId(), code); String accessCode = null; try { accessCode = new JWSBuilder().content(code.getId().getBytes("UTF-8")).rsa256(realm.getPrivateKey()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } code.setCode(accessCode); return code; } protected SkeletonKeyToken initToken(RealmModel realm, UserModel client, UserModel user) { SkeletonKeyToken token = new SkeletonKeyToken(); token.id(RealmManager.generateId()); token.principal(user.getLoginName()); token.audience(realm.getName()); token.issuedNow(); token.issuedFor(client.getLoginName()); if (realm.getTokenLifespan() > 0) { token.expiration((System.currentTimeMillis() / 1000) + realm.getTokenLifespan()); } Set<String> allowedOrigins = client.getWebOrigins(); if (allowedOrigins != null) { token.setAllowedOrigins(allowedOrigins); } return token; } protected void createToken(AccessCodeEntry accessCodeEntry, RealmModel realm, UserModel client, UserModel user) { SkeletonKeyToken token = initToken(realm, client, user); if (accessCodeEntry.getRealmRolesRequested().size() > 0) { SkeletonKeyToken.Access access = new SkeletonKeyToken.Access(); for (RoleModel role : accessCodeEntry.getRealmRolesRequested()) { access.addRole(role.getName()); } token.setRealmAccess(access); } if (accessCodeEntry.getResourceRolesRequested().size() > 0) { Map<String, ApplicationModel> resourceMap = realm.getApplicationNameMap(); for (String resourceName : accessCodeEntry.getResourceRolesRequested().keySet()) { ApplicationModel resource = resourceMap.get(resourceName); SkeletonKeyToken.Access access = token.addAccess(resourceName).verifyCaller(resource.isSurrogateAuthRequired()); for (RoleModel role : accessCodeEntry.getResourceRolesRequested().get(resourceName)) { access.addRole(role.getName()); } } } accessCodeEntry.setToken(token); } public String encodeScope(SkeletonKeyScope scope) { String token = null; try { token = JsonSerialization.toString(scope, false); } catch (Exception e) { throw new RuntimeException(e); } return Base64Url.encode(token.getBytes()); } public SkeletonKeyScope decodeScope(String scopeParam) { SkeletonKeyScope scope = null; byte[] bytes = Base64Url.decode(scopeParam); try { scope = JsonSerialization.fromBytes(SkeletonKeyScope.class, bytes); } catch (IOException e) { throw new RuntimeException(e); } return scope; } public SkeletonKeyToken createAccessToken(RealmModel realm, UserModel user) { List<ApplicationModel> resources = realm.getApplications(); SkeletonKeyToken token = new SkeletonKeyToken(); token.id(RealmManager.generateId()); token.issuedNow(); token.principal(user.getLoginName()); token.audience(realm.getId()); if (realm.getTokenLifespan() > 0) { token.expiration((System.currentTimeMillis() / 1000) + realm.getTokenLifespan()); } Set<String> realmMapping = realm.getRoleMappingValues(user); if (realmMapping != null && realmMapping.size() > 0) { SkeletonKeyToken.Access access = new SkeletonKeyToken.Access(); for (String role : realmMapping) { access.addRole(role); } token.setRealmAccess(access); } if (resources != null) { for (ApplicationModel resource : resources) { Set<String> mapping = resource.getRoleMappingValues(user); if (mapping == null) continue; SkeletonKeyToken.Access access = token.addAccess(resource.getName()) .verifyCaller(resource.isSurrogateAuthRequired()); for (String role : mapping) { access.addRole(role); } } } return token; } public String encodeToken(RealmModel realm, Object token) { byte[] tokenBytes = null; try { tokenBytes = JsonSerialization.toByteArray(token, false); } catch (Exception e) { throw new RuntimeException(e); } String encodedToken = new JWSBuilder() .content(tokenBytes) .rsa256(realm.getPrivateKey()); return encodedToken; } }
true
true
public AccessCodeEntry createAccessCode(String scopeParam, String state, String redirect, RealmModel realm, UserModel client, UserModel user) { boolean applicationResource = realm.hasRole(client, realm.getRole(Constants.APPLICATION_ROLE)); AccessCodeEntry code = new AccessCodeEntry(); SkeletonKeyScope scopeMap = null; if (scopeParam != null) scopeMap = decodeScope(scopeParam); List<RoleModel> realmRolesRequested = code.getRealmRolesRequested(); MultivaluedMap<String, RoleModel> resourceRolesRequested = code.getResourceRolesRequested(); Set<String> realmMapping = realm.getRoleMappingValues(user); if (realmMapping != null && realmMapping.size() > 0 && (scopeMap == null || scopeMap.containsKey("realm"))) { Set<String> scope = realm.getScopeMappingValues(client); if (scope.size() > 0) { Set<String> scopeRequest = scopeMap != null ? new HashSet<String>(scopeMap.get("realm")) : null; for (String role : realmMapping) { if ((scopeRequest == null || scopeRequest.contains(role)) && scope.contains(role)) realmRolesRequested.add(realm.getRole(role)); } } } for (ApplicationModel resource : realm.getApplications()) { if (applicationResource && resource.getApplicationUser().getLoginName().equals(client.getLoginName())) { resourceRolesRequested.addAll(resource.getName(), resource.getRoles()); } else { Set<String> mapping = resource.getRoleMappingValues(user); if (mapping != null && mapping.size() > 0 && (scopeMap == null || scopeMap.containsKey(resource.getName()))) { Set<String> scope = resource.getScopeMappingValues(client); if (scope.size() > 0) { Set<String> scopeRequest = scopeMap != null ? new HashSet<String>(scopeMap.get(resource.getName())) : null; for (String role : mapping) { if ((scopeRequest == null || scopeRequest.contains(role)) && scope.contains(role)) resourceRolesRequested.add(resource.getName(), resource.getRole(role)); } } } } } createToken(code, realm, client, user); code.setRealm(realm); code.setExpiration((System.currentTimeMillis() / 1000) + realm.getAccessCodeLifespan()); code.setClient(client); code.setUser(user); code.setState(state); code.setRedirectUri(redirect); accessCodeMap.put(code.getId(), code); String accessCode = null; try { accessCode = new JWSBuilder().content(code.getId().getBytes("UTF-8")).rsa256(realm.getPrivateKey()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } code.setCode(accessCode); return code; }
public AccessCodeEntry createAccessCode(String scopeParam, String state, String redirect, RealmModel realm, UserModel client, UserModel user) { boolean applicationResource = realm.hasRole(client, realm.getRole(Constants.APPLICATION_ROLE)); AccessCodeEntry code = new AccessCodeEntry(); SkeletonKeyScope scopeMap = null; if (scopeParam != null) scopeMap = decodeScope(scopeParam); List<RoleModel> realmRolesRequested = code.getRealmRolesRequested(); MultivaluedMap<String, RoleModel> resourceRolesRequested = code.getResourceRolesRequested(); Set<String> realmMapping = realm.getRoleMappingValues(user); if (realmMapping != null && realmMapping.size() > 0 && (scopeMap == null || scopeMap.containsKey("realm"))) { Set<String> scope = realm.getScopeMappingValues(client); if (scope.size() > 0) { Set<String> scopeRequest = scopeMap != null ? new HashSet<String>(scopeMap.get("realm")) : null; for (String role : realmMapping) { if ((scopeRequest == null || scopeRequest.contains(role)) && scope.contains(role)) realmRolesRequested.add(realm.getRole(role)); } } } for (ApplicationModel resource : realm.getApplications()) { if (applicationResource && resource.getApplicationUser().getLoginName().equals(client.getLoginName())) { for (String role : resource.getRoleMappingValues(user)) { resourceRolesRequested.addAll(resource.getName(), resource.getRole(role)); } } else { Set<String> mapping = resource.getRoleMappingValues(user); if (mapping != null && mapping.size() > 0 && (scopeMap == null || scopeMap.containsKey(resource.getName()))) { Set<String> scope = resource.getScopeMappingValues(client); if (scope.size() > 0) { Set<String> scopeRequest = scopeMap != null ? new HashSet<String>(scopeMap.get(resource.getName())) : null; for (String role : mapping) { if ((scopeRequest == null || scopeRequest.contains(role)) && scope.contains(role)) resourceRolesRequested.add(resource.getName(), resource.getRole(role)); } } } } } createToken(code, realm, client, user); code.setRealm(realm); code.setExpiration((System.currentTimeMillis() / 1000) + realm.getAccessCodeLifespan()); code.setClient(client); code.setUser(user); code.setState(state); code.setRedirectUri(redirect); accessCodeMap.put(code.getId(), code); String accessCode = null; try { accessCode = new JWSBuilder().content(code.getId().getBytes("UTF-8")).rsa256(realm.getPrivateKey()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } code.setCode(accessCode); return code; }
diff --git a/core/resource/src/main/java/org/mobicents/slee/resource/EndAllActivitiesRAEntityTimerTask.java b/core/resource/src/main/java/org/mobicents/slee/resource/EndAllActivitiesRAEntityTimerTask.java index 322a76ad9..6a462ea2b 100644 --- a/core/resource/src/main/java/org/mobicents/slee/resource/EndAllActivitiesRAEntityTimerTask.java +++ b/core/resource/src/main/java/org/mobicents/slee/resource/EndAllActivitiesRAEntityTimerTask.java @@ -1,115 +1,121 @@ package org.mobicents.slee.resource; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import org.mobicents.slee.container.SleeContainer; import org.mobicents.slee.container.activity.ActivityContext; import org.mobicents.slee.container.activity.ActivityContextHandle; import org.mobicents.slee.container.activity.ActivityType; import org.mobicents.slee.container.event.EventContext; import org.mobicents.slee.container.eventrouter.EventRoutingTask; import org.mobicents.slee.container.resource.ResourceAdaptorActivityContextHandle; import org.mobicents.slee.container.resource.ResourceAdaptorEntity; import org.mobicents.slee.container.sbbentity.SbbEntityID; public class EndAllActivitiesRAEntityTimerTask implements Runnable { private static final Logger logger = Logger.getLogger(EndAllActivitiesRAEntityTimerTask.class); private static final long delay = 45; private final ResourceAdaptorEntity raEntity; private final SleeContainer sleeContainer; private final ScheduledFuture<?> scheduledFuture; public EndAllActivitiesRAEntityTimerTask(ResourceAdaptorEntity raEntity,SleeContainer sleeContainer) { this.raEntity = raEntity; this.sleeContainer = sleeContainer; this.scheduledFuture = sleeContainer.getNonClusteredScheduler().schedule(this, delay,TimeUnit.SECONDS); } public boolean cancel() { return scheduledFuture.cancel(false); } @Override public void run() { logger.info("Forcing the end of all activities for ra entity "+ raEntity.getName()); // first round, end all activities gracefully boolean noActivitiesFound = true; for (ActivityContextHandle handle : sleeContainer .getActivityContextFactory() .getAllActivityContextsHandles()) { if (handle.getActivityType() == ActivityType.RA) { final ResourceAdaptorActivityContextHandle raHandle = (ResourceAdaptorActivityContextHandle) handle; if (raHandle.getResourceAdaptorEntity().equals(raEntity)) { noActivitiesFound = false; try { if (logger.isDebugEnabled()) { logger.debug("Forcing the end of activity " + handle+" Pt.1"); } ActivityContext ac = sleeContainer .getActivityContextFactory() .getActivityContext(handle); if (ac != null) { // if it has a suspended event context then resume it EventRoutingTask routingTask = ac.getLocalActivityContext().getCurrentEventRoutingTask(); EventContext eventContext = routingTask != null ? routingTask.getEventContext() : null; if (eventContext != null && eventContext.isSuspended()) { eventContext.resumeDelivery(); } // end activity ac.endActivity(); } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Failed to end activity " + handle+" Pt.1", e); } } } } } if (noActivitiesFound) { raEntity.allActivitiesEnded(); } else { // second round, enforcing the removal of all stuck activities // sleep 15s try { Thread.sleep(15000); } catch (InterruptedException e) { logger.error(e.getMessage(),e); } + noActivitiesFound = true; for (ActivityContextHandle handle : sleeContainer .getActivityContextFactory() .getAllActivityContextsHandles()) { if (handle.getActivityType() == ActivityType.RA) { final ResourceAdaptorActivityContextHandle raHandle = (ResourceAdaptorActivityContextHandle) handle; if (raHandle.getResourceAdaptorEntity().equals(raEntity)) { + noActivitiesFound = false; try { if (logger.isDebugEnabled()) { logger.debug("Forcing the end of activity " + handle+" Pt.2"); } ActivityContext ac = sleeContainer .getActivityContextFactory() .getActivityContext(handle); if (ac != null) { for(SbbEntityID sbbEntityId : ac.getSbbAttachmentSet()) { ac.detachSbbEntity(sbbEntityId); } ac.activityEnded(); } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Failed to end activity " + handle+" Pt.2", e); } } } } } + if (noActivitiesFound) { + // concurrent ending of activities may fail to notify the ra entity + raEntity.allActivitiesEnded(); + } } } }
false
true
public void run() { logger.info("Forcing the end of all activities for ra entity "+ raEntity.getName()); // first round, end all activities gracefully boolean noActivitiesFound = true; for (ActivityContextHandle handle : sleeContainer .getActivityContextFactory() .getAllActivityContextsHandles()) { if (handle.getActivityType() == ActivityType.RA) { final ResourceAdaptorActivityContextHandle raHandle = (ResourceAdaptorActivityContextHandle) handle; if (raHandle.getResourceAdaptorEntity().equals(raEntity)) { noActivitiesFound = false; try { if (logger.isDebugEnabled()) { logger.debug("Forcing the end of activity " + handle+" Pt.1"); } ActivityContext ac = sleeContainer .getActivityContextFactory() .getActivityContext(handle); if (ac != null) { // if it has a suspended event context then resume it EventRoutingTask routingTask = ac.getLocalActivityContext().getCurrentEventRoutingTask(); EventContext eventContext = routingTask != null ? routingTask.getEventContext() : null; if (eventContext != null && eventContext.isSuspended()) { eventContext.resumeDelivery(); } // end activity ac.endActivity(); } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Failed to end activity " + handle+" Pt.1", e); } } } } } if (noActivitiesFound) { raEntity.allActivitiesEnded(); } else { // second round, enforcing the removal of all stuck activities // sleep 15s try { Thread.sleep(15000); } catch (InterruptedException e) { logger.error(e.getMessage(),e); } for (ActivityContextHandle handle : sleeContainer .getActivityContextFactory() .getAllActivityContextsHandles()) { if (handle.getActivityType() == ActivityType.RA) { final ResourceAdaptorActivityContextHandle raHandle = (ResourceAdaptorActivityContextHandle) handle; if (raHandle.getResourceAdaptorEntity().equals(raEntity)) { try { if (logger.isDebugEnabled()) { logger.debug("Forcing the end of activity " + handle+" Pt.2"); } ActivityContext ac = sleeContainer .getActivityContextFactory() .getActivityContext(handle); if (ac != null) { for(SbbEntityID sbbEntityId : ac.getSbbAttachmentSet()) { ac.detachSbbEntity(sbbEntityId); } ac.activityEnded(); } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Failed to end activity " + handle+" Pt.2", e); } } } } } } }
public void run() { logger.info("Forcing the end of all activities for ra entity "+ raEntity.getName()); // first round, end all activities gracefully boolean noActivitiesFound = true; for (ActivityContextHandle handle : sleeContainer .getActivityContextFactory() .getAllActivityContextsHandles()) { if (handle.getActivityType() == ActivityType.RA) { final ResourceAdaptorActivityContextHandle raHandle = (ResourceAdaptorActivityContextHandle) handle; if (raHandle.getResourceAdaptorEntity().equals(raEntity)) { noActivitiesFound = false; try { if (logger.isDebugEnabled()) { logger.debug("Forcing the end of activity " + handle+" Pt.1"); } ActivityContext ac = sleeContainer .getActivityContextFactory() .getActivityContext(handle); if (ac != null) { // if it has a suspended event context then resume it EventRoutingTask routingTask = ac.getLocalActivityContext().getCurrentEventRoutingTask(); EventContext eventContext = routingTask != null ? routingTask.getEventContext() : null; if (eventContext != null && eventContext.isSuspended()) { eventContext.resumeDelivery(); } // end activity ac.endActivity(); } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Failed to end activity " + handle+" Pt.1", e); } } } } } if (noActivitiesFound) { raEntity.allActivitiesEnded(); } else { // second round, enforcing the removal of all stuck activities // sleep 15s try { Thread.sleep(15000); } catch (InterruptedException e) { logger.error(e.getMessage(),e); } noActivitiesFound = true; for (ActivityContextHandle handle : sleeContainer .getActivityContextFactory() .getAllActivityContextsHandles()) { if (handle.getActivityType() == ActivityType.RA) { final ResourceAdaptorActivityContextHandle raHandle = (ResourceAdaptorActivityContextHandle) handle; if (raHandle.getResourceAdaptorEntity().equals(raEntity)) { noActivitiesFound = false; try { if (logger.isDebugEnabled()) { logger.debug("Forcing the end of activity " + handle+" Pt.2"); } ActivityContext ac = sleeContainer .getActivityContextFactory() .getActivityContext(handle); if (ac != null) { for(SbbEntityID sbbEntityId : ac.getSbbAttachmentSet()) { ac.detachSbbEntity(sbbEntityId); } ac.activityEnded(); } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Failed to end activity " + handle+" Pt.2", e); } } } } } if (noActivitiesFound) { // concurrent ending of activities may fail to notify the ra entity raEntity.allActivitiesEnded(); } } }