code
stringlengths
3
1.18M
language
stringclasses
1 value
package de.mpg.mpiz.koeln.anna.serverimpl; import java.util.concurrent.Callable; import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher; import de.mpg.koeln.anna.core.events.StepStateChangeEvent; import de.mpg.mpiz.koeln.anna.server.Server; import de.mpg.mpiz.koeln.anna.step.AnnaStep; import de.mpg.mpiz.koeln.anna.step.ObservableStep; import de.mpg.mpiz.koeln.anna.step.ObservableStep.State; import de.mpg.mpiz.koeln.anna.step.common.StepExecutionException; import de.mpg.mpiz.koeln.anna.step.common.StepUtils; /** * * @author Alexander Kerner * @lastVisit 2009-09-22 * @thradSave custom * */ class AnnaSepExecutor implements Callable<Boolean> { private final AnnaStep step; private final LogDispatcher logger; private final EventHandler handler; AnnaSepExecutor(AnnaStep step, EventHandler handler, LogDispatcher logger) { this.step = step; this.logger = logger; this.handler = handler; } public Boolean call() throws Exception { boolean success = true; try { stepStateChanged(step, State.CHECK_NEED_TO_RUN); final boolean b = step.canBeSkipped(); if (b) { logger.info(this, "step " + step + " does not need to run, skipping"); stepStateChanged(step, State.SKIPPED); // success == true; return success; } logger.debug(this, "step " + step + " needs to run"); stepStateChanged(step, State.WAIT_FOR_REQ); synchronized (Server.class) { while (!step.requirementsSatisfied()) { logger.debug(this, "requirements for step " + step + " not satisfied, putting it to sleep"); Server.class.wait(); } logger.debug(this, "requirements for step " + step + " satisfied"); logger.debug(this, "notifying others"); Server.class.notifyAll(); } success = runStep(); stepFinished(success); } catch (Exception e) { logger.info(this, "executing step " + step + " was erroneous", e); stepStateChanged(step, State.ERROR); } return success; } private synchronized boolean runStep() throws StepExecutionException { logger.debug(this, "step " + step + "running"); stepStateChanged(step, State.RUNNING); return step.run(); } private synchronized void stepStateChanged(AnnaStep step, State state){ step.setState(state); handler.stepStateChanged(step); } private void stepFinished(boolean success) { logger.debug(this, "step " + step + "done running"); if (success) { stepStateChanged(step, State.DONE); } else { stepStateChanged(step, State.ERROR); } synchronized (Server.class) { logger.debug(this, "notifying others"); Server.class.notifyAll(); } } public String toString() { return this.getClass().getSimpleName() + ":" + step.getClass().getSimpleName(); } }
Java
package de.mpg.mpiz.koeln.anna.server; import de.mpg.mpiz.koeln.anna.step.ExecutableStep; /** * * @lastVisit 2009-09-22 * @author Alexander Kerner * */ public interface ExecutorServer extends Server { void registerStep(ExecutableStep step); void unregisterStep(ExecutableStep step); }
Java
package de.mpg.mpiz.koeln.anna.server; import java.util.EventListener; import de.mpg.koeln.anna.core.events.AnnaEvent; /** * * @lastVisit 2009-09-22 * @author Alexander Kerner * */ public interface AnnaEventListener extends EventListener { void eventOccoured(AnnaEvent event); }
Java
package de.mpg.mpiz.koeln.anna.server; /** * * @lastVisit 2009-09-22 * @author Alexander Kerner * */ public interface AnnaServer extends ExecutorServer { final static String PROPERTIES_KEY_PREFIX = "anna.server."; final static String WORKING_DIR_KEY = PROPERTIES_KEY_PREFIX + "workingdir"; }
Java
package de.mpg.mpiz.koeln.anna.server; import java.util.Properties; /** * * @lastVisit 2009-09-22 * @author Alexander Kerner * */ public interface Server { Properties getServerProperties(); void addEventListener(AnnaEventListener observer); void removeEventListener(AnnaEventListener observer); }
Java
package de.mpg.mpiz.koeln.anna.step; public interface AnnaStep extends ExecutableStep, ObservableStep { }
Java
package de.mpg.mpiz.koeln.anna.step; import java.util.Properties; import de.mpg.mpiz.koeln.anna.step.common.StepExecutionException; public interface ExecutableStep { boolean requirementsSatisfied() throws StepExecutionException; boolean canBeSkipped() throws StepExecutionException; boolean run() throws StepExecutionException; Properties getStepProperties(); boolean isCyclic(); }
Java
package de.mpg.mpiz.koeln.anna.step; public interface ObservableStep { public enum State { LOOSE, REGISTERED, CHECK_NEED_TO_RUN, WAIT_FOR_REQ, RUNNING, DONE, ERROR, SKIPPED } State getState(); void setState(State state); }
Java
package de.mpg.koeln.anna.core.events; import java.util.Collection; import de.mpg.mpiz.koeln.anna.step.AnnaStep; import de.mpg.mpiz.koeln.anna.step.ObservableStep.State; /** * * @lastVisit 2009-09-22 * @author Alexander Kerner * */ public class StepStateChangeEvent extends AnnaEvent { private static final long serialVersionUID = 4513665226131110643L; private final AnnaStep step; public StepStateChangeEvent(Object source, Collection<AnnaStep> steps, AnnaStep step) { super(source, steps); this.step = step; } public AnnaStep getStep() { return step; } public State getState() { return step.getState(); } @Override public String toString() { return new StringBuilder().append(super.toString()).append("[").append( "step").append("=").append(step).append("]").append("[").append( "state").append("=").append(step.getState()).append("]").toString(); } }
Java
package de.mpg.koeln.anna.core.events; import java.util.Collection; import java.util.EventObject; import java.util.HashSet; import java.util.Set; import de.mpg.mpiz.koeln.anna.step.AnnaStep; /** * * @lastVisit 2009-09-22 * @author Alexander Kerner * */ public class AnnaEvent extends EventObject { private static final long serialVersionUID = 1551843380559471696L; private final Set<AnnaStep> registeredSteps = new HashSet<AnnaStep>(); public AnnaEvent(Object source, Collection<? extends AnnaStep> registeredSteps) { super(source); this.registeredSteps.clear(); this.registeredSteps.addAll(registeredSteps); } public Collection<AnnaStep> getRegisteredSteps(){ return new HashSet<AnnaStep>(registeredSteps); } @Override public String toString() { return new StringBuilder().append("[").append( "stepReg").append("=").append(registeredSteps).append("]").toString(); } }
Java
package de.mpg.mpiz.koeln.anna.serverimpl; import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher; import de.mpg.mpiz.koeln.anna.step.AnnaStep; /** * * @author Alexander Kerner * @lastVisit 2009-09-22 * @thradSave custom * */ class ImmediateStepSheduler extends StepSheduler { ImmediateStepSheduler(AnnaStep step, EventHandler handler, LogDispatcher logger) { super(step, handler, logger); } public Void call() throws Exception { start(); return null; } }
Java
package de.mpg.mpiz.koeln.anna.serverimpl; import java.util.ArrayList; import java.util.Collection; import de.mpg.koeln.anna.core.events.AnnaEvent; import de.mpg.koeln.anna.core.events.StepStateChangeEvent; import de.mpg.mpiz.koeln.anna.server.AnnaEventListener; import de.mpg.mpiz.koeln.anna.step.AnnaStep; /** * <p> Simple helper class </p> * @threadSave all sync to this * @author Alexander Kerner * @lastVisit 2009-09-22 * */ class EventHandler { private final Collection<AnnaEventListener> observers = new ArrayList<AnnaEventListener>(); private final Collection<AnnaStep> registeredSteps; public EventHandler(Collection<AnnaStep> registeredSteps) { this.registeredSteps = registeredSteps; } public synchronized void stepStateChanged(AnnaStep step){ broadcastEvent(new StepStateChangeEvent(this, registeredSteps, step)); } private void broadcastEvent(AnnaEvent event) { if (observers.isEmpty()) return; for (AnnaEventListener l : observers) { l.eventOccoured(event); } } synchronized void addEventListener(AnnaEventListener observer) { observers.add(observer); } synchronized void removeEventListener(AnnaEventListener observer) { observers.remove(observer); } }
Java
package de.mpg.mpiz.koeln.anna.serverimpl; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher; import de.mpg.mpiz.koeln.anna.step.AnnaStep; /** * * @author Alexander Kerner * @lastVisit 2009-09-22 * */ public abstract class StepSheduler implements Callable<Void> { private final ExecutorService pool = Executors.newSingleThreadExecutor(); protected final AnnaStep step; protected final EventHandler handler; protected final LogDispatcher logger; protected volatile AnnaSepExecutor exe; StepSheduler(AnnaStep step, EventHandler handler, LogDispatcher logger) { this.step = step; this.handler = handler; this.logger = logger; this.exe = new AnnaSepExecutor(step, handler, logger); } @Override public String toString() { return this.getClass().getSimpleName() + ":" + exe.getClass().getSimpleName(); } public synchronized void start(){ pool.submit(exe); } }
Java
package de.mpg.mpiz.koeln.anna.serverimpl; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import de.kerner.commons.file.FileUtils; import de.mpg.mpiz.koeln.anna.server.AnnaEventListener; import de.mpg.mpiz.koeln.anna.server.AnnaServer; import de.mpg.mpiz.koeln.anna.step.AnnaStep; import de.mpg.mpiz.koeln.anna.step.ExecutableStep; import de.mpg.mpiz.koeln.anna.step.ObservableStep.State; /** * * @author Alexander Kerner * @lastVisit 2009-09-22 * @thradSave custom * */ public class AnnaServerImpl implements AnnaServer { // TODO path private final static File PROPERTIES_FILE = new File(FileUtils.WORKING_DIR, "configuration" + File.separatorChar + "server.properties"); private final Collection<AnnaStep> registeredSteps = new HashSet<AnnaStep>(); private final EventHandler handler; private final Properties properties; private final ExecutorService exe = Executors.newCachedThreadPool(); private final LogDispatcher logger; AnnaServerImpl(final LogDispatcher logger) { if (logger != null) this.logger = logger; else this.logger = new ConsoleLogger(); properties = getPropertes(); logger.debug(this, "loaded properties: " + properties); handler = new EventHandler(registeredSteps); handler.addEventListener(new NotifyOthersListener(logger)); } public synchronized void unregisterStep(ExecutableStep step) { // TODO Auto-generated method stub } public synchronized void registerStep(ExecutableStep step) { registeredSteps.add((AnnaStep) step); setStepState(step, State.REGISTERED); logger.debug(this, "registered step " + step); StepSheduler ss; if(step.isCyclic()){ ss = new CyclicStepSheduler((AnnaStep) step, handler, logger); } else { ss = new ImmediateStepSheduler((AnnaStep) step, handler, logger); } exe.submit(ss); } public synchronized Properties getServerProperties() { return new Properties(properties); } // handler threadsave public void addEventListener(AnnaEventListener observer) { handler.addEventListener(observer); } // handler threadsave public void removeEventListener(AnnaEventListener observer) { handler.removeEventListener(observer); } public String toString() { return this.getClass().getSimpleName(); } private synchronized Properties getPropertes() { final Properties defaultProperties = initDefaults(); final Properties pro = new Properties(defaultProperties); try { System.out.println(this + ": loading settings from " + PROPERTIES_FILE); final FileInputStream fi = new FileInputStream(PROPERTIES_FILE); pro.load(fi); fi.close(); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println(this + ": could not load settings from " + PROPERTIES_FILE.getAbsolutePath() + ", using defaults"); } catch (IOException e) { e.printStackTrace(); System.out.println(this + ": could not load settings from " + PROPERTIES_FILE.getAbsolutePath() + ", using defaults"); } return pro; } private Properties initDefaults() { Properties pro = new Properties(); // pro.setProperty(WORKING_DIR_KEY, WORKING_DIR_VALUE); return pro; } private void setStepState(ExecutableStep step, State state) { ((AnnaStep) step).setState(state); handler.stepStateChanged((AnnaStep) step); } }
Java
package de.mpg.mpiz.koeln.anna.serverimpl; import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher; import de.mpg.koeln.anna.core.events.AnnaEvent; import de.mpg.koeln.anna.core.events.StepStateChangeEvent; import de.mpg.mpiz.koeln.anna.server.AnnaEventListener; import de.mpg.mpiz.koeln.anna.step.AnnaStep; import de.mpg.mpiz.koeln.anna.step.ObservableStep; public class CyclicStepSheduler extends ImmediateStepSheduler implements AnnaEventListener { CyclicStepSheduler(AnnaStep step, EventHandler handler, LogDispatcher logger) { super(step, handler, logger); handler.addEventListener(this); } @Override public Void call() throws Exception { // do nothing until some other steps are done return null; } public void eventOccoured(AnnaEvent event) { if (event instanceof StepStateChangeEvent) { logger.debug(this, "received step state changed event " + event); final StepStateChangeEvent c = (StepStateChangeEvent) event; if (c.getStep().equals(step)) { logger.debug(this, "it was us, ignoring"); } else if (!(c.getStep().getState().equals( ObservableStep.State.DONE) || c.getStep().getState() .equals(ObservableStep.State.SKIPPED))) { logger.debug(this, "step state change was not to state " + ObservableStep.State.DONE + "/" + ObservableStep.State.SKIPPED + ", ignoring"); } else { logger.debug(this, "someone else finished, starting"); exe = new AnnaSepExecutor(step, handler, logger); start(); } } } }
Java
package de.mpg.mpiz.koeln.anna.serverimpl; import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher; import de.mpg.koeln.anna.core.events.AnnaEvent; import de.mpg.koeln.anna.core.events.StepStateChangeEvent; import de.mpg.mpiz.koeln.anna.server.AnnaEventListener; import de.mpg.mpiz.koeln.anna.step.ObservableStep.State; /** * <p> Helper class, to release lock when step finished.</p> * @author Alexander Kerner * */ class NotifyOthersListener implements AnnaEventListener { private final LogDispatcher logger; NotifyOthersListener(LogDispatcher logger) { this.logger = logger; } public void eventOccoured(AnnaEvent event) { if(event instanceof StepStateChangeEvent){ final State state = ((StepStateChangeEvent) event).getState(); // state "SKIPPED" not needed, because skipped steps never acquire lock if(state.equals(State.DONE) || state.equals(State.ERROR)){ synchronized (AnnaSepExecutor.LOCK) { logger.debug(this, "notifying others"); AnnaSepExecutor.LOCK.notifyAll(); } } else { // nothing } }else { // nothing } } @Override public String toString() { return this.getClass().getSimpleName(); } }
Java
package de.mpg.mpiz.koeln.anna.serverimpl; import java.util.Hashtable; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher; import de.kerner.osgi.commons.logger.dispatcher.LogDispatcherImpl; import de.mpg.mpiz.koeln.anna.server.AnnaServer; /** * @lastVisit 2009-09-18 * @author Alexander Kerner * */ public class AnnaServerActivator implements BundleActivator { private LogDispatcher logger = null; public void start(BundleContext context) throws Exception { logger = new LogDispatcherImpl(context); final AnnaServer service = new AnnaServerImpl(logger); context.registerService(AnnaServer.class.getName(), service, new Hashtable<Object, Object>()); logger.debug(this, "activated"); } public void stop(BundleContext context) throws Exception { // TODO method stub } public String toString() { return this.getClass().getSimpleName(); } }
Java
package de.mpg.mpiz.koeln.anna.serverimpl; import java.util.concurrent.Callable; import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher; import de.mpg.mpiz.koeln.anna.server.Server; import de.mpg.mpiz.koeln.anna.step.AnnaStep; import de.mpg.mpiz.koeln.anna.step.ObservableStep; import de.mpg.mpiz.koeln.anna.step.ObservableStep.State; import de.mpg.mpiz.koeln.anna.step.common.StepExecutionException; /** * * @author Alexander Kerner * @lastVisit 2009-09-22 * @thradSave custom * */ class AnnaSepExecutor implements Callable<Void> { public final static Object LOCK = Server.class; private final AnnaStep step; private final LogDispatcher logger; private final EventHandler handler; AnnaSepExecutor(AnnaStep step, EventHandler handler, LogDispatcher logger) { this.step = step; this.logger = logger; this.handler = handler; } public Void call() throws Exception { boolean success = true; stepStateChanged(State.CHECK_NEED_TO_RUN); final boolean b = step.canBeSkipped(); if (b) { logger.info(this, "step " + step + " does not need to run, skipping"); stepStateChanged(State.SKIPPED); stepFinished(success); return null; } logger.debug(this, "step " + step + " needs to run"); stepStateChanged(State.WAIT_FOR_REQ); synchronized (LOCK) { while (!step.requirementsSatisfied()) { logger.debug(this, "requirements for step " + step + " not satisfied, putting it to sleep"); LOCK.wait(); } logger.debug(this, "requirements for step " + step + " satisfied"); } try { success = runStep(); } catch (Exception e) { if (e instanceof StepExecutionException) { logger.warn(this, e.getLocalizedMessage(), e); } else { logger.error(this, e.getLocalizedMessage(), e); } stepStateChanged(State.ERROR); success = false; } stepFinished(success); return null; } private boolean runStep() throws StepExecutionException { logger.debug(this, "step " + step + " running"); stepStateChanged(State.RUNNING); return step.run(); } private void stepStateChanged(State state) { step.setState(state); handler.stepStateChanged(step); } private void stepFinished(boolean success) { logger.debug(this, "step " + step + " done running"); if (success && !(step.getState().equals(ObservableStep.State.SKIPPED))) { stepStateChanged(ObservableStep.State.DONE); } else if (!success && !(step.getState().equals(ObservableStep.State.SKIPPED))) { stepStateChanged(ObservableStep.State.ERROR); } } public String toString() { return this.getClass().getSimpleName() + ":" + step.getClass().getSimpleName(); } }
Java
package de.mpg.mpiz.koeln.anna.server; import de.mpg.mpiz.koeln.anna.step.ExecutableStep; /** * * @lastVisit 2009-09-22 * @author Alexander Kerner * */ public interface ExecutorServer extends Server { void registerStep(ExecutableStep step); void unregisterStep(ExecutableStep step); }
Java
package de.mpg.mpiz.koeln.anna.server; import java.util.EventListener; import de.mpg.koeln.anna.core.events.AnnaEvent; /** * * @lastVisit 2009-09-22 * @author Alexander Kerner * */ public interface AnnaEventListener extends EventListener { void eventOccoured(AnnaEvent event); }
Java
package de.mpg.mpiz.koeln.anna.server; /** * * @lastVisit 2009-09-22 * @author Alexander Kerner * */ public interface AnnaServer extends ExecutorServer { final static String PROPERTIES_KEY_PREFIX = "anna.server."; final static String WORKING_DIR_KEY = PROPERTIES_KEY_PREFIX + "workingdir"; }
Java
package de.mpg.mpiz.koeln.anna.server; import java.util.Properties; /** * * @lastVisit 2009-09-22 * @author Alexander Kerner * */ public interface Server { Properties getServerProperties(); // TODO: AnnaEventListener does not match this interface abstraction void addEventListener(AnnaEventListener observer); void removeEventListener(AnnaEventListener observer); }
Java
package de.mpg.mpiz.koeln.anna.step; public interface AnnaStep extends ExecutableStep, ObservableStep { }
Java
package de.mpg.mpiz.koeln.anna.step; import java.util.Properties; import de.mpg.mpiz.koeln.anna.step.common.StepExecutionException; public interface ExecutableStep { boolean requirementsSatisfied() throws StepExecutionException; boolean canBeSkipped() throws StepExecutionException; boolean run() throws StepExecutionException; Properties getStepProperties(); boolean isCyclic(); }
Java
package de.mpg.mpiz.koeln.anna.step; import java.util.List; public interface ObservableStep { public enum State { // non-finished steps LOOSE, REGISTERED, CHECK_NEED_TO_RUN, WAIT_FOR_REQ, RUNNING, // finished steps DONE, ERROR, SKIPPED; public boolean isFinished(){ switch (this) { case DONE: return true; case ERROR: return true; case SKIPPED: return true; default: return false; } } } State getState(); void setState(State state); List<String> requirementsNeeded(); }
Java
package de.mpg.mpiz.koeln.anna.step.common; import de.mpg.mpiz.koeln.anna.step.ExecutableStep; public class StepExecutionException extends Exception { private static final long serialVersionUID = 5683856650378220175L; private final ExecutableStep step; public StepExecutionException(ExecutableStep step) { this.step = step; } public StepExecutionException(ExecutableStep step, String arg0) { super(arg0); this.step = step; } public StepExecutionException(ExecutableStep step, Throwable arg0) { super(arg0); this.step = step; } public StepExecutionException(ExecutableStep step, String arg0, Throwable arg1) { super(arg0, arg1); this.step = step; } public ExecutableStep getStep(){ return step; } }
Java
package de.mpg.mpiz.koeln.anna.step.common; import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher; import de.mpg.mpiz.koeln.anna.step.ExecutableStep; /** * @lastVisit 2009-08-12 * @ThreadSave stateless * @author Alexander Kerner * @Exceptions good * */ public class StepUtils { private StepUtils() {} public static void handleException(ExecutableStep cause, Throwable t, LogDispatcher logger) throws StepExecutionException { if (logger == null) { handleException(cause, t); } else { // t.printStackTrace(); logger.error(cause, t.getLocalizedMessage(), t); throw new StepExecutionException(cause, t); } } public static void handleException(ExecutableStep cause, Throwable t) throws StepExecutionException { t.printStackTrace(); throw new StepExecutionException(cause, t); } }
Java
package de.mpg.mpiz.koeln.anna.server.data; public class DataBeanAccessException extends Exception { private static final long serialVersionUID = 4002480662305683330L; public DataBeanAccessException() { } public DataBeanAccessException(String arg0) { super(arg0); } public DataBeanAccessException(Throwable arg0) { super(arg0); } public DataBeanAccessException(String arg0, Throwable arg1) { super(arg0, arg1); } }
Java
package de.mpg.mpiz.koeln.anna.server.data; import java.io.Serializable; import java.util.ArrayList; import java.util.Map; import de.bioutils.fasta.FASTAElement; import de.bioutils.gff.element.NewGFFElement; public interface GFF3DataBean extends DataBean{ public ArrayList<FASTAElement> getInputSequence(); public void setInputSequence(ArrayList<FASTAElement> inputSequence); public ArrayList<FASTAElement> getVerifiedGenesFasta(); public void setVerifiedGenesFasta(ArrayList<FASTAElement> verifiedGenesFasta); public ArrayList<NewGFFElement> getVerifiedGenesGFF(); public void setVerifiedGenesGFF(ArrayList<NewGFFElement> verifiedGenesGFF); public ArrayList<NewGFFElement> getPredictedGenesGFF(); public void setPredictedGenesGFF(ArrayList<NewGFFElement> predictedGenesGFF); public ArrayList<NewGFFElement> getRepeatMaskerGFF(); public void setRepeatMaskerGFF(ArrayList<NewGFFElement> repeatMaskerGFF); public Map<String, Serializable> getCustom(); public void setCustom(Map<String, Serializable> custom); }
Java
package de.mpg.mpiz.koeln.anna.server.data.impl; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import de.bioutils.fasta.FASTAElement; import de.bioutils.gff.element.NewGFFElement; import de.mpg.mpiz.koeln.anna.server.data.GFF3DataBean; public class GFF3DataBeanImpl implements GFF3DataBean { private static final long serialVersionUID = -8241571899555002582L; private ArrayList<FASTAElement> inputSequence = new ArrayList<FASTAElement>(); private ArrayList<FASTAElement> verifiedGenesFasta = new ArrayList<FASTAElement>(); private ArrayList<NewGFFElement> verifiedGenesGFF = new ArrayList<NewGFFElement>(); private ArrayList<NewGFFElement> predictedGenesGFF = new ArrayList<NewGFFElement>(); private ArrayList<NewGFFElement> repeatMaskerGFF = new ArrayList<NewGFFElement>(); private Map<String, Serializable> custom = new HashMap<String, Serializable>(); public ArrayList<FASTAElement> getInputSequence() { return inputSequence; } public void setInputSequence(ArrayList<FASTAElement> inputSequence) { this.inputSequence = inputSequence; } public ArrayList<FASTAElement> getVerifiedGenesFasta() { return verifiedGenesFasta; } public void setVerifiedGenesFasta(ArrayList<FASTAElement> verifiedGenesFasta) { this.verifiedGenesFasta = verifiedGenesFasta; } public ArrayList<NewGFFElement> getVerifiedGenesGFF() { return verifiedGenesGFF; } public void setVerifiedGenesGFF(ArrayList<NewGFFElement> verifiedGenesGFF) { this.verifiedGenesGFF = verifiedGenesGFF; } public ArrayList<NewGFFElement> getPredictedGenesGFF() { return predictedGenesGFF; } public void setPredictedGenesGFF(ArrayList<NewGFFElement> predictedGenesGFF) { this.predictedGenesGFF = predictedGenesGFF; } public ArrayList<NewGFFElement> getRepeatMaskerGFF() { return repeatMaskerGFF; } public void setRepeatMaskerGFF(ArrayList<NewGFFElement> repeatMaskerGFF) { this.repeatMaskerGFF = repeatMaskerGFF; } public Map<String, Serializable> getCustom() { return custom; } public void setCustom(Map<String, Serializable> custom) { this.custom = custom; } @Override public String toString(){ return this.getClass().getSimpleName(); } }
Java
package de.mpg.mpiz.koeln.anna.server.data; import java.io.Serializable; import java.util.Map; public interface DataBean extends Serializable { public Map<String, Serializable> getCustom(); public void setCustom(Map<String, Serializable> custom); }
Java
package de.mpg.mpiz.koeln.anna.server.data; public interface DataModifier<V> { void modifiyData(V v); }
Java
package de.mpg.mpiz.koeln.anna.server.data; import de.mpg.mpiz.koeln.anna.data.DataBeanAccessException; // TODO: should be <V extends DataBean> public interface DataProxy<V> { /** * * <p> * Atomar operation on data. Data will be synchronized bevor and after this * operation. * </p> * * @param v * Type of Data, that is accessed. * @throws DataBeanAccessException */ void modifiyData(DataModifier<V> v) throws DataBeanAccessException; /** * * <p> * Use this method for reading data only. If you make changes to the data * you get from this method, these changes will not be updated! If you * want to write data, use {@link modifiyData()} instead. * * @return the data object. * @throws DataBeanAccessException */ V viewData() throws DataBeanAccessException; }
Java
package de.mpg.mpiz.koeln.anna.server.data.impl; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.io.StreamCorruptedException; import de.kerner.commons.logging.Log; import de.mpg.mpiz.koeln.anna.data.DataBean; import de.mpg.mpiz.koeln.anna.data.DataBeanAccessException; /** * * @author Alexander Kerner * @lastVisit 2009-09-21 * */ abstract class AbstractDiskSerialisation implements SerialisationStrategy { private final static Log logger = new Log(AbstractDiskSerialisation.class); protected void objectToFile(Serializable s, File file) throws IOException { if (s == null || file == null) throw new NullPointerException(s + " + " + file + " must not be null"); OutputStream fos = null; ObjectOutputStream outStream = null; try { fos = new FileOutputStream(file); outStream = new ObjectOutputStream(fos); outStream.writeObject(s); } finally { if (outStream != null) outStream.close(); if (fos != null) fos.close(); } } protected <V> V fileToObject(Class<V> c, File file) throws IOException, ClassNotFoundException { if (c == null || file == null) throw new NullPointerException(c + " + " + file + " must not be null"); InputStream fis = null; ObjectInputStream inStream = null; try { fis = new FileInputStream(file); inStream = new ObjectInputStream(fis); V v = c.cast(inStream.readObject()); return v; } finally { if (inStream != null) inStream.close(); if (fis != null) fis.close(); } } protected <V extends DataBean> V handleCorruptData(File file) { logger.warn(file.toString() + " corrupt, returning new one"); try{ if (file.delete()) { logger.info("deleted corrupted data"); } else { logger.warn("could not delete corrupt data " + file); }}catch(Throwable t){ logger.debug("ignoring \"" + t.getLocalizedMessage() + "\"", t); } return getNewDataBean(); } public synchronized <V extends DataBean> V readDataBean(File file, Class<V> v) throws DataBeanAccessException { try { final V data = fileToObject(v, file); logger.debug("reading data from file"); return data; } catch (EOFException e) { logger.warn(e.getLocalizedMessage(), e); return handleCorruptData(file); } catch (StreamCorruptedException e) { logger.warn(e.getLocalizedMessage(), e); return handleCorruptData(file); } catch (IOException e) { logger.warn(e.getLocalizedMessage(), e); return handleCorruptData(file); } catch (Throwable t) { logger.error(t.getLocalizedMessage(), t); throw new DataBeanAccessException(t); } } public synchronized <V extends DataBean> void writeDataBean(V v, File file) throws DataBeanAccessException { try { logger.debug("writing data to file"); objectToFile(v, file); } catch (IOException e) { logger.error(e.toString(), e); throw new DataBeanAccessException(e); } } }
Java
package de.mpg.mpiz.koeln.anna.server.data.impl; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import de.kerner.commons.file.FileUtils; import de.kerner.commons.logging.Log; import de.mpg.mpiz.koeln.anna.data.DataBeanAccessException; import de.mpg.mpiz.koeln.anna.data.GFF3DataBean; import de.mpg.mpiz.koeln.anna.server.data.DataModifier; import de.mpg.mpiz.koeln.anna.server.data.GFF3DataProxy; /** * * @author Alexander Kerner * @lastVisit 2009-09-21 * */ public class GFF3DataProxyImpl implements GFF3DataProxy{ private final Log logger = new Log(GFF3DataProxyImpl.class); final static String WORKING_DIR_KEY = "anna.server.data.workingDir"; final static File PROPERTIES_FILE = new File(FileUtils.WORKING_DIR, "configuration" + File.separatorChar + "data.properties"); final static String DATA_FILE_NAME = "data.ser"; private final SerialisationStrategy strategy; private final Properties properties; private final File workingDir; private final File file; public GFF3DataProxyImpl(final SerialisationStrategy strategy) throws FileNotFoundException { this.strategy = strategy; properties = getPropertes(); workingDir = new File(properties.getProperty(WORKING_DIR_KEY)); if(!FileUtils.dirCheck(workingDir, true)){ final FileNotFoundException e = new FileNotFoundException("cannot access working dir " + workingDir); logger.error(e.getLocalizedMessage(), e); throw e; } file = new File(workingDir, DATA_FILE_NAME); printProperties(); } public GFF3DataProxyImpl() throws FileNotFoundException { this.strategy = new CachedDiskSerialisation(); properties = getPropertes(); workingDir = new File(properties.getProperty(WORKING_DIR_KEY)); if(!FileUtils.dirCheck(workingDir, true)){ final FileNotFoundException e = new FileNotFoundException("cannot access working dir " + workingDir); logger.error(e.getLocalizedMessage(), e); throw e; } file = new File(workingDir, DATA_FILE_NAME); printProperties(); } private GFF3DataBean getData() throws DataBeanAccessException { if(!FileUtils.fileCheck(file, false)){ logger.debug("file " + file + " not there, creating new data"); return strategy.getNewDataBean(); } return strategy.readDataBean(file, GFF3DataBean.class); } private void setData(GFF3DataBean data) throws DataBeanAccessException { strategy.writeDataBean(data, file); } public synchronized void modifiyData(DataModifier<GFF3DataBean> v) throws DataBeanAccessException { final GFF3DataBean data = getData(); v.modifiyData(data); setData(data); } public GFF3DataBean viewData() throws DataBeanAccessException { return getData(); } @Override public String toString() { return this.getClass().getSimpleName(); } private void printProperties() { logger.debug("created, properties:"); logger.debug("\tdatafile=" + file); } private Properties getPropertes() { final Properties defaultProperties = initDefaults(); final Properties pro = new Properties(defaultProperties); try { logger.debug("loading settings from " + PROPERTIES_FILE); final FileInputStream fi = new FileInputStream(PROPERTIES_FILE); pro.load(fi); fi.close(); } catch (FileNotFoundException e) { e.printStackTrace(); logger.warn("could not load settings from " + PROPERTIES_FILE.getAbsolutePath() + ", using defaults"); } catch (IOException e) { e.printStackTrace(); logger.warn("could not load settings from " + PROPERTIES_FILE.getAbsolutePath() + ", using defaults"); } return pro; } private Properties initDefaults() { Properties pro = new Properties(); return pro; } }
Java
package de.mpg.mpiz.koeln.anna.server.data.impl; import de.mpg.mpiz.koeln.anna.data.DataBean; import de.mpg.mpiz.koeln.anna.data.impl.GFF3DataBeanImpl; public class GFF3DiskSerialisation extends AbstractDiskSerialisation { protected volatile DataBean data = new GFF3DataBeanImpl(); @SuppressWarnings("unchecked") public <V extends DataBean> V getNewDataBean() { return (V) new GFF3DataBeanImpl(); } }
Java
package de.mpg.mpiz.koeln.anna.server.data.impl; public class SimpleDiskSerialisation extends GFF3DiskSerialisation { @Override public String toString() { return this.getClass().getSimpleName(); } }
Java
package de.mpg.mpiz.koeln.anna.server.data.impl; import java.util.Hashtable; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import de.kerner.commons.logging.Log; import de.mpg.mpiz.koeln.anna.server.data.GFF3DataProxy; /** * * @author Alexander Kerner * @lastVisit 2009-11-12 * */ public class GFF3DataProxyActivator implements BundleActivator { private final static Log logger = new Log(GFF3DataProxyActivator.class); public void start(BundleContext context) throws Exception { GFF3DataProxy proxy = new GFF3DataProxyImpl(new CachedDiskSerialisation()); context.registerService(GFF3DataProxy.class.getName(), proxy, new Hashtable<Object, Object>()); } public void stop(BundleContext context) throws Exception { logger.debug("stopping. (TODO implement)"); // TODO implement } public String toString() { return this.getClass().getSimpleName(); } }
Java
package de.mpg.mpiz.koeln.anna.server.data.impl; import java.io.File; import de.mpg.mpiz.koeln.anna.data.DataBean; import de.mpg.mpiz.koeln.anna.data.DataBeanAccessException; /** * * @author Alexander Kerner * @lastVisit 2009-09-21 * */ interface SerialisationStrategy { <V extends DataBean> V readDataBean(File file, Class<V> v) throws DataBeanAccessException; <V extends DataBean> void writeDataBean(V v, File file) throws DataBeanAccessException; <V extends DataBean> V getNewDataBean(); }
Java
package de.mpg.mpiz.koeln.anna.server.data.impl; import java.io.File; import de.kerner.commons.file.FileUtils; import de.kerner.commons.logging.Log; import de.mpg.mpiz.koeln.anna.data.DataBean; import de.mpg.mpiz.koeln.anna.data.DataBeanAccessException; import de.mpg.mpiz.koeln.anna.data.impl.GFF3DataBeanImpl; /** * * @author Alexander Kerner * @lastVisit 2009-09-21 * @threadSave no need to synchronize (data is volatile), methods from "super" * already are threadsave. * */ class CachedDiskSerialisation extends GFF3DiskSerialisation { private final Log logger = new Log(CachedDiskSerialisation.class); private volatile boolean dirty = true; @SuppressWarnings("unchecked") @Override public <V extends DataBean> V readDataBean(File file, Class<V> v) throws DataBeanAccessException { if (FileUtils.fileCheck(file, true)) ; if (dirty) { logger.debug("data dirty, reading from disk"); data = super.readDataBean(file, v); dirty = false; } else { logger.debug("reading data from cache"); } return (V) data; } public <V extends DataBean> void writeDataBean(V v, File file) throws DataBeanAccessException { try { super.writeDataBean(v, file); } finally { this.dirty = true; } } protected <V extends DataBean> V handleCorruptData(File file) { dirty = true; data = new GFF3DataBeanImpl(); return super.handleCorruptData(file); } @Override public String toString() { return this.getClass().getSimpleName(); } }
Java
package de.mpg.mpiz.koeln.anna.server.data; import de.mpg.mpiz.koeln.anna.data.GFF3DataBean; public interface GFF3DataProxy extends DataProxy<GFF3DataBean>{ }
Java
package de.mpg.mpiz.koeln.anna.listener.abstractlistener; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher; import de.kerner.osgi.commons.logger.dispatcher.LogDispatcherImpl; import de.kerner.osgi.commons.utils.ServiceRetriever; import de.kerner.osgi.commons.utils.ServiceRetrieverImpl; import de.mpg.mpiz.koeln.anna.server.AnnaEventListener; import de.mpg.mpiz.koeln.anna.server.AnnaServer; public abstract class AbstractEventListener implements BundleActivator, AnnaEventListener { private volatile ServiceRetriever<AnnaServer> retriever; protected LogDispatcher logger; public void start(BundleContext context) throws Exception { this.retriever = new ServiceRetrieverImpl<AnnaServer>(context, AnnaServer.class); AnnaServer s = retriever.getService(); s.addEventListener(this); logger = new LogDispatcherImpl(context); } public void stop(BundleContext context) throws Exception { retriever = null; logger = null; } }
Java
package de.mpg.mpiz.koeln.anna.listener.abstractlistener; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import de.kerner.commons.osgi.utils.ServiceNotAvailabeException; import de.kerner.commons.osgi.utils.ServiceRetriever; import de.kerner.commons.osgi.utils.ServiceRetrieverImpl; import de.mpg.mpiz.koeln.anna.core.events.AnnaEventListener; import de.mpg.mpiz.koeln.anna.server.AnnaServer; public abstract class AbstractEventListener implements BundleActivator, AnnaEventListener { private volatile ServiceRetriever<AnnaServer> retriever; public void start(BundleContext context) throws Exception { this.retriever = new ServiceRetrieverImpl<AnnaServer>(context, AnnaServer.class); AnnaServer s = retriever.getService(); s.addEventListener(this); } public void stop(BundleContext context) throws Exception { retriever = null; } public AnnaServer getServer() throws ServiceNotAvailabeException { return retriever.getService(); } }
Java
package de.mpg.mpiz.koeln.anna.data; /** * * @author Alexander Kerner * @lastVisit 2009-11-12 * */ public class DataBeanAccessException extends Exception { private static final long serialVersionUID = 4002480662305683330L; public DataBeanAccessException() { } public DataBeanAccessException(String arg0) { super(arg0); } public DataBeanAccessException(Throwable arg0) { super(arg0); } public DataBeanAccessException(String arg0, Throwable arg1) { super(arg0, arg1); } }
Java
package de.mpg.mpiz.koeln.anna.data; import java.io.Serializable; /** * * @author Alexander Kerner * @lastVisit 2009-11-12 * */ public interface DataBean extends Serializable { public Serializable getCustom(String ident); public void addCustom(String ident, Serializable custom); }
Java
package de.mpg.mpiz.koeln.anna.step.exonerate.common; public class ExonerateConstants { private ExonerateConstants(){} public final static String WORKING_DIR_KEY = "anna.step.exonerate.workingDir"; public final static String EXE_DIR_KEY = "anna.step.exonerate.exeDir"; public final static String EXE = "exonerate"; public static final String EST_FILENAME = "ests.fasta"; public static final String INSEQ_FILENAME = "inputsequence.fasta"; public static final String RESULT_FILENAME = "exonerate-result.gff"; }
Java
package de.mpg.mpiz.koeln.anna.step.exonerate.common; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.osgi.framework.BundleContext; import de.bioutils.fasta.FASTAElementGroup; import de.bioutils.fasta.NewFASTAFileImpl; import de.bioutils.gff.GFFFormatErrorException; import de.bioutils.gff.file.NewGFFFile; import de.bioutils.gff.file.NewGFFFileImpl; import de.bioutils.gff3.GFF3Utils; import de.bioutils.gff3.Type; import de.bioutils.gff3.converter.GFF3FileExtender; import de.bioutils.gff3.element.GFF3Element; import de.bioutils.gff3.element.GFF3ElementBuilder; import de.bioutils.gff3.element.GFF3ElementGroup; import de.bioutils.gff3.element.GFF3ElementGroupImpl; import de.bioutils.gff3.file.GFF3File; import de.bioutils.gff3.file.GFF3FileImpl; import de.kerner.commons.StringUtils; import de.kerner.commons.file.FileUtils; import de.kerner.commons.osgi.utils.ServiceNotAvailabeException; import de.mpg.mpiz.koeln.anna.abstractstep.AbstractGFF3WrapperStep; import de.mpg.mpiz.koeln.anna.core.AnnaConstants; import de.mpg.mpiz.koeln.anna.data.DataBeanAccessException; import de.mpg.mpiz.koeln.anna.data.GFF3DataBean; import de.mpg.mpiz.koeln.anna.server.data.DataModifier; import de.mpg.mpiz.koeln.anna.server.data.DataProxy; import de.mpg.mpiz.koeln.anna.step.StepExecutionException; public abstract class AbstractStepExonerate extends AbstractGFF3WrapperStep { private final class DataAdapter implements GFF3FileExtender { public GFF3File extend(GFF3File gff3File) { // TODO really sorted?? final GFF3ElementGroup g = new GFF3ElementGroupImpl(true); for (GFF3Element e : gff3File.getElements()) { final String source = e.getSource(); final String sourceNew = source.replaceAll(":", ""); // logger.debug("changing source identifier from \"" + source // + "\" to \"" + sourceNew + "\""); g.add(new GFF3ElementBuilder(e).setSource(sourceNew).setType( Type.EST).setSource(AnnaConstants.IDENT).build()); } return new GFF3FileImpl(g); } } @Override protected void init(BundleContext context) throws StepExecutionException { super.init(context); exeDir = new File(getStepProperties().getProperty( ExonerateConstants.EXE_DIR_KEY)); workingDir = new File(getStepProperties().getProperty( ExonerateConstants.WORKING_DIR_KEY)); logger.debug("exeDir=" + exeDir.getAbsolutePath()); logger.debug("workingDir=" + workingDir.getAbsolutePath()); } public void prepare(DataProxy<GFF3DataBean> data) throws Exception { createInputFile(data); createESTFasta(data); } // workingDir volatile private void createESTFasta(DataProxy<GFF3DataBean> data) throws DataBeanAccessException, ServiceNotAvailabeException, IOException { final FASTAElementGroup ests = data.viewData().getESTs(); final File f2 = new File(workingDir, ExonerateConstants.EST_FILENAME); new NewFASTAFileImpl(ests).write(f2); logger.debug("created tmp file for est fasta: " + f2.getAbsolutePath()); } // workingDir volatile private void createInputFile(DataProxy<GFF3DataBean> data) throws Exception { final FASTAElementGroup inFastas = data.viewData().getInputSequence(); final File f1 = new File(workingDir, ExonerateConstants.INSEQ_FILENAME); new NewFASTAFileImpl(inFastas).write(f1); logger.debug("created tmp file input sequence(s): " + f1.getAbsolutePath()); } // workingDir volatile public void update(DataProxy<GFF3DataBean> data) throws Throwable { // TODO really sorted?? GFF3File file = GFF3Utils.convertFromGFFFile(new File(workingDir, ExonerateConstants.RESULT_FILENAME), true); file = new DataAdapter().extend(file); final GFF3ElementGroup result = file.getElements(); data.modifiyData(new DataModifier<GFF3DataBean>() { public void modifiyData(GFF3DataBean v) { v.setMappedESTs(new GFF3ElementGroupImpl(result)); } }); } public boolean run(DataProxy<GFF3DataBean> proxy) throws Throwable { logger.debug("starting"); final File file = new File(workingDir, ExonerateConstants.RESULT_FILENAME); if (FileUtils.fileCheck(file, false) && outFileIsValid(file)) { super.addShortCutFile(file); } else { logger.debug(file + " is not there or invalid, will not do shortcut"); } redirectOutStreamToFile(file); addResultFileToWaitFor(file); return start(); } private boolean outFileIsValid(File file) throws IOException, GFFFormatErrorException { NewGFFFile gff; gff = NewGFFFileImpl.parseFile(file); // TODO: size == 0 does not really indicate an invalid file if (gff.getElements() == null || gff.getElements().size() == 0) return false; return true; } public boolean isCyclic() { return false; } public boolean canBeSkipped(DataProxy<GFF3DataBean> data) throws Throwable { final boolean b = (data.viewData().getMappedESTs() != null && data .viewData().getMappedESTs().getSize() != 0); logger.debug(StringUtils.getString("need to run: ests=", b)); return b; } @Override public List<String> requirementsNeeded(DataProxy<GFF3DataBean> data) throws Exception { final List<String> r = new ArrayList<String>(); final boolean ests = (data.viewData().getESTs() != null && (data .viewData().getESTs().asList().size() != 0)); final boolean inseq = (data.viewData().getInputSequence() != null && data .viewData().getInputSequence().asList().size() != 0); if (!ests) { r.add("EST sequences"); } if (!inseq) { r.add("input sequence(s)"); } return r; } public boolean requirementsSatisfied(DataProxy<GFF3DataBean> data) throws Throwable { final boolean ests = (data.viewData().getESTs() != null && (data .viewData().getESTs().asList().size() != 0)); final boolean inseq = (data.viewData().getInputSequence() != null && data .viewData().getInputSequence().asList().size() != 0); logger.debug(StringUtils.getString("requirements: ests=", ests)); logger.debug(StringUtils.getString("requirements: inseq=", inseq)); return (ests && inseq); } @Override public String toString() { return this.getClass().getSimpleName(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.ERROR_SERVICE_NOT_AVAILABLE; import static com.google.android.gcm.GCMConstants.EXTRA_ERROR; import static com.google.android.gcm.GCMConstants.EXTRA_REGISTRATION_ID; import static com.google.android.gcm.GCMConstants.EXTRA_SPECIAL_MESSAGE; import static com.google.android.gcm.GCMConstants.EXTRA_TOTAL_DELETED; import static com.google.android.gcm.GCMConstants.EXTRA_UNREGISTERED; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_MESSAGE; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK; import static com.google.android.gcm.GCMConstants.VALUE_DELETED_MESSAGES; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import java.util.Random; import java.util.concurrent.TimeUnit; /** * Skeleton for application-specific {@link IntentService}s responsible for * handling communication from Google Cloud Messaging service. * <p> * The abstract methods in this class are called from its worker thread, and * hence should run in a limited amount of time. If they execute long * operations, they should spawn new threads, otherwise the worker thread will * be blocked. * <p> * Subclasses must provide a public no-arg constructor. */ public abstract class GCMBaseIntentService extends IntentService { public static final String TAG = "GCMBaseIntentService"; // wakelock private static final String WAKELOCK_KEY = "GCM_LIB"; private static PowerManager.WakeLock sWakeLock; // Java lock used to synchronize access to sWakelock private static final Object LOCK = GCMBaseIntentService.class; private final String[] mSenderIds; // instance counter private static int sCounter = 0; private static final Random sRandom = new Random(); private static final int MAX_BACKOFF_MS = (int) TimeUnit.SECONDS.toMillis(3600); // 1 hour // token used to check intent origin private static final String TOKEN = Long.toBinaryString(sRandom.nextLong()); private static final String EXTRA_TOKEN = "token"; /** * Constructor that does not set a sender id, useful when the sender id * is context-specific. * <p> * When using this constructor, the subclass <strong>must</strong> * override {@link #getSenderIds(Context)}, otherwise methods such as * {@link #onHandleIntent(Intent)} will throw an * {@link IllegalStateException} on runtime. */ protected GCMBaseIntentService() { this(getName("DynamicSenderIds"), null); } /** * Constructor used when the sender id(s) is fixed. */ protected GCMBaseIntentService(String... senderIds) { this(getName(senderIds), senderIds); } private GCMBaseIntentService(String name, String[] senderIds) { super(name); // name is used as base name for threads, etc. mSenderIds = senderIds; } private static String getName(String senderId) { String name = "GCMIntentService-" + senderId + "-" + (++sCounter); Log.v(TAG, "Intent service name: " + name); return name; } private static String getName(String[] senderIds) { String flatSenderIds = GCMRegistrar.getFlatSenderIds(senderIds); return getName(flatSenderIds); } /** * Gets the sender ids. * * <p>By default, it returns the sender ids passed in the constructor, but * it could be overridden to provide a dynamic sender id. * * @throws IllegalStateException if sender id was not set on constructor. */ protected String[] getSenderIds(Context context) { if (mSenderIds == null) { throw new IllegalStateException("sender id not set on constructor"); } return mSenderIds; } /** * Called when a cloud message has been received. * * @param context application's context. * @param intent intent containing the message payload as extras. */ protected abstract void onMessage(Context context, Intent intent); /** * Called when the GCM server tells pending messages have been deleted * because the device was idle. * * @param context application's context. * @param total total number of collapsed messages */ protected void onDeletedMessages(Context context, int total) { } /** * Called on a registration error that could be retried. * * <p>By default, it does nothing and returns {@literal true}, but could be * overridden to change that behavior and/or display the error. * * @param context application's context. * @param errorId error id returned by the GCM service. * * @return if {@literal true}, failed operation will be retried (using * exponential backoff). */ protected boolean onRecoverableError(Context context, String errorId) { return true; } /** * Called on registration or unregistration error. * * @param context application's context. * @param errorId error id returned by the GCM service. */ protected abstract void onError(Context context, String errorId); /** * Called after a device has been registered. * * @param context application's context. * @param registrationId the registration id returned by the GCM service. */ protected abstract void onRegistered(Context context, String registrationId); /** * Called after a device has been unregistered. * * @param registrationId the registration id that was previously registered. * @param context application's context. */ protected abstract void onUnregistered(Context context, String registrationId); @Override public final void onHandleIntent(Intent intent) { try { Context context = getApplicationContext(); String action = intent.getAction(); if (action.equals(INTENT_FROM_GCM_REGISTRATION_CALLBACK)) { GCMRegistrar.setRetryBroadcastReceiver(context); handleRegistration(context, intent); } else if (action.equals(INTENT_FROM_GCM_MESSAGE)) { // checks for special messages String messageType = intent.getStringExtra(EXTRA_SPECIAL_MESSAGE); if (messageType != null) { if (messageType.equals(VALUE_DELETED_MESSAGES)) { String sTotal = intent.getStringExtra(EXTRA_TOTAL_DELETED); if (sTotal != null) { try { int total = Integer.parseInt(sTotal); Log.v(TAG, "Received deleted messages " + "notification: " + total); onDeletedMessages(context, total); } catch (NumberFormatException e) { Log.e(TAG, "GCM returned invalid number of " + "deleted messages: " + sTotal); } } } else { // application is not using the latest GCM library Log.e(TAG, "Received unknown special message: " + messageType); } } else { onMessage(context, intent); } } else if (action.equals(INTENT_FROM_GCM_LIBRARY_RETRY)) { String token = intent.getStringExtra(EXTRA_TOKEN); if (!TOKEN.equals(token)) { // make sure intent was generated by this class, not by a // malicious app. Log.e(TAG, "Received invalid token: " + token); return; } // retry last call if (GCMRegistrar.isRegistered(context)) { GCMRegistrar.internalUnregister(context); } else { String[] senderIds = getSenderIds(context); GCMRegistrar.internalRegister(context, senderIds); } } } finally { // Release the power lock, so phone can get back to sleep. // The lock is reference-counted by default, so multiple // messages are ok. // If onMessage() needs to spawn a thread or do something else, // it should use its own lock. synchronized (LOCK) { // sanity check for null as this is a public method if (sWakeLock != null) { sWakeLock.release(); } else { // should never happen during normal workflow Log.e(TAG, "Wakelock reference is null"); } } } } /** * Called from the broadcast receiver. * <p> * Will process the received intent, call handleMessage(), registered(), * etc. in background threads, with a wake lock, while keeping the service * alive. */ static void runIntentInService(Context context, Intent intent, String className) { synchronized (LOCK) { if (sWakeLock == null) { // This is called from BroadcastReceiver, there is no init. PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY); } } sWakeLock.acquire(); intent.setClassName(context, className); context.startService(intent); } private void handleRegistration(final Context context, Intent intent) { GCMRegistrar.cancelAppPendingIntent(); String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID); String error = intent.getStringExtra(EXTRA_ERROR); String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED); Log.d(TAG, "handleRegistration: registrationId = " + registrationId + ", error = " + error + ", unregistered = " + unregistered); // registration succeeded if (registrationId != null) { GCMRegistrar.resetBackoff(context); GCMRegistrar.setRegistrationId(context, registrationId); onRegistered(context, registrationId); return; } // unregistration succeeded if (unregistered != null) { // Remember we are unregistered GCMRegistrar.resetBackoff(context); String oldRegistrationId = GCMRegistrar.clearRegistrationId(context); onUnregistered(context, oldRegistrationId); return; } // last operation (registration or unregistration) returned an error; Log.d(TAG, "Registration error: " + error); // Registration failed if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) { boolean retry = onRecoverableError(context, error); if (retry) { int backoffTimeMs = GCMRegistrar.getBackoff(context); int nextAttempt = backoffTimeMs / 2 + sRandom.nextInt(backoffTimeMs); Log.d(TAG, "Scheduling registration retry, backoff = " + nextAttempt + " (" + backoffTimeMs + ")"); Intent retryIntent = new Intent(INTENT_FROM_GCM_LIBRARY_RETRY); retryIntent.putExtra(EXTRA_TOKEN, TOKEN); PendingIntent retryPendingIntent = PendingIntent .getBroadcast(context, 0, retryIntent, 0); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + nextAttempt, retryPendingIntent); // Next retry should wait longer. if (backoffTimeMs < MAX_BACKOFF_MS) { GCMRegistrar.setBackoff(context, backoffTimeMs * 2); } } else { Log.d(TAG, "Not retrying failed operation"); } } else { // Unrecoverable error, notify app onError(context, error); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.os.Build; import android.util.Log; import java.sql.Timestamp; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Utilities for device registration. * <p> * <strong>Note:</strong> this class uses a private {@link SharedPreferences} * object to keep track of the registration token. */ public final class GCMRegistrar { /** * Default lifespan (7 days) of the {@link #isRegisteredOnServer(Context)} * flag until it is considered expired. */ // NOTE: cannot use TimeUnit.DAYS because it's not available on API Level 8 public static final long DEFAULT_ON_SERVER_LIFESPAN_MS = 1000 * 3600 * 24 * 7; private static final String TAG = "GCMRegistrar"; private static final String BACKOFF_MS = "backoff_ms"; private static final String GSF_PACKAGE = "com.google.android.gsf"; private static final String PREFERENCES = "com.google.android.gcm"; private static final int DEFAULT_BACKOFF_MS = 3000; private static final String PROPERTY_REG_ID = "regId"; private static final String PROPERTY_APP_VERSION = "appVersion"; private static final String PROPERTY_ON_SERVER = "onServer"; private static final String PROPERTY_ON_SERVER_EXPIRATION_TIME = "onServerExpirationTime"; private static final String PROPERTY_ON_SERVER_LIFESPAN = "onServerLifeSpan"; /** * {@link GCMBroadcastReceiver} instance used to handle the retry intent. * * <p> * This instance cannot be the same as the one defined in the manifest * because it needs a different permission. */ // guarded by GCMRegistrar.class private static GCMBroadcastReceiver sRetryReceiver; // guarded by GCMRegistrar.class private static Context sRetryReceiverContext; // guarded by GCMRegistrar.class private static String sRetryReceiverClassName; // guarded by GCMRegistrar.class private static PendingIntent sAppPendingIntent; /** * Checks if the device has the proper dependencies installed. * <p> * This method should be called when the application starts to verify that * the device supports GCM. * * @param context application context. * @throws UnsupportedOperationException if the device does not support GCM. */ public static void checkDevice(Context context) { int version = Build.VERSION.SDK_INT; if (version < 8) { throw new UnsupportedOperationException("Device must be at least " + "API Level 8 (instead of " + version + ")"); } PackageManager packageManager = context.getPackageManager(); try { packageManager.getPackageInfo(GSF_PACKAGE, 0); } catch (NameNotFoundException e) { throw new UnsupportedOperationException( "Device does not have package " + GSF_PACKAGE); } } /** * Checks that the application manifest is properly configured. * <p> * A proper configuration means: * <ol> * <li>It creates a custom permission called * {@code PACKAGE_NAME.permission.C2D_MESSAGE}. * <li>It defines at least one {@link BroadcastReceiver} with category * {@code PACKAGE_NAME}. * <li>The {@link BroadcastReceiver}(s) uses the * {@value com.google.android.gcm.GCMConstants#PERMISSION_GCM_INTENTS} * permission. * <li>The {@link BroadcastReceiver}(s) handles the 2 GCM intents * ({@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE} * and * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}). * </ol> * ...where {@code PACKAGE_NAME} is the application package. * <p> * This method should be used during development time to verify that the * manifest is properly set up, but it doesn't need to be called once the * application is deployed to the users' devices. * * @param context application context. * @throws IllegalStateException if any of the conditions above is not met. */ public static void checkManifest(Context context) { PackageManager packageManager = context.getPackageManager(); String packageName = context.getPackageName(); String permissionName = packageName + ".permission.C2D_MESSAGE"; // check permission try { packageManager.getPermissionInfo(permissionName, PackageManager.GET_PERMISSIONS); } catch (NameNotFoundException e) { throw new IllegalStateException( "Application does not define permission " + permissionName); } // check receivers PackageInfo receiversInfo; try { receiversInfo = packageManager.getPackageInfo( packageName, PackageManager.GET_RECEIVERS); } catch (NameNotFoundException e) { throw new IllegalStateException( "Could not get receivers for package " + packageName); } ActivityInfo[] receivers = receiversInfo.receivers; if (receivers == null || receivers.length == 0) { throw new IllegalStateException("No receiver for package " + packageName); } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "number of receivers for " + packageName + ": " + receivers.length); } Set<String> allowedReceivers = new HashSet<String>(); for (ActivityInfo receiver : receivers) { if (GCMConstants.PERMISSION_GCM_INTENTS.equals( receiver.permission)) { allowedReceivers.add(receiver.name); } } if (allowedReceivers.isEmpty()) { throw new IllegalStateException("No receiver allowed to receive " + GCMConstants.PERMISSION_GCM_INTENTS); } checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK); checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_MESSAGE); } private static void checkReceiver(Context context, Set<String> allowedReceivers, String action) { PackageManager pm = context.getPackageManager(); String packageName = context.getPackageName(); Intent intent = new Intent(action); intent.setPackage(packageName); List<ResolveInfo> receivers = pm.queryBroadcastReceivers(intent, PackageManager.GET_INTENT_FILTERS); if (receivers.isEmpty()) { throw new IllegalStateException("No receivers for action " + action); } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Found " + receivers.size() + " receivers for action " + action); } // make sure receivers match for (ResolveInfo receiver : receivers) { String name = receiver.activityInfo.name; if (!allowedReceivers.contains(name)) { throw new IllegalStateException("Receiver " + name + " is not set with permission " + GCMConstants.PERMISSION_GCM_INTENTS); } } } /** * Initiate messaging registration for the current application. * <p> * The result will be returned as an * {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with * either a {@link GCMConstants#EXTRA_REGISTRATION_ID} or * {@link GCMConstants#EXTRA_ERROR}. * * @param context application context. * @param senderIds Google Project ID of the accounts authorized to send * messages to this application. * @throws IllegalStateException if device does not have all GCM * dependencies installed. */ public static void register(Context context, String... senderIds) { GCMRegistrar.resetBackoff(context); internalRegister(context, senderIds); } static void internalRegister(Context context, String... senderIds) { String flatSenderIds = getFlatSenderIds(senderIds); Log.v(TAG, "Registering app " + context.getPackageName() + " of senders " + flatSenderIds); Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION); intent.setPackage(GSF_PACKAGE); setPackageNameExtra(context, intent); intent.putExtra(GCMConstants.EXTRA_SENDER, flatSenderIds); context.startService(intent); } /** * Unregister the application. * <p> * The result will be returned as an * {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with an * {@link GCMConstants#EXTRA_UNREGISTERED} extra. */ public static void unregister(Context context) { GCMRegistrar.resetBackoff(context); internalUnregister(context); } static void internalUnregister(Context context) { Log.v(TAG, "Unregistering app " + context.getPackageName()); Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_UNREGISTRATION); intent.setPackage(GSF_PACKAGE); setPackageNameExtra(context, intent); context.startService(intent); } static String getFlatSenderIds(String... senderIds) { if (senderIds == null || senderIds.length == 0) { throw new IllegalArgumentException("No senderIds"); } StringBuilder builder = new StringBuilder(senderIds[0]); for (int i = 1; i < senderIds.length; i++) { builder.append(',').append(senderIds[i]); } return builder.toString(); } /** * Clear internal resources. * * <p> * This method should be called by the main activity's {@code onDestroy()} * method. */ public static synchronized void onDestroy(Context context) { if (sRetryReceiver != null) { Log.v(TAG, "Unregistering retry receiver"); sRetryReceiverContext.unregisterReceiver(sRetryReceiver); sRetryReceiver = null; sRetryReceiverContext = null; } } static synchronized void cancelAppPendingIntent() { if (sAppPendingIntent != null) { sAppPendingIntent.cancel(); sAppPendingIntent = null; } } private synchronized static void setPackageNameExtra(Context context, Intent intent) { if (sAppPendingIntent == null) { Log.v(TAG, "Creating pending intent to get package name"); sAppPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(), 0); } intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT, sAppPendingIntent); } /** * Lazy initializes the {@link GCMBroadcastReceiver} instance. */ static synchronized void setRetryBroadcastReceiver(Context context) { if (sRetryReceiver == null) { if (sRetryReceiverClassName == null) { // should never happen Log.e(TAG, "internal error: retry receiver class not set yet"); sRetryReceiver = new GCMBroadcastReceiver(); } else { Class<?> clazz; try { clazz = Class.forName(sRetryReceiverClassName); sRetryReceiver = (GCMBroadcastReceiver) clazz.newInstance(); } catch (Exception e) { Log.e(TAG, "Could not create instance of " + sRetryReceiverClassName + ". Using " + GCMBroadcastReceiver.class.getName() + " directly."); sRetryReceiver = new GCMBroadcastReceiver(); } } String category = context.getPackageName(); IntentFilter filter = new IntentFilter( GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY); filter.addCategory(category); // must use a permission that is defined on manifest for sure String permission = category + ".permission.C2D_MESSAGE"; Log.v(TAG, "Registering retry receiver"); sRetryReceiverContext = context; sRetryReceiverContext.registerReceiver(sRetryReceiver, filter, permission, null); } } /** * Sets the name of the retry receiver class. */ static synchronized void setRetryReceiverClassName(String className) { Log.v(TAG, "Setting the name of retry receiver class to " + className); sRetryReceiverClassName = className; } /** * Gets the current registration id for application on GCM service. * <p> * If result is empty, the registration has failed. * * @return registration id, or empty string if the registration is not * complete. */ public static String getRegistrationId(Context context) { final SharedPreferences prefs = getGCMPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); // check if app was updated; if so, it must clear registration id to // avoid a race condition if GCM sends a message int oldVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int newVersion = getAppVersion(context); if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) { Log.v(TAG, "App version changed from " + oldVersion + " to " + newVersion + "; resetting registration id"); clearRegistrationId(context); registrationId = ""; } return registrationId; } /** * Checks whether the application was successfully registered on GCM * service. */ public static boolean isRegistered(Context context) { return getRegistrationId(context).length() > 0; } /** * Clears the registration id in the persistence store. * * @param context application's context. * @return old registration id. */ static String clearRegistrationId(Context context) { return setRegistrationId(context, ""); } /** * Sets the registration id in the persistence store. * * @param context application's context. * @param regId registration id */ static String setRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGCMPreferences(context); String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, ""); int appVersion = getAppVersion(context); Log.v(TAG, "Saving regId on app version " + appVersion); Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); return oldRegistrationId; } /** * Sets whether the device was successfully registered in the server side. */ public static void setRegisteredOnServer(Context context, boolean flag) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putBoolean(PROPERTY_ON_SERVER, flag); // set the flag's expiration date long lifespan = getRegisterOnServerLifespan(context); long expirationTime = System.currentTimeMillis() + lifespan; Log.v(TAG, "Setting registeredOnServer status as " + flag + " until " + new Timestamp(expirationTime)); editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime); editor.commit(); } /** * Checks whether the device was successfully registered in the server side, * as set by {@link #setRegisteredOnServer(Context, boolean)}. * * <p>To avoid the scenario where the device sends the registration to the * server but the server loses it, this flag has an expiration date, which * is {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} by default (but can be changed * by {@link #setRegisterOnServerLifespan(Context, long)}). */ public static boolean isRegisteredOnServer(Context context) { final SharedPreferences prefs = getGCMPreferences(context); boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false); Log.v(TAG, "Is registered on server: " + isRegistered); if (isRegistered) { // checks if the information is not stale long expirationTime = prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1); if (System.currentTimeMillis() > expirationTime) { Log.v(TAG, "flag expired on: " + new Timestamp(expirationTime)); return false; } } return isRegistered; } /** * Gets how long (in milliseconds) the {@link #isRegistered(Context)} * property is valid. * * @return value set by {@link #setRegisteredOnServer(Context, boolean)} or * {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} if not set. */ public static long getRegisterOnServerLifespan(Context context) { final SharedPreferences prefs = getGCMPreferences(context); long lifespan = prefs.getLong(PROPERTY_ON_SERVER_LIFESPAN, DEFAULT_ON_SERVER_LIFESPAN_MS); return lifespan; } /** * Sets how long (in milliseconds) the {@link #isRegistered(Context)} * flag is valid. */ public static void setRegisterOnServerLifespan(Context context, long lifespan) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putLong(PROPERTY_ON_SERVER_LIFESPAN, lifespan); editor.commit(); } /** * Gets the application version. */ private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (NameNotFoundException e) { // should never happen throw new RuntimeException("Coult not get package name: " + e); } } /** * Resets the backoff counter. * <p> * This method should be called after a GCM call succeeds. * * @param context application's context. */ static void resetBackoff(Context context) { Log.d(TAG, "Resetting backoff for " + context.getPackageName()); setBackoff(context, DEFAULT_BACKOFF_MS); } /** * Gets the current backoff counter. * * @param context application's context. * @return current backoff counter, in milliseconds. */ static int getBackoff(Context context) { final SharedPreferences prefs = getGCMPreferences(context); return prefs.getInt(BACKOFF_MS, DEFAULT_BACKOFF_MS); } /** * Sets the backoff counter. * <p> * This method should be called after a GCM call fails, passing an * exponential value. * * @param context application's context. * @param backoff new backoff counter, in milliseconds. */ static void setBackoff(Context context, int backoff) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putInt(BACKOFF_MS, backoff); editor.commit(); } private static SharedPreferences getGCMPreferences(Context context) { return context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE); } private GCMRegistrar() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; /** * Constants used by the GCM library. */ public final class GCMConstants { /** * Intent sent to GCM to register the application. */ public static final String INTENT_TO_GCM_REGISTRATION = "com.google.android.c2dm.intent.REGISTER"; /** * Intent sent to GCM to unregister the application. */ public static final String INTENT_TO_GCM_UNREGISTRATION = "com.google.android.c2dm.intent.UNREGISTER"; /** * Intent sent by GCM indicating with the result of a registration request. */ public static final String INTENT_FROM_GCM_REGISTRATION_CALLBACK = "com.google.android.c2dm.intent.REGISTRATION"; /** * Intent used by the GCM library to indicate that the registration call * should be retried. */ public static final String INTENT_FROM_GCM_LIBRARY_RETRY = "com.google.android.gcm.intent.RETRY"; /** * Intent sent by GCM containing a message. */ public static final String INTENT_FROM_GCM_MESSAGE = "com.google.android.c2dm.intent.RECEIVE"; /** * Extra used on {@value #INTENT_TO_GCM_REGISTRATION} to indicate which * senders (Google API project ids) can send messages to the application. */ public static final String EXTRA_SENDER = "sender"; /** * Extra used on {@value #INTENT_TO_GCM_REGISTRATION} to get the * application info. */ public static final String EXTRA_APPLICATION_PENDING_INTENT = "app"; /** * Extra used on {@value #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate * that the application has been unregistered. */ public static final String EXTRA_UNREGISTERED = "unregistered"; /** * Extra used on {@value #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate * an error when the registration fails. See constants starting with ERROR_ * for possible values. */ public static final String EXTRA_ERROR = "error"; /** * Extra used on {@value #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate * the registration id when the registration succeeds. */ public static final String EXTRA_REGISTRATION_ID = "registration_id"; /** * Type of message present in the {@value #INTENT_FROM_GCM_MESSAGE} intent. * This extra is only set for special messages sent from GCM, not for * messages originated from the application. */ public static final String EXTRA_SPECIAL_MESSAGE = "message_type"; /** * Special message indicating the server deleted the pending messages. */ public static final String VALUE_DELETED_MESSAGES = "deleted_messages"; /** * Number of messages deleted by the server because the device was idle. * Present only on messages of special type * {@value #VALUE_DELETED_MESSAGES} */ public static final String EXTRA_TOTAL_DELETED = "total_deleted"; /** * Extra used on {@value #INTENT_FROM_GCM_MESSAGE} to indicate which * sender (Google API project id) sent the message. */ public static final String EXTRA_FROM = "from"; /** * Permission necessary to receive GCM intents. */ public static final String PERMISSION_GCM_INTENTS = "com.google.android.c2dm.permission.SEND"; /** * @see GCMBroadcastReceiver */ public static final String DEFAULT_INTENT_SERVICE_CLASS_NAME = ".GCMIntentService"; /** * The device can't read the response, or there was a 500/503 from the * server that can be retried later. The application should use exponential * back off and retry. */ public static final String ERROR_SERVICE_NOT_AVAILABLE = "SERVICE_NOT_AVAILABLE"; /** * There is no Google account on the phone. The application should ask the * user to open the account manager and add a Google account. */ public static final String ERROR_ACCOUNT_MISSING = "ACCOUNT_MISSING"; /** * Bad password. The application should ask the user to enter his/her * password, and let user retry manually later. Fix on the device side. */ public static final String ERROR_AUTHENTICATION_FAILED = "AUTHENTICATION_FAILED"; /** * The request sent by the phone does not contain the expected parameters. * This phone doesn't currently support GCM. */ public static final String ERROR_INVALID_PARAMETERS = "INVALID_PARAMETERS"; /** * The sender account is not recognized. Fix on the device side. */ public static final String ERROR_INVALID_SENDER = "INVALID_SENDER"; /** * Incorrect phone registration with Google. This phone doesn't currently * support GCM. */ public static final String ERROR_PHONE_REGISTRATION_ERROR = "PHONE_REGISTRATION_ERROR"; private GCMConstants() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.DEFAULT_INTENT_SERVICE_CLASS_NAME; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * {@link BroadcastReceiver} that receives GCM messages and delivers them to * an application-specific {@link GCMBaseIntentService} subclass. * <p> * By default, the {@link GCMBaseIntentService} class belongs to the application * main package and is named * {@link GCMConstants#DEFAULT_INTENT_SERVICE_CLASS_NAME}. To use a new class, * the {@link #getGCMIntentServiceClassName(Context)} must be overridden. */ public class GCMBroadcastReceiver extends BroadcastReceiver { private static final String TAG = "GCMBroadcastReceiver"; private static boolean mReceiverSet = false; @Override public final void onReceive(Context context, Intent intent) { Log.v(TAG, "onReceive: " + intent.getAction()); // do a one-time check if app is using a custom GCMBroadcastReceiver if (!mReceiverSet) { mReceiverSet = true; GCMRegistrar.setRetryReceiverClassName(getClass().getName()); } String className = getGCMIntentServiceClassName(context); Log.v(TAG, "GCM IntentService class: " + className); // Delegates to the application-specific intent service. GCMBaseIntentService.runIntentInService(context, intent, className); setResult(Activity.RESULT_OK, null /* data */, null /* extra */); } /** * Gets the class name of the intent service that will handle GCM messages. */ protected String getGCMIntentServiceClassName(Context context) { return getDefaultIntentServiceClassName(context); } /** * Gets the default class name of the intent service that will handle GCM * messages. */ static final String getDefaultIntentServiceClassName(Context context) { String className = context.getPackageName() + DEFAULT_INTENT_SERVICE_CLASS_NAME; return className; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.IOException; /** * Exception thrown when GCM returned an error due to an invalid request. * <p> * This is equivalent to GCM posts that return an HTTP error different of 200. */ public final class InvalidRequestException extends IOException { private final int status; private final String description; public InvalidRequestException(int status) { this(status, null); } public InvalidRequestException(int status, String description) { super(getMessage(status, description)); this.status = status; this.description = description; } private static String getMessage(int status, String description) { StringBuilder base = new StringBuilder("HTTP Status Code: ").append(status); if (description != null) { base.append("(").append(description).append(")"); } return base.toString(); } /** * Gets the HTTP Status Code. */ public int getHttpStatusCode() { return status; } /** * Gets the error description. */ public String getDescription() { return description; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.Serializable; /** * Result of a GCM message request that returned HTTP status code 200. * * <p> * If the message is successfully created, the {@link #getMessageId()} returns * the message id and {@link #getErrorCodeName()} returns {@literal null}; * otherwise, {@link #getMessageId()} returns {@literal null} and * {@link #getErrorCodeName()} returns the code of the error. * * <p> * There are cases when a request is accept and the message successfully * created, but GCM has a canonical registration id for that device. In this * case, the server should update the registration id to avoid rejected requests * in the future. * * <p> * In a nutshell, the workflow to handle a result is: * <pre> * - Call {@link #getMessageId()}: * - {@literal null} means error, call {@link #getErrorCodeName()} * - non-{@literal null} means the message was created: * - Call {@link #getCanonicalRegistrationId()} * - if it returns {@literal null}, do nothing. * - otherwise, update the server datastore with the new id. * </pre> */ public final class Result implements Serializable { private final String messageId; private final String canonicalRegistrationId; private final String errorCode; static final class Builder { // optional parameters private String messageId; private String canonicalRegistrationId; private String errorCode; public Builder canonicalRegistrationId(String value) { canonicalRegistrationId = value; return this; } public Builder messageId(String value) { messageId = value; return this; } public Builder errorCode(String value) { errorCode = value; return this; } public Result build() { return new Result(this); } } private Result(Builder builder) { canonicalRegistrationId = builder.canonicalRegistrationId; messageId = builder.messageId; errorCode = builder.errorCode; } /** * Gets the message id, if any. */ public String getMessageId() { return messageId; } /** * Gets the canonical registration id, if any. */ public String getCanonicalRegistrationId() { return canonicalRegistrationId; } /** * Gets the error code, if any. */ public String getErrorCodeName() { return errorCode; } @Override public String toString() { StringBuilder builder = new StringBuilder("["); if (messageId != null) { builder.append(" messageId=").append(messageId); } if (canonicalRegistrationId != null) { builder.append(" canonicalRegistrationId=") .append(canonicalRegistrationId); } if (errorCode != null) { builder.append(" errorCode=").append(errorCode); } return builder.append(" ]").toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import static com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT; import static com.google.android.gcm.server.Constants.JSON_CANONICAL_IDS; import static com.google.android.gcm.server.Constants.JSON_ERROR; import static com.google.android.gcm.server.Constants.JSON_FAILURE; import static com.google.android.gcm.server.Constants.JSON_MESSAGE_ID; import static com.google.android.gcm.server.Constants.JSON_MULTICAST_ID; import static com.google.android.gcm.server.Constants.JSON_PAYLOAD; import static com.google.android.gcm.server.Constants.JSON_REGISTRATION_IDS; import static com.google.android.gcm.server.Constants.JSON_RESULTS; import static com.google.android.gcm.server.Constants.JSON_SUCCESS; import static com.google.android.gcm.server.Constants.PARAM_COLLAPSE_KEY; import static com.google.android.gcm.server.Constants.PARAM_DELAY_WHILE_IDLE; import static com.google.android.gcm.server.Constants.PARAM_PAYLOAD_PREFIX; import static com.google.android.gcm.server.Constants.PARAM_REGISTRATION_ID; import static com.google.android.gcm.server.Constants.PARAM_TIME_TO_LIVE; import static com.google.android.gcm.server.Constants.TOKEN_CANONICAL_REG_ID; import static com.google.android.gcm.server.Constants.TOKEN_ERROR; import static com.google.android.gcm.server.Constants.TOKEN_MESSAGE_ID; import com.google.android.gcm.server.Result.Builder; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; /** * Helper class to send messages to the GCM service using an API Key. */ public class Sender { protected static final String UTF8 = "UTF-8"; /** * Initial delay before first retry, without jitter. */ protected static final int BACKOFF_INITIAL_DELAY = 1000; /** * Maximum delay before a retry. */ protected static final int MAX_BACKOFF_DELAY = 1024000; protected final Random random = new Random(); protected static final Logger logger = Logger.getLogger(Sender.class.getName()); private final String key; /** * Default constructor. * * @param key API key obtained through the Google API Console. */ public Sender(String key) { this.key = nonNull(key); } /** * Sends a message to one device, retrying in case of unavailability. * * <p> * <strong>Note: </strong> this method uses exponential back-off to retry in * case of service unavailability and hence could block the calling thread * for many seconds. * * @param message message to be sent, including the device's registration id. * @param registrationId device where the message will be sent. * @param retries number of retries in case of service unavailability errors. * * @return result of the request (see its javadoc for more details). * * @throws IllegalArgumentException if registrationId is {@literal null}. * @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status. * @throws IOException if message could not be sent. */ public Result send(Message message, String registrationId, int retries) throws IOException { int attempt = 0; Result result = null; int backoff = BACKOFF_INITIAL_DELAY; boolean tryAgain; do { attempt++; if (logger.isLoggable(Level.FINE)) { logger.fine("Attempt #" + attempt + " to send message " + message + " to regIds " + registrationId); } result = sendNoRetry(message, registrationId); tryAgain = result == null && attempt <= retries; if (tryAgain) { int sleepTime = backoff / 2 + random.nextInt(backoff); sleep(sleepTime); if (2 * backoff < MAX_BACKOFF_DELAY) { backoff *= 2; } } } while (tryAgain); if (result == null) { throw new IOException("Could not send message after " + attempt + " attempts"); } return result; } /** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, String, int)} for more info. * * @return result of the post, or {@literal null} if the GCM service was * unavailable or any network exception caused the request to fail. * * @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status. * @throws IllegalArgumentException if registrationId is {@literal null}. */ public Result sendNoRetry(Message message, String registrationId) throws IOException { StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId); Boolean delayWhileIdle = message.isDelayWhileIdle(); if (delayWhileIdle != null) { addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0"); } String collapseKey = message.getCollapseKey(); if (collapseKey != null) { addParameter(body, PARAM_COLLAPSE_KEY, collapseKey); } Integer timeToLive = message.getTimeToLive(); if (timeToLive != null) { addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive)); } for (Entry<String, String> entry : message.getData().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (key == null || value == null) { logger.warning("Ignoring payload entry thas has null: " + entry); } else { key = PARAM_PAYLOAD_PREFIX + key; addParameter(body, key, URLEncoder.encode(value, UTF8)); } } String requestBody = body.toString(); logger.finest("Request body: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } if (status / 100 == 5) { logger.fine("GCM service is unavailable (status " + status + ")"); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.finest("Plain post error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an InvalidRequestException // anyways responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } else { try { responseBody = getAndClose(conn.getInputStream()); } catch (IOException e) { logger.log(Level.WARNING, "Exception reading response: ", e); // return null so it can retry return null; } } String[] lines = responseBody.split("\n"); if (lines.length == 0 || lines[0].equals("")) { throw new IOException("Received empty response from GCM service."); } String firstLine = lines[0]; String[] responseParts = split(firstLine); String token = responseParts[0]; String value = responseParts[1]; if (token.equals(TOKEN_MESSAGE_ID)) { Builder builder = new Result.Builder().messageId(value); // check for canonical registration id if (lines.length > 1) { String secondLine = lines[1]; responseParts = split(secondLine); token = responseParts[0]; value = responseParts[1]; if (token.equals(TOKEN_CANONICAL_REG_ID)) { builder.canonicalRegistrationId(value); } else { logger.warning("Invalid response from GCM: " + responseBody); } } Result result = builder.build(); if (logger.isLoggable(Level.FINE)) { logger.fine("Message created succesfully (" + result + ")"); } return result; } else if (token.equals(TOKEN_ERROR)) { return new Result.Builder().errorCode(value).build(); } else { throw new IOException("Invalid response from GCM: " + responseBody); } } /** * Sends a message to many devices, retrying in case of unavailability. * * <p> * <strong>Note: </strong> this method uses exponential back-off to retry in * case of service unavailability and hence could block the calling thread * for many seconds. * * @param message message to be sent. * @param regIds registration id of the devices that will receive * the message. * @param retries number of retries in case of service unavailability errors. * * @return combined result of all requests made. * * @throws IllegalArgumentException if registrationIds is {@literal null} or * empty. * @throws InvalidRequestException if GCM didn't returned a 200 or 503 status. * @throws IOException if message could not be sent. */ public MulticastResult send(Message message, List<String> regIds, int retries) throws IOException { int attempt = 0; MulticastResult multicastResult; int backoff = BACKOFF_INITIAL_DELAY; // Map of results by registration id, it will be updated after each attempt // to send the messages Map<String, Result> results = new HashMap<String, Result>(); List<String> unsentRegIds = new ArrayList<String>(regIds); boolean tryAgain; List<Long> multicastIds = new ArrayList<Long>(); do { multicastResult = null; attempt++; if (logger.isLoggable(Level.FINE)) { logger.fine("Attempt #" + attempt + " to send message " + message + " to regIds " + unsentRegIds); } try { multicastResult = sendNoRetry(message, unsentRegIds); } catch(IOException e) { // no need for WARNING since exception might be already logged logger.log(Level.FINEST, "IOException on attempt " + attempt, e); } if (multicastResult != null) { long multicastId = multicastResult.getMulticastId(); logger.fine("multicast_id on attempt # " + attempt + ": " + multicastId); multicastIds.add(multicastId); unsentRegIds = updateStatus(unsentRegIds, results, multicastResult); tryAgain = !unsentRegIds.isEmpty() && attempt <= retries; } else { tryAgain = attempt <= retries; } if (tryAgain) { int sleepTime = backoff / 2 + random.nextInt(backoff); sleep(sleepTime); if (2 * backoff < MAX_BACKOFF_DELAY) { backoff *= 2; } } } while (tryAgain); if (multicastIds.isEmpty()) { // all JSON posts failed due to GCM unavailability throw new IOException("Could not post JSON requests to GCM after " + attempt + " attempts"); } // calculate summary int success = 0, failure = 0 , canonicalIds = 0; for (Result result : results.values()) { if (result.getMessageId() != null) { success++; if (result.getCanonicalRegistrationId() != null) { canonicalIds++; } } else { failure++; } } // build a new object with the overall result long multicastId = multicastIds.remove(0); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId).retryMulticastIds(multicastIds); // add results, in the same order as the input for (String regId : regIds) { Result result = results.get(regId); builder.addResult(result); } return builder.build(); } /** * Updates the status of the messages sent to devices and the list of devices * that should be retried. * * @param unsentRegIds list of devices that are still pending an update. * @param allResults map of status that will be updated. * @param multicastResult result of the last multicast sent. * * @return updated version of devices that should be retried. */ private List<String> updateStatus(List<String> unsentRegIds, Map<String, Result> allResults, MulticastResult multicastResult) { List<Result> results = multicastResult.getResults(); if (results.size() != unsentRegIds.size()) { // should never happen, unless there is a flaw in the algorithm throw new RuntimeException("Internal error: sizes do not match. " + "currentResults: " + results + "; unsentRegIds: " + unsentRegIds); } List<String> newUnsentRegIds = new ArrayList<String>(); for (int i = 0; i < unsentRegIds.size(); i++) { String regId = unsentRegIds.get(i); Result result = results.get(i); allResults.put(regId, result); String error = result.getErrorCodeName(); if (error != null && (error.equals(Constants.ERROR_UNAVAILABLE) || error.equals(Constants.ERROR_INTERNAL_SERVER_ERROR))) { newUnsentRegIds.add(regId); } } return newUnsentRegIds; } /** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, List, int)} for more info. * * @return multicast results if the message was sent successfully, * {@literal null} if it failed but could be retried. * * @throws IllegalArgumentException if registrationIds is {@literal null} or * empty. * @throws InvalidRequestException if GCM didn't returned a 200 status. * @throws IOException if there was a JSON parsing error */ public MulticastResult sendNoRetry(Message message, List<String> registrationIds) throws IOException { if (nonNull(registrationIds).isEmpty()) { throw new IllegalArgumentException("registrationIds cannot be empty"); } Map<Object, Object> jsonRequest = new HashMap<Object, Object>(); setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive()); setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey()); setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle()); jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds); Map<String, String> payload = message.getData(); if (!payload.isEmpty()) { jsonRequest.put(JSON_PAYLOAD, payload); } String requestBody = JSONValue.toJSONString(jsonRequest); logger.finest("JSON request: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.finest("JSON error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an InvalidRequestException // anyways responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } try { responseBody = getAndClose(conn.getInputStream()); } catch(IOException e) { logger.log(Level.WARNING, "IOException reading response", e); return null; } logger.finest("JSON response: " + responseBody); JSONParser parser = new JSONParser(); JSONObject jsonResponse; try { jsonResponse = (JSONObject) parser.parse(responseBody); int success = getNumber(jsonResponse, JSON_SUCCESS).intValue(); int failure = getNumber(jsonResponse, JSON_FAILURE).intValue(); int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue(); long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue(); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId); @SuppressWarnings("unchecked") List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS); if (results != null) { for (Map<String, Object> jsonResult : results) { String messageId = (String) jsonResult.get(JSON_MESSAGE_ID); String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID); String error = (String) jsonResult.get(JSON_ERROR); Result result = new Result.Builder() .messageId(messageId) .canonicalRegistrationId(canonicalRegId) .errorCode(error) .build(); builder.addResult(result); } } MulticastResult multicastResult = builder.build(); return multicastResult; } catch (ParseException e) { throw newIoException(responseBody, e); } catch (CustomParserException e) { throw newIoException(responseBody, e); } } private IOException newIoException(String responseBody, Exception e) { // log exception, as IOException constructor that takes a message and cause // is only available on Java 6 String msg = "Error parsing JSON response (" + responseBody + ")"; logger.log(Level.WARNING, msg, e); return new IOException(msg + ":" + e); } private static void close(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { // ignore error logger.log(Level.FINEST, "IOException closing stream", e); } } } /** * Sets a JSON field, but only if the value is not {@literal null}. */ private void setJsonField(Map<Object, Object> json, String field, Object value) { if (value != null) { json.put(field, value); } } private Number getNumber(Map<?, ?> json, String field) { Object value = json.get(field); if (value == null) { throw new CustomParserException("Missing field: " + field); } if (!(value instanceof Number)) { throw new CustomParserException("Field " + field + " does not contain a number: " + value); } return (Number) value; } class CustomParserException extends RuntimeException { CustomParserException(String message) { super(message); } } private String[] split(String line) throws IOException { String[] split = line.split("=", 2); if (split.length != 2) { throw new IOException("Received invalid response line from GCM: " + line); } return split; } /** * Make an HTTP post to a given URL. * * @return HTTP response. */ protected HttpURLConnection post(String url, String body) throws IOException { return post(url, "application/x-www-form-urlencoded;charset=UTF-8", body); } /** * Makes an HTTP POST request to a given endpoint. * * <p> * <strong>Note: </strong> the returned connected should not be disconnected, * otherwise it would kill persistent connections made using Keep-Alive. * * @param url endpoint to post the request. * @param contentType type of request. * @param body body of the request. * * @return the underlying connection. * * @throws IOException propagated from underlying methods. */ protected HttpURLConnection post(String url, String contentType, String body) throws IOException { if (url == null || body == null) { throw new IllegalArgumentException("arguments cannot be null"); } if (!url.startsWith("https://")) { logger.warning("URL does not use https: " + url); } logger.fine("Sending POST to " + url); logger.finest("POST body: " + body); byte[] bytes = body.getBytes(); HttpURLConnection conn = getConnection(url); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Authorization", "key=" + key); OutputStream out = conn.getOutputStream(); try { out.write(bytes); } finally { close(out); } return conn; } /** * Creates a map with just one key-value pair. */ protected static final Map<String, String> newKeyValues(String key, String value) { Map<String, String> keyValues = new HashMap<String, String>(1); keyValues.put(nonNull(key), nonNull(value)); return keyValues; } /** * Creates a {@link StringBuilder} to be used as the body of an HTTP POST. * * @param name initial parameter for the POST. * @param value initial value for that parameter. * @return StringBuilder to be used an HTTP POST body. */ protected static StringBuilder newBody(String name, String value) { return new StringBuilder(nonNull(name)).append('=').append(nonNull(value)); } /** * Adds a new parameter to the HTTP POST body. * * @param body HTTP POST body. * @param name parameter's name. * @param value parameter's value. */ protected static void addParameter(StringBuilder body, String name, String value) { nonNull(body).append('&') .append(nonNull(name)).append('=').append(nonNull(value)); } /** * Gets an {@link HttpURLConnection} given an URL. */ protected HttpURLConnection getConnection(String url) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); return conn; } /** * Convenience method to convert an InputStream to a String. * <p> * If the stream ends in a newline character, it will be stripped. * <p> * If the stream is {@literal null}, returns an empty string. */ protected static String getString(InputStream stream) throws IOException { if (stream == null) { return ""; } BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder content = new StringBuilder(); String newLine; do { newLine = reader.readLine(); if (newLine != null) { content.append(newLine).append('\n'); } } while (newLine != null); if (content.length() > 0) { // strip last newline content.setLength(content.length() - 1); } return content.toString(); } private static String getAndClose(InputStream stream) throws IOException { try { return getString(stream); } finally { if (stream != null) { close(stream); } } } static <T> T nonNull(T argument) { if (argument == null) { throw new IllegalArgumentException("argument cannot be null"); } return argument; } void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; /** * Constants used on GCM service communication. */ public final class Constants { /** * Endpoint for sending messages. */ public static final String GCM_SEND_ENDPOINT = "https://android.googleapis.com/gcm/send"; /** * HTTP parameter for registration id. */ public static final String PARAM_REGISTRATION_ID = "registration_id"; /** * HTTP parameter for collapse key. */ public static final String PARAM_COLLAPSE_KEY = "collapse_key"; /** * HTTP parameter for delaying the message delivery if the device is idle. */ public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle"; /** * Prefix to HTTP parameter used to pass key-values in the message payload. */ public static final String PARAM_PAYLOAD_PREFIX = "data."; /** * Prefix to HTTP parameter used to set the message time-to-live. */ public static final String PARAM_TIME_TO_LIVE = "time_to_live"; /** * Too many messages sent by the sender. Retry after a while. */ public static final String ERROR_QUOTA_EXCEEDED = "QuotaExceeded"; /** * Too many messages sent by the sender to a specific device. * Retry after a while. */ public static final String ERROR_DEVICE_QUOTA_EXCEEDED = "DeviceQuotaExceeded"; /** * Missing registration_id. * Sender should always add the registration_id to the request. */ public static final String ERROR_MISSING_REGISTRATION = "MissingRegistration"; /** * Bad registration_id. Sender should remove this registration_id. */ public static final String ERROR_INVALID_REGISTRATION = "InvalidRegistration"; /** * The sender_id contained in the registration_id does not match the * sender_id used to register with the GCM servers. */ public static final String ERROR_MISMATCH_SENDER_ID = "MismatchSenderId"; /** * The user has uninstalled the application or turned off notifications. * Sender should stop sending messages to this device and delete the * registration_id. The client needs to re-register with the GCM servers to * receive notifications again. */ public static final String ERROR_NOT_REGISTERED = "NotRegistered"; /** * The payload of the message is too big, see the limitations. * Reduce the size of the message. */ public static final String ERROR_MESSAGE_TOO_BIG = "MessageTooBig"; /** * Collapse key is required. Include collapse key in the request. */ public static final String ERROR_MISSING_COLLAPSE_KEY = "MissingCollapseKey"; /** * A particular message could not be sent because the GCM servers were not * available. Used only on JSON requests, as in plain text requests * unavailability is indicated by a 503 response. */ public static final String ERROR_UNAVAILABLE = "Unavailable"; /** * A particular message could not be sent because the GCM servers encountered * an error. Used only on JSON requests, as in plain text requests internal * errors are indicated by a 500 response. */ public static final String ERROR_INTERNAL_SERVER_ERROR = "InternalServerError"; /** * Time to Live value passed is less than zero or more than maximum. */ public static final String ERROR_INVALID_TTL= "InvalidTtl"; /** * Token returned by GCM when a message was successfully sent. */ public static final String TOKEN_MESSAGE_ID = "id"; /** * Token returned by GCM when the requested registration id has a canonical * value. */ public static final String TOKEN_CANONICAL_REG_ID = "registration_id"; /** * Token returned by GCM when there was an error sending a message. */ public static final String TOKEN_ERROR = "Error"; /** * JSON-only field representing the registration ids. */ public static final String JSON_REGISTRATION_IDS = "registration_ids"; /** * JSON-only field representing the payload data. */ public static final String JSON_PAYLOAD = "data"; /** * JSON-only field representing the number of successful messages. */ public static final String JSON_SUCCESS = "success"; /** * JSON-only field representing the number of failed messages. */ public static final String JSON_FAILURE = "failure"; /** * JSON-only field representing the number of messages with a canonical * registration id. */ public static final String JSON_CANONICAL_IDS = "canonical_ids"; /** * JSON-only field representing the id of the multicast request. */ public static final String JSON_MULTICAST_ID = "multicast_id"; /** * JSON-only field representing the result of each individual request. */ public static final String JSON_RESULTS = "results"; /** * JSON-only field representing the error field of an individual request. */ public static final String JSON_ERROR = "error"; /** * JSON-only field sent by GCM when a message was successfully sent. */ public static final String JSON_MESSAGE_ID = "message_id"; private Constants() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.Serializable; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * GCM message. * * <p> * Instances of this class are immutable and should be created using a * {@link Builder}. Examples: * * <strong>Simplest message:</strong> * <pre><code> * Message message = new Message.Builder().build(); * </pre></code> * * <strong>Message with optional attributes:</strong> * <pre><code> * Message message = new Message.Builder() * .collapseKey(collapseKey) * .timeToLive(3) * .delayWhileIdle(true) * .build(); * </pre></code> * * <strong>Message with optional attributes and payload data:</strong> * <pre><code> * Message message = new Message.Builder() * .collapseKey(collapseKey) * .timeToLive(3) * .delayWhileIdle(true) * .addData("key1", "value1") * .addData("key2", "value2") * .build(); * </pre></code> */ public final class Message implements Serializable { private final String collapseKey; private final Boolean delayWhileIdle; private final Integer timeToLive; private final Map<String, String> data; public static final class Builder { private final Map<String, String> data; // optional parameters private String collapseKey; private Boolean delayWhileIdle; private Integer timeToLive; public Builder() { this.data = new LinkedHashMap<String, String>(); } /** * Sets the collapseKey property. */ public Builder collapseKey(String value) { collapseKey = value; return this; } /** * Sets the delayWhileIdle property (default value is {@literal false}). */ public Builder delayWhileIdle(boolean value) { delayWhileIdle = value; return this; } /** * Sets the time to live, in seconds. */ public Builder timeToLive(int value) { timeToLive = value; return this; } /** * Adds a key/value pair to the payload data. */ public Builder addData(String key, String value) { data.put(key, value); return this; } public Message build() { return new Message(this); } } private Message(Builder builder) { collapseKey = builder.collapseKey; delayWhileIdle = builder.delayWhileIdle; data = Collections.unmodifiableMap(builder.data); timeToLive = builder.timeToLive; } /** * Gets the collapse key. */ public String getCollapseKey() { return collapseKey; } /** * Gets the delayWhileIdle flag. */ public Boolean isDelayWhileIdle() { return delayWhileIdle; } /** * Gets the time to live (in seconds). */ public Integer getTimeToLive() { return timeToLive; } /** * Gets the payload data, which is immutable. */ public Map<String, String> getData() { return data; } @Override public String toString() { StringBuilder builder = new StringBuilder("Message("); if (collapseKey != null) { builder.append("collapseKey=").append(collapseKey).append(", "); } if (timeToLive != null) { builder.append("timeToLive=").append(timeToLive).append(", "); } if (delayWhileIdle != null) { builder.append("delayWhileIdle=").append(delayWhileIdle).append(", "); } if (!data.isEmpty()) { builder.append("data: {"); for (Map.Entry<String, String> entry : data.entrySet()) { builder.append(entry.getKey()).append("=").append(entry.getValue()) .append(","); } builder.delete(builder.length() - 1, builder.length()); builder.append("}"); } if (builder.charAt(builder.length() - 1) == ' ') { builder.delete(builder.length() - 2, builder.length()); } builder.append(")"); return builder.toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Result of a GCM multicast message request . */ public final class MulticastResult implements Serializable { private final int success; private final int failure; private final int canonicalIds; private final long multicastId; private final List<Result> results; private final List<Long> retryMulticastIds; static final class Builder { private final List<Result> results = new ArrayList<Result>(); // required parameters private final int success; private final int failure; private final int canonicalIds; private final long multicastId; // optional parameters private List<Long> retryMulticastIds; public Builder(int success, int failure, int canonicalIds, long multicastId) { this.success = success; this.failure = failure; this.canonicalIds = canonicalIds; this.multicastId = multicastId; } public Builder addResult(Result result) { results.add(result); return this; } public Builder retryMulticastIds(List<Long> retryMulticastIds) { this.retryMulticastIds = retryMulticastIds; return this; } public MulticastResult build() { return new MulticastResult(this); } } private MulticastResult(Builder builder) { success = builder.success; failure = builder.failure; canonicalIds = builder.canonicalIds; multicastId = builder.multicastId; results = Collections.unmodifiableList(builder.results); List<Long> tmpList = builder.retryMulticastIds; if (tmpList == null) { tmpList = Collections.emptyList(); } retryMulticastIds = Collections.unmodifiableList(tmpList); } /** * Gets the multicast id. */ public long getMulticastId() { return multicastId; } /** * Gets the number of successful messages. */ public int getSuccess() { return success; } /** * Gets the total number of messages sent, regardless of the status. */ public int getTotal() { return success + failure; } /** * Gets the number of failed messages. */ public int getFailure() { return failure; } /** * Gets the number of successful messages that also returned a canonical * registration id. */ public int getCanonicalIds() { return canonicalIds; } /** * Gets the results of each individual message, which is immutable. */ public List<Result> getResults() { return results; } /** * Gets additional ids if more than one multicast message was sent. */ public List<Long> getRetryMulticastIds() { return retryMulticastIds; } @Override public String toString() { StringBuilder builder = new StringBuilder("MulticastResult(") .append("multicast_id=").append(multicastId).append(",") .append("total=").append(getTotal()).append(",") .append("success=").append(success).append(",") .append("failure=").append(failure).append(",") .append("canonical_ids=").append(canonicalIds).append(","); if (!results.isEmpty()) { builder.append("results: " + results); } return builder.toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.logging.Level; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds a new message to all registered devices. * <p> * This servlet is used just by the browser (i.e., not device). */ @SuppressWarnings("serial") public class SendAllMessagesServlet extends BaseServlet { private static final int MULTICAST_SIZE = 1000; private Sender sender; private static final Executor threadPool = Executors.newFixedThreadPool(5); @Override public void init(ServletConfig config) throws ServletException { super.init(config); sender = newSender(config); } /** * Creates the {@link Sender} based on the servlet settings. */ protected Sender newSender(ServletConfig config) { String key = (String) config.getServletContext() .getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); return new Sender(key); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { List<String> devices = Datastore.getDevices(); String status; if (devices.isEmpty()) { status = "Message ignored as there is no device registered!"; } else { // NOTE: check below is for demonstration purposes; a real application // could always send a multicast, even for just one recipient if (devices.size() == 1) { // send a single message using plain post String registrationId = devices.get(0); Message message = new Message.Builder().build(); Result result = sender.send(message, registrationId, 5); status = "Sent message to one device: " + result; } else { // send a multicast message using JSON // must split in chunks of 1000 devices (GCM limit) int total = devices.size(); List<String> partialDevices = new ArrayList<String>(total); int counter = 0; int tasks = 0; for (String device : devices) { counter++; partialDevices.add(device); int partialSize = partialDevices.size(); if (partialSize == MULTICAST_SIZE || counter == total) { asyncSend(partialDevices); partialDevices.clear(); tasks++; } } status = "Asynchronously sending " + tasks + " multicast messages to " + total + " devices"; } } req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString()); getServletContext().getRequestDispatcher("/home").forward(req, resp); } private void asyncSend(List<String> partialDevices) { // make a copy final List<String> devices = new ArrayList<String>(partialDevices); threadPool.execute(new Runnable() { public void run() { Message message = new Message.Builder().build(); MulticastResult multicastResult; try { multicastResult = sender.send(message, devices, 5); } catch (IOException e) { logger.log(Level.SEVERE, "Error posting messages", e); return; } List<Result> results = multicastResult.getResults(); // analyze the results for (int i = 0; i < devices.size(); i++) { String regId = devices.get(i); Result result = results.get(i); String messageId = result.getMessageId(); if (messageId != null) { logger.fine("Succesfully sent message to device: " + regId + "; messageId = " + messageId); String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { // same device has more than on registration id: update it logger.info("canonicalRegId " + canonicalRegId); Datastore.updateRegistration(regId, canonicalRegId); } } else { String error = result.getErrorCodeName(); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it logger.info("Unregistered device: " + regId); Datastore.unregister(regId); } else { logger.severe("Error sending message to " + regId + ": " + error); } } } }}); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION} with an * {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.unregister(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an * error or {@code unregistered} extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.register(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; /** * Simple implementation of a data store using standard Java collections. * <p> * This class is thread-safe but not persistent (it will lost the data when the * app is restarted) - it is meant just as an example. */ public final class Datastore { private static final List<String> regIds = new ArrayList<String>(); private static final Logger logger = Logger.getLogger(Datastore.class.getName()); private Datastore() { throw new UnsupportedOperationException(); } /** * Registers a device. */ public static void register(String regId) { logger.info("Registering " + regId); synchronized (regIds) { regIds.add(regId); } } /** * Unregisters a device. */ public static void unregister(String regId) { logger.info("Unregistering " + regId); synchronized (regIds) { regIds.remove(regId); } } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldId, String newId) { logger.info("Updating " + oldId + " to " + newId); synchronized (regIds) { regIds.remove(oldId); regIds.add(newId); } } /** * Gets all registered devices. */ public static List<String> getDevices() { synchronized (regIds) { return new ArrayList<String>(regIds); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. */ @SuppressWarnings("serial") abstract class BaseServlet extends HttpServlet { // change to true to allow GET calls static final boolean DEBUG = true; protected final Logger logger = Logger.getLogger(getClass().getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (DEBUG) { doPost(req, resp); } else { super.doGet(req, resp); } } protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { if (DEBUG) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.fine("parameters: " + parameters); } throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected String getParameter(HttpServletRequest req, String parameter, String defaultValue) { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { value = defaultValue; } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { setSuccess(resp, 0); } protected void setSuccess(HttpServletResponse resp, int size) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(size); } protected boolean isEmptyOrNull(String value) { return value == null || value.trim().length() == 0; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Context initializer that loads the API key from a * {@value #PATH} file located in the classpath (typically under * {@code WEB-INF/classes}). */ public class ApiKeyInitializer implements ServletContextListener { static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String PATH = "/api.key"; private final Logger logger = Logger.getLogger(getClass().getName()); public void contextInitialized(ServletContextEvent event) { logger.info("Reading " + PATH + " from resources (probably from " + "WEB-INF/classes"); String key = getKey(); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, key); } /** * Gets the access key. */ protected String getKey() { InputStream stream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(PATH); if (stream == null) { throw new IllegalStateException("Could not find file " + PATH + " on web resources)"); } BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { String key = reader.readLine(); return key; } catch (IOException e) { throw new RuntimeException("Could not read file " + PATH, e); } finally { try { reader.close(); } catch (IOException e) { logger.log(Level.WARNING, "Exception closing " + PATH, e); } } } public void contextDestroyed(ServletContextEvent event) { } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds display number of devices and button to send a message. * <p> * This servlet is used just by the browser (i.e., not device) and contains the * main page of the demo app. */ @SuppressWarnings("serial") public class HomeServlet extends BaseServlet { static final String ATTRIBUTE_STATUS = "status"; /** * Displays the existing messages and offer the option to send a new one. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head>"); out.print(" <title>GCM Demo</title>"); out.print(" <link rel='icon' href='favicon.png'/>"); out.print("</head>"); String status = (String) req.getAttribute(ATTRIBUTE_STATUS); if (status != null) { out.print(status); } List<String> devices = Datastore.getDevices(); if (devices.isEmpty()) { out.print("<h2>No devices registered!</h2>"); } else { out.print("<h2>" + devices.size() + " device(s) registered!</h2>"); out.print("<form name='form' method='POST' action='sendAll'>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); } out.print("</body></html>"); resp.setStatus(HttpServletResponse.SC_OK); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import static com.google.android.gcm.demo.app.CommonUtilities.DISPLAY_MESSAGE_ACTION; import static com.google.android.gcm.demo.app.CommonUtilities.EXTRA_MESSAGE; import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID; import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL; import com.google.android.gcm.GCMRegistrar; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; /** * Main UI for the demo app. */ public class DemoActivity extends Activity { TextView mDisplay; AsyncTask<Void, Void, Void> mRegisterTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkNotNull(SERVER_URL, "SERVER_URL"); checkNotNull(SENDER_ID, "SENDER_ID"); // Make sure the device has the proper dependencies. GCMRegistrar.checkDevice(this); // Make sure the manifest was properly set - comment out this line // while developing the app, then uncomment it when it's ready. GCMRegistrar.checkManifest(this); setContentView(R.layout.main); mDisplay = (TextView) findViewById(R.id.display); registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION)); final String regId = GCMRegistrar.getRegistrationId(this); if (regId.equals("")) { // Automatically registers application on startup. GCMRegistrar.register(this, SENDER_ID); } else { // Device is already registered on GCM, check server. if (GCMRegistrar.isRegisteredOnServer(this)) { // Skips registration. mDisplay.append(getString(R.string.already_registered) + "\n"); } else { // Try to register again, but not in the UI thread. // It's also necessary to cancel the thread onDestroy(), // hence the use of AsyncTask instead of a raw thread. final Context context = this; mRegisterTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { ServerUtilities.register(context, regId); return null; } @Override protected void onPostExecute(Void result) { mRegisterTask = null; } }; mRegisterTask.execute(null, null, null); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { /* * Typically, an application registers automatically, so options * below are disabled. Uncomment them if you want to manually * register or unregister the device (you will also need to * uncomment the equivalent options on options_menu.xml). */ /* case R.id.options_register: GCMRegistrar.register(this, SENDER_ID); return true; case R.id.options_unregister: GCMRegistrar.unregister(this); return true; */ case R.id.options_clear: mDisplay.setText(null); return true; case R.id.options_exit: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onDestroy() { if (mRegisterTask != null) { mRegisterTask.cancel(true); } unregisterReceiver(mHandleMessageReceiver); GCMRegistrar.onDestroy(this); super.onDestroy(); } private void checkNotNull(Object reference, String name) { if (reference == null) { throw new NullPointerException( getString(R.string.error_config, name)); } } private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String newMessage = intent.getExtras().getString(EXTRA_MESSAGE); mDisplay.append(newMessage + "\n"); } }; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL; import static com.google.android.gcm.demo.app.CommonUtilities.TAG; import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage; import com.google.android.gcm.GCMRegistrar; import android.content.Context; import android.util.Log; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; /** * Helper class used to communicate with the demo server. */ public final class ServerUtilities { private static final int MAX_ATTEMPTS = 5; private static final int BACKOFF_MILLI_SECONDS = 2000; private static final Random random = new Random(); /** * Register this account/device pair within the server. * */ static void register(final Context context, final String regId) { Log.i(TAG, "registering device (regId = " + regId + ")"); String serverUrl = SERVER_URL + "/register"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000); // Once GCM returns a registration id, we need to register it in the // demo server. As the server might be down, we will retry it a couple // times. for (int i = 1; i <= MAX_ATTEMPTS; i++) { Log.d(TAG, "Attempt #" + i + " to register"); try { displayMessage(context, context.getString( R.string.server_registering, i, MAX_ATTEMPTS)); post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, true); String message = context.getString(R.string.server_registered); CommonUtilities.displayMessage(context, message); return; } catch (IOException e) { // Here we are simplifying and retrying on any error; in a real // application, it should retry only on unrecoverable errors // (like HTTP error code 503). Log.e(TAG, "Failed to register on attempt " + i + ":" + e); if (i == MAX_ATTEMPTS) { break; } try { Log.d(TAG, "Sleeping for " + backoff + " ms before retry"); Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. Log.d(TAG, "Thread interrupted: abort remaining retries!"); Thread.currentThread().interrupt(); return; } // increase backoff exponentially backoff *= 2; } } String message = context.getString(R.string.server_register_error, MAX_ATTEMPTS); CommonUtilities.displayMessage(context, message); } /** * Unregister this account/device pair within the server. */ static void unregister(final Context context, final String regId) { Log.i(TAG, "unregistering device (regId = " + regId + ")"); String serverUrl = SERVER_URL + "/unregister"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); try { post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, false); String message = context.getString(R.string.server_unregistered); CommonUtilities.displayMessage(context, message); } catch (IOException e) { // At this point the device is unregistered from GCM, but still // registered in the server. // We could try to unregister again, but it is not necessary: // if the server tries to send a message to the device, it will get // a "NotRegistered" error message and should unregister the device. String message = context.getString(R.string.server_unregister_error, e.getMessage()); CommonUtilities.displayMessage(context, message); } } /** * Issue a POST request to the server. * * @param endpoint POST address. * @param params request parameters. * * @throws IOException propagated from POST. */ private static void post(String endpoint, Map<String, String> params) throws IOException { URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=') .append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); Log.v(TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import android.content.Context; import android.content.Intent; /** * Helper class providing methods and constants common to other classes in the * app. */ public final class CommonUtilities { /** * Base URL of the Demo Server (such as http://my_host:8080/gcm-demo) */ static final String SERVER_URL = null; /** * Google API project id registered to use GCM. */ static final String SENDER_ID = null; /** * Tag used on log messages. */ static final String TAG = "GCMDemo"; /** * Intent used to display a message in the screen. */ static final String DISPLAY_MESSAGE_ACTION = "com.google.android.gcm.demo.app.DISPLAY_MESSAGE"; /** * Intent's extra that contains the message to be displayed. */ static final String EXTRA_MESSAGE = "message"; /** * Notifies UI to display a message. * <p> * This method is defined in the common helper because it's used both by * the UI and the background service. * * @param context application's context. * @param message message to be displayed. */ static void displayMessage(Context context, String message) { Intent intent = new Intent(DISPLAY_MESSAGE_ACTION); intent.putExtra(EXTRA_MESSAGE, message); context.sendBroadcast(intent); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID; import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.Log; import com.google.android.gcm.GCMBaseIntentService; /** * IntentService responsible for handling GCM messages. */ public class GCMIntentService extends GCMBaseIntentService { @SuppressWarnings("hiding") private static final String TAG = "GCMIntentService"; public GCMIntentService() { super(SENDER_ID); } @Override protected void onRegistered(Context context, String registrationId) { Log.i(TAG, "Device registered: regId = " + registrationId); displayMessage(context, getString(R.string.gcm_registered)); ServerUtilities.register(context, registrationId); } @Override protected void onUnregistered(Context context, String registrationId) { Log.i(TAG, "Device unregistered"); displayMessage(context, getString(R.string.gcm_unregistered)); ServerUtilities.unregister(context, registrationId); } @Override protected void onMessage(Context context, Intent intent) { Log.i(TAG, "Received message"); String message = getString(R.string.gcm_message); displayMessage(context, message); // notifies user generateNotification(context, message); } @Override protected void onDeletedMessages(Context context, int total) { Log.i(TAG, "Received deleted messages notification"); String message = getString(R.string.gcm_deleted, total); displayMessage(context, message); // notifies user generateNotification(context, message); } @Override public void onError(Context context, String errorId) { Log.i(TAG, "Received error: " + errorId); displayMessage(context, getString(R.string.gcm_error, errorId)); } @Override protected boolean onRecoverableError(Context context, String errorId) { // log message Log.i(TAG, "Received recoverable error: " + errorId); displayMessage(context, getString(R.string.gcm_recoverable_error, errorId)); return super.onRecoverableError(context, errorId); } /** * Issues a notification to inform the user that server has sent a message. */ private static void generateNotification(Context context, String message) { int icon = R.drawable.ic_stat_gcm; long when = System.currentTimeMillis(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(icon, message, when); String title = context.getString(R.string.app_name); Intent notificationIntent = new Intent(context, DemoActivity.class); // set intent so it does not start a new activity notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, title, message, intent); notification.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, notification); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds a new message to all registered devices. * <p> * This servlet is used just by the browser (i.e., not device). */ @SuppressWarnings("serial") public class SendAllMessagesServlet extends BaseServlet { /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { List<String> devices = Datastore.getDevices(); String status; if (devices.isEmpty()) { status = "Message ignored as there is no device registered!"; } else { Queue queue = QueueFactory.getQueue("gcm"); // NOTE: check below is for demonstration purposes; a real application // could always send a multicast, even for just one recipient if (devices.size() == 1) { // send a single message using plain post String device = devices.get(0); queue.add(withUrl("/send").param( SendMessageServlet.PARAMETER_DEVICE, device)); status = "Single message queued for registration id " + device; } else { // send a multicast message using JSON // must split in chunks of 1000 devices (GCM limit) int total = devices.size(); List<String> partialDevices = new ArrayList<String>(total); int counter = 0; int tasks = 0; for (String device : devices) { counter++; partialDevices.add(device); int partialSize = partialDevices.size(); if (partialSize == Datastore.MULTICAST_SIZE || counter == total) { String multicastKey = Datastore.createMulticast(partialDevices); logger.fine("Queuing " + partialSize + " devices on multicast " + multicastKey); TaskOptions taskOptions = TaskOptions.Builder .withUrl("/send") .param(SendMessageServlet.PARAMETER_MULTICAST, multicastKey) .method(Method.POST); queue.add(taskOptions); partialDevices.clear(); tasks++; } } status = "Queued tasks to send " + tasks + " multicast messages to " + total + " devices"; } } req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString()); getServletContext().getRequestDispatcher("/home").forward(req, resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that sends a message to a device. * <p> * This servlet is invoked by AppEngine's Push Queue mechanism. */ @SuppressWarnings("serial") public class SendMessageServlet extends BaseServlet { private static final String HEADER_QUEUE_COUNT = "X-AppEngine-TaskRetryCount"; private static final String HEADER_QUEUE_NAME = "X-AppEngine-QueueName"; private static final int MAX_RETRY = 3; static final String PARAMETER_DEVICE = "device"; static final String PARAMETER_MULTICAST = "multicastKey"; private Sender sender; @Override public void init(ServletConfig config) throws ServletException { super.init(config); sender = newSender(config); } /** * Creates the {@link Sender} based on the servlet settings. */ protected Sender newSender(ServletConfig config) { String key = (String) config.getServletContext() .getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); return new Sender(key); } /** * Indicates to App Engine that this task should be retried. */ private void retryTask(HttpServletResponse resp) { resp.setStatus(500); } /** * Indicates to App Engine that this task is done. */ private void taskDone(HttpServletResponse resp) { resp.setStatus(200); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (req.getHeader(HEADER_QUEUE_NAME) == null) { throw new IOException("Missing header " + HEADER_QUEUE_NAME); } String retryCountHeader = req.getHeader(HEADER_QUEUE_COUNT); logger.fine("retry count: " + retryCountHeader); if (retryCountHeader != null) { int retryCount = Integer.parseInt(retryCountHeader); if (retryCount > MAX_RETRY) { logger.severe("Too many retries, dropping task"); taskDone(resp); return; } } String regId = req.getParameter(PARAMETER_DEVICE); if (regId != null) { sendSingleMessage(regId, resp); return; } String multicastKey = req.getParameter(PARAMETER_MULTICAST); if (multicastKey != null) { sendMulticastMessage(multicastKey, resp); return; } logger.severe("Invalid request!"); taskDone(resp); return; } private Message createMessage() { Message message = new Message.Builder().build(); return message; } private void sendSingleMessage(String regId, HttpServletResponse resp) { logger.info("Sending message to device " + regId); Message message = createMessage(); Result result; try { result = sender.sendNoRetry(message, regId); } catch (IOException e) { logger.log(Level.SEVERE, "Exception posting " + message, e); taskDone(resp); return; } if (result == null) { retryTask(resp); return; } if (result.getMessageId() != null) { logger.info("Succesfully sent message to device " + regId); String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { // same device has more than on registration id: update it logger.finest("canonicalRegId " + canonicalRegId); Datastore.updateRegistration(regId, canonicalRegId); } } else { String error = result.getErrorCodeName(); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it Datastore.unregister(regId); } else { logger.severe("Error sending message to device " + regId + ": " + error); } } } private void sendMulticastMessage(String multicastKey, HttpServletResponse resp) { // Recover registration ids from datastore List<String> regIds = Datastore.getMulticast(multicastKey); Message message = createMessage(); MulticastResult multicastResult; try { multicastResult = sender.sendNoRetry(message, regIds); } catch (IOException e) { logger.log(Level.SEVERE, "Exception posting " + message, e); multicastDone(resp, multicastKey); return; } boolean allDone = true; // check if any registration id must be updated if (multicastResult.getCanonicalIds() != 0) { List<Result> results = multicastResult.getResults(); for (int i = 0; i < results.size(); i++) { String canonicalRegId = results.get(i).getCanonicalRegistrationId(); if (canonicalRegId != null) { String regId = regIds.get(i); Datastore.updateRegistration(regId, canonicalRegId); } } } if (multicastResult.getFailure() != 0) { // there were failures, check if any could be retried List<Result> results = multicastResult.getResults(); List<String> retriableRegIds = new ArrayList<String>(); for (int i = 0; i < results.size(); i++) { String error = results.get(i).getErrorCodeName(); if (error != null) { String regId = regIds.get(i); logger.warning("Got error (" + error + ") for regId " + regId); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it Datastore.unregister(regId); } if (error.equals(Constants.ERROR_UNAVAILABLE)) { retriableRegIds.add(regId); } } } if (!retriableRegIds.isEmpty()) { // update task Datastore.updateMulticast(multicastKey, retriableRegIds); allDone = false; retryTask(resp); } } if (allDone) { multicastDone(resp, multicastKey); } else { retryTask(resp); } } private void multicastDone(HttpServletResponse resp, String encodedKey) { Datastore.deleteMulticast(encodedKey); taskDone(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION} with an * {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.unregister(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an * error or {@code unregistered} extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.register(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Transaction; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Logger; /** * Simple implementation of a data store using standard Java collections. * <p> * This class is neither persistent (it will lost the data when the app is * restarted) nor thread safe. */ public final class Datastore { static final int MULTICAST_SIZE = 1000; private static final String DEVICE_TYPE = "Device"; private static final String DEVICE_REG_ID_PROPERTY = "regId"; private static final String MULTICAST_TYPE = "Multicast"; private static final String MULTICAST_REG_IDS_PROPERTY = "regIds"; private static final FetchOptions DEFAULT_FETCH_OPTIONS = FetchOptions.Builder .withPrefetchSize(MULTICAST_SIZE).chunkSize(MULTICAST_SIZE); private static final Logger logger = Logger.getLogger(Datastore.class.getName()); private static final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); private Datastore() { throw new UnsupportedOperationException(); } /** * Registers a device. * * @param regId device's registration id. */ public static void register(String regId) { logger.info("Registering " + regId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity != null) { logger.fine(regId + " is already registered; ignoring."); return; } entity = new Entity(DEVICE_TYPE); entity.setProperty(DEVICE_REG_ID_PROPERTY, regId); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Unregisters a device. * * @param regId device's registration id. */ public static void unregister(String regId) { logger.info("Unregistering " + regId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity == null) { logger.warning("Device " + regId + " already unregistered"); } else { Key key = entity.getKey(); datastore.delete(key); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldId, String newId) { logger.info("Updating " + oldId + " to " + newId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(oldId); if (entity == null) { logger.warning("No device for registration id " + oldId); return; } entity.setProperty(DEVICE_REG_ID_PROPERTY, newId); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Gets all registered devices. */ public static List<String> getDevices() { List<String> devices; Transaction txn = datastore.beginTransaction(); try { Query query = new Query(DEVICE_TYPE); Iterable<Entity> entities = datastore.prepare(query).asIterable(DEFAULT_FETCH_OPTIONS); devices = new ArrayList<String>(); for (Entity entity : entities) { String device = (String) entity.getProperty(DEVICE_REG_ID_PROPERTY); devices.add(device); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return devices; } /** * Gets the number of total devices. */ public static int getTotalDevices() { Transaction txn = datastore.beginTransaction(); try { Query query = new Query(DEVICE_TYPE).setKeysOnly(); List<Entity> allKeys = datastore.prepare(query).asList(DEFAULT_FETCH_OPTIONS); int total = allKeys.size(); logger.fine("Total number of devices: " + total); txn.commit(); return total; } finally { if (txn.isActive()) { txn.rollback(); } } } private static Entity findDeviceByRegId(String regId) { Query query = new Query(DEVICE_TYPE) .addFilter(DEVICE_REG_ID_PROPERTY, FilterOperator.EQUAL, regId); PreparedQuery preparedQuery = datastore.prepare(query); List<Entity> entities = preparedQuery.asList(DEFAULT_FETCH_OPTIONS); Entity entity = null; if (!entities.isEmpty()) { entity = entities.get(0); } int size = entities.size(); if (size > 0) { logger.severe( "Found " + size + " entities for regId " + regId + ": " + entities); } return entity; } /** * Creates a persistent record with the devices to be notified using a * multicast message. * * @param devices registration ids of the devices. * @return encoded key for the persistent record. */ public static String createMulticast(List<String> devices) { logger.info("Storing multicast for " + devices.size() + " devices"); String encodedKey; Transaction txn = datastore.beginTransaction(); try { Entity entity = new Entity(MULTICAST_TYPE); entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); datastore.put(entity); Key key = entity.getKey(); encodedKey = KeyFactory.keyToString(key); logger.fine("multicast key: " + encodedKey); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return encodedKey; } /** * Gets a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. */ public static List<String> getMulticast(String encodedKey) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = datastore.beginTransaction(); try { entity = datastore.get(key); @SuppressWarnings("unchecked") List<String> devices = (List<String>) entity.getProperty(MULTICAST_REG_IDS_PROPERTY); txn.commit(); return devices; } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return Collections.emptyList(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. * @param devices new list of registration ids of the devices. */ public static void updateMulticast(String encodedKey, List<String> devices) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = datastore.beginTransaction(); try { try { entity = datastore.get(key); } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return; } entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Deletes a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. */ public static void deleteMulticast(String encodedKey) { Transaction txn = datastore.beginTransaction(); try { Key key = KeyFactory.stringToKey(encodedKey); datastore.delete(key); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. */ @SuppressWarnings("serial") abstract class BaseServlet extends HttpServlet { // change to true to allow GET calls static final boolean DEBUG = true; protected final Logger logger = Logger.getLogger(getClass().getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (DEBUG) { doPost(req, resp); } else { super.doGet(req, resp); } } protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { if (DEBUG) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.fine("parameters: " + parameters); } throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected String getParameter(HttpServletRequest req, String parameter, String defaultValue) { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { value = defaultValue; } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { setSuccess(resp, 0); } protected void setSuccess(HttpServletResponse resp, int size) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(size); } protected boolean isEmptyOrNull(String value) { return value == null || value.trim().length() == 0; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Context initializer that loads the API key from the App Engine datastore. */ public class ApiKeyInitializer implements ServletContextListener { static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String ENTITY_KIND = "Settings"; private static final String ENTITY_KEY = "MyKey"; private static final String ACCESS_KEY_FIELD = "ApiKey"; private final Logger logger = Logger.getLogger(getClass().getName()); public void contextInitialized(ServletContextEvent event) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); Entity entity; try { entity = datastore.get(key); } catch (EntityNotFoundException e) { entity = new Entity(key); // NOTE: it's not possible to change entities in the local server, so // it will be necessary to hardcode the API key below if you are running // it locally. entity.setProperty(ACCESS_KEY_FIELD, "replace_this_text_by_your_Simple_API_Access_key"); datastore.put(entity); logger.severe("Created fake key. Please go to App Engine admin " + "console, change its value to your API Key (the entity " + "type is '" + ENTITY_KIND + "' and its field to be changed is '" + ACCESS_KEY_FIELD + "'), then restart the server!"); } String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey); } public void contextDestroyed(ServletContextEvent event) { } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds display number of devices and button to send a message. * <p> * This servlet is used just by the browser (i.e., not device) and contains the * main page of the demo app. */ @SuppressWarnings("serial") public class HomeServlet extends BaseServlet { static final String ATTRIBUTE_STATUS = "status"; /** * Displays the existing messages and offer the option to send a new one. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head>"); out.print(" <title>GCM Demo</title>"); out.print(" <link rel='icon' href='favicon.png'/>"); out.print("</head>"); String status = (String) req.getAttribute(ATTRIBUTE_STATUS); if (status != null) { out.print(status); } int total = Datastore.getTotalDevices(); if (total == 0) { out.print("<h2>No devices registered!</h2>"); } else { out.print("<h2>" + total + " device(s) registered!</h2>"); out.print("<form name='form' method='POST' action='sendAll'>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); } out.print("</body></html>"); resp.setStatus(HttpServletResponse.SC_OK); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } }
Java
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /* * MOA.java * Copyright (C) 2009 University of Waikato, Hamilton, New Zealand * */ package weka.datagenerators.classifiers.classification; import weka.core.Instance; import weka.core.Instances; import weka.core.MOAUtils; import weka.core.Option; import weka.core.RevisionUtils; import weka.core.Utils; import weka.datagenerators.ClassificationGenerator; import java.util.Enumeration; import java.util.Random; import java.util.Vector; import moa.options.AbstractOptionHandler; import moa.options.ClassOption; import moa.streams.InstanceStream; import moa.streams.generators.LEDGenerator; /** <!-- globalinfo-start --> * A wrapper around MOA instance streams. * <p/> <!-- globalinfo-end --> * <!-- options-start --> * Valid options are: <p/> * * <pre> -h * Prints this help.</pre> * * <pre> -o &lt;file&gt; * The name of the output file, otherwise the generated data is * printed to stdout.</pre> * * <pre> -r &lt;name&gt; * The name of the relation.</pre> * * <pre> -d * Whether to print debug informations.</pre> * * <pre> -S * The seed for random function (default 1)</pre> * * <pre> -n &lt;num&gt; * The number of examples to generate (default 100)</pre> * * <pre> -B &lt;classname + options&gt; * The MOA stream generator. * (default: moa.streams.generators.LEDGenerator)</pre> * <!-- options-end --> * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class MOA extends ClassificationGenerator { /** for serialization. */ private static final long serialVersionUID = 13533833825026962L; /** the actual data generator. */ protected InstanceStream m_ActualGenerator = new LEDGenerator(); /** for manipulating the generator through the GUI. */ protected ClassOption m_Generator = new ClassOption("InstanceStream", 'B', "The MOA instance stream generator to use from within WEKA.", InstanceStream.class, m_ActualGenerator.getClass().getName()); /** * Returns a string describing this data generator. * * @return a description of the data generator suitable for * displaying in the explorer/experimenter gui */ public String globalInfo() { return "A wrapper around MOA instance streams."; } /** * Returns an enumeration describing the available options. * * @return an enumeration of all the available options */ public Enumeration listOptions() { Vector result = enumToVector(super.listOptions()); result.add(new Option( "\tThe MOA stream generator.\n" + "\t(default: " + MOAUtils.toCommandLine(new LEDGenerator()) + ")", "B", 1, "-B <classname + options>")); return result.elements(); } /** * Parses a list of options for this object. <p/> * <!-- options-start --> * Valid options are: <p/> * * <pre> -h * Prints this help.</pre> * * <pre> -o &lt;file&gt; * The name of the output file, otherwise the generated data is * printed to stdout.</pre> * * <pre> -r &lt;name&gt; * The name of the relation.</pre> * * <pre> -d * Whether to print debug informations.</pre> * * <pre> -S * The seed for random function (default 1)</pre> * * <pre> -n &lt;num&gt; * The number of examples to generate (default 100)</pre> * * <pre> -B &lt;classname + options&gt; * The MOA stream generator. * (default: moa.streams.generators.LEDGenerator)</pre> * <!-- options-end --> * * @param options the list of options as an array of strings * @throws Exception if an option is not supported */ public void setOptions(String[] options) throws Exception { String tmpStr; ClassOption option; tmpStr = Utils.getOption('B', options); option = (ClassOption) m_Generator.copy(); if (tmpStr.length() == 0) option.setCurrentObject(new LEDGenerator()); else option.setCurrentObject(MOAUtils.fromCommandLine(m_Generator, tmpStr)); setGenerator(option); super.setOptions(options); } /** * Gets the current settings of the datagenerator. * * @return an array of strings suitable for passing to setOptions */ public String[] getOptions() { Vector<String> result; String[] options; int i; result = new Vector<String>(); result.add("-B"); result.add(MOAUtils.toCommandLine(m_ActualGenerator)); options = super.getOptions(); for (i = 0; i < options.length; i++) result.add(options[i]); return result.toArray(new String[result.size()]); } /** * Sets the MOA stream generator to use. * * @param value the stream generator to use */ public void setGenerator(ClassOption value) { m_Generator = value; m_ActualGenerator = (InstanceStream) MOAUtils.fromOption(m_Generator); } /** * Returns the current MOA stream generator in use. * * @return the stream generator in use */ public ClassOption getGenerator() { return m_Generator; } /** * Returns the tooltip displayed in the GUI. * * @return the tooltip */ public String generatorTipText() { return "The MOA stream generator to use."; } /** * Return if single mode is set for the given data generator * mode depends on option setting and or generator type. * * @return single mode flag, always true * @throws Exception if mode is not set yet */ public boolean getSingleModeFlag() throws Exception { return true; } /** * Initializes the format for the dataset produced. * * @return the format for the dataset * @throws Exception if the generating of the format failed */ public Instances defineDataFormat() throws Exception { int numExamples; m_ActualGenerator = (InstanceStream) MOAUtils.fromOption(m_Generator); ((AbstractOptionHandler) m_ActualGenerator).prepareForUse(); m_DatasetFormat = new Instances(m_ActualGenerator.getHeader()); // determine number of instances to generate numExamples = getNumExamples(); if (m_ActualGenerator.estimatedRemainingInstances() != -1) { if (m_ActualGenerator.estimatedRemainingInstances() < numExamples) numExamples = (int) m_ActualGenerator.estimatedRemainingInstances(); } setNumExamplesAct(numExamples); return m_DatasetFormat; } /** * Generates one example of the dataset. * * @return the generated example, null if no further example available * @throws Exception if the format of the dataset is not yet defined * @throws Exception if the generator only works with generateExamples * which means in non single mode */ public Instance generateExample() throws Exception { if (m_ActualGenerator.hasMoreInstances()) return m_ActualGenerator.nextInstance(); else return null; } /** * Generates all examples of the dataset. Re-initializes the random number * generator with the given seed, before generating instances. * * @return the generated dataset * @throws Exception if the format of the dataset is not yet defined * @throws Exception if the generator only works with generateExample, * which means in single mode * @see #getSeed() */ public Instances generateExamples() throws Exception { Instances result; Instance inst; int i; result = new Instances(m_DatasetFormat, 0); m_Random = new Random(getSeed()); for (i = 0; i < getNumExamplesAct(); i++) { inst = generateExample(); if (inst != null) result.add(inst); else break; } return result; } /** * Generates a comment string that documentates the data generator. * By default this string is added at the beginning of the produced output * as ARFF file type, next after the options. * * @return string contains info about the generated rules */ public String generateStart () { return ""; } /** * Generates a comment string that documentats the data generator. * By default this string is added at the end of theproduces output * as ARFF file type. * * @return string contains info about the generated rules * @throws Exception if the generating of the documentaion fails */ public String generateFinished() throws Exception { return ""; } /** * Returns the revision string. * * @return the revision */ public String getRevision() { return RevisionUtils.extract("$Revision$"); } /** * Main method for executing this class. * * @param args should contain arguments for the data producer: */ public static void main(String[] args) { runDataGenerator(new MOA(), args); } }
Java
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /* * MOA.java * Copyright (C) 2009 University of Waikato, Hamilton, New Zealand */ package weka.classifiers.meta; import weka.classifiers.UpdateableClassifier; import weka.core.Capabilities; import weka.core.Instance; import weka.core.Instances; import weka.core.MOAUtils; import weka.core.Option; import weka.core.RevisionUtils; import weka.core.Utils; import weka.core.Capabilities.Capability; import java.util.Enumeration; import java.util.Vector; import moa.classifiers.Classifier; import moa.classifiers.trees.DecisionStump; import moa.options.ClassOption; /** <!-- globalinfo-start --> * Wrapper for MOA classifiers.<br/> * <br/> * Since MOA doesn't offer a mechanism to query a classifier for the types of attributes and classes it can handle, the capabilities of this wrapper are hard-coded: nominal and numeric attributes and only nominal class attributes are allowed. * <p/> <!-- globalinfo-end --> * <!-- options-start --> * Valid options are: <p/> * * <pre> -B &lt;classname + options&gt; * The MOA classifier to use. * (default: moa.classifiers.DecisionStump)</pre> * * <pre> -D * If set, classifier is run in debug mode and * may output additional info to the console</pre> * <!-- options-end --> * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class MOA extends weka.classifiers.AbstractClassifier implements UpdateableClassifier { /** for serialization. */ private static final long serialVersionUID = 2605797948130310166L; /** the actual moa classifier to use for learning. */ protected Classifier m_ActualClassifier = new DecisionStump(); /** the moa classifier option (this object is used in the GenericObjectEditor). */ protected ClassOption m_Classifier = new ClassOption( "classifier", 'B', "The MOA classifier to use from within WEKA.", Classifier.class, m_ActualClassifier.getClass().getName().replace("moa.classifiers.", ""), m_ActualClassifier.getClass().getName()); /** * Returns a string describing the classifier. * * @return a description suitable for * displaying in the explorer/experimenter gui */ public String globalInfo() { return "Wrapper for MOA classifiers.\n\n" + "Since MOA doesn't offer a mechanism to query a classifier for the " + "types of attributes and classes it can handle, the capabilities of " + "this wrapper are hard-coded: nominal and numeric attributes and " + "only nominal class attributes are allowed."; } /** * Returns an enumeration describing the available options. * * @return an enumeration of all the available options. */ public Enumeration listOptions() { Vector result = new Vector(); result.addElement(new Option( "\tThe MOA classifier to use.\n" + "\t(default: " + MOAUtils.toCommandLine(new DecisionStump()) + ")", "B", 1, "-B <classname + options>")); Enumeration en = super.listOptions(); while (en.hasMoreElements()) result.addElement(en.nextElement()); return result.elements(); } /** * Parses a given list of options. <p/> * <!-- options-start --> * Valid options are: <p/> * * <pre> -B &lt;classname + options&gt; * The MOA classifier to use. * (default: moa.classifiers.trees.DecisionStump)</pre> * * <pre> -D * If set, classifier is run in debug mode and * may output additional info to the console</pre> * <!-- options-end --> * * @param options the list of options as an array of strings * @throws Exception if an option is not supported */ public void setOptions(String[] options) throws Exception { String tmpStr; ClassOption option; tmpStr = Utils.getOption('B', options); option = (ClassOption) m_Classifier.copy(); if (tmpStr.length() == 0) option.setCurrentObject(new DecisionStump()); else option.setCurrentObject(MOAUtils.fromCommandLine(m_Classifier, tmpStr)); setClassifier(option); super.setOptions(options); } /** * Gets the current settings of the Classifier. * * @return an array of strings suitable for passing to setOptions */ public String[] getOptions() { Vector<String> result; String[] options; int i; result = new Vector<String>(); result.add("-B"); result.add(MOAUtils.toCommandLine(m_ActualClassifier)); options = super.getOptions(); for (i = 0; i < options.length; i++) result.add(options[i]); return result.toArray(new String[result.size()]); } /** * Sets the MOA classifier to use. * * @param value the classifier to use */ public void setClassifier(ClassOption value) { m_Classifier = value; m_ActualClassifier = (Classifier) MOAUtils.fromOption(m_Classifier); } /** * Returns the current MOA classifier in use. * * @return the classifier in use */ public ClassOption getClassifier() { return m_Classifier; } /** * Returns the tooltip displayed in the GUI. * * @return the tooltip */ public String classifierTipText() { return "The MOA classifier to use."; } /** * Returns the Capabilities of this classifier. Maximally permissive * capabilities are allowed by default. MOA doesn't specify what * * @return the capabilities of this object * @see Capabilities */ public Capabilities getCapabilities() { Capabilities result = new Capabilities(this); // attributes result.enable(Capability.NOMINAL_ATTRIBUTES); result.enable(Capability.NUMERIC_ATTRIBUTES); result.enable(Capability.MISSING_VALUES); // class result.enable(Capability.NOMINAL_CLASS); result.enable(Capability.MISSING_CLASS_VALUES); result.setMinimumNumberInstances(0); return result; } /** * Generates a classifier. * * @param data set of instances serving as training data * @throws Exception if the classifier has not been * generated successfully */ public void buildClassifier(Instances data) throws Exception { getCapabilities().testWithFail(data); data = new Instances(data); data.deleteWithMissingClass(); m_ActualClassifier.resetLearning(); for (int i = 0; i < data.numInstances(); i++) updateClassifier(data.instance(i)); } /** * Updates a classifier using the given instance. * * @param instance the instance to included * @throws Exception if instance could not be incorporated * successfully */ public void updateClassifier(Instance instance) throws Exception { m_ActualClassifier.trainOnInstance(instance); } /** * Predicts the class memberships for a given instance. If * an instance is unclassified, the returned array elements * must be all zero. If the class is numeric, the array * must consist of only one element, which contains the * predicted value. * * @param instance the instance to be classified * @return an array containing the estimated membership * probabilities of the test instance in each class * or the numeric prediction * @throws Exception if distribution could not be * computed successfully */ public double[] distributionForInstance(Instance instance) throws Exception { double[] result; result = m_ActualClassifier.getVotesForInstance(instance); // ensure that the array has as many elements as there are // class values! if (result.length < instance.numClasses()) { double[] newResult = new double[instance.numClasses()]; System.arraycopy(result, 0, newResult, 0, result.length); result = newResult; } try { Utils.normalize(result); } catch (Exception e) { result = new double[instance.numClasses()]; } return result; } /** * Returns the revision string. * * @return the revision */ public String getRevision() { return RevisionUtils.extract("$Revision$"); } /** * Returns a string representation of the model. * * @return the string representation */ public String toString() { StringBuilder result; result = new StringBuilder(); m_ActualClassifier.getDescription(result, 0); return result.toString(); } /** * Main method for testing this class. * * @param args the options */ public static void main(String [] args) { runClassifier(new MOA(), args); } }
Java
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /* * MOAUtils.java * Copyright (C) 2009 University of Waikato, Hamilton, New Zealand */ package weka.core; import moa.MOAObject; import moa.options.AbstractOptionHandler; import moa.options.ClassOption; /** * A helper class for MOA related classes. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class MOAUtils { /** * Turns a commandline into an object (classname + optional options). * * @param option the corresponding class option * @param commandline the commandline to turn into an object * @return the generated oblect */ public static MOAObject fromCommandLine(ClassOption option, String commandline) { return fromCommandLine(option.getRequiredType(), commandline); } /** * Turns a commandline into an object (classname + optional options). * * @param requiredType the required class * @param commandline the commandline to turn into an object * @return the generated oblect */ public static MOAObject fromCommandLine(Class requiredType, String commandline) { MOAObject result; String[] tmpOptions; String classname; try { tmpOptions = Utils.splitOptions(commandline); classname = tmpOptions[0]; tmpOptions[0] = ""; try { result = (MOAObject) Class.forName(classname).newInstance(); } catch (Exception e) { // try to prepend package name result = (MOAObject) Class.forName(requiredType.getPackage().getName() + "." + classname).newInstance(); } if (result instanceof AbstractOptionHandler) { ((AbstractOptionHandler) result).getOptions().setViaCLIString(Utils.joinOptions(tmpOptions)); ((AbstractOptionHandler) result).prepareForUse(); } } catch (Exception e) { e.printStackTrace(); result = null; } return result; } /** * Creates a MOA object from the specified class option. * * @param option the option to build the object from * @return the created object */ public static MOAObject fromOption(ClassOption option) { return MOAUtils.fromCommandLine(option.getRequiredType(), option.getValueAsCLIString()); } /** * Returs the commandline for the given object. If the object is not * derived from AbstractOptionHandler, then only the classname. Otherwise * the classname and the options are returned. * * @param obj the object to generate the commandline for * @return the commandline */ public static String toCommandLine(MOAObject obj) { String result = obj.getClass().getName(); if (obj instanceof AbstractOptionHandler) result += " " + ((AbstractOptionHandler) obj).getOptions().getAsCLIString(); return result.trim(); } }
Java
/* * MOAClassOptionEditor.java * Copyright (C) 2009 University of Waikato, Hamilton, New Zealand */ package weka.gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Rectangle; import java.beans.PropertyEditorSupport; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import moa.gui.ClassOptionEditComponent; import moa.options.ClassOption; /** * An editor for MOA ClassOption objects. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ * @see ClassOption */ public class MOAClassOptionEditor extends PropertyEditorSupport { /** the custom editor. */ protected Component m_CustomEditor; /** the component for editing. */ protected ClassOptionEditComponent m_EditComponent; /** * Returns true since this editor is paintable. * * @return always true. */ public boolean isPaintable() { return false; } /** * Returns true because we do support a custom editor. * * @return always true */ public boolean supportsCustomEditor() { return true; } /** * Closes the dialog. */ protected void closeDialog() { if (m_CustomEditor instanceof Container) { Dialog dlg = PropertyDialog.getParentDialog((Container) m_CustomEditor); if (dlg != null) dlg.setVisible(false); } } /** * Creates the custom editor. * * @return the editor */ protected Component createCustomEditor() { JPanel panel; panel = new JPanel(new BorderLayout()); panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); m_EditComponent = (ClassOptionEditComponent) ((ClassOption) getValue()).getEditComponent(); m_EditComponent.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { m_EditComponent.applyState(); setValue(m_EditComponent.getEditedOption()); } }); panel.add(m_EditComponent, BorderLayout.CENTER); return panel; } /** * Gets the custom editor component. * * @return the editor */ public Component getCustomEditor() { if (m_CustomEditor == null) m_CustomEditor = createCustomEditor(); return m_CustomEditor; } /** * Paints a representation of the current Object. * * @param gfx the graphics context to use * @param box the area we are allowed to paint into */ public void paintValue(Graphics gfx, Rectangle box) { FontMetrics fm; int vpad; String val; fm = gfx.getFontMetrics(); vpad = (box.height - fm.getHeight()) / 2 ; val = ((ClassOption) getValue()).getValueAsCLIString(); gfx.drawString(val, 2, fm.getHeight() + vpad); } }
Java
/* * F1.java * Copyright (C) 2010 RWTH Aachen University, Germany * @author Jansen (moa@cs.rwth-aachen.de) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package moa.evaluation; import java.util.ArrayList; import moa.cluster.Clustering; import moa.gui.visualization.DataPoint; public class F1 extends MeasureCollection{ @Override protected String[] getNames() { String[] names = {"F1-P","F1-R","Purity"}; return names; } // @Override // protected boolean[] getDefaultEnabled() { // boolean [] defaults = {false, false, false}; // return defaults; // } public void evaluateClustering(Clustering clustering, Clustering trueClustering, ArrayList<DataPoint> points) { if (clustering.size()<0){ addValue(0,0); addValue(1,0); return; } MembershipMatrix mm = new MembershipMatrix(clustering, points); //System.out.println(mm.toString()); int numClasses = mm.getNumClasses(); if(mm.hasNoiseClass()) numClasses--; //F1 as defined in P3C, try using F1 optimization double F1_P = 0.0; double purity = 0; int realClusters = 0; for (int i = 0; i < clustering.size(); i++) { int max_weight = 0; int max_weight_index = -1; //find max index for (int j = 0; j < numClasses; j++) { if(mm.getClusterClassWeight(i, j) > max_weight){ max_weight = mm.getClusterClassWeight(i, j); max_weight_index = j; } } if(max_weight_index!=-1){ realClusters++; double precision = mm.getClusterClassWeight(i, max_weight_index)/(double)mm.getClusterSum(i); double recall = mm.getClusterClassWeight(i, max_weight_index)/(double) mm.getClassSum(max_weight_index); double f1 = 0; if(precision > 0 || recall > 0){ f1 = 2*precision*recall/(precision+recall); } F1_P += f1; purity += precision; //TODO should we move setMeasure stuff into the Cluster interface? clustering.get(i).setMeasureValue("F1-P", Double.toString(f1)); } } if(realClusters > 0){ F1_P/=realClusters; purity/=realClusters; } addValue("F1-P",F1_P); addValue("Purity",purity); //F1 as defined in .... mainly maximizes F1 for each class double F1_R = 0.0; for (int j = 0; j < numClasses; j++) { double max_f1 = 0; for (int i = 0; i < clustering.size(); i++) { double precision = mm.getClusterClassWeight(i, j)/(double)mm.getClusterSum(i); double recall = mm.getClusterClassWeight(i, j)/(double)mm.getClassSum(j); double f1 = 0; if(precision > 0 || recall > 0){ f1 = 2*precision*recall/(precision+recall); } if(max_f1 < f1){ max_f1 = f1; } } F1_R+= max_f1; } F1_R/=numClasses; addValue("F1-R",F1_R); } }
Java
/* * ClusteringEvalPanel.java * Copyright (C) 2010 RWTH Aachen University, Germany * @author Jansen (moa@cs.rwth-aachen.de) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package moa.evaluation; /** * Classification Measure Collection interface that it is used to not appear in clustering */ public interface ClassificationMeasureCollection { }
Java
/* * EWMAClassificationPerformanceEvaluator.java * Copyright (C) 2007 University of Waikato, Hamilton, New Zealand * @author Albert Bifet (abifet at cs dot waikato dot ac dot nz) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package moa.evaluation; import moa.core.Measurement; import moa.core.ObjectRepository; import moa.options.FloatOption; import moa.options.AbstractOptionHandler; import moa.tasks.TaskMonitor; import weka.core.Instance; import weka.core.Utils; /** * Classification evaluator that updates evaluation results using an Exponential Weighted Moving Average. * * @author Albert Bifet (abifet at cs dot waikato dot ac dot nz) * @version $Revision: 7 $ */ public class EWMAClassificationPerformanceEvaluator extends AbstractOptionHandler implements ClassificationPerformanceEvaluator { private static final long serialVersionUID = 1L; protected double TotalweightObserved; public FloatOption alphaOption = new FloatOption("alpha", 'a', "Fading factor or exponential smoothing factor", .01); protected Estimator weightCorrect; protected class Estimator { protected double alpha; protected double estimation; public Estimator(double a) { alpha = a; estimation = 0; } public void add(double value) { estimation += alpha * (value - estimation); } public double estimation() { return estimation; } } /* public void setalpha(double a) { this.alpha = a; reset(); }*/ @Override public void reset() { weightCorrect = new Estimator(this.alphaOption.getValue()); } @Override public void addResult(Instance inst, double[] classVotes) { double weight = inst.weight(); int trueClass = (int) inst.classValue(); if (weight > 0.0) { this.TotalweightObserved += weight; if (Utils.maxIndex(classVotes) == trueClass) { this.weightCorrect.add(1); } else { this.weightCorrect.add(0); } } } /*public void addClassificationAttempt(int trueClass, double[] classVotes, double weight) { if (weight > 0.0) { this.TotalweightObserved += weight; if (Utils.maxIndex(classVotes) == trueClass) { this.weightCorrect.add(1); } else this.weightCorrect.add(0); } }*/ @Override public Measurement[] getPerformanceMeasurements() { return new Measurement[]{ new Measurement("classified instances", this.TotalweightObserved), new Measurement("classifications correct (percent)", getFractionCorrectlyClassified() * 100.0)}; } public double getTotalWeightObserved() { return this.TotalweightObserved; } public double getFractionCorrectlyClassified() { return this.weightCorrect.estimation(); } public double getFractionIncorrectlyClassified() { return 1.0 - getFractionCorrectlyClassified(); } @Override public void getDescription(StringBuilder sb, int indent) { Measurement.getMeasurementsDescription(getPerformanceMeasurements(), sb, indent); } @Override public void prepareForUseImpl(TaskMonitor monitor, ObjectRepository repository) { reset(); } }
Java
/* * BasicClusteringPerformanceEvaluator.java * Copyright (C) 2009 University of Waikato, Hamilton, New Zealand * @author Albert Bifet (abifet at cs dot waikato dot ac dot nz) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package moa.evaluation; import moa.AbstractMOAObject; import moa.core.Measurement; import weka.core.Utils; /** * Clustering evaluator that performs basic incremental evaluation. * * @author Albert Bifet (abifet at cs dot waikato dot ac dot nz) * @version $Revision: 7 $ */ public class BasicClusteringPerformanceEvaluator extends AbstractMOAObject implements LearningPerformanceEvaluator { private static final long serialVersionUID = 1L; protected double weightObserved; protected double weightCorrect; @Override public void reset() { this.weightObserved = 0.0; this.weightCorrect = 0.0; } @Override public void addLearningAttempt(int trueClass, double[] classVotes, double weight) { if (weight > 0.0) { this.weightObserved += weight; if (Utils.maxIndex(classVotes) == trueClass) { this.weightCorrect += weight; } } } @Override public Measurement[] getPerformanceMeasurements() { return new Measurement[]{ new Measurement("instances", getTotalWeightObserved()) //,new Measurement("classifications correct (percent)", // getFractionCorrectlyClassified() * 100.0) }; } public double getTotalWeightObserved() { return this.weightObserved; } public double getFractionCorrectlyClassified() { return this.weightObserved > 0.0 ? this.weightCorrect / this.weightObserved : 0.0; } public double getFractionIncorrectlyClassified() { return 1.0 - getFractionCorrectlyClassified(); } @Override public void getDescription(StringBuilder sb, int indent) { Measurement.getMeasurementsDescription(getPerformanceMeasurements(), sb, indent); } }
Java
/* * OutlierPerformance.java * Copyright (C) 2013 Aristotle University of Thessaloniki, Greece * @author D. Georgiadis, A. Gounaris, A. Papadopoulos, K. Tsichlas, Y. Manolopoulos * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package moa.evaluation; import java.util.ArrayList; import java.util.Arrays; import moa.cluster.Clustering; import moa.gui.visualization.DataPoint; public class OutlierPerformance extends MeasureCollection{ @Override protected String[] getNames() { String[] names = {"time per object","needed?###"}; return names; } @Override protected boolean[] getDefaultEnabled() { boolean [] defaults = {false, false}; return defaults; } @Override public void evaluateClustering(Clustering clustering, Clustering trueClustering, ArrayList<DataPoint> points) throws Exception { // nothing to do } public void addTimePerObject(double time) { addValue("time per object", time); } }
Java
/* * General.java * Copyright (C) 2010 RWTH Aachen University, Germany * @author Jansen (moa@cs.rwth-aachen.de) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package moa.evaluation; import java.util.ArrayList; import moa.cluster.Clustering; import moa.cluster.SphereCluster; import moa.gui.visualization.DataPoint; import weka.core.Instance; public class General extends MeasureCollection{ private int numPoints; private int numFClusters; private int numDims; private double pointInclusionProbThreshold = 0.8; private Clustering clustering; private ArrayList<DataPoint> points; public General() { super(); } @Override protected String[] getNames() { String[] names = {"GPrecision","GRecall","Redundancy","numCluster","numClasses"}; //String[] names = {"GPrecision","GRecall","Redundancy","Overlap","numCluster","numClasses","Compactness"}; return names; } // @Override // protected boolean[] getDefaultEnabled() { // boolean [] defaults = {false, false, false, false, false ,false}; // return defaults; // } @Override public void evaluateClustering(Clustering clustering, Clustering trueClustering, ArrayList<DataPoint> points) throws Exception{ this.points = points; this.clustering = clustering; numPoints = points.size(); numFClusters = clustering.size(); numDims = points.get(0).numAttributes()-1; int totalRedundancy = 0; int trueCoverage = 0; int totalCoverage = 0; int numNoise = 0; for (int p = 0; p < numPoints; p++) { int coverage = 0; for (int c = 0; c < numFClusters; c++) { //contained in cluster c? if(clustering.get(c).getInclusionProbability(points.get(p)) >= pointInclusionProbThreshold){ coverage++; } } if(points.get(p).classValue()==-1){ numNoise++; } else{ if(coverage>0) trueCoverage++; } if(coverage>0) totalCoverage++; //points covered by clustering (incl. noise) if(coverage>1) totalRedundancy++; //include noise } addValue("numCluster", clustering.size()); addValue("numClasses", trueClustering.size()); addValue("Redundancy", ((double)totalRedundancy/(double)numPoints)); addValue("GPrecision", (totalCoverage==0?0:((double)trueCoverage/(double)(totalCoverage)))); addValue("GRecall", ((double)trueCoverage/(double)(numPoints-numNoise))); // if(isEnabled(3)){ // addValue("Compactness", computeCompactness()); // } // if(isEnabled(3)){ // addValue("Overlap", computeOverlap()); // } } private double computeOverlap(){ for (int c = 0; c < numFClusters; c++) { if(!(clustering.get(c) instanceof SphereCluster)){ System.out.println("Overlap only supports Sphere Cluster. Found: "+clustering.get(c).getClass()); return Double.NaN; } } boolean[] overlap = new boolean[numFClusters]; for (int c0 = 0; c0 < numFClusters; c0++) { if(overlap[c0]) continue; SphereCluster s0 = (SphereCluster)clustering.get(c0); for (int c1 = c0; c1 < clustering.size(); c1++) { if(c1 == c0) continue; SphereCluster s1 = (SphereCluster)clustering.get(c1); if(s0.overlapRadiusDegree(s1) > 0){ overlap[c0] = overlap[c1] = true; } } } double totalOverlap = 0; for (int c0 = 0; c0 < numFClusters; c0++) { if(overlap[c0]) totalOverlap++; } // if(totalOverlap/(double)numFClusters > .8) RunVisualizer.pause(); if(numFClusters>0) totalOverlap/=(double)numFClusters; return totalOverlap; } private double computeCompactness(){ if(numFClusters == 0) return 0; for (int c = 0; c < numFClusters; c++) { if(!(clustering.get(c) instanceof SphereCluster)){ System.out.println("Compactness only supports Sphere Cluster. Found: "+clustering.get(c).getClass()); return Double.NaN; } } //TODO weight radius by number of dimensions double totalCompactness = 0; for (int c = 0; c < numFClusters; c++) { ArrayList<Instance> containedPoints = new ArrayList<Instance>(); for (int p = 0; p < numPoints; p++) { //p in c if(clustering.get(c).getInclusionProbability(points.get(p)) >= pointInclusionProbThreshold){ containedPoints.add(points.get(p)); } } double compactness = 0; if(containedPoints.size()>1){ //cluster not empty SphereCluster minEnclosingCluster = new SphereCluster(containedPoints, numDims); double minRadius = minEnclosingCluster.getRadius(); double cfRadius = ((SphereCluster)clustering.get(c)).getRadius(); if(Math.abs(minRadius-cfRadius) < 0.1e-10){ compactness = 1; } else if(minRadius < cfRadius) compactness = minRadius/cfRadius; else{ System.out.println("Optimal radius bigger then real one ("+(cfRadius-minRadius)+"), this is really wrong"); compactness = 1; } } else{ double cfRadius = ((SphereCluster)clustering.get(c)).getRadius(); if(cfRadius==0) compactness = 1; } //weight by weight of cluster??? totalCompactness+=compactness; clustering.get(c).setMeasureValue("Compactness", Double.toString(compactness)); } return (totalCompactness/numFClusters); } }
Java
/* * FadingFactorClassificationPerformanceEvaluator.java * Copyright (C) 2007 University of Waikato, Hamilton, New Zealand * @author Albert Bifet (abifet at cs dot waikato dot ac dot nz) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package moa.evaluation; import moa.core.Measurement; import moa.core.ObjectRepository; import moa.options.FloatOption; import moa.options.AbstractOptionHandler; import moa.tasks.TaskMonitor; import weka.core.Utils; import weka.core.Instance; /** * Classification evaluator that updates evaluation results using a fading factor. * * @author Albert Bifet (abifet at cs dot waikato dot ac dot nz) * @version $Revision: 7 $ */ public class FadingFactorClassificationPerformanceEvaluator extends AbstractOptionHandler implements ClassificationPerformanceEvaluator { private static final long serialVersionUID = 1L; protected double TotalweightObserved; public FloatOption alphaOption = new FloatOption("alpha", 'a', "Fading factor or exponential smoothing factor", .999); protected Estimator weightCorrect; protected class Estimator { protected double alpha; protected double estimation; protected double b; public Estimator(double a) { alpha = a; estimation = 0.0; b = 0.0; } public void add(double value) { estimation = alpha * estimation + value; b = alpha * b + 1.0; } public double estimation() { return b > 0.0 ? estimation / b : 0; } } /* public void setalpha(double a) { this.alpha = a; reset(); }*/ @Override public void reset() { weightCorrect = new Estimator(this.alphaOption.getValue()); } /*public void addClassificationAttempt(int trueClass, double[] classVotes, double weight) { if (weight > 0.0) { this.TotalweightObserved += weight; if (Utils.maxIndex(classVotes) == trueClass) { this.weightCorrect.add(1); } else this.weightCorrect.add(0); } }*/ @Override public void addResult(Instance inst, double[] classVotes) { double weight = inst.weight(); int trueClass = (int) inst.classValue(); if (weight > 0.0) { this.TotalweightObserved += weight; if (Utils.maxIndex(classVotes) == trueClass) { this.weightCorrect.add(1); } else { this.weightCorrect.add(0); } } } @Override public Measurement[] getPerformanceMeasurements() { return new Measurement[]{ new Measurement("classified instances", this.TotalweightObserved), new Measurement("classifications correct (percent)", getFractionCorrectlyClassified() * 100.0)}; } public double getTotalWeightObserved() { return this.TotalweightObserved; } public double getFractionCorrectlyClassified() { return this.weightCorrect.estimation(); } public double getFractionIncorrectlyClassified() { return 1.0 - getFractionCorrectlyClassified(); } @Override public void getDescription(StringBuilder sb, int indent) { Measurement.getMeasurementsDescription(getPerformanceMeasurements(), sb, indent); } @Override public void prepareForUseImpl(TaskMonitor monitor, ObjectRepository repository) { reset(); } }
Java
/* * LearningEvaluation.java * Copyright (C) 2007 University of Waikato, Hamilton, New Zealand * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package moa.evaluation; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import moa.AbstractMOAObject; import moa.classifiers.Classifier; import moa.clusterers.Clusterer; import moa.core.Measurement; /** * Class that stores an array of evaluation measurements. * * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @version $Revision: 7 $ */ public class LearningEvaluation extends AbstractMOAObject { private static final long serialVersionUID = 1L; protected Measurement[] measurements; public LearningEvaluation(Measurement[] measurements) { this.measurements = measurements.clone(); } public LearningEvaluation(Measurement[] evaluationMeasurements, ClassificationPerformanceEvaluator cpe, Classifier model) { List<Measurement> measurementList = new LinkedList<Measurement>(); if (evaluationMeasurements != null){ measurementList.addAll(Arrays.asList(evaluationMeasurements)); } measurementList.addAll(Arrays.asList(cpe.getPerformanceMeasurements())); measurementList.addAll(Arrays.asList(model.getModelMeasurements())); this.measurements = measurementList.toArray(new Measurement[measurementList.size()]); } public LearningEvaluation( ClassificationPerformanceEvaluator cpe, Classifier model) { this(null,cpe,model); } // Must change to Learner model public LearningEvaluation(Measurement[] evaluationMeasurements, LearningPerformanceEvaluator cpe, Clusterer model) { List<Measurement> measurementList = new LinkedList<Measurement>(); measurementList.addAll(Arrays.asList(evaluationMeasurements)); measurementList.addAll(Arrays.asList(cpe.getPerformanceMeasurements())); measurementList.addAll(Arrays.asList(model.getModelMeasurements())); this.measurements = measurementList.toArray(new Measurement[measurementList.size()]); } public Measurement[] getMeasurements() { return this.measurements.clone(); } @Override public void getDescription(StringBuilder sb, int indent) { Measurement.getMeasurementsDescription(this.measurements, sb, indent); } }
Java
/* * EntropyCollection.java * Copyright (C) 2010 RWTH Aachen University, Germany * @author Jansen (moa@cs.rwth-aachen.de) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package moa.evaluation; import java.util.ArrayList; import moa.cluster.Clustering; import moa.gui.visualization.DataPoint; public class EntropyCollection extends MeasureCollection{ private boolean debug = false; private final double beta = 1; @Override protected String[] getNames() { String[] names = {"GT cross entropy","FC cross entropy","Homogeneity","Completeness","V-Measure","VarInformation"}; return names; } @Override protected boolean[] getDefaultEnabled() { boolean [] defaults = {false, false, false, false, false, false}; return defaults; } @Override public void evaluateClustering(Clustering fclustering, Clustering hClustering, ArrayList<DataPoint> points) throws Exception { MembershipMatrix mm = new MembershipMatrix(fclustering, points); int numClasses = mm.getNumClasses(); int numCluster = fclustering.size()+1; int n = mm.getTotalEntries(); double FCentropy = 0; if(numCluster > 1){ for (int fc = 0; fc < numCluster; fc++){ double weight = mm.getClusterSum(fc)/(double)n; if(weight > 0) FCentropy+= weight * Math.log10(weight); } FCentropy/=(-1*Math.log10(numCluster)); } if(debug){ System.out.println("FC entropy "+FCentropy); } double GTentropy = 0; if(numClasses > 1){ for (int hc = 0; hc < numClasses; hc++){ double weight = mm.getClassSum(hc)/(double)n; if(weight > 0) GTentropy+= weight * Math.log10(weight); } GTentropy/=(-1*Math.log10(numClasses)); } if(debug){ System.out.println("GT entropy "+GTentropy); } //cluster based entropy double FCcrossEntropy = 0; for (int fc = 0; fc < numCluster; fc++){ double e = 0; int clusterWeight = mm.getClusterSum(fc); if(clusterWeight>0){ for (int hc = 0; hc < numClasses; hc++) { double p = mm.getClusterClassWeight(fc, hc)/(double)clusterWeight; if(p!=0){ e+=p * Math.log10(p); } } FCcrossEntropy+=((clusterWeight/(double)n) * e); } } if(numCluster > 1){ FCcrossEntropy/=-1*Math.log10(numCluster); } addValue("FC cross entropy", 1-FCcrossEntropy); if(debug){ System.out.println("FC cross entropy "+(1-FCcrossEntropy)); } //class based entropy double GTcrossEntropy = 0; for (int hc = 0; hc < numClasses; hc++){ double e = 0; int classWeight = mm.getClassSum(hc); if(classWeight>0){ for (int fc = 0; fc < numCluster; fc++) { double p = mm.getClusterClassWeight(fc, hc)/(double)classWeight; if(p!=0){ e+=p * Math.log10(p); } } } GTcrossEntropy+=((classWeight/(double)n) * e); } if(numClasses > 1) GTcrossEntropy/=-1*Math.log10(numClasses); addValue("GT cross entropy", 1-GTcrossEntropy); if(debug){ System.out.println("GT cross entropy "+(1-GTcrossEntropy)); } double homogeneity; if(FCentropy == 0) homogeneity = 1; else homogeneity = 1 - FCcrossEntropy/FCentropy; //TODO set err values for now, needs to be debugged if(homogeneity > 1 || homogeneity < 0) addValue("Homogeneity",-1); else addValue("Homogeneity",homogeneity); double completeness; if(GTentropy == 0) completeness = 1; else completeness = 1 - GTcrossEntropy/GTentropy; addValue("Completeness",completeness); double vmeasure = (1+beta)*homogeneity*completeness/(beta*homogeneity+completeness); if(vmeasure > 1 || homogeneity < 0) addValue("V-Measure",-1); else addValue("V-Measure",vmeasure); double mutual = 0; for (int i = 0; i < numCluster; i++){ for (int j = 0; j < numClasses; j++) { if(mm.getClusterClassWeight(i, j)==0) continue; double m = Math.log10(mm.getClusterClassWeight(i, j)/(double)mm.getClusterSum(i)/(double)mm.getClassSum(j)*(double)n); m*= mm.getClusterClassWeight(i, j)/(double)n; if(debug) System.out.println("("+j+"/"+ j + "): "+m); mutual+=m; } } if(numClasses > 1) mutual/=Math.log10(numClasses); double varInfo = 1; if(FCentropy + GTentropy > 0) varInfo = 2*mutual/(FCentropy + GTentropy); if(debug) System.out.println("mutual "+mutual+ " / VI "+varInfo); addValue("VarInformation", varInfo); } }
Java
/** * [CMM.java] * * CMM: Main class * * Reference: Kremer et al., "An Effective Evaluation Measure for Clustering on Evolving Data Streams", KDD, 2011 * * @author Timm jansen * Data Management and Data Exploration Group, RWTH Aachen University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package moa.evaluation; import java.util.ArrayList; import moa.cluster.Cluster; import moa.cluster.Clustering; import moa.cluster.SphereCluster; import moa.evaluation.CMM_GTAnalysis.CMMPoint; import moa.gui.visualization.DataPoint; public class CMM extends MeasureCollection{ private static final long serialVersionUID = 1L; /** * found clustering */ private Clustering clustering; /** * the ground truth analysis */ private CMM_GTAnalysis gtAnalysis; /** * number of points within the horizon */ private int numPoints; /** * number of clusters in the found clustering */ private int numFClusters; /** * number of cluster in the adjusted groundtruth clustering that * was calculated through the groundtruth analysis */ private int numGT0Classes; /** * match found clusters to GT clusters */ private int matchMap[]; /** * pointInclusionProbFC[p][C] contains the probability of point p * being included in cluster C */ private double[][] pointInclusionProbFC; /** * threshold that defines when a point is being considered belonging to a cluster */ private double pointInclusionProbThreshold = 0.5; /** * parameterize the error weight of missed points (default 1) */ private double lamdaMissed = 1; /** * enable/disable debug mode */ public boolean debug = false; /** * enable/disable class merge (main feature of ground truth analysis) */ public boolean enableClassMerge = true; /** * enable/disable model error * when enabled errors that are caused by the underling cluster model will not be counted */ public boolean enableModelError = true; @Override protected String[] getNames() { String[] names = {"CMM","CMM Basic","CMM Missed","CMM Misplaced","CMM Noise", "CA Seperability", "CA Noise", "CA Modell"}; return names; } @Override protected boolean[] getDefaultEnabled() { boolean [] defaults = {false, false, false, false, false, false, false, false}; return defaults; } @Override public void evaluateClustering(Clustering clustering, Clustering trueClustering, ArrayList<DataPoint> points) throws Exception{ this.clustering = clustering; numPoints = points.size(); numFClusters = clustering.size(); gtAnalysis = new CMM_GTAnalysis(trueClustering, points, enableClassMerge); numGT0Classes = gtAnalysis.getNumberOfGT0Classes(); addValue("CA Seperability",gtAnalysis.getClassSeparability()); addValue("CA Noise",gtAnalysis.getNoiseSeparability()); addValue("CA Modell",gtAnalysis.getModelQuality()); /* init the matching and point distances */ calculateMatching(); /* calculate the actual error */ calculateError(); } /** * calculates the CMM specific matching between found clusters and ground truth clusters */ private void calculateMatching(){ /** * found cluster frequencies */ int[][] mapFC = new int[numFClusters][numGT0Classes]; /** * ground truth cluster frequencies */ int[][] mapGT = new int[numGT0Classes][numGT0Classes]; int [] sumsFC = new int[numFClusters]; //calculate fuzzy mapping from pointInclusionProbFC = new double[numPoints][numFClusters]; for (int p = 0; p < numPoints; p++) { CMMPoint cmdp = gtAnalysis.getPoint(p); //found cluster frequencies for (int fc = 0; fc < numFClusters; fc++) { Cluster cl = clustering.get(fc); pointInclusionProbFC[p][fc] = cl.getInclusionProbability(cmdp); if (pointInclusionProbFC[p][fc] >= pointInclusionProbThreshold) { //make sure we don't count points twice that are contained in two merged clusters if(cmdp.isNoise()) continue; mapFC[fc][cmdp.workclass()]++; sumsFC[fc]++; } } //ground truth cluster frequencies if(!cmdp.isNoise()){ for(int hc = 0; hc < numGT0Classes;hc++){ if(hc == cmdp.workclass()){ mapGT[hc][hc]++; } else{ if(gtAnalysis.getGT0Cluster(hc).getInclusionProbability(cmdp) >= 1){ mapGT[hc][cmdp.workclass()]++; } } } } } //assign each found cluster to a hidden cluster matchMap = new int[numFClusters]; for (int fc = 0; fc < numFClusters; fc++) { int matchIndex = -1; //check if we only have one entry anyway for (int hc0 = 0; hc0 < numGT0Classes; hc0++) { if(mapFC[fc][hc0]!=0){ if(matchIndex == -1) matchIndex = hc0; else{ matchIndex = -1; break; } } } //more then one entry, so look for most similar frequency profile int minDiff = Integer.MAX_VALUE; if(sumsFC[fc]!=0 && matchIndex == -1){ ArrayList<Integer> fitCandidates = new ArrayList<Integer>(); for (int hc0 = 0; hc0 < numGT0Classes; hc0++) { int errDiff = 0; for (int hc1 = 0; hc1 < numGT0Classes; hc1++) { //fc profile doesn't fit into current hc profile double freq_diff = mapFC[fc][hc1] - mapGT[hc0][hc1]; if(freq_diff > 0){ errDiff+= freq_diff; } } if(errDiff == 0){ fitCandidates.add(hc0); } if(errDiff < minDiff){ minDiff = errDiff; matchIndex = hc0; } if(debug){ //System.out.println("FC"+fc+"("+Arrays.toString(mapFC[fc])+") - HC0_"+hc0+"("+Arrays.toString(mapGT[hc0])+"):"+errDiff); } } //if we have a fitting profile overwrite the min error choice //if we have multiple fit candidates, use majority vote of corresponding classes if(fitCandidates.size()!=0){ int bestGTfit = fitCandidates.get(0); for(int i = 1; i < fitCandidates.size(); i++){ int GTfit = fitCandidates.get(i); if(mapFC[fc][GTfit] > mapFC[fc][bestGTfit]) bestGTfit=fitCandidates.get(i); } matchIndex = bestGTfit; } } matchMap[fc] = matchIndex; int realMatch = -1; if(matchIndex==-1){ if(debug) System.out.println("No cluster match: needs to be implemented?"); } else{ realMatch = gtAnalysis.getGT0Cluster(matchMap[fc]).getLabel(); } clustering.get(fc).setMeasureValue("CMM Match", "C"+realMatch); clustering.get(fc).setMeasureValue("CMM Workclass", "C"+matchMap[fc]); } //print matching table if(debug){ for (int i = 0; i < numFClusters; i++) { System.out.print("C"+((int)clustering.get(i).getId()) + " N:"+((int)clustering.get(i).getWeight())+" | "); for (int j = 0; j < numGT0Classes; j++) { System.out.print(mapFC[i][j] + " "); } System.out.print(" = "+sumsFC[i] + " | "); String match = "-"; if (matchMap[i]!=-1) { match = Integer.toString(gtAnalysis.getGT0Cluster(matchMap[i]).getLabel()); } System.out.println(" --> " + match + "(work:"+matchMap[i]+")"); } } } /** * Calculate the actual error values */ private void calculateError(){ int totalErrorCount = 0; int totalRedundancy = 0; int trueCoverage = 0; int totalCoverage = 0; int numNoise = 0; double errorNoise = 0; double errorNoiseMax = 0; double errorMissed = 0; double errorMissedMax = 0; double errorMisplaced = 0; double errorMisplacedMax = 0; double totalError = 0.0; double totalErrorMax = 0.0; /** mainly iterate over all points and find the right error value for the point. * within the same run calculate various other stuff like coverage etc... */ for (int p = 0; p < numPoints; p++) { CMMPoint cmdp = gtAnalysis.getPoint(p); double weight = cmdp.weight(); //noise counter if(cmdp.isNoise()){ numNoise++; //this is always 1 errorNoiseMax+=cmdp.connectivity*weight; } else{ errorMissedMax+=cmdp.connectivity*weight; errorMisplacedMax+=cmdp.connectivity*weight; } //sum up maxError as the individual errors are the quality weighted between 0-1 totalErrorMax+=cmdp.connectivity*weight; double err = 0; int coverage = 0; //check every FCluster for (int c = 0; c < numFClusters; c++) { //contained in cluster c? if(pointInclusionProbFC[p][c] >= pointInclusionProbThreshold){ coverage++; if(!cmdp.isNoise()){ //PLACED CORRECTLY if(matchMap[c] == cmdp.workclass()){ } //MISPLACED else{ double errvalue = misplacedError(cmdp, c); if(errvalue > err) err = errvalue; } } else{ //NOISE double errvalue = noiseError(cmdp, c); if(errvalue > err) err = errvalue; } } } //not in any cluster if(coverage == 0){ //MISSED if(!cmdp.isNoise()){ err = missedError(cmdp,true); errorMissed+= weight*err; } //NOISE else{ } } else{ if(!cmdp.isNoise()){ errorMisplaced+= err*weight; } else{ errorNoise+= err*weight; } } /* processing of other evaluation values */ totalError+= err*weight; if(err!=0)totalErrorCount++; if(coverage>0) totalCoverage++; //points covered by clustering (incl. noise) if(coverage>0 && !cmdp.isNoise()) trueCoverage++; //points covered by clustering, don't count noise if(coverage>1) totalRedundancy++; //include noise cmdp.p.setMeasureValue("CMM",err); cmdp.p.setMeasureValue("Redundancy", coverage); } addValue("CMM", (totalErrorMax!=0)?1-totalError/totalErrorMax:1); addValue("CMM Missed", (errorMissedMax!=0)?1-errorMissed/errorMissedMax:1); addValue("CMM Misplaced", (errorMisplacedMax!=0)?1-errorMisplaced/errorMisplacedMax:1); addValue("CMM Noise", (errorNoiseMax!=0)?1-errorNoise/errorNoiseMax:1); addValue("CMM Basic", 1-((double)totalErrorCount/(double)numPoints)); if(debug){ System.out.println("-------------"); } } private double noiseError(CMMPoint cmdp, int assignedClusterID){ int gtAssignedID = matchMap[assignedClusterID]; double error; //Cluster wasn't matched, so just contains noise //TODO: Noiscluster? //also happens when we decrease the radius and there is only a noise point in the center if(gtAssignedID==-1){ error = 1; cmdp.p.setMeasureValue("CMM Type","noise - cluster"); } else{ if(enableModelError && gtAnalysis.getGT0Cluster(gtAssignedID).getInclusionProbability(cmdp) >= pointInclusionProbThreshold){ //set to MIN_ERROR so we can still track the error error = 0.00001; cmdp.p.setMeasureValue("CMM Type","noise - byModel"); } else{ error = 1 - gtAnalysis.getConnectionValue(cmdp, gtAssignedID); cmdp.p.setMeasureValue("CMM Type","noise"); } } return error; } private double missedError(CMMPoint cmdp, boolean useHullDistance){ cmdp.p.setMeasureValue("CMM Type","missed"); if(!useHullDistance){ return cmdp.connectivity; } else{ //main idea: look at relative distance of missed point to cluster double minHullDist = 1; for (int fc = 0; fc < numFClusters; fc++){ //if fc is mappend onto the class of the point, check it for its hulldist if(matchMap[fc]!=-1 && matchMap[fc] == cmdp.workclass()){ if(clustering.get(fc) instanceof SphereCluster){ SphereCluster sc = (SphereCluster)clustering.get(fc); double distanceFC = sc.getCenterDistance(cmdp); double radius = sc.getRadius(); double hullDist = (distanceFC-radius)/(distanceFC+radius); if(hullDist < minHullDist) minHullDist = hullDist; } else{ double min = 1; double max = 1; //TODO: distance for random shape //generate X points from the cluster with clustering.get(fc).sample(null) //and find Min and Max values double hullDist = min/max; if(hullDist < minHullDist) minHullDist = hullDist; } } } //use distance as weight if(minHullDist>1) minHullDist = 1; double weight = (1-Math.exp(-lamdaMissed*minHullDist)); cmdp.p.setMeasureValue("HullDistWeight",weight); return weight*cmdp.connectivity; } } private double misplacedError(CMMPoint cmdp, int assignedClusterID){ double weight = 0; int gtAssignedID = matchMap[assignedClusterID]; //TODO take care of noise cluster? if(gtAssignedID ==-1){ System.out.println("Point "+cmdp.getTimestamp()+" from gtcluster "+cmdp.trueClass+" assigned to noise cluster "+assignedClusterID); return 1; } if(gtAssignedID == cmdp.workclass()) return 0; else{ //assigned and real GT0 cluster are not connected, but does the model have the //chance of separating this point after all? if(enableModelError && gtAnalysis.getGT0Cluster(gtAssignedID).getInclusionProbability(cmdp) >= pointInclusionProbThreshold){ weight = 0; cmdp.p.setMeasureValue("CMM Type","missplaced - byModel"); } else{ //point was mapped onto wrong cluster (assigned), so check how far away //the nearest point is within the wrongly assigned cluster weight = 1 - gtAnalysis.getConnectionValue(cmdp, gtAssignedID); } } double err_value; //set to MIN_ERROR so we can still track the error if(weight == 0){ err_value= 0.00001; } else{ err_value = weight*cmdp.connectivity; cmdp.p.setMeasureValue("CMM Type","missplaced"); } return err_value; } public String getParameterString(){ String para = gtAnalysis.getParameterString(); para+="lambdaMissed="+lamdaMissed+";"; return para; } }
Java
/* * Accuracy.java * Copyright (C) 2010 RWTH Aachen University, Germany * @author Jansen (moa@cs.rwth-aachen.de) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package moa.evaluation; import java.util.ArrayList; import moa.cluster.Clustering; import moa.gui.visualization.DataPoint; public class Accuracy extends MeasureCollection implements ClassificationMeasureCollection{ private boolean debug = false; public Accuracy() { super(); } @Override public String[] getNames() { String[] names = {"Accuracy","Kappa","Kappa Temp","Ram-Hours","Time","Memory"}; return names; } @Override protected boolean[] getDefaultEnabled() { boolean[] defaults = {true, true, true, true, true, true}; return defaults; } public void evaluateClustering(Clustering clustering, Clustering trueClsutering, ArrayList<DataPoint> points) { } }
Java
/* * RegressionPerformanceEvaluator.java * Copyright (C) 2007 University of Waikato, Hamilton, New Zealand * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package moa.evaluation; /** * Interface implemented by learner evaluators to monitor * the results of the regression learning process. * * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @version $Revision: 7 $ */ public interface RegressionPerformanceEvaluator extends ClassificationPerformanceEvaluator { }
Java
/* * BasicClassificationPerformanceEvaluator.java * Copyright (C) 2007 University of Waikato, Hamilton, New Zealand * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @author Albert Bifet (abifet at cs dot waikato dot ac dot nz) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package moa.evaluation; import moa.AbstractMOAObject; import moa.core.Measurement; import weka.core.Utils; import weka.core.Instance; /** * Classification evaluator that performs basic incremental evaluation. * * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @author Albert Bifet (abifet at cs dot waikato dot ac dot nz) * @version $Revision: 7 $ */ public class BasicClassificationPerformanceEvaluator extends AbstractMOAObject implements ClassificationPerformanceEvaluator { private static final long serialVersionUID = 1L; protected double weightObserved; protected double weightCorrect; protected double[] columnKappa; protected double[] rowKappa; protected int numClasses; private double weightCorrectNoChangeClassifier; private int lastSeenClass; @Override public void reset() { reset(this.numClasses); } public void reset(int numClasses) { this.numClasses = numClasses; this.rowKappa = new double[numClasses]; this.columnKappa = new double[numClasses]; for (int i = 0; i < this.numClasses; i++) { this.rowKappa[i] = 0.0; this.columnKappa[i] = 0.0; } this.weightObserved = 0.0; this.weightCorrect = 0.0; this.weightCorrectNoChangeClassifier = 0.0; this.lastSeenClass = 0; } @Override public void addResult(Instance inst, double[] classVotes) { double weight = inst.weight(); int trueClass = (int) inst.classValue(); if (weight > 0.0) { if (this.weightObserved == 0) { reset(inst.dataset().numClasses()); } this.weightObserved += weight; int predictedClass = Utils.maxIndex(classVotes); if (predictedClass == trueClass) { this.weightCorrect += weight; } this.rowKappa[predictedClass] += weight; this.columnKappa[trueClass] += weight; } if (this.lastSeenClass == trueClass) { this.weightCorrectNoChangeClassifier += weight; } this.lastSeenClass = trueClass; } @Override public Measurement[] getPerformanceMeasurements() { return new Measurement[]{ new Measurement("classified instances", getTotalWeightObserved()), new Measurement("classifications correct (percent)", getFractionCorrectlyClassified() * 100.0), new Measurement("Kappa Statistic (percent)", getKappaStatistic() * 100.0), new Measurement("Kappa Temporal Statistic (percent)", getKappaTemporalStatistic() * 100.0) }; } public double getTotalWeightObserved() { return this.weightObserved; } public double getFractionCorrectlyClassified() { return this.weightObserved > 0.0 ? this.weightCorrect / this.weightObserved : 0.0; } public double getFractionIncorrectlyClassified() { return 1.0 - getFractionCorrectlyClassified(); } public double getKappaStatistic() { if (this.weightObserved > 0.0) { double p0 = getFractionCorrectlyClassified(); double pc = 0.0; for (int i = 0; i < this.numClasses; i++) { pc += (this.rowKappa[i] / this.weightObserved) * (this.columnKappa[i] / this.weightObserved); } return (p0 - pc) / (1.0 - pc); } else { return 0; } } public double getKappaTemporalStatistic() { if (this.weightObserved > 0.0) { double p0 = this.weightCorrect / this.weightObserved; double pc = this.weightCorrectNoChangeClassifier / this.weightObserved; return (p0 - pc) / (1.0 - pc); } else { return 0; } } @Override public void getDescription(StringBuilder sb, int indent) { Measurement.getMeasurementsDescription(getPerformanceMeasurements(), sb, indent); } }
Java
/* * RegressionAccuracy.java * Copyright (C) 2010 RWTH Aachen University, Germany * @author Jansen (moa@cs.rwth-aachen.de) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package moa.evaluation; public class RegressionAccuracy extends Accuracy{ @Override public String[] getNames() { String[] names = {"mean abs. error","root mean sq. er.","","Ram-Hours","Time","Memory"}; return names; } @Override protected boolean[] getDefaultEnabled() { boolean[] defaults = {true, true, false, true, true, true}; return defaults; } }
Java
/* * Cluster.java * Copyright (C) 2010 RWTH Aachen University, Germany * @author Jansen (moa@cs.rwth-aachen.de) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package moa.evaluation; import java.util.ArrayList; import java.util.HashMap; import moa.cluster.Clustering; import moa.gui.visualization.DataPoint; public class MembershipMatrix { HashMap<Integer, Integer> classmap; int cluster_class_weights[][]; int cluster_sums[]; int class_sums[]; int total_entries; int class_distribution[]; int total_class_entries; int initalBuildTimestamp = -1; public MembershipMatrix(Clustering foundClustering, ArrayList<DataPoint> points) { classmap = Clustering.classValues(points); // int lastID = classmap.size()-1; // classmap.put(-1, lastID); int numClasses = classmap.size(); int numCluster = foundClustering.size()+1; cluster_class_weights = new int[numCluster][numClasses]; class_distribution = new int[numClasses]; cluster_sums = new int[numCluster]; class_sums = new int[numClasses]; total_entries = 0; total_class_entries = points.size(); for (int p = 0; p < points.size(); p++) { int worklabel = classmap.get((int)points.get(p).classValue()); //real class distribution class_distribution[worklabel]++; boolean covered = false; for (int c = 0; c < numCluster-1; c++) { double prob = foundClustering.get(c).getInclusionProbability(points.get(p)); if(prob >= 1){ cluster_class_weights[c][worklabel]++; class_sums[worklabel]++; cluster_sums[c]++; total_entries++; covered = true; } } if(!covered){ cluster_class_weights[numCluster-1][worklabel]++; class_sums[worklabel]++; cluster_sums[numCluster-1]++; total_entries++; } } initalBuildTimestamp = points.get(0).getTimestamp(); } public int getClusterClassWeight(int i, int j){ return cluster_class_weights[i][j]; } public int getClusterSum(int i){ return cluster_sums[i]; } public int getClassSum(int j){ return class_sums[j]; } public int getClassDistribution(int j){ return class_distribution[j]; } public int getClusterClassWeightByLabel(int cluster, int classLabel){ return cluster_class_weights[cluster][classmap.get(classLabel)]; } public int getClassSumByLabel(int classLabel){ return class_sums[classmap.get(classLabel)]; } public int getClassDistributionByLabel(int classLabel){ return class_distribution[classmap.get(classLabel)]; } public int getTotalEntries(){ return total_entries; } public int getNumClasses(){ return classmap.size(); } public boolean hasNoiseClass(){ return classmap.containsKey(-1); } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Membership Matrix\n"); for (int i = 0; i < cluster_class_weights.length; i++) { for (int j = 0; j < cluster_class_weights[i].length; j++) { sb.append(cluster_class_weights[i][j]+"\t "); } sb.append("| "+cluster_sums[i]+"\n"); } //sb.append("-----------\n"); for (int i = 0; i < class_sums.length; i++) { sb.append(class_sums[i]+"\t "); } sb.append("| "+total_entries+"\n"); sb.append("Real class distribution \n"); for (int i = 0; i < class_distribution.length; i++) { sb.append(class_distribution[i]+"\t "); } sb.append("| "+total_class_entries+"\n"); return sb.toString(); } public int getInitalBuildTimestamp(){ return initalBuildTimestamp; } }
Java
/* * MeasureCollection.java * Copyright (C) 2010 RWTH Aachen University, Germany * @author Jansen (moa@cs.rwth-aachen.de) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package moa.evaluation; import java.util.ArrayList; import java.util.HashMap; import moa.AbstractMOAObject; import moa.cluster.Clustering; import moa.gui.visualization.DataPoint; public abstract class MeasureCollection extends AbstractMOAObject{ private String[] names; private ArrayList<Double>[] values; private ArrayList<Double>[] sortedValues; private ArrayList<String> events; private double[] minValue; private double[] maxValue; private double[] sumValues; private boolean[] enabled; private boolean[] corrupted; private double time; private boolean debug = true; private MembershipMatrix mm = null; private HashMap<String, Integer> map; private int numMeasures = 0; public MeasureCollection() { names = getNames(); numMeasures = names.length; map = new HashMap<String, Integer>(numMeasures); for (int i = 0; i < names.length; i++) { map.put(names[i],i); } values = (ArrayList<Double>[]) new ArrayList[numMeasures]; sortedValues = (ArrayList<Double>[]) new ArrayList[numMeasures]; maxValue = new double[numMeasures]; minValue = new double[numMeasures]; sumValues = new double[numMeasures]; corrupted = new boolean[numMeasures]; enabled = getDefaultEnabled(); time = 0; events = new ArrayList<String>(); for (int i = 0; i < numMeasures; i++) { values[i] = new ArrayList<Double>(); sortedValues[i] = new ArrayList<Double>(); maxValue[i] = Double.MIN_VALUE; minValue[i] = Double.MAX_VALUE; corrupted[i] = false; sumValues[i] = 0.0; } } protected abstract String[] getNames(); public void addValue(int index, double value){ if(Double.isNaN(value)){ if(debug) System.out.println("NaN for "+names[index]); corrupted[index] = true; } if(value < 0){ if(debug) System.out.println("Negative value for "+names[index]); } values[index].add(value); sumValues[index]+=value; if(value < minValue[index]) minValue[index] = value; if(value > maxValue[index]) maxValue[index] = value; } protected void addValue(String name, double value){ if(map.containsKey(name)){ addValue(map.get(name),value); } else{ System.out.println(name+" is not a valid measure key, no value added"); } } //add an empty entry e.g. if evaluation crashed internally public void addEmptyValue(int index){ values[index].add(Double.NaN); corrupted[index] = true; } public int getNumMeasures(){ return numMeasures; } public String getName(int index){ return names[index]; } public double getMaxValue(int index){ return maxValue[index]; } public double getMinValue(int index){ return minValue[index]; } public double getLastValue(int index){ if(values[index].size()<1) return Double.NaN; return values[index].get(values[index].size()-1); } public double getMean(int index){ if(corrupted[index] || values[index].size()<1) return Double.NaN; return sumValues[index]/values[index].size(); } private void updateSortedValues(int index){ //naive implementation of insertion sort for (int i = sortedValues[index].size(); i < values[index].size(); i++) { double v = values[index].get(i); int insertIndex = 0; while(!sortedValues[index].isEmpty() && insertIndex < sortedValues[index].size() && v > sortedValues[index].get(insertIndex)) insertIndex++; sortedValues[index].add(insertIndex,v); } // for (int i = 0; i < sortedValues[index].size(); i++) { // System.out.print(sortedValues[index].get(i)+" "); // } // System.out.println(); } public void clean(int index){ sortedValues[index].clear(); } public double getMedian(int index){ updateSortedValues(index); int size = sortedValues[index].size(); if(size > 0){ if(size%2 == 1) return sortedValues[index].get((int)(size/2)); else return (sortedValues[index].get((size-1)/2)+sortedValues[index].get((size-1)/2+1))/2.0; } return Double.NaN; } public double getLowerQuartile(int index){ updateSortedValues(index); int size = sortedValues[index].size(); if(size > 11){ return sortedValues[index].get(Math.round(size*0.25f)); } return Double.NaN; } public double getUpperQuartile(int index){ updateSortedValues(index); int size = sortedValues[index].size(); if(size > 11){ return sortedValues[index].get(Math.round(size*0.75f-1)); } return Double.NaN; } public int getNumberOfValues(int index){ return values[index].size(); } public double getValue(int index, int i){ if(i>=values[index].size()) return Double.NaN; return values[index].get(i); } public ArrayList<Double> getAllValues(int index){ return values[index]; } public void setEnabled(int index, boolean value){ enabled[index] = value; } public boolean isEnabled(int index){ return enabled[index]; } public double getMeanRunningTime(){ if(values[0].size()!=0) return (time/10e5/values[0].size()); else return 0; } protected boolean[] getDefaultEnabled(){ boolean[] defaults = new boolean[numMeasures]; for (int i = 0; i < defaults.length; i++) { defaults[i] = true; } return defaults; } protected abstract void evaluateClustering(Clustering clustering, Clustering trueClustering, ArrayList<DataPoint> points) throws Exception; /* * Evaluate Clustering * * return Time in milliseconds */ public double evaluateClusteringPerformance(Clustering clustering, Clustering trueClustering, ArrayList<DataPoint> points) throws Exception{ long start = System.nanoTime(); evaluateClustering(clustering, trueClustering, points); long duration = System.nanoTime()-start; time+=duration; duration/=10e5; return duration; } public void getDescription(StringBuilder sb, int indent) { } public void addEventType(String type){ events.add(type); } public String getEventType(int index){ if(index < events.size()) return events.get(index); else return null; } }
Java
/* * WindowRegressionPerformanceEvaluator.java * Copyright (C) 2011 University of Waikato, Hamilton, New Zealand * @author Albert Bifet (abifet at cs dot waikato dot ac dot nz) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package moa.evaluation; import moa.core.Measurement; import moa.core.ObjectRepository; import moa.options.AbstractOptionHandler; import moa.options.IntOption; import moa.tasks.TaskMonitor; import weka.core.Instance; /** * Regression evaluator that updates evaluation results using a sliding window. * * @author Albert Bifet (abifet at cs dot waikato dot ac dot nz) * @version $Revision: 7 $ */ public class WindowRegressionPerformanceEvaluator extends AbstractOptionHandler implements RegressionPerformanceEvaluator { private static final long serialVersionUID = 1L; public IntOption widthOption = new IntOption("width", 'w', "Size of Window", 1000); protected double TotalweightObserved = 0; protected Estimator weightObserved; protected Estimator squareError; protected Estimator averageError; protected int numClasses; public class Estimator { protected double[] window; protected int posWindow; protected int lenWindow; protected int SizeWindow; protected double sum; public Estimator(int sizeWindow) { window = new double[sizeWindow]; SizeWindow = sizeWindow; posWindow = 0; } public void add(double value) { sum -= window[posWindow]; sum += value; window[posWindow] = value; posWindow++; if (posWindow == SizeWindow) { posWindow = 0; } } public double total() { return sum; } } /* public void setWindowWidth(int w) { this.width = w; reset(); }*/ @Override public void reset() { reset(this.numClasses); } public void reset(int numClasses) { this.numClasses = numClasses; this.weightObserved = new Estimator(this.widthOption.getValue()); this.squareError = new Estimator(this.widthOption.getValue()); this.averageError = new Estimator(this.widthOption.getValue()); this.TotalweightObserved = 0; } @Override public void addResult(Instance inst, double[] prediction) { double weight = inst.weight(); if (weight > 0.0) { if (TotalweightObserved == 0) { reset(inst.dataset().numClasses()); } this.TotalweightObserved += weight; this.weightObserved.add(weight); if (prediction.length > 0) { this.squareError.add((inst.classValue() - prediction[0]) * (inst.classValue() - prediction[0])); this.averageError.add(Math.abs(inst.classValue() - prediction[0])); } //System.out.println(inst.classValue()+", "+prediction[0]); } } @Override public Measurement[] getPerformanceMeasurements() { return new Measurement[]{ new Measurement("classified instances", getTotalWeightObserved()), new Measurement("mean absolute error", getMeanError()), new Measurement("root mean squared error", getSquareError())}; } public double getTotalWeightObserved() { return this.weightObserved.total(); } public double getMeanError() { return this.weightObserved.total() > 0.0 ? this.averageError.total() / this.weightObserved.total() : 0.0; } public double getSquareError() { return Math.sqrt(this.weightObserved.total() > 0.0 ? this.squareError.total() / this.weightObserved.total() : 0.0); } @Override public void getDescription(StringBuilder sb, int indent) { Measurement.getMeasurementsDescription(getPerformanceMeasurements(), sb, indent); } @Override public void prepareForUseImpl(TaskMonitor monitor, ObjectRepository repository) { } }
Java
/* * LearningCurve.java * Copyright (C) 2007 University of Waikato, Hamilton, New Zealand * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package moa.evaluation; import java.util.ArrayList; import java.util.List; import moa.AbstractMOAObject; import moa.core.DoubleVector; import moa.core.Measurement; import moa.core.StringUtils; /** * Class that stores and keeps the history of evaluation measurements. * * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @version $Revision: 7 $ */ public class LearningCurve extends AbstractMOAObject { private static final long serialVersionUID = 1L; protected List<String> measurementNames = new ArrayList<String>(); protected List<double[]> measurementValues = new ArrayList<double[]>(); public LearningCurve(String orderingMeasurementName) { this.measurementNames.add(orderingMeasurementName); } public String getOrderingMeasurementName() { return this.measurementNames.get(0); } public void insertEntry(LearningEvaluation learningEvaluation) { Measurement[] measurements = learningEvaluation.getMeasurements(); Measurement orderMeasurement = Measurement.getMeasurementNamed( getOrderingMeasurementName(), measurements); if (orderMeasurement == null) { throw new IllegalArgumentException(); } DoubleVector entryVals = new DoubleVector(); for (Measurement measurement : measurements) { entryVals.setValue(addMeasurementName(measurement.getName()), measurement.getValue()); } double orderVal = orderMeasurement.getValue(); int index = 0; while ((index < this.measurementValues.size()) && (orderVal > this.measurementValues.get(index)[0])) { index++; } this.measurementValues.add(index, entryVals.getArrayRef()); } public int numEntries() { return this.measurementValues.size(); } protected int addMeasurementName(String name) { int index = this.measurementNames.indexOf(name); if (index < 0) { index = this.measurementNames.size(); this.measurementNames.add(name); } return index; } public String headerToString() { StringBuilder sb = new StringBuilder(); boolean first = true; for (String name : this.measurementNames) { if (!first) { sb.append(','); } else { first = false; } sb.append(name); } return sb.toString(); } public String entryToString(int entryIndex) { StringBuilder sb = new StringBuilder(); double[] vals = this.measurementValues.get(entryIndex); for (int i = 0; i < this.measurementNames.size(); i++) { if (i > 0) { sb.append(','); } if ((i >= vals.length) || Double.isNaN(vals[i])) { sb.append('?'); } else { sb.append(Double.toString(vals[i])); } } return sb.toString(); } @Override public void getDescription(StringBuilder sb, int indent) { sb.append(headerToString()); for (int i = 0; i < numEntries(); i++) { StringUtils.appendNewlineIndented(sb, indent, entryToString(i)); } } public double getMeasurement(int entryIndex, int measurementIndex) { return this.measurementValues.get(entryIndex)[measurementIndex]; } public String getMeasurementName(int measurementIndex) { return this.measurementNames.get(measurementIndex); } }
Java
/* * SSQ.java * Copyright (C) 2010 RWTH Aachen University, Germany * @author Jansen (moa@cs.rwth-aachen.de) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package moa.evaluation; import java.util.ArrayList; import moa.cluster.Clustering; import moa.gui.visualization.DataPoint; public class SSQ extends MeasureCollection{ public SSQ() { super(); } @Override public String[] getNames() { String[] names = {"SSQ"}; return names; } @Override protected boolean[] getDefaultEnabled() { boolean [] defaults = {false}; return defaults; } public void evaluateClustering(Clustering clustering, Clustering trueClsutering, ArrayList<DataPoint> points) { double sum = 0.0; for (int p = 0; p < points.size(); p++) { //don't include noise if(points.get(p).classValue()==-1) continue; double minDistance = Double.MAX_VALUE; for (int c = 0; c < clustering.size(); c++) { double distance = 0.0; double[] center = clustering.get(c).getCenter(); for (int i = 0; i < center.length; i++) { double d = points.get(p).value(i) - center[i]; distance += d * d; } minDistance = Math.min(distance, minDistance); } sum+=minDistance; } addValue(0,sum); } }
Java
/* * ClassificationPerformanceEvaluator.java * Copyright (C) 2007 University of Waikato, Hamilton, New Zealand * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package moa.evaluation; import moa.MOAObject; import moa.core.Measurement; import weka.core.Instance; /** * Interface implemented by learner evaluators to monitor * the results of the learning process. * * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @version $Revision: 7 $ */ public interface ClassificationPerformanceEvaluator extends MOAObject { /** * Resets this evaluator. It must be similar to * starting a new evaluator from scratch. * */ public void reset(); //public void addClassificationAttempt(int trueClass, double[] classVotes, // double weight); /** * Adds a learning result to this evaluator. * * @param inst the instance to be classified * @param classVotes an array containing the estimated membership * probabilities of the test instance in each class * @return an array of measurements monitored in this evaluator */ public void addResult(Instance inst, double[] classVotes); /** * Gets the current measurements monitored by this evaluator. * * @return an array of measurements monitored by this evaluator */ public Measurement[] getPerformanceMeasurements(); }
Java