Author: xor Date: 2008-09-17 13:37:05 +0000 (Wed, 17 Sep 2008) New Revision: 22664
Added: trunk/plugins/WoT/Config.java trunk/plugins/WoT/DuplicateIdentityException.java trunk/plugins/WoT/DuplicateScoreException.java trunk/plugins/WoT/DuplicateTrustException.java trunk/plugins/WoT/Identity.java trunk/plugins/WoT/IdentityFetcher.java trunk/plugins/WoT/IdentityInserter.java trunk/plugins/WoT/IdentityParser.java trunk/plugins/WoT/IdentityTest.java trunk/plugins/WoT/InvalidParameterException.java trunk/plugins/WoT/NotInTrustTreeException.java trunk/plugins/WoT/NotTrustedException.java trunk/plugins/WoT/OwnIdentity.java trunk/plugins/WoT/Score.java trunk/plugins/WoT/ScoreTest.java trunk/plugins/WoT/Trust.java trunk/plugins/WoT/TrustTest.java trunk/plugins/WoT/Trustlist.java trunk/plugins/WoT/UnknownIdentityException.java trunk/plugins/WoT/Version.java trunk/plugins/WoT/WebInterface.java trunk/plugins/WoT/WoT.java trunk/plugins/WoT/WoTTest.java Removed: trunk/plugins/WoT/src/plugins/WoT/Config.java trunk/plugins/WoT/src/plugins/WoT/DuplicateIdentityException.java trunk/plugins/WoT/src/plugins/WoT/DuplicateScoreException.java trunk/plugins/WoT/src/plugins/WoT/DuplicateTrustException.java trunk/plugins/WoT/src/plugins/WoT/Identity.java trunk/plugins/WoT/src/plugins/WoT/IdentityFetcher.java trunk/plugins/WoT/src/plugins/WoT/IdentityInserter.java trunk/plugins/WoT/src/plugins/WoT/IdentityParser.java trunk/plugins/WoT/src/plugins/WoT/IdentityTest.java trunk/plugins/WoT/src/plugins/WoT/InvalidParameterException.java trunk/plugins/WoT/src/plugins/WoT/NotInTrustTreeException.java trunk/plugins/WoT/src/plugins/WoT/NotTrustedException.java trunk/plugins/WoT/src/plugins/WoT/OwnIdentity.java trunk/plugins/WoT/src/plugins/WoT/Score.java trunk/plugins/WoT/src/plugins/WoT/ScoreTest.java trunk/plugins/WoT/src/plugins/WoT/Trust.java trunk/plugins/WoT/src/plugins/WoT/TrustTest.java trunk/plugins/WoT/src/plugins/WoT/Trustlist.java trunk/plugins/WoT/src/plugins/WoT/UnknownIdentityException.java trunk/plugins/WoT/src/plugins/WoT/Version.java trunk/plugins/WoT/src/plugins/WoT/WebInterface.java trunk/plugins/WoT/src/plugins/WoT/WoT.java trunk/plugins/WoT/src/plugins/WoT/WoTTest.java Log: Move the source files into the right place so that compiling works when the whole Freenet project has been checked out. Copied: trunk/plugins/WoT/Config.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/Config.java) =================================================================== --- trunk/plugins/WoT/Config.java (rev 0) +++ trunk/plugins/WoT/Config.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,43 @@ +/** + * 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.WoT; + +import java.util.HashMap; + +import com.db4o.ObjectContainer; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + */ +public class Config { + + private ObjectContainer db; + private HashMap<String, String> params = null; + + public Config(ObjectContainer db) { + this.db = db; + if(params == null) { + params = new HashMap<String, String>(); + initDefault(false); + } + } + + public void set(String key, String value) { + params.put(key, value); + db.store(params); + } + + public String get(String key) { + return params.get(key); + } + + public void initDefault(boolean overwrite) { + + if (!params.containsKey("delayBetweenInserts") || overwrite) set("delayBetweenInserts", "30"); + + db.store(this); + } +} Copied: trunk/plugins/WoT/DuplicateIdentityException.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/DuplicateIdentityException.java) =================================================================== --- trunk/plugins/WoT/DuplicateIdentityException.java (rev 0) +++ trunk/plugins/WoT/DuplicateIdentityException.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,19 @@ +/** + * 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.WoT; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + * + */ +public class DuplicateIdentityException extends Exception { + + private static final long serialVersionUID = -1; + + public DuplicateIdentityException(String message) { + super(message); + } +} Copied: trunk/plugins/WoT/DuplicateScoreException.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/DuplicateScoreException.java) =================================================================== --- trunk/plugins/WoT/DuplicateScoreException.java (rev 0) +++ trunk/plugins/WoT/DuplicateScoreException.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,19 @@ +/** + * 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.WoT; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + * + */ +public class DuplicateScoreException extends Exception { + + private static final long serialVersionUID = -1; + + public DuplicateScoreException(String message) { + super(message); + } +} Copied: trunk/plugins/WoT/DuplicateTrustException.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/DuplicateTrustException.java) =================================================================== --- trunk/plugins/WoT/DuplicateTrustException.java (rev 0) +++ trunk/plugins/WoT/DuplicateTrustException.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,18 @@ +/** + * 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.WoT; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + */ +public class DuplicateTrustException extends Exception { + + private static final long serialVersionUID = -1; + + public DuplicateTrustException(String message) { + super(message); + } +} Copied: trunk/plugins/WoT/Identity.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/Identity.java) =================================================================== --- trunk/plugins/WoT/Identity.java (rev 0) +++ trunk/plugins/WoT/Identity.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,397 @@ +/** + * 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.WoT; + +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; + +import com.db4o.ObjectContainer; +import com.db4o.ObjectSet; +import com.db4o.query.Query; + +import freenet.keys.FreenetURI; +import freenet.support.Logger; + +/** + * An identity as handled by the WoT (a USK) + * + * @author Julien Cornuwel (batosai at freenetproject.org) + * + */ +public class Identity { + + // Capacity is the maximum amount of points an identity can give to an other by trusting it. + public final static 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 + + private String id; + + private FreenetURI requestURI; + + private Date lastChange; + private String nickName; + private boolean publishTrustList; + private HashMap<String, String> props; + private ArrayList<String> contexts; + + + public Identity (FreenetURI requestURI, String nickName, String publishTrustList) throws InvalidParameterException { + + setRequestURI(requestURI); + setNickName(nickName); + setPublishTrustList(publishTrustList); + props = new HashMap<String, String>(); + contexts = new ArrayList<String>(); + id = getIdFromURI(getRequestURI()); + + Logger.debug(this, "New identity : " + getNickName()); + } + + public Identity (String requestURI, String nickName, String publishTrustList) throws InvalidParameterException, MalformedURLException { + this(new FreenetURI(requestURI), nickName, publishTrustList); + } + + + + @SuppressWarnings("unchecked") + public static Identity getById (ObjectContainer db, String id) throws DuplicateIdentityException, UnknownIdentityException { + + Query query = db.query(); + query.constrain(Identity.class); + query.descend("id").constrain(id); + ObjectSet<Identity> result = query.execute(); + + if(result.size() == 0) throw new UnknownIdentityException(id.toString()); + if(result.size() > 1) throw new DuplicateIdentityException(id.toString()); + return result.next(); + } + + public static Identity getByURI (ObjectContainer db, String uri) throws UnknownIdentityException, DuplicateIdentityException, MalformedURLException { + return getByURI(db, new FreenetURI(uri)); + } + + public static Identity getByURI (ObjectContainer db, FreenetURI uri) throws UnknownIdentityException, DuplicateIdentityException { + return getById(db, getIdFromURI(uri)); + } + + public static int getNbIdentities(ObjectContainer db) { + return db.queryByExample(Identity.class).size() - OwnIdentity.getNbOwnIdentities(db); + } + + public static ObjectSet<Identity> getAllIdentities(ObjectContainer db) { + return db.queryByExample(Identity.class); + } + + public static String getIdFromURI (FreenetURI uri) { + int begin = uri.toString().indexOf(',') + 1; + int end = uri.toString().indexOf(',', begin); + return uri.toString().substring(begin, end); + } + + + + @SuppressWarnings("unchecked") + public Score getScore(OwnIdentity treeOwner, ObjectContainer db) throws NotInTrustTreeException, DuplicateScoreException { + Query query = db.query(); + query.constrain(Score.class); + query.descend("treeOwner").constrain(treeOwner).and(query.descend("target").constrain(this)); + ObjectSet<Score> result = query.execute(); + + if(result.size() == 0) throw new NotInTrustTreeException(this.getRequestURI().toString()+" is not in that trust tree"); + else if(result.size() > 1) throw new DuplicateScoreException(this.getRequestURI().toString()+" ("+ getNickName() +") has "+result.size()+" scores in "+treeOwner.getNickName()+"'s trust tree"); + else return result.next(); + } + + @SuppressWarnings("unchecked") + public ObjectSet<Score> getScores(ObjectContainer db) { + Query query = db.query(); + query.constrain(Score.class); + query.descend("target").constrain(this); + return query.execute(); + } + + @SuppressWarnings("unchecked") + public Trust getReceivedTrust(Identity truster, ObjectContainer db) throws NotTrustedException, DuplicateTrustException { + Query query = db.query(); + query.constrain(Trust.class); + query.descend("truster").constrain(truster).and(query.descend("trustee").constrain(this)); + ObjectSet<Trust> result = query.execute(); + + if(result.size() == 0) throw new NotTrustedException(truster.getNickName() + " does not trust " + this.getNickName()); + else if(result.size() > 1) throw new DuplicateTrustException("Trust from " + truster.getNickName() + "to " + this.getNickName() + " exists " + result.size() + " times in the database"); + else return result.next(); + } + + @SuppressWarnings("unchecked") + public Trust getGivenTrust(Identity trustee, ObjectContainer db) throws NotTrustedException, DuplicateTrustException { + Query query = db.query(); + query.constrain(Trust.class); + query.descend("truster").constrain(this).and(query.descend("trustee").constrain(trustee)); + ObjectSet<Trust> result = query.execute(); + + if(result.size() == 0) throw new NotTrustedException(trustee.getNickName() + " does not trust " + this.getNickName()); + else if(result.size() > 1) throw new DuplicateTrustException("Trust from " + this.getNickName() + "to " + trustee.getNickName() + " exists " + result.size() + " times in the database"); + else return result.next(); + } + + @SuppressWarnings("unchecked") + public ObjectSet<Trust> getReceivedTrusts(ObjectContainer db) { + Query query = db.query(); + query.constrain(Trust.class); + query.descend("trustee").constrain(this); + return query.execute(); + } + + public long getNbReceivedTrusts(ObjectContainer db) { + return getReceivedTrusts(db).size(); + } + + @SuppressWarnings("unchecked") + public ObjectSet<Trust> getGivenTrusts(ObjectContainer db) { + Query query = db.query(); + query.constrain(Trust.class); + query.descend("truster").constrain(this); + return query.execute(); + } + + public long getNbGivenTrusts(ObjectContainer db) { + return getGivenTrusts(db).size(); + } + + public void setTrust(ObjectContainer db, Identity trustee, int value, String comment) throws DuplicateTrustException, InvalidParameterException, DuplicateScoreException { + // Check if we are updating an existing trust value + Trust trust; + try { + trust = getGivenTrust(trustee, db); + + if(!trust.getComment().equals(comment)) { + trust.setComment(comment); + db.store(trust); + } + + if(trust.getValue() != value) { + trust.setValue(value); + db.store(trust); + Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); + trustee.updateScore(db); + } + } catch (NotTrustedException e) { + trust = new Trust(this, trustee, value, comment); + db.store(trust); + Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); + trustee.updateScore(db); + } + } + + public void updateScore (ObjectContainer db) throws DuplicateScoreException, DuplicateTrustException { + ObjectSet<OwnIdentity> treeOwners = OwnIdentity.getAllOwnIdentities(db); + if(treeOwners.size() == 0) Logger.error(this, "Can't update "+ getNickName()+"'s score : there is no own identity yet"); + while(treeOwners.hasNext()) + updateScore (db, treeOwners.next()); + } + + public void updateScore (ObjectContainer db, OwnIdentity treeOwner) throws DuplicateScoreException, DuplicateTrustException { + + if(this == treeOwner) return; + + boolean hasNegativeTrust = false; + boolean changedCapacity = false; + Score score; + + Logger.debug(this, "Updating " + getNickName() + "'s score in " + treeOwner.getNickName() + "'s trust tree"); + + int value = computeScoreValue(db, treeOwner); + int rank = computeRank(db, treeOwner); + + if(rank == -1) { // -1 value means the identity is not in the trust tree + try { // If he had a score, we delete it + score = getScore(treeOwner, db); + db.delete(score); // He had a score, we delete it + changedCapacity = true; + Logger.debug(this, getNickName() + " is not in " + treeOwner.getNickName() + "'s trust tree anymore"); + } catch (NotInTrustTreeException e) {} + } + else { // The identity is in the trust tree + + try { // Get existing score or create one if needed + score = getScore(treeOwner, db); + } catch (NotInTrustTreeException e) { + score = new Score(treeOwner, this, 0, -1, 0); + } + + score.setScore(value); + score.setRank(rank + 1); + int oldCapacity = score.getCapacity(); + + // Does the treeOwner personally distrust this identity ? + try { + if(getReceivedTrust(treeOwner, db).getValue() < 0) { + hasNegativeTrust = true; + Logger.debug(this, getNickName() + " received negative trust from " + treeOwner.getNickName() + " and therefore has no capacity in his trust tree."); + } + } catch (NotTrustedException e) {} + + if(hasNegativeTrust) score.setCapacity(0); + else score.setCapacity((score.getRank() >= capacities.length) ? 1 : capacities[score.getRank()]); + + if(score.getCapacity() != oldCapacity) changedCapacity = true; + db.store(score); + Logger.debug(this, score.toString()); + } + + if(changedCapacity) { // We have to update trustees' score + ObjectSet<Trust> trustees = getGivenTrusts(db); + Logger.debug(this, getNickName() + "'s capacity has changed in " + treeOwner.getNickName() + "'s trust tree, updating his ("+trustees.size()+") trustees"); + while(trustees.hasNext()) trustees.next().getTrustee().updateScore(db, treeOwner); + } + } + + public int computeScoreValue(ObjectContainer db, OwnIdentity treeOwner) throws DuplicateScoreException { + int value = 0; + + ObjectSet<Trust> receivedTrusts = getReceivedTrusts(db); + while(receivedTrusts.hasNext()) { + Trust trust = receivedTrusts.next(); + try { + value += trust.getValue() * trust.getTruster().getScore(treeOwner, db).getCapacity() / 100; + } catch (NotInTrustTreeException e) {} + } + return value; + } + + public int computeRank(ObjectContainer db, OwnIdentity treeOwner) throws DuplicateScoreException { + int rank = -1; + + ObjectSet<Trust> receivedTrusts = getReceivedTrusts(db); + while(receivedTrusts.hasNext()) { + Trust trust = receivedTrusts.next(); + try { + Score score = trust.getTruster().getScore(treeOwner, db); + if(score.getCapacity() != 0) // If the truster has no capacity, he can't give his rank + if(rank == -1 || score.getRank() < rank) // If the truster's rank is better than ours or if we have not + rank = score.getRank(); + } catch (NotInTrustTreeException e) {} + } + return rank; + } + + public void setRequestURI(FreenetURI requestURI) throws InvalidParameterException { + if(requestURI.getKeyType().equals("SSK")) requestURI = requestURI.setKeyType("USK"); + if(!requestURI.getKeyType().equals("USK")) throw new InvalidParameterException("Key type not supported"); + this.requestURI = requestURI.setKeyType("USK").setDocName("WoT"); + updated(); + } + + public void setEdition(long edition) throws InvalidParameterException { + setRequestURI(getRequestURI().setSuggestedEdition(edition)); + } + + public void setNickName(String nickName) throws InvalidParameterException { + String nick = nickName.trim(); + if(nick.length() == 0) throw new InvalidParameterException("Blank nickName"); + if(nick.length() > 50) throw new InvalidParameterException("NickName is too long (50 chars max)"); + this.nickName = nick; + updated(); + } + + public void setPublishTrustList(boolean publishTrustList) { + this.publishTrustList = publishTrustList; + updated(); + } + + public void setPublishTrustList(String publishTrustList) { + setPublishTrustList(publishTrustList.equals("true")); + } + + public void setProp(String key, String value, ObjectContainer db) throws InvalidParameterException { + if(key.trim().length() == 0 || value.trim().length() == 0) throw new InvalidParameterException("Blank key or value in this property"); + props.put(key.trim(), value.trim()); + db.store(props); + updated(); + } + + public void removeProp(String key, ObjectContainer db) throws InvalidParameterException { + if(!props.containsKey(key)) throw new InvalidParameterException("Property '"+key+"' isn't set on this identity"); + props.remove(key.trim()); + db.store(props); + updated(); + } + + public Iterator<Entry<String, String>> getProps() { + Iterator<Entry<String, String>> i = props.entrySet().iterator(); + return i; + } + + public void addContext(String context, ObjectContainer db) throws InvalidParameterException { + String newContext = context.trim(); + if(newContext.length() == 0) throw new InvalidParameterException("Blank context"); + if(!contexts.contains(newContext)) contexts.add(newContext); + db.store(contexts); + updated(); + } + + public void removeContext(String context, ObjectContainer db) throws InvalidParameterException { + if(contexts.size() == 1) throw new InvalidParameterException("Only one context left"); + contexts.remove(context); + db.store(contexts); + updated(); + } + + public Iterator<String> getContexts() { + return contexts.iterator(); + } + + public void updated() { + lastChange = new Date(); + } + + public String getId() { + return id; + } + + public FreenetURI getRequestURI() { + return requestURI.setMetaString(new String[] {"identity.xml"} ); + } + + public Date getLastChange() { + return lastChange; + } + + public String getNickName() { + return nickName; + } + + public boolean doesPublishTrustList() { + return publishTrustList; + } + + public String getContextsAsString() { + return contexts.toString(); + } + + public String getProp(String key) throws InvalidParameterException { + if(!props.containsKey(key)) throw new InvalidParameterException("Property '"+key+"' isn't set on this identity"); + return props.get(key); + } + + public String getPropsAsString() { + return props.toString(); + } + + public boolean hasContext(String context) { + return contexts.contains(context.trim()); + } +} Copied: trunk/plugins/WoT/IdentityFetcher.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/IdentityFetcher.java) =================================================================== --- trunk/plugins/WoT/IdentityFetcher.java (rev 0) +++ trunk/plugins/WoT/IdentityFetcher.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,127 @@ +/** + * 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.WoT; + +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; + +import com.db4o.ObjectContainer; + +import freenet.client.FetchContext; +import freenet.client.FetchException; +import freenet.client.FetchResult; +import freenet.client.HighLevelSimpleClient; +import freenet.client.InsertException; +import freenet.client.async.BaseClientPutter; +import freenet.client.async.ClientCallback; +import freenet.client.async.ClientGetter; +import freenet.keys.FreenetURI; +import freenet.support.Logger; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + * + */ +public class IdentityFetcher implements ClientCallback { + + private ObjectContainer db; + private HighLevelSimpleClient client; + private ArrayList<ClientGetter> requests; + + public IdentityFetcher(ObjectContainer db, HighLevelSimpleClient client) { + + this.db = db; + this.client = client; + requests = new ArrayList<ClientGetter>(); + } + + public void fetch(Identity identity) { + + fetch(identity, false); + } + + public void fetch(Identity identity, boolean nextEdition) { + + try { + if(nextEdition && !identity.getLastChange().equals(new Date(0))) + fetch(identity.getRequestURI().setSuggestedEdition(identity.getRequestURI().getSuggestedEdition() + 1)); + else + fetch(identity.getRequestURI()); + } catch (FetchException e) { + Logger.error(this, "Request restart failed: "+e, e); + } + } + + public void fetch(FreenetURI uri) throws FetchException { + + FetchContext fetchContext = client.getFetchContext(); + fetchContext.maxSplitfileBlockRetries = -1; // retry forever + fetchContext.maxNonSplitfileRetries = -1; // retry forever + requests.add(client.fetch(uri, -1, this, this, fetchContext)); + Logger.debug(this, "Start fetching identity "+uri.toString()); + } + + public void stop() { + Iterator<ClientGetter> i = requests.iterator(); + Logger.debug(this, "Trying to stop "+requests.size()+" requests"); + while (i.hasNext()) i.next().cancel(); + Logger.debug(this, "Stopped all current requests"); + } + + public void onFailure(FetchException e, ClientGetter state) { + + if ((e.mode == FetchException.PERMANENT_REDIRECT) || (e.mode == FetchException.TOO_MANY_PATH_COMPONENTS )) { + // restart the request + try { + state.restart(e.newURI); + // Done. bye. + return; + } catch (FetchException e1) { + Logger.error(this, "Request restart failed: "+e1, e1); + } + } + // Errors we can't/want deal with + Logger.error(this, "Fetch failed for "+ state.getURI(), e); + requests.remove(state); + } + + public void onFailure(InsertException e, BaseClientPutter state) { + + } + + public void onFetchable(BaseClientPutter state) { + + } + + public void onGeneratedURI(FreenetURI uri, BaseClientPutter state) { + + } + + public void onMajorProgress() { + + } + + public void onSuccess(FetchResult result, ClientGetter state) { + + Logger.debug(this, "Fetched key (ClientGetter) : " + state.getURI()); + + try { + Logger.debug(this, "Sucessfully fetched identity "+ state.getURI().toString()); + new IdentityParser(db, client, this).parse(result.asBucket().getInputStream(), state.getURI()); + db.commit(); + state.restart(state.getURI().setSuggestedEdition(state.getURI().getSuggestedEdition() + 1)); + } catch (Exception e) { + Logger.error(this, "Parsing failed for "+ state.getURI(), e); + } + } + + public void onSuccess(BaseClientPutter state) { + + Logger.debug(this, "Fetched key (BaseClientPutter) : " + state.getURI()); + } +} Copied: trunk/plugins/WoT/IdentityInserter.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/IdentityInserter.java) =================================================================== --- trunk/plugins/WoT/IdentityInserter.java (rev 0) +++ trunk/plugins/WoT/IdentityInserter.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,117 @@ +/** + * 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.WoT; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Date; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; + +import com.db4o.ObjectContainer; +import com.db4o.ObjectSet; +import com.db4o.ext.DatabaseClosedException; +import com.db4o.ext.Db4oIOException; + +import freenet.client.ClientMetadata; +import freenet.client.HighLevelSimpleClient; +import freenet.client.InsertBlock; +import freenet.client.InsertException; +import freenet.keys.FreenetURI; +import freenet.support.Logger; +import freenet.support.api.Bucket; +import freenet.support.io.TempBucketFactory; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + * + */ +public class IdentityInserter implements Runnable { + + ObjectContainer db; + HighLevelSimpleClient client; + final TempBucketFactory tBF; + + boolean isRunning; + + public IdentityInserter(ObjectContainer db, HighLevelSimpleClient client, TempBucketFactory tbf) { + this.db = db; + this.client = client; + isRunning = true; + tBF = tbf; + } + + public void run() { + try{ + Thread.sleep(30 * 1000); // Let the node start up (30 seconds) + } catch (InterruptedException e){} + while(isRunning) { + ObjectSet<OwnIdentity> identities = OwnIdentity.getAllOwnIdentities(db); + while(identities.hasNext()) { + OwnIdentity identity = identities.next(); + if(identity.needsInsert()) { + try { + Logger.debug(this, "Starting insert of "+identity.getNickName() + " (" + identity.getInsertURI().toString() + ")"); + insert(identity); + // We set the date now, so if the identity is modified during the insert, we'll insert it again next time + identity.setLastInsert(new Date()); + db.store(identity); + } catch (Exception e) { + Logger.error(this, "Identity insert failed: "+e.getMessage(), e); + } + } + } + db.commit(); + try{ + Thread.sleep(30 * 60 * 1000); // 30 minutes + } catch (InterruptedException e){} + } + } + + public void stop() { + isRunning = false; + Logger.debug(this, "Stopping IdentityInserter thread"); + } + + public void insert(OwnIdentity identity) throws TransformerConfigurationException, FileNotFoundException, ParserConfigurationException, TransformerException, IOException, Db4oIOException, DatabaseClosedException, InvalidParameterException, InsertException { + + Bucket tempB = tBF.makeBucket(1); + OutputStream os = tempB.getOutputStream(); + FreenetURI iURI; + try { + // Create XML file to insert + identity.exportToXML(db, os); + + os.close(); + tempB.setReadOnly(); + + // Prepare the insert + ClientMetadata cmd = new ClientMetadata("text/xml"); + InsertBlock ib = new InsertBlock(tempB,cmd,identity.getInsertURI()); + + // Logging + Logger.debug(this, "Started insert of identity '" + identity.getNickName() + "'"); + + // Blocking Insert + iURI = client.insert(ib, false, "identity.xml"); + } finally { + tempB.free(); + } + + identity.setEdition(iURI.getSuggestedEdition()); + identity.setLastInsert(new Date()); + + db.store(identity); + db.commit(); + + // Logging + Logger.debug(this, "Successful insert of identity '" + identity.getNickName() + "'"); + } +} Copied: trunk/plugins/WoT/IdentityParser.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/IdentityParser.java) =================================================================== --- trunk/plugins/WoT/IdentityParser.java (rev 0) +++ trunk/plugins/WoT/IdentityParser.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,110 @@ +/** + * 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.WoT; + +import java.io.IOException; +import java.io.InputStream; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +import com.db4o.ObjectContainer; + +import freenet.client.HighLevelSimpleClient; +import freenet.keys.FreenetURI; +import freenet.support.Logger; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + * + */ +public class IdentityParser { + + ObjectContainer db; + HighLevelSimpleClient client; + IdentityFetcher fetcher; + SAXParser saxParser; + Identity identity; + + public IdentityParser(ObjectContainer db, HighLevelSimpleClient client, IdentityFetcher fetcher) throws ParserConfigurationException, SAXException { + + this.db = db; + this.client = client; + this.fetcher = fetcher; + saxParser = SAXParserFactory.newInstance().newSAXParser(); + } + + public void parse (InputStream is, FreenetURI uri) throws InvalidParameterException, SAXException, IOException, UnknownIdentityException, DuplicateIdentityException { + + identity = Identity.getByURI(db,uri); + if(!(identity instanceof OwnIdentity)) identity.updated(); + identity.setEdition(uri.getSuggestedEdition()); + + saxParser.parse(is, new IdentityHandler() ); + db.store(identity); + + Logger.debug(this, "Successfuly parsed identity '" + identity.getNickName() + "'"); + } + + public class IdentityHandler extends DefaultHandler { + + public IdentityHandler() { + + } + + public void startElement(String nameSpaceURI, String localName, String rawName, Attributes attrs) throws SAXException { + + String elt_name; + if (rawName == null) elt_name = localName; + else elt_name = rawName; + + try { + if (elt_name.equals("nickName")) { + identity.setNickName(attrs.getValue("value")); + } + if (elt_name.equals("publishTrustList")) { + identity.setPublishTrustList(attrs.getValue("value")); + } + else if (elt_name.equals("prop")) { + identity.setProp(attrs.getValue("key"), attrs.getValue("value"), db); + } + else if(elt_name.equals("context")) { + identity.addContext(attrs.getValue("value"), db); + } + else if (elt_name.equals("trust")) { + + Identity trustee; + int value = Integer.parseInt(attrs.getValue("value")); + String comment = attrs.getValue("comment"); + + try{ + trustee = Identity.getByURI(db, attrs.getValue("uri")); + identity.setTrust(db, trustee, value, comment); + } + catch (UnknownIdentityException e) { + + // TODO Don't create Identity object before we succesfully fetched it ! + + trustee = new Identity(attrs.getValue("uri"), "Not found yet...", "false"); + db.store(trustee); + identity.setTrust(db, trustee, value, comment); + fetcher.fetch(trustee); + } + + } + } catch (Exception e1) { + Logger.error(this, "Parsing error",e1); + e1.printStackTrace(); + } + } + } +} Copied: trunk/plugins/WoT/IdentityTest.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/IdentityTest.java) =================================================================== --- trunk/plugins/WoT/IdentityTest.java (rev 0) +++ trunk/plugins/WoT/IdentityTest.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,102 @@ +/** + * 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.WoT; + +import java.io.File; +import java.net.MalformedURLException; + +import com.db4o.Db4o; +import com.db4o.ObjectContainer; +import com.db4o.ObjectSet; + +import junit.framework.TestCase; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + */ +public class IdentityTest extends TestCase { + + private String uri = "USK at yGvITGZzrY1vUZK-4AaYLgcjZ7ysRqNTMfdcO8gS-LY,-ab5bJVD3Lp-LXEQqBAhJpMKrKJ19RnNaZMIkusU79s,AQACAAE/WoT/0"; + private Identity identity; + private ObjectContainer db; + + public IdentityTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + super.setUp(); + + db = Db4o.openFile("identityTest.db4o"); + + identity = new Identity(uri, "test", "true"); + identity.addContext("bleh", db); + + db.store(identity); + db.commit(); + } + + protected void tearDown() throws Exception { + db.close(); + new File("identityTest.db4o").delete(); + } + + public void testIdentityStored() { + ObjectSet<Identity> result = db.queryByExample(Identity.class); + assertEquals(result.size(), 1); + } + + public void testGetByURI() throws MalformedURLException, UnknownIdentityException, DuplicateIdentityException { + assertNotNull(Identity.getByURI(db, uri)); + } + + public void testGetNbIdentities() { + assertEquals(Identity.getNbIdentities(db), 1); + } + + public void testContexts() throws InvalidParameterException { + assertFalse(identity.hasContext("foo")); + identity.addContext("test", db); + assertTrue(identity.hasContext("test")); + identity.removeContext("test", db); + assertFalse(identity.hasContext("test")); + } + + public void testProperties() { + try { + identity.setProp("foo", "bar", db); + } catch (InvalidParameterException e) {} + + try { + assertTrue(identity.getProp("foo").equals("bar")); + } catch (InvalidParameterException e) { fail(); } + + try { + identity.removeProp("foo", db); + } catch (InvalidParameterException e) { fail(); } + + try { + identity.getProp("foo"); + fail(); + } catch (InvalidParameterException e) {} + } + + public void testPersistence() throws MalformedURLException, DuplicateIdentityException { + db.close(); + + System.gc(); + System.runFinalization(); + + db = Db4o.openFile("identityTest.db4o"); + + assertEquals(Identity.getNbIdentities(db), 1); + try { + Identity.getByURI(db, uri); + } catch (UnknownIdentityException e) { + fail(); + } + } +} Copied: trunk/plugins/WoT/InvalidParameterException.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/InvalidParameterException.java) =================================================================== --- trunk/plugins/WoT/InvalidParameterException.java (rev 0) +++ trunk/plugins/WoT/InvalidParameterException.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,19 @@ +/** + * 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.WoT; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + * + */ +public class InvalidParameterException extends Exception { + + private static final long serialVersionUID = -1; + + public InvalidParameterException(String message) { + super(message); + } +} Copied: trunk/plugins/WoT/NotInTrustTreeException.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/NotInTrustTreeException.java) =================================================================== --- trunk/plugins/WoT/NotInTrustTreeException.java (rev 0) +++ trunk/plugins/WoT/NotInTrustTreeException.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,20 @@ +/** + * 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.WoT; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + * + */ +public class NotInTrustTreeException extends Exception { + + private static final long serialVersionUID = -1; + + public NotInTrustTreeException(String message) { + super(message); + } + +} Copied: trunk/plugins/WoT/NotTrustedException.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/NotTrustedException.java) =================================================================== --- trunk/plugins/WoT/NotTrustedException.java (rev 0) +++ trunk/plugins/WoT/NotTrustedException.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,18 @@ +/** + * 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.WoT; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + */ +public class NotTrustedException extends Exception { + + private static final long serialVersionUID = -1; + + public NotTrustedException(String message) { + super(message); + } +} Copied: trunk/plugins/WoT/OwnIdentity.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/OwnIdentity.java) =================================================================== --- trunk/plugins/WoT/OwnIdentity.java (rev 0) +++ trunk/plugins/WoT/OwnIdentity.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,186 @@ +/** + * 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.WoT; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.util.Date; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import com.db4o.ObjectContainer; +import com.db4o.ObjectSet; +import com.db4o.ext.DatabaseClosedException; +import com.db4o.ext.Db4oIOException; +import com.db4o.query.Query; + +import freenet.keys.FreenetURI; + +/** + * A local Identity (it belongs to the user) + * + * @author Julien Cornuwel (batosai at freenetproject.org) + * + */ +public class OwnIdentity extends Identity { + + private FreenetURI insertURI; + private Date lastInsert; + + public OwnIdentity (FreenetURI insertURI, FreenetURI requestURI, String nickName, String publishTrustList) throws InvalidParameterException { + super(requestURI, nickName, publishTrustList); + setInsertURI(insertURI); + setLastInsert(new Date(0)); + } + + public OwnIdentity (String insertURI, String requestURI, String nickName, String publishTrustList) throws InvalidParameterException, MalformedURLException { + this(new FreenetURI(insertURI), new FreenetURI(requestURI), nickName, publishTrustList); + } + + public void initTrustTree (ObjectContainer db) throws DuplicateScoreException { + try { + getScore(this,db); + return; + } catch (NotInTrustTreeException e) { + db.store(new Score(this, this, 100, 0, 100)); + } + } + + @SuppressWarnings("unchecked") + public static OwnIdentity getById (ObjectContainer db, String id) throws UnknownIdentityException, DuplicateIdentityException { + Query query = db.query(); + query.constrain(OwnIdentity.class); + query.descend("id").constrain(id); + ObjectSet<OwnIdentity> result = query.execute(); + + if(result.size() == 0) throw new UnknownIdentityException(id.toString()); + if(result.size() > 1) throw new DuplicateIdentityException(id.toString()); + return result.next(); + } + + public static OwnIdentity getByURI (ObjectContainer db, String uri) throws UnknownIdentityException, DuplicateIdentityException, MalformedURLException { + return getByURI(db, new FreenetURI(uri)); + } + + public static OwnIdentity getByURI (ObjectContainer db, FreenetURI uri) throws UnknownIdentityException, DuplicateIdentityException { + return getById(db, getIdFromURI(uri)); + } + + public static int getNbOwnIdentities(ObjectContainer db) { + return db.queryByExample(OwnIdentity.class).size(); + } + + public static ObjectSet<OwnIdentity> getAllOwnIdentities (ObjectContainer db) { + return db.queryByExample(OwnIdentity.class); + } + + public void exportToXML(ObjectContainer db, OutputStream os) throws ParserConfigurationException, TransformerConfigurationException, TransformerException, FileNotFoundException, IOException, Db4oIOException, DatabaseClosedException, InvalidParameterException { + + // Create the output file + StreamResult resultStream = new StreamResult(os); + + // Create the XML document + DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder xmlBuilder = xmlFactory.newDocumentBuilder(); + DOMImplementation impl = xmlBuilder.getDOMImplementation(); + Document xmlDoc = impl.createDocument(null, "WoT", null); + Element rootElement = xmlDoc.getDocumentElement(); + + // Create the content + Element identity = xmlDoc.createElement("identity"); + + // NickName + Element nickNameTag = xmlDoc.createElement("nickName"); + nickNameTag.setAttribute("value", getNickName()); + identity.appendChild(nickNameTag); + + // PublishTrustList + Element publishTrustListTag = xmlDoc.createElement("publishTrustList"); + publishTrustListTag.setAttribute("value", doesPublishTrustList() ? "true" : "false"); + identity.appendChild(publishTrustListTag); + + // Properties + + Iterator<Entry<String, String>> props = getProps(); + while(props.hasNext()){ + Map.Entry<String,String> prop = props.next(); + Element propTag = xmlDoc.createElement("prop"); + propTag.setAttribute("key", prop.getKey()); + propTag.setAttribute("value", prop.getValue()); + identity.appendChild(propTag); + } + + // Contexts + Iterator<String> contexts = getContexts(); + while(contexts.hasNext()) { + String context = (String)contexts.next(); + Element contextTag = xmlDoc.createElement("context"); + contextTag.setAttribute("value", context); + identity.appendChild(contextTag); + } + + rootElement.appendChild(identity); + + if(doesPublishTrustList()) { + Trustlist trustList = new Trustlist(db, this); + rootElement.appendChild(trustList.toXML(xmlDoc)); + } + + DOMSource domSource = new DOMSource(xmlDoc); + TransformerFactory transformFactory = TransformerFactory.newInstance(); + Transformer serializer = transformFactory.newTransformer(); + + serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + serializer.setOutputProperty(OutputKeys.INDENT,"yes"); + serializer.transform(domSource, resultStream); + } + + public boolean needsInsert() { + return (getLastChange().after(getLastInsert()) || (new Date().getTime() - getLastInsert().getTime()) > 1000*60*60*24*7); + } + + public FreenetURI getInsertURI() { + return insertURI; + } + + public void setInsertURI(FreenetURI key) throws InvalidParameterException { + if(key.getKeyType().equals("SSK")) key = key.setKeyType("USK"); + if(!key.getKeyType().equals("USK")) throw new InvalidParameterException("Key type not supported"); + + this.insertURI = key; + } + + public void setEdition(long edition) throws InvalidParameterException { + setInsertURI(getInsertURI().setSuggestedEdition(edition)); + setRequestURI(getRequestURI().setSuggestedEdition(edition)); + } + + public Date getLastInsert() { + return lastInsert; + } + + public void setLastInsert(Date lastInsert) { + this.lastInsert = lastInsert; + } +} Copied: trunk/plugins/WoT/Score.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/Score.java) =================================================================== --- trunk/plugins/WoT/Score.java (rev 0) +++ trunk/plugins/WoT/Score.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,106 @@ +/** + * 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.WoT; + +import java.net.MalformedURLException; + +import com.db4o.ObjectContainer; +import com.db4o.ObjectSet; +import com.db4o.query.Query; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + * + */ +public class Score { + + private OwnIdentity treeOwner; + private Identity target; + private int score; + private int rank; + private int capacity; + + + public Score (OwnIdentity treeOwner, Identity target, int score, int rank, int capacity) { + this.treeOwner = treeOwner; + this.target = target; + this.score = score; + this.rank = rank; + this.capacity = capacity; + } + + public static int getNb(ObjectContainer db) { + ObjectSet<Score> scores = db.queryByExample(Score.class); + return scores.size(); + } + + @SuppressWarnings("unchecked") + public static ObjectSet<Score> getIdentitiesByScore (String owner, String select, ObjectContainer db) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { + + OwnIdentity treeOwner = OwnIdentity.getByURI(db, owner); + + Query query = db.query(); + query.constrain(Score.class); + query.descend("treeOwner").constrain(treeOwner); + + if(select.equals("+")) { + query.descend("score").constrain(new Integer(0)).greater(); + } + else if(select.equals("0")) { + query.descend("score").constrain(new Integer(0)); + } + else if(select.equals("-")) { + query.descend("score").constrain(new Integer(0)).smaller(); + } + else throw new InvalidParameterException("Unhandled select value ("+select+")"); + + return query.execute(); + } + + public String toString() { + return getTarget().getNickName() + " has " + getScore() + " points in " + getTreeOwner().getNickName() + "'s trust tree (rank : " + getRank() + ", capacity : " + getCapacity() + ")"; + } + + public OwnIdentity getTreeOwner() { + return treeOwner; + } + + public void setTreeOwner(OwnIdentity treeOwner) { + this.treeOwner = treeOwner; + } + + public Identity getTarget() { + return target; + } + + public void setTarget(Identity target) { + this.target = target; + } + + public int getScore() { + return score; + } + + public void setScore(int score) { + this.score = score; + } + + public int getRank() { + return rank; + } + + public void setRank(int rank) { + this.rank = rank; + } + + public int getCapacity() { + return capacity; + } + + public void setCapacity(int capacity) { + this.capacity = capacity; + } +} Copied: trunk/plugins/WoT/ScoreTest.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/ScoreTest.java) =================================================================== --- trunk/plugins/WoT/ScoreTest.java (rev 0) +++ trunk/plugins/WoT/ScoreTest.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,81 @@ +/** + * 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.WoT; + +import java.io.File; +import java.net.MalformedURLException; + +import junit.framework.TestCase; + +import com.db4o.Db4o; +import com.db4o.ObjectContainer; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + */ +public class ScoreTest extends TestCase { + + private String uriA = "USK at MF2Vc6FRgeFMZJ0s2l9hOop87EYWAydUZakJzL0OfV8,fQeN-RMQZsUrDha2LCJWOMFk1-EiXZxfTnBT8NEgY00,AQACAAE/WoT/0"; + private String uriB = "USK at R3Lp2s4jdX-3Q96c0A9530qg7JsvA9vi2K0hwY9wG-4,ipkgYftRpo0StBlYkJUawZhg~SO29NZIINseUtBhEfE,AQACAAE/WoT/0"; + OwnIdentity a; + Identity b; + + private ObjectContainer db; + + public ScoreTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + + super.setUp(); + db = Db4o.openFile("scoreTest.db4o"); + + a = new OwnIdentity(uriA, uriA, "A", "true"); + b = new Identity(uriB, "B", "true"); + db.store(a); + db.store(b); + Score score = new Score(a,b,100,1,40); + db.store(score); + db.commit(); + } + + protected void tearDown() throws Exception { + db.close(); + new File("scoreTest.db4o").delete(); + } + + public void testScoreCreation() throws NotInTrustTreeException, DuplicateScoreException { + + Score score = b.getScore(a, db); + + assertTrue(score.getScore() == 100); + assertTrue(score.getRank() == 1); + assertTrue(score.getCapacity() == 40); + assertTrue(score.getTreeOwner() == a); + assertTrue(score.getTarget() == b); + } + + public void testScorePersistence() throws NotInTrustTreeException, DuplicateScoreException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { + + db.close(); + + System.gc(); + System.runFinalization(); + + db = Db4o.openFile("scoreTest.db4o"); + + a = OwnIdentity.getByURI(db, uriA); + b = Identity.getByURI(db, uriB); + Score score = b.getScore(a, db); + + assertTrue(score.getScore() == 100); + assertTrue(score.getRank() == 1); + assertTrue(score.getCapacity() == 40); + assertTrue(score.getTreeOwner() == a); + assertTrue(score.getTarget() == b); + } +} \ No newline at end of file Copied: trunk/plugins/WoT/Trust.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/Trust.java) =================================================================== --- trunk/plugins/WoT/Trust.java (rev 0) +++ trunk/plugins/WoT/Trust.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,116 @@ +/** + * 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.WoT; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import com.db4o.ObjectContainer; +import com.db4o.ObjectSet; + +/** + * A trust relationship between two identities + * + * @author Julien Cornuwel (batosai at freenetproject.org) + * + */ +public class Trust { + + /* We use a reference to the truster here rather that storing the trustList in the Identity. + * This allows us to load only what's needed in memory instead of everything. + * Maybe db4o can handle this, I don't know ATM. + */ + private Identity truster; + private Identity trustee; + private int value; + private String comment; + + + public Trust(Identity truster, Identity trustee, int value, String comment) throws InvalidParameterException { + this.truster = truster; + this.trustee = trustee; + setValue(value); + setComment(comment); + } + + public static int getNb(ObjectContainer db) { + ObjectSet<Trust> trusts = db.queryByExample(Trust.class); + return trusts.size(); + } + + public Element toXML(Document xmlDoc) { + Element elem = xmlDoc.createElement("trust"); + elem.setAttribute("uri", trustee.getRequestURI().toString()); + elem.setAttribute("value", String.valueOf(value)); + elem.setAttribute("comment", comment); + + return elem; + } + + public String toString() { + return getTruster().getNickName() + " trusts " + getTrustee().getNickName() + " (" + getValue() + " : " + getComment() + ")"; + } + + /** + * @return truster + */ + public Identity getTruster() { + return truster; + } + + /** + * @param truster Identity that gives the trust + */ + public void setTruster(Identity truster) { + this.truster = truster; + } + + /** + * @return trustee + */ + public Identity getTrustee() { + return trustee; + } + + /** + * @param trustee Identity that receives the trust + */ + public void setTrustee(Identity trustee) { + this.trustee = trustee; + } + + /** + * @return value + */ + public int getValue() { + return value; + } + + /** + * @param value Numeric value of the trust [-100;+100] + * @throws InvalidParameterException if value isn't in the range + */ + public void setValue(int value) throws InvalidParameterException { + if(value >= -100 && value <= 100) this.value = value; + else throw new InvalidParameterException("Invalid trust value ("+value+")"); + } + + /** + * + * @return Comment + */ + public String getComment() { + return comment; + } + + /** + * + * @param comment Comment on that trust relationship + */ + public void setComment(String comment) { + this.comment = comment; + } +} Copied: trunk/plugins/WoT/TrustTest.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/TrustTest.java) =================================================================== --- trunk/plugins/WoT/TrustTest.java (rev 0) +++ trunk/plugins/WoT/TrustTest.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,79 @@ +/** + * 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.WoT; + +import java.io.File; +import java.net.MalformedURLException; + +import junit.framework.TestCase; + +import com.db4o.Db4o; +import com.db4o.ObjectContainer; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + */ +public class TrustTest extends TestCase { + + private String uriA = "USK at MF2Vc6FRgeFMZJ0s2l9hOop87EYWAydUZakJzL0OfV8,fQeN-RMQZsUrDha2LCJWOMFk1-EiXZxfTnBT8NEgY00,AQACAAE/WoT/0"; + private String uriB = "USK at R3Lp2s4jdX-3Q96c0A9530qg7JsvA9vi2K0hwY9wG-4,ipkgYftRpo0StBlYkJUawZhg~SO29NZIINseUtBhEfE,AQACAAE/WoT/0"; + + private Identity a; + private Identity b; + + private ObjectContainer db; + + public TrustTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + + super.setUp(); + db = Db4o.openFile("trustTest.db4o"); + + a = new Identity(uriA, "A", "true"); + b = new Identity(uriB, "B", "true"); + Trust trust = new Trust(a,b,100,"test"); + db.store(trust); + db.store(a); + db.store(b); + db.commit(); + } + + protected void tearDown() throws Exception { + db.close(); + new File("trustTest.db4o").delete(); + } + + public void testTrust() throws InvalidParameterException, NotTrustedException, DuplicateTrustException { + + Trust trust = a.getGivenTrust(b, db); + assertTrue(trust.getTruster() == a); + assertTrue(trust.getTrustee() == b); + assertTrue(trust.getValue() == 100); + assertTrue(trust.getComment().equals("test")); + } + + public void testTrustPersistence() throws MalformedURLException, UnknownIdentityException, DuplicateIdentityException, NotTrustedException, DuplicateTrustException { + + db.close(); + + System.gc(); + System.runFinalization(); + + db = Db4o.openFile("trustTest.db4o"); + + a = Identity.getByURI(db, uriA); + b = Identity.getByURI(db, uriB); + Trust trust = a.getGivenTrust(b, db); + + assertTrue(trust.getTruster() == a); + assertTrue(trust.getTrustee() == b); + assertTrue(trust.getValue() == 100); + assertTrue(trust.getComment().equals("test")); + } +} Copied: trunk/plugins/WoT/Trustlist.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/Trustlist.java) =================================================================== --- trunk/plugins/WoT/Trustlist.java (rev 0) +++ trunk/plugins/WoT/Trustlist.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,52 @@ +/** + * 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.WoT; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import com.db4o.ObjectContainer; +import com.db4o.ObjectSet; +import com.db4o.ext.DatabaseClosedException; +import com.db4o.ext.Db4oIOException; + +/** + * TrustList of an Identity + * @author Julien Cornuwel (batosai at freenetproject.org) + * + */ +public class Trustlist { + + public ObjectSet<Trust> list; + + /** + * Creates the trustlist of a local Identity + * + * @param db Connection to db4o + * @param truster Identity that owns that trustList + * @throws InvalidParameterException + * @throws DatabaseClosedException + * @throws Db4oIOException + */ + public Trustlist(ObjectContainer db, OwnIdentity truster) throws Db4oIOException, DatabaseClosedException, InvalidParameterException { + list = truster.getGivenTrusts(db); + } + + /** + * Returns an XML Element containing the trustList + * @param xmlDoc The XML Document + * @return Element containing details of the trustList + */ + public Element toXML(Document xmlDoc) { + Element elem = xmlDoc.createElement("trustList"); + + while(list.hasNext()) { + elem.appendChild(list.next().toXML(xmlDoc)); + } + + return elem; + } +} Copied: trunk/plugins/WoT/UnknownIdentityException.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/UnknownIdentityException.java) =================================================================== --- trunk/plugins/WoT/UnknownIdentityException.java (rev 0) +++ trunk/plugins/WoT/UnknownIdentityException.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,20 @@ +/** + * 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.WoT; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + * + */ +public class UnknownIdentityException extends Exception { + + private static final long serialVersionUID = -1; + + public UnknownIdentityException(String message) { + super(message); + } + +} Copied: trunk/plugins/WoT/Version.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/Version.java) =================================================================== --- trunk/plugins/WoT/Version.java (rev 0) +++ trunk/plugins/WoT/Version.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,25 @@ +/** + * 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.WoT; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + * + */ +public class Version { + private static final String svnRevision = "@custom@"; + + static String getSvnRevision() { + return svnRevision; + } + + public static void main(String[] args) { + System.out.println("====="); + System.out.println(svnRevision); + System.out.println("====="); + } +} + Copied: trunk/plugins/WoT/WebInterface.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/WebInterface.java) =================================================================== --- trunk/plugins/WoT/WebInterface.java (rev 0) +++ trunk/plugins/WoT/WebInterface.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,478 @@ +/** + * 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.WoT; + +import java.net.MalformedURLException; +import java.util.Date; + +import com.db4o.ObjectContainer; +import com.db4o.ObjectSet; +import com.db4o.ext.DatabaseClosedException; +import com.db4o.ext.Db4oIOException; + +import freenet.client.HighLevelSimpleClient; +import freenet.clients.http.PageMaker; +import freenet.keys.FreenetURI; +import freenet.pluginmanager.PluginRespirator; +import freenet.support.HTMLNode; +import freenet.support.api.HTTPRequest; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + * + */ +public class WebInterface { + + private PluginRespirator pr; + private PageMaker pm; + private HighLevelSimpleClient client; + private String SELF_URI; + private ObjectContainer db; + + public WebInterface(PluginRespirator pr, ObjectContainer db, HighLevelSimpleClient client, String uri) { + this.pr = pr; + this.client = client; + this.SELF_URI = uri; + this.db = db; + + pm = pr.getPageMaker(); + pm.addNavigationLink(SELF_URI, "Home", "Home page", false, null); + pm.addNavigationLink(SELF_URI + "?ownidentities", "Own Identities", "Manage your own identities", false, null); + pm.addNavigationLink(SELF_URI + "?knownidentities", "Known Identities", "Manage others identities", false, null); + pm.addNavigationLink("/plugins/", "Plugins page", "Back to Plugins page", false, null); + } + + private HTMLNode getPageNode() { + return pm.getPageNode("Web of Trust", null); + } + + public String makeHomePage() { + + HTMLNode list = new HTMLNode("ul"); + + list.addChild(new HTMLNode("li", "Own Identities : " + OwnIdentity.getNbOwnIdentities(db))); + list.addChild(new HTMLNode("li", "Known Identities : " + Identity.getNbIdentities(db))); + list.addChild(new HTMLNode("li", "Trust relationships : " + Trust.getNb(db))); + list.addChild(new HTMLNode("li", "Scores : " + Score.getNb(db))); + + HTMLNode pageNode = getPageNode(); + HTMLNode contentNode = pm.getContentNode(pageNode); + HTMLNode box = pm.getInfobox("Summary"); + + HTMLNode boxContent = pm.getContentNode(box); + boxContent.addChild(list); + + contentNode.addChild(box); + return pageNode.generate(); + } + + public String makeOwnIdentitiesPage() { + + HTMLNode pageNode = getPageNode(); + HTMLNode contentNode = pm.getContentNode(pageNode); + HTMLNode box = pm.getInfobox("Own Identities"); + HTMLNode boxContent = pm.getContentNode(box); + + + ObjectSet<OwnIdentity> ownIdentities = OwnIdentity.getAllOwnIdentities(db); + if(ownIdentities.size() == 0) { + boxContent.addChild("p", "You have no own identity yet, you should create one..."); + } + else { + + HTMLNode identitiesTable = boxContent.addChild("table", "border", "0"); + HTMLNode row=identitiesTable.addChild("tr"); + row.addChild("th", "Name"); + row.addChild("th", "Last change"); + row.addChild("th", "Last insert"); + row.addChild("th", "Publish TrustList ?"); + row.addChild("th", "Manage"); + + while(ownIdentities.hasNext()) { + OwnIdentity id = ownIdentities.next(); + row=identitiesTable.addChild("tr"); + row.addChild("td", new String[] {"title", "style"}, new String[] {id.getRequestURI().toString(), "cursor: help;"}, id.getNickName()); + row.addChild("td",id.getLastChange().toString()); + HTMLNode cell = row.addChild("td"); + if(id.getLastInsert() == null) { + cell.addChild("p", "Insert in progress..."); + } + else if(id.getLastInsert().equals(new Date(0))) { + cell.addChild("p", "Never"); + } + else { + cell.addChild(new HTMLNode("a", "href", "/"+id.getRequestURI().toString(), id.getLastInsert().toString())); + } + row.addChild("td", id.doesPublishTrustList() ? "Yes" : "No"); + + HTMLNode manageCell = row.addChild("td"); + + HTMLNode editForm = pr.addFormChild(manageCell, SELF_URI, "editIdentity"); + editForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "editIdentity" }); + editForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "id", id.getRequestURI().toString() }); + editForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "edit", "Details" }); + + HTMLNode deleteForm = pr.addFormChild(manageCell, SELF_URI, "deleteIdentity"); + deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "deleteIdentity" }); + deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "id", id.getId() }); + deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "delete", "Delete" }); + } + } + + HTMLNode createForm = pr.addFormChild(boxContent, SELF_URI, "createIdentity"); + createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "createIdentity" }); + createForm.addChild("span", new String[] {"title", "style"}, new String[] { "No spaces or special characters.", "border-bottom: 1px dotted; cursor: help;"} , "NickName : "); + createForm.addChild("input", new String[] {"type", "name", "size"}, new String[] {"text", "nickName", "30"}); + createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "create", "Create a new identity !" }); + + contentNode.addChild(box); + + + // Form to restore an existing OwnIdentity from Freenet + HTMLNode restoreBox = pm.getInfobox("Restore an identity from Freenet"); + HTMLNode restoreBoxContent = pm.getContentNode(restoreBox); + + restoreBoxContent.addChild("p", "Use this if you lost your database for some reason (crash, reinstall...) but still have your identity's keys :"); + + HTMLNode restoreForm = pr.addFormChild(restoreBoxContent, SELF_URI, "restoreIdentity"); + restoreForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "restoreIdentity" }); + restoreForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "requestURI", "70", "Request URI" }); + restoreForm.addChild("br"); + restoreForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "insertURI", "70", "InsertURI" }); + restoreForm.addChild("br"); + restoreForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "restore", "Restore this identity !" }); + + restoreBoxContent.addChild("p", "Please don't use that identity (set trust, edit parameters...) until it has been restored from Freenet, or you might loose all its content."); + + contentNode.addChild(restoreBox); + + return pageNode.generate(); + } + + public String makeKnownIdentitiesPage() throws Db4oIOException, DatabaseClosedException, InvalidParameterException, NotInTrustTreeException, DuplicateScoreException, DuplicateTrustException { + return makeKnownIdentitiesPage(""); + } + + public String makeKnownIdentitiesPage(HTTPRequest request) throws Db4oIOException, DatabaseClosedException, InvalidParameterException, NotInTrustTreeException, DuplicateScoreException, DuplicateTrustException { + return makeKnownIdentitiesPage(request.getPartAsString("ownerURI", 1024)); + } + + public String makeKnownIdentitiesPage(String owner) throws Db4oIOException, DatabaseClosedException, InvalidParameterException, NotInTrustTreeException, DuplicateScoreException, DuplicateTrustException { + + OwnIdentity treeOwner = null; + + HTMLNode pageNode = getPageNode(); + HTMLNode contentNode = pm.getContentNode(pageNode); + + // Add an identity form + HTMLNode addBox = pm.getInfobox("Add an identity"); + HTMLNode addBoxContent = pm.getContentNode(addBox); + + HTMLNode createForm = pr.addFormChild(addBoxContent, SELF_URI, "addIdentity"); + createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "addIdentity" }); + createForm.addChild("span", new String[] {"title", "style"}, new String[] { "This must be a valid Freenet URI.", "border-bottom: 1px dotted; cursor: help;"} , "Identity URI : "); + createForm.addChild("input", new String[] {"type", "name", "size"}, new String[] {"text", "identityURI", "70"}); + createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "add", "Add this identity !" }); + + + // Known identities list + HTMLNode listBox = pm.getInfobox("Known Identities"); + HTMLNode listBoxContent = pm.getContentNode(listBox); + + int nbOwnIdentities = OwnIdentity.getNbOwnIdentities(db); + + if (nbOwnIdentities == 0) { + listBoxContent.addChild("p", "You should create an identity first..."); + contentNode.addChild(listBox); + return pageNode.generate(); + } + else if (nbOwnIdentities == 1) { + treeOwner = OwnIdentity.getAllOwnIdentities(db).next(); + } + else { + // Get the identity the user asked for, or the first one if he didn't + if(owner.equals("")) { + treeOwner = OwnIdentity.getAllOwnIdentities(db).next(); + } + else { + try { + treeOwner = OwnIdentity.getByURI(db, owner); + } catch (Exception e) { + return e.getMessage(); + } + } + + // Display a form to select the tree owner + HTMLNode selectForm = pr.addFormChild(listBoxContent, SELF_URI, "viewTree"); + selectForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "viewTree" }); + HTMLNode selectBox = selectForm.addChild("select", "name", "ownerURI"); + + ObjectSet<OwnIdentity> ownIdentities = OwnIdentity.getAllOwnIdentities(db); + while(ownIdentities.hasNext()) { + OwnIdentity ownIdentity = ownIdentities.next(); + if(ownIdentity == treeOwner) { + selectBox.addChild("option", new String [] {"value", "selected"}, new String [] {ownIdentity.getRequestURI().toString(), "selected"}, ownIdentity.getNickName()); + } + else { + selectBox.addChild("option", "value", ownIdentity.getRequestURI().toString(), ownIdentity.getNickName()); + } + } + selectForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "select", "View this identity's Web of Trust" }); + } + + // Display the list of known identities + HTMLNode identitiesTable = listBoxContent.addChild("table", "border", "0"); + HTMLNode row=identitiesTable.addChild("tr"); + row.addChild("th", "NickName"); + row.addChild("th", "Last update"); + row.addChild("th", "Publish TrustList ?"); + row.addChild("th", "Score (Rank)"); + row.addChild("th", "Trust/Comment"); + row.addChild("th", "Trusters"); + row.addChild("th", "Trustees"); + + ObjectSet<Identity> identities = Identity.getAllIdentities(db); + while(identities.hasNext()) { + Identity id = identities.next(); + + if(id == treeOwner) continue; + + row=identitiesTable.addChild("tr"); + + // NickName + row.addChild("td", new String[] {"title", "style"}, new String[] {id.getRequestURI().toString(), "cursor: help;"}, id.getNickName()); + + // Last Change + if (id.getLastChange().equals(new Date(0))) row.addChild("td", "Fetching..."); + else row.addChild("td", id.getLastChange().toString()); + + // Publish TrustList + row.addChild("td", new String[] { "align" }, new String[] { "center" } , id.doesPublishTrustList() ? "Yes" : "No"); + + //Score + try { + row.addChild("td", new String[] { "align" }, new String[] { "center" } , String.valueOf(id.getScore((OwnIdentity)treeOwner, db).getScore())+" ("+id.getScore((OwnIdentity)treeOwner, db).getRank()+")"); + } + catch (NotInTrustTreeException e) { + // This only happen with identities added manually by the user + // TODO Maybe we should give the opportunity to trust it at creation time + row.addChild("td", "null"); + } + + // Trust + String trustValue = ""; + String trustComment = ""; + + Trust trust; + try { + trust = treeOwner.getGivenTrust(id, db); + trustValue = String.valueOf(trust.getValue()); + trustComment = trust.getComment(); + } catch (NotTrustedException e) {} + + HTMLNode cell = row.addChild("td"); + HTMLNode trustForm = pr.addFormChild(cell, SELF_URI, "setTrust"); + trustForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "setTrust" }); + trustForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "truster", treeOwner.getRequestURI().toString() }); + trustForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "trustee", id.getRequestURI().toString() }); + trustForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "value", "2", trustValue }); + trustForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "comment", "20", trustComment }); + trustForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "update", "Update !" }); + + // Trusters + HTMLNode trustersCell = row.addChild("td", new String[] { "align" }, new String[] { "center" }); + trustersCell.addChild(new HTMLNode("a", "href", SELF_URI + "?getTrusters&id="+id.getId(), Long.toString(id.getNbReceivedTrusts(db)))); + + //Trustees + HTMLNode trusteesCell = row.addChild("td", new String[] { "align" }, new String[] { "center" }); + trusteesCell.addChild(new HTMLNode("a", "href", SELF_URI + "?getTrustees&id="+id.getId(), Long.toString(id.getNbGivenTrusts(db)))); + } + contentNode.addChild(addBox); + contentNode.addChild(listBox); + return pageNode.generate(); + } + + public String makeCreateIdentityPage(HTTPRequest request) { + + String nickName = request.getPartAsString("nickName",1024); + HTMLNode pageNode = getPageNode(); + HTMLNode contentNode = pm.getContentNode(pageNode); + HTMLNode box = pm.getInfobox("Identity creation"); + HTMLNode boxContent = pm.getContentNode(box); + + FreenetURI[] keypair = client.generateKeyPair("WoT"); + + HTMLNode createForm = pr.addFormChild(boxContent, SELF_URI, "createIdentity2"); + createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "createIdentity2" }); + createForm.addChild("#", "Request URI : "); + createForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "requestURI", "70", keypair[1].toString() }); + createForm.addChild("br"); + createForm.addChild("#", "Insert URI : "); + createForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "insertURI", "70", keypair[0].toString() }); + createForm.addChild("br"); + createForm.addChild("#", "Publish trust list "); + createForm.addChild("input", new String[] { "type", "name", "value", "checked" }, new String[] { "checkbox", "publishTrustList", "true", "checked"}); + createForm.addChild("br"); + createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "nickName", nickName }); + createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "create", "Create a new identity !" }); + + contentNode.addChild(box); + return pageNode.generate(); + } + + public String makeEditIdentityPage(String requestURI) throws MalformedURLException, InvalidParameterException, UnknownIdentityException, DuplicateIdentityException { + + OwnIdentity id = OwnIdentity.getByURI(db, requestURI); + + HTMLNode pageNode = getPageNode(); + HTMLNode contentNode = pm.getContentNode(pageNode); + HTMLNode box = pm.getInfobox("Identity edition"); + HTMLNode boxContent = pm.getContentNode(box); + + HTMLNode createForm = pr.addFormChild(boxContent, SELF_URI, "editIdentity2"); + createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "editIdentity2"}); + + createForm.addChild("p", "NickName : " + id.getNickName()); + + createForm.addChild("p", new String[] { "style" }, new String[] { "font-size: x-small" }, "Request URI : "+id.getRequestURI().toString()); + createForm.addChild("p", new String[] { "style" }, new String[] { "font-size: x-small" }, "Insert URI : "+id.getInsertURI().toString()); + + createForm.addChild("#", "Publish trust list "); + if(id.doesPublishTrustList()) + createForm.addChild("input", new String[] { "type", "name", "value", "checked" }, new String[] { "checkbox", "publishTrustList", "true", "checked"}); + else + createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "checkbox", "publishTrustList", "true"}); + createForm.addChild("br"); + + createForm.addChild("p", "Contexts : "+id.getContextsAsString()); + + createForm.addChild("p", "Properties : "+id.getPropsAsString()); + + // TODO Give the user the ability to edit these parameters... + + contentNode.addChild(box); + return pageNode.generate(); + } + + public String getTrustersPage(String id) throws DuplicateIdentityException, UnknownIdentityException { + + Identity identity = Identity.getById(db, id); + + HTMLNode pageNode = getPageNode(); + HTMLNode contentNode = pm.getContentNode(pageNode); + HTMLNode box = pm.getInfobox("Identities that trust '" + identity.getNickName() + "'"); + HTMLNode boxContent = pm.getContentNode(box); + + // Display the list of known identities + HTMLNode identitiesTable = boxContent.addChild("table", "border", "0"); + HTMLNode title = identitiesTable.addChild("tr"); + title.addChild("th", "NickName"); + title.addChild("th", "Last update"); + title.addChild("th", "Trust (Comment)"); + title.addChild("th", "Trusters"); + title.addChild("th", "Trustees"); + + ObjectSet<Trust> trusters = identity.getReceivedTrusts(db); + while(trusters.hasNext()) { + + Trust trust = trusters.next(); + HTMLNode row=identitiesTable.addChild("tr"); + + // NickName + row.addChild("td", new String[] {"title", "style"}, new String[] {trust.getTruster().getRequestURI().toString(), "cursor: help;"}, trust.getTruster().getNickName()); + + // Last Change + if (trust.getTruster().getLastChange().equals(new Date(0))) row.addChild("td", "Fetching..."); + else row.addChild("td", trust.getTruster().getLastChange().toString()); + + // Trust/Comment + row.addChild("td", trust.getValue() + " (" + trust.getComment() + ")"); + + // Trusters + HTMLNode trustersCell = row.addChild("td", new String[] { "align" }, new String[] { "center" }); + trustersCell.addChild(new HTMLNode("a", "href", SELF_URI + "?getTrusters&id="+trust.getTruster().getId(), Long.toString(trust.getTruster().getNbReceivedTrusts(db)))); + + //Trustees + HTMLNode trusteesCell = row.addChild("td", new String[] { "align" }, new String[] { "center" }); + trusteesCell.addChild(new HTMLNode("a", "href", SELF_URI + "?getTrustees&id="+trust.getTruster().getId(), Long.toString(trust.getTruster().getNbGivenTrusts(db)))); + + } + + contentNode.addChild(box); + return pageNode.generate(); + } + + public String getTrusteesPage(String id) throws DuplicateIdentityException, UnknownIdentityException { + + Identity identity = Identity.getById(db, id); + + HTMLNode pageNode = getPageNode(); + HTMLNode contentNode = pm.getContentNode(pageNode); + HTMLNode box = pm.getInfobox("Identities that '" + identity.getNickName() + "' trusts"); + HTMLNode boxContent = pm.getContentNode(box); + + // Display the list of known identities + HTMLNode identitiesTable = boxContent.addChild("table", "border", "0"); + HTMLNode title = identitiesTable.addChild("tr"); + title.addChild("th", "NickName"); + title.addChild("th", "Last update"); + title.addChild("th", "Trust (Comment)"); + title.addChild("th", "Trusters"); + title.addChild("th", "Trustees"); + + ObjectSet<Trust> trustees = identity.getGivenTrusts(db); + while(trustees.hasNext()) { + + Trust trust = trustees.next(); + HTMLNode row=identitiesTable.addChild("tr"); + + // NickName + row.addChild("td", new String[] {"title", "style"}, new String[] {trust.getTrustee().getRequestURI().toString(), "cursor: help;"}, trust.getTrustee().getNickName()); + + // Last Change + if (trust.getTrustee().getLastChange().equals(new Date(0))) row.addChild("td", "Fetching..."); + else row.addChild("td", trust.getTrustee().getLastChange().toString()); + + // Trust/Comment + row.addChild("td", trust.getValue() + " (" + trust.getComment() + ")"); + + // Trusters + HTMLNode trustersCell = row.addChild("td", new String[] { "align" }, new String[] { "center" }); + trustersCell.addChild(new HTMLNode("a", "href", SELF_URI + "?getTrusters&id="+trust.getTrustee().getId(), Long.toString(trust.getTrustee().getNbReceivedTrusts(db)))); + + //Trustees + HTMLNode trusteesCell = row.addChild("td", new String[] { "align" }, new String[] { "center" }); + trusteesCell.addChild(new HTMLNode("a", "href", SELF_URI + "?getTrustees&id="+trust.getTrustee().getId(), Long.toString(trust.getTrustee().getNbGivenTrusts(db)))); + + } + + contentNode.addChild(box); + return pageNode.generate(); + } + + public String makeDeleteIdentityPage(String id) throws DuplicateIdentityException, UnknownIdentityException { + Identity identity = Identity.getById(db, id); + + HTMLNode pageNode = getPageNode(); + HTMLNode contentNode = pm.getContentNode(pageNode); + HTMLNode box = pm.getInfobox("Confirm identity deletion"); + HTMLNode boxContent = pm.getContentNode(box); + + boxContent.addChild(new HTMLNode("p", "You are about to delete identity '" + identity.getNickName() + "', are you sure ?")); + + if(identity instanceof OwnIdentity) + boxContent.addChild(new HTMLNode("p", "You might want to backup its keys for later use...")); + + HTMLNode confirmForm = pr.addFormChild(boxContent, SELF_URI, "deleteIdentity2"); + + confirmForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "deleteIdentity2" }); + confirmForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "id", identity.getId() }); + confirmForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "confirm", "Confirm !" }); + + contentNode.addChild(box); + return pageNode.generate(); + } +} Copied: trunk/plugins/WoT/WoT.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/WoT.java) =================================================================== --- trunk/plugins/WoT/WoT.java (rev 0) +++ trunk/plugins/WoT/WoT.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,691 @@ +/** + * 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.WoT; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.MalformedURLException; +import java.util.Iterator; +import java.util.Map.Entry; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; + +import com.db4o.Db4o; +import com.db4o.config.Configuration; +import com.db4o.ObjectContainer; +import com.db4o.ObjectSet; +import com.db4o.ext.DatabaseClosedException; +import com.db4o.ext.Db4oIOException; + +import freenet.client.FetchException; +import freenet.client.HighLevelSimpleClient; +import freenet.client.InsertException; +import freenet.keys.FreenetURI; +import freenet.l10n.L10n.LANGUAGE; +import freenet.pluginmanager.FredPlugin; +import freenet.pluginmanager.FredPluginFCP; +import freenet.pluginmanager.FredPluginHTTP; +import freenet.pluginmanager.FredPluginL10n; +import freenet.pluginmanager.FredPluginThreadless; +import freenet.pluginmanager.FredPluginVersioned; +import freenet.pluginmanager.PluginHTTPException; +import freenet.pluginmanager.PluginReplySender; +import freenet.pluginmanager.PluginRespirator; +import freenet.support.Logger; +import freenet.support.SimpleFieldSet; +import freenet.support.api.Bucket; +import freenet.support.api.HTTPRequest; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + */ +public class WoT implements FredPlugin, FredPluginHTTP, FredPluginThreadless, FredPluginFCP, FredPluginVersioned, FredPluginL10n { + + private PluginRespirator pr; + private HighLevelSimpleClient client; + + private ObjectContainer db; + private WebInterface web; + private IdentityInserter inserter; + private IdentityFetcher fetcher; + private String seedURI = "USK at MF2Vc6FRgeFMZJ0s2l9hOop87EYWAydUZakJzL0OfV8,fQeN-RMQZsUrDha2LCJWOMFk1-EiXZxfTnBT8NEgY00,AQACAAE/WoT/0"; + private Identity seed; + //private Config config; + + public static String SELF_URI = "/plugins/plugins.WoT.WoT"; + + public void runPlugin(PluginRespirator pr) { + + Logger.debug(this, "Start"); + + // Init + this.pr = pr; + Configuration config = Db4o.newConfiguration(); + config.objectClass(Identity.class).objectField("id").indexed(true); + config.objectClass(OwnIdentity.class).objectField("id").indexed(true); + config.objectClass(Trust.class).objectField("truster").indexed(true); + config.objectClass(Trust.class).objectField("trustee").indexed(true); + config.objectClass(Score.class).objectField("treeOwner").indexed(true); + config.objectClass(Score.class).objectField("target").indexed(true); + db = Db4o.openFile(config, "WoT.db4o"); + + client = pr.getHLSimpleClient(); + web = new WebInterface(pr, db, client, SELF_URI); + + /* + try { + ObjectSet<Config> result = db.queryByExample(Config.class); + if(result.size() == 0) { + Logger.debug(this, "Created new config"); + config = new Config(db); + db.store(config); + } + else { + Logger.debug(this, "Loaded config"); + config = result.next(); + config.initDefault(false); + } + } + catch(Exception e) { + Logger.error(this, e.getMessage(), e); + } + */ + + // Create the seed Identity if it doesn't exist + try { + seed = Identity.getByURI(db, seedURI); + } catch (UnknownIdentityException e) { + try { + seed = new Identity(seedURI, "Fetching seed identity...", "true"); + } catch (Exception e1) { + Logger.error(this, "Seed identity creation error", e); + return; + } + db.store(seed); + db.commit(); + } catch (Exception e) { + Logger.error(this, "Seed identity loading error", e); + return; + } + + // Start the inserter thread + inserter = new IdentityInserter(db, client, pr.getNode().clientCore.tempBucketFactory); + pr.getNode().executor.execute(inserter, "WoTinserter"); + + // Create the fetcher + fetcher = new IdentityFetcher(db, client); + + // Try to fetch all known identities + ObjectSet<Identity> identities = Identity.getAllIdentities(db); + while (identities.hasNext()) { + fetcher.fetch(identities.next(), true); + } + } + + public void terminate() { + inserter.stop(); + db.commit(); + db.close(); + fetcher.stop(); // Do this after cleanly closing the database, as it sometimes locks + } + + public String handleHTTPGet(HTTPRequest request) throws PluginHTTPException { + + try { + if(request.isParameterSet("ownidentities")) + return web.makeOwnIdentitiesPage(); + + if(request.isParameterSet("knownidentities")) + return web.makeKnownIdentitiesPage(); + + if(request.isParameterSet("getTrusters")) + return web.getTrustersPage(request.getParam("id")); + + if(request.isParameterSet("getTrustees")) + return web.getTrusteesPage(request.getParam("id")); + + return web.makeHomePage(); + + } catch (Exception e) { + e.printStackTrace(); + return e.getMessage(); + } + } + + public String handleHTTPPost(HTTPRequest request) throws PluginHTTPException { + + String pass = request.getPartAsString("formPassword", 32); + if ((pass.length() == 0) || !pass.equals(pr.getNode().clientCore.formPassword)) { + return "Buh! Invalid form password"; + } + + try { + if(request.getPartAsString("page",50).equals("createIdentity")) { + return web.makeCreateIdentityPage(request); + } + else if(request.getPartAsString("page",50).equals("createIdentity2")) { + createIdentity(request); + return web.makeOwnIdentitiesPage(); + } + else if(request.getPartAsString("page",50).equals("addIdentity")) { + addIdentity(request); + return web.makeKnownIdentitiesPage(); + } + else if(request.getPartAsString("page",50).equals("viewTree")) { + return web.makeKnownIdentitiesPage(request); + } + else if(request.getPartAsString("page",50).equals("setTrust")) { + setTrust(request); + return web.makeKnownIdentitiesPage(request.getPartAsString("truster", 1024)); + } + else if(request.getPartAsString("page",50).equals("editIdentity")) { + return web.makeEditIdentityPage(request.getPartAsString("id", 1024)); + } + else if(request.getPartAsString("page",50).equals("restoreIdentity")) { + restoreIdentity(request.getPartAsString("requestURI", 1024), request.getPartAsString("insertURI", 1024)); + return web.makeOwnIdentitiesPage(); + } + else if(request.getPartAsString("page",50).equals("deleteIdentity")) { + return web.makeDeleteIdentityPage(request.getPartAsString("id", 1024)); + } + else if(request.getPartAsString("page",50).equals("deleteIdentity2")) { + deleteIdentity(request.getPartAsString("id", 1024)); + return web.makeOwnIdentitiesPage(); + } + else { + return web.makeHomePage(); + } + } catch (Exception e) { + e.printStackTrace(); + return e.getLocalizedMessage(); + } + } + + private void deleteIdentity(String id) throws DuplicateIdentityException, UnknownIdentityException, DuplicateScoreException, DuplicateTrustException { + Identity identity = Identity.getById(db, id); + + // Remove all scores + ObjectSet<Score> scores = identity.getScores(db); + while (scores.hasNext()) db.delete(scores.next()); + + // Remove all received trusts + ObjectSet<Trust> receivedTrusts = identity.getReceivedTrusts(db); + while (receivedTrusts.hasNext()) db.delete(receivedTrusts.next()); + + // Remove all given trusts and update trustees' scores + ObjectSet<Trust> givenTrusts = identity.getGivenTrusts(db); + while (givenTrusts.hasNext()) { + Trust givenTrust = givenTrusts.next(); + db.delete(givenTrust); + givenTrust.getTrustee().updateScore(db); + } + + db.delete(identity); + } + + private void restoreIdentity(String requestURI, String insertURI) throws InvalidParameterException, MalformedURLException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, DuplicateIdentityException, DuplicateTrustException { + + OwnIdentity id; + + try { + Identity old = Identity.getByURI(db, requestURI); + + // We already have fetched this identity as a stranger's one. We need to update the database. + id = new OwnIdentity(insertURI, requestURI, old.getNickName(), old.doesPublishTrustList() ? "true" : "false"); + + Iterator<String> i1 = old.getContexts(); + while (i1.hasNext()) id.addContext(i1.next(), db); + + Iterator<Entry<String, String>> i2 = old.getProps(); + while (i2.hasNext()) { + Entry<String, String> prop = i2.next(); + id.setProp(prop.getKey(), prop.getValue(), db); + } + + // Update all received trusts + ObjectSet<Trust> receivedTrusts = old.getReceivedTrusts(db); + while(receivedTrusts.hasNext()) { + Trust receivedTrust = receivedTrusts.next(); + receivedTrust.setTrustee(id); + db.store(receivedTrust); + } + + // Update all received scores + ObjectSet<Score> scores = old.getScores(db); + while(scores.hasNext()) { + Score score = scores.next(); + score.setTarget(id); + db.store(score); + } + + // Store the new identity + db.store(id); + id.initTrustTree(db); + + // Update all given trusts + ObjectSet<Trust> givenTrusts = old.getGivenTrusts(db); + while(givenTrusts.hasNext()) { + Trust givenTrust = givenTrusts.next(); + id.setTrust(db, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); + db.delete(givenTrust); + } + + // Remove the old identity + db.delete(old); + + Logger.debug(this, "Successfully restored an already known identity from Freenet (" + id.getNickName() + ")"); + + } catch (UnknownIdentityException e) { + id = new OwnIdentity(insertURI, requestURI, "Restore in progress...", "false"); + + // Store the new identity + db.store(id); + id.initTrustTree(db); + + // Fetch the identity from freenet + fetcher.fetch(id); + + Logger.debug(this, "Trying to restore a not-yet-known identity from Freenet (" + id.getRequestURI() + ")"); + } + db.commit(); + } + + private void setTrust(HTTPRequest request) throws NumberFormatException, TransformerConfigurationException, FileNotFoundException, InvalidParameterException, UnknownIdentityException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, DuplicateIdentityException, NotTrustedException, DuplicateTrustException { + + setTrust( request.getPartAsString("truster", 1024), + request.getPartAsString("trustee", 1024), + request.getPartAsString("value", 1024), + request.getPartAsString("comment", 1024)); + } + + private void setTrust(String truster, String trustee, String value, String comment) throws InvalidParameterException, UnknownIdentityException, NumberFormatException, TransformerConfigurationException, FileNotFoundException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, DuplicateIdentityException, NotTrustedException, DuplicateTrustException { + + OwnIdentity trusterId = OwnIdentity.getByURI(db, truster); + Identity trusteeId = Identity.getByURI(db, trustee); + + setTrust((OwnIdentity)trusterId, trusteeId, Integer.parseInt(value), comment); +} + + private void setTrust(OwnIdentity truster, Identity trustee, int value, String comment) throws TransformerConfigurationException, FileNotFoundException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, InvalidParameterException, DuplicateScoreException, NotTrustedException, DuplicateTrustException { + + truster.setTrust(db, trustee, value, comment); + truster.updated(); + db.store(truster); + db.commit(); + } + + private void addIdentity(HTTPRequest request) throws MalformedURLException, InvalidParameterException, FetchException, DuplicateIdentityException { + addIdentity(request.getPartAsString("identityURI", 1024).trim()); + } + + private Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException, FetchException, DuplicateIdentityException { + Identity identity = null; + try { + identity = Identity.getByURI(db, requestURI); + Logger.error(this, "Tried to manually add an identity we already know, ignored."); + throw new InvalidParameterException("We already have this identity"); + } + catch (UnknownIdentityException e) { + // TODO Only add the identity after it is successfully fetched + + identity = new Identity(requestURI, "Not found yet...", "false"); + db.store(identity); + db.commit(); + Logger.debug(this, "Trying to fetch manually added identity (" + identity.getRequestURI() + ")"); + fetcher.fetch(identity); + } + return identity; + } + + private OwnIdentity createIdentity(HTTPRequest request) throws TransformerConfigurationException, FileNotFoundException, InvalidParameterException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, NotTrustedException, DuplicateTrustException { + + return createIdentity( request.getPartAsString("insertURI",1024), + request.getPartAsString("requestURI",1024), + request.getPartAsString("nickName", 1024), + request.getPartAsString("publishTrustList", 1024), + "testing"); + } + + private OwnIdentity createIdentity(String nickName, String publishTrustList, String context) throws TransformerConfigurationException, FileNotFoundException, InvalidParameterException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, NotTrustedException, DuplicateTrustException { + + FreenetURI[] keypair = client.generateKeyPair("WoT"); + return createIdentity(keypair[0].toString(), keypair[1].toString(), nickName, publishTrustList, context); + } + + private OwnIdentity createIdentity(String insertURI, String requestURI, String nickName, String publishTrustList, String context) throws InvalidParameterException, TransformerConfigurationException, FileNotFoundException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, NotTrustedException, DuplicateTrustException { + + // TODO Add context in the creation form + OwnIdentity identity = new OwnIdentity(insertURI, requestURI, nickName, publishTrustList); + db.store(identity); + identity.initTrustTree(db); + + // This identity trusts the seed identity + identity.setTrust(db, seed, 100, "I trust the WoT plugin"); + + Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickName() + ")"); + + db.commit(); + + return identity; + } + + private void addContext(String identity, String context) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { + Identity id = OwnIdentity.getByURI(db, identity); + id.addContext(context, db); + db.store(id); + + Logger.debug(this, "Added context '" + context + "' to identity '" + id.getNickName() + "'"); + } + + private void removeContext(String identity, String context) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { + Identity id = OwnIdentity.getByURI(db, identity); + id.removeContext(context, db); + db.store(id); + + Logger.debug(this, "Removed context '" + context + "' from identity '" + id.getNickName() + "'"); + } + + private void setProperty(String identity, String property, String value) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { + Identity id = OwnIdentity.getByURI(db, identity); + id.setProp(property, value, db); + db.store(id); + + Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + id.getNickName() + "'"); + } + + private String getProperty(String identity, String property) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { + return Identity.getByURI(db, identity).getProp(property); + } + + private void removeProperty(String identity, String property) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { + Identity id = OwnIdentity.getByURI(db, identity); + id.removeProp(property, db); + db.store(id); + + Logger.debug(this, "Removed property '" + property + "' from identity '" + id.getNickName() + "'"); + } + + public String handleHTTPPut(HTTPRequest request) throws PluginHTTPException { + return null; + } + + public String getVersion() { + return "0.3.1 r"+Version.getSvnRevision(); + } + + public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { + + try { + if(params.get("Message").equals("CreateIdentity")) { + replysender.send(handleCreateIdentity(params), data); + } + else if(params.get("Message").equals("SetTrust")) { + replysender.send(handleSetTrust(params), data); + } + else if(params.get("Message").equals("AddIdentity")) { + replysender.send(handleAddIdentity(params), data); + } + else if(params.get("Message").equals("GetIdentity")) { + replysender.send(handleGetIdentity(params), data); + } + else if(params.get("Message").equals("GetIdentitiesByScore")) { + replysender.send(handleGetIdentitiesByScore(params), data); + } + else if(params.get("Message").equals("GetTrusters")) { + replysender.send(handleGetTrusters(params), data); + } + else if(params.get("Message").equals("GetTrustees")) { + replysender.send(handleGetTrustees(params), data); + } + else if(params.get("Message").equals("AddContext")) { + replysender.send(handleAddContext(params), data); + } + else if(params.get("Message").equals("RemoveContext")) { + replysender.send(handleRemoveContext(params), data); + } + else if(params.get("Message").equals("SetProperty")) { + replysender.send(handleSetProperty(params), data); + } + else if(params.get("Message").equals("GetProperty")) { + replysender.send(handleGetProperty(params), data); + } + else if(params.get("Message").equals("RemoveProperty")) { + replysender.send(handleRemoveProperty(params), data); + } + else { + throw new Exception("Unknown message (" + params.get("Message") + ")"); + } + } + catch (Exception e) { + replysender.send(errorMessageFCP(e), data); + } + } + + private SimpleFieldSet handleCreateIdentity(SimpleFieldSet params) throws TransformerConfigurationException, FileNotFoundException, InvalidParameterException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, NotTrustedException, DuplicateTrustException { + + SimpleFieldSet sfs = new SimpleFieldSet(false); + OwnIdentity identity; + + if(params.get("NickName")==null || params.get("PublishTrustList")==null || params.get("Context")==null) throw new InvalidParameterException("Missing mandatory parameter"); + + if(params.get("RequestURI")==null || params.get("InsertURI")==null) { + identity = createIdentity(params.get("NickName"), params.get("PublishTrustList"), params.get("Context")); + } + else { + identity = createIdentity( params.get("InsertURI"), + params.get("RequestURI"), + params.get("NickName"), + params.get("PublishTrustList"), + params.get("Context")); + } + sfs.putAppend("Message", "IdentityCreated"); + sfs.putAppend("InsertURI", identity.getInsertURI().toString()); + sfs.putAppend("RequestURI", identity.getRequestURI().toString()); + return sfs; + } + + private SimpleFieldSet handleSetTrust(SimpleFieldSet params) throws NumberFormatException, TransformerConfigurationException, FileNotFoundException, InvalidParameterException, ParserConfigurationException, TransformerException, IOException, InsertException, UnknownIdentityException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, DuplicateIdentityException, NotTrustedException, DuplicateTrustException { + + SimpleFieldSet sfs = new SimpleFieldSet(false); + + if(params.get("Truster") == null || params.get("Trustee") == null || params.get("Value") == null || params.get("Comment") == null) throw new InvalidParameterException("Missing mandatory parameter"); + + setTrust(params.get("Truster"), params.get("Trustee"), params.get("Value"), params.get("Comment")); + + sfs.putAppend("Message", "TrustSet"); + return sfs; + } + + private SimpleFieldSet handleAddIdentity(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, FetchException, DuplicateIdentityException { + + SimpleFieldSet sfs = new SimpleFieldSet(false); + + if(params.get("RequestURI") == null) throw new InvalidParameterException("Missing mandatory parameter"); + + Identity identity = addIdentity(params.get("RequestURI").trim()); + + sfs.putAppend("Message", "IdentityAdded"); + sfs.putAppend("RequestURI", identity.getRequestURI().toString()); + return sfs; + } + + private SimpleFieldSet handleGetIdentity(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, FetchException, UnknownIdentityException, DuplicateScoreException, DuplicateIdentityException, DuplicateTrustException { + + SimpleFieldSet sfs = new SimpleFieldSet(false); + + if(params.get("TreeOwner") == null || params.get("Identity") == null) throw new InvalidParameterException("Missing mandatory parameter"); + + sfs.putAppend("Message", "Identity"); + + OwnIdentity treeOwner = OwnIdentity.getByURI(db, params.get("TreeOwner")); + Identity identity = Identity.getByURI(db, params.get("Identity")); + + try { + Trust trust = identity.getReceivedTrust(treeOwner, db); + sfs.putAppend("Trust", String.valueOf(trust.getValue())); + } catch (NotTrustedException e1) { + sfs.putAppend("Trust", "null"); + } + + Score score; + try { + score = identity.getScore(treeOwner, db); + sfs.putAppend("Score", String.valueOf(score.getScore())); + sfs.putAppend("Rank", String.valueOf(score.getRank())); + } catch (NotInTrustTreeException e) { + sfs.putAppend("Score", "null"); + sfs.putAppend("Rank", "null"); + } + + Iterator<String> contexts = identity.getContexts(); + for(int i = 1 ; contexts.hasNext() ; i++) sfs.putAppend("Context"+i, contexts.next()); + + return sfs; + } + + private SimpleFieldSet handleGetIdentitiesByScore(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { + + SimpleFieldSet sfs = new SimpleFieldSet(false); + + if(params.get("TreeOwner") == null || params.get("Select") == null || params.get("Context") == null) throw new InvalidParameterException("Missing mandatory parameter"); + + sfs.putAppend("Message", "Identities"); + + ObjectSet<Score> result = Score.getIdentitiesByScore(params.get("TreeOwner"), params.get("Select").trim(), db); + for(int i = 1 ; result.hasNext() ; i++) { + Score score = result.next(); + // Maybe there is a way to do this through SODA + if(score.getTarget().hasContext(params.get("Context")) || params.get("Context").equals("all")) + sfs.putAppend("Identity"+i, score.getTarget().getRequestURI().toString()); + } + return sfs; + } + + private SimpleFieldSet handleGetTrusters(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, Db4oIOException, DatabaseClosedException, DuplicateIdentityException { + + SimpleFieldSet sfs = new SimpleFieldSet(false); + + if(params.get("Identity") == null || params.get("Context") == null) throw new InvalidParameterException("Missing mandatory parameter"); + + sfs.putAppend("Message", "Identities"); + + ObjectSet<Trust> result = Identity.getByURI(db, params.get("Identity")).getReceivedTrusts(db); + + for(int i = 1 ; result.hasNext() ; i++) { + Trust trust = result.next(); + // Maybe there is a way to do this through SODA + if(trust.getTruster().hasContext(params.get("Context")) || params.get("Context").equals("all")) { + sfs.putAppend("Identity"+i, trust.getTruster().getRequestURI().toString()); + sfs.putAppend("Value"+i, String.valueOf(trust.getValue())); + sfs.putAppend("Comment"+i, trust.getComment()); + } + } + return sfs; + } + + private SimpleFieldSet handleGetTrustees(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, Db4oIOException, DatabaseClosedException, DuplicateIdentityException { + + SimpleFieldSet sfs = new SimpleFieldSet(false); + + if(params.get("Identity") == null || params.get("Context") == null) throw new InvalidParameterException("Missing mandatory parameter"); + + sfs.putAppend("Message", "Identities"); + + ObjectSet<Trust> result = Identity.getByURI(db, params.get("Identity")).getGivenTrusts(db); + + for(int i = 1 ; result.hasNext() ; i++) { + Trust trust = result.next(); + // Maybe there is a way to do this through SODA + if(trust.getTrustee().hasContext(params.get("Context")) || params.get("Context").equals("all")) { + sfs.putAppend("Identity"+i, trust.getTrustee().getRequestURI().toString()); + sfs.putAppend("Value"+i, String.valueOf(trust.getValue())); + sfs.putAppend("Comment"+i, trust.getComment()); + } + } + return sfs; + } + + private SimpleFieldSet handleAddContext(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { + + SimpleFieldSet sfs = new SimpleFieldSet(false); + + if(params.get("Identity") == null || params.get("Context") == null) throw new InvalidParameterException("Missing mandatory parameter"); + + addContext(params.get("Identity"), params.get("Context")); + + sfs.putAppend("Message", "ContextAdded"); + return sfs; + } + + private SimpleFieldSet handleRemoveContext(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { + + SimpleFieldSet sfs = new SimpleFieldSet(false); + + if(params.get("Identity") == null || params.get("Context") == null) throw new InvalidParameterException("Missing mandatory parameter"); + + removeContext(params.get("Identity"), params.get("Context")); + + sfs.putAppend("Message", "ContextRemoved"); + return sfs; + } + + private SimpleFieldSet handleSetProperty(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { + + SimpleFieldSet sfs = new SimpleFieldSet(false); + + if(params.get("Identity") == null || params.get("Property") == null || params.get("Value") == null) throw new InvalidParameterException("Missing mandatory parameter"); + + setProperty(params.get("Identity"), params.get("Property"), params.get("Value")); + + sfs.putAppend("Message", "PropertyAdded"); + return sfs; + } + + private SimpleFieldSet handleGetProperty(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { + + SimpleFieldSet sfs = new SimpleFieldSet(false); + + if(params.get("Identity") == null || params.get("Property") == null) throw new InvalidParameterException("Missing mandatory parameter"); + + sfs.putAppend("Message", "PropertyValue"); + sfs.putAppend("Property", getProperty(params.get("Identity"), params.get("Property"))); + + return sfs; + } + + private SimpleFieldSet handleRemoveProperty(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { + + SimpleFieldSet sfs = new SimpleFieldSet(false); + + if(params.get("Identity") == null || params.get("Property") == null) throw new InvalidParameterException("Missing mandatory parameter"); + + removeProperty(params.get("Identity"), params.get("Property")); + + sfs.putAppend("Message", "PropertyRemoved"); + return sfs; + } + + private SimpleFieldSet errorMessageFCP (Exception e) { + + SimpleFieldSet sfs = new SimpleFieldSet(false); + sfs.putAppend("Message", "Error"); + sfs.putAppend("Description", (e.getLocalizedMessage() == null) ? "null" : e.getLocalizedMessage()); + e.printStackTrace(); + return sfs; + } + + public String getString(String key) { + // TODO Auto-generated method stub + return key; + } + + public void setLanguage(LANGUAGE newLanguage) { + // TODO Auto-generated method stub + } +} Copied: trunk/plugins/WoT/WoTTest.java (from rev 22663, trunk/plugins/WoT/src/plugins/WoT/WoTTest.java) =================================================================== --- trunk/plugins/WoT/WoTTest.java (rev 0) +++ trunk/plugins/WoT/WoTTest.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -0,0 +1,269 @@ +/** + * 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.WoT; + +import java.io.File; +import java.net.MalformedURLException; + +import com.db4o.Db4o; +import com.db4o.ObjectContainer; +import com.db4o.ObjectSet; + +import junit.framework.TestCase; + +/** + * @author Julien Cornuwel (batosai at freenetproject.org) + */ +public class WoTTest extends TestCase { + + private ObjectContainer db; + + private String uriA = "USK at MF2Vc6FRgeFMZJ0s2l9hOop87EYWAydUZakJzL0OfV8,fQeN-RMQZsUrDha2LCJWOMFk1-EiXZxfTnBT8NEgY00,AQACAAE/WoT/0"; + private String uriB = "USK at R3Lp2s4jdX-3Q96c0A9530qg7JsvA9vi2K0hwY9wG-4,ipkgYftRpo0StBlYkJUawZhg~SO29NZIINseUtBhEfE,AQACAAE/WoT/0"; + private String uriC = "USK at qd-hk0vHYg7YvK2BQsJMcUD5QSF0tDkgnnF6lnWUH0g,xTFOV9ddCQQk6vQ6G~jfL6IzRUgmfMcZJ6nuySu~NUc,AQACAAE/WoT/0"; + + public WoTTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + + super.setUp(); + db = Db4o.openFile("wotTest.db4o"); + } + + protected void tearDown() throws Exception { + db.close(); + new File("wotTest.db4o").delete(); + } + + public void testInitTrustTree() throws DuplicateScoreException, NotInTrustTreeException, MalformedURLException, InvalidParameterException { + + OwnIdentity a = new OwnIdentity(uriA, uriA, "A", "true"); + db.store(a); + a.initTrustTree(db); + + assertTrue(Identity.getNbIdentities(db) == 0); + assertTrue(OwnIdentity.getNbOwnIdentities(db) == 1); + assertTrue(Trust.getNb(db) == 0); + assertTrue(Score.getNb(db) == 1); + + assertTrue(a.getScore(a, db).getScore() == 100); + assertTrue(a.getScore(a, db).getRank() == 0); + assertTrue(a.getScore(a, db).getCapacity() == 100); + assertTrue(a.getScore(a, db).getTreeOwner() == a); + assertTrue(a.getScore(a, db).getTarget() == a); + + // Empty the database + ObjectSet<Object> all = db.queryByExample(new Object()); + while(all.hasNext()) db.delete(all.next()); + } + + public void testSetTrust() throws DuplicateTrustException, InvalidParameterException, DuplicateScoreException, NotTrustedException, NotInTrustTreeException, MalformedURLException { + + OwnIdentity a = new OwnIdentity(uriA, uriA, "A", "true"); + Identity b = new Identity(uriB, "B", "true"); + db.store(a); + db.store(b); + + // With A's trust tree not initialized, B shouldn't get a Score. + a.setTrust(db, b, 10, "Foo"); + + assertTrue(Identity.getNbIdentities(db) == 1); + assertTrue(OwnIdentity.getNbOwnIdentities(db) == 1); + assertTrue(Trust.getNb(db) == 1); + assertTrue(Score.getNb(db) == 0); + + // Initialize A's trust tree and set the trust relationship + a.initTrustTree(db); + a.setTrust(db, b, 100, "Foo"); + + // Check we have the correct number of objects + assertTrue(Identity.getNbIdentities(db) == 1); + assertTrue(OwnIdentity.getNbOwnIdentities(db) == 1); + assertTrue(Trust.getNb(db) == 1); + assertTrue(Score.getNb(db) == 2); + + // Check the Trust object + assertTrue(b.getReceivedTrust(a, db).getTruster() == a); + assertTrue(b.getReceivedTrust(a, db).getTrustee() == b); + assertTrue(b.getReceivedTrust(a, db).getValue() == 100); + assertTrue(b.getReceivedTrust(a, db).getComment().equals("Foo")); + + // Check a's Score object + assertTrue(a.getScore(a, db).getScore() == 100); + assertTrue(a.getScore(a, db).getRank() == 0); + assertTrue(a.getScore(a, db).getCapacity() == 100); + + // Check B's Score object + assertTrue(b.getScore(a, db).getScore() == 100); + assertTrue(b.getScore(a, db).getRank() == 1); + assertTrue(b.getScore(a, db).getCapacity() == 40); + + // Change the trust value and comment + a.setTrust(db, b, 50, "Bar"); + + // Check we have the correct number of objects + assertTrue(Identity.getNbIdentities(db) == 1); + assertTrue(OwnIdentity.getNbOwnIdentities(db) == 1); + assertTrue(Trust.getNb(db) == 1); + assertTrue(Score.getNb(db) == 2); + + // Check the Trust object + assertTrue(b.getReceivedTrust(a, db).getTruster() == a); + assertTrue(b.getReceivedTrust(a, db).getTrustee() == b); + assertTrue(b.getReceivedTrust(a, db).getValue() == 50); + assertTrue(b.getReceivedTrust(a, db).getComment().equals("Bar")); + + // Check a's Score object + assertTrue(a.getScore(a, db).getScore() == 100); + assertTrue(a.getScore(a, db).getRank() == 0); + assertTrue(a.getScore(a, db).getCapacity() == 100); + + // Check B's Score object + assertTrue(b.getScore(a, db).getScore() == 50); + assertTrue(b.getScore(a, db).getRank() == 1); + assertTrue(b.getScore(a, db).getCapacity() == 40); + + // Empty the database + ObjectSet<Object> all = db.queryByExample(new Object()); + while(all.hasNext()) db.delete(all.next()); + } + + public void testRemoveTrust() throws MalformedURLException, InvalidParameterException, DuplicateScoreException, DuplicateTrustException, NotTrustedException, NotInTrustTreeException { + OwnIdentity a = new OwnIdentity(uriA, uriA, "A", "true"); + Identity b = new Identity(uriB, "B", "true"); + Identity c = new Identity(uriC, "C", "true"); + db.store(a); + db.store(b); + db.store(c); + a.initTrustTree(db); + a.setTrust(db, b, 100, "Foo"); + b.setTrust(db, c, 50, "Bar"); + + // Check we have the correct number of objects + assertTrue(OwnIdentity.getNbOwnIdentities(db) == 1); + assertTrue(Identity.getNbIdentities(db) == 2); + assertTrue(Trust.getNb(db) == 2); + assertTrue(Score.getNb(db) == 3); + + // Check a's Score object + assertTrue(a.getScore(a, db).getScore() == 100); + assertTrue(a.getScore(a, db).getRank() == 0); + assertTrue(a.getScore(a, db).getCapacity() == 100); + + // Check B's Score object + assertTrue(b.getScore(a, db).getScore() == 100); + assertTrue(b.getScore(a, db).getRank() == 1); + assertTrue(b.getScore(a, db).getCapacity() == 40); + + // Check C's Score object + assertTrue(c.getScore(a, db).getScore() == 20); + assertTrue(c.getScore(a, db).getRank() == 2); + assertTrue(c.getScore(a, db).getCapacity() == 16); + + a.setTrust(db, b, -1, "Bastard"); + + // Check we have the correct number of objects + assertTrue(OwnIdentity.getNbOwnIdentities(db) == 1); + assertTrue(Identity.getNbIdentities(db) == 2); + assertTrue(Trust.getNb(db) == 2); + assertTrue(Score.getNb(db) == 2); + + // Check a's Score object + assertTrue(a.getScore(a, db).getScore() == 100); + assertTrue(a.getScore(a, db).getRank() == 0); + assertTrue(a.getScore(a, db).getCapacity() == 100); + + // Check B's Score object + assertTrue(b.getScore(a, db).getScore() == -1); + assertTrue(b.getScore(a, db).getRank() == 1); + assertTrue(b.getScore(a, db).getCapacity() == 0); + + // C should not have a score anymore + try { + c.getScore(a, db); + fail(); + } + catch (NotInTrustTreeException e) {} + + // Empty the database + ObjectSet<Object> all = db.queryByExample(new Object()); + while(all.hasNext()) db.delete(all.next()); + } + + public void testTrustLoop() throws MalformedURLException, InvalidParameterException, DuplicateScoreException, DuplicateTrustException, NotInTrustTreeException { + OwnIdentity a = new OwnIdentity(uriA, uriA, "A", "true"); + Identity b = new Identity(uriB, "B", "true"); + Identity c = new Identity(uriC, "C", "true"); + db.store(a); + db.store(b); + db.store(c); + a.initTrustTree(db); + a.setTrust(db, b, 100, "Foo"); + b.setTrust(db, c, 50, "Bar"); + c.setTrust(db, a, 100, "Bleh"); + c.setTrust(db, b, 50, "Oops"); + + // Check we have the correct number of objects + assertTrue(OwnIdentity.getNbOwnIdentities(db) == 1); + assertTrue(Identity.getNbIdentities(db) == 2); + assertTrue(Trust.getNb(db) == 4); + assertTrue(Score.getNb(db) == 3); + + // Check a's Score object + assertTrue(a.getScore(a, db).getScore() == 100); + assertTrue(a.getScore(a, db).getRank() == 0); + assertTrue(a.getScore(a, db).getCapacity() == 100); + + // Check B's Score object + assertTrue(b.getScore(a, db).getScore() == 108); + assertTrue(b.getScore(a, db).getRank() == 1); + assertTrue(b.getScore(a, db).getCapacity() == 40); + + // Check C's Score object + assertTrue(c.getScore(a, db).getScore() == 20); + assertTrue(c.getScore(a, db).getRank() == 2); + assertTrue(c.getScore(a, db).getCapacity() == 16); + } + + public void testOwnIndentitiesTrust() throws MalformedURLException, InvalidParameterException, DuplicateScoreException, DuplicateTrustException, NotTrustedException, NotInTrustTreeException { + OwnIdentity a = new OwnIdentity(uriA, uriA, "A", "true"); + OwnIdentity b = new OwnIdentity(uriB, uriB, "B", "true"); + db.store(a); + db.store(b); + a.initTrustTree(db); + b.initTrustTree(db); + a.setTrust(db, b, 100, "Foo"); + b.setTrust(db, a, 100, "Bar"); + + // Check we have the correct number of objects + assertTrue(OwnIdentity.getNbOwnIdentities(db) == 2); + assertTrue(Identity.getNbIdentities(db) == 0); + assertTrue(Trust.getNb(db) == 2); + assertTrue(Score.getNb(db) == 4); + + // Check a's own Score object + assertTrue(a.getScore(a, db).getScore() == 100); + assertTrue(a.getScore(a, db).getRank() == 0); + assertTrue(a.getScore(a, db).getCapacity() == 100); + + // Check a's Score object + assertTrue(a.getScore(b, db).getScore() == 100); + assertTrue(a.getScore(b, db).getRank() == 1); + assertTrue(a.getScore(b, db).getCapacity() == 40); + + // Check B's own Score object + assertTrue(b.getScore(b, db).getScore() == 100); + assertTrue(b.getScore(b, db).getRank() == 0); + assertTrue(b.getScore(b, db).getCapacity() == 100); + + // Check B's Score object + assertTrue(b.getScore(a, db).getScore() == 100); + assertTrue(b.getScore(a, db).getRank() == 1); + assertTrue(b.getScore(a, db).getCapacity() == 40); + } +} Deleted: trunk/plugins/WoT/src/plugins/WoT/Config.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/Config.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/Config.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,43 +0,0 @@ -/** - * 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.WoT; - -import java.util.HashMap; - -import com.db4o.ObjectContainer; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - */ -public class Config { - - private ObjectContainer db; - private HashMap<String, String> params = null; - - public Config(ObjectContainer db) { - this.db = db; - if(params == null) { - params = new HashMap<String, String>(); - initDefault(false); - } - } - - public void set(String key, String value) { - params.put(key, value); - db.store(params); - } - - public String get(String key) { - return params.get(key); - } - - public void initDefault(boolean overwrite) { - - if (!params.containsKey("delayBetweenInserts") || overwrite) set("delayBetweenInserts", "30"); - - db.store(this); - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/DuplicateIdentityException.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/DuplicateIdentityException.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/DuplicateIdentityException.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,19 +0,0 @@ -/** - * 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.WoT; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - * - */ -public class DuplicateIdentityException extends Exception { - - private static final long serialVersionUID = -1; - - public DuplicateIdentityException(String message) { - super(message); - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/DuplicateScoreException.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/DuplicateScoreException.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/DuplicateScoreException.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,19 +0,0 @@ -/** - * 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.WoT; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - * - */ -public class DuplicateScoreException extends Exception { - - private static final long serialVersionUID = -1; - - public DuplicateScoreException(String message) { - super(message); - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/DuplicateTrustException.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/DuplicateTrustException.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/DuplicateTrustException.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,18 +0,0 @@ -/** - * 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.WoT; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - */ -public class DuplicateTrustException extends Exception { - - private static final long serialVersionUID = -1; - - public DuplicateTrustException(String message) { - super(message); - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/Identity.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/Identity.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/Identity.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,397 +0,0 @@ -/** - * 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.WoT; - -import java.net.MalformedURLException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; - -import com.db4o.ObjectContainer; -import com.db4o.ObjectSet; -import com.db4o.query.Query; - -import freenet.keys.FreenetURI; -import freenet.support.Logger; - -/** - * An identity as handled by the WoT (a USK) - * - * @author Julien Cornuwel (batosai at freenetproject.org) - * - */ -public class Identity { - - // Capacity is the maximum amount of points an identity can give to an other by trusting it. - public final static 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 - - private String id; - - private FreenetURI requestURI; - - private Date lastChange; - private String nickName; - private boolean publishTrustList; - private HashMap<String, String> props; - private ArrayList<String> contexts; - - - public Identity (FreenetURI requestURI, String nickName, String publishTrustList) throws InvalidParameterException { - - setRequestURI(requestURI); - setNickName(nickName); - setPublishTrustList(publishTrustList); - props = new HashMap<String, String>(); - contexts = new ArrayList<String>(); - id = getIdFromURI(getRequestURI()); - - Logger.debug(this, "New identity : " + getNickName()); - } - - public Identity (String requestURI, String nickName, String publishTrustList) throws InvalidParameterException, MalformedURLException { - this(new FreenetURI(requestURI), nickName, publishTrustList); - } - - - - @SuppressWarnings("unchecked") - public static Identity getById (ObjectContainer db, String id) throws DuplicateIdentityException, UnknownIdentityException { - - Query query = db.query(); - query.constrain(Identity.class); - query.descend("id").constrain(id); - ObjectSet<Identity> result = query.execute(); - - if(result.size() == 0) throw new UnknownIdentityException(id.toString()); - if(result.size() > 1) throw new DuplicateIdentityException(id.toString()); - return result.next(); - } - - public static Identity getByURI (ObjectContainer db, String uri) throws UnknownIdentityException, DuplicateIdentityException, MalformedURLException { - return getByURI(db, new FreenetURI(uri)); - } - - public static Identity getByURI (ObjectContainer db, FreenetURI uri) throws UnknownIdentityException, DuplicateIdentityException { - return getById(db, getIdFromURI(uri)); - } - - public static int getNbIdentities(ObjectContainer db) { - return db.queryByExample(Identity.class).size() - OwnIdentity.getNbOwnIdentities(db); - } - - public static ObjectSet<Identity> getAllIdentities(ObjectContainer db) { - return db.queryByExample(Identity.class); - } - - public static String getIdFromURI (FreenetURI uri) { - int begin = uri.toString().indexOf(',') + 1; - int end = uri.toString().indexOf(',', begin); - return uri.toString().substring(begin, end); - } - - - - @SuppressWarnings("unchecked") - public Score getScore(OwnIdentity treeOwner, ObjectContainer db) throws NotInTrustTreeException, DuplicateScoreException { - Query query = db.query(); - query.constrain(Score.class); - query.descend("treeOwner").constrain(treeOwner).and(query.descend("target").constrain(this)); - ObjectSet<Score> result = query.execute(); - - if(result.size() == 0) throw new NotInTrustTreeException(this.getRequestURI().toString()+" is not in that trust tree"); - else if(result.size() > 1) throw new DuplicateScoreException(this.getRequestURI().toString()+" ("+ getNickName() +") has "+result.size()+" scores in "+treeOwner.getNickName()+"'s trust tree"); - else return result.next(); - } - - @SuppressWarnings("unchecked") - public ObjectSet<Score> getScores(ObjectContainer db) { - Query query = db.query(); - query.constrain(Score.class); - query.descend("target").constrain(this); - return query.execute(); - } - - @SuppressWarnings("unchecked") - public Trust getReceivedTrust(Identity truster, ObjectContainer db) throws NotTrustedException, DuplicateTrustException { - Query query = db.query(); - query.constrain(Trust.class); - query.descend("truster").constrain(truster).and(query.descend("trustee").constrain(this)); - ObjectSet<Trust> result = query.execute(); - - if(result.size() == 0) throw new NotTrustedException(truster.getNickName() + " does not trust " + this.getNickName()); - else if(result.size() > 1) throw new DuplicateTrustException("Trust from " + truster.getNickName() + "to " + this.getNickName() + " exists " + result.size() + " times in the database"); - else return result.next(); - } - - @SuppressWarnings("unchecked") - public Trust getGivenTrust(Identity trustee, ObjectContainer db) throws NotTrustedException, DuplicateTrustException { - Query query = db.query(); - query.constrain(Trust.class); - query.descend("truster").constrain(this).and(query.descend("trustee").constrain(trustee)); - ObjectSet<Trust> result = query.execute(); - - if(result.size() == 0) throw new NotTrustedException(trustee.getNickName() + " does not trust " + this.getNickName()); - else if(result.size() > 1) throw new DuplicateTrustException("Trust from " + this.getNickName() + "to " + trustee.getNickName() + " exists " + result.size() + " times in the database"); - else return result.next(); - } - - @SuppressWarnings("unchecked") - public ObjectSet<Trust> getReceivedTrusts(ObjectContainer db) { - Query query = db.query(); - query.constrain(Trust.class); - query.descend("trustee").constrain(this); - return query.execute(); - } - - public long getNbReceivedTrusts(ObjectContainer db) { - return getReceivedTrusts(db).size(); - } - - @SuppressWarnings("unchecked") - public ObjectSet<Trust> getGivenTrusts(ObjectContainer db) { - Query query = db.query(); - query.constrain(Trust.class); - query.descend("truster").constrain(this); - return query.execute(); - } - - public long getNbGivenTrusts(ObjectContainer db) { - return getGivenTrusts(db).size(); - } - - public void setTrust(ObjectContainer db, Identity trustee, int value, String comment) throws DuplicateTrustException, InvalidParameterException, DuplicateScoreException { - // Check if we are updating an existing trust value - Trust trust; - try { - trust = getGivenTrust(trustee, db); - - if(!trust.getComment().equals(comment)) { - trust.setComment(comment); - db.store(trust); - } - - if(trust.getValue() != value) { - trust.setValue(value); - db.store(trust); - Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); - trustee.updateScore(db); - } - } catch (NotTrustedException e) { - trust = new Trust(this, trustee, value, comment); - db.store(trust); - Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); - trustee.updateScore(db); - } - } - - public void updateScore (ObjectContainer db) throws DuplicateScoreException, DuplicateTrustException { - ObjectSet<OwnIdentity> treeOwners = OwnIdentity.getAllOwnIdentities(db); - if(treeOwners.size() == 0) Logger.error(this, "Can't update "+ getNickName()+"'s score : there is no own identity yet"); - while(treeOwners.hasNext()) - updateScore (db, treeOwners.next()); - } - - public void updateScore (ObjectContainer db, OwnIdentity treeOwner) throws DuplicateScoreException, DuplicateTrustException { - - if(this == treeOwner) return; - - boolean hasNegativeTrust = false; - boolean changedCapacity = false; - Score score; - - Logger.debug(this, "Updating " + getNickName() + "'s score in " + treeOwner.getNickName() + "'s trust tree"); - - int value = computeScoreValue(db, treeOwner); - int rank = computeRank(db, treeOwner); - - if(rank == -1) { // -1 value means the identity is not in the trust tree - try { // If he had a score, we delete it - score = getScore(treeOwner, db); - db.delete(score); // He had a score, we delete it - changedCapacity = true; - Logger.debug(this, getNickName() + " is not in " + treeOwner.getNickName() + "'s trust tree anymore"); - } catch (NotInTrustTreeException e) {} - } - else { // The identity is in the trust tree - - try { // Get existing score or create one if needed - score = getScore(treeOwner, db); - } catch (NotInTrustTreeException e) { - score = new Score(treeOwner, this, 0, -1, 0); - } - - score.setScore(value); - score.setRank(rank + 1); - int oldCapacity = score.getCapacity(); - - // Does the treeOwner personally distrust this identity ? - try { - if(getReceivedTrust(treeOwner, db).getValue() < 0) { - hasNegativeTrust = true; - Logger.debug(this, getNickName() + " received negative trust from " + treeOwner.getNickName() + " and therefore has no capacity in his trust tree."); - } - } catch (NotTrustedException e) {} - - if(hasNegativeTrust) score.setCapacity(0); - else score.setCapacity((score.getRank() >= capacities.length) ? 1 : capacities[score.getRank()]); - - if(score.getCapacity() != oldCapacity) changedCapacity = true; - db.store(score); - Logger.debug(this, score.toString()); - } - - if(changedCapacity) { // We have to update trustees' score - ObjectSet<Trust> trustees = getGivenTrusts(db); - Logger.debug(this, getNickName() + "'s capacity has changed in " + treeOwner.getNickName() + "'s trust tree, updating his ("+trustees.size()+") trustees"); - while(trustees.hasNext()) trustees.next().getTrustee().updateScore(db, treeOwner); - } - } - - public int computeScoreValue(ObjectContainer db, OwnIdentity treeOwner) throws DuplicateScoreException { - int value = 0; - - ObjectSet<Trust> receivedTrusts = getReceivedTrusts(db); - while(receivedTrusts.hasNext()) { - Trust trust = receivedTrusts.next(); - try { - value += trust.getValue() * trust.getTruster().getScore(treeOwner, db).getCapacity() / 100; - } catch (NotInTrustTreeException e) {} - } - return value; - } - - public int computeRank(ObjectContainer db, OwnIdentity treeOwner) throws DuplicateScoreException { - int rank = -1; - - ObjectSet<Trust> receivedTrusts = getReceivedTrusts(db); - while(receivedTrusts.hasNext()) { - Trust trust = receivedTrusts.next(); - try { - Score score = trust.getTruster().getScore(treeOwner, db); - if(score.getCapacity() != 0) // If the truster has no capacity, he can't give his rank - if(rank == -1 || score.getRank() < rank) // If the truster's rank is better than ours or if we have not - rank = score.getRank(); - } catch (NotInTrustTreeException e) {} - } - return rank; - } - - public void setRequestURI(FreenetURI requestURI) throws InvalidParameterException { - if(requestURI.getKeyType().equals("SSK")) requestURI = requestURI.setKeyType("USK"); - if(!requestURI.getKeyType().equals("USK")) throw new InvalidParameterException("Key type not supported"); - this.requestURI = requestURI.setKeyType("USK").setDocName("WoT"); - updated(); - } - - public void setEdition(long edition) throws InvalidParameterException { - setRequestURI(getRequestURI().setSuggestedEdition(edition)); - } - - public void setNickName(String nickName) throws InvalidParameterException { - String nick = nickName.trim(); - if(nick.length() == 0) throw new InvalidParameterException("Blank nickName"); - if(nick.length() > 50) throw new InvalidParameterException("NickName is too long (50 chars max)"); - this.nickName = nick; - updated(); - } - - public void setPublishTrustList(boolean publishTrustList) { - this.publishTrustList = publishTrustList; - updated(); - } - - public void setPublishTrustList(String publishTrustList) { - setPublishTrustList(publishTrustList.equals("true")); - } - - public void setProp(String key, String value, ObjectContainer db) throws InvalidParameterException { - if(key.trim().length() == 0 || value.trim().length() == 0) throw new InvalidParameterException("Blank key or value in this property"); - props.put(key.trim(), value.trim()); - db.store(props); - updated(); - } - - public void removeProp(String key, ObjectContainer db) throws InvalidParameterException { - if(!props.containsKey(key)) throw new InvalidParameterException("Property '"+key+"' isn't set on this identity"); - props.remove(key.trim()); - db.store(props); - updated(); - } - - public Iterator<Entry<String, String>> getProps() { - Iterator<Entry<String, String>> i = props.entrySet().iterator(); - return i; - } - - public void addContext(String context, ObjectContainer db) throws InvalidParameterException { - String newContext = context.trim(); - if(newContext.length() == 0) throw new InvalidParameterException("Blank context"); - if(!contexts.contains(newContext)) contexts.add(newContext); - db.store(contexts); - updated(); - } - - public void removeContext(String context, ObjectContainer db) throws InvalidParameterException { - if(contexts.size() == 1) throw new InvalidParameterException("Only one context left"); - contexts.remove(context); - db.store(contexts); - updated(); - } - - public Iterator<String> getContexts() { - return contexts.iterator(); - } - - public void updated() { - lastChange = new Date(); - } - - public String getId() { - return id; - } - - public FreenetURI getRequestURI() { - return requestURI.setMetaString(new String[] {"identity.xml"} ); - } - - public Date getLastChange() { - return lastChange; - } - - public String getNickName() { - return nickName; - } - - public boolean doesPublishTrustList() { - return publishTrustList; - } - - public String getContextsAsString() { - return contexts.toString(); - } - - public String getProp(String key) throws InvalidParameterException { - if(!props.containsKey(key)) throw new InvalidParameterException("Property '"+key+"' isn't set on this identity"); - return props.get(key); - } - - public String getPropsAsString() { - return props.toString(); - } - - public boolean hasContext(String context) { - return contexts.contains(context.trim()); - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/IdentityFetcher.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/IdentityFetcher.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/IdentityFetcher.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,127 +0,0 @@ -/** - * 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.WoT; - -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; - -import com.db4o.ObjectContainer; - -import freenet.client.FetchContext; -import freenet.client.FetchException; -import freenet.client.FetchResult; -import freenet.client.HighLevelSimpleClient; -import freenet.client.InsertException; -import freenet.client.async.BaseClientPutter; -import freenet.client.async.ClientCallback; -import freenet.client.async.ClientGetter; -import freenet.keys.FreenetURI; -import freenet.support.Logger; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - * - */ -public class IdentityFetcher implements ClientCallback { - - private ObjectContainer db; - private HighLevelSimpleClient client; - private ArrayList<ClientGetter> requests; - - public IdentityFetcher(ObjectContainer db, HighLevelSimpleClient client) { - - this.db = db; - this.client = client; - requests = new ArrayList<ClientGetter>(); - } - - public void fetch(Identity identity) { - - fetch(identity, false); - } - - public void fetch(Identity identity, boolean nextEdition) { - - try { - if(nextEdition && !identity.getLastChange().equals(new Date(0))) - fetch(identity.getRequestURI().setSuggestedEdition(identity.getRequestURI().getSuggestedEdition() + 1)); - else - fetch(identity.getRequestURI()); - } catch (FetchException e) { - Logger.error(this, "Request restart failed: "+e, e); - } - } - - public void fetch(FreenetURI uri) throws FetchException { - - FetchContext fetchContext = client.getFetchContext(); - fetchContext.maxSplitfileBlockRetries = -1; // retry forever - fetchContext.maxNonSplitfileRetries = -1; // retry forever - requests.add(client.fetch(uri, -1, this, this, fetchContext)); - Logger.debug(this, "Start fetching identity "+uri.toString()); - } - - public void stop() { - Iterator<ClientGetter> i = requests.iterator(); - Logger.debug(this, "Trying to stop "+requests.size()+" requests"); - while (i.hasNext()) i.next().cancel(); - Logger.debug(this, "Stopped all current requests"); - } - - public void onFailure(FetchException e, ClientGetter state) { - - if ((e.mode == FetchException.PERMANENT_REDIRECT) || (e.mode == FetchException.TOO_MANY_PATH_COMPONENTS )) { - // restart the request - try { - state.restart(e.newURI); - // Done. bye. - return; - } catch (FetchException e1) { - Logger.error(this, "Request restart failed: "+e1, e1); - } - } - // Errors we can't/want deal with - Logger.error(this, "Fetch failed for "+ state.getURI(), e); - requests.remove(state); - } - - public void onFailure(InsertException e, BaseClientPutter state) { - - } - - public void onFetchable(BaseClientPutter state) { - - } - - public void onGeneratedURI(FreenetURI uri, BaseClientPutter state) { - - } - - public void onMajorProgress() { - - } - - public void onSuccess(FetchResult result, ClientGetter state) { - - Logger.debug(this, "Fetched key (ClientGetter) : " + state.getURI()); - - try { - Logger.debug(this, "Sucessfully fetched identity "+ state.getURI().toString()); - new IdentityParser(db, client, this).parse(result.asBucket().getInputStream(), state.getURI()); - db.commit(); - state.restart(state.getURI().setSuggestedEdition(state.getURI().getSuggestedEdition() + 1)); - } catch (Exception e) { - Logger.error(this, "Parsing failed for "+ state.getURI(), e); - } - } - - public void onSuccess(BaseClientPutter state) { - - Logger.debug(this, "Fetched key (BaseClientPutter) : " + state.getURI()); - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/IdentityInserter.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/IdentityInserter.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/IdentityInserter.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,117 +0,0 @@ -/** - * 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.WoT; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Date; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; - -import com.db4o.ObjectContainer; -import com.db4o.ObjectSet; -import com.db4o.ext.DatabaseClosedException; -import com.db4o.ext.Db4oIOException; - -import freenet.client.ClientMetadata; -import freenet.client.HighLevelSimpleClient; -import freenet.client.InsertBlock; -import freenet.client.InsertException; -import freenet.keys.FreenetURI; -import freenet.support.Logger; -import freenet.support.api.Bucket; -import freenet.support.io.TempBucketFactory; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - * - */ -public class IdentityInserter implements Runnable { - - ObjectContainer db; - HighLevelSimpleClient client; - final TempBucketFactory tBF; - - boolean isRunning; - - public IdentityInserter(ObjectContainer db, HighLevelSimpleClient client, TempBucketFactory tbf) { - this.db = db; - this.client = client; - isRunning = true; - tBF = tbf; - } - - public void run() { - try{ - Thread.sleep(30 * 1000); // Let the node start up (30 seconds) - } catch (InterruptedException e){} - while(isRunning) { - ObjectSet<OwnIdentity> identities = OwnIdentity.getAllOwnIdentities(db); - while(identities.hasNext()) { - OwnIdentity identity = identities.next(); - if(identity.needsInsert()) { - try { - Logger.debug(this, "Starting insert of "+identity.getNickName() + " (" + identity.getInsertURI().toString() + ")"); - insert(identity); - // We set the date now, so if the identity is modified during the insert, we'll insert it again next time - identity.setLastInsert(new Date()); - db.store(identity); - } catch (Exception e) { - Logger.error(this, "Identity insert failed: "+e.getMessage(), e); - } - } - } - db.commit(); - try{ - Thread.sleep(30 * 60 * 1000); // 30 minutes - } catch (InterruptedException e){} - } - } - - public void stop() { - isRunning = false; - Logger.debug(this, "Stopping IdentityInserter thread"); - } - - public void insert(OwnIdentity identity) throws TransformerConfigurationException, FileNotFoundException, ParserConfigurationException, TransformerException, IOException, Db4oIOException, DatabaseClosedException, InvalidParameterException, InsertException { - - Bucket tempB = tBF.makeBucket(1); - OutputStream os = tempB.getOutputStream(); - FreenetURI iURI; - try { - // Create XML file to insert - identity.exportToXML(db, os); - - os.close(); - tempB.setReadOnly(); - - // Prepare the insert - ClientMetadata cmd = new ClientMetadata("text/xml"); - InsertBlock ib = new InsertBlock(tempB,cmd,identity.getInsertURI()); - - // Logging - Logger.debug(this, "Started insert of identity '" + identity.getNickName() + "'"); - - // Blocking Insert - iURI = client.insert(ib, false, "identity.xml"); - } finally { - tempB.free(); - } - - identity.setEdition(iURI.getSuggestedEdition()); - identity.setLastInsert(new Date()); - - db.store(identity); - db.commit(); - - // Logging - Logger.debug(this, "Successful insert of identity '" + identity.getNickName() + "'"); - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/IdentityParser.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/IdentityParser.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/IdentityParser.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,110 +0,0 @@ -/** - * 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.WoT; - -import java.io.IOException; -import java.io.InputStream; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -import com.db4o.ObjectContainer; - -import freenet.client.HighLevelSimpleClient; -import freenet.keys.FreenetURI; -import freenet.support.Logger; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - * - */ -public class IdentityParser { - - ObjectContainer db; - HighLevelSimpleClient client; - IdentityFetcher fetcher; - SAXParser saxParser; - Identity identity; - - public IdentityParser(ObjectContainer db, HighLevelSimpleClient client, IdentityFetcher fetcher) throws ParserConfigurationException, SAXException { - - this.db = db; - this.client = client; - this.fetcher = fetcher; - saxParser = SAXParserFactory.newInstance().newSAXParser(); - } - - public void parse (InputStream is, FreenetURI uri) throws InvalidParameterException, SAXException, IOException, UnknownIdentityException, DuplicateIdentityException { - - identity = Identity.getByURI(db,uri); - if(!(identity instanceof OwnIdentity)) identity.updated(); - identity.setEdition(uri.getSuggestedEdition()); - - saxParser.parse(is, new IdentityHandler() ); - db.store(identity); - - Logger.debug(this, "Successfuly parsed identity '" + identity.getNickName() + "'"); - } - - public class IdentityHandler extends DefaultHandler { - - public IdentityHandler() { - - } - - public void startElement(String nameSpaceURI, String localName, String rawName, Attributes attrs) throws SAXException { - - String elt_name; - if (rawName == null) elt_name = localName; - else elt_name = rawName; - - try { - if (elt_name.equals("nickName")) { - identity.setNickName(attrs.getValue("value")); - } - if (elt_name.equals("publishTrustList")) { - identity.setPublishTrustList(attrs.getValue("value")); - } - else if (elt_name.equals("prop")) { - identity.setProp(attrs.getValue("key"), attrs.getValue("value"), db); - } - else if(elt_name.equals("context")) { - identity.addContext(attrs.getValue("value"), db); - } - else if (elt_name.equals("trust")) { - - Identity trustee; - int value = Integer.parseInt(attrs.getValue("value")); - String comment = attrs.getValue("comment"); - - try{ - trustee = Identity.getByURI(db, attrs.getValue("uri")); - identity.setTrust(db, trustee, value, comment); - } - catch (UnknownIdentityException e) { - - // TODO Don't create Identity object before we succesfully fetched it ! - - trustee = new Identity(attrs.getValue("uri"), "Not found yet...", "false"); - db.store(trustee); - identity.setTrust(db, trustee, value, comment); - fetcher.fetch(trustee); - } - - } - } catch (Exception e1) { - Logger.error(this, "Parsing error",e1); - e1.printStackTrace(); - } - } - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/IdentityTest.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/IdentityTest.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/IdentityTest.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,102 +0,0 @@ -/** - * 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.WoT; - -import java.io.File; -import java.net.MalformedURLException; - -import com.db4o.Db4o; -import com.db4o.ObjectContainer; -import com.db4o.ObjectSet; - -import junit.framework.TestCase; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - */ -public class IdentityTest extends TestCase { - - private String uri = "USK at yGvITGZzrY1vUZK-4AaYLgcjZ7ysRqNTMfdcO8gS-LY,-ab5bJVD3Lp-LXEQqBAhJpMKrKJ19RnNaZMIkusU79s,AQACAAE/WoT/0"; - private Identity identity; - private ObjectContainer db; - - public IdentityTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - super.setUp(); - - db = Db4o.openFile("identityTest.db4o"); - - identity = new Identity(uri, "test", "true"); - identity.addContext("bleh", db); - - db.store(identity); - db.commit(); - } - - protected void tearDown() throws Exception { - db.close(); - new File("identityTest.db4o").delete(); - } - - public void testIdentityStored() { - ObjectSet<Identity> result = db.queryByExample(Identity.class); - assertEquals(result.size(), 1); - } - - public void testGetByURI() throws MalformedURLException, UnknownIdentityException, DuplicateIdentityException { - assertNotNull(Identity.getByURI(db, uri)); - } - - public void testGetNbIdentities() { - assertEquals(Identity.getNbIdentities(db), 1); - } - - public void testContexts() throws InvalidParameterException { - assertFalse(identity.hasContext("foo")); - identity.addContext("test", db); - assertTrue(identity.hasContext("test")); - identity.removeContext("test", db); - assertFalse(identity.hasContext("test")); - } - - public void testProperties() { - try { - identity.setProp("foo", "bar", db); - } catch (InvalidParameterException e) {} - - try { - assertTrue(identity.getProp("foo").equals("bar")); - } catch (InvalidParameterException e) { fail(); } - - try { - identity.removeProp("foo", db); - } catch (InvalidParameterException e) { fail(); } - - try { - identity.getProp("foo"); - fail(); - } catch (InvalidParameterException e) {} - } - - public void testPersistence() throws MalformedURLException, DuplicateIdentityException { - db.close(); - - System.gc(); - System.runFinalization(); - - db = Db4o.openFile("identityTest.db4o"); - - assertEquals(Identity.getNbIdentities(db), 1); - try { - Identity.getByURI(db, uri); - } catch (UnknownIdentityException e) { - fail(); - } - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/InvalidParameterException.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/InvalidParameterException.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/InvalidParameterException.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,19 +0,0 @@ -/** - * 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.WoT; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - * - */ -public class InvalidParameterException extends Exception { - - private static final long serialVersionUID = -1; - - public InvalidParameterException(String message) { - super(message); - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/NotInTrustTreeException.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/NotInTrustTreeException.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/NotInTrustTreeException.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,20 +0,0 @@ -/** - * 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.WoT; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - * - */ -public class NotInTrustTreeException extends Exception { - - private static final long serialVersionUID = -1; - - public NotInTrustTreeException(String message) { - super(message); - } - -} Deleted: trunk/plugins/WoT/src/plugins/WoT/NotTrustedException.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/NotTrustedException.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/NotTrustedException.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,18 +0,0 @@ -/** - * 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.WoT; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - */ -public class NotTrustedException extends Exception { - - private static final long serialVersionUID = -1; - - public NotTrustedException(String message) { - super(message); - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/OwnIdentity.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/OwnIdentity.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/OwnIdentity.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,186 +0,0 @@ -/** - * 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.WoT; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.OutputStream; -import java.net.MalformedURLException; -import java.util.Date; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import com.db4o.ObjectContainer; -import com.db4o.ObjectSet; -import com.db4o.ext.DatabaseClosedException; -import com.db4o.ext.Db4oIOException; -import com.db4o.query.Query; - -import freenet.keys.FreenetURI; - -/** - * A local Identity (it belongs to the user) - * - * @author Julien Cornuwel (batosai at freenetproject.org) - * - */ -public class OwnIdentity extends Identity { - - private FreenetURI insertURI; - private Date lastInsert; - - public OwnIdentity (FreenetURI insertURI, FreenetURI requestURI, String nickName, String publishTrustList) throws InvalidParameterException { - super(requestURI, nickName, publishTrustList); - setInsertURI(insertURI); - setLastInsert(new Date(0)); - } - - public OwnIdentity (String insertURI, String requestURI, String nickName, String publishTrustList) throws InvalidParameterException, MalformedURLException { - this(new FreenetURI(insertURI), new FreenetURI(requestURI), nickName, publishTrustList); - } - - public void initTrustTree (ObjectContainer db) throws DuplicateScoreException { - try { - getScore(this,db); - return; - } catch (NotInTrustTreeException e) { - db.store(new Score(this, this, 100, 0, 100)); - } - } - - @SuppressWarnings("unchecked") - public static OwnIdentity getById (ObjectContainer db, String id) throws UnknownIdentityException, DuplicateIdentityException { - Query query = db.query(); - query.constrain(OwnIdentity.class); - query.descend("id").constrain(id); - ObjectSet<OwnIdentity> result = query.execute(); - - if(result.size() == 0) throw new UnknownIdentityException(id.toString()); - if(result.size() > 1) throw new DuplicateIdentityException(id.toString()); - return result.next(); - } - - public static OwnIdentity getByURI (ObjectContainer db, String uri) throws UnknownIdentityException, DuplicateIdentityException, MalformedURLException { - return getByURI(db, new FreenetURI(uri)); - } - - public static OwnIdentity getByURI (ObjectContainer db, FreenetURI uri) throws UnknownIdentityException, DuplicateIdentityException { - return getById(db, getIdFromURI(uri)); - } - - public static int getNbOwnIdentities(ObjectContainer db) { - return db.queryByExample(OwnIdentity.class).size(); - } - - public static ObjectSet<OwnIdentity> getAllOwnIdentities (ObjectContainer db) { - return db.queryByExample(OwnIdentity.class); - } - - public void exportToXML(ObjectContainer db, OutputStream os) throws ParserConfigurationException, TransformerConfigurationException, TransformerException, FileNotFoundException, IOException, Db4oIOException, DatabaseClosedException, InvalidParameterException { - - // Create the output file - StreamResult resultStream = new StreamResult(os); - - // Create the XML document - DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder xmlBuilder = xmlFactory.newDocumentBuilder(); - DOMImplementation impl = xmlBuilder.getDOMImplementation(); - Document xmlDoc = impl.createDocument(null, "WoT", null); - Element rootElement = xmlDoc.getDocumentElement(); - - // Create the content - Element identity = xmlDoc.createElement("identity"); - - // NickName - Element nickNameTag = xmlDoc.createElement("nickName"); - nickNameTag.setAttribute("value", getNickName()); - identity.appendChild(nickNameTag); - - // PublishTrustList - Element publishTrustListTag = xmlDoc.createElement("publishTrustList"); - publishTrustListTag.setAttribute("value", doesPublishTrustList() ? "true" : "false"); - identity.appendChild(publishTrustListTag); - - // Properties - - Iterator<Entry<String, String>> props = getProps(); - while(props.hasNext()){ - Map.Entry<String,String> prop = props.next(); - Element propTag = xmlDoc.createElement("prop"); - propTag.setAttribute("key", prop.getKey()); - propTag.setAttribute("value", prop.getValue()); - identity.appendChild(propTag); - } - - // Contexts - Iterator<String> contexts = getContexts(); - while(contexts.hasNext()) { - String context = (String)contexts.next(); - Element contextTag = xmlDoc.createElement("context"); - contextTag.setAttribute("value", context); - identity.appendChild(contextTag); - } - - rootElement.appendChild(identity); - - if(doesPublishTrustList()) { - Trustlist trustList = new Trustlist(db, this); - rootElement.appendChild(trustList.toXML(xmlDoc)); - } - - DOMSource domSource = new DOMSource(xmlDoc); - TransformerFactory transformFactory = TransformerFactory.newInstance(); - Transformer serializer = transformFactory.newTransformer(); - - serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - serializer.setOutputProperty(OutputKeys.INDENT,"yes"); - serializer.transform(domSource, resultStream); - } - - public boolean needsInsert() { - return (getLastChange().after(getLastInsert()) || (new Date().getTime() - getLastInsert().getTime()) > 1000*60*60*24*7); - } - - public FreenetURI getInsertURI() { - return insertURI; - } - - public void setInsertURI(FreenetURI key) throws InvalidParameterException { - if(key.getKeyType().equals("SSK")) key = key.setKeyType("USK"); - if(!key.getKeyType().equals("USK")) throw new InvalidParameterException("Key type not supported"); - - this.insertURI = key; - } - - public void setEdition(long edition) throws InvalidParameterException { - setInsertURI(getInsertURI().setSuggestedEdition(edition)); - setRequestURI(getRequestURI().setSuggestedEdition(edition)); - } - - public Date getLastInsert() { - return lastInsert; - } - - public void setLastInsert(Date lastInsert) { - this.lastInsert = lastInsert; - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/Score.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/Score.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/Score.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,106 +0,0 @@ -/** - * 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.WoT; - -import java.net.MalformedURLException; - -import com.db4o.ObjectContainer; -import com.db4o.ObjectSet; -import com.db4o.query.Query; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - * - */ -public class Score { - - private OwnIdentity treeOwner; - private Identity target; - private int score; - private int rank; - private int capacity; - - - public Score (OwnIdentity treeOwner, Identity target, int score, int rank, int capacity) { - this.treeOwner = treeOwner; - this.target = target; - this.score = score; - this.rank = rank; - this.capacity = capacity; - } - - public static int getNb(ObjectContainer db) { - ObjectSet<Score> scores = db.queryByExample(Score.class); - return scores.size(); - } - - @SuppressWarnings("unchecked") - public static ObjectSet<Score> getIdentitiesByScore (String owner, String select, ObjectContainer db) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { - - OwnIdentity treeOwner = OwnIdentity.getByURI(db, owner); - - Query query = db.query(); - query.constrain(Score.class); - query.descend("treeOwner").constrain(treeOwner); - - if(select.equals("+")) { - query.descend("score").constrain(new Integer(0)).greater(); - } - else if(select.equals("0")) { - query.descend("score").constrain(new Integer(0)); - } - else if(select.equals("-")) { - query.descend("score").constrain(new Integer(0)).smaller(); - } - else throw new InvalidParameterException("Unhandled select value ("+select+")"); - - return query.execute(); - } - - public String toString() { - return getTarget().getNickName() + " has " + getScore() + " points in " + getTreeOwner().getNickName() + "'s trust tree (rank : " + getRank() + ", capacity : " + getCapacity() + ")"; - } - - public OwnIdentity getTreeOwner() { - return treeOwner; - } - - public void setTreeOwner(OwnIdentity treeOwner) { - this.treeOwner = treeOwner; - } - - public Identity getTarget() { - return target; - } - - public void setTarget(Identity target) { - this.target = target; - } - - public int getScore() { - return score; - } - - public void setScore(int score) { - this.score = score; - } - - public int getRank() { - return rank; - } - - public void setRank(int rank) { - this.rank = rank; - } - - public int getCapacity() { - return capacity; - } - - public void setCapacity(int capacity) { - this.capacity = capacity; - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/ScoreTest.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/ScoreTest.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/ScoreTest.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,81 +0,0 @@ -/** - * 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.WoT; - -import java.io.File; -import java.net.MalformedURLException; - -import junit.framework.TestCase; - -import com.db4o.Db4o; -import com.db4o.ObjectContainer; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - */ -public class ScoreTest extends TestCase { - - private String uriA = "USK at MF2Vc6FRgeFMZJ0s2l9hOop87EYWAydUZakJzL0OfV8,fQeN-RMQZsUrDha2LCJWOMFk1-EiXZxfTnBT8NEgY00,AQACAAE/WoT/0"; - private String uriB = "USK at R3Lp2s4jdX-3Q96c0A9530qg7JsvA9vi2K0hwY9wG-4,ipkgYftRpo0StBlYkJUawZhg~SO29NZIINseUtBhEfE,AQACAAE/WoT/0"; - OwnIdentity a; - Identity b; - - private ObjectContainer db; - - public ScoreTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - - super.setUp(); - db = Db4o.openFile("scoreTest.db4o"); - - a = new OwnIdentity(uriA, uriA, "A", "true"); - b = new Identity(uriB, "B", "true"); - db.store(a); - db.store(b); - Score score = new Score(a,b,100,1,40); - db.store(score); - db.commit(); - } - - protected void tearDown() throws Exception { - db.close(); - new File("scoreTest.db4o").delete(); - } - - public void testScoreCreation() throws NotInTrustTreeException, DuplicateScoreException { - - Score score = b.getScore(a, db); - - assertTrue(score.getScore() == 100); - assertTrue(score.getRank() == 1); - assertTrue(score.getCapacity() == 40); - assertTrue(score.getTreeOwner() == a); - assertTrue(score.getTarget() == b); - } - - public void testScorePersistence() throws NotInTrustTreeException, DuplicateScoreException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { - - db.close(); - - System.gc(); - System.runFinalization(); - - db = Db4o.openFile("scoreTest.db4o"); - - a = OwnIdentity.getByURI(db, uriA); - b = Identity.getByURI(db, uriB); - Score score = b.getScore(a, db); - - assertTrue(score.getScore() == 100); - assertTrue(score.getRank() == 1); - assertTrue(score.getCapacity() == 40); - assertTrue(score.getTreeOwner() == a); - assertTrue(score.getTarget() == b); - } -} \ No newline at end of file Deleted: trunk/plugins/WoT/src/plugins/WoT/Trust.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/Trust.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/Trust.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,116 +0,0 @@ -/** - * 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.WoT; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import com.db4o.ObjectContainer; -import com.db4o.ObjectSet; - -/** - * A trust relationship between two identities - * - * @author Julien Cornuwel (batosai at freenetproject.org) - * - */ -public class Trust { - - /* We use a reference to the truster here rather that storing the trustList in the Identity. - * This allows us to load only what's needed in memory instead of everything. - * Maybe db4o can handle this, I don't know ATM. - */ - private Identity truster; - private Identity trustee; - private int value; - private String comment; - - - public Trust(Identity truster, Identity trustee, int value, String comment) throws InvalidParameterException { - this.truster = truster; - this.trustee = trustee; - setValue(value); - setComment(comment); - } - - public static int getNb(ObjectContainer db) { - ObjectSet<Trust> trusts = db.queryByExample(Trust.class); - return trusts.size(); - } - - public Element toXML(Document xmlDoc) { - Element elem = xmlDoc.createElement("trust"); - elem.setAttribute("uri", trustee.getRequestURI().toString()); - elem.setAttribute("value", String.valueOf(value)); - elem.setAttribute("comment", comment); - - return elem; - } - - public String toString() { - return getTruster().getNickName() + " trusts " + getTrustee().getNickName() + " (" + getValue() + " : " + getComment() + ")"; - } - - /** - * @return truster - */ - public Identity getTruster() { - return truster; - } - - /** - * @param truster Identity that gives the trust - */ - public void setTruster(Identity truster) { - this.truster = truster; - } - - /** - * @return trustee - */ - public Identity getTrustee() { - return trustee; - } - - /** - * @param trustee Identity that receives the trust - */ - public void setTrustee(Identity trustee) { - this.trustee = trustee; - } - - /** - * @return value - */ - public int getValue() { - return value; - } - - /** - * @param value Numeric value of the trust [-100;+100] - * @throws InvalidParameterException if value isn't in the range - */ - public void setValue(int value) throws InvalidParameterException { - if(value >= -100 && value <= 100) this.value = value; - else throw new InvalidParameterException("Invalid trust value ("+value+")"); - } - - /** - * - * @return Comment - */ - public String getComment() { - return comment; - } - - /** - * - * @param comment Comment on that trust relationship - */ - public void setComment(String comment) { - this.comment = comment; - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/TrustTest.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/TrustTest.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/TrustTest.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,79 +0,0 @@ -/** - * 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.WoT; - -import java.io.File; -import java.net.MalformedURLException; - -import junit.framework.TestCase; - -import com.db4o.Db4o; -import com.db4o.ObjectContainer; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - */ -public class TrustTest extends TestCase { - - private String uriA = "USK at MF2Vc6FRgeFMZJ0s2l9hOop87EYWAydUZakJzL0OfV8,fQeN-RMQZsUrDha2LCJWOMFk1-EiXZxfTnBT8NEgY00,AQACAAE/WoT/0"; - private String uriB = "USK at R3Lp2s4jdX-3Q96c0A9530qg7JsvA9vi2K0hwY9wG-4,ipkgYftRpo0StBlYkJUawZhg~SO29NZIINseUtBhEfE,AQACAAE/WoT/0"; - - private Identity a; - private Identity b; - - private ObjectContainer db; - - public TrustTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - - super.setUp(); - db = Db4o.openFile("trustTest.db4o"); - - a = new Identity(uriA, "A", "true"); - b = new Identity(uriB, "B", "true"); - Trust trust = new Trust(a,b,100,"test"); - db.store(trust); - db.store(a); - db.store(b); - db.commit(); - } - - protected void tearDown() throws Exception { - db.close(); - new File("trustTest.db4o").delete(); - } - - public void testTrust() throws InvalidParameterException, NotTrustedException, DuplicateTrustException { - - Trust trust = a.getGivenTrust(b, db); - assertTrue(trust.getTruster() == a); - assertTrue(trust.getTrustee() == b); - assertTrue(trust.getValue() == 100); - assertTrue(trust.getComment().equals("test")); - } - - public void testTrustPersistence() throws MalformedURLException, UnknownIdentityException, DuplicateIdentityException, NotTrustedException, DuplicateTrustException { - - db.close(); - - System.gc(); - System.runFinalization(); - - db = Db4o.openFile("trustTest.db4o"); - - a = Identity.getByURI(db, uriA); - b = Identity.getByURI(db, uriB); - Trust trust = a.getGivenTrust(b, db); - - assertTrue(trust.getTruster() == a); - assertTrue(trust.getTrustee() == b); - assertTrue(trust.getValue() == 100); - assertTrue(trust.getComment().equals("test")); - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/Trustlist.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/Trustlist.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/Trustlist.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,52 +0,0 @@ -/** - * 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.WoT; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import com.db4o.ObjectContainer; -import com.db4o.ObjectSet; -import com.db4o.ext.DatabaseClosedException; -import com.db4o.ext.Db4oIOException; - -/** - * TrustList of an Identity - * @author Julien Cornuwel (batosai at freenetproject.org) - * - */ -public class Trustlist { - - public ObjectSet<Trust> list; - - /** - * Creates the trustlist of a local Identity - * - * @param db Connection to db4o - * @param truster Identity that owns that trustList - * @throws InvalidParameterException - * @throws DatabaseClosedException - * @throws Db4oIOException - */ - public Trustlist(ObjectContainer db, OwnIdentity truster) throws Db4oIOException, DatabaseClosedException, InvalidParameterException { - list = truster.getGivenTrusts(db); - } - - /** - * Returns an XML Element containing the trustList - * @param xmlDoc The XML Document - * @return Element containing details of the trustList - */ - public Element toXML(Document xmlDoc) { - Element elem = xmlDoc.createElement("trustList"); - - while(list.hasNext()) { - elem.appendChild(list.next().toXML(xmlDoc)); - } - - return elem; - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/UnknownIdentityException.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/UnknownIdentityException.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/UnknownIdentityException.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,20 +0,0 @@ -/** - * 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.WoT; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - * - */ -public class UnknownIdentityException extends Exception { - - private static final long serialVersionUID = -1; - - public UnknownIdentityException(String message) { - super(message); - } - -} Deleted: trunk/plugins/WoT/src/plugins/WoT/Version.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/Version.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/Version.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,25 +0,0 @@ -/** - * 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.WoT; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - * - */ -public class Version { - private static final String svnRevision = "@custom@"; - - static String getSvnRevision() { - return svnRevision; - } - - public static void main(String[] args) { - System.out.println("====="); - System.out.println(svnRevision); - System.out.println("====="); - } -} - Deleted: trunk/plugins/WoT/src/plugins/WoT/WebInterface.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/WebInterface.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/WebInterface.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,478 +0,0 @@ -/** - * 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.WoT; - -import java.net.MalformedURLException; -import java.util.Date; - -import com.db4o.ObjectContainer; -import com.db4o.ObjectSet; -import com.db4o.ext.DatabaseClosedException; -import com.db4o.ext.Db4oIOException; - -import freenet.client.HighLevelSimpleClient; -import freenet.clients.http.PageMaker; -import freenet.keys.FreenetURI; -import freenet.pluginmanager.PluginRespirator; -import freenet.support.HTMLNode; -import freenet.support.api.HTTPRequest; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - * - */ -public class WebInterface { - - private PluginRespirator pr; - private PageMaker pm; - private HighLevelSimpleClient client; - private String SELF_URI; - private ObjectContainer db; - - public WebInterface(PluginRespirator pr, ObjectContainer db, HighLevelSimpleClient client, String uri) { - this.pr = pr; - this.client = client; - this.SELF_URI = uri; - this.db = db; - - pm = pr.getPageMaker(); - pm.addNavigationLink(SELF_URI, "Home", "Home page", false, null); - pm.addNavigationLink(SELF_URI + "?ownidentities", "Own Identities", "Manage your own identities", false, null); - pm.addNavigationLink(SELF_URI + "?knownidentities", "Known Identities", "Manage others identities", false, null); - pm.addNavigationLink("/plugins/", "Plugins page", "Back to Plugins page", false, null); - } - - private HTMLNode getPageNode() { - return pm.getPageNode("Web of Trust", null); - } - - public String makeHomePage() { - - HTMLNode list = new HTMLNode("ul"); - - list.addChild(new HTMLNode("li", "Own Identities : " + OwnIdentity.getNbOwnIdentities(db))); - list.addChild(new HTMLNode("li", "Known Identities : " + Identity.getNbIdentities(db))); - list.addChild(new HTMLNode("li", "Trust relationships : " + Trust.getNb(db))); - list.addChild(new HTMLNode("li", "Scores : " + Score.getNb(db))); - - HTMLNode pageNode = getPageNode(); - HTMLNode contentNode = pm.getContentNode(pageNode); - HTMLNode box = pm.getInfobox("Summary"); - - HTMLNode boxContent = pm.getContentNode(box); - boxContent.addChild(list); - - contentNode.addChild(box); - return pageNode.generate(); - } - - public String makeOwnIdentitiesPage() { - - HTMLNode pageNode = getPageNode(); - HTMLNode contentNode = pm.getContentNode(pageNode); - HTMLNode box = pm.getInfobox("Own Identities"); - HTMLNode boxContent = pm.getContentNode(box); - - - ObjectSet<OwnIdentity> ownIdentities = OwnIdentity.getAllOwnIdentities(db); - if(ownIdentities.size() == 0) { - boxContent.addChild("p", "You have no own identity yet, you should create one..."); - } - else { - - HTMLNode identitiesTable = boxContent.addChild("table", "border", "0"); - HTMLNode row=identitiesTable.addChild("tr"); - row.addChild("th", "Name"); - row.addChild("th", "Last change"); - row.addChild("th", "Last insert"); - row.addChild("th", "Publish TrustList ?"); - row.addChild("th", "Manage"); - - while(ownIdentities.hasNext()) { - OwnIdentity id = ownIdentities.next(); - row=identitiesTable.addChild("tr"); - row.addChild("td", new String[] {"title", "style"}, new String[] {id.getRequestURI().toString(), "cursor: help;"}, id.getNickName()); - row.addChild("td",id.getLastChange().toString()); - HTMLNode cell = row.addChild("td"); - if(id.getLastInsert() == null) { - cell.addChild("p", "Insert in progress..."); - } - else if(id.getLastInsert().equals(new Date(0))) { - cell.addChild("p", "Never"); - } - else { - cell.addChild(new HTMLNode("a", "href", "/"+id.getRequestURI().toString(), id.getLastInsert().toString())); - } - row.addChild("td", id.doesPublishTrustList() ? "Yes" : "No"); - - HTMLNode manageCell = row.addChild("td"); - - HTMLNode editForm = pr.addFormChild(manageCell, SELF_URI, "editIdentity"); - editForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "editIdentity" }); - editForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "id", id.getRequestURI().toString() }); - editForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "edit", "Details" }); - - HTMLNode deleteForm = pr.addFormChild(manageCell, SELF_URI, "deleteIdentity"); - deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "deleteIdentity" }); - deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "id", id.getId() }); - deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "delete", "Delete" }); - } - } - - HTMLNode createForm = pr.addFormChild(boxContent, SELF_URI, "createIdentity"); - createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "createIdentity" }); - createForm.addChild("span", new String[] {"title", "style"}, new String[] { "No spaces or special characters.", "border-bottom: 1px dotted; cursor: help;"} , "NickName : "); - createForm.addChild("input", new String[] {"type", "name", "size"}, new String[] {"text", "nickName", "30"}); - createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "create", "Create a new identity !" }); - - contentNode.addChild(box); - - - // Form to restore an existing OwnIdentity from Freenet - HTMLNode restoreBox = pm.getInfobox("Restore an identity from Freenet"); - HTMLNode restoreBoxContent = pm.getContentNode(restoreBox); - - restoreBoxContent.addChild("p", "Use this if you lost your database for some reason (crash, reinstall...) but still have your identity's keys :"); - - HTMLNode restoreForm = pr.addFormChild(restoreBoxContent, SELF_URI, "restoreIdentity"); - restoreForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "restoreIdentity" }); - restoreForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "requestURI", "70", "Request URI" }); - restoreForm.addChild("br"); - restoreForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "insertURI", "70", "InsertURI" }); - restoreForm.addChild("br"); - restoreForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "restore", "Restore this identity !" }); - - restoreBoxContent.addChild("p", "Please don't use that identity (set trust, edit parameters...) until it has been restored from Freenet, or you might loose all its content."); - - contentNode.addChild(restoreBox); - - return pageNode.generate(); - } - - public String makeKnownIdentitiesPage() throws Db4oIOException, DatabaseClosedException, InvalidParameterException, NotInTrustTreeException, DuplicateScoreException, DuplicateTrustException { - return makeKnownIdentitiesPage(""); - } - - public String makeKnownIdentitiesPage(HTTPRequest request) throws Db4oIOException, DatabaseClosedException, InvalidParameterException, NotInTrustTreeException, DuplicateScoreException, DuplicateTrustException { - return makeKnownIdentitiesPage(request.getPartAsString("ownerURI", 1024)); - } - - public String makeKnownIdentitiesPage(String owner) throws Db4oIOException, DatabaseClosedException, InvalidParameterException, NotInTrustTreeException, DuplicateScoreException, DuplicateTrustException { - - OwnIdentity treeOwner = null; - - HTMLNode pageNode = getPageNode(); - HTMLNode contentNode = pm.getContentNode(pageNode); - - // Add an identity form - HTMLNode addBox = pm.getInfobox("Add an identity"); - HTMLNode addBoxContent = pm.getContentNode(addBox); - - HTMLNode createForm = pr.addFormChild(addBoxContent, SELF_URI, "addIdentity"); - createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "addIdentity" }); - createForm.addChild("span", new String[] {"title", "style"}, new String[] { "This must be a valid Freenet URI.", "border-bottom: 1px dotted; cursor: help;"} , "Identity URI : "); - createForm.addChild("input", new String[] {"type", "name", "size"}, new String[] {"text", "identityURI", "70"}); - createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "add", "Add this identity !" }); - - - // Known identities list - HTMLNode listBox = pm.getInfobox("Known Identities"); - HTMLNode listBoxContent = pm.getContentNode(listBox); - - int nbOwnIdentities = OwnIdentity.getNbOwnIdentities(db); - - if (nbOwnIdentities == 0) { - listBoxContent.addChild("p", "You should create an identity first..."); - contentNode.addChild(listBox); - return pageNode.generate(); - } - else if (nbOwnIdentities == 1) { - treeOwner = OwnIdentity.getAllOwnIdentities(db).next(); - } - else { - // Get the identity the user asked for, or the first one if he didn't - if(owner.equals("")) { - treeOwner = OwnIdentity.getAllOwnIdentities(db).next(); - } - else { - try { - treeOwner = OwnIdentity.getByURI(db, owner); - } catch (Exception e) { - return e.getMessage(); - } - } - - // Display a form to select the tree owner - HTMLNode selectForm = pr.addFormChild(listBoxContent, SELF_URI, "viewTree"); - selectForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "viewTree" }); - HTMLNode selectBox = selectForm.addChild("select", "name", "ownerURI"); - - ObjectSet<OwnIdentity> ownIdentities = OwnIdentity.getAllOwnIdentities(db); - while(ownIdentities.hasNext()) { - OwnIdentity ownIdentity = ownIdentities.next(); - if(ownIdentity == treeOwner) { - selectBox.addChild("option", new String [] {"value", "selected"}, new String [] {ownIdentity.getRequestURI().toString(), "selected"}, ownIdentity.getNickName()); - } - else { - selectBox.addChild("option", "value", ownIdentity.getRequestURI().toString(), ownIdentity.getNickName()); - } - } - selectForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "select", "View this identity's Web of Trust" }); - } - - // Display the list of known identities - HTMLNode identitiesTable = listBoxContent.addChild("table", "border", "0"); - HTMLNode row=identitiesTable.addChild("tr"); - row.addChild("th", "NickName"); - row.addChild("th", "Last update"); - row.addChild("th", "Publish TrustList ?"); - row.addChild("th", "Score (Rank)"); - row.addChild("th", "Trust/Comment"); - row.addChild("th", "Trusters"); - row.addChild("th", "Trustees"); - - ObjectSet<Identity> identities = Identity.getAllIdentities(db); - while(identities.hasNext()) { - Identity id = identities.next(); - - if(id == treeOwner) continue; - - row=identitiesTable.addChild("tr"); - - // NickName - row.addChild("td", new String[] {"title", "style"}, new String[] {id.getRequestURI().toString(), "cursor: help;"}, id.getNickName()); - - // Last Change - if (id.getLastChange().equals(new Date(0))) row.addChild("td", "Fetching..."); - else row.addChild("td", id.getLastChange().toString()); - - // Publish TrustList - row.addChild("td", new String[] { "align" }, new String[] { "center" } , id.doesPublishTrustList() ? "Yes" : "No"); - - //Score - try { - row.addChild("td", new String[] { "align" }, new String[] { "center" } , String.valueOf(id.getScore((OwnIdentity)treeOwner, db).getScore())+" ("+id.getScore((OwnIdentity)treeOwner, db).getRank()+")"); - } - catch (NotInTrustTreeException e) { - // This only happen with identities added manually by the user - // TODO Maybe we should give the opportunity to trust it at creation time - row.addChild("td", "null"); - } - - // Trust - String trustValue = ""; - String trustComment = ""; - - Trust trust; - try { - trust = treeOwner.getGivenTrust(id, db); - trustValue = String.valueOf(trust.getValue()); - trustComment = trust.getComment(); - } catch (NotTrustedException e) {} - - HTMLNode cell = row.addChild("td"); - HTMLNode trustForm = pr.addFormChild(cell, SELF_URI, "setTrust"); - trustForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "setTrust" }); - trustForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "truster", treeOwner.getRequestURI().toString() }); - trustForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "trustee", id.getRequestURI().toString() }); - trustForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "value", "2", trustValue }); - trustForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "comment", "20", trustComment }); - trustForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "update", "Update !" }); - - // Trusters - HTMLNode trustersCell = row.addChild("td", new String[] { "align" }, new String[] { "center" }); - trustersCell.addChild(new HTMLNode("a", "href", SELF_URI + "?getTrusters&id="+id.getId(), Long.toString(id.getNbReceivedTrusts(db)))); - - //Trustees - HTMLNode trusteesCell = row.addChild("td", new String[] { "align" }, new String[] { "center" }); - trusteesCell.addChild(new HTMLNode("a", "href", SELF_URI + "?getTrustees&id="+id.getId(), Long.toString(id.getNbGivenTrusts(db)))); - } - contentNode.addChild(addBox); - contentNode.addChild(listBox); - return pageNode.generate(); - } - - public String makeCreateIdentityPage(HTTPRequest request) { - - String nickName = request.getPartAsString("nickName",1024); - HTMLNode pageNode = getPageNode(); - HTMLNode contentNode = pm.getContentNode(pageNode); - HTMLNode box = pm.getInfobox("Identity creation"); - HTMLNode boxContent = pm.getContentNode(box); - - FreenetURI[] keypair = client.generateKeyPair("WoT"); - - HTMLNode createForm = pr.addFormChild(boxContent, SELF_URI, "createIdentity2"); - createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "createIdentity2" }); - createForm.addChild("#", "Request URI : "); - createForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "requestURI", "70", keypair[1].toString() }); - createForm.addChild("br"); - createForm.addChild("#", "Insert URI : "); - createForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "insertURI", "70", keypair[0].toString() }); - createForm.addChild("br"); - createForm.addChild("#", "Publish trust list "); - createForm.addChild("input", new String[] { "type", "name", "value", "checked" }, new String[] { "checkbox", "publishTrustList", "true", "checked"}); - createForm.addChild("br"); - createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "nickName", nickName }); - createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "create", "Create a new identity !" }); - - contentNode.addChild(box); - return pageNode.generate(); - } - - public String makeEditIdentityPage(String requestURI) throws MalformedURLException, InvalidParameterException, UnknownIdentityException, DuplicateIdentityException { - - OwnIdentity id = OwnIdentity.getByURI(db, requestURI); - - HTMLNode pageNode = getPageNode(); - HTMLNode contentNode = pm.getContentNode(pageNode); - HTMLNode box = pm.getInfobox("Identity edition"); - HTMLNode boxContent = pm.getContentNode(box); - - HTMLNode createForm = pr.addFormChild(boxContent, SELF_URI, "editIdentity2"); - createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "editIdentity2"}); - - createForm.addChild("p", "NickName : " + id.getNickName()); - - createForm.addChild("p", new String[] { "style" }, new String[] { "font-size: x-small" }, "Request URI : "+id.getRequestURI().toString()); - createForm.addChild("p", new String[] { "style" }, new String[] { "font-size: x-small" }, "Insert URI : "+id.getInsertURI().toString()); - - createForm.addChild("#", "Publish trust list "); - if(id.doesPublishTrustList()) - createForm.addChild("input", new String[] { "type", "name", "value", "checked" }, new String[] { "checkbox", "publishTrustList", "true", "checked"}); - else - createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "checkbox", "publishTrustList", "true"}); - createForm.addChild("br"); - - createForm.addChild("p", "Contexts : "+id.getContextsAsString()); - - createForm.addChild("p", "Properties : "+id.getPropsAsString()); - - // TODO Give the user the ability to edit these parameters... - - contentNode.addChild(box); - return pageNode.generate(); - } - - public String getTrustersPage(String id) throws DuplicateIdentityException, UnknownIdentityException { - - Identity identity = Identity.getById(db, id); - - HTMLNode pageNode = getPageNode(); - HTMLNode contentNode = pm.getContentNode(pageNode); - HTMLNode box = pm.getInfobox("Identities that trust '" + identity.getNickName() + "'"); - HTMLNode boxContent = pm.getContentNode(box); - - // Display the list of known identities - HTMLNode identitiesTable = boxContent.addChild("table", "border", "0"); - HTMLNode title = identitiesTable.addChild("tr"); - title.addChild("th", "NickName"); - title.addChild("th", "Last update"); - title.addChild("th", "Trust (Comment)"); - title.addChild("th", "Trusters"); - title.addChild("th", "Trustees"); - - ObjectSet<Trust> trusters = identity.getReceivedTrusts(db); - while(trusters.hasNext()) { - - Trust trust = trusters.next(); - HTMLNode row=identitiesTable.addChild("tr"); - - // NickName - row.addChild("td", new String[] {"title", "style"}, new String[] {trust.getTruster().getRequestURI().toString(), "cursor: help;"}, trust.getTruster().getNickName()); - - // Last Change - if (trust.getTruster().getLastChange().equals(new Date(0))) row.addChild("td", "Fetching..."); - else row.addChild("td", trust.getTruster().getLastChange().toString()); - - // Trust/Comment - row.addChild("td", trust.getValue() + " (" + trust.getComment() + ")"); - - // Trusters - HTMLNode trustersCell = row.addChild("td", new String[] { "align" }, new String[] { "center" }); - trustersCell.addChild(new HTMLNode("a", "href", SELF_URI + "?getTrusters&id="+trust.getTruster().getId(), Long.toString(trust.getTruster().getNbReceivedTrusts(db)))); - - //Trustees - HTMLNode trusteesCell = row.addChild("td", new String[] { "align" }, new String[] { "center" }); - trusteesCell.addChild(new HTMLNode("a", "href", SELF_URI + "?getTrustees&id="+trust.getTruster().getId(), Long.toString(trust.getTruster().getNbGivenTrusts(db)))); - - } - - contentNode.addChild(box); - return pageNode.generate(); - } - - public String getTrusteesPage(String id) throws DuplicateIdentityException, UnknownIdentityException { - - Identity identity = Identity.getById(db, id); - - HTMLNode pageNode = getPageNode(); - HTMLNode contentNode = pm.getContentNode(pageNode); - HTMLNode box = pm.getInfobox("Identities that '" + identity.getNickName() + "' trusts"); - HTMLNode boxContent = pm.getContentNode(box); - - // Display the list of known identities - HTMLNode identitiesTable = boxContent.addChild("table", "border", "0"); - HTMLNode title = identitiesTable.addChild("tr"); - title.addChild("th", "NickName"); - title.addChild("th", "Last update"); - title.addChild("th", "Trust (Comment)"); - title.addChild("th", "Trusters"); - title.addChild("th", "Trustees"); - - ObjectSet<Trust> trustees = identity.getGivenTrusts(db); - while(trustees.hasNext()) { - - Trust trust = trustees.next(); - HTMLNode row=identitiesTable.addChild("tr"); - - // NickName - row.addChild("td", new String[] {"title", "style"}, new String[] {trust.getTrustee().getRequestURI().toString(), "cursor: help;"}, trust.getTrustee().getNickName()); - - // Last Change - if (trust.getTrustee().getLastChange().equals(new Date(0))) row.addChild("td", "Fetching..."); - else row.addChild("td", trust.getTrustee().getLastChange().toString()); - - // Trust/Comment - row.addChild("td", trust.getValue() + " (" + trust.getComment() + ")"); - - // Trusters - HTMLNode trustersCell = row.addChild("td", new String[] { "align" }, new String[] { "center" }); - trustersCell.addChild(new HTMLNode("a", "href", SELF_URI + "?getTrusters&id="+trust.getTrustee().getId(), Long.toString(trust.getTrustee().getNbReceivedTrusts(db)))); - - //Trustees - HTMLNode trusteesCell = row.addChild("td", new String[] { "align" }, new String[] { "center" }); - trusteesCell.addChild(new HTMLNode("a", "href", SELF_URI + "?getTrustees&id="+trust.getTrustee().getId(), Long.toString(trust.getTrustee().getNbGivenTrusts(db)))); - - } - - contentNode.addChild(box); - return pageNode.generate(); - } - - public String makeDeleteIdentityPage(String id) throws DuplicateIdentityException, UnknownIdentityException { - Identity identity = Identity.getById(db, id); - - HTMLNode pageNode = getPageNode(); - HTMLNode contentNode = pm.getContentNode(pageNode); - HTMLNode box = pm.getInfobox("Confirm identity deletion"); - HTMLNode boxContent = pm.getContentNode(box); - - boxContent.addChild(new HTMLNode("p", "You are about to delete identity '" + identity.getNickName() + "', are you sure ?")); - - if(identity instanceof OwnIdentity) - boxContent.addChild(new HTMLNode("p", "You might want to backup its keys for later use...")); - - HTMLNode confirmForm = pr.addFormChild(boxContent, SELF_URI, "deleteIdentity2"); - - confirmForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "deleteIdentity2" }); - confirmForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "id", identity.getId() }); - confirmForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "confirm", "Confirm !" }); - - contentNode.addChild(box); - return pageNode.generate(); - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/WoT.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/WoT.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/WoT.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,691 +0,0 @@ -/** - * 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.WoT; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.Iterator; -import java.util.Map.Entry; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; - -import com.db4o.Db4o; -import com.db4o.config.Configuration; -import com.db4o.ObjectContainer; -import com.db4o.ObjectSet; -import com.db4o.ext.DatabaseClosedException; -import com.db4o.ext.Db4oIOException; - -import freenet.client.FetchException; -import freenet.client.HighLevelSimpleClient; -import freenet.client.InsertException; -import freenet.keys.FreenetURI; -import freenet.l10n.L10n.LANGUAGE; -import freenet.pluginmanager.FredPlugin; -import freenet.pluginmanager.FredPluginFCP; -import freenet.pluginmanager.FredPluginHTTP; -import freenet.pluginmanager.FredPluginL10n; -import freenet.pluginmanager.FredPluginThreadless; -import freenet.pluginmanager.FredPluginVersioned; -import freenet.pluginmanager.PluginHTTPException; -import freenet.pluginmanager.PluginReplySender; -import freenet.pluginmanager.PluginRespirator; -import freenet.support.Logger; -import freenet.support.SimpleFieldSet; -import freenet.support.api.Bucket; -import freenet.support.api.HTTPRequest; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - */ -public class WoT implements FredPlugin, FredPluginHTTP, FredPluginThreadless, FredPluginFCP, FredPluginVersioned, FredPluginL10n { - - private PluginRespirator pr; - private HighLevelSimpleClient client; - - private ObjectContainer db; - private WebInterface web; - private IdentityInserter inserter; - private IdentityFetcher fetcher; - private String seedURI = "USK at MF2Vc6FRgeFMZJ0s2l9hOop87EYWAydUZakJzL0OfV8,fQeN-RMQZsUrDha2LCJWOMFk1-EiXZxfTnBT8NEgY00,AQACAAE/WoT/0"; - private Identity seed; - //private Config config; - - public static String SELF_URI = "/plugins/plugins.WoT.WoT"; - - public void runPlugin(PluginRespirator pr) { - - Logger.debug(this, "Start"); - - // Init - this.pr = pr; - Configuration config = Db4o.newConfiguration(); - config.objectClass(Identity.class).objectField("id").indexed(true); - config.objectClass(OwnIdentity.class).objectField("id").indexed(true); - config.objectClass(Trust.class).objectField("truster").indexed(true); - config.objectClass(Trust.class).objectField("trustee").indexed(true); - config.objectClass(Score.class).objectField("treeOwner").indexed(true); - config.objectClass(Score.class).objectField("target").indexed(true); - db = Db4o.openFile(config, "WoT.db4o"); - - client = pr.getHLSimpleClient(); - web = new WebInterface(pr, db, client, SELF_URI); - - /* - try { - ObjectSet<Config> result = db.queryByExample(Config.class); - if(result.size() == 0) { - Logger.debug(this, "Created new config"); - config = new Config(db); - db.store(config); - } - else { - Logger.debug(this, "Loaded config"); - config = result.next(); - config.initDefault(false); - } - } - catch(Exception e) { - Logger.error(this, e.getMessage(), e); - } - */ - - // Create the seed Identity if it doesn't exist - try { - seed = Identity.getByURI(db, seedURI); - } catch (UnknownIdentityException e) { - try { - seed = new Identity(seedURI, "Fetching seed identity...", "true"); - } catch (Exception e1) { - Logger.error(this, "Seed identity creation error", e); - return; - } - db.store(seed); - db.commit(); - } catch (Exception e) { - Logger.error(this, "Seed identity loading error", e); - return; - } - - // Start the inserter thread - inserter = new IdentityInserter(db, client, pr.getNode().clientCore.tempBucketFactory); - pr.getNode().executor.execute(inserter, "WoTinserter"); - - // Create the fetcher - fetcher = new IdentityFetcher(db, client); - - // Try to fetch all known identities - ObjectSet<Identity> identities = Identity.getAllIdentities(db); - while (identities.hasNext()) { - fetcher.fetch(identities.next(), true); - } - } - - public void terminate() { - inserter.stop(); - db.commit(); - db.close(); - fetcher.stop(); // Do this after cleanly closing the database, as it sometimes locks - } - - public String handleHTTPGet(HTTPRequest request) throws PluginHTTPException { - - try { - if(request.isParameterSet("ownidentities")) - return web.makeOwnIdentitiesPage(); - - if(request.isParameterSet("knownidentities")) - return web.makeKnownIdentitiesPage(); - - if(request.isParameterSet("getTrusters")) - return web.getTrustersPage(request.getParam("id")); - - if(request.isParameterSet("getTrustees")) - return web.getTrusteesPage(request.getParam("id")); - - return web.makeHomePage(); - - } catch (Exception e) { - e.printStackTrace(); - return e.getMessage(); - } - } - - public String handleHTTPPost(HTTPRequest request) throws PluginHTTPException { - - String pass = request.getPartAsString("formPassword", 32); - if ((pass.length() == 0) || !pass.equals(pr.getNode().clientCore.formPassword)) { - return "Buh! Invalid form password"; - } - - try { - if(request.getPartAsString("page",50).equals("createIdentity")) { - return web.makeCreateIdentityPage(request); - } - else if(request.getPartAsString("page",50).equals("createIdentity2")) { - createIdentity(request); - return web.makeOwnIdentitiesPage(); - } - else if(request.getPartAsString("page",50).equals("addIdentity")) { - addIdentity(request); - return web.makeKnownIdentitiesPage(); - } - else if(request.getPartAsString("page",50).equals("viewTree")) { - return web.makeKnownIdentitiesPage(request); - } - else if(request.getPartAsString("page",50).equals("setTrust")) { - setTrust(request); - return web.makeKnownIdentitiesPage(request.getPartAsString("truster", 1024)); - } - else if(request.getPartAsString("page",50).equals("editIdentity")) { - return web.makeEditIdentityPage(request.getPartAsString("id", 1024)); - } - else if(request.getPartAsString("page",50).equals("restoreIdentity")) { - restoreIdentity(request.getPartAsString("requestURI", 1024), request.getPartAsString("insertURI", 1024)); - return web.makeOwnIdentitiesPage(); - } - else if(request.getPartAsString("page",50).equals("deleteIdentity")) { - return web.makeDeleteIdentityPage(request.getPartAsString("id", 1024)); - } - else if(request.getPartAsString("page",50).equals("deleteIdentity2")) { - deleteIdentity(request.getPartAsString("id", 1024)); - return web.makeOwnIdentitiesPage(); - } - else { - return web.makeHomePage(); - } - } catch (Exception e) { - e.printStackTrace(); - return e.getLocalizedMessage(); - } - } - - private void deleteIdentity(String id) throws DuplicateIdentityException, UnknownIdentityException, DuplicateScoreException, DuplicateTrustException { - Identity identity = Identity.getById(db, id); - - // Remove all scores - ObjectSet<Score> scores = identity.getScores(db); - while (scores.hasNext()) db.delete(scores.next()); - - // Remove all received trusts - ObjectSet<Trust> receivedTrusts = identity.getReceivedTrusts(db); - while (receivedTrusts.hasNext()) db.delete(receivedTrusts.next()); - - // Remove all given trusts and update trustees' scores - ObjectSet<Trust> givenTrusts = identity.getGivenTrusts(db); - while (givenTrusts.hasNext()) { - Trust givenTrust = givenTrusts.next(); - db.delete(givenTrust); - givenTrust.getTrustee().updateScore(db); - } - - db.delete(identity); - } - - private void restoreIdentity(String requestURI, String insertURI) throws InvalidParameterException, MalformedURLException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, DuplicateIdentityException, DuplicateTrustException { - - OwnIdentity id; - - try { - Identity old = Identity.getByURI(db, requestURI); - - // We already have fetched this identity as a stranger's one. We need to update the database. - id = new OwnIdentity(insertURI, requestURI, old.getNickName(), old.doesPublishTrustList() ? "true" : "false"); - - Iterator<String> i1 = old.getContexts(); - while (i1.hasNext()) id.addContext(i1.next(), db); - - Iterator<Entry<String, String>> i2 = old.getProps(); - while (i2.hasNext()) { - Entry<String, String> prop = i2.next(); - id.setProp(prop.getKey(), prop.getValue(), db); - } - - // Update all received trusts - ObjectSet<Trust> receivedTrusts = old.getReceivedTrusts(db); - while(receivedTrusts.hasNext()) { - Trust receivedTrust = receivedTrusts.next(); - receivedTrust.setTrustee(id); - db.store(receivedTrust); - } - - // Update all received scores - ObjectSet<Score> scores = old.getScores(db); - while(scores.hasNext()) { - Score score = scores.next(); - score.setTarget(id); - db.store(score); - } - - // Store the new identity - db.store(id); - id.initTrustTree(db); - - // Update all given trusts - ObjectSet<Trust> givenTrusts = old.getGivenTrusts(db); - while(givenTrusts.hasNext()) { - Trust givenTrust = givenTrusts.next(); - id.setTrust(db, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); - db.delete(givenTrust); - } - - // Remove the old identity - db.delete(old); - - Logger.debug(this, "Successfully restored an already known identity from Freenet (" + id.getNickName() + ")"); - - } catch (UnknownIdentityException e) { - id = new OwnIdentity(insertURI, requestURI, "Restore in progress...", "false"); - - // Store the new identity - db.store(id); - id.initTrustTree(db); - - // Fetch the identity from freenet - fetcher.fetch(id); - - Logger.debug(this, "Trying to restore a not-yet-known identity from Freenet (" + id.getRequestURI() + ")"); - } - db.commit(); - } - - private void setTrust(HTTPRequest request) throws NumberFormatException, TransformerConfigurationException, FileNotFoundException, InvalidParameterException, UnknownIdentityException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, DuplicateIdentityException, NotTrustedException, DuplicateTrustException { - - setTrust( request.getPartAsString("truster", 1024), - request.getPartAsString("trustee", 1024), - request.getPartAsString("value", 1024), - request.getPartAsString("comment", 1024)); - } - - private void setTrust(String truster, String trustee, String value, String comment) throws InvalidParameterException, UnknownIdentityException, NumberFormatException, TransformerConfigurationException, FileNotFoundException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, DuplicateIdentityException, NotTrustedException, DuplicateTrustException { - - OwnIdentity trusterId = OwnIdentity.getByURI(db, truster); - Identity trusteeId = Identity.getByURI(db, trustee); - - setTrust((OwnIdentity)trusterId, trusteeId, Integer.parseInt(value), comment); -} - - private void setTrust(OwnIdentity truster, Identity trustee, int value, String comment) throws TransformerConfigurationException, FileNotFoundException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, InvalidParameterException, DuplicateScoreException, NotTrustedException, DuplicateTrustException { - - truster.setTrust(db, trustee, value, comment); - truster.updated(); - db.store(truster); - db.commit(); - } - - private void addIdentity(HTTPRequest request) throws MalformedURLException, InvalidParameterException, FetchException, DuplicateIdentityException { - addIdentity(request.getPartAsString("identityURI", 1024).trim()); - } - - private Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException, FetchException, DuplicateIdentityException { - Identity identity = null; - try { - identity = Identity.getByURI(db, requestURI); - Logger.error(this, "Tried to manually add an identity we already know, ignored."); - throw new InvalidParameterException("We already have this identity"); - } - catch (UnknownIdentityException e) { - // TODO Only add the identity after it is successfully fetched - - identity = new Identity(requestURI, "Not found yet...", "false"); - db.store(identity); - db.commit(); - Logger.debug(this, "Trying to fetch manually added identity (" + identity.getRequestURI() + ")"); - fetcher.fetch(identity); - } - return identity; - } - - private OwnIdentity createIdentity(HTTPRequest request) throws TransformerConfigurationException, FileNotFoundException, InvalidParameterException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, NotTrustedException, DuplicateTrustException { - - return createIdentity( request.getPartAsString("insertURI",1024), - request.getPartAsString("requestURI",1024), - request.getPartAsString("nickName", 1024), - request.getPartAsString("publishTrustList", 1024), - "testing"); - } - - private OwnIdentity createIdentity(String nickName, String publishTrustList, String context) throws TransformerConfigurationException, FileNotFoundException, InvalidParameterException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, NotTrustedException, DuplicateTrustException { - - FreenetURI[] keypair = client.generateKeyPair("WoT"); - return createIdentity(keypair[0].toString(), keypair[1].toString(), nickName, publishTrustList, context); - } - - private OwnIdentity createIdentity(String insertURI, String requestURI, String nickName, String publishTrustList, String context) throws InvalidParameterException, TransformerConfigurationException, FileNotFoundException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, NotTrustedException, DuplicateTrustException { - - // TODO Add context in the creation form - OwnIdentity identity = new OwnIdentity(insertURI, requestURI, nickName, publishTrustList); - db.store(identity); - identity.initTrustTree(db); - - // This identity trusts the seed identity - identity.setTrust(db, seed, 100, "I trust the WoT plugin"); - - Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickName() + ")"); - - db.commit(); - - return identity; - } - - private void addContext(String identity, String context) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { - Identity id = OwnIdentity.getByURI(db, identity); - id.addContext(context, db); - db.store(id); - - Logger.debug(this, "Added context '" + context + "' to identity '" + id.getNickName() + "'"); - } - - private void removeContext(String identity, String context) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { - Identity id = OwnIdentity.getByURI(db, identity); - id.removeContext(context, db); - db.store(id); - - Logger.debug(this, "Removed context '" + context + "' from identity '" + id.getNickName() + "'"); - } - - private void setProperty(String identity, String property, String value) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { - Identity id = OwnIdentity.getByURI(db, identity); - id.setProp(property, value, db); - db.store(id); - - Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + id.getNickName() + "'"); - } - - private String getProperty(String identity, String property) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { - return Identity.getByURI(db, identity).getProp(property); - } - - private void removeProperty(String identity, String property) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { - Identity id = OwnIdentity.getByURI(db, identity); - id.removeProp(property, db); - db.store(id); - - Logger.debug(this, "Removed property '" + property + "' from identity '" + id.getNickName() + "'"); - } - - public String handleHTTPPut(HTTPRequest request) throws PluginHTTPException { - return null; - } - - public String getVersion() { - return "0.3.1 r"+Version.getSvnRevision(); - } - - public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { - - try { - if(params.get("Message").equals("CreateIdentity")) { - replysender.send(handleCreateIdentity(params), data); - } - else if(params.get("Message").equals("SetTrust")) { - replysender.send(handleSetTrust(params), data); - } - else if(params.get("Message").equals("AddIdentity")) { - replysender.send(handleAddIdentity(params), data); - } - else if(params.get("Message").equals("GetIdentity")) { - replysender.send(handleGetIdentity(params), data); - } - else if(params.get("Message").equals("GetIdentitiesByScore")) { - replysender.send(handleGetIdentitiesByScore(params), data); - } - else if(params.get("Message").equals("GetTrusters")) { - replysender.send(handleGetTrusters(params), data); - } - else if(params.get("Message").equals("GetTrustees")) { - replysender.send(handleGetTrustees(params), data); - } - else if(params.get("Message").equals("AddContext")) { - replysender.send(handleAddContext(params), data); - } - else if(params.get("Message").equals("RemoveContext")) { - replysender.send(handleRemoveContext(params), data); - } - else if(params.get("Message").equals("SetProperty")) { - replysender.send(handleSetProperty(params), data); - } - else if(params.get("Message").equals("GetProperty")) { - replysender.send(handleGetProperty(params), data); - } - else if(params.get("Message").equals("RemoveProperty")) { - replysender.send(handleRemoveProperty(params), data); - } - else { - throw new Exception("Unknown message (" + params.get("Message") + ")"); - } - } - catch (Exception e) { - replysender.send(errorMessageFCP(e), data); - } - } - - private SimpleFieldSet handleCreateIdentity(SimpleFieldSet params) throws TransformerConfigurationException, FileNotFoundException, InvalidParameterException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, NotTrustedException, DuplicateTrustException { - - SimpleFieldSet sfs = new SimpleFieldSet(false); - OwnIdentity identity; - - if(params.get("NickName")==null || params.get("PublishTrustList")==null || params.get("Context")==null) throw new InvalidParameterException("Missing mandatory parameter"); - - if(params.get("RequestURI")==null || params.get("InsertURI")==null) { - identity = createIdentity(params.get("NickName"), params.get("PublishTrustList"), params.get("Context")); - } - else { - identity = createIdentity( params.get("InsertURI"), - params.get("RequestURI"), - params.get("NickName"), - params.get("PublishTrustList"), - params.get("Context")); - } - sfs.putAppend("Message", "IdentityCreated"); - sfs.putAppend("InsertURI", identity.getInsertURI().toString()); - sfs.putAppend("RequestURI", identity.getRequestURI().toString()); - return sfs; - } - - private SimpleFieldSet handleSetTrust(SimpleFieldSet params) throws NumberFormatException, TransformerConfigurationException, FileNotFoundException, InvalidParameterException, ParserConfigurationException, TransformerException, IOException, InsertException, UnknownIdentityException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, DuplicateIdentityException, NotTrustedException, DuplicateTrustException { - - SimpleFieldSet sfs = new SimpleFieldSet(false); - - if(params.get("Truster") == null || params.get("Trustee") == null || params.get("Value") == null || params.get("Comment") == null) throw new InvalidParameterException("Missing mandatory parameter"); - - setTrust(params.get("Truster"), params.get("Trustee"), params.get("Value"), params.get("Comment")); - - sfs.putAppend("Message", "TrustSet"); - return sfs; - } - - private SimpleFieldSet handleAddIdentity(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, FetchException, DuplicateIdentityException { - - SimpleFieldSet sfs = new SimpleFieldSet(false); - - if(params.get("RequestURI") == null) throw new InvalidParameterException("Missing mandatory parameter"); - - Identity identity = addIdentity(params.get("RequestURI").trim()); - - sfs.putAppend("Message", "IdentityAdded"); - sfs.putAppend("RequestURI", identity.getRequestURI().toString()); - return sfs; - } - - private SimpleFieldSet handleGetIdentity(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, FetchException, UnknownIdentityException, DuplicateScoreException, DuplicateIdentityException, DuplicateTrustException { - - SimpleFieldSet sfs = new SimpleFieldSet(false); - - if(params.get("TreeOwner") == null || params.get("Identity") == null) throw new InvalidParameterException("Missing mandatory parameter"); - - sfs.putAppend("Message", "Identity"); - - OwnIdentity treeOwner = OwnIdentity.getByURI(db, params.get("TreeOwner")); - Identity identity = Identity.getByURI(db, params.get("Identity")); - - try { - Trust trust = identity.getReceivedTrust(treeOwner, db); - sfs.putAppend("Trust", String.valueOf(trust.getValue())); - } catch (NotTrustedException e1) { - sfs.putAppend("Trust", "null"); - } - - Score score; - try { - score = identity.getScore(treeOwner, db); - sfs.putAppend("Score", String.valueOf(score.getScore())); - sfs.putAppend("Rank", String.valueOf(score.getRank())); - } catch (NotInTrustTreeException e) { - sfs.putAppend("Score", "null"); - sfs.putAppend("Rank", "null"); - } - - Iterator<String> contexts = identity.getContexts(); - for(int i = 1 ; contexts.hasNext() ; i++) sfs.putAppend("Context"+i, contexts.next()); - - return sfs; - } - - private SimpleFieldSet handleGetIdentitiesByScore(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { - - SimpleFieldSet sfs = new SimpleFieldSet(false); - - if(params.get("TreeOwner") == null || params.get("Select") == null || params.get("Context") == null) throw new InvalidParameterException("Missing mandatory parameter"); - - sfs.putAppend("Message", "Identities"); - - ObjectSet<Score> result = Score.getIdentitiesByScore(params.get("TreeOwner"), params.get("Select").trim(), db); - for(int i = 1 ; result.hasNext() ; i++) { - Score score = result.next(); - // Maybe there is a way to do this through SODA - if(score.getTarget().hasContext(params.get("Context")) || params.get("Context").equals("all")) - sfs.putAppend("Identity"+i, score.getTarget().getRequestURI().toString()); - } - return sfs; - } - - private SimpleFieldSet handleGetTrusters(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, Db4oIOException, DatabaseClosedException, DuplicateIdentityException { - - SimpleFieldSet sfs = new SimpleFieldSet(false); - - if(params.get("Identity") == null || params.get("Context") == null) throw new InvalidParameterException("Missing mandatory parameter"); - - sfs.putAppend("Message", "Identities"); - - ObjectSet<Trust> result = Identity.getByURI(db, params.get("Identity")).getReceivedTrusts(db); - - for(int i = 1 ; result.hasNext() ; i++) { - Trust trust = result.next(); - // Maybe there is a way to do this through SODA - if(trust.getTruster().hasContext(params.get("Context")) || params.get("Context").equals("all")) { - sfs.putAppend("Identity"+i, trust.getTruster().getRequestURI().toString()); - sfs.putAppend("Value"+i, String.valueOf(trust.getValue())); - sfs.putAppend("Comment"+i, trust.getComment()); - } - } - return sfs; - } - - private SimpleFieldSet handleGetTrustees(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, Db4oIOException, DatabaseClosedException, DuplicateIdentityException { - - SimpleFieldSet sfs = new SimpleFieldSet(false); - - if(params.get("Identity") == null || params.get("Context") == null) throw new InvalidParameterException("Missing mandatory parameter"); - - sfs.putAppend("Message", "Identities"); - - ObjectSet<Trust> result = Identity.getByURI(db, params.get("Identity")).getGivenTrusts(db); - - for(int i = 1 ; result.hasNext() ; i++) { - Trust trust = result.next(); - // Maybe there is a way to do this through SODA - if(trust.getTrustee().hasContext(params.get("Context")) || params.get("Context").equals("all")) { - sfs.putAppend("Identity"+i, trust.getTrustee().getRequestURI().toString()); - sfs.putAppend("Value"+i, String.valueOf(trust.getValue())); - sfs.putAppend("Comment"+i, trust.getComment()); - } - } - return sfs; - } - - private SimpleFieldSet handleAddContext(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { - - SimpleFieldSet sfs = new SimpleFieldSet(false); - - if(params.get("Identity") == null || params.get("Context") == null) throw new InvalidParameterException("Missing mandatory parameter"); - - addContext(params.get("Identity"), params.get("Context")); - - sfs.putAppend("Message", "ContextAdded"); - return sfs; - } - - private SimpleFieldSet handleRemoveContext(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { - - SimpleFieldSet sfs = new SimpleFieldSet(false); - - if(params.get("Identity") == null || params.get("Context") == null) throw new InvalidParameterException("Missing mandatory parameter"); - - removeContext(params.get("Identity"), params.get("Context")); - - sfs.putAppend("Message", "ContextRemoved"); - return sfs; - } - - private SimpleFieldSet handleSetProperty(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { - - SimpleFieldSet sfs = new SimpleFieldSet(false); - - if(params.get("Identity") == null || params.get("Property") == null || params.get("Value") == null) throw new InvalidParameterException("Missing mandatory parameter"); - - setProperty(params.get("Identity"), params.get("Property"), params.get("Value")); - - sfs.putAppend("Message", "PropertyAdded"); - return sfs; - } - - private SimpleFieldSet handleGetProperty(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { - - SimpleFieldSet sfs = new SimpleFieldSet(false); - - if(params.get("Identity") == null || params.get("Property") == null) throw new InvalidParameterException("Missing mandatory parameter"); - - sfs.putAppend("Message", "PropertyValue"); - sfs.putAppend("Property", getProperty(params.get("Identity"), params.get("Property"))); - - return sfs; - } - - private SimpleFieldSet handleRemoveProperty(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { - - SimpleFieldSet sfs = new SimpleFieldSet(false); - - if(params.get("Identity") == null || params.get("Property") == null) throw new InvalidParameterException("Missing mandatory parameter"); - - removeProperty(params.get("Identity"), params.get("Property")); - - sfs.putAppend("Message", "PropertyRemoved"); - return sfs; - } - - private SimpleFieldSet errorMessageFCP (Exception e) { - - SimpleFieldSet sfs = new SimpleFieldSet(false); - sfs.putAppend("Message", "Error"); - sfs.putAppend("Description", (e.getLocalizedMessage() == null) ? "null" : e.getLocalizedMessage()); - e.printStackTrace(); - return sfs; - } - - public String getString(String key) { - // TODO Auto-generated method stub - return key; - } - - public void setLanguage(LANGUAGE newLanguage) { - // TODO Auto-generated method stub - } -} Deleted: trunk/plugins/WoT/src/plugins/WoT/WoTTest.java =================================================================== --- trunk/plugins/WoT/src/plugins/WoT/WoTTest.java 2008-09-17 12:24:54 UTC (rev 22663) +++ trunk/plugins/WoT/src/plugins/WoT/WoTTest.java 2008-09-17 13:37:05 UTC (rev 22664) @@ -1,269 +0,0 @@ -/** - * 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.WoT; - -import java.io.File; -import java.net.MalformedURLException; - -import com.db4o.Db4o; -import com.db4o.ObjectContainer; -import com.db4o.ObjectSet; - -import junit.framework.TestCase; - -/** - * @author Julien Cornuwel (batosai at freenetproject.org) - */ -public class WoTTest extends TestCase { - - private ObjectContainer db; - - private String uriA = "USK at MF2Vc6FRgeFMZJ0s2l9hOop87EYWAydUZakJzL0OfV8,fQeN-RMQZsUrDha2LCJWOMFk1-EiXZxfTnBT8NEgY00,AQACAAE/WoT/0"; - private String uriB = "USK at R3Lp2s4jdX-3Q96c0A9530qg7JsvA9vi2K0hwY9wG-4,ipkgYftRpo0StBlYkJUawZhg~SO29NZIINseUtBhEfE,AQACAAE/WoT/0"; - private String uriC = "USK at qd-hk0vHYg7YvK2BQsJMcUD5QSF0tDkgnnF6lnWUH0g,xTFOV9ddCQQk6vQ6G~jfL6IzRUgmfMcZJ6nuySu~NUc,AQACAAE/WoT/0"; - - public WoTTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - - super.setUp(); - db = Db4o.openFile("wotTest.db4o"); - } - - protected void tearDown() throws Exception { - db.close(); - new File("wotTest.db4o").delete(); - } - - public void testInitTrustTree() throws DuplicateScoreException, NotInTrustTreeException, MalformedURLException, InvalidParameterException { - - OwnIdentity a = new OwnIdentity(uriA, uriA, "A", "true"); - db.store(a); - a.initTrustTree(db); - - assertTrue(Identity.getNbIdentities(db) == 0); - assertTrue(OwnIdentity.getNbOwnIdentities(db) == 1); - assertTrue(Trust.getNb(db) == 0); - assertTrue(Score.getNb(db) == 1); - - assertTrue(a.getScore(a, db).getScore() == 100); - assertTrue(a.getScore(a, db).getRank() == 0); - assertTrue(a.getScore(a, db).getCapacity() == 100); - assertTrue(a.getScore(a, db).getTreeOwner() == a); - assertTrue(a.getScore(a, db).getTarget() == a); - - // Empty the database - ObjectSet<Object> all = db.queryByExample(new Object()); - while(all.hasNext()) db.delete(all.next()); - } - - public void testSetTrust() throws DuplicateTrustException, InvalidParameterException, DuplicateScoreException, NotTrustedException, NotInTrustTreeException, MalformedURLException { - - OwnIdentity a = new OwnIdentity(uriA, uriA, "A", "true"); - Identity b = new Identity(uriB, "B", "true"); - db.store(a); - db.store(b); - - // With A's trust tree not initialized, B shouldn't get a Score. - a.setTrust(db, b, 10, "Foo"); - - assertTrue(Identity.getNbIdentities(db) == 1); - assertTrue(OwnIdentity.getNbOwnIdentities(db) == 1); - assertTrue(Trust.getNb(db) == 1); - assertTrue(Score.getNb(db) == 0); - - // Initialize A's trust tree and set the trust relationship - a.initTrustTree(db); - a.setTrust(db, b, 100, "Foo"); - - // Check we have the correct number of objects - assertTrue(Identity.getNbIdentities(db) == 1); - assertTrue(OwnIdentity.getNbOwnIdentities(db) == 1); - assertTrue(Trust.getNb(db) == 1); - assertTrue(Score.getNb(db) == 2); - - // Check the Trust object - assertTrue(b.getReceivedTrust(a, db).getTruster() == a); - assertTrue(b.getReceivedTrust(a, db).getTrustee() == b); - assertTrue(b.getReceivedTrust(a, db).getValue() == 100); - assertTrue(b.getReceivedTrust(a, db).getComment().equals("Foo")); - - // Check a's Score object - assertTrue(a.getScore(a, db).getScore() == 100); - assertTrue(a.getScore(a, db).getRank() == 0); - assertTrue(a.getScore(a, db).getCapacity() == 100); - - // Check B's Score object - assertTrue(b.getScore(a, db).getScore() == 100); - assertTrue(b.getScore(a, db).getRank() == 1); - assertTrue(b.getScore(a, db).getCapacity() == 40); - - // Change the trust value and comment - a.setTrust(db, b, 50, "Bar"); - - // Check we have the correct number of objects - assertTrue(Identity.getNbIdentities(db) == 1); - assertTrue(OwnIdentity.getNbOwnIdentities(db) == 1); - assertTrue(Trust.getNb(db) == 1); - assertTrue(Score.getNb(db) == 2); - - // Check the Trust object - assertTrue(b.getReceivedTrust(a, db).getTruster() == a); - assertTrue(b.getReceivedTrust(a, db).getTrustee() == b); - assertTrue(b.getReceivedTrust(a, db).getValue() == 50); - assertTrue(b.getReceivedTrust(a, db).getComment().equals("Bar")); - - // Check a's Score object - assertTrue(a.getScore(a, db).getScore() == 100); - assertTrue(a.getScore(a, db).getRank() == 0); - assertTrue(a.getScore(a, db).getCapacity() == 100); - - // Check B's Score object - assertTrue(b.getScore(a, db).getScore() == 50); - assertTrue(b.getScore(a, db).getRank() == 1); - assertTrue(b.getScore(a, db).getCapacity() == 40); - - // Empty the database - ObjectSet<Object> all = db.queryByExample(new Object()); - while(all.hasNext()) db.delete(all.next()); - } - - public void testRemoveTrust() throws MalformedURLException, InvalidParameterException, DuplicateScoreException, DuplicateTrustException, NotTrustedException, NotInTrustTreeException { - OwnIdentity a = new OwnIdentity(uriA, uriA, "A", "true"); - Identity b = new Identity(uriB, "B", "true"); - Identity c = new Identity(uriC, "C", "true"); - db.store(a); - db.store(b); - db.store(c); - a.initTrustTree(db); - a.setTrust(db, b, 100, "Foo"); - b.setTrust(db, c, 50, "Bar"); - - // Check we have the correct number of objects - assertTrue(OwnIdentity.getNbOwnIdentities(db) == 1); - assertTrue(Identity.getNbIdentities(db) == 2); - assertTrue(Trust.getNb(db) == 2); - assertTrue(Score.getNb(db) == 3); - - // Check a's Score object - assertTrue(a.getScore(a, db).getScore() == 100); - assertTrue(a.getScore(a, db).getRank() == 0); - assertTrue(a.getScore(a, db).getCapacity() == 100); - - // Check B's Score object - assertTrue(b.getScore(a, db).getScore() == 100); - assertTrue(b.getScore(a, db).getRank() == 1); - assertTrue(b.getScore(a, db).getCapacity() == 40); - - // Check C's Score object - assertTrue(c.getScore(a, db).getScore() == 20); - assertTrue(c.getScore(a, db).getRank() == 2); - assertTrue(c.getScore(a, db).getCapacity() == 16); - - a.setTrust(db, b, -1, "Bastard"); - - // Check we have the correct number of objects - assertTrue(OwnIdentity.getNbOwnIdentities(db) == 1); - assertTrue(Identity.getNbIdentities(db) == 2); - assertTrue(Trust.getNb(db) == 2); - assertTrue(Score.getNb(db) == 2); - - // Check a's Score object - assertTrue(a.getScore(a, db).getScore() == 100); - assertTrue(a.getScore(a, db).getRank() == 0); - assertTrue(a.getScore(a, db).getCapacity() == 100); - - // Check B's Score object - assertTrue(b.getScore(a, db).getScore() == -1); - assertTrue(b.getScore(a, db).getRank() == 1); - assertTrue(b.getScore(a, db).getCapacity() == 0); - - // C should not have a score anymore - try { - c.getScore(a, db); - fail(); - } - catch (NotInTrustTreeException e) {} - - // Empty the database - ObjectSet<Object> all = db.queryByExample(new Object()); - while(all.hasNext()) db.delete(all.next()); - } - - public void testTrustLoop() throws MalformedURLException, InvalidParameterException, DuplicateScoreException, DuplicateTrustException, NotInTrustTreeException { - OwnIdentity a = new OwnIdentity(uriA, uriA, "A", "true"); - Identity b = new Identity(uriB, "B", "true"); - Identity c = new Identity(uriC, "C", "true"); - db.store(a); - db.store(b); - db.store(c); - a.initTrustTree(db); - a.setTrust(db, b, 100, "Foo"); - b.setTrust(db, c, 50, "Bar"); - c.setTrust(db, a, 100, "Bleh"); - c.setTrust(db, b, 50, "Oops"); - - // Check we have the correct number of objects - assertTrue(OwnIdentity.getNbOwnIdentities(db) == 1); - assertTrue(Identity.getNbIdentities(db) == 2); - assertTrue(Trust.getNb(db) == 4); - assertTrue(Score.getNb(db) == 3); - - // Check a's Score object - assertTrue(a.getScore(a, db).getScore() == 100); - assertTrue(a.getScore(a, db).getRank() == 0); - assertTrue(a.getScore(a, db).getCapacity() == 100); - - // Check B's Score object - assertTrue(b.getScore(a, db).getScore() == 108); - assertTrue(b.getScore(a, db).getRank() == 1); - assertTrue(b.getScore(a, db).getCapacity() == 40); - - // Check C's Score object - assertTrue(c.getScore(a, db).getScore() == 20); - assertTrue(c.getScore(a, db).getRank() == 2); - assertTrue(c.getScore(a, db).getCapacity() == 16); - } - - public void testOwnIndentitiesTrust() throws MalformedURLException, InvalidParameterException, DuplicateScoreException, DuplicateTrustException, NotTrustedException, NotInTrustTreeException { - OwnIdentity a = new OwnIdentity(uriA, uriA, "A", "true"); - OwnIdentity b = new OwnIdentity(uriB, uriB, "B", "true"); - db.store(a); - db.store(b); - a.initTrustTree(db); - b.initTrustTree(db); - a.setTrust(db, b, 100, "Foo"); - b.setTrust(db, a, 100, "Bar"); - - // Check we have the correct number of objects - assertTrue(OwnIdentity.getNbOwnIdentities(db) == 2); - assertTrue(Identity.getNbIdentities(db) == 0); - assertTrue(Trust.getNb(db) == 2); - assertTrue(Score.getNb(db) == 4); - - // Check a's own Score object - assertTrue(a.getScore(a, db).getScore() == 100); - assertTrue(a.getScore(a, db).getRank() == 0); - assertTrue(a.getScore(a, db).getCapacity() == 100); - - // Check a's Score object - assertTrue(a.getScore(b, db).getScore() == 100); - assertTrue(a.getScore(b, db).getRank() == 1); - assertTrue(a.getScore(b, db).getCapacity() == 40); - - // Check B's own Score object - assertTrue(b.getScore(b, db).getScore() == 100); - assertTrue(b.getScore(b, db).getRank() == 0); - assertTrue(b.getScore(b, db).getCapacity() == 100); - - // Check B's Score object - assertTrue(b.getScore(a, db).getScore() == 100); - assertTrue(b.getScore(a, db).getRank() == 1); - assertTrue(b.getScore(a, db).getCapacity() == 40); - } -}
