code
stringlengths
3
1.18M
language
stringclasses
1 value
package fr.utt.millebornes.exception; public class AbsenceCarteDefausseException extends Exception { }
Java
package fr.utt.millebornes.exception; public class AvancementImpossibleRalentissementException extends Exception { }
Java
package fr.utt.millebornes.exception; public class NonAttaqueException extends Exception { }
Java
package fr.utt.millebornes.exception; public class CibleIncorrecteException extends Exception { }
Java
package fr.utt.millebornes.exception; public class MauvaiseParadeException extends Exception { }
Java
package fr.utt.millebornes.exception; public class NombreJoueursExcessif extends Exception { }
Java
package fr.utt.millebornes.exception; public class DejaRalentiException extends Exception { }
Java
package fr.utt.millebornes.exception; public class ActionImpossibleException extends Exception { }
Java
package fr.utt.millebornes.exception; public class JoueurDebutantNonAttaquableException extends Exception { }
Java
package fr.utt.millebornes.joueur; public interface StrategieDeJeu { public void choisirUneCarte(JoueurVirtuel j); }
Java
package fr.utt.millebornes.joueur; public class StrategiePassive implements StrategieDeJeu { public void choisirUneCarte(JoueurVirtuel j) { } public String toString() { return "passive"; } }
Java
package fr.utt.millebornes.cartes; public class Crevaison extends Attaque { public Crevaison() { super(); type = Carte.TYPE_CREVAISON; } public String toString() { return "Carte crevaison"; } }
Java
package fr.utt.millebornes.cartes; public class PanneEssence extends Attaque { public PanneEssence() { type = Carte.TYPE_PANNE_ESSENCE; } public String toString() { return "Carte Panne essence"; } }
Java
package fr.utt.millebornes.cartes; public abstract class CarteDefensive extends Carte { protected int[] typeDeCarteContrees; public boolean isCarteDefensive() { return true; } public boolean peutContrer(Carte c) { return peutContrer(c.getType()); } public boolean peutContrer(int typeDeCarte) { for (int i=0;i<typeDeCarteContrees.length;i++) { if (typeDeCarteContrees[i]==typeDeCarte) return true; } return false; } }
Java
package fr.utt.millebornes.cartes; public class FinCrevaison extends Parade { public FinCrevaison() { type = Carte.TYPE_FIN_CREVAISON; this.typeDeCarteContrees = new int[1]; this.typeDeCarteContrees[0] = Carte.TYPE_CREVAISON; } public String toString() { return "Carte FIN crevaison"; } }
Java
package fr.utt.millebornes.cartes; public class BotteIncrevable extends Botte { public BotteIncrevable() { super(); type = Carte.TYPE_BOTTE_INCREVABLE; this.typeDeCarteContrees = new int[1]; this.typeDeCarteContrees[0] = Carte.TYPE_CREVAISON; } public String toString() { return "Carte Botte Increvable"; } }
Java
package fr.utt.millebornes.cartes; import fr.utt.millebornes.exception.AvancementImpossibleAttaqueException; import fr.utt.millebornes.exception.AvancementImpossibleEtape200Exception; import fr.utt.millebornes.exception.AvancementImpossibleFeuVertException; import fr.utt.millebornes.exception.AvancementImpossibleKilometresException; import fr.utt.millebornes.exception.AvancementImpossibleRalentissementException; import fr.utt.millebornes.exception.BotteException; import fr.utt.millebornes.exception.CibleIncorrecteException; import fr.utt.millebornes.exception.CibleSuicideException; import fr.utt.millebornes.exception.CoupFourreException; import fr.utt.millebornes.exception.DejaAttaqueException; import fr.utt.millebornes.exception.DejaRalentiException; import fr.utt.millebornes.exception.ImmuniseException; import fr.utt.millebornes.exception.JoueurDebutantNonAttaquableException; import fr.utt.millebornes.exception.MauvaiseParadeException; import fr.utt.millebornes.exception.NonAttaqueException; import fr.utt.millebornes.exception.NonRalentiException; import fr.utt.millebornes.joueur.Joueur; public abstract class Attaque extends Carte { public Attaque() { pileDestination = Joueur.PILE_BATAILLE; } public boolean isCarteAttaque() { return true; } public boolean peutEtrePosee(Joueur jcible) throws DejaAttaqueException, ImmuniseException, JoueurDebutantNonAttaquableException, DejaRalentiException { if (!jcible.estPasAttaque()) throw new DejaAttaqueException(); if (jcible.estImmunise(this)) throw new ImmuniseException(); if (!jcible.aPoseUneCarteFeuVert()) throw new JoueurDebutantNonAttaquableException(); return true; //return jcible.estAttaquable() && !jcible.estImmunise(this) && jcible.aPoseUneCarteFeuVert(); } public boolean jouer(Joueur jsource, Joueur jcible) throws CibleSuicideException, CoupFourreException, DejaAttaqueException, ImmuniseException, JoueurDebutantNonAttaquableException, DejaRalentiException, AvancementImpossibleRalentissementException, AvancementImpossibleEtape200Exception, NonAttaqueException, MauvaiseParadeException, NonRalentiException, AvancementImpossibleAttaqueException, AvancementImpossibleFeuVertException, AvancementImpossibleKilometresException, BotteException, CibleIncorrecteException { if (jsource.equals(jcible)) throw new CibleSuicideException(); return super.jouer(jsource,jcible); } protected void effetDeJeu(Joueur jsource,Joueur jcible) throws CoupFourreException { if (jcible.peutEffectuerCoupFourre()) throw new CoupFourreException(jcible); } }
Java
package fr.utt.millebornes.cartes; import fr.utt.millebornes.exception.AvancementImpossibleAttaqueException; import fr.utt.millebornes.exception.AvancementImpossibleEtape200Exception; import fr.utt.millebornes.exception.AvancementImpossibleFeuVertException; import fr.utt.millebornes.exception.AvancementImpossibleKilometresException; import fr.utt.millebornes.exception.AvancementImpossibleRalentissementException; import fr.utt.millebornes.joueur.Joueur; public class Etape200 extends Etape { public Etape200() { super(200); type = Carte.TYPE_ETAPE_200; } public String toString() { return "Carte Etape 200"; } public boolean peutEtrePosee(Joueur jcible) throws AvancementImpossibleRalentissementException,AvancementImpossibleEtape200Exception, AvancementImpossibleAttaqueException, AvancementImpossibleFeuVertException, AvancementImpossibleKilometresException { super.peutEtrePosee(jcible); if (!jcible.estRalentissable()) throw new AvancementImpossibleRalentissementException(); if (!jcible.peutPoserUneEtape200()) throw new AvancementImpossibleEtape200Exception(); return true; //return super.peutEtrePosee(jcible) && jcible.estRalentissable() && jcible.peutPoserUneEtape200(); } }
Java
package fr.utt.millebornes.cartes; public class BottePrioritaire extends Botte { public BottePrioritaire() { super(); type = Carte.TYPE_BOTTE_PRIORITAIRE; this.typeDeCarteContrees = new int[2]; this.typeDeCarteContrees[0] = Carte.TYPE_FEU_ROUGE; this.typeDeCarteContrees[1] = Carte.TYPE_LIMITATION_VITESSE; } public String toString() { return "Carte Botte Prioritaire"; } }
Java
package fr.utt.millebornes.cartes; import fr.utt.millebornes.exception.AvancementImpossibleAttaqueException; import fr.utt.millebornes.exception.AvancementImpossibleEtape200Exception; import fr.utt.millebornes.exception.AvancementImpossibleFeuVertException; import fr.utt.millebornes.exception.AvancementImpossibleKilometresException; import fr.utt.millebornes.exception.AvancementImpossibleRalentissementException; import fr.utt.millebornes.joueur.Joueur; public class Etape75 extends Etape { public Etape75() { super(75); type = Carte.TYPE_ETAPE_75; } public String toString() { return "Carte Etape 75"; } public boolean peutEtrePosee(Joueur jcible) throws AvancementImpossibleRalentissementException, AvancementImpossibleAttaqueException, AvancementImpossibleFeuVertException, AvancementImpossibleKilometresException, AvancementImpossibleEtape200Exception { super.peutEtrePosee(jcible); if (!jcible.estRalentissable()) throw new AvancementImpossibleRalentissementException(); return true; //return super.peutEtrePosee(jcible) && jcible.estRalentissable(); } }
Java
package fr.utt.millebornes.cartes; public class Etape50 extends Etape { public Etape50() { super(50); type = Carte.TYPE_ETAPE_50; } public String toString() { return "Carte Etape 50"; } }
Java
package fr.utt.millebornes.cartes; public class BotteAsDuVolant extends Botte { public BotteAsDuVolant() { super(); type = Carte.TYPE_BOTTE_AS_DU_VOLANT; this.typeDeCarteContrees = new int[1]; this.typeDeCarteContrees[0] = Carte.TYPE_ACCIDENT; } public String toString() { return "Carte Botte As du Volant"; } }
Java
package fr.utt.millebornes.cartes; public class Etape25 extends Etape { public Etape25() { super(25); type = Carte.TYPE_ETAPE_25; } public String toString() { return "Carte Etape 25"; } }
Java
package fr.utt.millebornes.cartes; public class Accident extends Attaque { public Accident() { super(); type = Carte.TYPE_ACCIDENT; } public String toString() { return "Carte accident"; } }
Java
package fr.utt.millebornes.cartes; import fr.utt.millebornes.exception.AvancementImpossibleAttaqueException; import fr.utt.millebornes.exception.AvancementImpossibleEtape200Exception; import fr.utt.millebornes.exception.AvancementImpossibleFeuVertException; import fr.utt.millebornes.exception.AvancementImpossibleKilometresException; import fr.utt.millebornes.exception.AvancementImpossibleRalentissementException; import fr.utt.millebornes.joueur.Joueur; public class Etape100 extends Etape { public Etape100() { super(100); type = Carte.TYPE_ETAPE_100; } public String toString() { return "Carte Etape 100"; } public boolean peutEtrePosee(Joueur jcible) throws AvancementImpossibleAttaqueException, AvancementImpossibleFeuVertException, AvancementImpossibleKilometresException, AvancementImpossibleRalentissementException, AvancementImpossibleEtape200Exception { super.peutEtrePosee(jcible); if (!jcible.estRalentissable()) throw new AvancementImpossibleRalentissementException(); return true; // return super.peutEtrePosee(jcible) && jcible.estRalentissable(); } }
Java
package fr.utt.millebornes.cartes; import fr.utt.millebornes.exception.NonRalentiException; import fr.utt.millebornes.joueur.Joueur; public class FinLimitationVitesse extends Parade { public FinLimitationVitesse() { this.typeDeCarteContrees = new int[1]; this.typeDeCarteContrees[0] = Carte.TYPE_LIMITATION_VITESSE; pileDestination = Joueur.PILE_VITESSE; type = TYPE_FIN_LIMITATION_VITESSE; } public String toString() { return "Carte FIN limitation vitesse"; } public boolean peutEtrePosee(Joueur jcible) throws NonRalentiException { if (jcible.estRalentissable()) throw new NonRalentiException(); return true; // return !jcible.estRalentissable(); } protected void effetDeJeu(Joueur jsource, Joueur jcible) { jcible.defausserPileVitesse(); } }
Java
package fr.utt.millebornes.cartes; public class BotteCiterne extends Botte { public BotteCiterne() { super(); type = Carte.TYPE_BOTTE_CITERNE; this.typeDeCarteContrees = new int[1]; this.typeDeCarteContrees[0] = Carte.TYPE_PANNE_ESSENCE; } public String toString() { return "Carte Botte Citerne"; } }
Java
package fr.utt.millebornes.cartes; import fr.utt.millebornes.exception.AvancementImpossibleAttaqueException; import fr.utt.millebornes.exception.AvancementImpossibleEtape200Exception; import fr.utt.millebornes.exception.AvancementImpossibleFeuVertException; import fr.utt.millebornes.exception.AvancementImpossibleKilometresException; import fr.utt.millebornes.exception.AvancementImpossibleRalentissementException; import fr.utt.millebornes.exception.BotteException; import fr.utt.millebornes.exception.CibleIncorrecteException; import fr.utt.millebornes.exception.CibleSuicideException; import fr.utt.millebornes.exception.CoupFourreException; import fr.utt.millebornes.exception.DejaAttaqueException; import fr.utt.millebornes.exception.DejaRalentiException; import fr.utt.millebornes.exception.ImmuniseException; import fr.utt.millebornes.exception.JoueurDebutantNonAttaquableException; import fr.utt.millebornes.exception.MauvaiseParadeException; import fr.utt.millebornes.exception.NonAttaqueException; import fr.utt.millebornes.exception.NonRalentiException; import fr.utt.millebornes.jeu.Partie; import fr.utt.millebornes.joueur.Joueur; public abstract class Botte extends CarteDefensive { private static final int VALEUR_COUP_FOURRE = 300; public Botte() { pileDestination = Joueur.PILE_BOTTES; } public boolean isCarteBotte() { return true; } // /!\ On peut tjs poser une botte public boolean peutEtrePosee(Joueur jcible) { return true; } public boolean jouer(Joueur jsource, Joueur jcible) throws CoupFourreException, DejaAttaqueException, ImmuniseException, JoueurDebutantNonAttaquableException, DejaRalentiException, CibleSuicideException, AvancementImpossibleRalentissementException, AvancementImpossibleEtape200Exception, NonAttaqueException, MauvaiseParadeException, NonRalentiException, AvancementImpossibleAttaqueException, AvancementImpossibleFeuVertException, AvancementImpossibleKilometresException, BotteException, CibleIncorrecteException { if (jsource!=jcible) throw new CibleIncorrecteException(); return super.jouer(jsource, jcible); } protected void effetDeJeu(Joueur jsource,Joueur jcible) throws BotteException { if (!jsource.estPasAttaque()) { if (this.peutContrer(jsource.getAttaqueEnCours())) jsource.defausserPileBataille(); } if (!jsource.estRalentissable()) { if (this.peutContrer(jsource.getRalentissementEnCours())) jsource.defausserPileVitesse(); } if ((jsource.getNombreDeKilometres()+100) <= Partie.KILOMETRES_POUR_LA_VICTOIRE) jsource.ajouterKilometres(100); throw new BotteException(); } public void jouerCoupFourre(Joueur jsource) { jsource.supprimerCarteDeLaMain(this); jsource.poser(this); if (!jsource.estPasAttaque()) { if (this.peutContrer(jsource.getAttaqueEnCours())) jsource.defausserPileBataille(); } if (!jsource.estRalentissable()) { if (this.peutContrer(jsource.getRalentissementEnCours())) jsource.defausserPileVitesse(); } if ((jsource.getNombreDeKilometres()+VALEUR_COUP_FOURRE) <= Partie.KILOMETRES_POUR_LA_VICTOIRE) jsource.ajouterKilometres(VALEUR_COUP_FOURRE); } }
Java
package fr.utt.millebornes.cartes; public class FeuRouge extends Attaque { public FeuRouge() { type = Carte.TYPE_FEU_ROUGE; } public String toString() { return "Carte Feu Rouge"; } }
Java
package fr.utt.millebornes.cartes; public class FinPanneEssence extends Parade { public FinPanneEssence() { this.typeDeCarteContrees = new int[1]; this.typeDeCarteContrees[0] = Carte.TYPE_PANNE_ESSENCE; type = TYPE_FIN_PANNE_ESSENCE; } public String toString() { return "Carte FIN panne essence"; } }
Java
package fr.utt.millebornes.cartes; public class FinAccident extends Parade { public FinAccident() { type= Carte.TYPE_FIN_ACCIDENT; this.typeDeCarteContrees = new int[1]; this.typeDeCarteContrees[0] = Carte.TYPE_ACCIDENT; } public String toString() { return "Carte FIN accident"; } }
Java
package fr.utt.millebornes.cartes; import fr.utt.millebornes.exception.AvancementImpossibleAttaqueException; import fr.utt.millebornes.exception.AvancementImpossibleEtape200Exception; import fr.utt.millebornes.exception.AvancementImpossibleFeuVertException; import fr.utt.millebornes.exception.AvancementImpossibleKilometresException; import fr.utt.millebornes.exception.AvancementImpossibleRalentissementException; import fr.utt.millebornes.exception.BotteException; import fr.utt.millebornes.exception.CibleIncorrecteException; import fr.utt.millebornes.exception.CibleSuicideException; import fr.utt.millebornes.exception.CoupFourreException; import fr.utt.millebornes.exception.DejaAttaqueException; import fr.utt.millebornes.exception.DejaRalentiException; import fr.utt.millebornes.exception.ImmuniseException; import fr.utt.millebornes.exception.JoueurDebutantNonAttaquableException; import fr.utt.millebornes.exception.MauvaiseParadeException; import fr.utt.millebornes.exception.NonAttaqueException; import fr.utt.millebornes.exception.NonRalentiException; import fr.utt.millebornes.joueur.Joueur; public abstract class Carte { protected int type; protected String representationVisuelle; protected int pileDestination; public final static int TYPE_ETAPE_25=101; public final static int TYPE_ETAPE_50=102; public final static int TYPE_ETAPE_75=103; public final static int TYPE_ETAPE_100=104; public final static int TYPE_ETAPE_200=105; public final static int TYPE_FEU_ROUGE=201; public final static int TYPE_LIMITATION_VITESSE=202; public final static int TYPE_PANNE_ESSENCE=203; public final static int TYPE_CREVAISON=204; public final static int TYPE_ACCIDENT=205; public final static int TYPE_FEU_VERT=301; public final static int TYPE_FIN_LIMITATION_VITESSE=302; public final static int TYPE_FIN_PANNE_ESSENCE=303; public final static int TYPE_FIN_CREVAISON=304; public final static int TYPE_FIN_ACCIDENT=305; public final static int TYPE_BOTTE_PRIORITAIRE=401; public final static int TYPE_BOTTE_CITERNE=403; public final static int TYPE_BOTTE_INCREVABLE=404; public final static int TYPE_BOTTE_AS_DU_VOLANT=405; public int getType() { return type; } public boolean isCarteAttaque() { return false; } public boolean isCarteDefensive() { return false; } public boolean isCarteEtape() { return false; } public boolean isCarteParade() { return false; } public boolean isCarteBotte() { return false; } public int getDestination() { return pileDestination; } public boolean jouer(Joueur jsource, Joueur jcible) throws CoupFourreException,DejaAttaqueException, ImmuniseException, JoueurDebutantNonAttaquableException, DejaRalentiException,CibleSuicideException,AvancementImpossibleRalentissementException,AvancementImpossibleEtape200Exception, NonAttaqueException, MauvaiseParadeException, NonRalentiException, AvancementImpossibleAttaqueException, AvancementImpossibleFeuVertException, AvancementImpossibleKilometresException, BotteException, CibleIncorrecteException { if (this.peutEtrePosee(jcible)) { jsource.supprimerCarteDeLaMain(this); jcible.poser(this); effetDeJeu(jsource,jcible); return true; } return false; } protected abstract void effetDeJeu(Joueur jsource,Joueur jcible) throws CoupFourreException, BotteException; public abstract boolean peutEtrePosee(Joueur jcible) throws AvancementImpossibleAttaqueException, AvancementImpossibleFeuVertException, AvancementImpossibleKilometresException, AvancementImpossibleRalentissementException, AvancementImpossibleEtape200Exception, NonAttaqueException, MauvaiseParadeException, NonRalentiException, DejaAttaqueException, ImmuniseException, JoueurDebutantNonAttaquableException, DejaRalentiException ; // public abstract boolean jouer(Joueur jsource, Joueur jcible); }
Java
package fr.utt.millebornes.cartes; import fr.utt.millebornes.exception.AvancementImpossibleAttaqueException; import fr.utt.millebornes.exception.AvancementImpossibleEtape200Exception; import fr.utt.millebornes.exception.AvancementImpossibleFeuVertException; import fr.utt.millebornes.exception.AvancementImpossibleKilometresException; import fr.utt.millebornes.exception.AvancementImpossibleRalentissementException; import fr.utt.millebornes.exception.BotteException; import fr.utt.millebornes.exception.CibleIncorrecteException; import fr.utt.millebornes.exception.CibleSuicideException; import fr.utt.millebornes.exception.CoupFourreException; import fr.utt.millebornes.exception.DejaAttaqueException; import fr.utt.millebornes.exception.DejaRalentiException; import fr.utt.millebornes.exception.ImmuniseException; import fr.utt.millebornes.exception.JoueurDebutantNonAttaquableException; import fr.utt.millebornes.exception.MauvaiseParadeException; import fr.utt.millebornes.exception.NonAttaqueException; import fr.utt.millebornes.exception.NonRalentiException; import fr.utt.millebornes.jeu.Partie; import fr.utt.millebornes.joueur.Joueur; public abstract class Etape extends Carte { protected int nombreDeKilometres; public Etape(int nombreKilometres) { nombreDeKilometres = nombreKilometres; pileDestination = Joueur.PILE_ETAPE; } public int getNombreDeKilometres() { return nombreDeKilometres; } public boolean isCarteEtape() { return true; } public boolean jouer(Joueur jsource, Joueur jcible) throws CoupFourreException, DejaAttaqueException, ImmuniseException, JoueurDebutantNonAttaquableException, DejaRalentiException, CibleSuicideException, AvancementImpossibleRalentissementException, AvancementImpossibleEtape200Exception, NonAttaqueException, MauvaiseParadeException, NonRalentiException, AvancementImpossibleAttaqueException, AvancementImpossibleFeuVertException, AvancementImpossibleKilometresException, BotteException, CibleIncorrecteException { if (jsource!=jcible) throw new CibleIncorrecteException(); return super.jouer(jsource, jcible); } public boolean peutEtrePosee(Joueur jcible) throws AvancementImpossibleAttaqueException, AvancementImpossibleFeuVertException, AvancementImpossibleKilometresException, AvancementImpossibleRalentissementException, AvancementImpossibleEtape200Exception { if (!jcible.estPasAttaque()) throw new AvancementImpossibleAttaqueException(); if (!jcible.aPoseUneCarteFeuVert()) throw new AvancementImpossibleFeuVertException(); if ((jcible.getNombreDeKilometres()+nombreDeKilometres) > Partie.KILOMETRES_POUR_LA_VICTOIRE) throw new AvancementImpossibleKilometresException(); return true; //return jcible.estAttaquable() && jcible.aPoseUneCarteFeuVert() && (jcible.getNombreDeKilometres()+nombreDeKilometres) <= Partie.KILOMETRES_POUR_LA_VICTOIRE; } protected void effetDeJeu(Joueur jsource,Joueur jcible) { jsource.ajouterKilometres(this.nombreDeKilometres); } }
Java
package fr.utt.millebornes.jeu; import java.util.Scanner; import fr.utt.millebornes.vue.VueConsole; public class Test { /** * @param args */ public static void main(String[] args) { Partie p = new Partie(); System.out.println("Charger un jeu de commande ? "); String rep = new Scanner(System.in).nextLine(); if (rep.equals("n")) rep = null; VueConsole vc = new VueConsole(p,rep); Thread t = new Thread(vc); t.start(); } }
Java
/* * Copyright 2013 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.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.support.v4.content.WakefulBroadcastReceiver; /** * This {@code WakefulBroadcastReceiver} takes care of creating and managing a * partial wake lock for your app. It passes off the work of processing the GCM * message to an {@code IntentService}, while ensuring that the device does not * go back to sleep in the transition. The {@code IntentService} calls * {@code GcmBroadcastReceiver.completeWakefulIntent()} when it is ready to * release the wake lock. */ public class GcmBroadcastReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Explicitly specify that GcmIntentService will handle the intent. ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName()); // Start the service, keeping the device awake while it is launching. startWakefulService(context, (intent.setComponent(comp))); setResultCode(Activity.RESULT_OK); } }
Java
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import com.google.android.gms.gcm.GoogleCloudMessaging; import android.app.IntentService; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.SystemClock; import android.support.v4.app.NotificationCompat; import android.util.Log; /** * This {@code IntentService} does the actual handling of the GCM message. * {@code GcmBroadcastReceiver} (a {@code WakefulBroadcastReceiver}) holds a * partial wake lock for this service while the service does its work. When the * service is finished, it calls {@code completeWakefulIntent()} to release the * wake lock. */ public class GcmIntentService extends IntentService { public static final int NOTIFICATION_ID = 1; private NotificationManager mNotificationManager; NotificationCompat.Builder builder; public GcmIntentService() { super("GcmIntentService"); } public static final String TAG = "GCM Demo"; @Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) { // has effect of unparcelling Bundle /* * Filter messages based on message type. Since it is likely that GCM will be * extended in the future with new message types, just ignore any message types you're * not interested in, or that you don't recognize. */ if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { sendNotification("Send error: " + extras.toString()); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { sendNotification("Deleted messages on server: " + extras.toString()); // If it's a regular GCM message, do some work. } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { // This loop represents the service doing some work. for (int i = 0; i < 5; i++) { Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime()); try { Thread.sleep(5000); } catch (InterruptedException e) { } } Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime()); // Post notification of received message. sendNotification("Received: " + extras.toString()); Log.i(TAG, "Received: " + extras.toString()); } } // Release the wake lock provided by the WakefulBroadcastReceiver. GcmBroadcastReceiver.completeWakefulIntent(intent); } // Put the message into a notification and post it. // This is just one simple example of what you might choose to do with // a GCM message. private void sendNotification(String msg) { mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, DemoActivity.class), 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_stat_gcm) .setContentTitle("GCM Notification") .setStyle(new NotificationCompat.BigTextStyle() .bigText(msg)) .setContentText(msg); mBuilder.setContentIntent(contentIntent); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); } }
Java
/* * Copyright 2013 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 com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; /** * Main UI for the demo app. */ public class DemoActivity extends Activity { public static final String EXTRA_MESSAGE = "message"; public static final String PROPERTY_REG_ID = "registration_id"; private static final String PROPERTY_APP_VERSION = "appVersion"; private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; /** * Substitute you own sender ID here. This is the project number you got * from the API Console, as described in "Getting Started." */ String SENDER_ID = "Your-Sender-ID"; /** * Tag used on log messages. */ static final String TAG = "GCM Demo"; TextView mDisplay; GoogleCloudMessaging gcm; AtomicInteger msgId = new AtomicInteger(); Context context; String regid; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mDisplay = (TextView) findViewById(R.id.display); context = getApplicationContext(); // Check device for Play Services APK. If check succeeds, proceed with GCM registration. if (checkPlayServices()) { gcm = GoogleCloudMessaging.getInstance(this); regid = getRegistrationId(context); if (regid.isEmpty()) { registerInBackground(); } } else { Log.i(TAG, "No valid Google Play Services APK found."); } } @Override protected void onResume() { super.onResume(); // Check device for Play Services APK. checkPlayServices(); } /** * Check the device to make sure it has the Google Play Services APK. If * it doesn't, display a dialog that allows users to download the APK from * the Google Play Store or enable it in the device's system settings. */ private boolean checkPlayServices() { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Log.i(TAG, "This device is not supported."); finish(); } return false; } return true; } /** * Stores the registration ID and the app versionCode in the application's * {@code SharedPreferences}. * * @param context application's context. * @param regId registration ID */ private void storeRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGcmPreferences(context); int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app version " + appVersion); SharedPreferences.Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); } /** * Gets the current registration ID for application on GCM service, if there is one. * <p> * If result is empty, the app needs to register. * * @return registration ID, or empty string if there is no existing * registration ID. */ private String getRegistrationId(Context context) { final SharedPreferences prefs = getGcmPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } // Check if app was updated; if so, it must clear the registration ID // since the existing regID is not guaranteed to work with the new // app version. int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App version changed."); return ""; } return registrationId; } /** * Registers the application with GCM servers asynchronously. * <p> * Stores the registration ID and the app versionCode in the application's * shared preferences. */ private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } regid = gcm.register(SENDER_ID); msg = "Device registered, registration ID=" + regid; // You should send the registration ID to your server over HTTP, so it // can use GCM/HTTP or CCS to send messages to your app. sendRegistrationIdToBackend(); // For this demo: we don't need to send it because the device will send // upstream messages to a server that echo back the message using the // 'from' address in the message. // Persist the regID - no need to register again. storeRegistrationId(context, regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); // If there is an error, don't just keep trying to register. // Require the user to click a button again, or perform // exponential back-off. } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); } // Send an upstream message. public void onClick(final View view) { if (view == findViewById(R.id.send)) { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { Bundle data = new Bundle(); data.putString("my_message", "Hello World"); data.putString("my_action", "com.google.android.gcm.demo.app.ECHO_NOW"); String id = Integer.toString(msgId.incrementAndGet()); gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data); msg = "Sent message"; } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); } else if (view == findViewById(R.id.clear)) { mDisplay.setText(""); } } @Override protected void onDestroy() { super.onDestroy(); } /** * @return Application's version code from the {@code PackageManager}. */ 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("Could not get package name: " + e); } } /** * @return Application's {@code SharedPreferences}. */ private SharedPreferences getGcmPreferences(Context context) { // This sample app persists the registration ID in shared preferences, but // how you store the regID in your app is up to you. return getSharedPreferences(DemoActivity.class.getSimpleName(), Context.MODE_PRIVATE); } /** * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send * messages to your app. Not needed for this demo since the device sends upstream messages * to a server that echoes back the message using the 'from' address in the message. */ private void sendRegistrationIdToBackend() { // Your implementation here. } }
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 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 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.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 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.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 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 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 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 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
/* * 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.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 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 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.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.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, registrationId)); 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. Extras: " + intent.getExtras()); 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.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 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
/** Automatically generated file. DO NOT MODIFY */ package com.google.android.gcm; public final class BuildConfig { public final static boolean DEBUG = true; }
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. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated 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 com.google.android.gcm.GCMConstants#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 com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION} * to get the application info. */ public static final String EXTRA_APPLICATION_PENDING_INTENT = "app"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} * to indicate that the application has been unregistered. */ public static final String EXTRA_UNREGISTERED = "unregistered"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#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 com.google.android.gcm.GCMConstants#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 com.google.android.gcm.GCMConstants#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 com.google.android.gcm.GCMConstants#VALUE_DELETED_MESSAGES} */ public static final String EXTRA_TOTAL_DELETED = "total_deleted"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#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 android.util.Log; /** * Custom logger. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated class GCMLogger { private final String mTag; // can't use class name on TAG since size is limited to 23 chars private final String mLogPrefix; GCMLogger(String tag, String logPrefix) { mTag = tag; mLogPrefix = logPrefix; } /** * Logs a message on logcat. * * @param priority logging priority * @param template message's template * @param args list of arguments */ protected void log(int priority, String template, Object... args) { if (Log.isLoggable(mTag, priority)) { String message = String.format(template, args); Log.println(priority, mTag, mLogPrefix + message); } } }
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. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public abstract class GCMBaseIntentService extends IntentService { /** * Old TAG used for logging. Marked as deprecated since it should have * been private at first place. */ @Deprecated public static final String TAG = "GCMBaseIntentService"; private final GCMLogger mLogger = new GCMLogger("GCMBaseIntentService", "[" + getClass().getName() + "]: "); // 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 /** * 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; mLogger.log(Log.VERBOSE, "Intent service name: %s", name); } private static String getName(String senderId) { String name = "GCMIntentService-" + senderId + "-" + (++sCounter); 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); mLogger.log(Log.VERBOSE, "Received notification for %d deleted" + "messages", total); onDeletedMessages(context, total); } catch (NumberFormatException e) { mLogger.log(Log.ERROR, "GCM returned invalid " + "number of deleted messages (%d)", sTotal); } } } else { // application is not using the latest GCM library mLogger.log(Log.ERROR, "Received unknown special message: %s", messageType); } } else { onMessage(context, intent); } } else if (action.equals(INTENT_FROM_GCM_LIBRARY_RETRY)) { String packageOnIntent = intent.getPackage(); if (packageOnIntent == null || !packageOnIntent.equals( getApplicationContext().getPackageName())) { mLogger.log(Log.ERROR, "Ignoring retry intent from another package (%s)", packageOnIntent); 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 mLogger.log(Log.ERROR, "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); mLogger.log(Log.DEBUG, "handleRegistration: registrationId = %s, " + "error = %s, unregistered = %s", registrationId, error, 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; // 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); mLogger.log(Log.DEBUG, "Scheduling registration retry, backoff = %d (%d)", nextAttempt, backoffTimeMs); Intent retryIntent = new Intent(INTENT_FROM_GCM_LIBRARY_RETRY); retryIntent.setPackage(context.getPackageName()); 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 { mLogger.log(Log.VERBOSE, "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 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. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public class GCMBroadcastReceiver extends BroadcastReceiver { private static boolean mReceiverSet = false; private final GCMLogger mLogger = new GCMLogger("GCMBroadcastReceiver", "[" + getClass().getName() + "]: "); @Override public final void onReceive(Context context, Intent intent) { mLogger.log(Log.VERBOSE, "onReceive: %s", intent.getAction()); // do a one-time check if app is using a custom GCMBroadcastReceiver if (!mReceiverSet) { mReceiverSet = true; GCMRegistrar.setRetryReceiverClassName(context, getClass().getName()); } String className = getGCMIntentServiceClassName(context); mLogger.log(Log.VERBOSE, "GCM IntentService class: %s", 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; 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. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated 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); } log(context, Log.VERBOSE, "number of receivers for %s: %d", 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); } log(context, Log.VERBOSE, "Found %d receivers for action %s", receivers.size(), 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(context, Log.VERBOSE, "Registering app for senders %s", 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(context, Log.VERBOSE, "Unregistering app"); 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(context, Log.VERBOSE, "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(context, Log.VERBOSE, "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(context, Log.ERROR, "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(context, Log.ERROR, "Could not create instance of %s. " + "Using %s directly.", sRetryReceiverClassName, GCMBroadcastReceiver.class.getName()); sRetryReceiver = new GCMBroadcastReceiver(); } } String category = context.getPackageName(); IntentFilter filter = new IntentFilter( GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY); filter.addCategory(category); log(context, Log.VERBOSE, "Registering retry receiver"); sRetryReceiverContext = context; sRetryReceiverContext.registerReceiver(sRetryReceiver, filter); } } /** * Sets the name of the retry receiver class. */ static synchronized void setRetryReceiverClassName(Context context, String className) { log(context, Log.VERBOSE, "Setting the name of retry receiver class to %s", 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(context, Log.VERBOSE, "App version changed from %d to %d;" + "resetting registration id", oldVersion, newVersion); 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. * * <p>As a side-effect, it also expires the registeredOnServer property. * * @param context application's context. * @return old registration id. */ static String clearRegistrationId(Context context) { setRegisteredOnServer(context, null, 0); 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(context, Log.VERBOSE, "Saving regId on app version %d", 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) { // set the flag's expiration date long lifespan = getRegisterOnServerLifespan(context); long expirationTime = System.currentTimeMillis() + lifespan; setRegisteredOnServer(context, flag, expirationTime); } private static void setRegisteredOnServer(Context context, Boolean flag, long expirationTime) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); if (flag != null) { editor.putBoolean(PROPERTY_ON_SERVER, flag); log(context, Log.VERBOSE, "Setting registeredOnServer flag as %b until %s", flag, new Timestamp(expirationTime)); } else { log(context, Log.VERBOSE, "Setting registeredOnServer expiration to %s", 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(context, Log.VERBOSE, "Is registered on server: %b", 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(context, Log.VERBOSE, "flag expired on: %s", 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(context, Log.VERBOSE, "Resetting backoff"); 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); } /** * Logs a message on logcat. * * @param context application's context. * @param priority logging priority * @param template message's template * @param args list of arguments */ private static void log(Context context, int priority, String template, Object... args) { if (Log.isLoggable(TAG, priority)) { String message = String.format(template, args); Log.println(priority, TAG, "[" + context.getPackageName() + "]: " + message); } } 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.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) * .dryRun(true) * .restrictedPackageName(restrictedPackageName) * .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) * .dryRun(true) * .restrictedPackageName(restrictedPackageName) * .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; private final Boolean dryRun; private final String restrictedPackageName; public static final class Builder { private final Map<String, String> data; // optional parameters private String collapseKey; private Boolean delayWhileIdle; private Integer timeToLive; private Boolean dryRun; private String restrictedPackageName; 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; } /** * Sets the dryRun property (default value is {@literal false}). */ public Builder dryRun(boolean value) { dryRun = value; return this; } /** * Sets the restrictedPackageName property. */ public Builder restrictedPackageName(String value) { restrictedPackageName = 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; dryRun = builder.dryRun; restrictedPackageName = builder.restrictedPackageName; } /** * 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 dryRun flag. */ public Boolean isDryRun() { return dryRun; } /** * Gets the restricted package name. */ public String getRestrictedPackageName() { return restrictedPackageName; } /** * 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 (dryRun != null) { builder.append("dryRun=").append(dryRun).append(", "); } if (restrictedPackageName != null) { builder.append("restrictedPackageName=").append(restrictedPackageName).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.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 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_DRY_RUN; 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_RESTRICTED_PACKAGE_NAME; 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"); } Boolean dryRun = message.isDryRun(); if (dryRun != null) { addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0"); } String collapseKey = message.getCollapseKey(); if (collapseKey != null) { addParameter(body, PARAM_COLLAPSE_KEY, collapseKey); } String restrictedPackageName = message.getRestrictedPackageName(); if (restrictedPackageName != null) { addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName); } 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_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName()); setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle()); setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun()); 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; 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; public 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 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; public 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.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"; /** * HTTP parameter for telling gcm to validate the message without actually sending it. */ public static final String PARAM_DRY_RUN = "dry_run"; /** * HTTP parameter for package name that can be used to restrict message delivery by matching * against the package name used to generate the registration id. */ public static final String PARAM_RESTRICTED_PACKAGE_NAME = "restricted_package_name"; /** * 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
package com.anores.web.domain; public class User { private String username; private User user; public User(String username) { this.username = username; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
Java
package com.anores.web.controller; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import javax.annotation.Resource; import javax.persistence.EntityManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.anores.persistence.domain.Role; import com.anores.persistence.domain.User; import com.anores.persistence.domain.UserRole; import com.anores.persistence.repository.RoleRepository; import com.anores.persistence.repository.UserRepository; import com.rits.cloning.Cloner; /** * Handles requests for the application home page. */ @Controller public class HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); @Resource private UserRepository userRepository; @Resource private RoleRepository roleRepository; /** * Simply selects the home view to render by returning its name. */ @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { logger.info("Welcome home! The client locale is {}.", locale); Date date = new Date(); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); String formattedDate = dateFormat.format(date); model.addAttribute("serverTime", formattedDate ); User user1 = new User(); Role role1 = new Role(); UserRole userRole1 = new UserRole(); userRole1.setUser(user1); userRole1.setRole(role1); //user1.getUserRoles().add(userRole1); //roleRepository.saveAndFlush(role1); userRepository.save(user1); return "home"; } @RequestMapping(value= "/user", method = RequestMethod.GET) public @ResponseBody User getUserByUsername(@RequestParam("username") String username) { return null; } }
Java
package com.anores.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.servlet.DispatcherServlet; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; import java.util.Set; public class WebAppInitializer implements WebApplicationInitializer { private static Logger LOG = LoggerFactory .getLogger(WebAppInitializer.class); @Override public void onStartup(ServletContext servletContext) { WebApplicationContext rootContext = createRootContext(servletContext); configureSpringMvc(servletContext, rootContext); configureSpringSecurity(servletContext, rootContext); } private WebApplicationContext createRootContext( ServletContext servletContext) { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(CoreConfig.class, PersistenceConfig.class, SecurityConfig.class, ApplicationContext.class); rootContext.refresh(); servletContext.addListener(new ContextLoaderListener(rootContext)); servletContext.setInitParameter("defaultHtmlEscape", "true"); return rootContext; } private void configureSpringMvc(ServletContext servletContext, WebApplicationContext rootContext) { AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext(); mvcContext.register(WebMVCConfig.class); mvcContext.setParent(rootContext); ServletRegistration.Dynamic appServlet = servletContext.addServlet( "webservice", new DispatcherServlet(mvcContext)); appServlet.setLoadOnStartup(1); Set<String> mappingConflicts = appServlet.addMapping("/"); if (!mappingConflicts.isEmpty()) { for (String s : mappingConflicts) { LOG.error("Mapping conflict: " + s); } throw new IllegalStateException( "'webservice' cannot be mapped to '/'"); } } private void configureSpringSecurity(ServletContext servletContext, WebApplicationContext rootContext) { FilterRegistration.Dynamic springSecurity = servletContext.addFilter( "springSecurityFilterChain", new DelegatingFilterProxy( "springSecurityFilterChain", rootContext)); springSecurity.addMappingForUrlPatterns(null, true, "/*"); } }
Java
package com.anores.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import com.anores.security.ApplicationAuthenticationProvider; @EnableWebSecurity @Configuration @ComponentScan(basePackages = { "com.anores.security" }) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public AuthenticationProvider authenticationProvider() { return new ApplicationAuthenticationProvider(); } @Autowired private AuthenticationProvider authenticationProvider; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password") .roles("USER"); } @Override protected void configure(AuthenticationManagerBuilder authManagerBuilder) throws Exception { authManagerBuilder .authenticationProvider(authenticationProvider); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/resources/**"); } @Override protected void configure(HttpSecurity http) throws Exception { // http.authorizeRequests().antMatchers("/singup", "/about", "/getuser").permitAll() // .antMatchers("/admin/**").hasRole("ADMIN").anyRequest() // .authenticated().and().formLogin().permitAll(); http.anonymous(); } }
Java
package com.anores.config; import java.util.Properties; import javax.annotation.Resource; import javax.sql.DataSource; import org.hibernate.ejb.HibernatePersistence; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.anores.persistence.services.UserPersistenceEventHandler; import com.anores.persistence.services.UserPersistenceService; import com.jolbox.bonecp.BoneCPDataSource; @Configuration @PropertySource("classpath:application.properties") @ComponentScan(basePackages = { "com.anores.persistence.services" }) @EnableTransactionManagement public class PersistenceConfig { private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver"; private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password"; private static final String PROPERTY_NAME_DATABASE_URL = "db.url"; private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username"; private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect"; private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql"; private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto"; private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy"; private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql"; private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan"; @Bean public UserPersistenceService userPersistenceService() { return new UserPersistenceEventHandler(); } @Resource private Environment environment; @Bean public DataSource dataSource() { BoneCPDataSource dataSource = new BoneCPDataSource(); dataSource.setDriverClass(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER)); dataSource.setJdbcUrl(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL)); dataSource.setUsername(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME)); dataSource.setPassword(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD)); return dataSource; } @Bean public JpaTransactionManager transactionManager() throws ClassNotFoundException { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject()); return transactionManager; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() throws ClassNotFoundException { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(dataSource()); entityManagerFactoryBean.setPackagesToScan(environment.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN)); entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class); Properties jpaProterties = new Properties(); jpaProterties.put(PROPERTY_NAME_HIBERNATE_DIALECT, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT)); jpaProterties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL)); jpaProterties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO)); jpaProterties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY)); jpaProterties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL)); entityManagerFactoryBean.setJpaProperties(jpaProterties); return entityManagerFactoryBean; } }
Java
package com.anores.config; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource("classpath:applicationContext.xml") public class ApplicationContext { }
Java
package com.anores.config; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.util.StringUtils; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.thymeleaf.spring3.SpringTemplateEngine; import org.thymeleaf.spring3.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.anores.web.controller" }) public class WebMVCConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations( "/resources/"); } @Override public void addInterceptors(InterceptorRegistry registry) { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("lang"); registry.addInterceptor(localeChangeInterceptor); } @Bean public LocaleResolver localeResolver() { CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); cookieLocaleResolver.setDefaultLocale(StringUtils .parseLocaleString("en")); return cookieLocaleResolver; } @Bean public ServletContextTemplateResolver templateResolver() { ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".html"); // NB, selecting HTML5 as the template mode. resolver.setTemplateMode("HTML5"); resolver.setCacheable(false); return resolver; } public SpringTemplateEngine templateEngine() { SpringTemplateEngine engine = new SpringTemplateEngine(); engine.setTemplateResolver(templateResolver()); return engine; } @Bean public ViewResolver viewResolver() { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); viewResolver.setOrder(1); viewResolver.setViewNames(new String[] { "*" }); viewResolver.setCache(false); return viewResolver; } @Bean public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasenames("classpath:messages/messages", "classpath:messages/validation"); // if true, the key of the message will be displayed if the key is not // found, instead of throwing a NoSuchMessageException messageSource.setUseCodeAsDefaultMessage(true); messageSource.setDefaultEncoding("UTF-8"); // # -1 : never reload, 0 always reload messageSource.setCacheSeconds(0); return messageSource; } }
Java
package com.anores.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import com.anores.core.services.UserEventHandler; import com.anores.core.services.UserService; @Configuration @ComponentScan(basePackages = { "com.anores.core.services" }) public class CoreConfig { @Bean public UserService userService() { return new UserEventHandler(); } }
Java
package com.anores.events; public class UpdateEvent { }
Java
package com.anores.events.user; import java.util.List; import org.springframework.security.core.GrantedAuthority; public class Role implements GrantedAuthority { /** * */ private static final long serialVersionUID = 1L; private String name; private List<Privilege> privileges; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Privilege> getPrivileges() { return privileges; } public void setPrivileges(List<Privilege> privileges) { this.privileges = privileges; } @Override public String getAuthority() { return this.name; } @Override public String toString() { return this.getClass().getName() + " [name="+ this.name +"" + ", privileges=" + this.privileges + "]"; } }
Java
package com.anores.events.user; import com.anores.events.RequestReadEvent; public class FindUserByUsernameEvent extends RequestReadEvent { private String username; public FindUserByUsernameEvent(String username) { this.username = username; } public String getUsername() { return username; } }
Java
package com.anores.events.user; import java.util.Collection; import java.util.List; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; public class User implements UserDetails { /** * */ private static final long serialVersionUID = 1L; private String username; private String password; private String email; private String firstName; private String lastName; /* Spring Security fields*/ private List<Role> authorities; private boolean accountNonExpired = true; private boolean accountNonLocked = true; private boolean credentialsNonExpired = true; private boolean enabled = true; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public void setAuthorities(List<Role> authorities) { this.authorities = authorities; } public void setAccountNonExpired(boolean accountNonExpired) { this.accountNonExpired = accountNonExpired; } public void setAccountNonLocked(boolean accountNonLocked) { this.accountNonLocked = accountNonLocked; } public void setCredentialsNonExpired(boolean credentialsNonExpired) { this.credentialsNonExpired = credentialsNonExpired; } public void setEnabled(boolean enabled) { this.enabled = enabled; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return this.authorities; } @Override public String getPassword() { return this.password; } @Override public String getUsername() { return this.username; } @Override public boolean isAccountNonExpired() { return this.accountNonExpired; } @Override public boolean isAccountNonLocked() { return this.accountNonLocked; } @Override public boolean isCredentialsNonExpired() { return this.credentialsNonExpired; } @Override public boolean isEnabled() { return this.enabled; } public String toString() { return this.getClass().getName() + " [username=" + this.username + ", email=" + this.email + ", password=" + this.password + ", firstname=" + this.firstName + ", lastname=" + this.lastName + ", authorities=" + this.authorities + ", accountNonExpired=" + this.accountNonExpired + ", credentialNonExpried=" + this.credentialsNonExpired + ", enabled=" + this.enabled + "]"; } }
Java
package com.anores.events.user; import com.anores.events.CreatedEvent; public class CreatedUserEvent extends CreatedEvent { }
Java
package com.anores.events.user; import com.anores.events.ReadEvent; public class UserEvent extends ReadEvent { private User user; public UserEvent(User user) { this.user = user; } public User getUser() { return user; } }
Java
package com.anores.events.user; import com.anores.events.CreatedEvent; public class CreateUserEvent extends CreatedEvent { }
Java
package com.anores.events.user; public class Privilege { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return this.getClass().getName() + " [name=" + name + "]"; } }
Java
package com.anores.events; public class UpdatedEvent { }
Java
package com.anores.events; public class RequestReadEvent { }
Java
package com.anores.events; public class CreatedEvent { }
Java
package com.anores.events; public class DeleteEvent { }
Java
package com.anores.events; public class CreateEvent { }
Java
package com.anores.events; public class ReadEvent { protected boolean entityFound = true; public boolean isEntityFound() { return entityFound; } }
Java
package com.anores.events; public class DeletedEvent { }
Java
package com.anores.core.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.anores.events.user.FindUserByUsernameEvent; import com.anores.events.user.UserEvent; import com.anores.persistence.services.UserPersistenceService; @Service @Transactional public class UserEventHandler implements UserService { @Autowired private UserPersistenceService userPersistenceService; @Override public UserEvent loadUserByUsername( FindUserByUsernameEvent loadUserByUsernameEvent) { return userPersistenceService.loadUserByUsername(loadUserByUsernameEvent); } }
Java
package com.anores.core.services; import com.anores.events.user.FindUserByUsernameEvent; import com.anores.events.user.UserEvent; public interface UserService { UserEvent loadUserByUsername(FindUserByUsernameEvent loadUserByUsernameEvent); }
Java
package com.anores.core.domain; public class Role { }
Java
package com.anores.core.domain; public class User { }
Java
package com.anores.core.domain; public class Privilege { }
Java
package com.anores.persistence.services; import com.anores.events.user.CreateUserEvent; import com.anores.events.user.CreatedUserEvent; import com.anores.events.user.FindUserByUsernameEvent; import com.anores.events.user.UserEvent; public interface UserPersistenceService { UserEvent loadUserByUsername(FindUserByUsernameEvent loadUserByUsernameEvent); public CreatedUserEvent create(CreateUserEvent createUserEvent); }
Java
package com.anores.persistence.services; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.anores.events.user.CreateUserEvent; import com.anores.events.user.CreatedUserEvent; import com.anores.events.user.FindUserByUsernameEvent; import com.anores.events.user.User; import com.anores.events.user.UserEvent; import com.anores.persistence.repository.UserRepository; @Service @Transactional public class UserPersistenceEventHandler implements UserPersistenceService { @Resource private UserRepository userRepository; @Override public UserEvent loadUserByUsername( FindUserByUsernameEvent loadUserByUsernameEvent) { return new UserEvent(new User()); } @Override public CreatedUserEvent create(CreateUserEvent createUserEvent) { // TODO Auto-generated method stub return null; } }
Java
package com.anores.persistence.domain; import java.io.Serializable; import javax.persistence.Embeddable; import javax.persistence.ManyToOne; @Embeddable public class UserRoleId implements Serializable { /** * */ private static final long serialVersionUID = -7589492895570441668L; @ManyToOne private User user; @ManyToOne private Role role; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } }
Java
package com.anores.persistence.domain; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "role") public class Role extends BaseEntityAudit { @OneToMany(mappedBy="pk.role", fetch=FetchType.LAZY) private Set<UserRole> userRoles = new HashSet<UserRole>(); public Set<UserRole> getUserRoles() { return userRoles; } public void setUserRoles(Set<UserRole> userRoles) { this.userRoles = userRoles; } }
Java